use std::{borrow::Cow, collections::BTreeMap, fmt};
use axum::http::Method;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::result::{ClassifyError, ErrorKind};
const MAX_ENDPOINT_RATE_LIMIT_LABEL_LENGTH: usize = 64;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EndpointMethod {
Delete,
Get,
Head,
Options,
Patch,
Post,
Put,
}
impl EndpointMethod {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Delete => "DELETE",
Self::Get => "GET",
Self::Head => "HEAD",
Self::Options => "OPTIONS",
Self::Patch => "PATCH",
Self::Post => "POST",
Self::Put => "PUT",
}
}
#[must_use]
pub const fn is_safe(self) -> bool {
matches!(self, Self::Get | Self::Head | Self::Options)
}
}
impl TryFrom<&Method> for EndpointMethod {
type Error = EndpointMethodError;
fn try_from(method: &Method) -> Result<Self, Self::Error> {
if method == Method::DELETE {
Ok(Self::Delete)
} else if method == Method::GET {
Ok(Self::Get)
} else if method == Method::HEAD {
Ok(Self::Head)
} else if method == Method::OPTIONS {
Ok(Self::Options)
} else if method == Method::PATCH {
Ok(Self::Patch)
} else if method == Method::POST {
Ok(Self::Post)
} else if method == Method::PUT {
Ok(Self::Put)
} else {
Err(EndpointMethodError)
}
}
}
impl fmt::Display for EndpointMethod {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[error("HTTP method is not supported by endpoint contracts")]
pub struct EndpointMethodError;
impl ClassifyError for EndpointMethodError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> Cow<'static, str> {
Cow::Borrowed("endpoint_method_unsupported")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EndpointPathPattern {
Exact(&'static str),
Template(&'static str),
}
impl EndpointPathPattern {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Exact(path) | Self::Template(path) => path,
}
}
#[must_use]
pub fn matches(self, path: &str) -> bool {
match self {
Self::Exact(expected) => path == expected,
Self::Template(template) => route_template_matches(template, path),
}
}
}
impl fmt::Display for EndpointPathPattern {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EndpointAuth {
Public,
Authenticated,
User,
Client,
Admin,
Service,
}
impl EndpointAuth {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Public => "public",
Self::Authenticated => "authenticated",
Self::User => "user",
Self::Client => "client",
Self::Admin => "admin",
Self::Service => "service",
}
}
#[must_use]
pub const fn requires_identity(self) -> bool {
!matches!(self, Self::Public)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EndpointPermissions<P: Copy + 'static = &'static str> {
Public,
One(P),
Any(&'static [P]),
All(&'static [P]),
}
impl<P: Copy + 'static> EndpointPermissions<P> {
#[must_use]
pub const fn public() -> Self {
Self::Public
}
#[must_use]
pub const fn one(permission: P) -> Self {
Self::One(permission)
}
#[must_use]
pub const fn any(permissions: &'static [P]) -> Self {
Self::Any(permissions)
}
#[must_use]
pub const fn all(permissions: &'static [P]) -> Self {
Self::All(permissions)
}
#[must_use]
pub const fn is_public(self) -> bool {
matches!(self, Self::Public)
}
#[must_use]
pub fn is_granted_by(self, mut has_permission: impl FnMut(P) -> bool) -> bool {
match self {
Self::Public => true,
Self::One(permission) => has_permission(permission),
Self::Any(permissions) => permissions.iter().copied().any(has_permission),
Self::All(permissions) => {
!permissions.is_empty() && permissions.iter().copied().all(has_permission)
}
}
}
#[must_use]
pub fn empty_requirement_mode(self) -> Option<&'static str> {
match self {
Self::Any([]) => Some("any"),
Self::All([]) => Some("all"),
Self::Public | Self::One(_) | Self::Any(_) | Self::All(_) => None,
}
}
}
impl<P: Copy + Eq + 'static> EndpointPermissions<P> {
#[must_use]
pub fn contains(self, permission: P) -> bool {
match self {
Self::Public => false,
Self::One(expected) => expected == permission,
Self::Any(permissions) | Self::All(permissions) => permissions.contains(&permission),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EndpointRisk {
Low,
Medium,
High,
Critical,
}
impl EndpointRisk {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Low => "low",
Self::Medium => "medium",
Self::High => "high",
Self::Critical => "critical",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EndpointIdempotency {
NotApplicable,
Optional,
Required,
}
impl EndpointIdempotency {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::NotApplicable => "not_applicable",
Self::Optional => "optional",
Self::Required => "required",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EndpointPagination {
None,
Offset,
Cursor,
}
impl EndpointPagination {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::None => "none",
Self::Offset => "offset",
Self::Cursor => "cursor",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EndpointRateLimit {
Default,
Read,
Write,
Authentication,
Sensitive,
Custom(&'static str),
}
impl EndpointRateLimit {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Default => "default",
Self::Read => "read",
Self::Write => "write",
Self::Authentication => "authentication",
Self::Sensitive => "sensitive",
Self::Custom(value) => value,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EndpointAudit {
None,
Optional,
Required,
}
impl EndpointAudit {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::None => "none",
Self::Optional => "optional",
Self::Required => "required",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct EndpointContract<P: Copy + 'static = &'static str> {
method: EndpointMethod,
path: EndpointPathPattern,
auth: EndpointAuth,
permissions: EndpointPermissions<P>,
risk: EndpointRisk,
idempotency: EndpointIdempotency,
pagination: EndpointPagination,
rate_limit: EndpointRateLimit,
audit: EndpointAudit,
}
impl<P: Copy + 'static> EndpointContract<P> {
#[must_use]
pub const fn new(method: EndpointMethod, path: EndpointPathPattern) -> Self {
Self {
method,
path,
auth: EndpointAuth::Public,
permissions: EndpointPermissions::Public,
risk: EndpointRisk::Low,
idempotency: EndpointIdempotency::NotApplicable,
pagination: EndpointPagination::None,
rate_limit: EndpointRateLimit::Default,
audit: EndpointAudit::None,
}
}
#[must_use]
pub const fn with_auth(mut self, auth: EndpointAuth) -> Self {
self.auth = auth;
self
}
#[must_use]
pub const fn with_permissions(mut self, permissions: EndpointPermissions<P>) -> Self {
self.permissions = permissions;
self
}
#[must_use]
pub const fn with_risk(mut self, risk: EndpointRisk) -> Self {
self.risk = risk;
self
}
#[must_use]
pub const fn with_idempotency(mut self, idempotency: EndpointIdempotency) -> Self {
self.idempotency = idempotency;
self
}
#[must_use]
pub const fn with_pagination(mut self, pagination: EndpointPagination) -> Self {
self.pagination = pagination;
self
}
#[must_use]
pub const fn with_rate_limit(mut self, rate_limit: EndpointRateLimit) -> Self {
self.rate_limit = rate_limit;
self
}
#[must_use]
pub const fn with_audit(mut self, audit: EndpointAudit) -> Self {
self.audit = audit;
self
}
#[must_use]
pub const fn method(&self) -> EndpointMethod {
self.method
}
#[must_use]
pub const fn path(&self) -> EndpointPathPattern {
self.path
}
#[must_use]
pub const fn auth(&self) -> EndpointAuth {
self.auth
}
#[must_use]
pub const fn permissions(&self) -> EndpointPermissions<P> {
self.permissions
}
#[must_use]
pub const fn risk(&self) -> EndpointRisk {
self.risk
}
#[must_use]
pub const fn idempotency(&self) -> EndpointIdempotency {
self.idempotency
}
#[must_use]
pub const fn pagination(&self) -> EndpointPagination {
self.pagination
}
#[must_use]
pub const fn rate_limit(&self) -> EndpointRateLimit {
self.rate_limit
}
#[must_use]
pub const fn audit(&self) -> EndpointAudit {
self.audit
}
#[must_use]
pub fn matches(self, method: &Method, path: &str) -> bool {
EndpointMethod::try_from(method)
.is_ok_and(|method| self.method == method && self.path.matches(path))
}
#[must_use]
pub fn document(self, permission_to_string: impl Fn(P) -> String) -> EndpointContractDocument {
EndpointContractDocument {
method: self.method.as_str().to_owned(),
path: self.path.as_str().to_owned(),
path_kind: match self.path {
EndpointPathPattern::Exact(_) => "exact",
EndpointPathPattern::Template(_) => "template",
}
.to_owned(),
auth: self.auth.as_str().to_owned(),
permissions: document_permissions(self.permissions, permission_to_string),
risk: self.risk.as_str().to_owned(),
idempotency: self.idempotency.as_str().to_owned(),
pagination: self.pagination.as_str().to_owned(),
rate_limit: self.rate_limit.as_str().to_owned(),
audit: self.audit.as_str().to_owned(),
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct EndpointContractRegistry<'a, P: Copy + 'static = &'static str> {
endpoints: &'a [EndpointContract<P>],
}
impl<'a, P: Copy + 'static> EndpointContractRegistry<'a, P> {
#[must_use]
pub const fn new(endpoints: &'a [EndpointContract<P>]) -> Self {
Self { endpoints }
}
#[must_use]
pub const fn endpoints(&self) -> &'a [EndpointContract<P>] {
self.endpoints
}
#[must_use]
pub fn find(&self, method: &Method, path: &str) -> Option<&'a EndpointContract<P>> {
self.endpoints
.iter()
.find(|contract| contract.matches(method, path))
}
pub fn validate(&self) -> Result<(), EndpointContractValidationError> {
for (index, endpoint) in self.endpoints.iter().enumerate() {
validate_endpoint(index, endpoint)?;
for (other_index, other) in self.endpoints.iter().enumerate().skip(index + 1) {
if endpoint.method == other.method && endpoint.path == other.path {
return Err(EndpointContractValidationError::DuplicateRoute {
first_index: index,
second_index: other_index,
method: endpoint.method,
path: endpoint.path.as_str(),
});
}
}
}
Ok(())
}
#[must_use]
pub fn documents(
&self,
permission_to_string: impl Fn(P) -> String + Copy,
) -> Vec<EndpointContractDocument> {
self.endpoints
.iter()
.map(|endpoint| endpoint.document(permission_to_string))
.collect()
}
#[must_use]
pub fn snapshot(
&self,
permission_to_string: impl Fn(P) -> String + Copy,
) -> EndpointContractSnapshot {
EndpointContractSnapshot::from_contracts(self.endpoints, permission_to_string)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct EndpointContractDocument {
pub method: String,
pub path: String,
pub path_kind: String,
pub auth: String,
pub permissions: EndpointPermissionsDocument,
pub risk: String,
pub idempotency: String,
pub pagination: String,
pub rate_limit: String,
pub audit: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct EndpointPermissionsDocument {
pub mode: String,
pub values: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct EndpointContractSnapshot {
pub schema_version: u32,
pub summary: EndpointContractSnapshotSummary,
pub endpoints: Vec<EndpointContractDocument>,
}
impl EndpointContractSnapshot {
pub const SCHEMA_VERSION: u32 = 1;
#[must_use]
pub fn new(endpoints: Vec<EndpointContractDocument>) -> Self {
Self {
schema_version: Self::SCHEMA_VERSION,
summary: EndpointContractSnapshotSummary::from_documents(&endpoints),
endpoints,
}
}
#[must_use]
pub fn from_contracts<P: Copy + 'static>(
endpoints: &[EndpointContract<P>],
permission_to_string: impl Fn(P) -> String + Copy,
) -> Self {
Self {
schema_version: Self::SCHEMA_VERSION,
summary: EndpointContractSnapshotSummary::from_contracts(endpoints),
endpoints: endpoints
.iter()
.map(|endpoint| endpoint.document(permission_to_string))
.collect(),
}
}
pub fn to_pretty_json(&self) -> Result<String, serde_json::Error> {
serde_json::to_string_pretty(self)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct EndpointContractSnapshotSummary {
pub total: usize,
pub by_auth: BTreeMap<String, usize>,
pub by_risk: BTreeMap<String, usize>,
pub by_audit: BTreeMap<String, usize>,
pub by_rate_limit: BTreeMap<String, usize>,
pub permissioned: usize,
pub paginated: usize,
pub idempotency_required: usize,
}
impl EndpointContractSnapshotSummary {
#[must_use]
pub fn from_contracts<P: Copy + 'static>(endpoints: &[EndpointContract<P>]) -> Self {
let mut summary = Self::new(endpoints.len());
for endpoint in endpoints {
increment(&mut summary.by_auth, endpoint.auth.as_str());
increment(&mut summary.by_risk, endpoint.risk.as_str());
increment(&mut summary.by_audit, endpoint.audit.as_str());
increment(&mut summary.by_rate_limit, endpoint.rate_limit.as_str());
if !endpoint.permissions.is_public() {
summary.permissioned += 1;
}
if endpoint.pagination != EndpointPagination::None {
summary.paginated += 1;
}
if endpoint.idempotency == EndpointIdempotency::Required {
summary.idempotency_required += 1;
}
}
summary
}
#[must_use]
pub fn from_documents(endpoints: &[EndpointContractDocument]) -> Self {
let mut summary = Self::new(endpoints.len());
for endpoint in endpoints {
increment(&mut summary.by_auth, &endpoint.auth);
increment(&mut summary.by_risk, &endpoint.risk);
increment(&mut summary.by_audit, &endpoint.audit);
increment(&mut summary.by_rate_limit, &endpoint.rate_limit);
if endpoint.permissions.mode != "public" {
summary.permissioned += 1;
}
if endpoint.pagination != "none" {
summary.paginated += 1;
}
if endpoint.idempotency == "required" {
summary.idempotency_required += 1;
}
}
summary
}
fn new(total: usize) -> Self {
Self {
total,
by_auth: BTreeMap::new(),
by_risk: BTreeMap::new(),
by_audit: BTreeMap::new(),
by_rate_limit: BTreeMap::new(),
permissioned: 0,
paginated: 0,
idempotency_required: 0,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum EndpointContractValidationError {
#[error("endpoint contract at index {index} has an empty path")]
EmptyPath {
#[doc = "The zero-based item index."]
index: usize,
},
#[error("endpoint contract at index {index} path must start with '/'")]
RelativePath {
#[doc = "The zero-based item index."]
index: usize,
#[doc = "The affected path."]
path: &'static str,
},
#[error("endpoint contract at index {index} has an invalid path: {path:?}")]
InvalidPath {
#[doc = "The zero-based item index."]
index: usize,
#[doc = "The affected path."]
path: &'static str,
},
#[error("endpoint contract at index {index} has an invalid template segment")]
InvalidTemplate {
#[doc = "The zero-based item index."]
index: usize,
#[doc = "The affected path."]
path: &'static str,
},
#[error("endpoint contract at index {index} has an invalid custom rate limit label: {value:?}")]
InvalidRateLimitLabel {
#[doc = "The zero-based item index."]
index: usize,
#[doc = "The offending value."]
value: &'static str,
},
#[error("endpoint contract at index {index} has empty {mode} permissions")]
EmptyPermissions {
#[doc = "The zero-based item index."]
index: usize,
#[doc = "The configured mode."]
mode: &'static str,
},
#[error("public endpoint contract at index {index} must not require permissions")]
PublicEndpointRequiresPermissions {
#[doc = "The zero-based item index."]
index: usize,
},
#[error("private endpoint contract at index {index} must require permissions")]
PrivateEndpointWithoutPermissions {
#[doc = "The zero-based item index."]
index: usize,
},
#[error(
"duplicate endpoint contract {method} {path} at indexes {first_index} and {second_index}"
)]
DuplicateRoute {
first_index: usize,
second_index: usize,
method: EndpointMethod,
path: &'static str,
},
}
impl ClassifyError for EndpointContractValidationError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> Cow<'static, str> {
Cow::Borrowed(match self {
Self::EmptyPath { .. } => "endpoint_contract_empty_path",
Self::RelativePath { .. } => "endpoint_contract_relative_path",
Self::InvalidPath { .. } => "endpoint_contract_invalid_path",
Self::InvalidTemplate { .. } => "endpoint_contract_invalid_template",
Self::InvalidRateLimitLabel { .. } => "endpoint_contract_invalid_rate_limit_label",
Self::EmptyPermissions { .. } => "endpoint_contract_empty_permissions",
Self::PublicEndpointRequiresPermissions { .. } => {
"endpoint_contract_public_requires_permissions"
}
Self::PrivateEndpointWithoutPermissions { .. } => {
"endpoint_contract_private_without_permissions"
}
Self::DuplicateRoute { .. } => "endpoint_contract_duplicate_route",
})
}
}
fn validate_endpoint<P: Copy + 'static>(
index: usize,
endpoint: &EndpointContract<P>,
) -> Result<(), EndpointContractValidationError> {
let path = endpoint.path.as_str();
if path.is_empty() {
return Err(EndpointContractValidationError::EmptyPath { index });
}
if !path.starts_with('/') {
return Err(EndpointContractValidationError::RelativePath { index, path });
}
if !valid_contract_path(path)
|| matches!(endpoint.path, EndpointPathPattern::Exact(_)) && path.contains(['{', '}'])
{
return Err(EndpointContractValidationError::InvalidPath { index, path });
}
if matches!(endpoint.path, EndpointPathPattern::Template(_)) && !valid_template_path(path) {
return Err(EndpointContractValidationError::InvalidTemplate { index, path });
}
if let EndpointRateLimit::Custom(value) = endpoint.rate_limit
&& !valid_rate_limit_label(value)
{
return Err(EndpointContractValidationError::InvalidRateLimitLabel { index, value });
}
if let Some(mode) = endpoint.permissions.empty_requirement_mode() {
return Err(EndpointContractValidationError::EmptyPermissions { index, mode });
}
if endpoint.auth == EndpointAuth::Public && !endpoint.permissions.is_public() {
return Err(EndpointContractValidationError::PublicEndpointRequiresPermissions { index });
}
if endpoint.auth.requires_identity() && endpoint.permissions.is_public() {
return Err(EndpointContractValidationError::PrivateEndpointWithoutPermissions { index });
}
Ok(())
}
fn document_permissions<P: Copy + 'static>(
permissions: EndpointPermissions<P>,
permission_to_string: impl Fn(P) -> String,
) -> EndpointPermissionsDocument {
match permissions {
EndpointPermissions::Public => EndpointPermissionsDocument {
mode: "public".to_owned(),
values: Vec::new(),
},
EndpointPermissions::One(permission) => EndpointPermissionsDocument {
mode: "one".to_owned(),
values: vec![permission_to_string(permission)],
},
EndpointPermissions::Any(permissions) => EndpointPermissionsDocument {
mode: "any".to_owned(),
values: permissions
.iter()
.copied()
.map(permission_to_string)
.collect(),
},
EndpointPermissions::All(permissions) => EndpointPermissionsDocument {
mode: "all".to_owned(),
values: permissions
.iter()
.copied()
.map(permission_to_string)
.collect(),
},
}
}
fn increment(values: &mut BTreeMap<String, usize>, key: &str) {
*values.entry(key.to_owned()).or_default() += 1;
}
fn route_template_matches(template: &str, path: &str) -> bool {
let Some(template) = template.strip_prefix('/') else {
return false;
};
let Some(path) = path.strip_prefix('/') else {
return false;
};
let mut template_segments = template.split('/');
let mut path_segments = path.split('/');
loop {
match (template_segments.next(), path_segments.next()) {
(None, None) => return true,
(Some(template_segment), Some(path_segment))
if route_segment_matches(template_segment, path_segment) => {}
_ => return false,
}
}
}
fn route_segment_matches(template_segment: &str, path_segment: &str) -> bool {
if path_segment.is_empty() {
return false;
}
if let Some(parameter) = template_segment
.strip_prefix('{')
.and_then(|segment| segment.strip_suffix('}'))
{
return !parameter.is_empty()
&& parameter
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_');
}
template_segment == path_segment
}
fn valid_contract_path(path: &str) -> bool {
path.is_ascii()
&& !path.bytes().any(|byte| {
byte.is_ascii_control()
|| byte.is_ascii_whitespace()
|| matches!(byte, b'?' | b'#' | b'\\')
})
}
fn valid_template_path(path: &str) -> bool {
let Some(path) = path.strip_prefix('/') else {
return false;
};
path.split('/').all(|segment| {
!segment.is_empty()
&& if segment.starts_with('{') || segment.ends_with('}') {
route_segment_matches(segment, "value")
} else {
!segment.contains(['{', '}'])
}
})
}
fn valid_rate_limit_label(value: &str) -> bool {
!value.is_empty()
&& value.len() <= MAX_ENDPOINT_RATE_LIMIT_LABEL_LENGTH
&& value
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
}
#[cfg(test)]
mod tests {
use axum::http::Method;
use super::{
EndpointAudit, EndpointAuth, EndpointContract, EndpointContractRegistry,
EndpointContractSnapshot, EndpointMethod, EndpointPathPattern, EndpointPermissions,
EndpointRateLimit, EndpointRisk,
};
use crate::result::{ClassifyError, ErrorKind};
#[test]
fn endpoint_contract_matches_exact_and_template_paths() {
let exact: EndpointContract = EndpointContract::new(
EndpointMethod::Get,
EndpointPathPattern::Exact("/api/users"),
);
let template: EndpointContract = EndpointContract::new(
EndpointMethod::Delete,
EndpointPathPattern::Template("/api/users/{id}"),
);
assert!(exact.matches(&Method::GET, "/api/users"));
assert!(!exact.matches(&Method::GET, "/api/users/123"));
assert!(template.matches(&Method::DELETE, "/api/users/123"));
assert!(!template.matches(&Method::DELETE, "/api/users/123/sessions"));
}
#[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_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");
assert!(registry.find(&Method::POST, "/api/users").is_some());
}
#[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\"")
);
}
}