use std::fmt;
use axum::http::Method;
use thiserror::Error;
use crate::result::{ClassifyError, ErrorKind};
#[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> {
match method.as_str() {
"DELETE" => Ok(Self::Delete),
"GET" => Ok(Self::Get),
"HEAD" => Ok(Self::Head),
"OPTIONS" => Ok(Self::Options),
"PATCH" => Ok(Self::Patch),
"POST" => Ok(Self::Post),
"PUT" => Ok(Self::Put),
_ => 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) -> crate::result::ErrorCode {
crate::result::ErrorCode::internal("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))
}
}
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,
}
}
}
pub(super) 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
}