footing 0.1.18

Feature-gated foundations for Rust backend services
Documentation
use axum::http::Method;

use super::{
    EndpointAudit, EndpointAuth, EndpointContract, EndpointContractRegistry,
    EndpointContractSnapshot, EndpointMethod, EndpointPathPattern, EndpointPermissions,
    EndpointRateLimit, EndpointRisk, EndpointRouter,
};
use crate::result::{ClassifyError, ErrorKind};

#[tokio::test]
async fn registered_contract_lookup_uses_axum_route_precedence_and_head_fallback() {
    use crate::http::{HttpMiddlewareConfig, HttpMiddlewareStack};
    use axum::{
        body::{Body, to_bytes},
        extract::{MatchedPath, State},
        http::Request,
    };
    use tower::ServiceExt;

    let contracts: [EndpointContract; 2] = [
        EndpointContract::new(
            EndpointMethod::Get,
            EndpointPathPattern::Template("/users/{id}"),
        ),
        EndpointContract::new(EndpointMethod::Get, EndpointPathPattern::Exact("/users/me")),
    ]
    .map(|contract| contract.with_rate_limit(EndpointRateLimit::Exempt));
    async fn selected(
        State(contracts): State<[EndpointContract; 2]>,
        method: Method,
        path: MatchedPath,
    ) -> &'static str {
        let registry = EndpointContractRegistry::new(&contracts);
        let contract = registry.find(&method, &path).unwrap();
        assert_eq!(
            registry.find(&Method::HEAD, &path).unwrap().path(),
            contract.path()
        );
        contract.path().as_str()
    }
    let routes = EndpointRouter::new()
        .route(contracts[0], selected)
        .unwrap()
        .route(contracts[1], selected)
        .unwrap();
    assert_eq!(routes.contracts().endpoints(), &contracts);
    let app = routes
        .into_router(
            HttpMiddlewareStack::builder(HttpMiddlewareConfig::minimal())
                .build()
                .unwrap(),
        )
        .unwrap()
        .with_state(contracts);
    for (path, expected) in [("/users/me", "/users/me"), ("/users/42", "/users/{id}")] {
        let response = app
            .clone()
            .oneshot(Request::get(path).body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(to_bytes(response.into_body(), 100).await.unwrap(), expected);
    }
}

#[test]
fn route_registration_rejects_duplicates_including_different_pattern_variants() {
    let first: EndpointContract =
        EndpointContract::new(EndpointMethod::Get, EndpointPathPattern::Exact("/users"));
    let duplicate =
        EndpointContract::new(EndpointMethod::Get, EndpointPathPattern::Template("/users"));
    assert!(matches!(
        EndpointRouter::<()>::new()
            .route(first, || async {})
            .unwrap()
            .route(duplicate, || async {}),
        Err(super::EndpointContractValidationError::DuplicateRoute { .. })
    ));
}

#[test]
fn unsupported_endpoint_method_is_classified_as_validation() {
    let error = EndpointMethod::try_from(&Method::TRACE)
        .expect_err("TRACE should not be contractable")
        .error_descriptor();

    assert_eq!(error.kind(), ErrorKind::Validation);
    assert_eq!(error.code().as_str(), "endpoint_method_unsupported");
}

#[test]
fn endpoint_method_converts_every_supported_http_method() {
    for (method, expected) in [
        (Method::DELETE, EndpointMethod::Delete),
        (Method::GET, EndpointMethod::Get),
        (Method::HEAD, EndpointMethod::Head),
        (Method::OPTIONS, EndpointMethod::Options),
        (Method::PATCH, EndpointMethod::Patch),
        (Method::POST, EndpointMethod::Post),
        (Method::PUT, EndpointMethod::Put),
    ] {
        assert_eq!(EndpointMethod::try_from(&method), Ok(expected));
    }
}

#[test]
fn endpoint_permissions_support_common_policy_modes() {
    let none = EndpointPermissions::<&str>::none();
    let one = EndpointPermissions::one("users:read");
    let any = EndpointPermissions::any(&["users:read", "users:write"]);
    let all = EndpointPermissions::all(&["users:read", "users:write"]);

    assert!(none.is_none());
    assert!(none.is_granted_by(|_| panic!("no permissions should be checked")));
    assert!(!none.contains("users:read"));
    assert!(one.is_granted_by(|permission| permission == "users:read"));
    assert!(any.is_granted_by(|permission| permission == "users:write"));
    assert!(!all.is_granted_by(|permission| permission == "users:write"));
    assert!(all.contains("users:read"));
    assert!(!EndpointPermissions::<&str>::all(&[]).is_granted_by(|_| true));
}

#[test]
fn authentication_and_permission_requirements_are_independent() {
    for auth in [
        EndpointAuth::Public,
        EndpointAuth::Authenticated,
        EndpointAuth::User,
        EndpointAuth::Client,
        EndpointAuth::Admin,
        EndpointAuth::Service,
    ] {
        let contract =
            EndpointContract::new(EndpointMethod::Get, EndpointPathPattern::Exact("/profile"))
                .with_auth(auth);
        EndpointContractRegistry::new(&[contract])
            .validate()
            .unwrap();
        let document = contract.document(str::to_owned);
        assert_eq!(document.auth, auth.as_str());
        assert_eq!(document.permissions.mode, "none");
        assert!(document.permissions.values.is_empty());

        let guarded = contract.with_permissions(EndpointPermissions::one("profile:read"));
        let endpoints = [guarded];
        let result = EndpointContractRegistry::new(&endpoints).validate();
        if auth == EndpointAuth::Public {
            assert!(matches!(
                result,
                Err(
                    super::EndpointContractValidationError::PublicEndpointRequiresPermissions { .. }
                )
            ));
        } else {
            result.unwrap();
        }
    }
}

#[test]
fn registry_validates_duplicate_routes_and_private_permissions() {
    let endpoints = [
        EndpointContract::new(
            EndpointMethod::Get,
            EndpointPathPattern::Exact("/api/users"),
        )
        .with_auth(EndpointAuth::Admin)
        .with_permissions(EndpointPermissions::one("users:read"))
        .with_risk(EndpointRisk::Low),
        EndpointContract::new(
            EndpointMethod::Post,
            EndpointPathPattern::Exact("/api/users"),
        )
        .with_auth(EndpointAuth::Admin)
        .with_permissions(EndpointPermissions::one("users:write"))
        .with_risk(EndpointRisk::Medium),
    ];

    let registry = EndpointContractRegistry::new(&endpoints);
    registry.validate().expect("contracts should be valid");
}

#[test]
fn registry_rejects_empty_permission_sets() {
    let endpoints = [EndpointContract::new(
        EndpointMethod::Get,
        EndpointPathPattern::Exact("/api/users"),
    )
    .with_auth(EndpointAuth::Admin)
    .with_permissions(EndpointPermissions::<&str>::all(&[]))];
    let registry = EndpointContractRegistry::new(&endpoints);
    let error = registry
        .validate()
        .expect_err("empty all permissions should be invalid");

    assert!(matches!(
        error,
        super::EndpointContractValidationError::EmptyPermissions { mode: "all", .. }
    ));
}

#[test]
fn registry_rejects_invalid_path_patterns() {
    let endpoints = [EndpointContract::new(
        EndpointMethod::Get,
        EndpointPathPattern::Exact("/api/users?active=true"),
    )];
    let registry = EndpointContractRegistry::<&str>::new(&endpoints);

    let error = registry
        .validate()
        .expect_err("query strings do not belong in route contracts");

    assert!(matches!(
        error,
        super::EndpointContractValidationError::InvalidPath { .. }
    ));
}

#[test]
fn registry_rejects_template_syntax_in_exact_paths() {
    let endpoints = [EndpointContract::new(
        EndpointMethod::Get,
        EndpointPathPattern::Exact("/api/users/{id}"),
    )];
    let registry = EndpointContractRegistry::<&str>::new(&endpoints);

    let error = registry
        .validate()
        .expect_err("template segments must use EndpointPathPattern::Template");

    assert!(matches!(
        error,
        super::EndpointContractValidationError::InvalidPath { .. }
    ));
}

#[test]
fn registry_rejects_invalid_custom_rate_limit_labels() {
    let endpoints = [EndpointContract::new(
        EndpointMethod::Get,
        EndpointPathPattern::Exact("/api/users"),
    )
    .with_rate_limit(EndpointRateLimit::Custom("User Reads"))];
    let registry = EndpointContractRegistry::<&str>::new(&endpoints);

    let error = registry
        .validate()
        .expect_err("custom rate limit labels must be stable metric labels");

    assert!(matches!(
        error,
        super::EndpointContractValidationError::InvalidRateLimitLabel { .. }
    ));
}

#[test]
fn registry_exports_stable_contract_documents() {
    let endpoints = [EndpointContract::new(
        EndpointMethod::Get,
        EndpointPathPattern::Exact("/api/users"),
    )
    .with_auth(EndpointAuth::Admin)
    .with_permissions(EndpointPermissions::one("users:read"))
    .with_risk(EndpointRisk::Low)];
    let registry = EndpointContractRegistry::new(&endpoints);

    let documents = registry.documents(str::to_owned);

    assert_eq!(documents.len(), 1);
    assert_eq!(documents[0].method, "GET");
    assert_eq!(documents[0].path, "/api/users");
    assert_eq!(documents[0].auth, "admin");
    assert_eq!(documents[0].permissions.mode, "one");
    assert_eq!(documents[0].permissions.values, ["users:read"]);
}

#[test]
fn registry_exports_stable_contract_snapshot() {
    let endpoints = [
        EndpointContract::new(
            EndpointMethod::Get,
            EndpointPathPattern::Exact("/api/users"),
        )
        .with_auth(EndpointAuth::Admin)
        .with_permissions(EndpointPermissions::one("users:read"))
        .with_risk(EndpointRisk::Low)
        .with_rate_limit(EndpointRateLimit::Read)
        .with_audit(EndpointAudit::Optional),
        EndpointContract::new(
            EndpointMethod::Delete,
            EndpointPathPattern::Template("/api/users/{id}"),
        )
        .with_auth(EndpointAuth::Admin)
        .with_permissions(EndpointPermissions::one("users:delete"))
        .with_risk(EndpointRisk::High)
        .with_rate_limit(EndpointRateLimit::Write)
        .with_audit(EndpointAudit::Required),
    ];
    let registry = EndpointContractRegistry::new(&endpoints);

    let snapshot = registry.snapshot(str::to_owned);

    assert_eq!(
        snapshot.schema_version(),
        EndpointContractSnapshot::SCHEMA_VERSION
    );
    assert_eq!(snapshot.summary().total, 2);
    assert_eq!(snapshot.summary().permissioned, 2);
    assert_eq!(snapshot.summary().by_auth["admin"], 2);
    assert_eq!(snapshot.summary().by_risk["high"], 1);
    assert_eq!(snapshot.summary().by_audit["required"], 1);
    assert!(
        snapshot
            .to_pretty_json()
            .expect("json")
            .contains("\"endpoints\"")
    );
}

#[test]
fn snapshots_normalize_order_and_validate_derived_data_on_deserialization() {
    let mut endpoints = [
        EndpointContract::new(EndpointMethod::Post, EndpointPathPattern::Exact("/users")),
        EndpointContract::new(EndpointMethod::Get, EndpointPathPattern::Exact("/health")),
        EndpointContract::new(EndpointMethod::Get, EndpointPathPattern::Exact("/users"))
            .with_auth(EndpointAuth::Authenticated),
    ];
    let snapshot = EndpointContractSnapshot::from_contracts(&endpoints, str::to_owned);
    endpoints.reverse();
    let reordered = EndpointContractSnapshot::from_contracts(&endpoints, str::to_owned);
    assert_eq!(snapshot, reordered);
    assert_eq!(
        snapshot.to_pretty_json().unwrap(),
        reordered.to_pretty_json().unwrap()
    );
    assert_eq!(snapshot.summary().total, 3);
    assert_eq!(snapshot.summary().permissioned, 0);
    assert_eq!(snapshot.summary().by_auth["authenticated"], 1);
    assert_eq!(
        snapshot
            .endpoints()
            .iter()
            .map(|endpoint| (endpoint.path.as_str(), endpoint.method.as_str()))
            .collect::<Vec<_>>(),
        [("/health", "GET"), ("/users", "GET"), ("/users", "POST")],
    );

    let mut wire = serde_json::to_value(&snapshot).unwrap();
    wire["endpoints"].as_array_mut().unwrap().reverse();
    assert_eq!(
        serde_json::from_value::<EndpointContractSnapshot>(wire.clone()).unwrap(),
        snapshot
    );
    let bytes = postcard::to_allocvec(&snapshot).unwrap();
    assert_eq!(
        postcard::from_bytes::<EndpointContractSnapshot>(&bytes).unwrap(),
        snapshot
    );

    let mut wrong_version = wire.clone();
    wrong_version["schema_version"] = 1.into();
    assert!(serde_json::from_value::<EndpointContractSnapshot>(wrong_version).is_err());
    let mut stale_counts = wire.clone();
    stale_counts["summary"]["permissioned"] = 1.into();
    assert!(serde_json::from_value::<EndpointContractSnapshot>(stale_counts).is_err());
    wire["endpoints"].as_array_mut().unwrap().pop();
    assert!(serde_json::from_value::<EndpointContractSnapshot>(wire).is_err());
}