feat: complete Epic 1 production foundation
This commit is contained in:
1 parent
767428436d
commit
182bde8ac0
298 files changed
+35711
-5291
No files matched your search
@@ -1,7 +1,10 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::{
|
||||
http::{HeaderMap, StatusCode, header::AUTHORIZATION},
|
||||
http::{
|
||||
HeaderMap, StatusCode,
|
||||
header::{AUTHORIZATION, ORIGIN},
|
||||
},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
|
||||
@@ -43,11 +46,14 @@ pub(super) async fn require_machine_access(
|
||||
headers: &HeaderMap,
|
||||
required_scope: PlatformApiKeyScope,
|
||||
) -> Result<VerifiedMachineCredential, MachineAccessError> {
|
||||
let secret =
|
||||
bearer_token(headers).ok_or(MachineAccessError::Denied(StatusCode::UNAUTHORIZED))?;
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -60,7 +66,10 @@ pub(super) async fn require_approval_access(
|
||||
headers: &HeaderMap,
|
||||
required_scope: PlatformApiKeyScope,
|
||||
) -> Result<crank_registry::PlatformApiKeyRecord, StatusCode> {
|
||||
let secret = bearer_token(headers).ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
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,
|
||||
@@ -75,10 +84,16 @@ pub(super) async fn require_approval_access(
|
||||
.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);
|
||||
}
|
||||
|
||||
@@ -92,13 +107,20 @@ pub(super) async fn require_approval_access(
|
||||
),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
.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 value = headers.get(AUTHORIZATION)?.to_str().ok()?;
|
||||
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;
|
||||
@@ -114,18 +136,6 @@ pub(super) fn credential_allows_security_level(
|
||||
security_level_rank(credential.max_security_level) >= security_level_rank(required_level)
|
||||
}
|
||||
|
||||
pub(super) fn serialize_security_level(level: OperationSecurityLevel) -> &'static str {
|
||||
match level {
|
||||
OperationSecurityLevel::Standard => "standard",
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn serialize_machine_access_mode(mode: crank_core::MachineAccessMode) -> &'static str {
|
||||
match mode {
|
||||
crank_core::MachineAccessMode::StaticAgentKey => "static_agent_key",
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn hash_access_secret(secret: &str) -> String {
|
||||
let digest = Sha256::digest(secret.as_bytes());
|
||||
URL_SAFE_NO_PAD.encode(digest)
|
||||
@@ -145,7 +155,10 @@ async fn resolve_machine_credential(
|
||||
.verify_bearer_token(&path.workspace_slug, &path.agent_slug, token)
|
||||
.await
|
||||
.map_err(|_| MachineAccessError::Unavailable)?
|
||||
.ok_or(MachineAccessError::Denied(StatusCode::UNAUTHORIZED))
|
||||
.ok_or_else(|| {
|
||||
record_machine_access_denial("unknown_or_inactive", None);
|
||||
MachineAccessError::Denied(StatusCode::UNAUTHORIZED)
|
||||
})
|
||||
}
|
||||
|
||||
async fn verify_static_agent_key(
|
||||
@@ -164,7 +177,13 @@ async fn verify_static_agent_key(
|
||||
)
|
||||
.instrument(read_span.clone())
|
||||
.await
|
||||
.map_err(|_| MachineAccessError::Unavailable);
|
||||
.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);
|
||||
@@ -189,7 +208,13 @@ async fn verify_static_agent_key(
|
||||
.touch_platform_api_key(&api_key.api_key.workspace_id, &api_key.api_key.id, &used_at)
|
||||
.instrument(touch_span.clone())
|
||||
.await
|
||||
.map_err(|_| MachineAccessError::Unavailable);
|
||||
.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);
|
||||
@@ -207,9 +232,46 @@ async fn verify_static_agent_key(
|
||||
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"
|
||||
);
|
||||
}
|
||||
|
||||
fn allows_scope(scopes: &[PlatformApiKeyScope], required_scope: PlatformApiKeyScope) -> bool {
|
||||
match required_scope {
|
||||
PlatformApiKeyScope::Read => scopes.iter().any(|scope| {
|
||||
@@ -249,8 +311,286 @@ fn approval_allows_scope(
|
||||
})
|
||||
}
|
||||
|
||||
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<Mutex<Vec<BTreeMap<String, String>>>>,
|
||||
}
|
||||
|
||||
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<String, String>,
|
||||
}
|
||||
|
||||
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:?}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user