footing 0.1.13

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 one = EndpointPermissions::one("users:read");
    let any = EndpointPermissions::any(&["users:read", "users:write"]);
    let all = EndpointPermissions::all(&["users:read", "users:write"]);

    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 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\"")
    );
}