use std::collections::HashSet;
use actix_web::{HttpResponse, web};
use serde::Serialize;
use crate::AxiamError;
use crate::management::{FieldError, ValidationError};
pub const PROTECTED_RESOURCE_METADATA_PREFIX: &str = "/.well-known/oauth-protected-resource";
const LOOPBACK_HOSTS: [&str; 3] = ["127.0.0.1", "[::1]", "localhost"];
pub(crate) fn refuse(
operation: &'static str,
field: &str,
detail: impl std::fmt::Display,
) -> AxiamError {
let detail = detail.to_string();
let message = format!("{field}: {detail} (CONTRACT.md §28)");
AxiamError::network_with_source(
message.clone(),
Box::new(ValidationError {
status: 400,
operation,
message,
fields: vec![FieldError {
field: field.to_string(),
message: detail,
}],
}),
)
}
fn is_nqchar(c: char) -> bool {
let code = c as u32;
code == 0x21 || (0x23..=0x5b).contains(&code) || (0x5d..=0x7e).contains(&code)
}
fn is_nqschar(c: char) -> bool {
c == ' ' || is_nqchar(c)
}
fn is_all(value: &str, predicate: impl Fn(char) -> bool) -> bool {
value.chars().all(predicate)
}
struct ParsedUri<'a> {
scheme: &'a str,
authority: &'a str,
path: &'a str,
has_query: bool,
has_fragment: bool,
}
fn parse_absolute_uri(raw: &str) -> Option<ParsedUri<'_>> {
let scheme_end = raw.find("://")?;
let scheme = &raw[..scheme_end];
let mut chars = scheme.chars();
let first = chars.next()?;
if !first.is_ascii_alphabetic() {
return None;
}
if !chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-')) {
return None;
}
let rest = &raw[scheme_end + 3..];
let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
let authority = &rest[..authority_end];
if authority.is_empty() {
return None;
}
let after_authority = &rest[authority_end..];
let path_end = after_authority
.find(['?', '#'])
.unwrap_or(after_authority.len());
let path = &after_authority[..path_end];
let after_path = &after_authority[path_end..];
let (has_query, after_query) = match after_path.strip_prefix('?') {
Some(stripped) => {
let query_end = stripped.find('#').unwrap_or(stripped.len());
(true, &stripped[query_end..])
}
None => (false, after_path),
};
let has_fragment = after_query.starts_with('#');
Some(ParsedUri {
scheme,
authority,
path,
has_query,
has_fragment,
})
}
fn host_of(authority: &str) -> &str {
let hostport = match authority.rfind('@') {
Some(at) => &authority[at + 1..],
None => authority,
};
if let Some(rest) = hostport.strip_prefix('[') {
match rest.find(']') {
Some(close) => &hostport[..close + 2],
None => hostport,
}
} else {
match hostport.find(':') {
Some(colon) => &hostport[..colon],
None => hostport,
}
}
}
#[derive(Clone, Copy)]
struct UriPolicy {
allow_query: bool,
allow_fragment: bool,
}
const IDENTIFIER: UriPolicy = UriPolicy {
allow_query: false,
allow_fragment: false,
};
const LOCATOR: UriPolicy = UriPolicy {
allow_query: true,
allow_fragment: true,
};
fn require_absolute_uri<'a>(
operation: &'static str,
field: &str,
raw: &'a str,
policy: UriPolicy,
) -> Result<ParsedUri<'a>, AxiamError> {
if raw.is_empty() {
return Err(refuse(operation, field, "must be a non-empty absolute URI"));
}
let Some(parsed) = parse_absolute_uri(raw) else {
return Err(refuse(
operation,
field,
format!("must be an absolute URI with a scheme and an authority, not {raw:?}"),
));
};
if parsed.has_query && !policy.allow_query {
return Err(refuse(
operation,
field,
"must carry no query — §28.3 derives the metadata path from it",
));
}
if parsed.has_fragment && !policy.allow_fragment {
return Err(refuse(operation, field, "must carry no fragment"));
}
let scheme_lower = parsed.scheme.to_ascii_lowercase();
if scheme_lower == "https" {
return Ok(parsed);
}
if scheme_lower == "http" {
let host_lower = host_of(parsed.authority).to_ascii_lowercase();
if LOOPBACK_HOSTS.contains(&host_lower.as_str()) {
return Ok(parsed);
}
}
Err(refuse(
operation,
field,
format!(
"must use https — http is accepted only on 127.0.0.1, [::1] or localhost, and {raw:?} is neither"
),
))
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ProtectedResourceMetadataDocument {
pub resource: String,
pub authorization_servers: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub scopes_supported: Vec<String>,
pub bearer_methods_supported: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub resource_documentation: Option<String>,
}
#[derive(Debug, Clone)]
pub struct ProtectedResourceMetadataOptions {
pub resource: String,
pub authorization_servers: Vec<String>,
pub scopes_supported: Vec<String>,
pub bearer_methods_supported: Vec<String>,
pub resource_documentation: Option<String>,
}
impl ProtectedResourceMetadataOptions {
pub fn new(resource: impl Into<String>, authorization_servers: Vec<String>) -> Self {
Self {
resource: resource.into(),
authorization_servers,
scopes_supported: Vec::new(),
bearer_methods_supported: vec!["header".to_string()],
resource_documentation: None,
}
}
#[must_use]
pub fn scopes_supported(mut self, scopes_supported: Vec<String>) -> Self {
self.scopes_supported = scopes_supported;
self
}
#[must_use]
pub fn bearer_methods_supported(mut self, bearer_methods_supported: Vec<String>) -> Self {
self.bearer_methods_supported = bearer_methods_supported;
self
}
#[must_use]
pub fn resource_documentation(mut self, resource_documentation: impl Into<String>) -> Self {
self.resource_documentation = Some(resource_documentation.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProtectedResourceMetadata {
pub document: ProtectedResourceMetadataDocument,
pub metadata_path: String,
pub metadata_url: String,
}
pub fn protected_resource_metadata(
options: ProtectedResourceMetadataOptions,
) -> Result<ProtectedResourceMetadata, AxiamError> {
let op = "protected_resource_metadata";
let parsed = require_absolute_uri(op, "resource", &options.resource, IDENTIFIER)?;
let scheme = parsed.scheme.to_string();
let authority = parsed.authority.to_string();
let path = parsed.path.to_string();
if options.authorization_servers.is_empty() {
return Err(refuse(
op,
"authorization_servers",
"must name at least one authorization server — a document that names none answers none of the question the client asked",
));
}
let mut seen_servers: HashSet<&str> = HashSet::new();
for entry in &options.authorization_servers {
require_absolute_uri(op, "authorization_servers", entry, IDENTIFIER)?;
if !seen_servers.insert(entry.as_str()) {
return Err(refuse(
op,
"authorization_servers",
format!("duplicate entry {entry:?}"),
));
}
}
let mut seen_scopes: HashSet<&str> = HashSet::new();
for scope in &options.scopes_supported {
if scope.is_empty() || !is_all(scope, is_nqchar) {
return Err(refuse(
op,
"scopes_supported",
format!(
"{scope:?} is not a scope token — one or more NQCHAR (no space, no '\"', no '\\', no control character, no non-ASCII)"
),
));
}
if !seen_scopes.insert(scope.as_str()) {
return Err(refuse(
op,
"scopes_supported",
format!("duplicate scope {scope:?}"),
));
}
}
if options.bearer_methods_supported.len() != 1
|| options.bearer_methods_supported[0] != "header"
{
return Err(refuse(
op,
"bearer_methods_supported",
format!(
"must be exactly [\"header\"] in this contract version — §10's guard reads a bearer credential from the Authorization header alone, so {:?} would describe behaviour this SDK does not have",
options.bearer_methods_supported
),
));
}
if let Some(documentation) = &options.resource_documentation {
require_absolute_uri(op, "resource_documentation", documentation, LOCATOR)?;
}
let document = ProtectedResourceMetadataDocument {
resource: options.resource.clone(),
authorization_servers: options.authorization_servers,
scopes_supported: options.scopes_supported,
bearer_methods_supported: vec!["header".to_string()],
resource_documentation: options.resource_documentation,
};
let metadata_path = derive_metadata_path(&path);
let metadata_url = format!("{scheme}://{authority}{metadata_path}");
Ok(ProtectedResourceMetadata {
document,
metadata_path,
metadata_url,
})
}
fn derive_metadata_path(resource_path: &str) -> String {
if resource_path.is_empty() || resource_path == "/" {
PROTECTED_RESOURCE_METADATA_PREFIX.to_string()
} else {
format!("{PROTECTED_RESOURCE_METADATA_PREFIX}{resource_path}")
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BearerChallengeError {
InvalidRequest,
InvalidToken,
InsufficientScope,
}
impl BearerChallengeError {
pub fn as_str(self) -> &'static str {
match self {
Self::InvalidRequest => "invalid_request",
Self::InvalidToken => "invalid_token",
Self::InsufficientScope => "insufficient_scope",
}
}
}
impl std::fmt::Display for BearerChallengeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone)]
pub struct BearerChallengeOptions {
pub resource_metadata_url: String,
pub error: Option<BearerChallengeError>,
pub error_description: Option<String>,
pub scope: Option<String>,
}
impl BearerChallengeOptions {
pub fn new(resource_metadata_url: impl Into<String>) -> Self {
Self {
resource_metadata_url: resource_metadata_url.into(),
error: None,
error_description: None,
scope: None,
}
}
#[must_use]
pub fn error(mut self, error: BearerChallengeError) -> Self {
self.error = Some(error);
self
}
#[must_use]
pub fn error_description(mut self, error_description: impl Into<String>) -> Self {
self.error_description = Some(error_description.into());
self
}
#[must_use]
pub fn scope(mut self, scope: impl Into<String>) -> Self {
self.scope = Some(scope.into());
self
}
}
pub fn bearer_challenge(options: BearerChallengeOptions) -> Result<String, AxiamError> {
let op = "bearer_challenge";
let mut params: Vec<String> = Vec::new();
if let Some(error) = options.error {
params.push(format!("error=\"{}\"", error.as_str()));
}
if let Some(description) = &options.error_description {
if description.is_empty() || !is_all(description, is_nqschar) {
return Err(refuse(
op,
"error_description",
"must be one or more NQSCHAR (no '\"', no '\\', no control character, no non-ASCII) — a value needing an escape does not belong in a challenge",
));
}
params.push(format!("error_description=\"{description}\""));
}
if let Some(scope) = &options.scope {
if scope.is_empty() {
return Err(refuse(
op,
"scope",
"must be one or more scope tokens joined by a single space",
));
}
for token in scope.split(' ') {
if token.is_empty() || !is_all(token, is_nqchar) {
return Err(refuse(
op,
"scope",
format!(
"{scope:?} is not a space-joined list of scope tokens — no leading, trailing or doubled space, and no empty token"
),
));
}
}
params.push(format!("scope=\"{scope}\""));
}
let url = &options.resource_metadata_url;
require_absolute_uri(op, "resource_metadata", url, LOCATOR)?;
if !is_all(url, is_nqchar) {
return Err(refuse(
op,
"resource_metadata",
"must carry no '\"', no '\\', no space and no control character — a correctly encoded URL cannot, so one that does has not been encoded",
));
}
params.push(format!("resource_metadata=\"{url}\""));
Ok(format!("Bearer {}", params.join(", ")))
}
#[derive(Debug, Clone)]
pub(crate) struct McpChallenges {
resource_metadata_url: String,
no_credential: String,
invalid_token: String,
}
impl McpChallenges {
pub(crate) fn build(resource_metadata_url: &str) -> Result<Self, AxiamError> {
let no_credential = bearer_challenge(BearerChallengeOptions::new(resource_metadata_url))?;
let invalid_token = bearer_challenge(
BearerChallengeOptions::new(resource_metadata_url)
.error(BearerChallengeError::InvalidToken),
)?;
Ok(Self {
resource_metadata_url: resource_metadata_url.to_string(),
no_credential,
invalid_token,
})
}
pub(crate) fn no_credential(&self) -> &str {
&self.no_credential
}
pub(crate) fn invalid_token(&self) -> &str {
&self.invalid_token
}
pub(crate) fn insufficient_scope_challenge(&self, scope: &str) -> Result<String, AxiamError> {
bearer_challenge(
BearerChallengeOptions::new(self.resource_metadata_url.clone())
.error(BearerChallengeError::InsufficientScope)
.scope(scope),
)
}
}
pub fn serve_protected_resource_metadata(
metadata: &ProtectedResourceMetadata,
verifier: Option<&crate::token::JwksVerifier>,
) -> Result<impl actix_web::dev::HttpServiceFactory + use<>, AxiamError> {
let op = "serve_protected_resource_metadata";
if let Some(verifier) = verifier {
let configured_url = verifier.resource_metadata_url();
if configured_url != Some(metadata.metadata_url.as_str()) {
return Err(refuse(
op,
"resource_metadata_url",
format!(
"is {configured_url:?} but this document is published at {:?} — the challenge would point at a document that is not this resource server's",
metadata.metadata_url
),
));
}
let configured_audience = verifier.expected_audience();
if configured_audience != Some(metadata.document.resource.as_str()) {
return Err(refuse(
op,
"expected_audience",
format!(
"is {configured_audience:?} but this document announces {:?} — the document would announce one identifier while the guard checked `aud` against another, so every token the flow produced would be refused",
metadata.document.resource
),
));
}
}
let body = serde_json::to_string(&metadata.document)
.map_err(|e| AxiamError::network(format!("{op}: failed to serialize the document: {e}")))?;
Ok(
web::resource(metadata.metadata_path.clone()).route(web::get().to(move || {
let body = body.clone();
async move {
HttpResponse::Ok()
.content_type("application/json")
.insert_header(("Cache-Control", "public, max-age=3600"))
.insert_header(("Access-Control-Allow-Origin", "*"))
.body(body)
}
})),
)
}