Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 100 additions & 3 deletions crates/sendbox-cli/src/governance.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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,
Expand All @@ -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)]
Expand Down Expand Up @@ -82,6 +85,24 @@ struct VerifyArgs {
json: bool,
}

#[derive(Debug, Args)]
struct LoginArgs {
#[arg(long, value_name = "PATH")]
governance_config: Option<PathBuf>,
/// 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<PathBuf>,
/// Requested lifetime; the service caps it.
#[arg(long, value_name = "SECONDS")]
ttl_seconds: Option<u64>,
#[arg(long)]
description: Option<String>,
#[arg(long, help = "Emit a deterministic JSON result")]
json: bool,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum CheckRuntime {
Apple,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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<Zeroizing<String>, (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),
Expand Down
179 changes: 177 additions & 2 deletions crates/sendbox-governance/src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -95,3 +95,178 @@ pub struct RevokeGrantRequest {
pub struct ExceptionList {
pub exceptions: Vec<PolicyException>,
}

/// `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<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}

/// `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", &"<redacted>")
.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<u16>,
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"));
}
}
Loading
Loading