use std::sync::Arc; use axum::{ http::{ HeaderMap, StatusCode, header::{AUTHORIZATION, ORIGIN}, }, response::{IntoResponse, Response}, }; use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; use crank_core::{OperationSecurityLevel, PlatformApiKeyScope}; use crank_trace::{DbOperation, ErrorCategory, StageOutcome, observe_db_query}; use sha2::{Digest, Sha256}; use time::OffsetDateTime; use tracing::Instrument; use crate::{ app::{AgentRoutePath, AppState}, auth::VerifiedMachineCredential, }; #[derive(Clone, Copy, Debug)] pub(super) enum MachineAccessError { Denied(StatusCode), Unavailable, } impl MachineAccessError { pub(super) fn is_denied(self) -> bool { matches!(self, Self::Denied(_)) } } impl IntoResponse for MachineAccessError { fn into_response(self) -> Response { match self { Self::Denied(status) => status.into_response(), Self::Unavailable => StatusCode::INTERNAL_SERVER_ERROR.into_response(), } } } pub(super) async fn require_machine_access( state: &Arc, path: &AgentRoutePath, headers: &HeaderMap, required_scope: PlatformApiKeyScope, ) -> Result { let secret = bearer_token(headers).ok_or_else(|| { record_machine_access_denial("missing_or_ambiguous_bearer", None); MachineAccessError::Denied(StatusCode::UNAUTHORIZED) })?; let credential = resolve_machine_credential(state, path, secret).await?; if !allows_scope(&credential.scopes, required_scope) { record_machine_access_denial("scope", credential.platform_api_key_id.as_ref()); return Err(MachineAccessError::Denied(StatusCode::FORBIDDEN)); } Ok(credential) } pub(super) async fn require_approval_access( state: &Arc, path: &AgentRoutePath, headers: &HeaderMap, required_scope: PlatformApiKeyScope, ) -> Result { let secret = bearer_token(headers).ok_or_else(|| { record_unknown_approval_access_denial("missing_or_ambiguous_bearer"); StatusCode::UNAUTHORIZED })?; let secret_hash = hash_access_secret(secret); let Some(api_key) = observe_db_query( DbOperation::MachineAccessRead, state .registry .get_approval_api_key_by_secret_for_agent_slug( &path.workspace_slug, &path.agent_slug, &secret_hash, ), ) .await .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)? else { record_unknown_approval_access_denial("unknown_or_inactive"); return Err(StatusCode::UNAUTHORIZED); }; if !approval_allows_scope(&api_key.api_key.scopes, required_scope) { record_approval_access_denial(&api_key, "scope"); return Err(StatusCode::FORBIDDEN); } if !approval_allows_origin(&api_key.api_key.allowed_origins, headers) { record_approval_access_denial(&api_key, "origin"); return Err(StatusCode::FORBIDDEN); } let used_at = OffsetDateTime::now_utc(); observe_db_query( DbOperation::MachineAccessTouch, state.registry.touch_platform_api_key( &api_key.api_key.workspace_id, &api_key.api_key.id, &used_at, ), ) .await .map_err(|error| match error { crank_registry::RegistryError::PlatformApiKeyInactive { .. } => StatusCode::UNAUTHORIZED, _ => StatusCode::INTERNAL_SERVER_ERROR, })?; Ok(api_key) } pub(super) fn bearer_token(headers: &HeaderMap) -> Option<&str> { let mut values = headers.get_all(AUTHORIZATION).iter(); let value = values.next()?.to_str().ok()?; if values.next().is_some() { return None; } let (scheme, token) = value.split_once(' ')?; if !scheme.eq_ignore_ascii_case("Bearer") || token.is_empty() { return None; } Some(token) } pub(super) fn credential_allows_security_level( credential: &VerifiedMachineCredential, required_level: OperationSecurityLevel, ) -> bool { security_level_rank(credential.max_security_level) >= security_level_rank(required_level) } pub(super) fn hash_access_secret(secret: &str) -> String { let digest = Sha256::digest(secret.as_bytes()); URL_SAFE_NO_PAD.encode(digest) } async fn resolve_machine_credential( state: &Arc, path: &AgentRoutePath, token: &str, ) -> Result { if let Some(credential) = verify_static_agent_key(state, path, token).await? { return Ok(credential); } state .credential_verifier .verify_bearer_token(&path.workspace_slug, &path.agent_slug, token) .await .map_err(|_| MachineAccessError::Unavailable)? .ok_or_else(|| { record_machine_access_denial("unknown_or_inactive", None); MachineAccessError::Denied(StatusCode::UNAUTHORIZED) }) } async fn verify_static_agent_key( state: &Arc, path: &AgentRoutePath, secret: &str, ) -> Result, MachineAccessError> { let secret_hash = hash_access_secret(secret); let read_span = DbOperation::MachineAccessRead.span(); let api_key_result = state .registry .get_platform_api_key_by_secret_for_agent_slug( &path.workspace_slug, &path.agent_slug, &secret_hash, ) .instrument(read_span.clone()) .await .map_err(|error| match error { crank_registry::RegistryError::PlatformApiKeyInactive { .. } => { record_machine_access_denial("unknown_or_inactive", None); MachineAccessError::Denied(StatusCode::UNAUTHORIZED) } _ => MachineAccessError::Unavailable, }); let api_key = match api_key_result { Ok(api_key) => { StageOutcome::Success.record(&read_span); drop(read_span); api_key } Err(status) => { StageOutcome::Error.record(&read_span); ErrorCategory::Database.record(&read_span); drop(read_span); return Err(status); } }; let Some(api_key) = api_key else { return Ok(None); }; let used_at = OffsetDateTime::now_utc(); let touch_span = DbOperation::MachineAccessTouch.span(); let touch_result = state .registry .touch_platform_api_key(&api_key.api_key.workspace_id, &api_key.api_key.id, &used_at) .instrument(touch_span.clone()) .await .map_err(|error| match error { crank_registry::RegistryError::PlatformApiKeyInactive { .. } => { record_machine_access_denial("unknown_or_inactive", None); MachineAccessError::Denied(StatusCode::UNAUTHORIZED) } _ => MachineAccessError::Unavailable, }); match touch_result { Ok(()) => { StageOutcome::Success.record(&touch_span); drop(touch_span); } Err(status) => { StageOutcome::Error.record(&touch_span); ErrorCategory::Database.record(&touch_span); drop(touch_span); return Err(status); } } Ok(Some(VerifiedMachineCredential { machine_access_mode: crank_core::MachineAccessMode::StaticAgentKey, max_security_level: crank_core::OperationSecurityLevel::Standard, scopes: api_key.api_key.scopes, platform_api_key_id: Some(api_key.api_key.id), })) } fn record_machine_access_denial( reason: &'static str, platform_api_key_id: Option<&crank_core::PlatformApiKeyId>, ) { let (request_id, trace_id) = crank_observability::current_request_correlation(); let credential_ref = platform_api_key_id .map(crank_core::PlatformApiKeyId::as_str) .unwrap_or("unknown"); tracing::warn!( target: "crank::audit", action = "credential.platform_api_key.access_denied", credential_type = "platform_api_key.mcp_client", credential_ref = credential_ref, outcome = "denied", reason = reason, request_id = request_id.as_deref().unwrap_or(""), trace_id = trace_id.as_deref().unwrap_or(""), "mcp platform key access denied" ); } fn record_unknown_approval_access_denial(reason: &'static str) { let (request_id, trace_id) = crank_observability::current_request_correlation(); tracing::warn!( target: "crank::audit", action = "credential.platform_api_key.access_denied", credential_type = "platform_api_key.approval", credential_ref = "unknown", outcome = "denied", reason = reason, request_id = request_id.as_deref().unwrap_or(""), trace_id = trace_id.as_deref().unwrap_or(""), "approval platform key access denied" ); } pub(super) fn allows_scope( scopes: &[PlatformApiKeyScope], required_scope: PlatformApiKeyScope, ) -> bool { match required_scope { PlatformApiKeyScope::Read => scopes.iter().any(|scope| { matches!( scope, PlatformApiKeyScope::Read | PlatformApiKeyScope::Write | PlatformApiKeyScope::Deploy ) }), PlatformApiKeyScope::Write => scopes.iter().any(|scope| { matches!( scope, PlatformApiKeyScope::Write | PlatformApiKeyScope::Deploy ) }), PlatformApiKeyScope::Deploy => scopes .iter() .any(|scope| matches!(scope, PlatformApiKeyScope::Deploy)), PlatformApiKeyScope::Approve | PlatformApiKeyScope::Deny | PlatformApiKeyScope::ReadPending => false, } } fn approval_allows_scope( scopes: &[PlatformApiKeyScope], required_scope: PlatformApiKeyScope, ) -> bool { scopes.iter().any(|scope| match required_scope { PlatformApiKeyScope::Approve => matches!(scope, PlatformApiKeyScope::Approve), PlatformApiKeyScope::Deny => matches!(scope, PlatformApiKeyScope::Deny), PlatformApiKeyScope::ReadPending => matches!(scope, PlatformApiKeyScope::ReadPending), PlatformApiKeyScope::Read | PlatformApiKeyScope::Write | PlatformApiKeyScope::Deploy => { false } }) } fn approval_allows_origin(allowed_origins: &[String], headers: &HeaderMap) -> bool { if allowed_origins.is_empty() { return true; } let mut origins = headers.get_all(ORIGIN).iter(); let Some(origin) = origins.next() else { return true; }; if origins.next().is_some() { return false; }; let Ok(origin) = origin.to_str() else { return false; }; allowed_origins .iter() .any(|allowed_origin| allowed_origin == origin) } fn record_approval_access_denial( api_key: &crank_registry::PlatformApiKeyRecord, reason: &'static str, ) { let (request_id, trace_id) = crank_observability::current_request_correlation(); let agent_id = api_key .api_key .agent_id .as_ref() .map(|id| id.as_str()) .unwrap_or(""); tracing::warn!( target: "crank::audit", action = "credential.platform_api_key.access_denied", credential_type = "platform_api_key.approval", credential_ref = %api_key.api_key.id, workspace_id = %api_key.api_key.workspace_id, agent_id = agent_id, outcome = "denied", reason = reason, request_id = request_id.as_deref().unwrap_or(""), trace_id = trace_id.as_deref().unwrap_or(""), "approval platform key access denied" ); } fn security_level_rank(level: OperationSecurityLevel) -> u8 { match level { OperationSecurityLevel::Standard => 0, } } #[cfg(test)] mod tests { use std::{ collections::BTreeMap, sync::{Arc, Mutex}, }; use axum::http::{ HeaderMap, HeaderValue, header::{AUTHORIZATION, ORIGIN}, }; use crank_core::{ AgentId, PlatformApiKey, PlatformApiKeyId, PlatformApiKeyKind, PlatformApiKeyScope, PlatformApiKeyStatus, WorkspaceId, }; use crank_registry::PlatformApiKeyRecord; use time::OffsetDateTime; use tracing::{ Event, Id, Metadata, Subscriber, field::{Field, Visit}, span::{Attributes, Record}, }; use super::{ approval_allows_origin, bearer_token, record_approval_access_denial, record_machine_access_denial, }; #[test] fn approval_origin_policy_allows_non_browser_clients_without_origin() { let allowed_origins = vec!["https://allowed.example.test".to_owned()]; let headers = HeaderMap::new(); assert!(approval_allows_origin(&allowed_origins, &headers)); } #[test] fn approval_origin_policy_rejects_ambiguous_or_malformed_origin() { let allowed_origins = vec!["https://allowed.example.test".to_owned()]; let mut duplicate = HeaderMap::new(); duplicate.append( ORIGIN, HeaderValue::from_static("https://allowed.example.test"), ); duplicate.append( ORIGIN, HeaderValue::from_static("https://evil.example.test"), ); assert!(!approval_allows_origin(&allowed_origins, &duplicate)); let mut malformed = HeaderMap::new(); malformed.insert(ORIGIN, HeaderValue::from_bytes(b"\xff").unwrap()); assert!(!approval_allows_origin(&allowed_origins, &malformed)); } #[test] fn bearer_token_rejects_duplicate_authorization_headers() { let mut headers = HeaderMap::new(); headers.append(AUTHORIZATION, HeaderValue::from_static("Bearer first")); headers.append(AUTHORIZATION, HeaderValue::from_static("Bearer second")); assert_eq!(bearer_token(&headers), None); } #[tokio::test] async fn machine_access_denial_audit_uses_known_key_id_only_when_resolved() { let events = Arc::new(Mutex::new(Vec::new())); let subscriber = CapturingSubscriber { events: Arc::clone(&events), }; let dispatch = tracing::Dispatch::new(subscriber); let _guard = tracing::dispatcher::set_default(&dispatch); let key_id = PlatformApiKeyId::new("pk_mcp_scope_audit"); crank_observability::with_request_correlation( "req_mcp_scope_audit".to_owned(), "0af7651916cd43dd8448eb211c80319c".to_owned(), async { record_machine_access_denial("scope", Some(&key_id)); record_machine_access_denial("unknown_or_inactive", None); }, ) .await; let events = events.lock().unwrap(); assert_eq!(events.len(), 2); assert_eq!( events[0].get("credential_ref").map(String::as_str), Some("pk_mcp_scope_audit") ); assert_eq!(events[0].get("reason").map(String::as_str), Some("scope")); assert_eq!( events[1].get("credential_ref").map(String::as_str), Some("unknown") ); assert_eq!( events[1].get("reason").map(String::as_str), Some("unknown_or_inactive") ); for event in events.iter() { assert_eq!( event.get("credential_type").map(String::as_str), Some("platform_api_key.mcp_client") ); assert_eq!(event.get("outcome").map(String::as_str), Some("denied")); assert_eq!( event.get("request_id").map(String::as_str), Some("req_mcp_scope_audit") ); assert_eq!( event.get("trace_id").map(String::as_str), Some("0af7651916cd43dd8448eb211c80319c") ); } } #[tokio::test] async fn known_approval_access_denial_emits_bounded_audit_event() { let events = Arc::new(Mutex::new(Vec::new())); let subscriber = CapturingSubscriber { events: Arc::clone(&events), }; let dispatch = tracing::Dispatch::new(subscriber); let _guard = tracing::dispatcher::set_default(&dispatch); let record = PlatformApiKeyRecord { api_key: PlatformApiKey { id: PlatformApiKeyId::new("pk_approval_audit"), workspace_id: WorkspaceId::new("ws_audit"), agent_id: Some(AgentId::new("agent_audit")), key_kind: PlatformApiKeyKind::Approval, name: "approval-audit".to_owned(), prefix: "crk_appr_audit".to_owned(), scopes: vec![PlatformApiKeyScope::ReadPending], status: PlatformApiKeyStatus::Active, created_at: OffsetDateTime::now_utc(), last_used_at: None, expires_at: None, allowed_origins: vec!["https://allowed.example.test".to_owned()], }, }; crank_observability::with_request_correlation( "req_approval_audit".to_owned(), "0af7651916cd43dd8448eb211c80319c".to_owned(), async { record_approval_access_denial(&record, "origin"); }, ) .await; let events = events.lock().unwrap(); assert_eq!(events.len(), 1); let event = &events[0]; assert_eq!( event.get("action").map(String::as_str), Some("credential.platform_api_key.access_denied") ); assert_eq!( event.get("credential_type").map(String::as_str), Some("platform_api_key.approval") ); assert_eq!( event.get("credential_ref").map(String::as_str), Some("pk_approval_audit") ); assert_eq!(event.get("outcome").map(String::as_str), Some("denied")); assert_eq!(event.get("reason").map(String::as_str), Some("origin")); assert_eq!( event.get("request_id").map(String::as_str), Some("req_approval_audit") ); assert_eq!( event.get("trace_id").map(String::as_str), Some("0af7651916cd43dd8448eb211c80319c") ); let serialized = format!("{event:?}"); assert!(!serialized.contains("secret")); assert!(!serialized.contains("allowed.example.test")); } struct CapturingSubscriber { events: Arc>>>, } impl Subscriber for CapturingSubscriber { fn enabled(&self, metadata: &Metadata<'_>) -> bool { metadata.target() == "crank::audit" } fn new_span(&self, _span: &Attributes<'_>) -> Id { Id::from_u64(1) } fn record(&self, _span: &Id, _values: &Record<'_>) {} fn record_follows_from(&self, _span: &Id, _follows: &Id) {} fn event(&self, event: &Event<'_>) { if event.metadata().target() != "crank::audit" { return; } let mut visitor = FieldCaptureVisitor::default(); event.record(&mut visitor); self.events.lock().unwrap().push(visitor.fields); } fn enter(&self, _span: &Id) {} fn exit(&self, _span: &Id) {} } #[derive(Default)] struct FieldCaptureVisitor { fields: BTreeMap, } impl Visit for FieldCaptureVisitor { fn record_str(&mut self, field: &Field, value: &str) { self.fields .insert(field.name().to_owned(), value.to_owned()); } fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) { self.fields .insert(field.name().to_owned(), format!("{value:?}")); } } }