use std::net::IpAddr;
use std::sync::{Arc, OnceLock};
use crate::rt::Instant;
use chrono::Utc;
use futures::FutureExt;
use plexus_auth_core::{
AuditDecision, AuditDenyReason, AuditRecord, AuditRecordKind, AuditSink, AuthContext,
MethodPath, RoleName, Scope, ScopeRegistry, SessionId, UserId,
};
use uuid::Uuid;
use super::plexus::{AuthzDenyReason, PlexusError};
use super::schema::MethodSchema;
#[derive(Debug, Clone, Default)]
pub(crate) struct MethodGateInfo {
pub(crate) public: bool,
pub(crate) scopes: Vec<Scope>,
pub(crate) grant: Option<String>,
pub(crate) target: Option<String>,
pub(crate) everywhere: bool,
pub(crate) door: bool,
}
impl MethodGateInfo {
pub(crate) fn from_schema(schema: &MethodSchema) -> Self {
Self {
public: schema.public,
scopes: schema
.requires_credential
.as_ref()
.map(|rc| rc.scopes.clone())
.unwrap_or_default(),
grant: schema.grant.clone(),
target: schema.target.clone(),
everywhere: schema.everywhere,
door: super::grant_gate::door_shaped(schema.everywhere, schema.target.as_deref(), false),
}
}
}
pub(crate) fn empty_registry() -> &'static ScopeRegistry {
static EMPTY: OnceLock<ScopeRegistry> = OnceLock::new();
EMPTY.get_or_init(ScopeRegistry::default)
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn enforce(
registry: &ScopeRegistry,
default_deny: bool,
sink: &Arc<dyn AuditSink>,
full_path: &str,
schema_info: Option<&MethodGateInfo>,
auth: Option<&AuthContext>,
client_ip: Option<IpAddr>,
) -> Result<(), PlexusError> {
decide(registry, default_deny, Some(sink), full_path, schema_info, auth, client_ip).await
}
pub(crate) async fn answers(
registry: &ScopeRegistry,
default_deny: bool,
full_path: &str,
schema_info: Option<&MethodGateInfo>,
auth: Option<&AuthContext>,
) -> bool {
decide(registry, default_deny, None, full_path, schema_info, auth, None).await.is_ok()
}
#[allow(clippy::too_many_arguments)]
async fn decide(
registry: &ScopeRegistry,
default_deny: bool,
sink: Option<&Arc<dyn AuditSink>>,
full_path: &str,
schema_info: Option<&MethodGateInfo>,
auth: Option<&AuthContext>,
client_ip: Option<IpAddr>,
) -> Result<(), PlexusError> {
let started = Instant::now();
let mpath = match MethodPath::try_new(full_path) {
Ok(p) => p,
Err(_) => {
if default_deny {
tracing::error!(
target: "plexus::audit",
method = full_path,
"scope gate: method name fails MethodPath grammar under default_deny — \
denying (fail closed); no audit record can be built for it"
);
return Err(PlexusError::Forbidden {
reason: AuthzDenyReason::MissingScope {
scope: Scope::new(full_path),
},
});
}
return Ok(());
}
};
let schema_public = schema_info.map(|i| i.public).unwrap_or(false);
if schema_public || registry.is_public(&mpath) {
emit(sink, mpath, auth, &[], AuditDecision::Allow, started, client_ip).await;
return Ok(());
}
let implicit = vec![Scope::new(mpath.as_str())];
let registry_resolved = registry.required_scopes_for(&mpath);
let overlay = if registry_resolved != implicit {
Some(registry_resolved)
} else {
None
};
let schema_scopes = schema_info
.map(|i| i.scopes.clone())
.filter(|s| !s.is_empty());
let required: Vec<Scope> = match (overlay, schema_scopes) {
(Some(overlay), _) => overlay,
(None, Some(scopes)) => scopes,
(None, None) => {
if default_deny {
implicit
} else {
return Ok(());
}
}
};
let authenticated = auth.map(|a| a.is_authenticated()).unwrap_or(false);
if !authenticated {
emit(
sink,
mpath,
auth,
&required,
AuditDecision::Deny {
reason: AuditDenyReason::Unauthenticated,
},
started,
client_ip,
)
.await;
return Err(PlexusError::Unauthenticated(format!(
"method '{}' requires authentication",
full_path
)));
}
let auth_ctx = auth.expect("authenticated implies Some(auth)");
let roles: Vec<RoleName> = auth_ctx.roles.iter().map(RoleName::new).collect();
let held = registry.effective_scopes(&roles);
let unmet = required
.iter()
.find(|req| !held.iter().any(|h| h.matches(req)));
match unmet {
Some(scope) => {
let scope = scope.clone();
emit(
sink,
mpath,
auth,
&required,
AuditDecision::Deny {
reason: AuditDenyReason::MissingScope,
},
started,
client_ip,
)
.await;
Err(PlexusError::Forbidden {
reason: AuthzDenyReason::MissingScope { scope },
})
}
None => {
emit(sink, mpath, auth, &required, AuditDecision::Allow, started, client_ip).await;
Ok(())
}
}
}
async fn emit(
sink: Option<&Arc<dyn AuditSink>>,
method: MethodPath,
auth: Option<&AuthContext>,
required: &[Scope],
decision: AuditDecision,
started: Instant,
client_ip: Option<IpAddr>,
) {
let Some(sink) = sink else { return };
let (originator, session_id) = match auth {
Some(a) if a.is_authenticated() => (
Some(UserId::new(a.user_id.clone())),
if a.session_id.is_empty() {
None
} else {
Some(SessionId::new(a.session_id.clone()))
},
),
_ => (None, None),
};
let roles: Vec<RoleName> = auth
.map(|a| a.roles.iter().map(RoleName::new).collect())
.unwrap_or_default();
let correlation_id = Uuid::new_v4();
let record = AuditRecord {
timestamp: Utc::now(),
kind: AuditRecordKind::ScopeCheck,
originator,
session_id,
invocation_chain: Vec::new(),
roles,
method,
scope_required: required.to_vec(),
decision,
latency_us: started.elapsed().as_micros() as u64,
origin: None,
client_ip,
correlation_id,
policy_name: None,
derivation: None,
caller_ns: None,
};
if let Err(panic) = std::panic::AssertUnwindSafe(sink.write(record))
.catch_unwind()
.await
{
tracing::error!(
target: "plexus::audit",
correlation_id = %correlation_id,
"audit sink panicked during ScopeCheck write; dispatch proceeds: {:?}",
panic
);
}
}