#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AuthFailureKind {
MissingCredential,
InvalidToken,
InvalidApiKey,
EmptyPrincipal,
InsufficientScope,
}
impl AuthFailureKind {
pub fn reason(self) -> &'static str {
match self {
Self::MissingCredential => "MISSING_CREDENTIAL",
Self::InvalidToken => "INVALID_TOKEN",
Self::InvalidApiKey => "INVALID_API_KEY",
Self::EmptyPrincipal => "EMPTY_PRINCIPAL",
Self::InsufficientScope => "INSUFFICIENT_SCOPE",
}
}
pub fn bearer_rfc6750_code(self) -> Option<&'static str> {
match self {
Self::InvalidToken | Self::EmptyPrincipal => Some("invalid_token"),
Self::InsufficientScope => Some("insufficient_scope"),
Self::MissingCredential | Self::InvalidApiKey => None,
}
}
pub fn bearer_challenge(self) -> Option<String> {
match self {
Self::MissingCredential => Some(r#"Bearer realm="a2a""#.to_string()),
other => other
.bearer_rfc6750_code()
.map(|code| format!(r#"Bearer realm="a2a", error="{code}""#)),
}
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum MiddlewareError {
Unauthenticated(AuthFailureKind),
HttpChallenge(AuthFailureKind),
Forbidden(AuthFailureKind),
Internal(String),
}
impl MiddlewareError {
pub(crate) fn precedence(&self) -> u8 {
match self {
Self::Forbidden(_) => 3,
Self::HttpChallenge(_) => 2,
Self::Unauthenticated(_) => 1,
Self::Internal(_) => 0, }
}
pub fn http_status(&self) -> u16 {
match self {
Self::HttpChallenge(AuthFailureKind::InsufficientScope) => 403,
Self::Unauthenticated(_) | Self::HttpChallenge(_) => 401,
Self::Forbidden(_) => 403,
Self::Internal(_) => 500,
}
}
pub fn kind(&self) -> Option<AuthFailureKind> {
match self {
Self::Unauthenticated(k) | Self::HttpChallenge(k) | Self::Forbidden(k) => Some(*k),
Self::Internal(_) => None,
}
}
pub fn reason(&self) -> &'static str {
match self.kind() {
Some(kind) => kind.reason(),
None => "INTERNAL_ERROR",
}
}
pub fn message(&self) -> &'static str {
match self.kind() {
Some(AuthFailureKind::MissingCredential) => "authentication credentials are required",
Some(AuthFailureKind::InvalidToken) => "the bearer token is invalid",
Some(AuthFailureKind::InvalidApiKey) => "the API key is invalid",
Some(AuthFailureKind::EmptyPrincipal) => "the credential does not identify a principal",
Some(AuthFailureKind::InsufficientScope) => "the credential lacks a required scope",
None => "authentication failed due to an internal error",
}
}
fn status_name(&self) -> &'static str {
match self.http_status() {
401 => "UNAUTHENTICATED",
403 => "PERMISSION_DENIED",
_ => "INTERNAL",
}
}
fn error_info(&self) -> serde_json::Value {
use turul_a2a_types::wire::errors;
turul_a2a_types::ErrorInfo::new(self.reason(), errors::AUTH_ERROR_DOMAIN).into()
}
pub fn http_body(&self) -> serde_json::Value {
serde_json::json!({
"error": {
"code": self.http_status(),
"status": self.status_name(),
"message": self.message(),
"details": [self.error_info()],
}
})
}
pub fn jsonrpc_body(&self) -> serde_json::Value {
use turul_a2a_types::wire::errors;
let code = match self.http_status() {
401 => errors::JSONRPC_UNAUTHENTICATED,
403 => errors::JSONRPC_PERMISSION_DENIED,
_ => errors::JSONRPC_INTERNAL_ERROR,
};
serde_json::json!({
"jsonrpc": "2.0",
"id": serde_json::Value::Null,
"error": {
"code": code,
"message": self.message(),
"data": [self.error_info()],
}
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reasons_are_stable() {
assert_eq!(
AuthFailureKind::MissingCredential.reason(),
"MISSING_CREDENTIAL"
);
assert_eq!(AuthFailureKind::InvalidToken.reason(), "INVALID_TOKEN");
assert_eq!(AuthFailureKind::InvalidApiKey.reason(), "INVALID_API_KEY");
assert_eq!(AuthFailureKind::EmptyPrincipal.reason(), "EMPTY_PRINCIPAL");
assert_eq!(
AuthFailureKind::InsufficientScope.reason(),
"INSUFFICIENT_SCOPE"
);
assert_eq!(
MiddlewareError::Internal("db down".into()).reason(),
"INTERNAL_ERROR"
);
}
#[test]
fn error_bodies_are_byte_stable() {
let err = MiddlewareError::Unauthenticated(AuthFailureKind::MissingCredential);
assert_eq!(
err.http_body().to_string(),
r#"{"error":{"code":401,"details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","domain":"turul-a2a","reason":"MISSING_CREDENTIAL"}],"message":"authentication credentials are required","status":"UNAUTHENTICATED"}}"#
);
assert_eq!(
err.jsonrpc_body().to_string(),
r#"{"error":{"code":-32040,"data":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","domain":"turul-a2a","reason":"MISSING_CREDENTIAL"}],"message":"authentication credentials are required"},"id":null,"jsonrpc":"2.0"}"#
);
}
#[test]
fn bearer_rfc6750_mapping() {
assert_eq!(
AuthFailureKind::MissingCredential.bearer_rfc6750_code(),
None,
"RFC 6750 Section 3.1: no error code when credentials are absent"
);
assert_eq!(
AuthFailureKind::InvalidToken.bearer_rfc6750_code(),
Some("invalid_token")
);
assert_eq!(
AuthFailureKind::EmptyPrincipal.bearer_rfc6750_code(),
Some("invalid_token")
);
assert_eq!(
AuthFailureKind::InsufficientScope.bearer_rfc6750_code(),
Some("insufficient_scope")
);
assert_eq!(AuthFailureKind::InvalidApiKey.bearer_rfc6750_code(), None);
}
#[test]
fn bearer_challenge_values() {
assert_eq!(
AuthFailureKind::MissingCredential
.bearer_challenge()
.as_deref(),
Some(r#"Bearer realm="a2a""#)
);
assert_eq!(
AuthFailureKind::InvalidToken.bearer_challenge().as_deref(),
Some(r#"Bearer realm="a2a", error="invalid_token""#)
);
assert_eq!(
AuthFailureKind::EmptyPrincipal
.bearer_challenge()
.as_deref(),
Some(r#"Bearer realm="a2a", error="invalid_token""#)
);
assert_eq!(
AuthFailureKind::InsufficientScope
.bearer_challenge()
.as_deref(),
Some(r#"Bearer realm="a2a", error="insufficient_scope""#)
);
assert_eq!(AuthFailureKind::InvalidApiKey.bearer_challenge(), None);
}
#[test]
fn http_status_codes() {
assert_eq!(
MiddlewareError::Unauthenticated(AuthFailureKind::MissingCredential).http_status(),
401
);
assert_eq!(
MiddlewareError::HttpChallenge(AuthFailureKind::InvalidToken).http_status(),
401
);
assert_eq!(
MiddlewareError::Forbidden(AuthFailureKind::InsufficientScope).http_status(),
403
);
assert_eq!(MiddlewareError::Internal("x".into()).http_status(), 500);
}
#[test]
fn http_challenge_insufficient_scope_returns_403() {
assert_eq!(
MiddlewareError::HttpChallenge(AuthFailureKind::InsufficientScope).http_status(),
403
);
}
}