diff --git a/crates/sendbox-cli/src/governance.rs b/crates/sendbox-cli/src/governance.rs index 78a99d1..4af2930 100644 --- a/crates/sendbox-cli/src/governance.rs +++ b/crates/sendbox-cli/src/governance.rs @@ -1,6 +1,6 @@ use std::collections::BTreeMap; use std::fs::{self, OpenOptions}; -use std::io::Write as _; +use std::io::{IsTerminal as _, Read as _, Write as _}; use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt}; use std::path::{Path, PathBuf}; use std::process::ExitCode; @@ -10,8 +10,8 @@ use clap::{Args, Subcommand, ValueEnum}; use sendbox_config::SandboxConfiguration; use sendbox_governance::{GovernanceProfile, RuntimeKind}; use sendbox_host::governance::{ - GovernanceCheckRequest, MANAGED_CONFIGURATION_PATH, SIGNATURES_FORMAT, check, - encode_signatures, verify_active, + FleetLoginRequest, GovernanceCheckRequest, MANAGED_CONFIGURATION_PATH, SIGNATURES_FORMAT, + check, encode_signatures, fleet_login, verify_active, }; use sendbox_security::provenance::{ DetachedSignature, SignedSubject, SigningKeyMaterial, SubjectKind, @@ -37,6 +37,9 @@ enum GovernanceCommand { Verify(VerifyArgs), /// Explain whether a project configuration fits the active profile. Check(CheckArgs), + /// Exchange an identity-provider token for a shared governance service + /// token and store it in the host secret store. + Login(LoginArgs), } #[derive(Debug, Args)] @@ -82,6 +85,24 @@ struct VerifyArgs { json: bool, } +#[derive(Debug, Args)] +struct LoginArgs { + #[arg(long, value_name = "PATH")] + governance_config: Option, + /// File holding the identity-provider token (for example an OIDC ID + /// token). Without it the token is read from stdin, or prompted for on a + /// terminal. + #[arg(long, value_name = "PATH")] + identity_token_file: Option, + /// Requested lifetime; the service caps it. + #[arg(long, value_name = "SECONDS")] + ttl_seconds: Option, + #[arg(long)] + description: Option, + #[arg(long, help = "Emit a deterministic JSON result")] + json: bool, +} + #[derive(Debug, Clone, Copy, ValueEnum)] enum CheckRuntime { Apple, @@ -148,6 +169,7 @@ pub(crate) fn execute(arguments: GovernanceArgs) -> ExitCode { GovernanceCommand::Sign(arguments) => (arguments.json, sign(&arguments)), GovernanceCommand::Verify(arguments) => (arguments.json, verify(&arguments)), GovernanceCommand::Check(arguments) => (arguments.json, check_configuration(&arguments)), + GovernanceCommand::Login(arguments) => (arguments.json, login(arguments)), }; match result { Ok(code) => code, @@ -336,6 +358,81 @@ fn sign(arguments: &SignArgs) -> CommandResult { Ok(ExitCode::SUCCESS) } +const MAX_IDENTITY_TOKEN_BYTES: u64 = 16 * 1024; + +fn read_identity_token(path: Option<&Path>) -> Result, (u8, String)> { + let mut text = Zeroizing::new(String::new()); + match path { + Some(path) => { + fs::File::open(path) + .and_then(|file| { + file.take(MAX_IDENTITY_TOKEN_BYTES + 1) + .read_to_string(&mut text) + }) + .map_err(|error| invalid(format!("read {}: {error}", path.display())))?; + } + None if !std::io::stdin().is_terminal() => { + std::io::stdin() + .take(MAX_IDENTITY_TOKEN_BYTES + 1) + .read_to_string(&mut text) + .map_err(|error| invalid(format!("read the identity token from stdin: {error}")))?; + } + None => { + text = Zeroizing::new( + rpassword::prompt_password("Identity token: ") + .map_err(|error| invalid(format!("read the identity token: {error}")))?, + ); + } + } + if text.len() as u64 > MAX_IDENTITY_TOKEN_BYTES { + return Err(invalid(format!( + "the identity token exceeds {MAX_IDENTITY_TOKEN_BYTES} bytes" + ))); + } + let trimmed = Zeroizing::new(text.trim().to_owned()); + if trimmed.is_empty() { + return Err(invalid("the identity token is empty")); + } + Ok(trimmed) +} + +fn login(arguments: LoginArgs) -> CommandResult { + let token = read_identity_token(arguments.identity_token_file.as_deref())?; + let identity_token = + sendbox_secrets::SecretValue::new(token.as_bytes().to_vec()).map_err(invalid)?; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|error| invalid(format!("start the async runtime: {error}")))?; + let report = runtime + .block_on(fleet_login(FleetLoginRequest { + managed_path: PathBuf::from(MANAGED_CONFIGURATION_PATH), + governance_config: arguments.governance_config, + identity_token, + ttl_seconds: arguments.ttl_seconds, + description: arguments.description, + })) + .map_err(governance)?; + if arguments.json { + print_json(&serde_json::json!({ + "schema_version": sendbox_core::CONFIG_SCHEMA_VERSION, + "ok": true, + "login": report, + })); + } else { + println!( + "logged in to {} ({}) as {}; token {} stored in host secret {} until {} (Unix seconds)", + report.url, + report.authority, + report.principal, + report.token_id, + report.secret, + report.expires_at_unix + ); + } + Ok(ExitCode::SUCCESS) +} + fn verify(arguments: &VerifyArgs) -> CommandResult { let active = verify_active( Path::new(MANAGED_CONFIGURATION_PATH), diff --git a/crates/sendbox-governance/src/api.rs b/crates/sendbox-governance/src/api.rs index ae5094d..0820d44 100644 --- a/crates/sendbox-governance/src/api.rs +++ b/crates/sendbox-governance/src/api.rs @@ -5,8 +5,8 @@ use serde::{Deserialize, Serialize}; use crate::{ - GovernanceBinding, PrincipalId, RevocationReason, SessionRef, digest::Sha256Digest, - exception::PolicyException, + GovernanceBinding, GovernanceError, PrincipalId, RevocationReason, ServiceId, SessionRef, + digest::Sha256Digest, exception::PolicyException, }; /// Media type of error responses (RFC 9457). @@ -95,3 +95,178 @@ pub struct RevokeGrantRequest { pub struct ExceptionList { pub exceptions: Vec, } + +/// `POST /v1/tokens` body: exchange an identity-provider login for a +/// service token that a host can store. Omitted fields take the service's +/// defaults. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct TokenRequest { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ttl_seconds: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub description: Option, +} + +/// `POST /v1/tokens` response. `token` is shown once and never stored by the +/// service; `Debug` redacts it. +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct IssuedToken { + pub id: String, + pub token: String, + pub principal: PrincipalId, + pub expires_at_unix: u64, +} + +impl std::fmt::Debug for IssuedToken { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("IssuedToken") + .field("id", &self.id) + .field("token", &"") + .field("principal", &self.principal) + .field("expires_at_unix", &self.expires_at_unix) + .finish() + } +} + +/// How a brokered request ended, as reported by the host. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ReportedOutcome { + /// The upstream response was relayed in full. + Succeeded, + /// The request was refused or failed before an uncertain upstream effect. + Failed, + /// The stream was cut after the request reached the upstream, so its + /// external effect cannot be confirmed. + Unknown, +} + +impl ReportedOutcome { + #[must_use] + pub const fn code(self) -> &'static str { + match self { + Self::Succeeded => "succeeded", + Self::Failed => "failed", + Self::Unknown => "unknown", + } + } +} + +const MAX_METHOD_BYTES: usize = 16; +const MAX_REASON_BYTES: usize = 64; +const MAX_REPORTED_PATH_BYTES: usize = 2048; + +/// `POST /v1/grants/{grant}:outcome` body: the redacted end of one brokered +/// stream. It never carries headers, query strings, or bodies. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RequestOutcomeReport { + pub service: ServiceId, + pub method: String, + /// Path without query; may be invalid when the host refused it. + pub path: String, + pub outcome: ReportedOutcome, + /// The host relay's reason code, such as `complete` or `grant_lapsed`. + pub reason: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub status: Option, + pub request_bytes: u64, + pub response_bytes: u64, + pub duration_ms: u64, +} + +impl RequestOutcomeReport { + pub fn validate(&self) -> Result<(), GovernanceError> { + let token = |value: &str, limit: usize, allowed: fn(u8) -> bool| { + !value.is_empty() && value.len() <= limit && value.bytes().all(allowed) + }; + if !token(&self.method, MAX_METHOD_BYTES, |byte| { + byte.is_ascii_uppercase() + }) { + return Err(GovernanceError::Encoding( + "outcome method must be 1-16 uppercase ASCII letters".to_owned(), + )); + } + if !token(&self.reason, MAX_REASON_BYTES, |byte| { + byte.is_ascii_lowercase() || byte == b'_' + }) { + return Err(GovernanceError::Encoding( + "outcome reason must be 1-64 lowercase ASCII letters or underscores".to_owned(), + )); + } + if self.path.len() > MAX_REPORTED_PATH_BYTES + || self.path.bytes().any(|byte| !byte.is_ascii_graphic()) + { + return Err(GovernanceError::Encoding( + "outcome path must be at most 2048 printable ASCII bytes".to_owned(), + )); + } + if self + .status + .is_some_and(|status| !(100..=599).contains(&status)) + { + return Err(GovernanceError::Encoding( + "outcome status must be an HTTP status code".to_owned(), + )); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn report() -> RequestOutcomeReport { + RequestOutcomeReport { + service: ServiceId::new("anthropic").unwrap(), + method: "POST".to_owned(), + path: "/v1/messages".to_owned(), + outcome: ReportedOutcome::Unknown, + reason: "aborted_uncertain".to_owned(), + status: Some(200), + request_bytes: 10, + response_bytes: 20, + duration_ms: 30, + } + } + + #[test] + fn outcome_reports_are_bounded_and_redacted() { + assert!(report().validate().is_ok()); + for broken in [ + RequestOutcomeReport { + method: "post".to_owned(), + ..report() + }, + RequestOutcomeReport { + reason: "Bad Reason".to_owned(), + ..report() + }, + RequestOutcomeReport { + path: "/v1/messages body".to_owned(), + ..report() + }, + RequestOutcomeReport { + status: Some(42), + ..report() + }, + ] { + assert!(broken.validate().is_err(), "{broken:?}"); + } + } + + #[test] + fn issued_tokens_never_print_their_secret() { + let issued = IssuedToken { + id: "ab".repeat(16), + token: "sbf_secret-value".to_owned(), + principal: PrincipalId::new("oidc:alice@example.com").unwrap(), + expires_at_unix: 1, + }; + assert!(!format!("{issued:?}").contains("secret-value")); + } +} diff --git a/crates/sendbox-host/src/governance/fleet.rs b/crates/sendbox-host/src/governance/fleet.rs index f0ea429..643ff2c 100644 --- a/crates/sendbox-host/src/governance/fleet.rs +++ b/crates/sendbox-host/src/governance/fleet.rs @@ -10,8 +10,8 @@ use std::time::Duration; use reqwest::{Method, StatusCode, Url, header}; use sendbox_governance::api::{ - CallerIdentity, ExceptionList, RevokeGrantRequest, SessionAdmission, SessionAdmissionRequest, - SessionEnd, SessionOutcome, + CallerIdentity, ExceptionList, IssuedToken, RequestOutcomeReport, RevokeGrantRequest, + SessionAdmission, SessionAdmissionRequest, SessionEnd, SessionOutcome, TokenRequest, }; use sendbox_governance::{ AuthorityFuture, CredentialGrant, Decision, DenyReason, GovernanceBinding, GovernanceError, @@ -259,6 +259,32 @@ impl FleetClient { } } +impl FleetClient { + /// Exchanges the identity-provider token this client was built with for a + /// service token. + pub(crate) async fn exchange(&self, request: &TokenRequest) -> Result { + self.call_required(Method::POST, "/v1/tokens", &[], Some(request)) + .await + } + + /// Reports how one brokered stream ended so the central audit can + /// correlate it with the authorization decision. + pub(crate) async fn report_outcome( + &self, + grant: &GrantId, + report: &RequestOutcomeReport, + ) -> Result<(), FleetError> { + self.call::( + Method::POST, + &format!("/v1/grants/{grant}:outcome"), + &[], + Some(report), + ) + .await + .map(drop) + } +} + /// The shared service as the session's grant authority. pub(crate) struct FleetGrantAuthority { client: std::sync::Arc, @@ -398,12 +424,12 @@ mod erased { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use std::collections::BTreeMap; use std::net::SocketAddr; use std::sync::{Arc, Mutex}; - use sendbox_governance::api::{CallerKind, SessionOutcome}; + use sendbox_governance::api::{CallerKind, IssuedToken, SessionOutcome}; use sendbox_governance::{ ExceptionId, ExceptionKind, ExceptionScope, ExceptionStatus, PrincipalId, ProfileRef, ServiceId, Sha256Digest, @@ -418,21 +444,21 @@ mod tests { }; use super::*; - const TOKEN: &str = "sbf_synthetic-test-token"; + pub(crate) const TOKEN: &str = "sbf_synthetic-test-token"; const ALICE: &str = "oidc:alice@example.com"; #[derive(Debug, Clone)] - struct Recorded { - method: String, - target: String, - authorization: Option, - body: Vec, + pub(crate) struct Recorded { + pub(crate) method: String, + pub(crate) target: String, + pub(crate) authorization: Option, + pub(crate) body: Vec, } - type Handler = dyn Fn(&Recorded) -> (u16, String) + Send + Sync; + pub(crate) type Handler = dyn Fn(&Recorded) -> (u16, String) + Send + Sync; /// A loopback HTTP/1.1 stand-in for the governance service. - async fn serve(handler: Arc) -> (SocketAddr, Arc>>) { + pub(crate) async fn serve(handler: Arc) -> (SocketAddr, Arc>>) { let listener = tokio::net::TcpListener::bind("127.0.0.1:0") .await .expect("bind"); @@ -515,6 +541,14 @@ mod tests { ) } + pub(crate) fn settings(address: SocketAddr) -> FleetSettings { + FleetSettings { + url: format!("http://{address}"), + token_secret: DEFAULT_FLEET_TOKEN_SECRET.to_owned(), + timeout_seconds: 5, + } + } + fn use_fleet(fixture: &Fixture, address: SocketAddr) { let mut operator = fixture.source.load().expect("operator"); operator.authority = "fleet.example.com".to_owned(); @@ -791,4 +825,151 @@ mod tests { .expect_err("mismatched admission"); assert!(error.detail.contains("different session or binding")); } + + /// A writable in-memory secret store. + struct MemoryStore(Mutex>>); + + impl MemoryStore { + fn metadata(name: &sendbox_secrets::SecretName) -> sendbox_secrets::SecretMetadata { + sendbox_secrets::SecretMetadata { + name: name.clone(), + created_at_unix_ms: 0, + updated_at_unix_ms: 0, + version: sendbox_secrets::RecordVersion::V1, + } + } + } + + impl SecretStore for MemoryStore { + fn store( + &self, + name: &sendbox_secrets::SecretName, + value: SecretValue, + ) -> Result { + let mut values = self.0.lock().unwrap(); + if values.contains_key(name.as_str()) { + return Err(sendbox_secrets::SecretStoreError::AlreadyExists( + name.clone(), + )); + } + values.insert(name.as_str().to_owned(), value.expose_secret().to_vec()); + Ok(Self::metadata(name)) + } + fn update( + &self, + name: &sendbox_secrets::SecretName, + value: SecretValue, + ) -> Result { + let mut values = self.0.lock().unwrap(); + let slot = values + .get_mut(name.as_str()) + .ok_or_else(|| sendbox_secrets::SecretStoreError::NotFound(name.clone()))?; + *slot = value.expose_secret().to_vec(); + Ok(Self::metadata(name)) + } + fn retrieve( + &self, + name: &sendbox_secrets::SecretName, + ) -> Result { + let values = self.0.lock().unwrap(); + let value = values + .get(name.as_str()) + .ok_or_else(|| sendbox_secrets::SecretStoreError::NotFound(name.clone()))?; + Ok(sendbox_secrets::Secret { + metadata: Self::metadata(name), + value: SecretValue::new(value.clone())?, + }) + } + fn delete( + &self, + _: &sendbox_secrets::SecretName, + ) -> Result<(), sendbox_secrets::SecretStoreError> { + Err(sendbox_secrets::SecretStoreError::AccessDenied) + } + fn list( + &self, + ) -> Result, sendbox_secrets::SecretStoreError> + { + Err(sendbox_secrets::SecretStoreError::AccessDenied) + } + fn exists( + &self, + name: &sendbox_secrets::SecretName, + ) -> Result { + Ok(self.0.lock().unwrap().contains_key(name.as_str())) + } + fn migrate( + &self, + _: &sendbox_secrets::SecretName, + ) -> Result { + Err(sendbox_secrets::SecretStoreError::AccessDenied) + } + } + + #[tokio::test] + async fn login_exchanges_the_identity_token_and_stores_the_service_token() { + if !protected_test_tree() { + return; + } + const ID_TOKEN: &str = "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJhbGljZSJ9.c2lnbmF0dXJl"; + let issued = std::sync::atomic::AtomicU8::new(0); + let handler: Arc = Arc::new(move |request: &Recorded| { + match (request.method.as_str(), request.target.as_str()) { + ("POST", "/v1/tokens") + if request.authorization.as_deref() == Some(&format!("Bearer {ID_TOKEN}")) => + { + let round = issued.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + ( + 201, + json(&IssuedToken { + id: "ab".repeat(16), + token: format!("sbf_issued-{round}"), + principal: PrincipalId::new(ALICE).unwrap(), + expires_at_unix: 99, + }), + ) + } + _ => ( + 401, + r#"{"detail":"bearer token was not accepted"}"#.to_owned(), + ), + } + }); + let (address, recorded) = serve(handler).await; + let fixture = fixture(&fleet_profile(), 1); + let store = Arc::new(MemoryStore(Mutex::new(BTreeMap::new()))); + let opener = { + let store = Arc::clone(&store); + move || -> Result, HostError> { Ok(store.clone()) } + }; + let request = || super::super::FleetLoginRequest { + managed_path: fixture.directory.path().join("absent-managed.yaml"), + governance_config: Some(fixture.source.path.clone()), + identity_token: SecretValue::try_from(ID_TOKEN).unwrap(), + ttl_seconds: Some(3_600), + description: Some("laptop".to_owned()), + }; + let error = super::super::fleet_login_with(request(), &opener) + .await + .expect_err("no fleet section"); + assert!(error.to_string().contains("no `fleet` section"), "{error}"); + + use_fleet(&fixture, address); + for round in 0..2 { + let report = super::super::fleet_login_with(request(), &opener) + .await + .expect("login"); + assert_eq!(report.principal, ALICE); + assert_eq!(report.secret, DEFAULT_FLEET_TOKEN_SECRET); + let stored = store.0.lock().unwrap()[DEFAULT_FLEET_TOKEN_SECRET].clone(); + assert_eq!(stored, format!("sbf_issued-{round}").into_bytes()); + assert!(!format!("{report:?}").contains("sbf_issued")); + } + let requests = recorded.lock().unwrap().clone(); + assert_eq!(requests.len(), 2); + assert_eq!( + requests[0].body, + br#"{"ttl_seconds":3600,"description":"laptop"}"# + ); + } } diff --git a/crates/sendbox-host/src/governance/mod.rs b/crates/sendbox-host/src/governance/mod.rs index 53f4842..a8d9c71 100644 --- a/crates/sendbox-host/src/governance/mod.rs +++ b/crates/sendbox-host/src/governance/mod.rs @@ -594,6 +594,82 @@ pub fn verify_active( })) } +/// Inputs for `sendbox governance login`. +pub struct FleetLoginRequest { + pub managed_path: PathBuf, + pub governance_config: Option, + /// The identity-provider token (for example an OIDC ID token) to exchange. + pub identity_token: sendbox_secrets::SecretValue, + pub ttl_seconds: Option, + pub description: Option, +} + +/// What `sendbox governance login` stored. +#[derive(Debug, Clone, Serialize)] +pub struct FleetLoginReport { + pub authority: String, + pub url: String, + pub principal: String, + pub token_id: String, + pub expires_at_unix: u64, + pub secret: String, +} + +/// Exchanges an identity-provider token with the configured shared +/// governance service and stores the returned service token in the host +/// secret store under the operator's `fleet.token_secret`. The service URL +/// comes only from the verified operator configuration. +pub async fn fleet_login(request: FleetLoginRequest) -> Result { + fleet_login_with(request, &crate::native_secret_store).await +} + +async fn fleet_login_with( + request: FleetLoginRequest, + open_secrets: SecretStoreOpener<'_>, +) -> Result { + let Some(ActiveGovernance { operator, .. }) = + verify_active(&request.managed_path, request.governance_config.as_deref())? + else { + return Err(HostError::Governance( + "no governance configuration is active; select one with --governance-config".to_owned(), + )); + }; + let settings = operator.fleet.as_ref().ok_or_else(|| { + HostError::Governance( + "the operator configuration has no `fleet` section; login applies only to a shared governance service" + .to_owned(), + ) + })?; + let client = fleet::FleetClient::new(settings, &request.identity_token)?; + let mut issued = client + .exchange(&sendbox_governance::api::TokenRequest { + ttl_seconds: request.ttl_seconds, + description: request.description, + }) + .await?; + let token = sendbox_secrets::SecretValue::new(std::mem::take(&mut issued.token).into_bytes())?; + fleet::FleetClient::new(settings, &token)?; + let name = SecretName::new(settings.token_secret.clone())?; + let store = open_secrets()?; + let exists = store + .exists(&name) + .map_err(|error| HostError::Governance(format!("read host secret `{name}`: {error}")))?; + if exists { + store.update(&name, token) + } else { + store.store(&name, token) + } + .map_err(|error| HostError::Governance(format!("store host secret `{name}`: {error}")))?; + Ok(FleetLoginReport { + authority: operator.authority.clone(), + url: settings.url.clone(), + principal: issued.principal.to_string(), + token_id: issued.id, + expires_at_unix: issued.expires_at_unix, + secret: settings.token_secret.clone(), + }) +} + /// Inputs for `sendbox governance check`. #[derive(Debug, Clone)] pub struct GovernanceCheckRequest { diff --git a/crates/sendbox-host/src/governance/relay.rs b/crates/sendbox-host/src/governance/relay.rs index 9fd4446..ca96765 100644 --- a/crates/sendbox-host/src/governance/relay.rs +++ b/crates/sendbox-host/src/governance/relay.rs @@ -9,9 +9,10 @@ use std::time::Duration; use sendbox_agent::{AgentError, BoxFuture, CredentialRelayHandler, CredentialRelayOutbound}; use sendbox_credentials::relay::{ RelayAuditEvent, RelayAuditSink, RelayAuthorization, RelayAuthorizer, RelayEndpoint, - RelayFuture, RelayLimits, RelayOutbound, RelayService, + RelayFuture, RelayLimits, RelayOutbound, RelayService, RelayStreamOutcome, }; use sendbox_credentials::{CredentialBrokerError, PinnedHttpsTransport, SecretResolver}; +use sendbox_governance::api::{ReportedOutcome, RequestOutcomeReport}; use sendbox_governance::profile::CredentialServiceProfile; use sendbox_governance::{ CredentialGrant, Decision, GrantAuthority, GrantId, GrantRequest, LocalAuthorityLimits, @@ -23,9 +24,13 @@ use sendbox_security::audit::{AuditCategory, AuditResult}; use sendbox_session_security::AuditRecorder; use tokio::task::JoinHandle; +use super::fleet::FleetClient; use super::{GovernedRun, operator::OperatorRevisionSource, record_audit}; use crate::HostError; +/// Longest the relay waits for queued outcome reports at session end. +const OUTCOME_FLUSH_TIMEOUT: Duration = Duration::from_secs(30); + /// Provider credentials resolved from the host secret store before the /// session starts. They are held only in this process. pub(crate) struct BrokeredSecrets { @@ -120,11 +125,113 @@ impl RelayAuthorizer for GrantAuthorizer { } } -/// Writes relay evidence into the signed session audit chain. +enum OutcomeMessage { + Report(GrantId, RequestOutcomeReport), + Flush(tokio::sync::oneshot::Sender<()>), +} + +/// Sends stream outcomes to a shared governance service in order. A failed +/// report is recorded in the session audit; the local record stays +/// authoritative. +struct OutcomeReporter { + sender: tokio::sync::mpsc::UnboundedSender, + grants: BTreeMap, + task: JoinHandle<()>, +} + +impl OutcomeReporter { + fn start( + client: Arc, + grants: BTreeMap, + audit: AuditRecorder, + metadata: BTreeMap, + failed: Arc, + ) -> Self { + let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel(); + let task = tokio::spawn(async move { + while let Some(message) = receiver.recv().await { + match message { + OutcomeMessage::Report(grant, report) => { + if let Err(error) = client.report_outcome(&grant, &report).await { + eprintln!( + "sendbox: reporting a credential request outcome to the governance service failed: {error}" + ); + let mut metadata = metadata.clone(); + metadata.extend([ + ("grant".to_owned(), grant.to_string()), + ("outcome".to_owned(), report.outcome.code().to_owned()), + ("error".to_owned(), error.to_string()), + ]); + if record_audit( + &audit, + AuditCategory::Secret, + "credential.request.outcome_report_failed", + report.service.as_str(), + AuditResult::Error, + metadata, + ) + .is_err() + { + failed.store(true, Ordering::SeqCst); + } + } + } + OutcomeMessage::Flush(done) => { + let _ = done.send(()); + } + } + } + }); + Self { + sender, + grants, + task, + } + } + + fn report(&self, report: RequestOutcomeReport) { + let Some(grant) = self.grants.get(report.service.as_str()) else { + return; + }; + if self + .sender + .send(OutcomeMessage::Report(grant.clone(), report)) + .is_err() + { + eprintln!("sendbox: the outcome reporter stopped before the session ended"); + } + } + + /// Waits until every queued report was attempted, then stops the task. + async fn finish(&self) -> bool { + let (done, wait) = tokio::sync::oneshot::channel(); + let flushed = self.sender.send(OutcomeMessage::Flush(done)).is_ok() + && tokio::time::timeout(OUTCOME_FLUSH_TIMEOUT, wait) + .await + .is_ok_and(|result| result.is_ok()); + self.task.abort(); + flushed + } +} + +/// Maps a relay stream outcome to the central audit vocabulary. +fn reported_outcome(outcome: RelayStreamOutcome) -> ReportedOutcome { + match outcome { + RelayStreamOutcome::Complete => ReportedOutcome::Succeeded, + RelayStreamOutcome::AbortedUncertain => ReportedOutcome::Unknown, + RelayStreamOutcome::Denied | RelayStreamOutcome::Failed | RelayStreamOutcome::Aborted => { + ReportedOutcome::Failed + } + } +} + +/// Writes relay evidence into the signed session audit chain and, with a +/// shared governance service, reports stream outcomes to it. struct RelayAudit { audit: AuditRecorder, metadata: BTreeMap, failed: Arc, + reporter: Option>, } impl RelayAuditSink for RelayAudit { @@ -172,6 +279,24 @@ impl RelayAuditSink for RelayAudit { response_bytes, duration_ms, } => { + if let (Some(reporter), Ok(service_id)) = + (&self.reporter, ServiceId::new(service.clone())) + { + let report = RequestOutcomeReport { + service: service_id, + method: method.clone(), + path: path.clone(), + outcome: reported_outcome(outcome), + reason: reason.to_owned(), + status, + request_bytes, + response_bytes, + duration_ms, + }; + if report.validate().is_ok() { + reporter.report(report); + } + } metadata.extend([ ("stream".to_owned(), stream.to_string()), ("service".to_owned(), service.clone()), @@ -187,10 +312,8 @@ impl RelayAuditSink for RelayAudit { metadata.insert("upstream_status".to_owned(), status.to_string()); } let result = match outcome { - sendbox_credentials::relay::RelayStreamOutcome::Complete => { - AuditResult::Success - } - sendbox_credentials::relay::RelayStreamOutcome::Denied => AuditResult::Denied, + RelayStreamOutcome::Complete => AuditResult::Success, + RelayStreamOutcome::Denied => AuditResult::Denied, _ => AuditResult::Error, }; ("credential.request.outcome", result, service) @@ -235,6 +358,7 @@ pub(crate) struct HostCredentialRelay { lease: Duration, revocation_grace: Duration, finished: AtomicBool, + reporter: Option>, } impl HostCredentialRelay { @@ -322,6 +446,15 @@ impl HostCredentialRelay { .map(RelayService::from_profile) .collect::, _>>()?; let audit_failed = Arc::new(AtomicBool::new(false)); + let reporter = run.session.fleet.as_ref().map(|client| { + Arc::new(OutcomeReporter::start( + Arc::clone(client), + grant_ids.clone(), + audit.clone(), + metadata.clone(), + Arc::clone(&audit_failed), + )) + }); let endpoint = RelayEndpoint::new( relay_services, Arc::new(GrantAuthorizer { @@ -349,6 +482,7 @@ impl HostCredentialRelay { audit: audit.clone(), metadata: metadata.clone(), failed: Arc::clone(&audit_failed), + reporter: reporter.clone(), }), RelayLimits { max_streams: usize::try_from(limits.max_concurrent_streams).unwrap_or(1), @@ -366,6 +500,7 @@ impl HostCredentialRelay { lease: Duration::from_secs(limits.lease_seconds), revocation_grace: Duration::from_secs(limits.revocation_grace_seconds), finished: AtomicBool::new(false), + reporter, }) } @@ -451,6 +586,13 @@ impl HostCredentialRelay { } self.stop_renewal(); self.endpoint.close(Duration::ZERO).await; + if let Some(reporter) = &self.reporter + && !reporter.finish().await + { + eprintln!( + "sendbox: some credential request outcomes were not reported to the governance service; the session audit keeps them" + ); + } let mut failures = Vec::new(); for grant in &self.grants { let mut metadata = self.metadata.clone(); @@ -512,7 +654,7 @@ impl CredentialRelayHandler for HostCredentialRelay { #[cfg(test)] mod tests { use sendbox_core::SessionId; - use sendbox_secrets::CredentialMasker; + use sendbox_secrets::{CredentialMasker, SecretValue}; use super::super::operator::tests::{fixture, protected_test_tree}; use super::super::tests::{FakeStore, admitted_run, brokered_profile, configuration}; @@ -614,4 +756,83 @@ mod tests { } assert_eq!(records[2].event.metadata["reason"], "session_completed"); } + + #[test] + fn stream_outcomes_map_to_the_central_vocabulary() { + assert_eq!( + reported_outcome(RelayStreamOutcome::Complete), + ReportedOutcome::Succeeded + ); + assert_eq!( + reported_outcome(RelayStreamOutcome::AbortedUncertain), + ReportedOutcome::Unknown + ); + for failed in [ + RelayStreamOutcome::Denied, + RelayStreamOutcome::Failed, + RelayStreamOutcome::Aborted, + ] { + assert_eq!(reported_outcome(failed), ReportedOutcome::Failed); + } + } + + #[tokio::test] + async fn outcomes_are_reported_in_order_and_failed_reports_are_audited() { + use super::super::fleet::tests::{Handler, Recorded, TOKEN, serve, settings}; + let handler: Arc = Arc::new(|request: &Recorded| { + if String::from_utf8_lossy(&request.body).contains("/v1/fail") { + (503, r#"{"detail":"unavailable"}"#.to_owned()) + } else { + (204, String::new()) + } + }); + let (address, recorded) = serve(handler).await; + let client = Arc::new( + FleetClient::new(&settings(address), &SecretValue::try_from(TOKEN).unwrap()) + .expect("client"), + ); + let audit = AuditRecorder::new(SessionId::from_bytes([7; 16])).expect("audit"); + let grant = GrantId::from_bytes([3; 16]); + let failed = Arc::new(AtomicBool::new(false)); + let reporter = OutcomeReporter::start( + client, + BTreeMap::from([("anthropic".to_owned(), grant.clone())]), + audit.clone(), + BTreeMap::from([("session".to_owned(), "s".to_owned())]), + Arc::clone(&failed), + ); + let report = |path: &str, outcome| RequestOutcomeReport { + service: ServiceId::new("anthropic").unwrap(), + method: "POST".to_owned(), + path: path.to_owned(), + outcome, + reason: "complete".to_owned(), + status: Some(200), + request_bytes: 1, + response_bytes: 2, + duration_ms: 3, + }; + reporter.report(report("/v1/messages", ReportedOutcome::Succeeded)); + reporter.report(report("/v1/fail", ReportedOutcome::Unknown)); + let mut unknown_service = report("/v1/messages", ReportedOutcome::Failed); + unknown_service.service = ServiceId::new("openai").unwrap(); + reporter.report(unknown_service); + assert!(reporter.finish().await); + + let requests = recorded.lock().unwrap().clone(); + assert_eq!(requests.len(), 2, "only granted services are reported"); + assert!( + requests + .iter() + .all(|request| request.target == format!("/v1/grants/{grant}:outcome")) + ); + let first: RequestOutcomeReport = serde_json::from_slice(&requests[0].body).unwrap(); + assert_eq!(first.path, "/v1/messages"); + let records = audit.records().expect("records"); + let failure = &records.last().expect("failure record").event; + assert_eq!(failure.action, "credential.request.outcome_report_failed"); + assert_eq!(failure.metadata["outcome"], "unknown"); + assert!(failure.metadata["error"].contains("503")); + assert!(!failed.load(Ordering::SeqCst)); + } } diff --git a/docs/architecture/governed-sessions.md b/docs/architecture/governed-sessions.md index 1bf4081..ebbf48d 100644 --- a/docs/architecture/governed-sessions.md +++ b/docs/architecture/governed-sessions.md @@ -332,6 +332,7 @@ Records join the existing signed session audit chain: | `credential.request.allowed`, `.denied` | each authorization decision | | `credential.request.outcome` | each stream ends, with status, byte counts, duration, and outcome | | `governance.exception.expired` | a lifted exception expired and the session was stopped | +| `credential.request.outcome_report_failed` | a stream outcome could not be reported to the shared service | Each record carries principal, project, session, authority, profile id, revision and digest, effective policy digest, and binding digest. The @@ -364,10 +365,20 @@ sequenceDiagram H->>F: POST /v1/sessions/{id}:end (revokes remaining grants) ``` -- **Authentication.** The caller stores their bearer token in the host - secret store (`sendbox secrets add SENDBOX_FLEET_TOKEN`, or the name in - `token_secret`). It is sent only to the configured URL, redirects are never - followed, system proxies are ignored, and it can never be a workload secret. +- **Authentication.** The caller stores a service token in the host secret + store under `token_secret` (default `SENDBOX_FLEET_TOKEN`). With an + identity provider, `sendbox governance login` exchanges an OIDC token for a + short-lived service token and stores it: + + ```bash + my-idp print-id-token | sendbox governance login # or --identity-token-file PATH + ``` + + The service URL comes only from the verified operator configuration. + Tokens can also be issued by the service operator and added with + `sendbox secrets add SENDBOX_FLEET_TOKEN`. A token is sent only to the + configured URL, redirects are never followed, system proxies are ignored, + and it can never be a workload secret. - **Identity.** The authenticated principal, not the local account, is the session principal. The service refuses a binding whose principal is not the caller, so a host cannot claim another identity. @@ -378,6 +389,12 @@ sequenceDiagram authorized by the service; any non-200 answer, timeout, or unreachable service denies with `authority_unavailable`. Nothing falls back to the local authority or to credential delivery. +- **Outcomes.** When a brokered stream ends, the host reports its redacted + outcome (`succeeded`, `failed`, or `unknown` when a stream was cut after + reaching the provider) to the service, which records it in the central + audit. Reports are sent in order and flushed before grants are revoked; a + report that fails is recorded as `credential.request.outcome_report_failed` + in the session audit, which keeps the authoritative local record. - **End.** After the workload ends, the host revokes its grants and ends the session on the service, which revokes any grant still live. diff --git a/docs/cli-reference.md b/docs/cli-reference.md index a14bdf8..486cd44 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -73,12 +73,13 @@ See [network grants](configuration.md#network-grants). | `sign PROFILE --key PATH [--append]` | Sign the profile's exact bytes into `PROFILE.sig.json`; `--append` adds a threshold signature | | `verify [--governance-config PATH]` | Verify the active operator configuration, profile, and signatures | | `check --config PATH [--governance-config PATH] [--runtime apple\|kata] [--image IMAGE@sha256:DIGEST]` | List every violation of the active profile without starting a session | +| `login [--governance-config PATH] [--identity-token-file PATH] [--ttl-seconds N] [--description TEXT]` | Exchange an identity-provider token (read from the file, stdin, or a prompt) with the configured shared governance service and store the returned service token in the host secret store | Each subcommand accepts `--json`. A governance failure or a rejected configuration exits with code `6`. `check` evaluates the local profile only; with a [shared governance service](architecture/governed-sessions.md#shared-governance-service), -store your service token with `sendbox secrets add SENDBOX_FLEET_TOKEN` before -`sendbox run`. +run `sendbox governance login` (or `sendbox secrets add SENDBOX_FLEET_TOKEN`) +before `sendbox run`. ## Examples