use crate::constants::ErrorCode;
use crate::registry::{Registry, RegistryError};
use serde_json::{Value, json};
use std::sync::Arc;
use std::time::Duration;
pub const MEDIA_JSON: &str = "application/json";
pub const MEDIA_BEVE: &str = "application/x-beve";
pub const MEDIA_PROBLEM: &str = "application/problem+json";
const ALLOW_VALUE: &str = "GET, HEAD, PUT, OPTIONS";
const ALLOW_FUNCTION: &str = "GET, HEAD, POST, OPTIONS";
const ALLOW_READ_ONLY: &str = "GET, HEAD, OPTIONS";
const ALLOW_SERVER: &str = "GET, HEAD, PUT, POST, OPTIONS";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Repr {
Json,
Beve,
}
impl Repr {
fn media_type(self) -> &'static str {
match self {
Repr::Json => MEDIA_JSON,
Repr::Beve => MEDIA_BEVE,
}
}
}
#[derive(Debug, Clone)]
pub struct RestConfig {
pub max_body_bytes: usize,
pub cache_control: Option<String>,
pub application_error_status: u16,
pub read_only: bool,
pub allow_root_write: bool,
pub accept_beve_bodies: bool,
pub max_connections: usize,
pub request_timeout: Option<Duration>,
}
impl Default for RestConfig {
fn default() -> Self {
Self {
max_body_bytes: 1024 * 1024,
cache_control: Some("no-cache".to_string()),
application_error_status: 500,
read_only: false,
allow_root_write: false,
accept_beve_bodies: true,
max_connections: 1024,
request_timeout: Some(Duration::from_secs(30)),
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct RestRequest<'a> {
pub method: &'a str,
pub target: &'a str,
pub content_type: Option<&'a str>,
pub accept: Option<&'a str>,
pub if_none_match: Option<&'a str>,
pub if_match: Option<&'a str>,
pub body: &'a [u8],
}
impl<'a> RestRequest<'a> {
pub fn new(method: &'a str, target: &'a str) -> Self {
Self {
method,
target,
content_type: None,
accept: None,
if_none_match: None,
if_match: None,
body: &[],
}
}
pub fn with_body(mut self, content_type: &'a str, body: &'a [u8]) -> Self {
self.content_type = Some(content_type);
self.body = body;
self
}
pub fn with_accept(mut self, accept: &'a str) -> Self {
self.accept = Some(accept);
self
}
pub fn with_if_none_match(mut self, tag: &'a str) -> Self {
self.if_none_match = Some(tag);
self
}
pub fn with_if_match(mut self, tag: &'a str) -> Self {
self.if_match = Some(tag);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RestResponse {
pub status: u16,
pub content_type: Option<&'static str>,
pub etag: Option<String>,
pub cache_control: Option<String>,
pub vary: Option<&'static str>,
pub allow: Option<&'static str>,
pub repe_error_code: Option<u32>,
pub omit_body: bool,
pub body: Vec<u8>,
}
impl RestResponse {
fn empty(status: u16) -> Self {
Self {
status,
content_type: None,
etag: None,
cache_control: None,
vary: None,
allow: None,
repe_error_code: None,
omit_body: false,
body: Vec::new(),
}
}
fn problem(status: u16, detail: impl Into<String>, repe_code: Option<u32>) -> Self {
let mut problem = json!({
"type": "about:blank",
"title": reason_phrase(status),
"status": status,
"detail": detail.into(),
});
if let Some(code) = repe_code {
problem["repe_code"] = json!(code);
}
Self {
content_type: Some(MEDIA_PROBLEM),
cache_control: Some("no-store".to_string()),
repe_error_code: repe_code,
body: serde_json::to_vec(&problem).unwrap_or_default(),
..Self::empty(status)
}
}
}
#[derive(Clone)]
pub struct RestGateway {
registry: Arc<Registry>,
mount: String,
config: RestConfig,
}
impl std::fmt::Debug for RestGateway {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RestGateway")
.field("mount", &self.mount)
.field("config", &self.config)
.finish_non_exhaustive()
}
}
impl RestGateway {
pub fn new(mount: &str, registry: Arc<Registry>) -> Self {
Self::with_config(mount, registry, RestConfig::default())
}
pub fn with_config(mount: &str, registry: Arc<Registry>, config: RestConfig) -> Self {
Self {
registry,
mount: crate::registry::normalize_mount(mount),
config,
}
}
pub fn registry(&self) -> &Arc<Registry> {
&self.registry
}
pub fn respond(&self, request: RestRequest<'_>) -> RestResponse {
let path = request.target.split(['?', '#']).next().unwrap_or("");
if request.method == "OPTIONS" && path == "*" {
let allow = if self.config.read_only {
ALLOW_READ_ONLY
} else {
ALLOW_SERVER
};
return RestResponse {
allow: Some(allow),
..RestResponse::empty(204)
};
}
let Some(remainder) = self.strip_mount(path) else {
return RestResponse::problem(
404,
format!("`{path}` is not under this gateway's mount"),
None,
);
};
let pointer = match path_to_pointer(remainder) {
Ok(pointer) => pointer,
Err(detail) => return RestResponse::problem(400, detail, None),
};
match request.method {
"GET" | "HEAD" => self.read(&pointer, request),
_ => {
let is_function = self.registry.is_function(&pointer);
let allow = self.allow_for(is_function);
match request.method {
"PUT" if is_function => method_not_allowed(
allow,
"this path is a function; a PUT would call it, which is not idempotent — use POST",
),
"POST" if !is_function => method_not_allowed(
allow,
"this path is a value; a POST would write it, which is idempotent — use PUT",
),
"PUT" | "POST" => self.write_or_call(&pointer, request, allow, is_function),
"OPTIONS" => RestResponse {
allow: Some(allow),
..RestResponse::empty(204)
},
_ => method_not_allowed(allow, "unsupported method"),
}
}
}
}
fn allow_for(&self, is_function: bool) -> &'static str {
match (self.config.read_only, is_function) {
(true, _) => ALLOW_READ_ONLY,
(false, true) => ALLOW_FUNCTION,
(false, false) => ALLOW_VALUE,
}
}
fn read(&self, pointer: &str, request: RestRequest<'_>) -> RestResponse {
let value = match self.registry.dispatch(pointer, None) {
Ok(value) => value,
Err(err) => return self.problem_for(err),
};
let (body, media) = match encode(&value, negotiate(request.accept)) {
Ok(encoded) => encoded,
Err(detail) => return RestResponse::problem(500, detail, None),
};
let etag = etag_for(&body);
let cache_control = self.config.cache_control.clone();
if let Some(header) = request.if_none_match
&& if_none_match_matches(header, &etag)
{
return RestResponse {
etag: Some(etag),
cache_control,
vary: Some("Accept"),
..RestResponse::empty(304)
};
}
RestResponse {
status: 200,
content_type: Some(media),
etag: Some(etag),
cache_control,
vary: Some("Accept"),
omit_body: request.method == "HEAD",
body,
..RestResponse::empty(200)
}
}
fn write_or_call(
&self,
pointer: &str,
request: RestRequest<'_>,
allow: &'static str,
is_function: bool,
) -> RestResponse {
if self.config.read_only {
return method_not_allowed(allow, "this gateway is configured read-only");
}
if crate::registry::addresses_root(pointer) && !self.config.allow_root_write {
return method_not_allowed(
ALLOW_READ_ONLY,
"a write at the mount root would merge arbitrary keys into the registry; \
enable `RestConfig::allow_root_write` to permit it",
);
}
if request.body.is_empty() {
return RestResponse::problem(
400,
"a body is required; send `null` for a call that takes no arguments",
Some(ErrorCode::InvalidBody as u32),
);
}
let repr = match self.body_repr(request.content_type) {
Ok(repr) => repr,
Err(detail) => {
return RestResponse::problem(415, detail, Some(ErrorCode::InvalidBody as u32));
}
};
let payload = match decode(request.body, repr) {
Ok(payload) => payload,
Err(detail) => {
return RestResponse::problem(400, detail, Some(ErrorCode::InvalidBody as u32));
}
};
let value = if is_function {
match self.registry.call(
pointer,
Some(payload),
&crate::CallContext::detached(pointer),
) {
Ok(value) => value,
Err(err) => return self.problem_for(err),
}
} else {
match self.conditional_write(pointer, payload, &request) {
Ok(Some(value)) => value,
Ok(None) => return precondition_failed(),
Err(err) => return self.problem_for(err),
}
};
let (body, media) = match encode(&value, negotiate(request.accept)) {
Ok(encoded) => encoded,
Err(detail) => return RestResponse::problem(500, detail, None),
};
RestResponse {
content_type: Some(media),
vary: Some("Accept"),
body,
..RestResponse::empty(200)
}
}
fn conditional_write(
&self,
pointer: &str,
payload: Value,
request: &RestRequest<'_>,
) -> Result<Option<Value>, RegistryError> {
let if_match = request.if_match;
let if_none_match = request.if_none_match;
if if_match.is_none() && if_none_match.is_none() {
return self.registry.write_if(pointer, payload, |_| true);
}
self.registry.write_if(pointer, payload, |current| {
if let Some(header) = if_match
&& !precondition_present(current, header, if_match_matches)
{
return false;
}
if let Some(header) = if_none_match
&& precondition_present(current, header, if_none_match_matches)
{
return false;
}
true
})
}
fn body_repr(&self, content_type: Option<&str>) -> Result<Repr, &'static str> {
let Some(content_type) = content_type else {
return Ok(Repr::Json);
};
match bare_media(content_type, ';').as_str() {
"" | MEDIA_JSON | "text/json" => Ok(Repr::Json),
"application/x-www-form-urlencoded" => Ok(Repr::Json),
MEDIA_BEVE | "application/beve" if self.config.accept_beve_bodies => Ok(Repr::Beve),
MEDIA_BEVE | "application/beve" => Err(
"BEVE request bodies are disabled; enable `RestConfig::accept_beve_bodies` \
or send application/json",
),
_ => Err("unsupported Content-Type; send application/json"),
}
}
fn strip_mount<'p>(&self, path: &'p str) -> Option<&'p str> {
if self.mount.is_empty() {
return Some(path);
}
let rest = path.strip_prefix(self.mount.as_str())?;
if rest.is_empty() || rest.starts_with('/') {
Some(rest)
} else {
None
}
}
fn problem_for(&self, err: RegistryError) -> RestResponse {
let code = err.code();
RestResponse::problem(self.status_for(code), err.to_string(), Some(code as u32))
}
fn status_for(&self, code: ErrorCode) -> u16 {
match code {
ErrorCode::Ok => 200,
ErrorCode::MethodNotFound => 404,
ErrorCode::Timeout => 504,
ErrorCode::ResourceExhausted => 503,
ErrorCode::InternalError => 500,
ErrorCode::ApplicationErrorBase => self.config.application_error_status,
_ => 400,
}
}
}
fn method_not_allowed(allow: &'static str, detail: &str) -> RestResponse {
RestResponse {
allow: Some(allow),
..RestResponse::problem(405, detail, None)
}
}
fn path_to_pointer(path: &str) -> Result<String, &'static str> {
if path.is_empty() || path == "/" {
return Ok(String::new());
}
let path = path.strip_suffix('/').unwrap_or(path);
if path.is_empty() {
return Ok(String::new());
}
if !path.starts_with('/') {
return Err("request path must be absolute");
}
let mut pointer = String::with_capacity(path.len());
for segment in path.split('/').skip(1) {
pointer.push('/');
pointer.push_str(&crate::registry::escape_token(&percent_decode(segment)?));
}
Ok(pointer)
}
fn percent_decode(segment: &str) -> Result<String, &'static str> {
if !segment.contains('%') {
return Ok(segment.to_string());
}
let bytes = segment.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' {
if i + 2 >= bytes.len() {
return Err("truncated percent-escape in request path");
}
let (hi, lo) = (hex_nibble(bytes[i + 1]), hex_nibble(bytes[i + 2]));
let (Some(hi), Some(lo)) = (hi, lo) else {
return Err("invalid percent-escape in request path");
};
out.push((hi << 4) | lo);
i += 3;
} else {
out.push(bytes[i]);
i += 1;
}
}
String::from_utf8(out).map_err(|_| "percent-escape decoded to invalid UTF-8")
}
fn hex_nibble(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
b'A'..=b'F' => Some(byte - b'A' + 10),
_ => None,
}
}
fn negotiate(accept: Option<&str>) -> Repr {
let Some(accept) = accept else {
return Repr::Json;
};
let mut best: Option<(u32, Repr)> = None;
for entry in accept.split(',') {
let media = bare_media(entry, ';');
let mut quality = 1000;
for param in entry.split(';').skip(1) {
let param = param.trim();
if let Some(value) = param
.strip_prefix("q=")
.or_else(|| param.strip_prefix("Q="))
{
quality = parse_quality(value);
}
}
let repr = match media.as_str() {
MEDIA_BEVE | "application/beve" => Repr::Beve,
MEDIA_JSON | "application/*" | "*/*" => Repr::Json,
_ => continue,
};
if quality == 0 {
continue;
}
if best.is_none_or(|(best_quality, _)| quality > best_quality) {
best = Some((quality, repr));
}
}
best.map_or(Repr::Json, |(_, repr)| repr)
}
fn parse_quality(value: &str) -> u32 {
value
.trim()
.parse::<f32>()
.map_or(1000, |q| (q.clamp(0.0, 1.0) * 1000.0).round() as u32)
}
fn encode(value: &Value, repr: Repr) -> Result<(Vec<u8>, &'static str), &'static str> {
let bytes = match repr {
Repr::Json => serde_json::to_vec(value).map_err(|_| "response is not encodable as JSON")?,
Repr::Beve => beve::to_vec(value).map_err(|_| "response is not encodable as BEVE")?,
};
Ok((bytes, repr.media_type()))
}
fn bare_media(value: &str, delimiter: char) -> String {
value
.split(delimiter)
.next()
.unwrap_or("")
.trim()
.to_ascii_lowercase()
}
fn decode(body: &[u8], repr: Repr) -> Result<Value, &'static str> {
match repr {
Repr::Json => serde_json::from_slice(body).map_err(|_| "request body is not valid JSON"),
Repr::Beve => beve::from_slice(body).map_err(|_| "request body is not valid BEVE"),
}
}
fn etag_for(body: &[u8]) -> String {
const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
let mut hash = FNV_OFFSET_BASIS;
for byte in body {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(FNV_PRIME);
}
format!("\"{hash:016x}\"")
}
fn precondition_present(
current: Option<&Value>,
header: &str,
matches: fn(&str, &str) -> bool,
) -> bool {
let Some(current) = current else {
return false;
};
if header.split(',').any(|candidate| candidate.trim() == "*") {
return true;
}
[Repr::Json, Repr::Beve]
.into_iter()
.any(|repr| encode(current, repr).is_ok_and(|(body, _)| matches(header, &etag_for(&body))))
}
fn precondition_failed() -> RestResponse {
RestResponse::problem(
412,
"a precondition failed: the resource has changed, or does not exist, or already exists",
None,
)
}
fn if_match_matches(header: &str, etag: &str) -> bool {
header.split(',').any(|candidate| candidate.trim() == etag)
}
fn if_none_match_matches(header: &str, etag: &str) -> bool {
header.split(',').any(|candidate| {
let candidate = candidate.trim();
candidate == "*" || candidate.strip_prefix("W/").unwrap_or(candidate) == etag
})
}
fn reason_phrase(status: u16) -> &'static str {
hyper::StatusCode::from_u16(status)
.ok()
.and_then(|status| status.canonical_reason())
.unwrap_or("Error")
}
use http_body_util::{BodyExt, Full, LengthLimitError, Limited};
use hyper::body::{Bytes, Incoming};
use hyper::{Request, Response};
use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer};
use hyper_util::server::conn::auto;
use std::convert::Infallible;
impl RestGateway {
pub async fn serve(self, listener: tokio::net::TcpListener) -> std::io::Result<()> {
let gateway = Arc::new(self);
let permits = Arc::new(tokio::sync::Semaphore::new(gateway.config.max_connections));
let mut backoff = ACCEPT_BACKOFF;
loop {
let Ok(permit) = Arc::clone(&permits).acquire_owned().await else {
return Ok(());
};
let stream = match listener.accept().await {
Ok((stream, _peer)) => {
backoff = ACCEPT_BACKOFF;
stream
}
Err(err) if is_per_connection_accept_error(&err) => continue,
Err(_) => {
tokio::time::sleep(backoff).await;
backoff = (backoff * 2).min(MAX_ACCEPT_BACKOFF);
continue;
}
};
let gateway = Arc::clone(&gateway);
tokio::spawn(async move {
let service = hyper::service::service_fn(move |request: Request<Incoming>| {
let gateway = Arc::clone(&gateway);
async move {
let response = match gateway.config.request_timeout {
Some(limit) => tokio::time::timeout(limit, gateway.handle(request))
.await
.unwrap_or_else(|_| request_timeout_response()),
None => gateway.handle(request).await,
};
Ok::<_, Infallible>(response)
}
});
let mut builder = auto::Builder::new(TokioExecutor::new());
builder
.http1()
.timer(TokioTimer::new())
.header_read_timeout(HEADER_READ_TIMEOUT);
let _ = builder
.serve_connection(TokioIo::new(stream), service)
.await;
drop(permit);
});
}
}
async fn handle(&self, request: Request<Incoming>) -> Response<Full<Bytes>> {
let (parts, body) = request.into_parts();
let method = parts.method.as_str().to_owned();
let target = parts
.uri
.path_and_query()
.map_or("/", |path_and_query| path_and_query.as_str())
.to_owned();
let header = |name: hyper::header::HeaderName| {
parts
.headers
.get(name)
.and_then(|value| value.to_str().ok())
.map(str::to_owned)
};
let content_type = header(hyper::header::CONTENT_TYPE);
let accept = header(hyper::header::ACCEPT);
let if_none_match = header(hyper::header::IF_NONE_MATCH);
let if_match = header(hyper::header::IF_MATCH);
let body = match Limited::new(body, self.config.max_body_bytes)
.collect()
.await
{
Ok(collected) => collected.to_bytes(),
Err(err) => {
let response = if err.downcast_ref::<LengthLimitError>().is_some() {
RestResponse::problem(
413,
format!(
"request body exceeds the {}-byte limit",
self.config.max_body_bytes
),
None,
)
} else {
RestResponse::problem(400, "request body could not be read", None)
};
return to_hyper(response);
}
};
to_hyper(self.respond(RestRequest {
method: &method,
target: &target,
content_type: content_type.as_deref(),
accept: accept.as_deref(),
if_none_match: if_none_match.as_deref(),
if_match: if_match.as_deref(),
body: &body,
}))
}
}
const HEADER_READ_TIMEOUT: Duration = Duration::from_secs(30);
const ACCEPT_BACKOFF: Duration = Duration::from_millis(50);
const MAX_ACCEPT_BACKOFF: Duration = Duration::from_secs(1);
fn is_per_connection_accept_error(err: &std::io::Error) -> bool {
use std::io::ErrorKind;
matches!(
err.kind(),
ErrorKind::ConnectionAborted | ErrorKind::ConnectionReset | ErrorKind::Interrupted
)
}
fn request_timeout_response() -> Response<Full<Bytes>> {
let mut response = to_hyper(RestResponse::problem(
408,
"the request was not completed within the gateway's time limit",
None,
));
response.headers_mut().insert(
hyper::header::CONNECTION,
hyper::header::HeaderValue::from_static("close"),
);
response
}
fn to_hyper(response: RestResponse) -> Response<Full<Bytes>> {
let mut builder = Response::builder().status(response.status);
if let Some(content_type) = response.content_type {
builder = builder.header(hyper::header::CONTENT_TYPE, content_type);
}
if let Some(etag) = &response.etag {
builder = builder.header(hyper::header::ETAG, etag);
}
if let Some(cache_control) = &response.cache_control {
builder = builder.header(hyper::header::CACHE_CONTROL, cache_control);
}
if let Some(vary) = response.vary {
builder = builder.header(hyper::header::VARY, vary);
}
if let Some(allow) = response.allow {
builder = builder.header(hyper::header::ALLOW, allow);
}
if let Some(code) = response.repe_error_code {
builder = builder.header("x-repe-error-code", code);
}
let built = if response.omit_body {
builder
.header(hyper::header::CONTENT_LENGTH, response.body.len())
.body(Full::new(Bytes::new()))
} else {
builder.body(Full::new(Bytes::from(response.body)))
};
built.unwrap_or_else(|_| {
Response::builder()
.status(500)
.body(Full::new(Bytes::new()))
.expect("a status-only response is always buildable")
})
}
#[cfg(test)]
mod tests {
use super::*;
fn gateway() -> RestGateway {
gateway_with(RestConfig::default())
}
fn gateway_with(config: RestConfig) -> RestGateway {
let registry = Arc::new(Registry::new());
registry.register_value("/counter", json!(7)).unwrap();
registry
.register_value("/config", json!({ "verbose": false }))
.unwrap();
registry
.register_value("/items/a~1b", json!("slashed"))
.unwrap();
registry
.register_value("/tilde/a~0b", json!("tilded"))
.unwrap();
registry
.register_function("/add", |params| {
let Some(Value::Object(map)) = params else {
return Err((ErrorCode::InvalidBody, "expected an object".into()));
};
let a = map.get("a").and_then(Value::as_i64).unwrap_or(0);
let b = map.get("b").and_then(Value::as_i64).unwrap_or(0);
Ok(json!({ "result": a + b }))
})
.unwrap();
registry
.register_function("/boom", |_| {
Err((ErrorCode::ApplicationErrorBase, "handler said no".into()))
})
.unwrap();
RestGateway::with_config("/api/v1", registry, config)
}
fn json_body(response: &RestResponse) -> Value {
serde_json::from_slice(&response.body).expect("response body is JSON")
}
#[test]
fn get_reads_a_value() {
let response = gateway().respond(RestRequest::new("GET", "/api/v1/counter"));
assert_eq!(response.status, 200);
assert_eq!(response.content_type, Some(MEDIA_JSON));
assert_eq!(json_body(&response), json!(7));
}
#[test]
fn get_at_the_mount_itself_reads_the_whole_tree() {
for target in ["/api/v1", "/api/v1/"] {
let response = gateway().respond(RestRequest::new("GET", target));
assert_eq!(response.status, 200, "{target}");
assert_eq!(json_body(&response)["counter"], json!(7), "{target}");
}
}
#[test]
fn put_writes_a_value() {
let gateway = gateway();
let response = gateway
.respond(RestRequest::new("PUT", "/api/v1/counter").with_body(MEDIA_JSON, b"42"));
assert_eq!(response.status, 200);
assert_eq!(
gateway.registry().read_value("/counter").unwrap(),
json!(42)
);
}
#[test]
fn post_calls_a_function() {
let response = gateway().respond(
RestRequest::new("POST", "/api/v1/add").with_body(MEDIA_JSON, br#"{"a":2,"b":3}"#),
);
assert_eq!(response.status, 200);
assert_eq!(json_body(&response), json!({ "result": 5 }));
}
#[test]
fn put_at_a_function_is_refused_rather_than_silently_calling_it() {
let response =
gateway().respond(RestRequest::new("PUT", "/api/v1/add").with_body(MEDIA_JSON, b"{}"));
assert_eq!(response.status, 405);
assert_eq!(response.allow, Some(ALLOW_FUNCTION));
assert_eq!(response.content_type, Some(MEDIA_PROBLEM));
}
#[test]
fn post_at_a_value_is_refused_rather_than_silently_writing_it() {
let gateway = gateway();
let response = gateway
.respond(RestRequest::new("POST", "/api/v1/counter").with_body(MEDIA_JSON, b"1"));
assert_eq!(response.status, 405);
assert_eq!(response.allow, Some(ALLOW_VALUE));
assert_eq!(
gateway.registry().read_value("/counter").unwrap(),
json!(7),
"the refused POST must not have written"
);
}
#[test]
fn a_write_with_no_body_is_refused_rather_than_read() {
for (method, target) in [("PUT", "/api/v1/counter"), ("POST", "/api/v1/add")] {
let response = gateway().respond(RestRequest::new(method, target));
assert_eq!(response.status, 400, "{method} {target}");
assert_eq!(
response.repe_error_code,
Some(ErrorCode::InvalidBody as u32),
"{method} {target}"
);
}
}
#[test]
fn a_no_argument_call_is_spelled_with_a_null_body() {
let registry = Arc::new(Registry::new());
registry
.register_function("/ping", |_| Ok(json!("pong")))
.unwrap();
let gateway = RestGateway::new("/api/v1", registry);
let response = gateway
.respond(RestRequest::new("POST", "/api/v1/ping").with_body(MEDIA_JSON, b"null"));
assert_eq!(response.status, 200);
assert_eq!(json_body(&response), json!("pong"));
}
#[test]
fn options_advertises_the_verbs_the_target_actually_supports() {
let gateway = gateway();
let value = gateway.respond(RestRequest::new("OPTIONS", "/api/v1/counter"));
assert_eq!(value.status, 204);
assert_eq!(value.allow, Some(ALLOW_VALUE));
let function = gateway.respond(RestRequest::new("OPTIONS", "/api/v1/add"));
assert_eq!(function.status, 204);
assert_eq!(function.allow, Some(ALLOW_FUNCTION));
}
#[test]
fn an_unsupported_method_is_405_with_allow() {
let response = gateway().respond(RestRequest::new("DELETE", "/api/v1/counter"));
assert_eq!(response.status, 405);
assert_eq!(response.allow, Some(ALLOW_VALUE));
}
#[test]
fn head_reports_the_length_without_the_body() {
let gateway = gateway();
let get = gateway.respond(RestRequest::new("GET", "/api/v1/config"));
let head = gateway.respond(RestRequest::new("HEAD", "/api/v1/config"));
assert!(head.omit_body);
assert!(!get.omit_body);
assert_eq!(head.body, get.body, "HEAD carries what GET would have sent");
assert_eq!(head.etag, get.etag);
}
#[test]
fn a_read_carries_a_validator_and_a_freshness_directive() {
let response = gateway().respond(RestRequest::new("GET", "/api/v1/counter"));
assert!(response.etag.is_some());
assert_eq!(response.cache_control.as_deref(), Some("no-cache"));
assert_eq!(response.vary, Some("Accept"));
}
#[test]
fn a_write_carries_neither() {
let response = gateway()
.respond(RestRequest::new("PUT", "/api/v1/counter").with_body(MEDIA_JSON, b"1"));
assert_eq!(response.etag, None);
assert_eq!(response.cache_control, None);
}
#[test]
fn a_matching_validator_answers_304_with_no_body() {
let gateway = gateway();
let first = gateway.respond(RestRequest::new("GET", "/api/v1/counter"));
let tag = first.etag.clone().unwrap();
let second =
gateway.respond(RestRequest::new("GET", "/api/v1/counter").with_if_none_match(&tag));
assert_eq!(second.status, 304);
assert!(second.body.is_empty());
assert_eq!(second.etag, first.etag, "304 still carries the validator");
}
#[test]
fn a_stale_validator_answers_the_full_body() {
let gateway = gateway();
let response = gateway.respond(
RestRequest::new("GET", "/api/v1/counter").with_if_none_match("\"0000000000000000\""),
);
assert_eq!(response.status, 200);
assert_eq!(json_body(&response), json!(7));
}
#[test]
fn the_validator_changes_when_the_value_does() {
let gateway = gateway();
let before = gateway.respond(RestRequest::new("GET", "/api/v1/counter"));
gateway.respond(RestRequest::new("PUT", "/api/v1/counter").with_body(MEDIA_JSON, b"8"));
let after = gateway.respond(RestRequest::new("GET", "/api/v1/counter"));
assert_ne!(before.etag, after.etag);
let conditional = gateway.respond(
RestRequest::new("GET", "/api/v1/counter").with_if_none_match(&before.etag.unwrap()),
);
assert_eq!(conditional.status, 200);
}
#[test]
fn a_weak_validator_and_a_star_both_match() {
let gateway = gateway();
let tag = gateway
.respond(RestRequest::new("GET", "/api/v1/counter"))
.etag
.unwrap();
for header in [format!("W/{tag}"), "*".to_string(), format!("\"x\", {tag}")] {
let response = gateway
.respond(RestRequest::new("GET", "/api/v1/counter").with_if_none_match(&header));
assert_eq!(response.status, 304, "{header}");
}
}
#[test]
fn the_two_representations_get_different_validators() {
let gateway = gateway();
let as_json = gateway.respond(RestRequest::new("GET", "/api/v1/config"));
let as_beve =
gateway.respond(RestRequest::new("GET", "/api/v1/config").with_accept(MEDIA_BEVE));
assert_ne!(as_json.etag, as_beve.etag);
assert_eq!(as_json.vary, Some("Accept"));
assert_eq!(as_beve.vary, Some("Accept"));
}
#[test]
fn beve_is_served_on_request_and_decodes_to_the_same_value() {
let response =
gateway().respond(RestRequest::new("GET", "/api/v1/config").with_accept(MEDIA_BEVE));
assert_eq!(response.content_type, Some(MEDIA_BEVE));
let decoded: Value = beve::from_slice(&response.body).unwrap();
assert_eq!(decoded, json!({ "verbose": false }));
}
#[test]
fn a_beve_request_body_is_accepted_by_default() {
let body = beve::to_vec(&json!({ "a": 20, "b": 22 })).unwrap();
let response =
gateway().respond(RestRequest::new("POST", "/api/v1/add").with_body(MEDIA_BEVE, &body));
assert_eq!(response.status, 200);
assert_eq!(json_body(&response), json!({ "result": 42 }));
}
#[test]
fn quality_values_are_honored() {
let gateway = gateway();
let cases = [
("application/json", MEDIA_JSON),
("application/x-beve", MEDIA_BEVE),
("*/*", MEDIA_JSON),
(
"application/json;q=0.1, application/x-beve;q=0.9",
MEDIA_BEVE,
),
(
"application/json;q=0.9, application/x-beve;q=0.1",
MEDIA_JSON,
),
("application/x-beve;q=0, application/json", MEDIA_JSON),
("application/x-beve, application/json", MEDIA_BEVE),
("text/plain", MEDIA_JSON),
];
for (accept, expected) in cases {
let response =
gateway.respond(RestRequest::new("GET", "/api/v1/counter").with_accept(accept));
assert_eq!(response.content_type, Some(expected), "Accept: {accept}");
}
}
#[test]
fn an_unsupported_content_type_is_415() {
let response = gateway().respond(
RestRequest::new("PUT", "/api/v1/counter").with_body("application/xml", b"<x/>"),
);
assert_eq!(response.status, 415);
}
#[test]
fn a_missing_content_type_is_treated_as_json() {
let mut request = RestRequest::new("PUT", "/api/v1/counter");
request.body = b"99";
let gateway = gateway();
assert_eq!(gateway.respond(request).status, 200);
assert_eq!(
gateway.registry().read_value("/counter").unwrap(),
json!(99)
);
}
#[test]
fn a_malformed_body_is_400_not_500() {
let response = gateway()
.respond(RestRequest::new("PUT", "/api/v1/counter").with_body(MEDIA_JSON, b"{oops"));
assert_eq!(response.status, 400);
}
#[test]
fn a_path_outside_the_mount_is_404() {
for target in ["/counter", "/other/counter", "/"] {
assert_eq!(
gateway().respond(RestRequest::new("GET", target)).status,
404,
"{target}"
);
}
}
#[test]
fn the_mount_must_match_on_a_segment_boundary() {
assert_eq!(
gateway()
.respond(RestRequest::new("GET", "/api/v1x/counter"))
.status,
404
);
}
#[test]
fn a_percent_encoded_separator_stays_inside_one_segment() {
let response = gateway().respond(RestRequest::new("GET", "/api/v1/items/a%2Fb"));
assert_eq!(response.status, 200);
assert_eq!(json_body(&response), json!("slashed"));
}
#[test]
fn a_literal_tilde_in_a_segment_is_escaped_not_interpreted() {
let response = gateway().respond(RestRequest::new("GET", "/api/v1/tilde/a~b"));
assert_eq!(response.status, 200);
assert_eq!(json_body(&response), json!("tilded"));
}
#[test]
fn a_trailing_slash_is_the_same_resource() {
let gateway = gateway();
assert_eq!(
gateway
.respond(RestRequest::new("GET", "/api/v1/counter/"))
.body,
gateway
.respond(RestRequest::new("GET", "/api/v1/counter"))
.body
);
}
#[test]
fn the_query_string_and_fragment_are_not_part_of_the_resource() {
let gateway = gateway();
let plain = gateway.respond(RestRequest::new("GET", "/api/v1/counter"));
for target in ["/api/v1/counter?pretty=1", "/api/v1/counter#x"] {
assert_eq!(
gateway.respond(RestRequest::new("GET", target)).body,
plain.body,
"{target}"
);
}
}
#[test]
fn a_malformed_percent_escape_is_400() {
for target in ["/api/v1/a%zz", "/api/v1/a%2"] {
assert_eq!(
gateway().respond(RestRequest::new("GET", target)).status,
400,
"{target}"
);
}
}
#[test]
fn a_root_mount_serves_every_path() {
let registry = Arc::new(Registry::new());
registry.register_value("/counter", json!(1)).unwrap();
for mount in ["", "/"] {
let gateway = RestGateway::new(mount, Arc::clone(®istry));
assert_eq!(
gateway.respond(RestRequest::new("GET", "/counter")).status,
200,
"mount {mount:?}"
);
}
}
#[test]
fn every_spelling_of_a_mount_names_the_same_mount() {
let registry = Arc::new(Registry::new());
registry.register_value("/counter", json!(1)).unwrap();
for mount in ["/api/v1", "/api/v1/", "api/v1"] {
let gateway = RestGateway::new(mount, Arc::clone(®istry));
assert_eq!(
gateway
.respond(RestRequest::new("GET", "/api/v1/counter"))
.status,
200,
"mount {mount:?}"
);
}
}
#[test]
fn a_missing_path_is_404_as_problem_details_carrying_the_repe_code() {
let response = gateway().respond(RestRequest::new("GET", "/api/v1/absent"));
assert_eq!(response.status, 404);
assert_eq!(response.content_type, Some(MEDIA_PROBLEM));
assert_eq!(
response.repe_error_code,
Some(ErrorCode::MethodNotFound as u32)
);
let problem = json_body(&response);
assert_eq!(problem["status"], json!(404));
assert_eq!(problem["title"], json!("Not Found"));
assert_eq!(
problem["repe_code"],
json!(ErrorCode::MethodNotFound as u32)
);
}
#[test]
fn a_handler_error_defaults_to_500_and_is_configurable() {
let default = gateway()
.respond(RestRequest::new("POST", "/api/v1/boom").with_body(MEDIA_JSON, b"null"));
assert_eq!(default.status, 500);
assert_eq!(
default.repe_error_code,
Some(ErrorCode::ApplicationErrorBase as u32)
);
assert_eq!(json_body(&default)["detail"], json!("handler said no"));
let remapped = gateway_with(RestConfig {
application_error_status: 422,
..RestConfig::default()
})
.respond(RestRequest::new("POST", "/api/v1/boom").with_body(MEDIA_JSON, b"null"));
assert_eq!(remapped.status, 422);
}
#[test]
fn a_handler_rejecting_its_arguments_is_400() {
let response = gateway()
.respond(RestRequest::new("POST", "/api/v1/add").with_body(MEDIA_JSON, b"[1,2]"));
assert_eq!(response.status, 400);
}
#[test]
fn beve_request_bodies_are_refused_when_the_knob_is_off() {
let gateway = gateway_with(RestConfig {
accept_beve_bodies: false,
..RestConfig::default()
});
let body = beve::to_vec(&json!({ "a": 1, "b": 2 })).unwrap();
let response =
gateway.respond(RestRequest::new("POST", "/api/v1/add").with_body(MEDIA_BEVE, &body));
assert_eq!(response.status, 415);
let read =
gateway.respond(RestRequest::new("GET", "/api/v1/config").with_accept(MEDIA_BEVE));
assert_eq!(read.status, 200);
assert_eq!(read.content_type, Some(MEDIA_BEVE));
}
#[test]
fn a_deeply_nested_beve_body_is_answered_rather_than_aborting() {
let mut body = Vec::new();
for _ in 0..20_000 {
body.extend_from_slice(&[0x05, 0x04]);
}
body.extend_from_slice(&[0x05, 0x00]);
let response =
gateway().respond(RestRequest::new("POST", "/api/v1/add").with_body(MEDIA_BEVE, &body));
assert_eq!(response.status, 400);
}
#[test]
fn read_only_refuses_every_mutation_and_says_so_in_allow() {
let gateway = gateway_with(RestConfig {
read_only: true,
..RestConfig::default()
});
for (method, target) in [("PUT", "/api/v1/counter"), ("POST", "/api/v1/add")] {
let response =
gateway.respond(RestRequest::new(method, target).with_body(MEDIA_JSON, b"1"));
assert_eq!(response.status, 405, "{method} {target}");
assert_eq!(response.allow, Some(ALLOW_READ_ONLY), "{method} {target}");
}
assert_eq!(gateway.registry().read_value("/counter").unwrap(), json!(7));
let options = gateway.respond(RestRequest::new("OPTIONS", "/api/v1/counter"));
assert_eq!(options.allow, Some(ALLOW_READ_ONLY));
assert_eq!(
gateway
.respond(RestRequest::new("GET", "/api/v1/counter"))
.status,
200
);
}
#[test]
fn a_write_at_the_mount_root_is_refused_unless_enabled() {
let gateway = gateway();
let response = gateway.respond(
RestRequest::new("PUT", "/api/v1").with_body(MEDIA_JSON, br#"{"injected":1}"#),
);
assert_eq!(response.status, 405);
assert!(gateway.registry().read_value("/injected").is_err());
let permissive = gateway_with(RestConfig {
allow_root_write: true,
..RestConfig::default()
});
let response = permissive.respond(
RestRequest::new("PUT", "/api/v1").with_body(MEDIA_JSON, br#"{"injected":1}"#),
);
assert_eq!(response.status, 200);
assert_eq!(
permissive.registry().read_value("/injected").unwrap(),
json!(1)
);
}
#[test]
fn if_match_gates_the_write() {
let gateway = gateway();
let tag = gateway
.respond(RestRequest::new("GET", "/api/v1/counter"))
.etag
.unwrap();
let stale = gateway.respond(
RestRequest::new("PUT", "/api/v1/counter")
.with_body(MEDIA_JSON, b"1")
.with_if_match("\"0000000000000000\""),
);
assert_eq!(stale.status, 412);
assert_eq!(gateway.registry().read_value("/counter").unwrap(), json!(7));
let fresh = gateway.respond(
RestRequest::new("PUT", "/api/v1/counter")
.with_body(MEDIA_JSON, b"1")
.with_if_match(&tag),
);
assert_eq!(fresh.status, 200);
assert_eq!(gateway.registry().read_value("/counter").unwrap(), json!(1));
let replay = gateway.respond(
RestRequest::new("PUT", "/api/v1/counter")
.with_body(MEDIA_JSON, b"2")
.with_if_match(&tag),
);
assert_eq!(replay.status, 412);
}
#[test]
fn if_match_star_requires_the_resource_to_exist() {
let gateway = gateway();
let existing = gateway.respond(
RestRequest::new("PUT", "/api/v1/counter")
.with_body(MEDIA_JSON, b"1")
.with_if_match("*"),
);
assert_eq!(existing.status, 200);
let absent = gateway.respond(
RestRequest::new("PUT", "/api/v1/absent")
.with_body(MEDIA_JSON, b"1")
.with_if_match("*"),
);
assert_eq!(absent.status, 412);
}
#[test]
fn if_match_uses_strong_comparison() {
let gateway = gateway();
let tag = gateway
.respond(RestRequest::new("GET", "/api/v1/counter"))
.etag
.unwrap();
let response = gateway.respond(
RestRequest::new("PUT", "/api/v1/counter")
.with_body(MEDIA_JSON, b"1")
.with_if_match(&format!("W/{tag}")),
);
assert_eq!(response.status, 412);
}
#[test]
fn a_doubled_slash_does_not_reach_the_root() {
let gateway = gateway();
for target in ["/api/v1", "/api/v1/", "/api/v1//"] {
let response = gateway
.respond(RestRequest::new("PUT", target).with_body(MEDIA_JSON, br#"{"x":1}"#));
assert_eq!(response.status, 405, "{target}");
}
assert!(
gateway.registry().read_value("/x").is_err(),
"the root was written through one of the spellings above"
);
}
#[test]
fn a_permitted_root_write_still_works_through_every_spelling() {
for target in ["/api/v1", "/api/v1/", "/api/v1//"] {
let gateway = gateway_with(RestConfig {
allow_root_write: true,
..RestConfig::default()
});
let response = gateway
.respond(RestRequest::new("PUT", target).with_body(MEDIA_JSON, br#"{"x":1}"#));
assert_eq!(response.status, 200, "{target}");
assert_eq!(gateway.registry().read_value("/x").unwrap(), json!(1));
}
}
#[test]
fn if_none_match_star_refuses_to_overwrite() {
let gateway = gateway();
let response = gateway.respond(
RestRequest {
if_none_match: Some("*"),
..RestRequest::new("PUT", "/api/v1/counter")
}
.with_body(MEDIA_JSON, b"99"),
);
assert_eq!(response.status, 412);
assert_eq!(gateway.registry().read_value("/counter").unwrap(), json!(7));
}
#[test]
fn if_none_match_star_permits_a_create() {
let gateway = gateway();
let response = gateway.respond(
RestRequest {
if_none_match: Some("*"),
..RestRequest::new("PUT", "/api/v1/fresh")
}
.with_body(MEDIA_JSON, b"1"),
);
assert_eq!(response.status, 200);
assert_eq!(gateway.registry().read_value("/fresh").unwrap(), json!(1));
}
#[test]
fn if_none_match_with_a_tag_refuses_a_matching_write() {
let gateway = gateway();
let tag = gateway
.respond(RestRequest::new("GET", "/api/v1/counter"))
.etag
.unwrap();
let response = gateway.respond(
RestRequest {
if_none_match: Some(&tag),
..RestRequest::new("PUT", "/api/v1/counter")
}
.with_body(MEDIA_JSON, b"99"),
);
assert_eq!(response.status, 412);
assert_eq!(gateway.registry().read_value("/counter").unwrap(), json!(7));
}
#[test]
fn exactly_one_racing_conditional_write_wins() {
let gateway = Arc::new(gateway());
let tag = gateway
.respond(RestRequest::new("GET", "/api/v1/counter"))
.etag
.unwrap();
let accepted = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let barrier = Arc::new(std::sync::Barrier::new(16));
std::thread::scope(|scope| {
for worker in 0..16 {
let gateway = Arc::clone(&gateway);
let accepted = Arc::clone(&accepted);
let barrier = Arc::clone(&barrier);
let tag = tag.clone();
scope.spawn(move || {
let body = (1000 + worker).to_string();
barrier.wait();
let response = gateway.respond(
RestRequest {
if_match: Some(&tag),
..RestRequest::new("PUT", "/api/v1/counter")
}
.with_body(MEDIA_JSON, body.as_bytes()),
);
if response.status == 200 {
accepted.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}
});
}
});
assert_eq!(
accepted.load(std::sync::atomic::Ordering::SeqCst),
1,
"more than one writer saw the same validator match"
);
}
#[test]
fn options_star_respects_read_only() {
let gateway = gateway_with(RestConfig {
read_only: true,
..RestConfig::default()
});
let response = gateway.respond(RestRequest::new("OPTIONS", "*"));
assert_eq!(response.status, 204);
assert_eq!(response.allow, Some(ALLOW_READ_ONLY));
}
#[test]
fn a_write_never_becomes_a_call_and_a_call_never_becomes_a_write() {
let registry = Arc::new(Registry::new());
registry.register_value("/value", json!(1)).unwrap();
registry
.register_function("/function", |_| Ok(json!("called")))
.unwrap();
assert!(
registry.write_if("/function", json!(2), |_| true).is_err(),
"a write reached a function"
);
assert!(
registry
.call(
"/value",
Some(json!(2)),
&crate::CallContext::detached("/value")
)
.is_err(),
"a call reached a value"
);
assert_eq!(registry.read_value("/value").unwrap(), json!(1));
}
#[test]
fn if_match_accepts_a_tag_from_either_representation() {
let gateway = gateway();
let beve_tag = gateway
.respond(RestRequest::new("GET", "/api/v1/counter").with_accept(MEDIA_BEVE))
.etag
.unwrap();
let response = gateway.respond(
RestRequest::new("PUT", "/api/v1/counter")
.with_body(MEDIA_JSON, b"1")
.with_if_match(&beve_tag),
);
assert_eq!(response.status, 200);
}
#[test]
fn an_error_response_is_never_cacheable() {
let gateway = gateway();
let cases = [
gateway.respond(RestRequest::new("GET", "/api/v1/absent")),
gateway.respond(RestRequest::new("DELETE", "/api/v1/counter")),
gateway
.respond(RestRequest::new("POST", "/api/v1/counter").with_body(MEDIA_JSON, b"1")),
];
for response in cases {
assert!(response.status >= 400);
assert_eq!(response.cache_control.as_deref(), Some("no-store"));
}
}
#[test]
fn options_star_asks_about_the_server_not_a_resource() {
let response = gateway().respond(RestRequest::new("OPTIONS", "*"));
assert_eq!(response.status, 204);
assert_eq!(response.allow, Some(ALLOW_SERVER));
}
#[test]
fn path_to_pointer_cases() {
let cases = [
("", ""),
("/", ""),
("/counter", "/counter"),
("/counter/", "/counter"),
("/a/b/c", "/a/b/c"),
("/a%2Fb", "/a~1b"),
("/a~b", "/a~0b"),
("/a%7Eb", "/a~0b"),
("/sp%20ace", "/sp ace"),
("/a//b", "/a//b"),
];
for (path, expected) in cases {
assert_eq!(path_to_pointer(path).unwrap(), expected, "{path}");
}
}
#[test]
fn etag_is_stable_and_content_addressed() {
assert_eq!(etag_for(b"abc"), etag_for(b"abc"));
assert_ne!(etag_for(b"abc"), etag_for(b"abd"));
assert_eq!(etag_for(b""), "\"cbf29ce484222325\"");
assert_eq!(etag_for(b"repe"), "\"4cac4e1fbfac553f\"");
}
}