capy-testing 0.10.0

In-process HTTP testing utilities for Capy applications.
Documentation
//! Test-only wire conformance against the application's declared OpenAPI output.
use axum::http::{header, HeaderMap, Method, StatusCode};
use regex::Regex;
use serde_json::Value;
use std::{collections::BTreeMap, sync::Arc};

#[derive(Clone)]
pub(crate) struct ContractRegistry {
    document: Arc<Value>,
    routes: Vec<RouteContract>,
    patterns: BTreeMap<String, Regex>,
}

#[derive(Clone)]
struct RouteContract {
    method: String,
    path: String,
    segments: Vec<String>,
    responses: BTreeMap<u16, Value>,
}

impl ContractRegistry {
    pub(crate) fn new(document: Value) -> Result<Self, String> {
        let mut routes = Vec::new();
        let paths = document["paths"]
            .as_object()
            .ok_or("OpenAPI paths must be an object")?;
        for (path, methods) in paths {
            let methods = methods
                .as_object()
                .ok_or("OpenAPI path methods must be an object")?;
            for (method, operation) in methods {
                if !matches!(
                    method.as_str(),
                    "get" | "post" | "put" | "patch" | "delete" | "head" | "options"
                ) {
                    continue;
                }
                let mut responses = BTreeMap::new();
                for (status, response) in operation["responses"]
                    .as_object()
                    .ok_or_else(|| format!("{method} {path} has no response map"))?
                {
                    let status = status.parse::<u16>().map_err(|_| {
                        format!("{method} {path} has unsupported wildcard status {status}")
                    })?;
                    responses.insert(status, response.clone());
                }
                routes.push(RouteContract {
                    method: method.to_ascii_uppercase(),
                    path: path.clone(),
                    segments: path.split('/').map(str::to_owned).collect(),
                    responses,
                });
            }
        }
        let mut patterns = BTreeMap::new();
        fn compile(value: &Value, patterns: &mut BTreeMap<String, Regex>) -> Result<(), String> {
            match value {
                Value::Object(object) => {
                    if let Some(pattern) = object.get("pattern").and_then(Value::as_str) {
                        if !patterns.contains_key(pattern) {
                            patterns.insert(
                                pattern.into(),
                                Regex::new(pattern).map_err(|error| {
                                    format!("Unsupported OpenAPI pattern `{pattern}`: {error}")
                                })?,
                            );
                        }
                    }
                    for child in object.values() {
                        compile(child, patterns)?;
                    }
                }
                Value::Array(items) => {
                    for child in items {
                        compile(child, patterns)?;
                    }
                }
                _ => {}
            }
            Ok(())
        }
        compile(&document, &mut patterns)?;
        Ok(Self {
            document: Arc::new(document),
            routes,
            patterns,
        })
    }

    pub(crate) fn validate(
        &self,
        method: &Method,
        path: &str,
        status: StatusCode,
        headers: &HeaderMap,
        body: &[u8],
    ) -> Result<(), String> {
        let path_only = path.split('?').next().unwrap_or(path);
        let requested = path_only.split('/').collect::<Vec<_>>();
        let route = self
            .routes
            .iter()
            .filter(|route| {
                route.method == method.as_str()
                    && route.segments.len() == requested.len()
                    && route
                        .segments
                        .iter()
                        .zip(&requested)
                        .all(|(segment, actual)| {
                            segment.starts_with('{') && segment.ends_with('}') || segment == actual
                        })
            })
            .max_by_key(|route| {
                route
                    .segments
                    .iter()
                    .filter(|segment| !segment.starts_with('{'))
                    .count()
            })
            .ok_or_else(|| format!("{method}: no matching documented operation"))?;
        let actual = status.as_u16();
        let response = route.responses.get(&actual).ok_or_else(|| {
            let expected = route.responses.keys().map(u16::to_string).collect::<Vec<_>>().join(", ");
            format!("{method} {}: returned undocumented status {actual}; documented statuses: {expected}", route.path)
        })?;
        let prefix = format!("{method} {} status {actual}", route.path);
        let content = response.get("content").and_then(Value::as_object);
        let Some(content) = content else {
            if !body.is_empty() {
                return Err(format!(
                    "{prefix}: response body was present but the contract declares no content"
                ));
            }
            return Ok(());
        };
        let media = headers
            .get(header::CONTENT_TYPE)
            .and_then(|value| value.to_str().ok())
            .map(|value| {
                value
                    .split(';')
                    .next()
                    .unwrap_or(value)
                    .trim()
                    .to_ascii_lowercase()
            })
            .unwrap_or_default();
        let declared = content.get(&media).ok_or_else(|| {
            format!(
                "{prefix}: returned media type `{}`; documented media types: {}",
                if media.is_empty() {
                    "<missing>"
                } else {
                    &media
                },
                content.keys().cloned().collect::<Vec<_>>().join(", ")
            )
        })?;
        if media == "application/json" {
            let json: Value = serde_json::from_slice(body)
                .map_err(|error| format!("{prefix}: invalid JSON body: {error}"))?;
            if let Some(schema) = declared.get("schema") {
                self.validate_schema(schema, &json, "$", 0)
                    .map_err(|error| format!("{prefix}: JSON schema mismatch at {error}"))?;
            }
        }
        Ok(())
    }

    fn validate_schema(
        &self,
        schema: &Value,
        value: &Value,
        location: &str,
        depth: usize,
    ) -> Result<(), String> {
        if depth > 64 {
            return Err(format!("{location}: schema reference depth exceeded 64"));
        }
        if let Some(reference) = schema.get("$ref").and_then(Value::as_str) {
            let pointer = reference.strip_prefix('#').ok_or_else(|| {
                format!("{location}: external schema reference `{reference}` is unsupported")
            })?;
            let target = self
                .document
                .pointer(pointer)
                .ok_or_else(|| format!("{location}: unresolved schema reference `{reference}`"))?;
            return self.validate_schema(target, value, location, depth + 1);
        }
        for keyword in [
            "not",
            "if",
            "then",
            "else",
            "patternProperties",
            "unevaluatedProperties",
            "dependentSchemas",
        ] {
            if schema.get(keyword).is_some() {
                return Err(format!(
                    "{location}: unsupported schema keyword `{keyword}`"
                ));
            }
        }
        if let Some(variants) = schema.get("allOf").and_then(Value::as_array) {
            for variant in variants {
                self.validate_schema(variant, value, location, depth + 1)?;
            }
        }
        if let Some(variants) = schema.get("anyOf").and_then(Value::as_array) {
            if !variants.iter().any(|variant| {
                self.validate_schema(variant, value, location, depth + 1)
                    .is_ok()
            }) {
                return Err(format!("{location}: value matches no anyOf branch"));
            }
        }
        if let Some(variants) = schema.get("oneOf").and_then(Value::as_array) {
            if variants
                .iter()
                .filter(|variant| {
                    self.validate_schema(variant, value, location, depth + 1)
                        .is_ok()
                })
                .count()
                != 1
            {
                return Err(format!(
                    "{location}: value must match exactly one oneOf branch"
                ));
            }
        }
        if let Some(expected) = schema.get("type") {
            let matches = match expected {
                Value::String(kind) => matches_type(kind, value),
                Value::Array(kinds) => kinds
                    .iter()
                    .any(|kind| kind.as_str().is_some_and(|kind| matches_type(kind, value))),
                _ => false,
            };
            if !matches {
                return Err(format!(
                    "{location}: expected type {}, received {}",
                    expected,
                    value_type(value)
                ));
            }
        }
        if let Some(expected) = schema.get("const") {
            if value != expected {
                return Err(format!(
                    "{location}: value does not match the declared constant"
                ));
            }
        }
        if let Some(allowed) = schema.get("enum").and_then(Value::as_array) {
            if !allowed.contains(value) {
                return Err(format!("{location}: value is outside the declared enum"));
            }
        }
        if let Some(text) = value.as_str() {
            let length = text.chars().count() as u64;
            if schema
                .get("minLength")
                .and_then(Value::as_u64)
                .is_some_and(|minimum| length < minimum)
            {
                return Err(format!("{location}: string is shorter than minLength"));
            }
            if schema
                .get("maxLength")
                .and_then(Value::as_u64)
                .is_some_and(|maximum| length > maximum)
            {
                return Err(format!("{location}: string is longer than maxLength"));
            }
            if let Some(pattern) = schema.get("pattern").and_then(Value::as_str) {
                let regex = self
                    .patterns
                    .get(pattern)
                    .ok_or_else(|| format!("{location}: pattern was not compiled"))?;
                if !regex.is_match(text) {
                    return Err(format!(
                        "{location}: string does not match pattern `{pattern}`"
                    ));
                }
            }
        }
        if let Some(number) = value.as_f64() {
            if schema
                .get("minimum")
                .and_then(Value::as_f64)
                .is_some_and(|minimum| number < minimum)
            {
                return Err(format!("{location}: number is below minimum"));
            }
            if schema
                .get("maximum")
                .and_then(Value::as_f64)
                .is_some_and(|maximum| number > maximum)
            {
                return Err(format!("{location}: number is above maximum"));
            }
            if schema
                .get("exclusiveMinimum")
                .and_then(Value::as_f64)
                .is_some_and(|minimum| number <= minimum)
            {
                return Err(format!("{location}: number is below exclusiveMinimum"));
            }
            if schema
                .get("exclusiveMaximum")
                .and_then(Value::as_f64)
                .is_some_and(|maximum| number >= maximum)
            {
                return Err(format!("{location}: number is above exclusiveMaximum"));
            }
        }
        if let Some(object) = value.as_object() {
            if let Some(required) = schema.get("required").and_then(Value::as_array) {
                for key in required.iter().filter_map(Value::as_str) {
                    if !object.contains_key(key) {
                        return Err(format!("{location}.{key}: missing required field"));
                    }
                }
            }
            let properties = schema.get("properties").and_then(Value::as_object);
            for (key, item) in object {
                let child = format!("{location}.{key}");
                if let Some(property) = properties.and_then(|properties| properties.get(key)) {
                    self.validate_schema(property, item, &child, depth + 1)?;
                } else if let Some(additional) = schema.get("additionalProperties") {
                    if additional == false {
                        return Err(format!("{child}: extra property is forbidden"));
                    }
                    if additional.is_object() {
                        self.validate_schema(additional, item, &child, depth + 1)?;
                    }
                }
            }
        }
        if let Some(items) = value.as_array() {
            if schema
                .get("minItems")
                .and_then(Value::as_u64)
                .is_some_and(|minimum| items.len() < minimum as usize)
            {
                return Err(format!("{location}: array is shorter than minItems"));
            }
            if schema
                .get("maxItems")
                .and_then(Value::as_u64)
                .is_some_and(|maximum| items.len() > maximum as usize)
            {
                return Err(format!("{location}: array is longer than maxItems"));
            }
            if let Some(item_schema) = schema.get("items") {
                for (index, item) in items.iter().enumerate() {
                    self.validate_schema(
                        item_schema,
                        item,
                        &format!("{location}[{index}]"),
                        depth + 1,
                    )?;
                }
            }
        }
        Ok(())
    }
}

fn matches_type(kind: &str, value: &Value) -> bool {
    match kind {
        "null" => value.is_null(),
        "boolean" => value.is_boolean(),
        "string" => value.is_string(),
        "integer" => value.is_i64() || value.is_u64(),
        "number" => value.is_number(),
        "object" => value.is_object(),
        "array" => value.is_array(),
        _ => false,
    }
}

fn value_type(value: &Value) -> &'static str {
    match value {
        Value::Null => "null",
        Value::Bool(_) => "boolean",
        Value::Number(_) => "number",
        Value::String(_) => "string",
        Value::Array(_) => "array",
        Value::Object(_) => "object",
    }
}