331 lines
13 KiB
Rust
331 lines
13 KiB
Rust
//! Stateful HTTP fixture. It verifies wire methods and bodies, not live credentials.
|
|
use serde_json::{Value, json};
|
|
use std::{
|
|
collections::BTreeMap,
|
|
sync::{Arc, Mutex},
|
|
};
|
|
use tokio::{
|
|
io::{AsyncReadExt, AsyncWriteExt},
|
|
net::TcpListener,
|
|
};
|
|
|
|
#[derive(Default)]
|
|
pub struct State {
|
|
pub objects: BTreeMap<String, Value>,
|
|
pub writes: usize,
|
|
pub rotation_creates: usize,
|
|
pub rotation_patches: usize,
|
|
pub fail_after_rotation_patch: bool,
|
|
pub fail_after_schedule_patch: bool,
|
|
pub fail_once: Option<String>,
|
|
pub external_override: bool,
|
|
pub users: Vec<Value>,
|
|
pub lookups: usize,
|
|
pub fail_after_override_create: bool,
|
|
pub fail_after_resource_create: bool,
|
|
pub override_not_before: Option<chrono::DateTime<chrono::Utc>>,
|
|
}
|
|
pub struct Server {
|
|
pub base: String,
|
|
pub state: Arc<Mutex<State>>,
|
|
task: tokio::task::JoinHandle<()>,
|
|
}
|
|
impl Drop for Server {
|
|
fn drop(&mut self) {
|
|
self.task.abort();
|
|
}
|
|
}
|
|
impl Server {
|
|
pub async fn start() -> Self {
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
|
let base = format!("http://{}", listener.local_addr().unwrap());
|
|
let state = Arc::new(Mutex::new(State::default()));
|
|
let copy = state.clone();
|
|
let task = tokio::spawn(async move {
|
|
loop {
|
|
let (mut socket, _) = listener.accept().await.unwrap();
|
|
let shared = copy.clone();
|
|
tokio::spawn(async move {
|
|
let mut buffer = vec![];
|
|
let (head_end, length) = loop {
|
|
let mut chunk = [0; 4096];
|
|
let n = socket.read(&mut chunk).await.unwrap();
|
|
if n == 0 {
|
|
return;
|
|
}
|
|
buffer.extend_from_slice(&chunk[..n]);
|
|
if let Some(end) = buffer.windows(4).position(|w| w == b"\r\n\r\n") {
|
|
let head = String::from_utf8_lossy(&buffer[..end]);
|
|
let length = head
|
|
.lines()
|
|
.find_map(|l| {
|
|
l.to_lowercase()
|
|
.strip_prefix("content-length: ")
|
|
.and_then(|v| v.parse::<usize>().ok())
|
|
})
|
|
.unwrap_or(0);
|
|
break (end + 4, length);
|
|
}
|
|
};
|
|
while buffer.len() < head_end + length {
|
|
let mut chunk = [0; 4096];
|
|
let n = socket.read(&mut chunk).await.unwrap();
|
|
if n == 0 {
|
|
return;
|
|
}
|
|
buffer.extend_from_slice(&chunk[..n]);
|
|
}
|
|
let head = String::from_utf8_lossy(&buffer[..head_end]);
|
|
assert!(head.to_lowercase().contains("authorization: basic "));
|
|
let mut first = head.lines().next().unwrap().split_whitespace();
|
|
let method = first.next().unwrap();
|
|
let uri = first.next().unwrap();
|
|
let body = if length > 0 {
|
|
serde_json::from_slice(&buffer[head_end..head_end + length]).unwrap()
|
|
} else {
|
|
Value::Null
|
|
};
|
|
let (code, result) =
|
|
handle_page(&mut shared.lock().unwrap(), method, uri, body);
|
|
let body = result.to_string();
|
|
let response = format!(
|
|
"HTTP/1.1 {code} Result\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
|
body.len()
|
|
);
|
|
socket.write_all(response.as_bytes()).await.unwrap();
|
|
});
|
|
}
|
|
});
|
|
Self { base, state, task }
|
|
}
|
|
}
|
|
fn handle_page(s: &mut State, method: &str, uri: &str, body: Value) -> (u16, Value) {
|
|
let url = reqwest::Url::parse(&format!("http://localhost{uri}")).unwrap();
|
|
let query: BTreeMap<_, _> = url.query_pairs().into_owned().collect();
|
|
let size = query.get("size").and_then(|s| s.parse::<usize>().ok());
|
|
if size.is_some_and(|size| size > 50) {
|
|
return (
|
|
422,
|
|
json!({"errors":[{"title":"Field: size, error: must be less than or equal to 50"}]}),
|
|
);
|
|
}
|
|
let (code, mut result) = handle(s, method, url.path(), body);
|
|
if method == "GET"
|
|
&& let Some(size) = size
|
|
&& let Some(values) = result.get_mut("values").and_then(Value::as_array_mut)
|
|
{
|
|
let offset = query
|
|
.get("offset")
|
|
.and_then(|s| s.parse().ok())
|
|
.unwrap_or(0);
|
|
let more = offset + size < values.len();
|
|
*values = values.iter().skip(offset).take(size).cloned().collect();
|
|
if more {
|
|
result["links"] =
|
|
json!({"next":format!("{}?offset={}&size={size}",url.path(),offset+size)});
|
|
}
|
|
}
|
|
(code, result)
|
|
}
|
|
fn read_response(path: &str, value: &Value) -> Value {
|
|
let mut response = value.clone();
|
|
if path.contains("/escalations/") && response["repeat"]["waitInterval"] == 0 {
|
|
response.as_object_mut().unwrap().remove("repeat");
|
|
}
|
|
response
|
|
}
|
|
|
|
fn handle(s: &mut State, method: &str, path: &str, mut body: Value) -> (u16, Value) {
|
|
if method == "POST" && s.fail_once.as_ref().is_some_and(|p| path.ends_with(p)) {
|
|
s.fail_once = None;
|
|
return (429, json!({"error":"Try later"}));
|
|
}
|
|
if method == "GET" {
|
|
if path.ends_with("/user/search") {
|
|
s.lookups += 1;
|
|
return (200, json!(s.users));
|
|
}
|
|
if path.ends_with("/overrides") {
|
|
if !s
|
|
.objects
|
|
.contains_key(path.strip_suffix("/overrides").unwrap())
|
|
{
|
|
return (404, json!({}));
|
|
}
|
|
let mut values: Vec<_> = s
|
|
.objects
|
|
.iter()
|
|
.filter(|(key, _)| {
|
|
key.rsplit_once('/')
|
|
.is_some_and(|(parent, _)| parent == path)
|
|
})
|
|
.map(|(_, value)| value.clone())
|
|
.collect();
|
|
if s.external_override {
|
|
values.push(json!({"alias":"external"}));
|
|
}
|
|
return (200, json!({"values":values}));
|
|
}
|
|
if let Some(parent) = path.strip_suffix("/rotations") {
|
|
let Some(object) = s.objects.get(parent) else {
|
|
return (404, json!({}));
|
|
};
|
|
let mut rotations = object["rotations"].as_array().unwrap().clone();
|
|
rotations.reverse();
|
|
return (200, json!({"values":rotations}));
|
|
}
|
|
if let Some(value) = s.objects.get(path) {
|
|
return (200, read_response(path, value));
|
|
}
|
|
if path.ends_with("/schedules")
|
|
|| path.ends_with("/escalations")
|
|
|| path.ends_with("/routing-rules")
|
|
{
|
|
return (
|
|
200,
|
|
json!({"values":s.objects.iter().filter(|(k,_)|k.rsplit_once('/').is_some_and(|(p,_)|p==path)).map(|(k,v)|read_response(k,v)).collect::<Vec<_>>()}),
|
|
);
|
|
}
|
|
return (404, json!({}));
|
|
}
|
|
if method == "DELETE" {
|
|
s.writes += 1;
|
|
if path.ends_with("/overrides/external") {
|
|
s.external_override = false;
|
|
} else {
|
|
s.objects.remove(path);
|
|
s.objects
|
|
.retain(|key, _| !key.starts_with(&format!("{path}/")));
|
|
}
|
|
return (200, json!({"result":"deleted"}));
|
|
}
|
|
if path.contains("routing-rules") {
|
|
assert!(body["order"].as_u64().unwrap() <= 100);
|
|
assert!(body["notify"].is_object());
|
|
}
|
|
if path.contains("escalations") {
|
|
assert!((1..=20).contains(&body["repeat"]["count"].as_u64().unwrap()));
|
|
assert!(body["rules"].is_array());
|
|
}
|
|
if path.contains("/overrides") {
|
|
assert!(body["responder"]["type"] == "user" || body["responder"]["type"] == "noone");
|
|
for field in ["startDate", "endDate"] {
|
|
let time = body[field]
|
|
.as_str()
|
|
.unwrap()
|
|
.parse::<chrono::DateTime<chrono::Utc>>()
|
|
.unwrap();
|
|
body[field] =
|
|
json!(chrono::DateTime::from_timestamp_millis(time.timestamp_millis()).unwrap());
|
|
}
|
|
if method == "POST"
|
|
&& s.override_not_before.is_some_and(|now| {
|
|
body["startDate"]
|
|
.as_str()
|
|
.unwrap()
|
|
.parse::<chrono::DateTime<chrono::Utc>>()
|
|
.unwrap()
|
|
< now
|
|
})
|
|
{
|
|
return (
|
|
400,
|
|
json!({"error":"Start time cannot be earlier than the current time"}),
|
|
);
|
|
}
|
|
s.writes += 1;
|
|
if method == "POST" {
|
|
let alias = uuid::Uuid::new_v4().to_string();
|
|
body["alias"] = json!(alias);
|
|
s.objects.insert(format!("{path}/{alias}"), body.clone());
|
|
if s.fail_after_override_create {
|
|
s.fail_after_override_create = false;
|
|
return (500, json!({"error":"Lost response after create"}));
|
|
}
|
|
} else {
|
|
assert_eq!(method, "PUT");
|
|
body["alias"] = json!(path.rsplit('/').next().unwrap());
|
|
s.objects.insert(path.into(), body.clone());
|
|
}
|
|
return (201, body);
|
|
}
|
|
if let Some((parent, id)) = path.split_once("/rotations/") {
|
|
assert_eq!(method, "PATCH");
|
|
let Some(rotation) = s
|
|
.objects
|
|
.get_mut(parent)
|
|
.and_then(|v| v["rotations"].as_array_mut())
|
|
.and_then(|r| r.iter_mut().find(|r| r["id"] == id))
|
|
else {
|
|
return (404, json!({}));
|
|
};
|
|
body["id"] = json!(id);
|
|
*rotation = body.clone();
|
|
s.writes += 1;
|
|
s.rotation_patches += 1;
|
|
if s.fail_after_rotation_patch {
|
|
s.fail_after_rotation_patch = false;
|
|
return (500, json!({"error":"Lost rotation update response"}));
|
|
}
|
|
return (200, body);
|
|
}
|
|
if path.contains("schedules") && body.get("rotations").is_some() {
|
|
let zone = body["timezone"]
|
|
.as_str()
|
|
.unwrap()
|
|
.parse::<chrono_tz::Tz>()
|
|
.unwrap();
|
|
for rotation in body["rotations"].as_array_mut().unwrap() {
|
|
rotation["id"] = json!(uuid::Uuid::new_v4().to_string());
|
|
s.rotation_creates += 1;
|
|
assert!(!rotation["participants"].as_array().unwrap().is_empty());
|
|
if let Some(end) = rotation["endDate"].as_str() {
|
|
assert!(end > rotation["startDate"].as_str().unwrap());
|
|
} else {
|
|
assert_eq!(rotation["participants"][0]["type"], "noone");
|
|
}
|
|
// Anonymized live behavior: native rotation minutes snap to a half-hour;
|
|
// override endpoints above retain arbitrary minutes and milliseconds.
|
|
for field in ["startDate", "endDate"] {
|
|
if let Some(raw) = rotation[field].as_str() {
|
|
use chrono::Timelike;
|
|
let time = raw.parse::<chrono::DateTime<chrono::Utc>>().unwrap();
|
|
let minute = i64::from(time.with_timezone(&zone).minute());
|
|
let rounded =
|
|
time + chrono::Duration::minutes(((minute + 15) / 30) * 30 - minute);
|
|
rotation[field] = json!(
|
|
chrono::DateTime::from_timestamp_millis(rounded.timestamp_millis())
|
|
.unwrap()
|
|
);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
s.writes += 1;
|
|
if method == "POST" {
|
|
let id = uuid::Uuid::new_v4().to_string();
|
|
body["id"] = json!(id);
|
|
s.objects.insert(format!("{path}/{id}"), body.clone());
|
|
if s.fail_after_resource_create {
|
|
s.fail_after_resource_create = false;
|
|
return (500, json!({"error":"Lost resource create response"}));
|
|
}
|
|
return (201, body);
|
|
}
|
|
assert_eq!(method, "PATCH");
|
|
if let Some(previous) = s.objects.get(path) {
|
|
let mut merged = previous.clone();
|
|
for (key, value) in body.as_object().unwrap() {
|
|
merged[key] = value.clone();
|
|
}
|
|
s.objects.insert(path.into(), merged.clone());
|
|
if path.starts_with("/schedules/") && s.fail_after_schedule_patch {
|
|
s.fail_after_schedule_patch = false;
|
|
return (500, json!({"error":"Lost schedule metadata response"}));
|
|
}
|
|
(200, merged)
|
|
} else {
|
|
(404, json!({}))
|
|
}
|
|
}
|