use actix_web::http::StatusCode;
use actix_web::{HttpRequest, HttpResponse};
use serde::Serialize;
use uuid::Uuid;
use crate::AxiamError;
use crate::client::AxiamClient;
use crate::middleware::AxiamUser;
#[derive(Debug)]
pub enum AuthzGuardError {
Unauthenticated(String),
Denied(String),
DeniedWithChallenge(String, String),
InvalidResource(String),
Unavailable(String),
Misconfigured(String),
}
impl AuthzGuardError {
pub fn unauthenticated(message: impl Into<String>) -> Self {
Self::Unauthenticated(message.into())
}
pub fn denied(message: impl Into<String>) -> Self {
Self::Denied(message.into())
}
pub fn denied_with_challenge(
message: impl Into<String>,
header_value: impl Into<String>,
) -> Self {
Self::DeniedWithChallenge(message.into(), header_value.into())
}
pub fn invalid_resource(message: impl Into<String>) -> Self {
Self::InvalidResource(message.into())
}
pub fn unavailable(message: impl Into<String>) -> Self {
Self::Unavailable(message.into())
}
pub fn misconfigured(message: impl Into<String>) -> Self {
Self::Misconfigured(message.into())
}
fn code(&self) -> &'static str {
match self {
Self::Unauthenticated(_) => "authentication_failed",
Self::Denied(_) | Self::DeniedWithChallenge(..) => "authorization_denied",
Self::InvalidResource(_) => "invalid_request",
Self::Unavailable(_) => "authz_unavailable",
Self::Misconfigured(_) => "internal_error",
}
}
fn message(&self) -> &str {
match self {
Self::Unauthenticated(m)
| Self::Denied(m)
| Self::DeniedWithChallenge(m, _)
| Self::InvalidResource(m)
| Self::Unavailable(m)
| Self::Misconfigured(m) => m,
}
}
}
impl std::fmt::Display for AuthzGuardError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", self.code(), self.message())
}
}
impl std::error::Error for AuthzGuardError {}
#[derive(Serialize)]
struct ErrorBody<'a> {
error: &'a str,
message: &'a str,
}
impl actix_web::ResponseError for AuthzGuardError {
fn status_code(&self) -> StatusCode {
match self {
Self::Unauthenticated(_) => StatusCode::UNAUTHORIZED,
Self::Denied(_) | Self::DeniedWithChallenge(..) => StatusCode::FORBIDDEN,
Self::InvalidResource(_) => StatusCode::BAD_REQUEST,
Self::Unavailable(_) => StatusCode::SERVICE_UNAVAILABLE,
Self::Misconfigured(_) => StatusCode::INTERNAL_SERVER_ERROR,
}
}
fn error_response(&self) -> HttpResponse {
let mut builder = HttpResponse::build(self.status_code());
if let Self::DeniedWithChallenge(_, header) = self {
builder.insert_header((actix_web::http::header::WWW_AUTHENTICATE, header.as_str()));
}
builder.json(ErrorBody {
error: self.code(),
message: self.message(),
})
}
}
pub fn resource_from_path(req: &HttpRequest, param: &str) -> Result<Uuid, AuthzGuardError> {
match req.match_info().get(param) {
Some(raw) => Uuid::parse_str(raw).map_err(|_| {
AuthzGuardError::invalid_resource(format!(
"path parameter '{param}' is not a valid resource UUID"
))
}),
None => Err(AuthzGuardError::invalid_resource(format!(
"missing path parameter '{param}'"
))),
}
}
pub fn resource_from_static(literal: &str) -> Result<Uuid, AuthzGuardError> {
Uuid::parse_str(literal).map_err(|_| {
AuthzGuardError::invalid_resource(format!(
"static resource_id '{literal}' is not a valid UUID"
))
})
}
pub fn require_role_check(user: &AxiamUser, required: &[&str]) -> Result<(), AuthzGuardError> {
let granted = user
.roles
.iter()
.any(|held| required.iter().any(|want| held == want));
if granted {
Ok(())
} else {
Err(AuthzGuardError::denied(
"caller does not hold any of the required roles".to_string(),
))
}
}
#[derive(Clone)]
pub struct UmaChallenger {
realm: String,
as_uri: String,
pat: crate::sensitive::Sensitive<String>,
}
impl UmaChallenger {
pub fn new(
realm: impl Into<String>,
as_uri: impl Into<String>,
pat: crate::sensitive::Sensitive<String>,
) -> Self {
Self {
realm: realm.into(),
as_uri: as_uri.into(),
pat,
}
}
}
impl std::fmt::Debug for UmaChallenger {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("UmaChallenger")
.field("realm", &self.realm)
.field("as_uri", &self.as_uri)
.field("pat", &self.pat)
.finish()
}
}
#[derive(Debug, Clone)]
pub struct RequireAccess {
action: String,
scope: Option<String>,
challenger: Option<UmaChallenger>,
mcp: Option<crate::middleware::mcp::McpChallenges>,
}
impl RequireAccess {
pub fn new(action: impl Into<String>) -> Self {
Self {
action: action.into(),
scope: None,
challenger: None,
mcp: None,
}
}
pub fn with_uma_challenge(mut self, challenger: UmaChallenger) -> Self {
self.challenger = Some(challenger);
self
}
#[must_use]
pub fn with_resource_metadata_url(mut self, verifier: &crate::token::JwksVerifier) -> Self {
self.mcp = verifier.mcp_challenges().cloned();
self
}
pub fn scope(mut self, scope: impl Into<String>) -> Self {
self.scope = Some(scope.into());
self
}
pub async fn check(
&self,
client: &AxiamClient,
user: &AxiamUser,
resource_id: Uuid,
) -> Result<(), AuthzGuardError> {
let outcome = client
.check_access_as(
user.user_id,
&self.action,
resource_id,
self.scope.as_deref(),
)
.await;
match outcome {
Ok(decision) if decision.allowed => Ok(()),
Ok(decision) => Err(self
.deny(client, resource_id, decision.reason_code.as_deref())
.await),
Err(AxiamError::Authz { .. }) => Err(self.deny(client, resource_id, None).await),
Err(AxiamError::Auth { .. }) => Err(AuthzGuardError::unauthenticated(
"authentication rejected by the authorization service".to_string(),
)),
Err(AxiamError::Network { .. }) => Err(AuthzGuardError::unavailable(
"authorization service unavailable".to_string(),
)),
}
}
async fn deny(
&self,
client: &AxiamClient,
resource_id: Uuid,
reason_code: Option<&str>,
) -> AuthzGuardError {
let message = format!("access denied for action '{}'", self.action);
if let Some(challenger) = self.challenger.as_ref() {
let permission = crate::uma::RequestedPermission {
resource_id,
resource_scopes: vec![self.action.clone()],
};
if let Ok(ticket) = client
.uma_request_ticket(&challenger.pat, std::slice::from_ref(&permission))
.await
{
return AuthzGuardError::denied_with_challenge(
message,
crate::uma::uma_challenge_header(
&challenger.realm,
&challenger.as_uri,
&ticket,
),
);
}
}
if let Some(header) = self.mcp_challenge(reason_code) {
return AuthzGuardError::denied_with_challenge(message, header);
}
AuthzGuardError::denied(message)
}
fn mcp_challenge(&self, reason_code: Option<&str>) -> Option<String> {
let mcp = self.mcp.as_ref()?;
let scope = self.scope.as_deref()?;
if reason_code != Some(crate::rest::authz::reason_code::NO_GRANT) {
return None;
}
mcp.insufficient_scope_challenge(scope).ok()
}
}
#[cfg(test)]
mod tests {
use super::*;
use actix_web::ResponseError;
use actix_web::body::to_bytes;
fn user_with_roles(roles: &[&str]) -> AxiamUser {
AxiamUser {
user_id: Uuid::new_v4(),
tenant_id: Uuid::new_v4(),
roles: roles.iter().map(|s| s.to_string()).collect(),
}
}
#[test]
fn error_status_and_code_mapping_covers_every_variant() {
let cases = [
(
AuthzGuardError::unauthenticated("x"),
StatusCode::UNAUTHORIZED,
"authentication_failed",
),
(
AuthzGuardError::denied("x"),
StatusCode::FORBIDDEN,
"authorization_denied",
),
(
AuthzGuardError::invalid_resource("x"),
StatusCode::BAD_REQUEST,
"invalid_request",
),
(
AuthzGuardError::unavailable("x"),
StatusCode::SERVICE_UNAVAILABLE,
"authz_unavailable",
),
(
AuthzGuardError::misconfigured("x"),
StatusCode::INTERNAL_SERVER_ERROR,
"internal_error",
),
];
for (err, status, code) in cases {
assert_eq!(err.status_code(), status);
assert_eq!(err.code(), code);
assert_eq!(err.message(), "x");
assert_eq!(err.to_string(), format!("{code}: x"));
}
}
#[tokio::test]
async fn error_response_emits_standardized_json_body() {
let err = AuthzGuardError::denied("nope");
let resp = err.error_response();
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
let bytes = to_bytes(resp.into_body()).await.expect("readable body");
let body: serde_json::Value = serde_json::from_slice(&bytes).expect("valid JSON");
assert_eq!(body["error"], "authorization_denied");
assert_eq!(body["message"], "nope");
}
#[test]
fn resource_from_path_rejects_a_missing_path_parameter() {
let req = actix_web::test::TestRequest::default().to_http_request();
let err = resource_from_path(&req, "id").expect_err("missing path parameter must fail");
assert_eq!(err.status_code(), StatusCode::BAD_REQUEST);
}
#[test]
fn resource_from_static_parses_and_rejects() {
let id = Uuid::new_v4();
assert_eq!(resource_from_static(&id.to_string()).unwrap(), id);
let err = resource_from_static("not-a-uuid").expect_err("must reject non-UUID");
assert_eq!(err.status_code(), StatusCode::BAD_REQUEST);
}
#[test]
fn require_role_check_allows_when_one_role_matches() {
let user = user_with_roles(&["editor", "admin"]);
assert!(require_role_check(&user, &["admin", "superadmin"]).is_ok());
}
#[test]
fn require_role_check_denies_when_no_role_matches() {
let user = user_with_roles(&["viewer"]);
let err = require_role_check(&user, &["admin"]).expect_err("must deny");
assert_eq!(err.status_code(), StatusCode::FORBIDDEN);
}
#[test]
fn require_access_builder_records_action_and_scope() {
let guard = RequireAccess::new("read").scope("confidential");
assert_eq!(guard.action, "read");
assert_eq!(guard.scope.as_deref(), Some("confidential"));
}
}