diff --git a/.env.example b/.env.example index e63e896..7e4d8c8 100644 --- a/.env.example +++ b/.env.example @@ -7,8 +7,14 @@ POSTGRES_PASSWORD=local-dev-only-change-me FLEET_PORT=8080 FLEET_LOG_LEVEL=info FLEET_LOG_RETENTION_DAYS=30 +FLEET_AUTHORITY_ID=sendbox-fleet +# Path inside the container to the profile signer file; mount it with a +# compose override. Publication is refused while this is empty. +FLEET_PROFILE_TRUST= # Running the binary directly with SQLite (export these in your shell) # FLEET_DATABASE_URL=sqlite://sendbox-fleet.db?mode=rwc # FLEET_BIND=127.0.0.1:8080 # FLEET_LOG_DIR=./logs +# FLEET_AUTHORITY_ID=sendbox-fleet +# FLEET_PROFILE_TRUST=./profile-trust.yaml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4fa15db..cc9032f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -71,8 +71,8 @@ jobs: - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 - - name: Run migration tests against PostgreSQL - run: cargo test --locked --workspace --test migrations -- --test-threads=1 + - name: Run migration and HTTP tests against PostgreSQL + run: cargo test --locked --workspace --test migrations --test http -- --test-threads=1 - name: Start the server against PostgreSQL and stop it gracefully env: diff --git a/Cargo.lock b/Cargo.lock index 7824d5e..c0c368d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -189,6 +189,56 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + [[package]] name = "atoi" version = "2.0.0" @@ -280,6 +330,52 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + [[package]] name = "const-oid" version = "0.9.6" @@ -383,6 +479,33 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "digest 0.10.7", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "der" version = "0.7.10" @@ -399,6 +522,9 @@ name = "deranged" version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" +dependencies = [ + "serde_core", +] [[package]] name = "derive_more" @@ -463,6 +589,30 @@ version = "0.15.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2 0.10.9", + "subtle", + "zeroize", +] + [[package]] name = "either" version = "1.19.0" @@ -499,7 +649,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -529,6 +679,12 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "find-msvc-tools" version = "0.1.15" @@ -541,9 +697,15 @@ version = "0.1.0" dependencies = [ "actix-http", "actix-web", + "base64", + "clap", + "getrandom 0.4.3", "sendbox-governance", + "sendbox-security", "serde", "serde_json", + "serde_json_canonicalizer", + "sha2 0.11.1", "sqlx", "tempfile", "thiserror", @@ -552,6 +714,7 @@ dependencies = [ "tracing", "tracing-appender", "tracing-subscriber", + "yaml_serde", ] [[package]] @@ -912,6 +1075,12 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itoa" version = "1.0.19" @@ -1122,6 +1291,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + [[package]] name = "parking" version = "2.2.1" @@ -1377,7 +1552,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -1447,7 +1622,7 @@ checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" [[package]] name = "sendbox-core" version = "0.2.7" -source = "git+https://github.com/mbianchidev/sendbox?branch=main#e24261c40be666a2e94b844f3379bdb4707bc9b0" +source = "git+https://github.com/mbianchidev/sendbox?branch=main#a04b2373f5dcc20829d028f9664d6744806b5f7e" dependencies = [ "serde", ] @@ -1455,7 +1630,7 @@ dependencies = [ [[package]] name = "sendbox-governance" version = "0.2.7" -source = "git+https://github.com/mbianchidev/sendbox?branch=main#e24261c40be666a2e94b844f3379bdb4707bc9b0" +source = "git+https://github.com/mbianchidev/sendbox?branch=main#a04b2373f5dcc20829d028f9664d6744806b5f7e" dependencies = [ "sendbox-core", "serde", @@ -1466,6 +1641,23 @@ dependencies = [ "yaml_serde", ] +[[package]] +name = "sendbox-security" +version = "0.2.7" +source = "git+https://github.com/mbianchidev/sendbox?branch=main#a04b2373f5dcc20829d028f9664d6744806b5f7e" +dependencies = [ + "base64", + "ed25519-dalek", + "getrandom 0.4.3", + "rustix", + "serde", + "serde_json", + "sha2 0.11.1", + "thiserror", + "time", + "zeroize", +] + [[package]] name = "serde" version = "1.0.229" @@ -1855,6 +2047,12 @@ dependencies = [ "unicode-properties", ] +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "subtle" version = "2.6.1" @@ -1910,7 +2108,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2201,6 +2399,12 @@ dependencies = [ "utf_types", ] +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + [[package]] name = "utf_types" version = "1.0.0" diff --git a/Cargo.toml b/Cargo.toml index ff81e29..a780504 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,14 @@ publish = false [workspace.dependencies] actix-http = { version = "3.21.0", default-features = false } actix-web = { version = "4.19.0", default-features = false, features = ["macros"] } +base64 = "0.22.1" +clap = { version = "4.6.2", features = ["derive"] } +getrandom = "0.4.3" sendbox-governance = { git = "https://github.com/mbianchidev/sendbox", branch = "main" } +sendbox-security = { git = "https://github.com/mbianchidev/sendbox", branch = "main" } +serde_json_canonicalizer = "0.3.2" +serde_yaml_ng = { package = "yaml_serde", version = "0.10.7" } +sha2 = "0.11.0" serde = { version = "1.0.229", features = ["derive"] } serde_json = "1.0.154" sqlx = { version = "0.8.6", default-features = false, features = ["macros", "migrate", "postgres", "runtime-tokio", "sqlite", "tls-rustls"] } diff --git a/README.md b/README.md index 453def8..a6c319a 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,28 @@ # sendbox-fleet -Shared governance service for [SendBox](https://github.com/mbianchidev/sendbox) governed sessions: operator-signed policy profiles shared across users and hosts, project-scoped roles, session admission, credential grant authorization and revocation, expiring exceptions, and central audit. It is increment 2 of [mbianchidev/sendbox#87](https://github.com/mbianchidev/sendbox/issues/87). +Shared governance service for [SendBox](https://github.com/mbianchidev/sendbox) governed sessions: operator-signed policy profiles shared across users and hosts, project-scoped roles, session admission, credential grant authorization and revocation, approved expiring exceptions, and a hash-chained central audit log. It is increment 2 of [mbianchidev/sendbox#87](https://github.com/mbianchidev/sendbox/issues/87). -> **Status: scaffold.** The server runs, applies its schema, authenticates every `/v1` request, and validates bodies against the shared contract, but every management operation returns `501 Not Implemented`. Provider credentials never reach this service; they stay in the SendBox host broker. +Provider credentials never reach this service; they stay in the SendBox host broker. ## Quick start ```sh export FLEET_DATABASE_URL='sqlite://sendbox-fleet.db?mode=rwc' +cargo run --bin sendbox-fleet -- admin principal add oidc:you@example.com --kind user --operator +cargo run --bin sendbox-fleet -- admin token issue oidc:you@example.com > you.token cargo run --bin sendbox-fleet -curl http://127.0.0.1:8080/readyz +curl -H "Authorization: Bearer $(cat you.token)" http://127.0.0.1:8080/v1/whoami ``` -With PostgreSQL: `cp .env.example .env`, set `POSTGRES_PASSWORD`, then `docker compose build --no-cache && docker compose up`. +Set `FLEET_PROFILE_TRUST` to publish signed profiles; see [development](docs/development.md#bootstrap-principals-tokens-and-projects). With PostgreSQL: `cp .env.example .env`, set `POSTGRES_PASSWORD`, then `docker compose build --no-cache && docker compose up`. ## Documentation -- [Architecture](docs/architecture.md): relationship to SendBox, trust boundaries, API surface, schema +- [Architecture](docs/architecture.md): relationship to SendBox, trust boundaries, roles, API surface, schema, audit - [Shared contract](docs/contract.md): how `sendbox-governance` is pinned and versioned - [Threat model](docs/threat-model.md) -- [Roadmap](docs/roadmap.md): increment-2 work mapped to the issue's acceptance criteria -- [Development](docs/development.md): configuration, local runs, tests, logs +- [Roadmap](docs/roadmap.md): delivered and remaining work mapped to the issue's acceptance criteria +- [Development](docs/development.md): configuration, bootstrap, local runs, tests, logs - [Contributing](CONTRIBUTING.md) and [security](SECURITY.md) ## License diff --git a/crates/fleet-server/Cargo.toml b/crates/fleet-server/Cargo.toml index bc7a69b..d004e28 100644 --- a/crates/fleet-server/Cargo.toml +++ b/crates/fleet-server/Cargo.toml @@ -14,7 +14,14 @@ path = "src/main.rs" [dependencies] actix-web.workspace = true +base64.workspace = true +clap.workspace = true +getrandom.workspace = true sendbox-governance.workspace = true +sendbox-security.workspace = true +serde_json_canonicalizer.workspace = true +serde_yaml_ng.workspace = true +sha2.workspace = true serde.workspace = true serde_json.workspace = true sqlx.workspace = true diff --git a/crates/fleet-server/src/admin.rs b/crates/fleet-server/src/admin.rs new file mode 100644 index 0000000..077791f --- /dev/null +++ b/crates/fleet-server/src/admin.rs @@ -0,0 +1,390 @@ +//! Operator bootstrap commands that act on the database directly: +//! `sendbox-fleet admin ...`. They need only `FLEET_DATABASE_URL` and are +//! meant for whoever operates the service host. Every change is audited with +//! the actor `cli:admin`. + +use clap::{Args, Subcommand, ValueEnum}; +use sendbox_governance::{Clock, PrincipalId, ProjectId, SystemClock}; + +use crate::audit::{self, AuditRecord}; +use crate::auth::token_from_bytes; +use crate::config::DatabaseUrl; +use crate::db::{Database, DbError}; +use crate::governance; +use crate::problem::Problem; +use crate::state::{from_db, to_db}; + +const ACTOR: &str = "cli:admin"; +const MAX_TOKEN_DAYS: u64 = 90; + +#[derive(Debug, Subcommand)] +pub enum AdminCommand { + /// Manage authenticated principals. + #[command(subcommand)] + Principal(PrincipalCommand), + /// Issue, list, and revoke bearer tokens. + #[command(subcommand)] + Token(TokenCommand), + /// Create projects with their first owner. + #[command(subcommand)] + Project(ProjectCommand), +} + +#[derive(Debug, Subcommand)] +pub enum PrincipalCommand { + /// Add a person (`user`) or machine identity (`worker`). + Add(PrincipalAdd), + /// Disable a principal. Its tokens stop working immediately. + Disable { id: String }, +} + +#[derive(Debug, Args)] +pub struct PrincipalAdd { + /// For example `oidc:alice@example.com` or `worker:ci-runner-1`. + pub id: String, + #[arg(long, value_enum)] + pub kind: Kind, + /// Fleet operator: may publish profiles and create projects. + #[arg(long)] + pub operator: bool, + #[arg(long)] + pub display_name: Option, +} + +#[derive(Debug, Clone, Copy, ValueEnum)] +pub enum Kind { + User, + Worker, +} + +#[derive(Debug, Subcommand)] +pub enum TokenCommand { + /// Issue a token and print it once on stdout. Only its digest is stored. + Issue { + principal: String, + #[arg(long, default_value_t = 30)] + ttl_days: u64, + #[arg(long)] + description: Option, + }, + /// List a principal's tokens without revealing them. + List { principal: String }, + /// Revoke a token by its id. + Revoke { token_id: String }, +} + +#[derive(Debug, Subcommand)] +pub enum ProjectCommand { + /// Create a project and make `--owner` its first owner. + Create { + /// `github:owner/repository` or `path-sha256:`. + project: String, + #[arg(long)] + owner: String, + #[arg(long)] + display_name: Option, + }, +} + +#[derive(Debug, thiserror::Error)] +pub enum AdminError { + #[error("{0}")] + Invalid(String), + #[error(transparent)] + Database(#[from] DbError), + #[error("{}", .0.detail)] + Refused(Problem), +} + +impl From for AdminError { + fn from(problem: Problem) -> Self { + Self::Refused(problem) + } +} + +fn principal(value: &str) -> Result { + let principal = + PrincipalId::new(value).map_err(|error| AdminError::Invalid(error.to_string()))?; + if principal.kind() == "local-user" { + return Err(AdminError::Invalid( + "local-user principals belong to a single host".to_owned(), + )); + } + Ok(principal) +} + +fn random() -> Result<[u8; N], AdminError> { + let mut bytes = [0_u8; N]; + getrandom::fill(&mut bytes) + .map_err(|error| AdminError::Invalid(format!("random generation failed: {error}")))?; + Ok(bytes) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} + +fn display_name(value: Option) -> Result, AdminError> { + if let Some(name) = &value + && (name.trim().is_empty() + || name.chars().count() > 200 + || name.chars().any(char::is_control)) + { + return Err(AdminError::Invalid( + "display names must be 1 to 200 characters without control characters".to_owned(), + )); + } + Ok(value) +} + +/// Runs one admin command. Results go to stdout; a new token is the only +/// thing printed for `token issue`. +pub async fn run(url: &DatabaseUrl, command: AdminCommand) -> Result<(), AdminError> { + let database = Database::connect(url).await?; + database.migrate().await?; + let result = execute(&database, command, SystemClock.now_unix()).await; + database.close().await; + result +} + +async fn execute(database: &Database, command: AdminCommand, now: u64) -> Result<(), AdminError> { + let mut tx = database.begin_write().await?; + let record = |event_type| AuditRecord { + event_type, + actor: Some(ACTOR.to_owned()), + ..AuditRecord::default() + }; + match command { + AdminCommand::Principal(PrincipalCommand::Add(add)) => { + let id = principal(&add.id)?; + if tx + .fetch_optional( + "SELECT id FROM principals WHERE id = $1", + &[id.as_str().into()], + ) + .await? + .is_some() + { + return Err(AdminError::Invalid(format!( + "principal `{id}` already exists" + ))); + } + let kind = match add.kind { + Kind::User => "user", + Kind::Worker => "worker", + }; + if add.operator && matches!(add.kind, Kind::Worker) { + return Err(AdminError::Invalid( + "workers cannot be operators".to_owned(), + )); + } + tx.execute( + "INSERT INTO principals (id, kind, display_name, created_at_unix, is_operator) \ + VALUES ($1, $2, $3, $4, $5)", + &[ + id.as_str().into(), + kind.into(), + display_name(add.display_name)?.into(), + to_db(now)?.into(), + add.operator.into(), + ], + ) + .await?; + audit::append( + &mut tx, + now, + AuditRecord { + principal: Some(id.to_string()), + detail: Some(format!("kind={kind} operator={}", add.operator)), + ..record("principal.added") + }, + ) + .await?; + println!( + "added {kind} `{id}`{}", + if add.operator { " (operator)" } else { "" } + ); + } + AdminCommand::Principal(PrincipalCommand::Disable { id }) => { + let id = principal(&id)?; + let changed = tx + .execute( + "UPDATE principals SET disabled_at_unix = $2 WHERE id = $1 \ + AND disabled_at_unix IS NULL", + &[id.as_str().into(), to_db(now)?.into()], + ) + .await?; + if changed == 0 { + return Err(AdminError::Invalid(format!( + "principal `{id}` does not exist or is already disabled" + ))); + } + audit::append( + &mut tx, + now, + AuditRecord { + principal: Some(id.to_string()), + ..record("principal.disabled") + }, + ) + .await?; + println!("disabled `{id}`"); + } + AdminCommand::Token(TokenCommand::Issue { + principal: id, + ttl_days, + description, + }) => { + let id = principal(&id)?; + if !(1..=MAX_TOKEN_DAYS).contains(&ttl_days) { + return Err(AdminError::Invalid(format!( + "--ttl-days must be 1 to {MAX_TOKEN_DAYS}" + ))); + } + if !governance::principal_active(&mut tx, &id).await? { + return Err(AdminError::Invalid(format!( + "principal `{id}` does not exist or is disabled" + ))); + } + let token_id = hex(&random::<16>()?); + let (token, digest) = token_from_bytes(&random::<32>()?); + let expires = now.saturating_add(ttl_days * 24 * 60 * 60); + tx.execute( + "INSERT INTO api_tokens (id, principal_id, token_sha256, description, \ + created_at_unix, expires_at_unix) VALUES ($1, $2, $3, $4, $5, $6)", + &[ + token_id.clone().into(), + id.as_str().into(), + digest.into(), + display_name(description)?.into(), + to_db(now)?.into(), + to_db(expires)?.into(), + ], + ) + .await?; + audit::append( + &mut tx, + now, + AuditRecord { + principal: Some(id.to_string()), + detail: Some(format!("token_id={token_id} expires_at_unix={expires}")), + ..record("token.issued") + }, + ) + .await?; + tx.commit().await?; + eprintln!("issued token {token_id} for `{id}`, expiring at {expires} (Unix seconds)"); + println!("{token}"); + return Ok(()); + } + AdminCommand::Token(TokenCommand::List { principal: id }) => { + let id = principal(&id)?; + let rows = tx + .fetch_all( + "SELECT id, description, created_at_unix, expires_at_unix, revoked_at_unix \ + FROM api_tokens WHERE principal_id = $1 ORDER BY created_at_unix", + &[id.as_str().into()], + ) + .await?; + for row in rows { + println!( + "{}\tcreated={}\texpires={}\trevoked={}\t{}", + row.text("id")?, + from_db(row.int("created_at_unix")?)?, + from_db(row.int("expires_at_unix")?)?, + row.opt_int("revoked_at_unix")? + .map_or_else(|| "-".to_owned(), |value| value.to_string()), + row.opt_text("description")?.unwrap_or_default() + ); + } + } + AdminCommand::Token(TokenCommand::Revoke { token_id }) => { + let row = tx + .fetch_optional( + "SELECT principal_id FROM api_tokens WHERE id = $1 AND revoked_at_unix IS NULL", + &[token_id.clone().into()], + ) + .await? + .ok_or_else(|| { + AdminError::Invalid(format!("token `{token_id}` does not exist or is revoked")) + })?; + tx.execute( + "UPDATE api_tokens SET revoked_at_unix = $2 WHERE id = $1", + &[token_id.clone().into(), to_db(now)?.into()], + ) + .await?; + audit::append( + &mut tx, + now, + AuditRecord { + principal: Some(row.text("principal_id")?), + detail: Some(format!("token_id={token_id}")), + ..record("token.revoked") + }, + ) + .await?; + println!("revoked token {token_id}"); + } + AdminCommand::Project(ProjectCommand::Create { + project, + owner, + display_name: name, + }) => { + let project = + ProjectId::new(project).map_err(|error| AdminError::Invalid(error.to_string()))?; + let owner = principal(&owner)?; + if governance::project_exists(&mut tx, &project).await? { + return Err(AdminError::Invalid(format!( + "project `{project}` already exists" + ))); + } + if !governance::principal_active(&mut tx, &owner).await? { + return Err(AdminError::Invalid(format!( + "principal `{owner}` does not exist or is disabled" + ))); + } + tx.execute( + "INSERT INTO projects (id, display_name, created_at_unix) VALUES ($1, $2, $3)", + &[ + project.as_str().into(), + display_name(name)?.into(), + to_db(now)?.into(), + ], + ) + .await?; + tx.execute( + "INSERT INTO role_bindings (project_id, principal_id, role, granted_by, \ + granted_at_unix) VALUES ($1, $2, 'owner', $2, $3)", + &[ + project.as_str().into(), + owner.as_str().into(), + to_db(now)?.into(), + ], + ) + .await?; + for (event_type, principal, detail) in [ + ("project.created", None, None), + ( + "role.assigned", + Some(owner.to_string()), + Some("role=owner".to_owned()), + ), + ] { + audit::append( + &mut tx, + now, + AuditRecord { + principal, + project: Some(project.to_string()), + detail, + ..record(event_type) + }, + ) + .await?; + } + println!("created `{project}` owned by `{owner}`"); + } + } + tx.commit().await?; + Ok(()) +} diff --git a/crates/fleet-server/src/audit.rs b/crates/fleet-server/src/audit.rs new file mode 100644 index 0000000..a9b52f3 --- /dev/null +++ b/crates/fleet-server/src/audit.rs @@ -0,0 +1,337 @@ +//! Central, append-only audit log. +//! +//! Every state change and every authorization decision appends one event in +//! the same transaction as the change it records. Events form a hash chain: +//! `event_hash` is the SHA-256 of the RFC 8785 canonical JSON of the event +//! without `event_hash`, which includes `previous_hash`. Events carry +//! identifiers, decisions, a redacted request target, and short non-secret +//! details; never credentials, tokens, headers, query strings, or bodies. + +use sendbox_governance::{DenyReason, Sha256Digest}; +use serde::{Deserialize, Serialize}; + +use crate::db::{Arg, Database, Row, Tx}; +use crate::problem::Problem; +use crate::state::{from_db, to_db}; + +pub const GENESIS_HASH: &str = "0000000000000000000000000000000000000000000000000000000000000000"; +const MAX_TARGET_BYTES: usize = 512; +const MAX_DETAIL_BYTES: usize = 1100; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AuditDecision { + Allow, + Deny, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum AuditOutcome { + Succeeded, + Failed, + /// The external effect could not be confirmed. + Unknown, +} + +/// What a caller records. The sequence, times, and hashes are assigned when +/// the event is appended. +#[derive(Debug, Clone, Default)] +pub struct AuditRecord { + pub event_type: &'static str, + pub actor: Option, + pub principal: Option, + pub project: Option, + pub session: Option, + pub grant: Option, + pub exception: Option, + pub profile: Option<(String, u64)>, + pub decision: Option, + pub deny_reason: Option, + pub outcome: Option, + pub target: Option, + pub detail: Option, +} + +/// A stored event exactly as it is hashed and returned. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AuditEvent { + pub sequence: u64, + pub occurred_at_unix: u64, + pub recorded_at_unix: u64, + pub event_type: String, + pub actor: Option, + pub principal: Option, + pub project: Option, + pub session: Option, + pub grant: Option, + pub exception: Option, + pub profile_id: Option, + pub profile_revision: Option, + pub decision: Option, + pub deny_reason: Option, + pub outcome: Option, + /// Method, service, and path only; never a query string or body. + pub target: Option, + pub detail: Option, + pub previous_hash: Sha256Digest, + #[serde(skip_serializing_if = "Option::is_none", default)] + pub event_hash: Option, +} + +impl AuditEvent { + /// The chain hash of this event, computed over every field except + /// `event_hash`. + pub fn compute_hash(&self) -> Result { + let unhashed = Self { + event_hash: None, + ..self.clone() + }; + sendbox_governance::canonical_digest(&unhashed).map_err(|error| { + tracing::error!(%error, "audit event encoding failed"); + Problem::internal() + }) + } +} + +/// Bounds free text to printable ASCII so it satisfies the schema. +#[must_use] +pub fn printable(value: &str, limit: usize) -> String { + let mut text = value + .chars() + .map(|character| { + if character == ' ' || character.is_ascii_graphic() { + character + } else { + '?' + } + }) + .collect::(); + text.truncate(limit); + text.trim().to_owned() +} + +/// Appends one event inside `tx`. The caller's write lock serializes appends. +pub async fn append(tx: &mut Tx, now_unix: u64, record: AuditRecord) -> Result { + let last = tx + .fetch_optional( + "SELECT sequence, event_hash FROM audit_events ORDER BY sequence DESC LIMIT 1", + &[], + ) + .await?; + let (sequence, previous_hash) = match last { + Some(row) => (from_db(row.int("sequence")?)? + 1, row.text("event_hash")?), + None => (1, GENESIS_HASH.to_owned()), + }; + let previous_hash = Sha256Digest::parse_hex(&previous_hash).map_err(|error| { + tracing::error!(%error, "stored audit hash is invalid"); + Problem::internal() + })?; + let (profile_id, profile_revision) = record + .profile + .map_or((None, None), |(id, revision)| (Some(id), Some(revision))); + let mut event = AuditEvent { + sequence, + occurred_at_unix: now_unix, + recorded_at_unix: now_unix, + event_type: record.event_type.to_owned(), + actor: record.actor, + principal: record.principal, + project: record.project, + session: record.session, + grant: record.grant, + exception: record.exception, + profile_id, + profile_revision, + decision: record.decision, + deny_reason: record.deny_reason, + outcome: record.outcome, + target: record + .target + .map(|target| printable(&target.replace('?', ""), MAX_TARGET_BYTES)) + .filter(|target| !target.is_empty()), + detail: record + .detail + .map(|detail| printable(&detail, MAX_DETAIL_BYTES)) + .filter(|detail| !detail.is_empty()), + previous_hash, + event_hash: None, + }; + let hash = event.compute_hash()?; + event.event_hash = Some(hash); + tx.execute( + "INSERT INTO audit_events (sequence, occurred_at_unix, recorded_at_unix, event_type, \ + actor_id, principal_id, project_id, session_id, grant_id, exception_id, profile_id, \ + profile_revision, decision, deny_reason, outcome, target_redacted, detail, \ + previous_hash, event_hash) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, \ + $13, $14, $15, $16, $17, $18, $19)", + &[ + to_db(event.sequence)?.into(), + to_db(event.occurred_at_unix)?.into(), + to_db(event.recorded_at_unix)?.into(), + event.event_type.clone().into(), + event.actor.clone().into(), + event.principal.clone().into(), + event.project.clone().into(), + event.session.clone().into(), + event.grant.clone().into(), + event.exception.clone().into(), + event.profile_id.clone().into(), + event.profile_revision.map(to_db).transpose()?.into(), + event.decision.map(|decision| code(&decision)).into(), + event + .deny_reason + .map(|reason| reason.code().to_owned()) + .into(), + event.outcome.map(|outcome| code(&outcome)).into(), + event.target.clone().into(), + event.detail.clone().into(), + event.previous_hash.to_string().into(), + hash.to_string().into(), + ], + ) + .await?; + Ok(sequence) +} + +fn code(value: &T) -> String { + serde_json::to_value(value) + .ok() + .and_then(|value| value.as_str().map(str::to_owned)) + .unwrap_or_default() +} + +fn parse Deserialize<'de>>(value: Option) -> Result, Problem> { + value + .map(|value| { + serde_json::from_value(serde_json::Value::String(value)).map_err(|error| { + tracing::error!(%error, "stored audit code is invalid"); + Problem::internal() + }) + }) + .transpose() +} + +const SELECT_EVENTS: &str = "SELECT sequence, occurred_at_unix, recorded_at_unix, event_type, \ + actor_id, principal_id, project_id, session_id, grant_id, exception_id, profile_id, \ + profile_revision, decision, deny_reason, outcome, target_redacted, detail, previous_hash, \ + event_hash FROM audit_events"; + +fn event_from_row(row: &Row) -> Result { + let digest = |value: String| { + Sha256Digest::parse_hex(&value).map_err(|error| { + tracing::error!(%error, "stored audit hash is invalid"); + Problem::internal() + }) + }; + Ok(AuditEvent { + sequence: from_db(row.int("sequence")?)?, + occurred_at_unix: from_db(row.int("occurred_at_unix")?)?, + recorded_at_unix: from_db(row.int("recorded_at_unix")?)?, + event_type: row.text("event_type")?, + actor: row.opt_text("actor_id")?, + principal: row.opt_text("principal_id")?, + project: row.opt_text("project_id")?, + session: row.opt_text("session_id")?, + grant: row.opt_text("grant_id")?, + exception: row.opt_text("exception_id")?, + profile_id: row.opt_text("profile_id")?, + profile_revision: row.opt_int("profile_revision")?.map(from_db).transpose()?, + decision: parse(row.opt_text("decision")?)?, + deny_reason: parse(row.opt_text("deny_reason")?)?, + outcome: parse(row.opt_text("outcome")?)?, + target: row.opt_text("target_redacted")?, + detail: row.opt_text("detail")?, + previous_hash: digest(row.text("previous_hash")?)?, + event_hash: Some(digest(row.text("event_hash")?)?), + }) +} + +/// Filters for one page of events, oldest first. +#[derive(Debug, Clone, Default)] +pub struct EventFilter { + pub project: Option, + pub session: Option, + pub principal: Option, + pub exception: Option, + pub after_sequence: u64, + pub limit: u32, +} + +pub async fn query(database: &Database, filter: &EventFilter) -> Result, Problem> { + let mut sql = format!("{SELECT_EVENTS} WHERE sequence > $1"); + let mut args = vec![Arg::from(to_db(filter.after_sequence)?)]; + for (column, value) in [ + ("project_id", &filter.project), + ("session_id", &filter.session), + ("principal_id", &filter.principal), + ("exception_id", &filter.exception), + ] { + if let Some(value) = value { + args.push(Arg::from(value.clone())); + sql.push_str(&format!(" AND {column} = ${}", args.len())); + } + } + args.push(Arg::from(i64::from(filter.limit))); + sql.push_str(&format!(" ORDER BY sequence LIMIT ${}", args.len())); + database + .fetch_all(&sql, &args) + .await? + .iter() + .map(event_from_row) + .collect() +} + +/// Result of recomputing the whole chain. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ChainVerification { + pub events: u64, + pub head_hash: Sha256Digest, + pub valid: bool, + #[serde(skip_serializing_if = "Option::is_none", default)] + pub first_invalid_sequence: Option, +} + +/// Recomputes every event hash and link, in pages. +pub async fn verify_chain(database: &Database) -> Result { + const PAGE: i64 = 1000; + let mut previous = Sha256Digest::parse_hex(GENESIS_HASH).map_err(|_| Problem::internal())?; + let mut expected_sequence = 1; + let mut after = 0_i64; + loop { + let rows = database + .fetch_all( + &format!("{SELECT_EVENTS} WHERE sequence > $1 ORDER BY sequence LIMIT $2"), + &[Arg::from(after), Arg::from(PAGE)], + ) + .await?; + if rows.is_empty() { + break; + } + for row in &rows { + let event = event_from_row(row)?; + let valid = event.sequence == expected_sequence + && event.previous_hash == previous + && event.event_hash == Some(event.compute_hash()?); + if !valid { + return Ok(ChainVerification { + events: expected_sequence - 1, + head_hash: previous, + valid: false, + first_invalid_sequence: Some(event.sequence), + }); + } + previous = event.event_hash.unwrap_or(previous); + expected_sequence += 1; + after = to_db(event.sequence)?; + } + } + Ok(ChainVerification { + events: expected_sequence - 1, + head_hash: previous, + valid: true, + first_invalid_sequence: None, + }) +} diff --git a/crates/fleet-server/src/auth.rs b/crates/fleet-server/src/auth.rs index 7f7b6f4..9c3007f 100644 --- a/crates/fleet-server/src/auth.rs +++ b/crates/fleet-server/src/auth.rs @@ -7,8 +7,10 @@ //! `X-Forwarded-User` or a principal field inside a request body, are never //! treated as authenticated identity. //! -//! No identity provider is wired up yet, so the production authenticator, -//! [`UnconfiguredAuthenticator`], rejects every token. +//! The production authenticator, [`DatabaseAuthenticator`], accepts opaque +//! tokens issued with `sendbox-fleet admin token issue`. Only their SHA-256 is +//! stored; a token is accepted while it is unexpired, unrevoked, and its +//! principal is not disabled. use std::future::{Future, Ready, ready}; use std::pin::Pin; @@ -19,30 +21,30 @@ use actix_web::dev::{Payload, ServiceRequest, ServiceResponse}; use actix_web::http::header; use actix_web::middleware::Next; use actix_web::{Error, FromRequest, HttpMessage, HttpRequest, ResponseError, web}; -use sendbox_governance::PrincipalId; +use base64::Engine as _; +pub use sendbox_governance::api::CallerKind; +use sendbox_governance::{Clock, PrincipalId}; +use sha2::{Digest, Sha256}; use thiserror::Error; +use crate::db::{Arg, Database}; use crate::problem::Problem; +/// Prefix of tokens this service issues, so leaked tokens are recognizable. +pub const TOKEN_PREFIX: &str = "sbf_"; + const MAX_TOKEN_BYTES: usize = 4096; const CHALLENGE: &str = r#"Bearer realm="sendbox-fleet""#; const CHALLENGE_INVALID_REQUEST: &str = r#"Bearer realm="sendbox-fleet", error="invalid_request""#; const CHALLENGE_INVALID_TOKEN: &str = r#"Bearer realm="sendbox-fleet", error="invalid_token""#; -/// What kind of authenticated party is calling. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum CallerKind { - /// A person using the management API. - User, - /// A SendBox host acting for sessions it runs. - Worker, -} - /// An authenticated caller. Only an [`Authenticator`] creates one. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Caller { pub principal: PrincipalId, pub kind: CallerKind, + /// Fleet-wide operator: publishes profiles and creates projects. + pub operator: bool, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Error)] @@ -51,6 +53,8 @@ pub enum AuthError { NotConfigured, #[error("bearer token was not accepted")] InvalidToken, + #[error("authentication is temporarily unavailable")] + Unavailable, } pub type AuthFuture<'a> = Pin> + Send + 'a>>; @@ -60,17 +64,81 @@ pub trait Authenticator: Send + Sync + 'static { fn authenticate<'a>(&'a self, bearer_token: &'a str) -> AuthFuture<'a>; } -/// The authenticator used until an identity provider is integrated: it -/// rejects every token. -#[derive(Debug, Default, Clone, Copy)] -pub struct UnconfiguredAuthenticator; +/// Accepts tokens recorded in `api_tokens`. +pub struct DatabaseAuthenticator { + database: Database, + clock: Arc, +} + +impl DatabaseAuthenticator { + #[must_use] + pub fn new(database: Database, clock: Arc) -> Self { + Self { database, clock } + } +} -impl Authenticator for UnconfiguredAuthenticator { - fn authenticate<'a>(&'a self, _bearer_token: &'a str) -> AuthFuture<'a> { - Box::pin(async { Err(AuthError::NotConfigured) }) +impl Authenticator for DatabaseAuthenticator { + fn authenticate<'a>(&'a self, bearer_token: &'a str) -> AuthFuture<'a> { + Box::pin(async move { + if !bearer_token.starts_with(TOKEN_PREFIX) { + return Err(AuthError::InvalidToken); + } + let now = i64::try_from(self.clock.now_unix()).map_err(|_| AuthError::Unavailable)?; + let row = self + .database + .fetch_optional( + "SELECT p.id AS principal, p.kind AS kind, p.is_operator AS operator \ + FROM api_tokens t JOIN principals p ON p.id = t.principal_id \ + WHERE t.token_sha256 = $1 AND t.revoked_at_unix IS NULL \ + AND t.expires_at_unix > $2 AND p.disabled_at_unix IS NULL", + &[Arg::from(token_digest(bearer_token)), Arg::from(now)], + ) + .await + .map_err(|error| { + tracing::error!(%error, "token lookup failed"); + AuthError::Unavailable + })? + .ok_or(AuthError::InvalidToken)?; + let caller = (|| { + let principal = PrincipalId::new(row.text("principal").ok()?).ok()?; + let kind = match row.text("kind").ok()?.as_str() { + "user" => CallerKind::User, + "worker" => CallerKind::Worker, + _ => return None, + }; + Some(Caller { + principal, + kind, + operator: row.flag("operator").ok()?, + }) + })(); + caller.ok_or_else(|| { + tracing::error!("stored principal row is invalid"); + AuthError::Unavailable + }) + }) } } +/// A new token and the SHA-256 digest that is stored in its place. +#[must_use] +pub fn token_from_bytes(bytes: &[u8; 32]) -> (String, String) { + let token = format!( + "{TOKEN_PREFIX}{}", + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes) + ); + let digest = token_digest(&token); + (token, digest) +} + +#[must_use] +pub fn token_digest(token: &str) -> String { + Sha256::digest(token.as_bytes()) + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + /// Shared handle stored in application data. pub type SharedAuthenticator = web::Data; @@ -143,7 +211,12 @@ fn valid_token(token: &str) -> bool { } fn rejection(error: AuthError) -> Problem { - Problem::unauthorized(error.to_string(), CHALLENGE_INVALID_TOKEN) + match error { + AuthError::Unavailable => Problem::service_unavailable(error.to_string()), + AuthError::NotConfigured | AuthError::InvalidToken => { + Problem::unauthorized(error.to_string(), CHALLENGE_INVALID_TOKEN) + } + } } /// Extracts the caller authenticated by [`require_bearer`]. Rejects the @@ -174,6 +247,17 @@ mod tests { use super::*; + #[test] + fn issued_tokens_are_bearer_tokens_stored_only_as_digests() { + let (token, digest) = token_from_bytes(&[7; 32]); + assert!(token.starts_with(TOKEN_PREFIX)); + assert!(valid_token(&token)); + assert_eq!(digest.len(), 64); + assert!(!digest.contains(&token[TOKEN_PREFIX.len()..])); + assert_eq!(token_digest(&token), digest); + assert_ne!(token_from_bytes(&[8; 32]).1, digest); + } + #[test] fn bearer_token_grammar_is_enforced() { let token = |value: &str| { diff --git a/crates/fleet-server/src/config.rs b/crates/fleet-server/src/config.rs index 2ddf155..4c5f609 100644 --- a/crates/fleet-server/src/config.rs +++ b/crates/fleet-server/src/config.rs @@ -13,18 +13,95 @@ pub const DATABASE_URL_VAR: &str = "FLEET_DATABASE_URL"; pub const LOG_DIR_VAR: &str = "FLEET_LOG_DIR"; pub const LOG_LEVEL_VAR: &str = "FLEET_LOG_LEVEL"; pub const LOG_RETENTION_DAYS_VAR: &str = "FLEET_LOG_RETENTION_DAYS"; +pub const AUTHORITY_ID_VAR: &str = "FLEET_AUTHORITY_ID"; +pub const PROFILE_TRUST_VAR: &str = "FLEET_PROFILE_TRUST"; const DEFAULT_BIND: &str = "127.0.0.1:8080"; const DEFAULT_LOG_DIR: &str = "./logs"; const DEFAULT_LOG_LEVEL: &str = "info,sqlx=warn"; const DEFAULT_LOG_RETENTION_DAYS: u32 = 30; const MAX_LOG_RETENTION_DAYS: u32 = 3650; +const DEFAULT_AUTHORITY_ID: &str = "sendbox-fleet"; +const MAX_TRUST_BYTES: u64 = 256 * 1024; +const MAX_TRUSTED_SIGNERS: usize = 32; #[derive(Debug, Clone)] pub struct Config { pub bind: SocketAddr, pub database_url: DatabaseUrl, pub logging: LogConfig, + /// The `authority` id hosts put in their operator configuration and bind + /// into every session. + pub authority_id: String, + /// File listing the operator signers that published profiles must satisfy. + pub profile_trust: Option, +} + +/// The signer set and threshold for profile publication. Same shape as the +/// `trust` section of a host's operator configuration. +#[derive(Debug, Clone, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ProfileTrust { + pub threshold: usize, + pub signers: Vec, +} + +impl ProfileTrust { + /// Reads and validates the trust file, returning a store that requires + /// `threshold` distinct, valid signers and never accepts unsigned input. + pub fn load( + path: &std::path::Path, + ) -> Result { + use std::io::Read as _; + let invalid = |reason: String| ConfigError::Invalid { + name: PROFILE_TRUST_VAR, + reason, + }; + let mut bytes = Vec::new(); + std::fs::File::open(path) + .and_then(|file| file.take(MAX_TRUST_BYTES + 1).read_to_end(&mut bytes)) + .map_err(|error| invalid(format!("cannot read {}: {error}", path.display())))?; + if bytes.len() as u64 > MAX_TRUST_BYTES { + return Err(invalid(format!( + "{} exceeds {MAX_TRUST_BYTES} bytes", + path.display() + ))); + } + let text = std::str::from_utf8(&bytes).map_err(|_| invalid("must be UTF-8".to_owned()))?; + let trust: Self = + serde_yaml_ng::from_str(text).map_err(|error| invalid(error.to_string()))?; + let fingerprints = trust + .signers + .iter() + .map(|signer| signer.fingerprint.as_str()) + .collect::>(); + if trust.signers.is_empty() + || trust.signers.len() > MAX_TRUSTED_SIGNERS + || fingerprints.len() != trust.signers.len() + { + return Err(invalid(format!( + "signers must list 1 to {MAX_TRUSTED_SIGNERS} distinct identities" + ))); + } + if trust.threshold == 0 || trust.threshold > trust.signers.len() { + return Err(invalid( + "threshold must be between 1 and the number of signers".to_owned(), + )); + } + let mut store = sendbox_security::provenance::TrustStore::new( + sendbox_security::provenance::TrustPolicy { + allow_unsigned: false, + threshold: trust.threshold, + required_signers: std::collections::BTreeSet::new(), + }, + ); + for signer in trust.signers { + store + .add_identity(signer) + .map_err(|error| invalid(format!("signer: {error}")))?; + } + Ok(store) + } } #[derive(Debug, Clone, PartialEq, Eq)] @@ -189,6 +266,22 @@ impl Config { })?, }; + let authority_id = + text(AUTHORITY_ID_VAR)?.unwrap_or_else(|| DEFAULT_AUTHORITY_ID.to_owned()); + if authority_id.is_empty() + || authority_id.len() > 128 + || authority_id == "local" + || !authority_id.bytes().all(|byte| byte.is_ascii_graphic()) + { + return Err(ConfigError::Invalid { + name: AUTHORITY_ID_VAR, + reason: "must be 1 to 128 printable ASCII bytes and not `local`".to_owned(), + }); + } + let profile_trust = lookup(PROFILE_TRUST_VAR) + .filter(|value| !value.is_empty()) + .map(PathBuf::from); + Ok(Self { bind, database_url, @@ -197,6 +290,8 @@ impl Config { filter, retention_days, }, + authority_id, + profile_trust, }) } } @@ -222,6 +317,8 @@ mod tests { assert_eq!(config.database_url.kind(), DatabaseKind::Sqlite); assert_eq!(config.logging.dir, PathBuf::from("./logs")); assert_eq!(config.logging.retention_days, 30); + assert_eq!(config.authority_id, "sendbox-fleet"); + assert!(config.profile_trust.is_none()); } #[test] @@ -250,6 +347,8 @@ mod tests { (LOG_LEVEL_VAR, "fleet_server=loud"), (LOG_RETENTION_DAYS_VAR, "0"), (LOG_RETENTION_DAYS_VAR, "thirty"), + (AUTHORITY_ID_VAR, "local"), + (AUTHORITY_ID_VAR, "has space"), ] { match config(&[base, (name, value)]) { Err(ConfigError::Invalid { name: reported, .. }) => assert_eq!(reported, name), diff --git a/crates/fleet-server/src/db.rs b/crates/fleet-server/src/db.rs index 839c758..fe61893 100644 --- a/crates/fleet-server/src/db.rs +++ b/crates/fleet-server/src/db.rs @@ -8,9 +8,9 @@ use std::str::FromStr; use std::time::Duration; use sqlx::migrate::{MigrateError, Migrator}; -use sqlx::postgres::{PgConnectOptions, PgPoolOptions}; -use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions}; -use sqlx::{PgPool, SqlitePool}; +use sqlx::postgres::{PgConnectOptions, PgPoolOptions, PgRow}; +use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteRow}; +use sqlx::{PgPool, Postgres, Row as _, Sqlite, SqlitePool, Transaction}; use thiserror::Error; use crate::config::{DatabaseKind, DatabaseUrl}; @@ -20,6 +20,9 @@ static SQLITE_MIGRATIONS: Migrator = sqlx::migrate!("../../migrations/sqlite"); const MAX_CONNECTIONS: u32 = 16; const ACQUIRE_TIMEOUT: Duration = Duration::from_secs(5); +/// Transaction-scoped PostgreSQL advisory lock that serializes writers, so +/// check-then-write decisions and the audit hash chain never race. +const WRITE_LOCK_KEY: i64 = 0x5345_4e44_424f_5846; #[derive(Debug, Error)] pub enum DbError { @@ -72,6 +75,7 @@ impl Database { source, })? .foreign_keys(true) + .busy_timeout(ACQUIRE_TIMEOUT) .journal_mode(if in_memory { SqliteJournalMode::Memory } else { @@ -136,4 +140,245 @@ impl Database { Self::Sqlite(pool) => pool.close().await, } } + + /// Starts a write transaction. Writers are serialized: SQLite takes the + /// write lock up front (`BEGIN IMMEDIATE`) and PostgreSQL takes a + /// transaction-scoped advisory lock. + pub async fn begin_write(&self) -> Result { + match self { + Self::Postgres(pool) => { + let mut transaction = pool.begin().await?; + sqlx::query("SELECT pg_advisory_xact_lock($1)") + .bind(WRITE_LOCK_KEY) + .execute(&mut *transaction) + .await?; + Ok(Tx::Postgres(transaction)) + } + Self::Sqlite(pool) => Ok(Tx::Sqlite(pool.begin_with("BEGIN IMMEDIATE").await?)), + } + } + + /// Runs a read-only query outside a transaction. + pub async fn fetch_all(&self, sql: &str, args: &[Arg]) -> Result, DbError> { + match self { + Self::Postgres(pool) => Ok(bind_pg(sqlx::query(sql), args) + .fetch_all(pool) + .await? + .into_iter() + .map(Row::Postgres) + .collect()), + Self::Sqlite(pool) => Ok(bind_sqlite(sqlx::query(sql), args) + .fetch_all(pool) + .await? + .into_iter() + .map(Row::Sqlite) + .collect()), + } + } + + pub async fn fetch_optional(&self, sql: &str, args: &[Arg]) -> Result, DbError> { + Ok(self.fetch_all(sql, args).await?.into_iter().next()) + } + + /// `CAST($n AS JSON)` on PostgreSQL, `$n` on SQLite, for binding JSON text. + #[must_use] + pub fn json_param(&self, index: usize, binary: bool) -> String { + json_param(self.kind(), index, binary) + } +} + +fn json_param(kind: DatabaseKind, index: usize, binary: bool) -> String { + match (kind, binary) { + (DatabaseKind::Postgres, true) => format!("CAST(${index} AS JSONB)"), + (DatabaseKind::Postgres, false) => format!("CAST(${index} AS JSON)"), + (DatabaseKind::Sqlite, _) => format!("${index}"), + } +} + +/// A bound query parameter. SQL uses `$1`, `$2`, ... on both backends. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Arg { + Text(Option), + Int(Option), + Bytes(Vec), + Bool(bool), +} + +impl From<&str> for Arg { + fn from(value: &str) -> Self { + Self::Text(Some(value.to_owned())) + } +} + +impl From for Arg { + fn from(value: String) -> Self { + Self::Text(Some(value)) + } +} + +impl From> for Arg { + fn from(value: Option) -> Self { + Self::Text(value) + } +} + +impl From for Arg { + fn from(value: i64) -> Self { + Self::Int(Some(value)) + } +} + +impl From> for Arg { + fn from(value: Option) -> Self { + Self::Int(value) + } +} + +impl From for Arg { + fn from(value: bool) -> Self { + Self::Bool(value) + } +} + +impl From> for Arg { + fn from(value: Vec) -> Self { + Self::Bytes(value) + } +} + +type PgQuery<'q> = sqlx::query::Query<'q, Postgres, sqlx::postgres::PgArguments>; +type SqliteQuery<'q> = sqlx::query::Query<'q, Sqlite, sqlx::sqlite::SqliteArguments<'q>>; + +fn bind_pg<'q>(mut query: PgQuery<'q>, args: &'q [Arg]) -> PgQuery<'q> { + for arg in args { + query = match arg { + Arg::Text(value) => query.bind(value.as_deref()), + Arg::Int(value) => query.bind(*value), + Arg::Bytes(value) => query.bind(value.as_slice()), + Arg::Bool(value) => query.bind(*value), + }; + } + query +} + +fn bind_sqlite<'q>(mut query: SqliteQuery<'q>, args: &'q [Arg]) -> SqliteQuery<'q> { + for arg in args { + query = match arg { + Arg::Text(value) => query.bind(value.as_deref()), + Arg::Int(value) => query.bind(*value), + Arg::Bytes(value) => query.bind(value.as_slice()), + Arg::Bool(value) => query.bind(*value), + }; + } + query +} + +/// A write transaction. Dropping it without [`Tx::commit`] rolls back. +pub enum Tx { + Postgres(Transaction<'static, Postgres>), + Sqlite(Transaction<'static, Sqlite>), +} + +impl Tx { + #[must_use] + pub const fn kind(&self) -> DatabaseKind { + match self { + Self::Postgres(_) => DatabaseKind::Postgres, + Self::Sqlite(_) => DatabaseKind::Sqlite, + } + } + + #[must_use] + pub fn json_param(&self, index: usize, binary: bool) -> String { + json_param(self.kind(), index, binary) + } + + /// Executes a statement and returns the number of affected rows. + pub async fn execute(&mut self, sql: &str, args: &[Arg]) -> Result { + Ok(match self { + Self::Postgres(transaction) => bind_pg(sqlx::query(sql), args) + .execute(&mut **transaction) + .await? + .rows_affected(), + Self::Sqlite(transaction) => bind_sqlite(sqlx::query(sql), args) + .execute(&mut **transaction) + .await? + .rows_affected(), + }) + } + + pub async fn fetch_all(&mut self, sql: &str, args: &[Arg]) -> Result, DbError> { + Ok(match self { + Self::Postgres(transaction) => bind_pg(sqlx::query(sql), args) + .fetch_all(&mut **transaction) + .await? + .into_iter() + .map(Row::Postgres) + .collect(), + Self::Sqlite(transaction) => bind_sqlite(sqlx::query(sql), args) + .fetch_all(&mut **transaction) + .await? + .into_iter() + .map(Row::Sqlite) + .collect(), + }) + } + + pub async fn fetch_optional( + &mut self, + sql: &str, + args: &[Arg], + ) -> Result, DbError> { + Ok(self.fetch_all(sql, args).await?.into_iter().next()) + } + + pub async fn commit(self) -> Result<(), DbError> { + match self { + Self::Postgres(transaction) => transaction.commit().await?, + Self::Sqlite(transaction) => transaction.commit().await?, + } + Ok(()) + } +} + +/// A result row with typed, backend-neutral accessors. +pub enum Row { + Postgres(PgRow), + Sqlite(SqliteRow), +} + +macro_rules! row_get { + ($row:expr, $column:expr, $kind:ty) => { + match $row { + Row::Postgres(row) => row.try_get::<$kind, _>($column), + Row::Sqlite(row) => row.try_get::<$kind, _>($column), + } + .map_err(DbError::from) + }; +} + +impl Row { + pub fn text(&self, column: &str) -> Result { + row_get!(self, column, String) + } + + pub fn opt_text(&self, column: &str) -> Result, DbError> { + row_get!(self, column, Option) + } + + pub fn int(&self, column: &str) -> Result { + row_get!(self, column, i64) + } + + pub fn opt_int(&self, column: &str) -> Result, DbError> { + row_get!(self, column, Option) + } + + pub fn bytes(&self, column: &str) -> Result, DbError> { + row_get!(self, column, Vec) + } + + pub fn flag(&self, column: &str) -> Result { + row_get!(self, column, bool) + } } diff --git a/crates/fleet-server/src/governance.rs b/crates/fleet-server/src/governance.rs new file mode 100644 index 0000000..6f3951e --- /dev/null +++ b/crates/fleet-server/src/governance.rs @@ -0,0 +1,499 @@ +//! Domain lookups shared by the `/v1` handlers: project roles, profile +//! revisions, sessions, grants, and exceptions. +//! +//! Every check reads stored state. Request bodies only ever supply claims to +//! compare against it. + +use std::future::Future; +use std::pin::Pin; + +use sendbox_governance::{ + CredentialGrant, CurrentProfile, DenyReason, ExceptionId, ExceptionKind, ExceptionScope, + ExceptionStatus, GovernanceBinding, GovernanceProfile, GrantId, PolicyException, PrincipalId, + ProfileId, ProfileRef, ProjectId, RevocationReason, SessionRef, Sha256Digest, +}; +use serde::{Deserialize, Serialize}; + +use crate::db::{Arg, Database, DbError, Row, Tx}; +use crate::problem::Problem; +use crate::state::{from_db, to_db}; + +/// Ordered from most to least privileged. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ProjectRole { + /// Manages roles, approves exceptions, and runs sessions. + Owner, + /// Approves exceptions, revokes grants, and runs sessions. + Admin, + /// Runs governed sessions and requests exceptions. + Member, + /// Reads roles, exceptions, and audit events. + Viewer, +} + +impl ProjectRole { + #[must_use] + pub const fn code(self) -> &'static str { + match self { + Self::Owner => "owner", + Self::Admin => "admin", + Self::Member => "member", + Self::Viewer => "viewer", + } + } + + fn parse(value: &str) -> Option { + match value { + "owner" => Some(Self::Owner), + "admin" => Some(Self::Admin), + "member" => Some(Self::Member), + "viewer" => Some(Self::Viewer), + _ => None, + } + } + + /// Whether this role grants at least `minimum`. + #[must_use] + pub fn at_least(self, minimum: Self) -> bool { + self <= minimum + } +} + +type RowsFuture<'a> = Pin, DbError>> + 'a>>; + +/// Runs read queries on a pool or inside a write transaction. +pub trait Reader { + fn rows<'a>(&'a mut self, sql: &'a str, args: &'a [Arg]) -> RowsFuture<'a>; +} + +impl Reader for Tx { + fn rows<'a>(&'a mut self, sql: &'a str, args: &'a [Arg]) -> RowsFuture<'a> { + Box::pin(self.fetch_all(sql, args)) + } +} + +impl Reader for Database { + fn rows<'a>(&'a mut self, sql: &'a str, args: &'a [Arg]) -> RowsFuture<'a> { + Box::pin(self.fetch_all(sql, args)) + } +} + +async fn first(reader: &mut impl Reader, sql: &str, args: &[Arg]) -> Result, Problem> { + Ok(reader.rows(sql, args).await?.into_iter().next()) +} + +fn corrupt(what: &str) -> Problem { + tracing::error!(what, "stored record is invalid"); + Problem::internal() +} + +pub async fn role_of( + reader: &mut impl Reader, + project: &ProjectId, + principal: &PrincipalId, +) -> Result, Problem> { + first( + reader, + "SELECT role FROM role_bindings WHERE project_id = $1 AND principal_id = $2", + &[project.as_str().into(), principal.as_str().into()], + ) + .await? + .map(|row| ProjectRole::parse(&row.text("role")?).ok_or_else(|| corrupt("role"))) + .transpose() +} + +pub async fn project_exists( + reader: &mut impl Reader, + project: &ProjectId, +) -> Result { + Ok(first( + reader, + "SELECT id FROM projects WHERE id = $1 AND archived_at_unix IS NULL", + &[project.as_str().into()], + ) + .await? + .is_some()) +} + +pub async fn principal_active( + reader: &mut impl Reader, + principal: &PrincipalId, +) -> Result { + Ok(first( + reader, + "SELECT id FROM principals WHERE id = $1 AND disabled_at_unix IS NULL", + &[principal.as_str().into()], + ) + .await? + .is_some()) +} + +/// The newest revision of a profile that has reached `not_before_unix`. +#[derive(Debug, Clone)] +pub struct StoredProfile { + pub reference: ProfileRef, + pub minimum_revision: u64, + pub not_before_unix: u64, + pub expires_at_unix: u64, + pub document: Vec, +} + +impl StoredProfile { + #[must_use] + pub fn current(&self) -> CurrentProfile { + CurrentProfile { + reference: self.reference.clone(), + minimum_revision: self.minimum_revision, + expires_at_unix: self.expires_at_unix, + } + } + + pub fn parse(&self) -> Result { + GovernanceProfile::parse(&self.document).map_err(|_| corrupt("profile")) + } +} + +const SELECT_PROFILE: &str = "SELECT p.id, p.revision, p.sha256, p.signed_bytes, \ + p.not_before_unix, p.expires_at_unix, COALESCE(m.minimum_revision, 1) AS minimum_revision \ + FROM profiles p LEFT JOIN profile_minimum_revisions m ON m.profile_id = p.id"; + +fn profile_from_row(row: &Row) -> Result { + Ok(StoredProfile { + reference: ProfileRef { + id: ProfileId::new(row.text("id")?).map_err(|_| corrupt("profile id"))?, + revision: from_db(row.int("revision")?)?, + sha256: Sha256Digest::parse_hex(&row.text("sha256")?) + .map_err(|_| corrupt("profile digest"))?, + }, + minimum_revision: from_db(row.int("minimum_revision")?)?, + not_before_unix: from_db(row.int("not_before_unix")?)?, + expires_at_unix: from_db(row.int("expires_at_unix")?)?, + document: row.bytes("signed_bytes")?, + }) +} + +pub async fn current_profile( + reader: &mut impl Reader, + id: &ProfileId, + now_unix: u64, +) -> Result, Problem> { + first( + reader, + &format!( + "{SELECT_PROFILE} WHERE p.id = $1 AND p.not_before_unix <= $2 \ + ORDER BY p.revision DESC LIMIT 1" + ), + &[id.as_str().into(), to_db(now_unix)?.into()], + ) + .await? + .map(|row| profile_from_row(&row)) + .transpose() +} + +pub async fn profile_revision( + reader: &mut impl Reader, + id: &ProfileId, + revision: u64, +) -> Result, Problem> { + first( + reader, + &format!("{SELECT_PROFILE} WHERE p.id = $1 AND p.revision = $2"), + &[id.as_str().into(), to_db(revision)?.into()], + ) + .await? + .map(|row| profile_from_row(&row)) + .transpose() +} + +/// Loads the current revision and requires `reference` to be exactly it, +/// at or above the minimum and unexpired. +pub async fn require_current( + reader: &mut impl Reader, + reference: &ProfileRef, + now_unix: u64, +) -> Result { + let current = current_profile(reader, &reference.id, now_unix) + .await + .map_err(|_| DenyReason::AuthorityUnavailable)? + .ok_or(DenyReason::StalePolicy)?; + sendbox_governance::check_current(reference, ¤t.current(), now_unix)?; + Ok(current) +} + +const SELECT_EXCEPTION: &str = "SELECT id, project_id, principal_id, profile_id, \ + profile_revision, profile_sha256, scope_kind, scope_value, reason, status, requested_by, \ + requested_at_unix, decided_by, decided_at_unix, expires_at_unix, revoked_by, \ + revoked_at_unix FROM exceptions"; + +fn exception_from_row(row: &Row) -> Result { + let principal = |value: Option| { + value + .map(|value| PrincipalId::new(value).map_err(|_| corrupt("exception principal"))) + .transpose() + }; + Ok(PolicyException { + id: ExceptionId::new(row.text("id")?).map_err(|_| corrupt("exception id"))?, + project: ProjectId::new(row.text("project_id")?).map_err(|_| corrupt("project"))?, + principal: principal(row.opt_text("principal_id")?)?, + profile: ProfileRef { + id: ProfileId::new(row.text("profile_id")?).map_err(|_| corrupt("profile id"))?, + revision: from_db(row.int("profile_revision")?)?, + sha256: Sha256Digest::parse_hex(&row.text("profile_sha256")?) + .map_err(|_| corrupt("profile digest"))?, + }, + scope: ExceptionScope { + kind: match row.text("scope_kind")?.as_str() { + "command" => ExceptionKind::Command, + "domain" => ExceptionKind::Domain, + "network" => ExceptionKind::Network, + _ => return Err(corrupt("exception kind")), + }, + value: row.text("scope_value")?, + }, + reason: row.text("reason")?, + status: match row.text("status")?.as_str() { + "pending" => ExceptionStatus::Pending, + "approved" => ExceptionStatus::Approved, + "rejected" => ExceptionStatus::Rejected, + _ => return Err(corrupt("exception status")), + }, + requested_by: PrincipalId::new(row.text("requested_by")?) + .map_err(|_| corrupt("requester"))?, + requested_at_unix: from_db(row.int("requested_at_unix")?)?, + decided_by: principal(row.opt_text("decided_by")?)?, + decided_at_unix: row.opt_int("decided_at_unix")?.map(from_db).transpose()?, + expires_at_unix: from_db(row.int("expires_at_unix")?)?, + revoked_by: principal(row.opt_text("revoked_by")?)?, + revoked_at_unix: row.opt_int("revoked_at_unix")?.map(from_db).transpose()?, + }) +} + +pub async fn exception( + reader: &mut impl Reader, + id: &ExceptionId, +) -> Result, Problem> { + first( + reader, + &format!("{SELECT_EXCEPTION} WHERE id = $1"), + &[id.as_str().into()], + ) + .await? + .map(|row| exception_from_row(&row)) + .transpose() +} + +/// Which exceptions a listing returns. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ExceptionState { + /// Approved, unrevoked, and unexpired. + Active, + Pending, + #[default] + All, +} + +pub async fn project_exceptions( + reader: &mut impl Reader, + project: &ProjectId, + state: ExceptionState, + now_unix: u64, +) -> Result, Problem> { + let (filter, args): (&str, Vec) = match state { + ExceptionState::Active => ( + " AND status = 'approved' AND revoked_at_unix IS NULL AND expires_at_unix > $2", + vec![project.as_str().into(), to_db(now_unix)?.into()], + ), + ExceptionState::Pending => (" AND status = 'pending'", vec![project.as_str().into()]), + ExceptionState::All => ("", vec![project.as_str().into()]), + }; + reader + .rows( + &format!( + "{SELECT_EXCEPTION} WHERE project_id = $1{filter} ORDER BY requested_at_unix, id LIMIT 500" + ), + &args, + ) + .await? + .iter() + .map(exception_from_row) + .collect() +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SessionStatus { + Admitted, + Ended, +} + +/// An admitted session as stored. +#[derive(Debug, Clone)] +pub struct StoredSession { + pub session: SessionRef, + pub binding: GovernanceBinding, + pub binding_sha256: Sha256Digest, + pub status: SessionStatus, +} + +pub async fn session( + reader: &mut impl Reader, + id: &SessionRef, +) -> Result, Problem> { + let Some(row) = first( + reader, + "SELECT id, CAST(binding AS TEXT) AS binding, binding_sha256, status FROM sessions \ + WHERE id = $1", + &[id.as_str().into()], + ) + .await? + else { + return Ok(None); + }; + Ok(Some(StoredSession { + session: SessionRef::new(row.text("id")?).map_err(|_| corrupt("session id"))?, + binding: serde_json::from_str(&row.text("binding")?).map_err(|_| corrupt("binding"))?, + binding_sha256: Sha256Digest::parse_hex(&row.text("binding_sha256")?) + .map_err(|_| corrupt("binding digest"))?, + status: if row.text("status")? == "admitted" { + SessionStatus::Admitted + } else { + SessionStatus::Ended + }, + })) +} + +/// Checks that every exception a session was admitted with is still +/// approved, unrevoked, unexpired, and bound to the session's revision. +/// Returns the earliest exception expiry, which caps grant lifetimes. +pub async fn session_exceptions( + reader: &mut impl Reader, + session: &StoredSession, + now_unix: u64, +) -> Result, DenyReason> { + let mut earliest = None; + for id in &session.binding.exceptions { + let exception = exception(reader, id) + .await + .map_err(|_| DenyReason::AuthorityUnavailable)? + .ok_or(DenyReason::StalePolicy)?; + if !exception.applies_to( + &session.binding.project, + &session.binding.principal, + &session.binding.profile, + now_unix, + ) { + return Err(DenyReason::StalePolicy); + } + earliest = Some(earliest.map_or(exception.expires_at_unix, |current: u64| { + current.min(exception.expires_at_unix) + })); + } + Ok(earliest) +} + +/// A grant as stored, with its revocation state. +#[derive(Debug, Clone)] +pub struct StoredGrant { + pub grant: CredentialGrant, + pub revoked: Option, +} + +pub async fn grant(reader: &mut impl Reader, id: &GrantId) -> Result, Problem> { + let Some(row) = first( + reader, + "SELECT g.id, g.session_id, g.principal_id, g.project_id, g.binding_sha256, \ + g.profile_id, g.profile_revision, g.profile_sha256, g.service_id, \ + CAST(g.methods AS TEXT) AS methods, CAST(g.path_prefixes AS TEXT) AS path_prefixes, \ + g.issued_at_unix, g.lease_expires_at_unix, g.max_expires_at_unix, g.generation, \ + r.reason AS revocation FROM credential_grants g \ + LEFT JOIN revocations r ON r.grant_id = g.id WHERE g.id = $1", + &[id.as_str().into()], + ) + .await? + else { + return Ok(None); + }; + let text = |column: &str| row.text(column); + let grant = CredentialGrant { + contract_version: sendbox_governance::CONTRACT_VERSION, + grant_id: GrantId::new(text("id")?).map_err(|_| corrupt("grant id"))?, + principal: PrincipalId::new(text("principal_id")?).map_err(|_| corrupt("principal"))?, + project: ProjectId::new(text("project_id")?).map_err(|_| corrupt("project"))?, + session: SessionRef::new(text("session_id")?).map_err(|_| corrupt("session"))?, + binding_sha256: Sha256Digest::parse_hex(&text("binding_sha256")?) + .map_err(|_| corrupt("binding digest"))?, + profile: ProfileRef { + id: ProfileId::new(text("profile_id")?).map_err(|_| corrupt("profile id"))?, + revision: from_db(row.int("profile_revision")?)?, + sha256: Sha256Digest::parse_hex(&text("profile_sha256")?) + .map_err(|_| corrupt("profile digest"))?, + }, + service: sendbox_governance::ServiceId::new(text("service_id")?) + .map_err(|_| corrupt("service"))?, + methods: serde_json::from_str(&text("methods")?).map_err(|_| corrupt("methods"))?, + path_prefixes: serde_json::from_str(&text("path_prefixes")?) + .map_err(|_| corrupt("path prefixes"))?, + issued_at_unix: from_db(row.int("issued_at_unix")?)?, + lease_expires_at_unix: from_db(row.int("lease_expires_at_unix")?)?, + max_expires_at_unix: from_db(row.int("max_expires_at_unix")?)?, + generation: from_db(row.int("generation")?)?, + }; + let revoked = row + .opt_text("revocation")? + .map(|reason| { + serde_json::from_value(serde_json::Value::String(reason)) + .map_err(|_| corrupt("revocation reason")) + }) + .transpose()?; + Ok(Some(StoredGrant { grant, revoked })) +} + +/// Unrevoked grants of one session. +pub async fn live_grants( + reader: &mut impl Reader, + session: &SessionRef, +) -> Result, Problem> { + reader + .rows( + "SELECT g.id FROM credential_grants g LEFT JOIN revocations r ON r.grant_id = g.id \ + WHERE g.session_id = $1 AND r.grant_id IS NULL ORDER BY g.id", + &[session.as_str().into()], + ) + .await? + .iter() + .map(|row| GrantId::new(row.text("id")?).map_err(|_| corrupt("grant id"))) + .collect() +} + +/// Revokes one grant inside `tx`. New requests are denied at once; open +/// streams may finish within the profile's grace window (at most 60 seconds). +pub async fn revoke_grant( + tx: &mut Tx, + grant: &CredentialGrant, + reason: RevocationReason, + actor: Option<&PrincipalId>, + grace_seconds: u64, + now_unix: u64, +) -> Result<(), Problem> { + let generation = grant.generation.saturating_add(1); + tx.execute( + "INSERT INTO revocations (grant_id, reason, revoked_by, revoked_at_unix, \ + grace_expires_at_unix, generation) VALUES ($1, $2, $3, $4, $5, $6)", + &[ + grant.grant_id.as_str().into(), + reason.code().into(), + actor.map(ToString::to_string).into(), + to_db(now_unix)?.into(), + to_db(now_unix.saturating_add(grace_seconds.min(60)))?.into(), + to_db(generation)?.into(), + ], + ) + .await?; + tx.execute( + "UPDATE credential_grants SET generation = $2 WHERE id = $1", + &[grant.grant_id.as_str().into(), to_db(generation)?.into()], + ) + .await?; + Ok(()) +} diff --git a/crates/fleet-server/src/lib.rs b/crates/fleet-server/src/lib.rs index dfe4a4d..e2a3228 100644 --- a/crates/fleet-server/src/lib.rs +++ b/crates/fleet-server/src/lib.rs @@ -1,18 +1,22 @@ #![forbid(unsafe_code)] //! SendBox fleet: the shared governance service for governed sessions. //! -//! This crate is a scaffold for increment 2 of -//! . It serves health and -//! readiness probes, authenticates every `/v1` request, validates request -//! bodies against the shared `sendbox-governance` contract, and answers every -//! management operation with an explicit `501 Not Implemented` problem. +//! Increment 2 of : an +//! authenticated, multi-user management API and shared grant authority. +//! It enforces project-scoped roles, admits governed sessions, issues and +//! checks credential grants, records bounded, expiring exceptions, and keeps a +//! hash-chained central audit log. It never holds provider credentials. +pub mod admin; +pub mod audit; pub mod auth; pub mod config; pub mod db; +pub mod governance; pub mod logging; pub mod problem; pub mod routes; pub mod server; +pub mod state; pub use sendbox_governance::CONTRACT_VERSION; diff --git a/crates/fleet-server/src/main.rs b/crates/fleet-server/src/main.rs index 13134db..b33f4c3 100644 --- a/crates/fleet-server/src/main.rs +++ b/crates/fleet-server/src/main.rs @@ -2,10 +2,56 @@ use std::process::ExitCode; -use fleet_server::config::Config; +use clap::{Parser, Subcommand}; +use fleet_server::admin::{self, AdminCommand}; +use fleet_server::config::{Config, DATABASE_URL_VAR, DatabaseUrl}; use fleet_server::{logging, server}; +/// SendBox shared governance service. +#[derive(Debug, Parser)] +#[command(name = "sendbox-fleet", version)] +struct Cli { + #[command(subcommand)] + command: Option, +} + +#[derive(Debug, Subcommand)] +enum Command { + /// Serve the API (the default). + Serve, + /// Bootstrap principals, tokens, and projects directly in the database. + #[command(subcommand)] + Admin(AdminCommand), +} + fn main() -> ExitCode { + match Cli::parse().command { + None | Some(Command::Serve) => serve(), + Some(Command::Admin(command)) => run_admin(command), + } +} + +fn run_admin(command: AdminCommand) -> ExitCode { + let url = match std::env::var(DATABASE_URL_VAR) + .map_err(|_| format!("{DATABASE_URL_VAR} is required")) + .and_then(|url| DatabaseUrl::parse(&url).map_err(|error| error.to_string())) + { + Ok(url) => url, + Err(error) => { + eprintln!("sendbox-fleet: configuration error: {error}"); + return ExitCode::from(2); + } + }; + match actix_web::rt::System::new().block_on(admin::run(&url, command)) { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + eprintln!("sendbox-fleet admin: {error}"); + ExitCode::FAILURE + } + } +} + +fn serve() -> ExitCode { let config = match Config::from_env() { Ok(config) => config, Err(error) => { diff --git a/crates/fleet-server/src/problem.rs b/crates/fleet-server/src/problem.rs index 37e3e24..9f69e25 100644 --- a/crates/fleet-server/src/problem.rs +++ b/crates/fleet-server/src/problem.rs @@ -63,6 +63,34 @@ impl Problem { Self::new(StatusCode::NOT_FOUND, "no resource exists at this path") } + /// A named resource that does not exist. + #[must_use] + pub fn missing(detail: impl Into) -> Self { + Self::new(StatusCode::NOT_FOUND, detail) + } + + /// The caller is authenticated but not authorized for this operation. + #[must_use] + pub fn forbidden(detail: impl Into) -> Self { + Self::new(StatusCode::FORBIDDEN, detail) + } + + /// The request conflicts with current state, such as a stale profile + /// revision or an exception that was already decided. + #[must_use] + pub fn conflict(detail: impl Into) -> Self { + Self::new(StatusCode::CONFLICT, detail) + } + + /// An internal failure. The cause is logged, never returned. + #[must_use] + pub fn internal() -> Self { + Self::new( + StatusCode::INTERNAL_SERVER_ERROR, + "the request could not be completed; see the service logs", + ) + } + #[must_use] pub fn method_not_allowed() -> Self { Self::new( @@ -95,6 +123,13 @@ impl Problem { } } +impl From for Problem { + fn from(error: crate::db::DbError) -> Self { + tracing::error!(%error, "database operation failed"); + Self::internal() + } +} + impl ResponseError for Problem { fn status_code(&self) -> StatusCode { StatusCode::from_u16(self.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR) diff --git a/crates/fleet-server/src/routes/v1/audit.rs b/crates/fleet-server/src/routes/v1/audit.rs index a57b3b3..ac6f3c5 100644 --- a/crates/fleet-server/src/routes/v1/audit.rs +++ b/crates/fleet-server/src/routes/v1/audit.rs @@ -1,18 +1,19 @@ -//! `GET /v1/audit/events`: page through the central, hash-chained audit log. -//! Events carry a redacted request target and never credentials, headers, -//! or request bodies. +//! Central audit: page through events and verify the hash chain. +//! +//! Operators read every event. Anyone else must name a project in which they +//! hold a role, and sees only that project's events. use actix_web::web; -use sendbox_governance::{ - DenyReason, GrantId, PrincipalId, ProfileRef, ProjectId, SessionRef, Sha256Digest, -}; +use sendbox_governance::{ExceptionId, PrincipalId, ProjectId, SessionRef}; use serde::{Deserialize, Serialize}; -use super::Capability; +use super::{State, caller_role, require_operator}; +use crate::audit::{self, AuditEvent, ChainVerification, EventFilter}; use crate::auth::Authenticated; use crate::problem::Problem; use crate::routes::resource; +const DEFAULT_PAGE_SIZE: u32 = 100; const MAX_PAGE_SIZE: u32 = 500; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -21,48 +22,12 @@ pub struct AuditQuery { pub project: Option, pub session: Option, pub principal: Option, + pub exception: Option, /// Return events with a sequence number greater than this cursor. pub after_sequence: Option, pub limit: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum AuditDecision { - Allow, - Deny, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum AuditOutcome { - Succeeded, - Failed, - /// The external effect could not be confirmed, for example a revoked - /// grant whose in-flight upstream request may still have completed. - Unknown, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct AuditEvent { - pub sequence: u64, - pub occurred_at_unix: u64, - pub event_type: String, - pub principal: Option, - pub project: Option, - pub session: Option, - pub grant: Option, - pub profile: Option, - pub decision: Option, - pub deny_reason: Option, - pub outcome: Option, - /// Method, host, and path prefix only; never a query string or body. - pub target: Option, - pub previous_hash: Sha256Digest, - pub event_hash: Sha256Digest, -} - #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct AuditPage { @@ -71,20 +36,64 @@ pub struct AuditPage { } pub fn configure(config: &mut web::ServiceConfig) { - config.service(resource("/audit/events").route(web::get().to(list))); + config + .service(resource("/audit/events").route(web::get().to(list))) + .service(resource("/audit/verify").route(web::get().to(verify))); } async fn list( - _caller: Authenticated, + state: State, + Authenticated(caller): Authenticated, query: web::Query, ) -> Result, Problem> { - if query - .limit - .is_some_and(|limit| !(1..=MAX_PAGE_SIZE).contains(&limit)) - { + let query = query.into_inner(); + let limit = query.limit.unwrap_or(DEFAULT_PAGE_SIZE); + if !(1..=MAX_PAGE_SIZE).contains(&limit) { return Err(Problem::bad_request(format!( "limit must be between 1 and {MAX_PAGE_SIZE}" ))); } - Err(Capability::AuditQuery.problem()) + if !caller.operator { + let Some(project) = &query.project else { + return Err(Problem::forbidden( + "name a project you hold a role in; only operators read the whole log", + )); + }; + let mut database = state.database.clone(); + if caller_role(&mut database, project, &caller) + .await? + .is_none() + { + return Err(Problem::forbidden(format!( + "you hold no role in project `{project}`" + ))); + } + } + let events = audit::query( + &state.database, + &EventFilter { + project: query.project.map(|value| value.to_string()), + session: query.session.map(|value| value.to_string()), + principal: query.principal.map(|value| value.to_string()), + exception: query.exception.map(|value| value.to_string()), + after_sequence: query.after_sequence.unwrap_or(0), + limit, + }, + ) + .await?; + let next_after_sequence = (events.len() == limit as usize) + .then(|| events.last().map(|event| event.sequence)) + .flatten(); + Ok(web::Json(AuditPage { + events, + next_after_sequence, + })) +} + +async fn verify( + state: State, + Authenticated(caller): Authenticated, +) -> Result, Problem> { + require_operator(&caller, "verify the audit chain")?; + Ok(web::Json(audit::verify_chain(&state.database).await?)) } diff --git a/crates/fleet-server/src/routes/v1/authorize.rs b/crates/fleet-server/src/routes/v1/authorize.rs index 2bec05d..bd5177a 100644 --- a/crates/fleet-server/src/routes/v1/authorize.rs +++ b/crates/fleet-server/src/routes/v1/authorize.rs @@ -1,24 +1,111 @@ //! `POST /v1/authorize`: decide one brokered upstream request. +//! +//! The decision uses the same rules as the single-host authority +//! (`sendbox_governance::evaluate_request`) against shared state, and also +//! denies once the session ended or an exception it depends on is no longer +//! active. A malformed path is a `deny` decision, not a request error. Hosts +//! treat any non-200 answer as `authority_unavailable` and deny. use actix_web::web; -use sendbox_governance::{Decision, RequestContext}; +use sendbox_governance::{Decision, DenyReason, RequestContext, evaluate_request}; -use super::Capability; +use super::State; +use crate::audit::{self, AuditDecision, AuditRecord}; use crate::auth::Authenticated; +use crate::governance::{self, SessionStatus}; use crate::problem::Problem; use crate::routes::resource; +const MAX_TARGET_PATH_BYTES: usize = 400; + pub fn configure(config: &mut web::ServiceConfig) { config.service(resource("/authorize").route(web::post().to(authorize))); } -/// Takes the enforcement point's trusted [`RequestContext`] and will answer -/// with a [`Decision`]. A malformed path is a `deny` decision, not a request -/// error, so only the contract schema is validated here. Callers must treat -/// any non-200 response as `authority_unavailable` and deny. +fn deny(reason: DenyReason) -> Decision { + Decision::Deny { reason } +} + +/// Method, service, and path without query; truncated to fit the schema. +fn target(context: &RequestContext) -> String { + let path = if sendbox_governance::validate_request_path(&context.path).is_ok() { + let mut path = context.path.clone(); + path.truncate(MAX_TARGET_PATH_BYTES); + path + } else { + "".to_owned() + }; + format!( + "{} {}{}", + context.method.chars().take(16).collect::(), + context.service, + path + ) +} + async fn authorize( - _caller: Authenticated, - _context: web::Json, + state: State, + Authenticated(caller): Authenticated, + context: web::Json, ) -> Result, Problem> { - Err(Capability::RequestAuthorization.problem()) + let context = context.into_inner(); + let now = state.now(); + let mut tx = state.database.begin_write().await?; + let stored = governance::grant(&mut tx, &context.grant_id).await?; + let decision = match &stored { + None => deny(DenyReason::UnknownGrant), + Some(_) if context.principal != caller.principal => deny(DenyReason::PrincipalMismatch), + Some(stored) => { + let current = governance::current_profile(&mut tx, &stored.grant.profile.id, now) + .await + .ok() + .flatten() + .map(|profile| profile.current()); + match evaluate_request( + &stored.grant, + stored.revoked.is_some(), + &context, + now, + current.as_ref(), + ) { + Decision::Allow(allowed) => { + match governance::session(&mut tx, &stored.grant.session).await? { + Some(session) if session.status == SessionStatus::Admitted => { + match governance::session_exceptions(&mut tx, &session, now).await { + Ok(_) => Decision::Allow(allowed), + Err(reason) => deny(reason), + } + } + _ => deny(DenyReason::Revoked), + } + } + denied @ Decision::Deny { .. } => denied, + } + } + }; + let (decision_code, deny_reason) = match &decision { + Decision::Allow(_) => (AuditDecision::Allow, None), + Decision::Deny { reason } => (AuditDecision::Deny, Some(*reason)), + }; + let grant = stored.as_ref().map(|stored| &stored.grant); + audit::append( + &mut tx, + now, + AuditRecord { + event_type: "request.authorized", + actor: Some(caller.principal.to_string()), + principal: Some(context.principal.to_string()), + project: Some(context.project.to_string()), + session: Some(context.session.to_string()), + grant: Some(context.grant_id.to_string()), + profile: grant.map(|grant| (grant.profile.id.to_string(), grant.profile.revision)), + decision: Some(decision_code), + deny_reason, + target: Some(target(&context)), + ..AuditRecord::default() + }, + ) + .await?; + tx.commit().await?; + Ok(web::Json(decision)) } diff --git a/crates/fleet-server/src/routes/v1/exceptions.rs b/crates/fleet-server/src/routes/v1/exceptions.rs index f75e1e4..324e0a7 100644 --- a/crates/fleet-server/src/routes/v1/exceptions.rs +++ b/crates/fleet-server/src/routes/v1/exceptions.rs @@ -1,38 +1,29 @@ -//! `POST /v1/exceptions`: request a bounded, expiring policy exception. +//! Bounded, expiring policy exceptions. //! -//! The requester is the authenticated caller; approval by a different, -//! authorized principal is a separate step. An exception is bound to the exact -//! profile revision it was reviewed against and can never exceed that -//! profile's ceiling. +//! A project member asks to lift one denial that the current profile revision +//! lists as liftable. A different principal holding the `owner` or `admin` +//! role approves or rejects it. An approval is bound to the exact revision it +//! was reviewed against: a newer revision or a raised minimum makes it stale, +//! so it can no longer admit sessions or keep their grants alive. Lifting a +//! denial never adds a capability; sessions must still fit the ceiling. -use actix_web::web; -use sendbox_governance::{PrincipalId, ProfileRef, ProjectId}; +use actix_web::{HttpResponse, web}; +use sendbox_governance::api::ExceptionList; +use sendbox_governance::exception::{MAX_EXCEPTION_TTL_SECONDS, validate_reason}; +use sendbox_governance::{ + ExceptionId, ExceptionScope, ExceptionStatus, PolicyException, PrincipalId, ProfileRef, + ProjectId, +}; use serde::{Deserialize, Serialize}; -use super::Capability; -use crate::auth::Authenticated; +use super::{State, actor, caller_role, invalid, refuse, require_user}; +use crate::audit::{self, AuditRecord}; +use crate::auth::{Authenticated, Caller}; +use crate::db::Tx; +use crate::governance::{self, ExceptionState, ProjectRole}; use crate::problem::Problem; use crate::routes::resource; - -const MAX_SCOPE_VALUE_BYTES: usize = 256; -const MAX_REASON_CHARS: usize = 1000; - -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ExceptionScopeKind { - NetworkDomain, - Command, - McpTool, - CredentialServicePath, -} - -/// One narrowly scoped permission, such as a single domain or command pattern. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct ExceptionScope { - pub kind: ExceptionScopeKind, - pub value: String, -} +use crate::state::to_db; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -41,48 +32,383 @@ pub struct ExceptionRequest { /// Limits the exception to one principal; omit to cover the project. #[serde(default, skip_serializing_if = "Option::is_none")] pub principal: Option, - /// The exact profile revision the exception was reviewed against. + /// The exact profile revision the exception is reviewed against. It must + /// be the current revision. pub profile: ProfileRef, pub scope: ExceptionScope, pub reason: String, pub expires_at_unix: u64, } -impl ExceptionRequest { - pub fn validate(&self) -> Result<(), Problem> { - let value = &self.scope.value; - if value.is_empty() - || value.len() > MAX_SCOPE_VALUE_BYTES - || !value.bytes().all(|byte| byte.is_ascii_graphic()) - { - return Err(Problem::bad_request(format!( - "scope.value must be 1 to {MAX_SCOPE_VALUE_BYTES} printable ASCII bytes without spaces" - ))); - } - let reason = self.reason.trim(); - if reason.is_empty() - || self.reason.chars().count() > MAX_REASON_CHARS - || self.reason.chars().any(char::is_control) - { - return Err(Problem::bad_request(format!( - "reason must be 1 to {MAX_REASON_CHARS} characters without control characters" - ))); - } - if self.expires_at_unix == 0 { - return Err(Problem::bad_request("expires_at_unix must be set")); - } - Ok(()) - } +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +struct ListQuery { + project: ProjectId, + #[serde(default)] + state: ExceptionState, } pub fn configure(config: &mut web::ServiceConfig) { - config.service(resource("/exceptions").route(web::post().to(request_exception))); + config + .service( + resource("/exceptions") + .route(web::post().to(request)) + .route(web::get().to(list)), + ) + .service(resource("/exceptions/{exception_id:[^/:]+}").route(web::get().to(read))) + .service( + resource("/exceptions/{exception_id:[^/:]+}:approve").route(web::post().to(approve)), + ) + .service(resource("/exceptions/{exception_id:[^/:]+}:reject").route(web::post().to(reject))) + .service( + resource("/exceptions/{exception_id:[^/:]+}:revoke").route(web::post().to(revoke)), + ); } -async fn request_exception( - _caller: Authenticated, +fn record(caller: &Caller, exception: &PolicyException, event_type: &'static str) -> AuditRecord { + AuditRecord { + event_type, + actor: actor(caller), + principal: exception.principal.as_ref().map(ToString::to_string), + project: Some(exception.project.to_string()), + exception: Some(exception.id.to_string()), + profile: Some((exception.profile.id.to_string(), exception.profile.revision)), + detail: Some(format!("scope={}", exception.scope)), + ..AuditRecord::default() + } +} + +async fn request( + state: State, + Authenticated(caller): Authenticated, request: web::Json, -) -> Result, Problem> { - request.validate()?; - Err(Capability::ExceptionRequest.problem()) +) -> Result { + let request = request.into_inner(); + require_user(&caller, "request policy exceptions")?; + request.scope.validate().map_err(invalid)?; + validate_reason(&request.reason).map_err(invalid)?; + let now = state.now(); + let mut tx = state.database.begin_write().await?; + let role = caller_role(&mut tx, &request.project, &caller).await?; + if !role.is_some_and(|role| role.at_least(ProjectRole::Member)) { + return Err(Problem::forbidden(format!( + "requesting exceptions in `{}` requires the member role or higher", + request.project + ))); + } + if let Some(principal) = &request.principal + && !governance::role_of(&mut tx, &request.project, principal) + .await? + .is_some_and(|role| role.at_least(ProjectRole::Member)) + { + return Err(Problem::bad_request(format!( + "`{principal}` cannot run sessions in `{}`", + request.project + ))); + } + let profile = governance::require_current(&mut tx, &request.profile, now) + .await + .map_err(|reason| { + Problem::conflict(format!( + "exceptions must be reviewed against the current profile revision ({reason})" + )) + })?; + let parsed = profile.parse()?; + if !parsed.permits_exception(&request.scope) { + return Err(Problem::forbidden(format!( + "profile `{}` revision {} does not permit an exception for `{}`", + request.profile.id, request.profile.revision, request.scope + ))); + } + let longest = parsed + .exceptions + .max_ttl_seconds + .min(MAX_EXCEPTION_TTL_SECONDS); + if request.expires_at_unix <= now + || request.expires_at_unix > now.saturating_add(longest) + || request.expires_at_unix > profile.expires_at_unix + { + return Err(Problem::bad_request(format!( + "expires_at_unix must be in the future, at most {longest} seconds away, and before the profile expires" + ))); + } + let exception = PolicyException { + id: ExceptionId::from_bytes(state.new_id()?), + project: request.project, + principal: request.principal, + profile: request.profile, + scope: request.scope, + reason: request.reason, + status: ExceptionStatus::Pending, + requested_by: caller.principal.clone(), + requested_at_unix: now, + decided_by: None, + decided_at_unix: None, + expires_at_unix: request.expires_at_unix, + revoked_by: None, + revoked_at_unix: None, + }; + tx.execute( + "INSERT INTO exceptions (id, project_id, principal_id, profile_id, profile_revision, \ + profile_sha256, scope_kind, scope_value, reason, status, requested_by, \ + requested_at_unix, expires_at_unix) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, \ + 'pending', $10, $11, $12)", + &[ + exception.id.as_str().into(), + exception.project.as_str().into(), + exception.principal.as_ref().map(ToString::to_string).into(), + exception.profile.id.as_str().into(), + to_db(exception.profile.revision)?.into(), + exception.profile.sha256.to_string().into(), + exception.scope.kind.code().into(), + exception.scope.value.clone().into(), + exception.reason.clone().into(), + exception.requested_by.as_str().into(), + to_db(now)?.into(), + to_db(exception.expires_at_unix)?.into(), + ], + ) + .await?; + audit::append( + &mut tx, + now, + AuditRecord { + detail: Some(format!( + "scope={} expires_at_unix={}", + exception.scope, exception.expires_at_unix + )), + ..record(&caller, &exception, "exception.requested") + }, + ) + .await?; + tx.commit().await?; + Ok(HttpResponse::Created().json(exception)) +} + +async fn list( + state: State, + Authenticated(caller): Authenticated, + query: web::Query, +) -> Result, Problem> { + let ListQuery { + project, + state: wanted, + } = query.into_inner(); + let mut database = state.database.clone(); + let role = caller_role(&mut database, &project, &caller).await?; + if !caller.operator && role.is_none() { + return Err(Problem::forbidden(format!( + "you hold no role in project `{project}`" + ))); + } + let exceptions = + governance::project_exceptions(&mut database, &project, wanted, state.now()).await?; + Ok(web::Json(ExceptionList { exceptions })) +} + +async fn read( + state: State, + Authenticated(caller): Authenticated, + id: web::Path, +) -> Result, Problem> { + let mut database = state.database.clone(); + let exception = governance::exception(&mut database, &id) + .await? + .ok_or_else(|| Problem::missing(format!("exception `{id}` does not exist")))?; + let role = governance::role_of(&mut database, &exception.project, &caller.principal).await?; + if !caller.operator && role.is_none() { + return Err(Problem::forbidden(format!( + "you hold no role in project `{}`", + exception.project + ))); + } + Ok(web::Json(exception)) +} + +/// Loads an exception and checks that the caller may decide it: a person +/// holding `owner` or `admin` in its project who did not request it. Refusals +/// are audited. +async fn decider( + state: &State, + mut tx: Tx, + caller: &Caller, + id: &ExceptionId, + event_type: &'static str, +) -> Result<(Tx, PolicyException), Problem> { + require_user(caller, "decide policy exceptions")?; + let exception = governance::exception(&mut tx, id) + .await? + .ok_or_else(|| Problem::missing(format!("exception `{id}` does not exist")))?; + let role = governance::role_of(&mut tx, &exception.project, &caller.principal).await?; + let refusal = if exception.requested_by == caller.principal { + Some("an exception cannot be decided by the principal who requested it") + } else if !role.is_some_and(|role| role.at_least(ProjectRole::Admin)) { + Some("deciding exceptions requires the owner or admin role in the project") + } else { + None + }; + if let Some(refusal) = refusal { + let record = record(caller, &exception, event_type); + return refuse(state, tx, record, Problem::forbidden(refusal)).await; + } + if exception.status != ExceptionStatus::Pending { + return Err(Problem::conflict(format!( + "exception `{id}` was already decided" + ))); + } + Ok((tx, exception)) +} + +async fn approve( + state: State, + Authenticated(caller): Authenticated, + id: web::Path, +) -> Result, Problem> { + let now = state.now(); + let tx = state.database.begin_write().await?; + let (mut tx, mut exception) = + decider(&state, tx, &caller, &id, "exception.approval_refused").await?; + if now >= exception.expires_at_unix { + return Err(Problem::conflict(format!( + "exception `{id}` already expired" + ))); + } + if let Err(reason) = governance::require_current(&mut tx, &exception.profile, now).await { + return refuse( + &state, + tx, + record(&caller, &exception, "exception.approval_refused"), + Problem::conflict(format!( + "exception `{id}` was reviewed against a profile revision that is no longer current ({reason}); request it again" + )), + ) + .await; + } + decide( + &mut tx, + &mut exception, + &caller, + ExceptionStatus::Approved, + now, + ) + .await?; + audit::append( + &mut tx, + now, + record(&caller, &exception, "exception.approved"), + ) + .await?; + tx.commit().await?; + Ok(web::Json(exception)) +} + +async fn reject( + state: State, + Authenticated(caller): Authenticated, + id: web::Path, +) -> Result, Problem> { + let now = state.now(); + let tx = state.database.begin_write().await?; + let (mut tx, mut exception) = + decider(&state, tx, &caller, &id, "exception.rejection_refused").await?; + decide( + &mut tx, + &mut exception, + &caller, + ExceptionStatus::Rejected, + now, + ) + .await?; + audit::append( + &mut tx, + now, + record(&caller, &exception, "exception.rejected"), + ) + .await?; + tx.commit().await?; + Ok(web::Json(exception)) +} + +async fn decide( + tx: &mut Tx, + exception: &mut PolicyException, + caller: &Caller, + status: ExceptionStatus, + now: u64, +) -> Result<(), Problem> { + let code = match status { + ExceptionStatus::Approved => "approved", + ExceptionStatus::Rejected => "rejected", + ExceptionStatus::Pending => return Err(Problem::internal()), + }; + tx.execute( + "UPDATE exceptions SET status = $2, decided_by = $3, decided_at_unix = $4 \ + WHERE id = $1 AND status = 'pending'", + &[ + exception.id.as_str().into(), + code.into(), + caller.principal.as_str().into(), + to_db(now)?.into(), + ], + ) + .await?; + exception.status = status; + exception.decided_by = Some(caller.principal.clone()); + exception.decided_at_unix = Some(now); + Ok(()) +} + +/// Revokes an approved exception. Sessions admitted with it lose their +/// grants on the next renewal or request. Its requester, the project's owners +/// and admins, and operators may revoke it. +async fn revoke( + state: State, + Authenticated(caller): Authenticated, + id: web::Path, +) -> Result, Problem> { + require_user(&caller, "revoke policy exceptions")?; + let now = state.now(); + let mut tx = state.database.begin_write().await?; + let mut exception = governance::exception(&mut tx, &id) + .await? + .ok_or_else(|| Problem::missing(format!("exception `{id}` does not exist")))?; + let role = governance::role_of(&mut tx, &exception.project, &caller.principal).await?; + let allowed = caller.operator + || exception.requested_by == caller.principal + || role.is_some_and(|role| role.at_least(ProjectRole::Admin)); + if !allowed { + return refuse( + &state, + tx, + record(&caller, &exception, "exception.revocation_refused"), + Problem::forbidden( + "only the requester, the project's owners and admins, or operators can revoke an exception", + ), + ) + .await; + } + if exception.status != ExceptionStatus::Approved || exception.revoked_at_unix.is_some() { + return Err(Problem::conflict(format!( + "exception `{id}` is not an active approval" + ))); + } + tx.execute( + "UPDATE exceptions SET revoked_by = $2, revoked_at_unix = $3 WHERE id = $1", + &[ + exception.id.as_str().into(), + caller.principal.as_str().into(), + to_db(now)?.into(), + ], + ) + .await?; + exception.revoked_by = Some(caller.principal.clone()); + exception.revoked_at_unix = Some(now); + audit::append( + &mut tx, + now, + record(&caller, &exception, "exception.revoked"), + ) + .await?; + tx.commit().await?; + Ok(web::Json(exception)) } diff --git a/crates/fleet-server/src/routes/v1/grants.rs b/crates/fleet-server/src/routes/v1/grants.rs index 796b2a8..424b134 100644 --- a/crates/fleet-server/src/routes/v1/grants.rs +++ b/crates/fleet-server/src/routes/v1/grants.rs @@ -1,21 +1,26 @@ -//! Credential grants: issue, renew, and revoke. Grants authorize one session -//! to use one brokered service; they never carry credential material. +//! Credential grants: issue, renew, and revoke. A grant authorizes one +//! admitted session to use one brokered service. It carries no credential +//! material; the provider credential stays in the SendBox host broker. use actix_web::{HttpResponse, web}; +use sendbox_governance::api::RevokeGrantRequest; use sendbox_governance::grant::{validate_method, validate_path_prefix}; -use sendbox_governance::{CredentialGrant, GrantId, GrantRequest, RevocationReason}; -use serde::{Deserialize, Serialize}; +use sendbox_governance::{ + CONTRACT_VERSION, CredentialGrant, DenyReason, GrantId, GrantRequest, RevocationReason, + path_permitted, +}; -use super::{Capability, invalid}; -use crate::auth::Authenticated; +use super::{State, actor, invalid, refuse}; +use crate::audit::{self, AuditDecision, AuditRecord}; +use crate::auth::{Authenticated, Caller}; +use crate::db::Tx; +use crate::governance::{self, ProjectRole, SessionStatus, StoredGrant}; use crate::problem::Problem; use crate::routes::resource; +use crate::state::to_db; -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct RevokeGrantRequest { - pub reason: RevocationReason, -} +/// Hard cap from the contract: 7 days from issue to expiry. +const MAX_GRANT_SECONDS: u64 = 7 * 24 * 60 * 60; pub fn configure(config: &mut web::ServiceConfig) { config @@ -24,11 +29,25 @@ pub fn configure(config: &mut web::ServiceConfig) { .service(resource("/grants/{grant_id:[^/:]+}:revoke").route(web::post().to(revoke))); } +fn base(caller: &Caller, grant: &CredentialGrant) -> AuditRecord { + AuditRecord { + actor: actor(caller), + principal: Some(grant.principal.to_string()), + project: Some(grant.project.to_string()), + session: Some(grant.session.to_string()), + grant: Some(grant.grant_id.to_string()), + profile: Some((grant.profile.id.to_string(), grant.profile.revision)), + ..AuditRecord::default() + } +} + async fn issue( - _caller: Authenticated, + state: State, + Authenticated(caller): Authenticated, request: web::Json, ) -> Result, Problem> { - request.binding.validate().map_err(invalid)?; + let request = request.into_inner(); + let binding_sha256 = request.binding.digest().map_err(invalid)?; if request.methods.is_empty() || request.path_prefixes.is_empty() { return Err(Problem::bad_request( "grants require at least one method and path prefix", @@ -43,20 +62,366 @@ async fn issue( if request.max_ttl_seconds == 0 { return Err(Problem::bad_request("max_ttl_seconds must be positive")); } - Err(Capability::GrantIssuance.problem()) + let now = state.now(); + let mut tx = state.database.begin_write().await?; + let record = AuditRecord { + event_type: "grant.refused", + actor: actor(&caller), + principal: Some(request.principal.to_string()), + project: Some(request.project.to_string()), + session: Some(request.session.to_string()), + profile: Some(( + request.binding.profile.id.to_string(), + request.binding.profile.revision, + )), + detail: Some(format!("service={}", request.service)), + ..AuditRecord::default() + }; + let Some(session) = governance::session(&mut tx, &request.session).await? else { + return Err(Problem::missing(format!( + "session `{}` was not admitted", + request.session + ))); + }; + let identity_matches = caller.principal == session.binding.principal + && request.principal == session.binding.principal + && request.project == session.binding.project + && request.binding == session.binding + && binding_sha256 == session.binding_sha256; + if !identity_matches { + return refuse( + &state, + tx, + record, + Problem::forbidden( + "the grant request does not match the caller and the admitted session binding", + ), + ) + .await; + } + if session.status != SessionStatus::Admitted { + return refuse( + &state, + tx, + record, + Problem::conflict("the session has ended"), + ) + .await; + } + if !session.binding.brokered_services.contains(&request.service) { + return refuse( + &state, + tx, + record, + Problem::forbidden("the service is not admitted by the session binding"), + ) + .await; + } + let deny = |reason: DenyReason, record: AuditRecord| AuditRecord { + decision: Some(AuditDecision::Deny), + deny_reason: Some(reason), + ..record + }; + let profile = match governance::require_current(&mut tx, &session.binding.profile, now).await { + Ok(profile) => profile, + Err(reason) => { + return refuse( + &state, + tx, + deny(reason, record), + Problem::conflict(format!( + "the session's profile revision is stale ({reason})" + )), + ) + .await; + } + }; + let earliest_exception = match governance::session_exceptions(&mut tx, &session, now).await { + Ok(earliest) => earliest, + Err(reason) => { + return refuse( + &state, + tx, + deny(reason, record), + Problem::conflict("an exception the session depends on is no longer active"), + ) + .await; + } + }; + let parsed = profile.parse()?; + let Some(service) = parsed.credential_service(&request.service) else { + return refuse( + &state, + tx, + record, + Problem::forbidden("the profile does not offer this service"), + ) + .await; + }; + let allowed_prefixes = service.effective_path_prefixes(); + let within_profile = request.methods.is_subset(&service.effective_methods()) + && request + .path_prefixes + .iter() + .all(|prefix| path_permitted(&allowed_prefixes, prefix)); + if !within_profile { + return refuse( + &state, + tx, + record, + Problem::forbidden("requested methods or path prefixes exceed the profile"), + ) + .await; + } + let mut max_expires_at_unix = now + .saturating_add(request.max_ttl_seconds.min(parsed.grants.max_ttl_seconds)) + .min(profile.expires_at_unix) + .min(now.saturating_add(MAX_GRANT_SECONDS)); + if let Some(earliest) = earliest_exception { + max_expires_at_unix = max_expires_at_unix.min(earliest); + } + if max_expires_at_unix <= now { + return Err(Problem::conflict("the grant would expire immediately")); + } + let grant = CredentialGrant { + contract_version: CONTRACT_VERSION, + grant_id: GrantId::from_bytes(state.new_id()?), + principal: request.principal, + project: request.project, + session: request.session, + binding_sha256, + profile: session.binding.profile.clone(), + service: request.service, + methods: request.methods, + path_prefixes: request.path_prefixes, + issued_at_unix: now, + lease_expires_at_unix: now + .saturating_add(parsed.grants.lease_seconds) + .min(max_expires_at_unix), + max_expires_at_unix, + generation: 1, + }; + grant.validate().map_err(invalid)?; + let methods = serde_json::to_string(&grant.methods).map_err(|_| Problem::internal())?; + let prefixes = serde_json::to_string(&grant.path_prefixes).map_err(|_| Problem::internal())?; + tx.execute( + &format!( + "INSERT INTO credential_grants (id, session_id, principal_id, project_id, \ + binding_sha256, profile_id, profile_revision, profile_sha256, service_id, methods, \ + path_prefixes, issued_at_unix, lease_expires_at_unix, max_expires_at_unix, \ + generation) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, {}, {}, $12, $13, $14, 1)", + tx.json_param(10, true), + tx.json_param(11, true) + ), + &[ + grant.grant_id.as_str().into(), + grant.session.as_str().into(), + grant.principal.as_str().into(), + grant.project.as_str().into(), + grant.binding_sha256.to_string().into(), + grant.profile.id.as_str().into(), + to_db(grant.profile.revision)?.into(), + grant.profile.sha256.to_string().into(), + grant.service.as_str().into(), + methods.into(), + prefixes.into(), + to_db(grant.issued_at_unix)?.into(), + to_db(grant.lease_expires_at_unix)?.into(), + to_db(grant.max_expires_at_unix)?.into(), + ], + ) + .await?; + audit::append( + &mut tx, + now, + AuditRecord { + event_type: "grant.issued", + decision: Some(AuditDecision::Allow), + detail: Some(format!( + "service={} lease_expires_at_unix={} max_expires_at_unix={}", + grant.service, grant.lease_expires_at_unix, grant.max_expires_at_unix + )), + ..base(&caller, &grant) + }, + ) + .await?; + tx.commit().await?; + Ok(web::Json(grant)) +} + +/// Why a stored grant can no longer be renewed, if it cannot. +async fn lapse_reason( + tx: &mut Tx, + stored: &StoredGrant, + now: u64, +) -> Result, Problem> { + let grant = &stored.grant; + if stored.revoked.is_some() { + return Ok(Some(DenyReason::Revoked)); + } + if now >= grant.max_expires_at_unix { + return Ok(Some(DenyReason::Expired)); + } + if now >= grant.lease_expires_at_unix { + return Ok(Some(DenyReason::LeaseExpired)); + } + let Some(session) = governance::session(tx, &grant.session).await? else { + return Ok(Some(DenyReason::SessionMismatch)); + }; + if session.status != SessionStatus::Admitted { + return Ok(Some(DenyReason::Revoked)); + } + if let Err(reason) = governance::require_current(tx, &grant.profile, now).await { + return Ok(Some(reason)); + } + Ok(governance::session_exceptions(tx, &session, now) + .await + .err()) } async fn renew( - _caller: Authenticated, - _grant: web::Path, + state: State, + Authenticated(caller): Authenticated, + grant_id: web::Path, ) -> Result, Problem> { - Err(Capability::GrantRenewal.problem()) + let grant_id = grant_id.into_inner(); + let now = state.now(); + let mut tx = state.database.begin_write().await?; + let stored = governance::grant(&mut tx, &grant_id) + .await? + .ok_or_else(|| Problem::missing(format!("grant `{grant_id}` does not exist")))?; + if stored.grant.principal != caller.principal { + return Err(Problem::forbidden( + "only the grant's principal can renew it", + )); + } + if let Some(reason) = lapse_reason(&mut tx, &stored, now).await? { + return refuse( + &state, + tx, + AuditRecord { + event_type: "grant.renewal_denied", + decision: Some(AuditDecision::Deny), + deny_reason: Some(reason), + ..base(&caller, &stored.grant) + }, + Problem::conflict(format!("the grant cannot be renewed ({reason})")), + ) + .await; + } + let session = governance::session(&mut tx, &stored.grant.session) + .await? + .ok_or_else(Problem::internal)?; + let profile = governance::profile_revision( + &mut tx, + &stored.grant.profile.id, + stored.grant.profile.revision, + ) + .await? + .ok_or_else(Problem::internal)? + .parse()?; + let mut lease = now + .saturating_add(profile.grants.lease_seconds) + .min(stored.grant.max_expires_at_unix); + if let Ok(Some(earliest)) = governance::session_exceptions(&mut tx, &session, now).await { + lease = lease.min(earliest); + } + let mut grant = stored.grant; + grant.lease_expires_at_unix = lease; + grant.generation = grant.generation.saturating_add(1); + tx.execute( + "UPDATE credential_grants SET lease_expires_at_unix = $2, generation = $3 WHERE id = $1", + &[ + grant.grant_id.as_str().into(), + to_db(grant.lease_expires_at_unix)?.into(), + to_db(grant.generation)?.into(), + ], + ) + .await?; + audit::append( + &mut tx, + now, + AuditRecord { + event_type: "grant.renewed", + decision: Some(AuditDecision::Allow), + detail: Some(format!( + "lease_expires_at_unix={} generation={}", + grant.lease_expires_at_unix, grant.generation + )), + ..base(&caller, &grant) + }, + ) + .await?; + tx.commit().await?; + Ok(web::Json(grant)) } async fn revoke( - _caller: Authenticated, - _grant: web::Path, - _request: web::Json, + state: State, + Authenticated(caller): Authenticated, + grant_id: web::Path, + request: web::Json, ) -> Result { - Err(Capability::GrantRevocation.problem()) + let grant_id = grant_id.into_inner(); + let reason = request.reason; + let now = state.now(); + let mut tx = state.database.begin_write().await?; + let stored = governance::grant(&mut tx, &grant_id) + .await? + .ok_or_else(|| Problem::missing(format!("grant `{grant_id}` does not exist")))?; + let own = stored.grant.principal == caller.principal; + let authorized = match reason { + RevocationReason::SessionCompleted + | RevocationReason::SessionCancelled + | RevocationReason::SessionFailed => own, + RevocationReason::OperatorRevoked | RevocationReason::PolicyChanged => { + caller.operator + || governance::role_of(&mut tx, &stored.grant.project, &caller.principal) + .await? + .is_some_and(|role| role.at_least(ProjectRole::Admin)) + } + }; + if !authorized { + return refuse( + &state, + tx, + AuditRecord { + event_type: "grant.revocation_refused", + detail: Some(format!("reason={}", reason.code())), + ..base(&caller, &stored.grant) + }, + Problem::forbidden( + "session reasons are for the grant's principal; operator and policy revocations need an admin, owner, or operator", + ), + ) + .await; + } + if stored.revoked.is_some() { + return Ok(HttpResponse::NoContent().finish()); + } + let grace = governance::profile_revision( + &mut tx, + &stored.grant.profile.id, + stored.grant.profile.revision, + ) + .await? + .map(|profile| profile.parse()) + .transpose()? + .map_or(0, |profile| profile.grants.revocation_grace_seconds); + let revoked_by = (reason == RevocationReason::OperatorRevoked + || reason == RevocationReason::PolicyChanged) + .then_some(&caller.principal); + governance::revoke_grant(&mut tx, &stored.grant, reason, revoked_by, grace, now).await?; + audit::append( + &mut tx, + now, + AuditRecord { + event_type: "grant.revoked", + detail: Some(format!("reason={}", reason.code())), + ..base(&caller, &stored.grant) + }, + ) + .await?; + tx.commit().await?; + Ok(HttpResponse::NoContent().finish()) } diff --git a/crates/fleet-server/src/routes/v1/mod.rs b/crates/fleet-server/src/routes/v1/mod.rs index 6634ecf..3ce884d 100644 --- a/crates/fleet-server/src/routes/v1/mod.rs +++ b/crates/fleet-server/src/routes/v1/mod.rs @@ -1,7 +1,7 @@ //! Versioned management API. Every route is mounted behind //! [`crate::auth::require_bearer`], validates its input against the shared -//! `sendbox-governance` contract, and then answers `501 Not Implemented` -//! naming the increment-2 capability it will provide. +//! `sendbox-governance` contract, authorizes the authenticated caller from +//! stored roles, and records an audit event for every decision it makes. pub mod audit; pub mod authorize; @@ -10,14 +10,21 @@ pub mod grants; pub mod profiles; pub mod projects; pub mod sessions; +pub mod whoami; use actix_web::web; -use sendbox_governance::GovernanceError; +use sendbox_governance::{GovernanceError, ProjectId}; +use crate::audit::AuditRecord; +use crate::auth::{Caller, CallerKind}; +use crate::db::Tx; +use crate::governance::{self, ProjectRole, Reader}; use crate::problem::Problem; +use crate::state::AppState; pub fn configure(config: &mut web::ServiceConfig) { config + .configure(whoami::configure) .configure(sessions::configure) .configure(grants::configure) .configure(authorize::configure) @@ -27,73 +34,68 @@ pub fn configure(config: &mut web::ServiceConfig) { .configure(audit::configure); } -/// Increment-2 capabilities that this scaffold does not implement yet. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Capability { - SessionAdmission, - GrantIssuance, - GrantRenewal, - GrantRevocation, - RequestAuthorization, - ProfileRead, - ProfilePublication, - RoleListing, - RoleAssignment, - ExceptionRequest, - AuditQuery, +/// Maps a contract validation failure to a 400 problem. +pub(crate) fn invalid(error: GovernanceError) -> Problem { + Problem::bad_request(error.to_string()) +} + +pub(crate) type State = web::Data; + +pub(crate) fn actor(caller: &Caller) -> Option { + Some(caller.principal.to_string()) } -impl Capability { - #[must_use] - pub const fn code(self) -> &'static str { - match self { - Self::SessionAdmission => "session_admission", - Self::GrantIssuance => "grant_issuance", - Self::GrantRenewal => "grant_renewal", - Self::GrantRevocation => "grant_revocation", - Self::RequestAuthorization => "request_authorization", - Self::ProfileRead => "profile_read", - Self::ProfilePublication => "profile_publication", - Self::RoleListing => "role_listing", - Self::RoleAssignment => "role_assignment", - Self::ExceptionRequest => "exception_request", - Self::AuditQuery => "audit_query", - } +/// People manage projects, roles, profiles, and exceptions; workers only run +/// sessions. +pub(crate) fn require_user(caller: &Caller, action: &str) -> Result<(), Problem> { + if caller.kind == CallerKind::User { + Ok(()) + } else { + Err(Problem::forbidden(format!("workers cannot {action}"))) } +} - const fn description(self) -> &'static str { - match self { - Self::SessionAdmission => { - "Session admission (checking the caller's project role and the current profile revision, then recording the session binding)" - } - Self::GrantIssuance => "Credential grant issuance", - Self::GrantRenewal => "Credential grant lease renewal", - Self::GrantRevocation => "Credential grant revocation", - Self::RequestAuthorization => "Per-request grant authorization", - Self::ProfileRead => "Governance profile retrieval", - Self::ProfilePublication => "Signed governance profile publication", - Self::RoleListing => "Project role listing", - Self::RoleAssignment => "Project role assignment", - Self::ExceptionRequest => "Expiring policy exception requests", - Self::AuditQuery => "Central audit event queries", - } +pub(crate) fn require_operator(caller: &Caller, action: &str) -> Result<(), Problem> { + require_user(caller, action)?; + if caller.operator { + Ok(()) + } else { + Err(Problem::forbidden(format!( + "only fleet operators can {action}" + ))) } +} - #[must_use] - pub fn problem(self) -> Problem { - Problem::not_implemented( - self.code(), - format!( - "{} is not implemented yet. It is part of governed sessions increment 2 \ - (https://github.com/mbianchidev/sendbox/issues/87); this scaffold only \ - authenticates and validates the request.", - self.description() - ), - ) +/// The caller's role in `project`, or a 404 when the project does not exist. +pub(crate) async fn caller_role( + reader: &mut impl Reader, + project: &ProjectId, + caller: &Caller, +) -> Result, Problem> { + if !governance::project_exists(reader, project).await? { + return Err(Problem::missing(format!( + "project `{project}` does not exist" + ))); } + governance::role_of(reader, project, &caller.principal).await } -/// Maps a contract validation failure to a 400 problem. -pub(crate) fn invalid(error: GovernanceError) -> Problem { - Problem::bad_request(error.to_string()) +/// Records a refused, security-relevant request and returns its problem. The +/// transaction holds no other change, so only the audit event is committed. +pub(crate) async fn refuse( + state: &AppState, + mut tx: Tx, + record: AuditRecord, + problem: Problem, +) -> Result { + let record = AuditRecord { + detail: Some(match record.detail { + Some(detail) => format!("{detail} refused={}", problem.detail), + None => format!("refused={}", problem.detail), + }), + ..record + }; + crate::audit::append(&mut tx, state.now(), record).await?; + tx.commit().await?; + Err(problem) } diff --git a/crates/fleet-server/src/routes/v1/profiles.rs b/crates/fleet-server/src/routes/v1/profiles.rs index 4fbcfb1..b21e6c3 100644 --- a/crates/fleet-server/src/routes/v1/profiles.rs +++ b/crates/fleet-server/src/routes/v1/profiles.rs @@ -1,39 +1,47 @@ -//! Governance profiles: read the current revision or publish a signed one. +//! Governance profiles: publish a signed revision, read the current (or a +//! given) revision, and raise the minimum accepted revision. +//! +//! Publication takes the exact profile bytes and the signature bundle that +//! `sendbox governance sign` writes, and verifies them against the operator +//! signers in `FLEET_PROFILE_TRUST`. Hosts verify the same bytes locally, so +//! a session is only admitted when both agree on the exact revision. -use std::collections::BTreeSet; - -use actix_web::web; +use actix_web::{HttpResponse, web}; use sendbox_governance::{GovernanceProfile, ProfileId, ProfileRef}; +use sendbox_security::provenance::{DetachedSignature, SubjectKind}; use serde::{Deserialize, Serialize}; -use super::{Capability, invalid}; +use super::{State, actor, invalid, require_operator}; +use crate::audit::{self, AuditRecord}; use crate::auth::Authenticated; +use crate::governance::{self, StoredProfile}; use crate::problem::Problem; use crate::routes::{json_config, resource}; +use crate::state::to_db; /// Generous enough for a maximum-size profile document after JSON escaping. const PUBLICATION_LIMIT_BYTES: usize = 1024 * 1024; const MAX_SIGNATURES: usize = 16; -const MAX_KEY_ID_BYTES: usize = 128; -const MAX_SIGNATURE_BYTES: usize = 2048; +pub const SIGNATURES_FORMAT: &str = "sendbox.governance-signatures"; +const SIGNATURES_VERSION: u32 = 1; +const MAX_REASON_CHARS: usize = 1000; -/// A profile revision as published by an operator: the exact signed YAML -/// document plus detached signatures over its bytes. The signature envelope is -/// a placeholder until the shared contract defines the operator signing -/// format; signatures are stored but not verified by this scaffold. +/// The detached signature file `sendbox governance sign` produces. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub struct ProfilePublication { - pub document: String, - pub signatures: Vec, +pub struct SignatureBundle { + pub format: String, + pub version: u32, + pub signatures: Vec, } +/// A profile revision as published by an operator. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub struct ProfileSignature { - pub key_id: String, - /// Standard base64 signature over the exact document bytes. - pub signature: String, +pub struct ProfilePublication { + /// The exact signed YAML document. + pub document: String, + pub signatures: SignatureBundle, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -44,7 +52,20 @@ pub struct ProfileRecord { pub not_before_unix: u64, pub expires_at_unix: u64, pub document: String, - pub signatures: Vec, + pub signatures: SignatureBundle, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MinimumRevision { + pub revision: u64, + pub reason: String, +} + +#[derive(Debug, Clone, Copy, Deserialize)] +#[serde(deny_unknown_fields)] +struct RevisionQuery { + revision: Option, } impl ProfilePublication { @@ -57,69 +78,256 @@ impl ProfilePublication { profile.id ))); } - if self.signatures.is_empty() || self.signatures.len() > MAX_SIGNATURES { + if self.signatures.format != SIGNATURES_FORMAT + || self.signatures.version != SIGNATURES_VERSION + { + return Err(Problem::bad_request(format!( + "signatures must use format `{SIGNATURES_FORMAT}` version {SIGNATURES_VERSION}" + ))); + } + if self.signatures.signatures.is_empty() + || self.signatures.signatures.len() > MAX_SIGNATURES + { return Err(Problem::bad_request(format!( "a publication needs 1 to {MAX_SIGNATURES} signatures" ))); } - let mut key_ids = BTreeSet::new(); - for signature in &self.signatures { - let key_id = &signature.key_id; - if key_id.is_empty() - || key_id.len() > MAX_KEY_ID_BYTES - || !key_id.bytes().all(|byte| byte.is_ascii_graphic()) - { - return Err(Problem::bad_request(format!( - "signature key_id must be 1 to {MAX_KEY_ID_BYTES} printable ASCII bytes" - ))); - } - if !key_ids.insert(key_id) { - return Err(Problem::bad_request(format!( - "signature key_id `{key_id}` appears more than once" - ))); - } - if !valid_base64(&signature.signature) { - return Err(Problem::bad_request(format!( - "signature for `{key_id}` must be 1 to {MAX_SIGNATURE_BYTES} bytes of padded standard base64" - ))); - } + for signature in &self.signatures.signatures { + let canonical = signature + .encode() + .map_err(|error| Problem::bad_request(format!("invalid signature: {error}")))?; + DetachedSignature::decode(&canonical) + .map_err(|error| Problem::bad_request(format!("invalid signature: {error}")))?; } Ok(profile) } } -fn valid_base64(value: &str) -> bool { - let body = value.trim_end_matches('='); - !value.is_empty() - && value.len() <= MAX_SIGNATURE_BYTES - && value.len().is_multiple_of(4) - && value.len() - body.len() <= 2 - && body - .bytes() - .all(|byte| byte.is_ascii_alphanumeric() || byte == b'+' || byte == b'/') +pub fn configure(config: &mut web::ServiceConfig) { + config + .service( + resource("/profiles/{profile_id}") + .app_data(json_config(PUBLICATION_LIMIT_BYTES)) + .route(web::get().to(read)) + .route(web::put().to(publish)), + ) + .service( + resource("/profiles/{profile_id}/minimum-revision").route(web::put().to(set_minimum)), + ); } -pub fn configure(config: &mut web::ServiceConfig) { - config.service( - resource("/profiles/{profile_id}") - .app_data(json_config(PUBLICATION_LIMIT_BYTES)) - .route(web::get().to(read)) - .route(web::put().to(publish)), - ); +async fn record( + stored: StoredProfile, + database: &mut crate::db::Database, +) -> Result { + let row = database + .fetch_optional( + "SELECT CAST(signatures AS TEXT) AS signatures FROM profiles \ + WHERE id = $1 AND revision = $2", + &[ + stored.reference.id.as_str().into(), + to_db(stored.reference.revision)?.into(), + ], + ) + .await? + .ok_or_else(Problem::internal)?; + let signatures = serde_json::from_str(&row.text("signatures")?).map_err(|error| { + tracing::error!(%error, "stored profile signatures are invalid"); + Problem::internal() + })?; + Ok(ProfileRecord { + document: String::from_utf8(stored.document).map_err(|_| Problem::internal())?, + reference: stored.reference, + minimum_revision: stored.minimum_revision, + not_before_unix: stored.not_before_unix, + expires_at_unix: stored.expires_at_unix, + signatures: SignatureBundle { + format: SIGNATURES_FORMAT.to_owned(), + version: SIGNATURES_VERSION, + signatures, + }, + }) } async fn read( - _caller: Authenticated, - _profile: web::Path, + state: State, + Authenticated(_caller): Authenticated, + profile: web::Path, + query: web::Query, ) -> Result, Problem> { - Err(Capability::ProfileRead.problem()) + let profile = profile.into_inner(); + let mut database = state.database.clone(); + let stored = match query.revision { + Some(revision) => governance::profile_revision(&mut database, &profile, revision).await?, + None => governance::current_profile(&mut database, &profile, state.now()).await?, + } + .ok_or_else(|| Problem::missing(format!("profile `{profile}` has no such revision")))?; + Ok(web::Json(record(stored, &mut database).await?)) } async fn publish( - _caller: Authenticated, - profile: web::Path, + state: State, + Authenticated(caller): Authenticated, + profile_id: web::Path, publication: web::Json, +) -> Result { + let profile_id = profile_id.into_inner(); + require_operator(&caller, "publish governance profiles")?; + let profile = publication.validate(&profile_id)?; + let now = state.now(); + if now >= profile.expires_at_unix { + return Err(Problem::bad_request(format!( + "profile `{profile_id}` revision {} has already expired", + profile.revision + ))); + } + let trust = state.profile_trust.as_ref().ok_or_else(|| { + Problem::service_unavailable( + "profile signers are not configured; set FLEET_PROFILE_TRUST before publishing", + ) + })?; + let bytes = publication.document.as_bytes(); + let verified = trust + .verify( + bytes, + SubjectKind::Configuration, + &publication.signatures.signatures, + now, + ) + .map_err(|error| { + Problem::forbidden(format!("profile signature verification failed: {error}")) + })?; + let reference = profile.reference(bytes); + let mut tx = state.database.begin_write().await?; + let newest = tx + .fetch_optional( + "SELECT MAX(revision) AS revision FROM profiles WHERE id = $1", + &[profile_id.as_str().into()], + ) + .await? + .and_then(|row| row.opt_int("revision").ok().flatten()); + if newest.is_some_and(|newest| newest >= to_db(profile.revision).unwrap_or(i64::MAX)) { + return Err(Problem::conflict(format!( + "profile `{profile_id}` already has revision {} or newer; publish a higher revision", + profile.revision + ))); + } + let signatures = serde_json::to_string(&publication.signatures.signatures) + .map_err(|_| Problem::internal())?; + tx.execute( + &format!( + "INSERT INTO profiles (id, revision, sha256, signed_bytes, signatures, \ + not_before_unix, expires_at_unix, published_by, published_at_unix) \ + VALUES ($1, $2, $3, $4, {}, $6, $7, $8, $9)", + tx.json_param(5, true) + ), + &[ + profile_id.as_str().into(), + to_db(profile.revision)?.into(), + reference.sha256.to_string().into(), + bytes.to_vec().into(), + signatures.into(), + to_db(profile.not_before_unix)?.into(), + to_db(profile.expires_at_unix)?.into(), + caller.principal.as_str().into(), + to_db(now)?.into(), + ], + ) + .await?; + audit::append( + &mut tx, + now, + AuditRecord { + event_type: "profile.published", + actor: actor(&caller), + profile: Some((profile_id.to_string(), profile.revision)), + detail: Some(format!( + "sha256={} signers={}", + reference.sha256, + verified + .valid_signers + .into_iter() + .collect::>() + .join(",") + )), + ..AuditRecord::default() + }, + ) + .await?; + tx.commit().await?; + let mut database = state.database.clone(); + let stored = governance::profile_revision(&mut database, &profile_id, profile.revision) + .await? + .ok_or_else(Problem::internal)?; + Ok(HttpResponse::Created().json(record(stored, &mut database).await?)) +} + +async fn set_minimum( + state: State, + Authenticated(caller): Authenticated, + profile_id: web::Path, + request: web::Json, ) -> Result, Problem> { - publication.validate(&profile)?; - Err(Capability::ProfilePublication.problem()) + let profile_id = profile_id.into_inner(); + let request = request.into_inner(); + require_operator(&caller, "set minimum profile revisions")?; + let reason = request.reason.trim(); + if reason.is_empty() + || request.reason.chars().count() > MAX_REASON_CHARS + || request.reason.chars().any(char::is_control) + { + return Err(Problem::bad_request(format!( + "reason must be 1 to {MAX_REASON_CHARS} characters without control characters" + ))); + } + let now = state.now(); + let mut tx = state.database.begin_write().await?; + let Some(target) = governance::profile_revision(&mut tx, &profile_id, request.revision).await? + else { + return Err(Problem::missing(format!( + "profile `{profile_id}` has no revision {}", + request.revision + ))); + }; + if request.revision < target.minimum_revision { + return Err(Problem::conflict(format!( + "the minimum revision of `{profile_id}` is already {}; it can only be raised", + target.minimum_revision + ))); + } + tx.execute( + "DELETE FROM profile_minimum_revisions WHERE profile_id = $1", + &[profile_id.as_str().into()], + ) + .await?; + tx.execute( + "INSERT INTO profile_minimum_revisions (profile_id, minimum_revision, reason, set_by, \ + set_at_unix) VALUES ($1, $2, $3, $4, $5)", + &[ + profile_id.as_str().into(), + to_db(request.revision)?.into(), + request.reason.clone().into(), + caller.principal.as_str().into(), + to_db(now)?.into(), + ], + ) + .await?; + audit::append( + &mut tx, + now, + AuditRecord { + event_type: "profile.minimum_revision_set", + actor: actor(&caller), + profile: Some((profile_id.to_string(), request.revision)), + detail: Some(format!("previous={}", target.minimum_revision)), + ..AuditRecord::default() + }, + ) + .await?; + tx.commit().await?; + let mut database = state.database.clone(); + let stored = governance::profile_revision(&mut database, &profile_id, request.revision) + .await? + .ok_or_else(Problem::internal)?; + Ok(web::Json(record(stored, &mut database).await?)) } diff --git a/crates/fleet-server/src/routes/v1/projects.rs b/crates/fleet-server/src/routes/v1/projects.rs index 053703f..3edb9a3 100644 --- a/crates/fleet-server/src/routes/v1/projects.rs +++ b/crates/fleet-server/src/routes/v1/projects.rs @@ -1,28 +1,25 @@ -//! Project-scoped roles. Roles authorize what an authenticated caller may do -//! within one project; they are never derived from workload-supplied fields. +//! Projects and project-scoped roles. Roles decide what an authenticated +//! caller may do within one project; they are never derived from +//! workload-supplied fields. Operators create projects with a first owner; +//! owners (and operators) assign and remove roles. Every change is audited. -use actix_web::web; +use actix_web::{HttpResponse, web}; use sendbox_governance::{PrincipalId, ProjectId}; use serde::{Deserialize, Serialize}; -use super::Capability; -use crate::auth::Authenticated; +use super::{State, actor, caller_role, refuse, require_operator, require_user}; +use crate::audit::{self, AuditRecord}; +use crate::auth::{Authenticated, Caller}; +use crate::db::Tx; +use crate::governance::{self, ProjectRole, Reader}; use crate::problem::Problem; use crate::routes::resource; +use crate::state::to_db; -/// Ordered from most to least privileged. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ProjectRole { - /// Manages roles and approves exceptions for the project. - Owner, - /// Approves exceptions and revokes grants. - Admin, - /// Starts governed sessions within the profile ceiling. - Member, - /// Reads sessions and audit events. - Viewer, -} +/// Principal kind used by single-host increment 1 for local OS accounts. A +/// shared service authenticates its own principals and never binds these. +const LOCAL_PRINCIPAL_KIND: &str = "local-user"; +const MAX_DISPLAY_NAME_CHARS: usize = 200; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -38,34 +35,323 @@ pub struct ProjectRoles { pub bindings: Vec, } -/// Principal kind used by single-host increment 1 for local OS accounts. A -/// shared service authenticates its own principals and never binds these. -const LOCAL_PRINCIPAL_KIND: &str = "local-user"; +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CreateProject { + pub project: ProjectId, + pub owner: PrincipalId, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub display_name: Option, +} pub fn configure(config: &mut web::ServiceConfig) { - config.service( - resource("/projects/{project_id}/roles") - .route(web::get().to(list)) - .route(web::post().to(assign)), - ); + config + .service(resource("/projects").route(web::post().to(create))) + .service( + resource("/projects/{project_id}/roles") + .route(web::get().to(list)) + .route(web::post().to(assign)), + ) + .service( + resource("/projects/{project_id}/roles/{principal_id}").route(web::delete().to(remove)), + ); +} + +fn reject_local(principal: &PrincipalId) -> Result<(), Problem> { + if principal.kind() == LOCAL_PRINCIPAL_KIND { + return Err(Problem::bad_request( + "local-user principals belong to a single host and cannot hold project roles", + )); + } + Ok(()) +} + +async fn bindings(reader: &mut impl Reader, project: &ProjectId) -> Result { + let rows = reader + .rows( + "SELECT principal_id, role FROM role_bindings WHERE project_id = $1 \ + ORDER BY principal_id", + &[project.as_str().into()], + ) + .await?; + let mut bindings = Vec::with_capacity(rows.len()); + for row in rows { + let principal = + PrincipalId::new(row.text("principal_id")?).map_err(|_| Problem::internal())?; + let role = serde_json::from_value(serde_json::Value::String(row.text("role")?)) + .map_err(|_| Problem::internal())?; + bindings.push(RoleBinding { principal, role }); + } + Ok(ProjectRoles { + project: project.clone(), + bindings, + }) +} + +async fn create( + state: State, + Authenticated(caller): Authenticated, + request: web::Json, +) -> Result { + let request = request.into_inner(); + require_operator(&caller, "create projects")?; + reject_local(&request.owner)?; + if let Some(name) = &request.display_name + && (name.trim().is_empty() + || name.chars().count() > MAX_DISPLAY_NAME_CHARS + || name.chars().any(char::is_control)) + { + return Err(Problem::bad_request(format!( + "display_name must be 1 to {MAX_DISPLAY_NAME_CHARS} characters without control characters" + ))); + } + let now = state.now(); + let mut tx = state.database.begin_write().await?; + if governance::project_exists(&mut tx, &request.project).await? { + return Err(Problem::conflict(format!( + "project `{}` already exists", + request.project + ))); + } + if !governance::principal_active(&mut tx, &request.owner).await? { + return Err(Problem::missing(format!( + "principal `{}` does not exist or is disabled", + request.owner + ))); + } + tx.execute( + "INSERT INTO projects (id, display_name, created_at_unix) VALUES ($1, $2, $3)", + &[ + request.project.as_str().into(), + request.display_name.clone().into(), + to_db(now)?.into(), + ], + ) + .await?; + tx.execute( + "INSERT INTO role_bindings (project_id, principal_id, role, granted_by, granted_at_unix) \ + VALUES ($1, $2, 'owner', $3, $4)", + &[ + request.project.as_str().into(), + request.owner.as_str().into(), + caller.principal.as_str().into(), + to_db(now)?.into(), + ], + ) + .await?; + for (event_type, principal, detail) in [ + ("project.created", None, None), + ( + "role.assigned", + Some(request.owner.to_string()), + Some("role=owner".to_owned()), + ), + ] { + audit::append( + &mut tx, + now, + AuditRecord { + event_type, + actor: actor(&caller), + principal, + project: Some(request.project.to_string()), + detail, + ..AuditRecord::default() + }, + ) + .await?; + } + let roles = bindings(&mut tx, &request.project).await?; + tx.commit().await?; + Ok(HttpResponse::Created().json(roles)) } async fn list( - _caller: Authenticated, - _project: web::Path, + state: State, + Authenticated(caller): Authenticated, + project: web::Path, ) -> Result, Problem> { - Err(Capability::RoleListing.problem()) + let project = project.into_inner(); + let mut database = state.database.clone(); + let role = caller_role(&mut database, &project, &caller).await?; + if !caller.operator && role.is_none() { + return Err(Problem::forbidden(format!( + "you hold no role in project `{project}`" + ))); + } + Ok(web::Json(bindings(&mut database, &project).await?)) +} + +/// Owners manage roles; operators may too, for example to recover ownership. +async fn authorize_role_change( + state: &State, + mut tx: Tx, + caller: &Caller, + project: &ProjectId, + principal: &PrincipalId, + detail: String, +) -> Result { + let role = caller_role(&mut tx, project, caller).await?; + if caller.operator || role == Some(ProjectRole::Owner) { + return Ok(tx); + } + refuse( + state, + tx, + AuditRecord { + event_type: "role.change_refused", + actor: actor(caller), + principal: Some(principal.to_string()), + project: Some(project.to_string()), + detail: Some(detail), + ..AuditRecord::default() + }, + Problem::forbidden(format!("only owners of `{project}` can change its roles")), + ) + .await +} + +/// Refuses to leave a project without an owner. +async fn keep_an_owner( + tx: &mut Tx, + project: &ProjectId, + principal: &PrincipalId, + new_role: Option, +) -> Result<(), Problem> { + if governance::role_of(tx, project, principal).await? != Some(ProjectRole::Owner) + || new_role == Some(ProjectRole::Owner) + { + return Ok(()); + } + let owners = tx + .fetch_all( + "SELECT principal_id FROM role_bindings WHERE project_id = $1 AND role = 'owner'", + &[project.as_str().into()], + ) + .await? + .len(); + if owners <= 1 { + return Err(Problem::conflict(format!( + "`{principal}` is the last owner of `{project}`; assign another owner first" + ))); + } + Ok(()) } async fn assign( - _caller: Authenticated, - _project: web::Path, + state: State, + Authenticated(caller): Authenticated, + project: web::Path, binding: web::Json, ) -> Result, Problem> { - if binding.principal.kind() == LOCAL_PRINCIPAL_KIND { - return Err(Problem::bad_request( - "local-user principals belong to a single host and cannot hold project roles", - )); + let project = project.into_inner(); + let binding = binding.into_inner(); + require_user(&caller, "change project roles")?; + reject_local(&binding.principal)?; + let now = state.now(); + let tx = state.database.begin_write().await?; + let mut tx = authorize_role_change( + &state, + tx, + &caller, + &project, + &binding.principal, + format!("role={}", binding.role.code()), + ) + .await?; + if !governance::principal_active(&mut tx, &binding.principal).await? { + return Err(Problem::missing(format!( + "principal `{}` does not exist or is disabled", + binding.principal + ))); + } + keep_an_owner(&mut tx, &project, &binding.principal, Some(binding.role)).await?; + let previous = governance::role_of(&mut tx, &project, &binding.principal).await?; + if previous != Some(binding.role) { + tx.execute( + "DELETE FROM role_bindings WHERE project_id = $1 AND principal_id = $2", + &[project.as_str().into(), binding.principal.as_str().into()], + ) + .await?; + tx.execute( + "INSERT INTO role_bindings (project_id, principal_id, role, granted_by, \ + granted_at_unix) VALUES ($1, $2, $3, $4, $5)", + &[ + project.as_str().into(), + binding.principal.as_str().into(), + binding.role.code().into(), + caller.principal.as_str().into(), + to_db(now)?.into(), + ], + ) + .await?; + audit::append( + &mut tx, + now, + AuditRecord { + event_type: "role.assigned", + actor: actor(&caller), + principal: Some(binding.principal.to_string()), + project: Some(project.to_string()), + detail: Some(match previous { + Some(previous) => { + format!("role={} previous={}", binding.role.code(), previous.code()) + } + None => format!("role={}", binding.role.code()), + }), + ..AuditRecord::default() + }, + ) + .await?; } - Err(Capability::RoleAssignment.problem()) + let roles = bindings(&mut tx, &project).await?; + tx.commit().await?; + Ok(web::Json(roles)) +} + +async fn remove( + state: State, + Authenticated(caller): Authenticated, + path: web::Path<(ProjectId, PrincipalId)>, +) -> Result, Problem> { + let (project, principal) = path.into_inner(); + require_user(&caller, "change project roles")?; + let now = state.now(); + let tx = state.database.begin_write().await?; + let mut tx = authorize_role_change( + &state, + tx, + &caller, + &project, + &principal, + "role=none".to_owned(), + ) + .await?; + let Some(previous) = governance::role_of(&mut tx, &project, &principal).await? else { + return Err(Problem::missing(format!( + "`{principal}` holds no role in `{project}`" + ))); + }; + keep_an_owner(&mut tx, &project, &principal, None).await?; + tx.execute( + "DELETE FROM role_bindings WHERE project_id = $1 AND principal_id = $2", + &[project.as_str().into(), principal.as_str().into()], + ) + .await?; + audit::append( + &mut tx, + now, + AuditRecord { + event_type: "role.removed", + actor: actor(&caller), + principal: Some(principal.to_string()), + project: Some(project.to_string()), + detail: Some(format!("previous={}", previous.code())), + ..AuditRecord::default() + }, + ) + .await?; + let roles = bindings(&mut tx, &project).await?; + tx.commit().await?; + Ok(web::Json(roles)) } diff --git a/crates/fleet-server/src/routes/v1/sessions.rs b/crates/fleet-server/src/routes/v1/sessions.rs index b7dbc15..a73fa70 100644 --- a/crates/fleet-server/src/routes/v1/sessions.rs +++ b/crates/fleet-server/src/routes/v1/sessions.rs @@ -1,40 +1,300 @@ -//! `POST /v1/sessions:admit`: admit a session under a governance profile. +//! Session admission and end. +//! +//! A SendBox host admits each governed session before it starts. The binding +//! principal must be the authenticated caller, who needs at least the +//! `member` role in the project. The binding must name this authority and the +//! profile's current revision, and every exception it lifts must be approved, +//! unrevoked, unexpired, bound to that exact revision, and permitted by it. -use actix_web::web; -use sendbox_governance::{GovernanceBinding, SessionRef, Sha256Digest}; -use serde::{Deserialize, Serialize}; +use actix_web::{HttpResponse, web}; +use sendbox_governance::api::{SessionAdmission, SessionAdmissionRequest, SessionEnd}; +use sendbox_governance::{DenyReason, SessionRef}; -use super::{Capability, invalid}; +use super::{State, actor, caller_role, invalid, refuse}; +use crate::audit::{self, AuditDecision, AuditRecord}; use crate::auth::Authenticated; +use crate::governance::{self, ProjectRole, SessionStatus}; use crate::problem::Problem; use crate::routes::resource; - -/// Submitted by a SendBox host (an authenticated worker) before it starts a -/// governed session. The binding's principal and project are claims to be -/// checked against the caller and its project roles, never trusted as-is. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct SessionAdmissionRequest { - pub session: SessionRef, - pub binding: GovernanceBinding, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct SessionAdmission { - pub session: SessionRef, - pub binding_sha256: Sha256Digest, - pub admitted_at_unix: u64, -} +use crate::state::to_db; pub fn configure(config: &mut web::ServiceConfig) { - config.service(resource("/sessions:admit").route(web::post().to(admit))); + config + .service(resource("/sessions:admit").route(web::post().to(admit))) + .service(resource("/sessions/{session_id:[^/:]+}:end").route(web::post().to(end))); } async fn admit( - _caller: Authenticated, + state: State, + Authenticated(caller): Authenticated, request: web::Json, ) -> Result, Problem> { - request.binding.validate().map_err(invalid)?; - Err(Capability::SessionAdmission.problem()) + let SessionAdmissionRequest { session, binding } = request.into_inner(); + let binding_sha256 = binding.digest().map_err(invalid)?; + let now = state.now(); + let mut tx = state.database.begin_write().await?; + let record = AuditRecord { + event_type: "session.refused", + actor: Some(caller.principal.to_string()), + principal: Some(binding.principal.to_string()), + project: Some(binding.project.to_string()), + session: Some(session.to_string()), + profile: Some((binding.profile.id.to_string(), binding.profile.revision)), + ..AuditRecord::default() + }; + if binding.principal != caller.principal { + return refuse( + &state, + tx, + record, + Problem::forbidden( + "the binding principal must be the authenticated caller; a host cannot claim another identity", + ), + ) + .await; + } + if binding.authority.id != state.authority_id { + return refuse( + &state, + tx, + record, + Problem::forbidden(format!( + "the binding names authority `{}`, but this service is `{}`", + binding.authority.id, state.authority_id + )), + ) + .await; + } + let role = caller_role(&mut tx, &binding.project, &caller).await?; + if !role.is_some_and(|role| role.at_least(ProjectRole::Member)) { + return refuse( + &state, + tx, + record, + Problem::forbidden(format!( + "running governed sessions in `{}` requires the member role or higher", + binding.project + )), + ) + .await; + } + let profile = match governance::require_current(&mut tx, &binding.profile, now).await { + Ok(profile) => profile.parse()?, + Err(reason) => { + return refuse( + &state, + tx, + AuditRecord { + decision: Some(AuditDecision::Deny), + deny_reason: Some(reason), + ..record + }, + Problem::conflict(format!( + "profile `{}` revision {} is not the current revision ({})", + binding.profile.id, + binding.profile.revision, + reason.code() + )), + ) + .await; + } + }; + if let Some(service) = binding + .brokered_services + .iter() + .find(|service| profile.credential_service(service).is_none()) + { + return refuse( + &state, + tx, + record, + Problem::forbidden(format!( + "credential service `{service}` is not offered by the profile" + )), + ) + .await; + } + let mut exceptions = Vec::with_capacity(binding.exceptions.len()); + for id in &binding.exceptions { + let exception = governance::exception(&mut tx, id).await?; + let usable = exception.as_ref().is_some_and(|exception| { + exception.applies_to(&binding.project, &binding.principal, &binding.profile, now) + && profile.permits_exception(&exception.scope) + }); + let Some(exception) = exception.filter(|_| usable) else { + return refuse( + &state, + tx, + AuditRecord { + exception: Some(id.to_string()), + decision: Some(AuditDecision::Deny), + deny_reason: Some(DenyReason::StalePolicy), + ..record + }, + Problem::conflict(format!( + "exception `{id}` is not an approved, active exception for this session and profile revision" + )), + ) + .await; + }; + exceptions.push(exception); + } + if governance::session(&mut tx, &session).await?.is_some() { + return Err(Problem::conflict(format!( + "session `{session}` was already admitted" + ))); + } + let canonical = serde_json_canonicalizer::to_string(&binding).map_err(|error| { + tracing::error!(%error, "binding encoding failed"); + Problem::internal() + })?; + tx.execute( + &format!( + "INSERT INTO sessions (id, principal_id, project_id, authority_id, profile_id, \ + profile_revision, profile_sha256, effective_policy_sha256, binding, binding_sha256, \ + status, admitted_by, admitted_at_unix) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, {}, \ + $10, 'admitted', $11, $12)", + tx.json_param(9, false) + ), + &[ + session.as_str().into(), + binding.principal.as_str().into(), + binding.project.as_str().into(), + binding.authority.id.clone().into(), + binding.profile.id.as_str().into(), + to_db(binding.profile.revision)?.into(), + binding.profile.sha256.to_string().into(), + binding.effective_policy_sha256.to_string().into(), + canonical.into(), + binding_sha256.to_string().into(), + caller.principal.as_str().into(), + to_db(now)?.into(), + ], + ) + .await?; + audit::append( + &mut tx, + now, + AuditRecord { + event_type: "session.admitted", + decision: Some(AuditDecision::Allow), + detail: Some(format!( + "binding_sha256={binding_sha256} services={}", + binding + .brokered_services + .iter() + .map(ToString::to_string) + .collect::>() + .join(",") + )), + ..record.clone() + }, + ) + .await?; + for exception in &exceptions { + tx.execute( + "INSERT INTO session_exceptions (session_id, exception_id) VALUES ($1, $2)", + &[session.as_str().into(), exception.id.as_str().into()], + ) + .await?; + audit::append( + &mut tx, + now, + AuditRecord { + event_type: "exception.applied", + exception: Some(exception.id.to_string()), + detail: Some(format!("scope={}", exception.scope)), + ..record.clone() + }, + ) + .await?; + } + tx.commit().await?; + Ok(web::Json(SessionAdmission { + session, + binding_sha256, + admitted_at_unix: now, + })) +} + +async fn end( + state: State, + Authenticated(caller): Authenticated, + session: web::Path, + request: web::Json, +) -> Result { + let session = session.into_inner(); + let outcome = request.outcome; + let now = state.now(); + let mut tx = state.database.begin_write().await?; + let stored = governance::session(&mut tx, &session) + .await? + .ok_or_else(|| Problem::missing(format!("session `{session}` was not admitted")))?; + if stored.binding.principal != caller.principal { + return Err(Problem::forbidden( + "only the session's principal can end it", + )); + } + if stored.status == SessionStatus::Ended { + return Ok(HttpResponse::NoContent().finish()); + } + tx.execute( + "UPDATE sessions SET status = $2, ended_at_unix = $3 WHERE id = $1", + &[ + session.as_str().into(), + outcome.code().into(), + to_db(now)?.into(), + ], + ) + .await?; + let base = AuditRecord { + actor: actor(&caller), + principal: Some(stored.binding.principal.to_string()), + project: Some(stored.binding.project.to_string()), + session: Some(session.to_string()), + profile: Some(( + stored.binding.profile.id.to_string(), + stored.binding.profile.revision, + )), + ..AuditRecord::default() + }; + audit::append( + &mut tx, + now, + AuditRecord { + event_type: "session.ended", + detail: Some(format!("outcome={}", outcome.code())), + ..base.clone() + }, + ) + .await?; + let grace = governance::profile_revision( + &mut tx, + &stored.binding.profile.id, + stored.binding.profile.revision, + ) + .await? + .map(|profile| profile.parse()) + .transpose()? + .map_or(0, |profile| profile.grants.revocation_grace_seconds); + let reason = outcome.revocation_reason(); + for grant_id in governance::live_grants(&mut tx, &session).await? { + let Some(grant) = governance::grant(&mut tx, &grant_id).await? else { + continue; + }; + governance::revoke_grant(&mut tx, &grant.grant, reason, None, grace, now).await?; + audit::append( + &mut tx, + now, + AuditRecord { + event_type: "grant.revoked", + grant: Some(grant_id.to_string()), + detail: Some(format!("reason={}", reason.code())), + ..base.clone() + }, + ) + .await?; + } + tx.commit().await?; + Ok(HttpResponse::NoContent().finish()) } diff --git a/crates/fleet-server/src/routes/v1/whoami.rs b/crates/fleet-server/src/routes/v1/whoami.rs new file mode 100644 index 0000000..2103942 --- /dev/null +++ b/crates/fleet-server/src/routes/v1/whoami.rs @@ -0,0 +1,19 @@ +//! `GET /v1/whoami`: the identity this service authenticated. + +use actix_web::web; +use sendbox_governance::api::CallerIdentity; + +use crate::auth::Authenticated; +use crate::routes::resource; + +pub fn configure(config: &mut web::ServiceConfig) { + config.service(resource("/whoami").route(web::get().to(whoami))); +} + +async fn whoami(Authenticated(caller): Authenticated) -> web::Json { + web::Json(CallerIdentity { + principal: caller.principal, + kind: caller.kind, + operator: caller.operator, + }) +} diff --git a/crates/fleet-server/src/server.rs b/crates/fleet-server/src/server.rs index 0170ea4..33da3f5 100644 --- a/crates/fleet-server/src/server.rs +++ b/crates/fleet-server/src/server.rs @@ -14,12 +14,13 @@ use thiserror::Error; use time::OffsetDateTime; use tokio::task::JoinHandle; -use crate::auth::{self, SharedAuthenticator, UnconfiguredAuthenticator}; -use crate::config::Config; +use crate::auth::{self, DatabaseAuthenticator, SharedAuthenticator}; +use crate::config::{Config, ConfigError, ProfileTrust}; use crate::db::{Database, DbError}; use crate::logging::{self, retention}; use crate::problem; use crate::routes; +use crate::state::{AppState, os_random}; /// Time in-flight requests get to finish after SIGINT or SIGTERM. const SHUTDOWN_GRACE_SECONDS: u64 = 30; @@ -27,6 +28,8 @@ const RETENTION_INTERVAL: Duration = Duration::from_secs(60 * 60); #[derive(Debug, Error)] pub enum ServerError { + #[error(transparent)] + Config(#[from] ConfigError), #[error(transparent)] Database(#[from] DbError), #[error("cannot listen on {address}: {source}")] @@ -40,7 +43,7 @@ pub enum ServerError { /// Builds the application. Shared by the server and the HTTP tests. pub fn app( - database: web::Data, + state: web::Data, authenticator: SharedAuthenticator, ) -> App< impl ServiceFactory< @@ -52,7 +55,8 @@ pub fn app( >, > { App::new() - .app_data(database) + .app_data(web::Data::new(state.database.clone())) + .app_data(state) .app_data(authenticator) .wrap(from_fn(logging::request_log)) .configure(routes::configure) @@ -61,6 +65,11 @@ pub fn app( /// Connects and migrates the database, then serves until SIGINT or SIGTERM. pub async fn run(config: Config, log_dir: PathBuf) -> Result<(), ServerError> { + let profile_trust = config + .profile_trust + .as_deref() + .map(ProfileTrust::load) + .transpose()?; let retention = spawn_retention(log_dir.clone(), config.logging.retention_days); let database = Database::connect(&config.database_url).await?; database.migrate().await?; @@ -68,16 +77,29 @@ pub async fn run(config: Config, log_dir: PathBuf) -> Result<(), ServerError> { bind = %config.bind, database = %config.database_url, log_dir = %log_dir.display(), + authority_id = %config.authority_id, contract_version = crate::CONTRACT_VERSION, "sendbox-fleet starting" ); - tracing::warn!( - "no authentication provider is configured; every /v1 request is rejected with 401" - ); + if profile_trust.is_none() { + tracing::warn!( + "FLEET_PROFILE_TRUST is not set; profile publication is refused until it is configured" + ); + } - let data = web::Data::new(database.clone()); - let authenticator = auth::shared(Arc::new(UnconfiguredAuthenticator)); - let server = HttpServer::new(move || app(data.clone(), authenticator.clone())) + let clock: Arc = Arc::new(sendbox_governance::SystemClock); + let state = web::Data::new(AppState { + database: database.clone(), + clock: Arc::clone(&clock), + random: Arc::new(os_random), + authority_id: config.authority_id.clone(), + profile_trust, + }); + let authenticator = auth::shared(Arc::new(DatabaseAuthenticator::new( + database.clone(), + clock, + ))); + let server = HttpServer::new(move || app(state.clone(), authenticator.clone())) .shutdown_timeout(SHUTDOWN_GRACE_SECONDS) .bind(config.bind) .map_err(|source| ServerError::Bind { diff --git a/crates/fleet-server/src/state.rs b/crates/fleet-server/src/state.rs new file mode 100644 index 0000000..478687f --- /dev/null +++ b/crates/fleet-server/src/state.rs @@ -0,0 +1,59 @@ +//! Shared application state: storage, time, identity of this authority, and +//! the trust that verifies published profiles. + +use std::sync::Arc; + +use sendbox_governance::{Clock, GovernanceError}; +use sendbox_security::provenance::TrustStore; + +use crate::db::Database; +use crate::problem::Problem; + +pub type RandomSource = dyn Fn() -> Result<[u8; 16], GovernanceError> + Send + Sync; + +pub struct AppState { + pub database: Database, + pub clock: Arc, + pub random: Arc, + /// Must equal `GovernanceBinding.authority.id` in every admitted session. + pub authority_id: String, + /// Operator signers that profile publications must satisfy. Publication + /// is refused while this is unset. + pub profile_trust: Option, +} + +impl AppState { + #[must_use] + pub fn now(&self) -> u64 { + self.clock.now_unix() + } + + /// A fresh random identifier as 32 lowercase hex characters. + pub fn new_id(&self) -> Result<[u8; 16], Problem> { + (self.random)().map_err(|error| { + tracing::error!(%error, "random identifier generation failed"); + Problem::internal() + }) + } +} + +/// Random bytes from the operating system. +pub fn os_random() -> Result<[u8; 16], GovernanceError> { + let mut bytes = [0_u8; 16]; + getrandom::fill(&mut bytes) + .map_err(|error| GovernanceError::AuthorityUnavailable(error.to_string()))?; + Ok(bytes) +} + +/// Signed 64-bit storage for unsigned contract times and counters. +pub fn to_db(value: u64) -> Result { + i64::try_from(value).map_err(|_| Problem::bad_request("a number is out of range")) +} + +/// Reads a stored non-negative number back into the contract's `u64`. +pub fn from_db(value: i64) -> Result { + u64::try_from(value).map_err(|_| { + tracing::error!(value, "stored number is negative"); + Problem::internal() + }) +} diff --git a/crates/fleet-server/tests/http.rs b/crates/fleet-server/tests/http.rs index e2de432..5963f97 100644 --- a/crates/fleet-server/tests/http.rs +++ b/crates/fleet-server/tests/http.rs @@ -1,604 +1,1287 @@ -//! HTTP behaviour of the scaffold: probes, authentication before validation, -//! contract validation, and explicit 501 responses. All data is synthetic. +//! HTTP behaviour of the shared governance service: authentication before +//! validation, project roles, signed profiles, session admission, grants, +//! authorization, exceptions, and the audit chain. All data is synthetic. +//! +//! Runs against in-memory SQLite by default. Set `FLEET_TEST_DATABASE_URL` to +//! a PostgreSQL database whose name ends in `_test` to run the same requests +//! against PostgreSQL; its `public` schema is dropped and recreated by every +//! test, so run with `--test-threads=1`. +use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; use actix_web::body::MessageBody; use actix_web::dev::{Service, ServiceResponse}; use actix_web::http::{Method, StatusCode, header}; use actix_web::{test, web}; -use fleet_server::auth::{self, AuthError, AuthFuture, Authenticator, Caller, CallerKind}; +use fleet_server::auth::{self, DatabaseAuthenticator, token_from_bytes}; use fleet_server::config::DatabaseUrl; -use fleet_server::db::Database; +use fleet_server::db::{Arg, Database}; use fleet_server::server; -use sendbox_governance::PrincipalId; +use fleet_server::state::AppState; +use sendbox_governance::{ + AuthorityRef, CONTRACT_VERSION, Clock, ExceptionId, GovernanceBinding, PrincipalId, ProfileRef, + ProjectId, ServiceId, SessionRef, Sha256Digest, +}; +use sendbox_security::provenance::{ + DetachedSignature, SignedSubject, SigningKeyMaterial, SubjectKind, TrustPolicy, TrustStore, +}; use serde_json::{Value, json}; -const TEST_TOKEN: &str = "synthetic-test-token"; -const SESSION: &str = "0123456789abcdef0123456789abcdef"; -const GRANT: &str = "fedcba9876543210fedcba9876543210"; -const PROFILE_YAML: &str = "\ -format: sendbox.governance-profile +const NOW: u64 = 1_800_000_000; +const AUTHORITY: &str = "fleet.example.com"; +const PROJECT: &str = "github:example/service"; +const PROJECT_PATH: &str = "github:example%2Fservice"; + +const OPERATOR: &str = "oidc:olivia@example.com"; +const OWNER: &str = "oidc:owen@example.com"; +const ADMIN: &str = "oidc:ada@example.com"; +const MEMBER: &str = "oidc:alice@example.com"; +const BOB: &str = "oidc:bob@example.com"; +const VIEWER: &str = "oidc:vera@example.com"; +const WORKER: &str = "worker:ci-1"; +const OUTSIDER: &str = "oidc:mallory@example.com"; + +struct TestClock(AtomicU64); + +impl Clock for TestClock { + fn now_unix(&self) -> u64 { + self.0.load(Ordering::SeqCst) + } +} + +fn profile_yaml(revision: u64) -> String { + format!( + r#"format: sendbox.governance-profile version: 1 -id: example-default -revision: 3 -not_before_unix: 1790000000 -expires_at_unix: 1800000000 +id: acme +revision: {revision} +not_before_unix: {} +expires_at_unix: {} ceiling: runtimes: [apple, kata] commands: default_action: deny + allowlist: ["git *"] network: default_action: deny -"; - -/// Accepts exactly one synthetic token, standing in for a real identity provider. -struct MockAuthenticator; - -impl Authenticator for MockAuthenticator { - fn authenticate<'a>(&'a self, bearer_token: &'a str) -> AuthFuture<'a> { - Box::pin(async move { - if bearer_token == TEST_TOKEN { - Ok(Caller { - principal: PrincipalId::new("oidc:alice@example.com").unwrap(), - kind: CallerKind::User, - }) - } else { - Err(AuthError::InvalidToken) - } - }) - } + allowed_domains: ["*.github.com"] +denials: + commands: ["git push --force *"] + domains: [gist.github.com, pastebin.com] +credential_services: + - id: anthropic + provider: anthropic + secret: SENDBOX_ANTHROPIC_API_KEY +grants: + lease_seconds: 60 + max_ttl_seconds: 3600 + revocation_grace_seconds: 5 + max_concurrent_streams: 4 +exceptions: + max_ttl_seconds: 86400 + commands: ["git push --force *"] + domains: [gist.github.com] +"#, + NOW - 100, + NOW + 30 * 86_400 + ) +} + +fn publication(document: &str, key: &SigningKeyMaterial) -> Value { + let signature = DetachedSignature::sign( + SignedSubject::from_bytes(SubjectKind::Configuration, None, document.as_bytes()), + key, + NOW - 10, + None, + BTreeMap::new(), + ) + .unwrap(); + json!({ + "document": document, + "signatures": { + "format": "sendbox.governance-signatures", + "version": 1, + "signatures": [signature], + } + }) +} + +struct Fleet { + service: S, + database: Database, + clock: Arc, + key: SigningKeyMaterial, + tokens: HashMap<&'static str, String>, } -async fn database() -> Database { - let database = Database::connect(&DatabaseUrl::parse("sqlite::memory:").unwrap()) +async fn fleet() -> Fleet< + impl Service< + actix_http::Request, + Response = ServiceResponse, + Error = actix_web::Error, + >, +> { + let url = + std::env::var("FLEET_TEST_DATABASE_URL").unwrap_or_else(|_| "sqlite::memory:".to_owned()); + let database = Database::connect(&DatabaseUrl::parse(&url).unwrap()) .await .unwrap(); + if let Database::Postgres(pool) = &database { + let name: String = sqlx::query_scalar("SELECT current_database()") + .fetch_one(pool) + .await + .unwrap(); + assert!( + name.ends_with("_test"), + "refusing to reset database `{name}`: FLEET_TEST_DATABASE_URL must name a database ending in `_test`" + ); + sqlx::raw_sql("DROP SCHEMA public CASCADE; CREATE SCHEMA public;") + .execute(pool) + .await + .unwrap(); + } database.migrate().await.unwrap(); - database + let clock = Arc::new(TestClock(AtomicU64::new(NOW))); + let key = SigningKeyMaterial::generate().unwrap(); + let mut trust = TrustStore::new(TrustPolicy { + allow_unsigned: false, + threshold: 1, + required_signers: Default::default(), + }); + trust + .add_identity(key.identity("Example operator", None, 0, None)) + .unwrap(); + + let mut tokens = HashMap::new(); + let mut tx = database.begin_write().await.unwrap(); + for (index, (principal, kind, operator)) in [ + (OPERATOR, "user", true), + (OWNER, "user", false), + (ADMIN, "user", false), + (MEMBER, "user", false), + (BOB, "user", false), + (VIEWER, "user", false), + (WORKER, "worker", false), + (OUTSIDER, "user", false), + ] + .into_iter() + .enumerate() + { + tx.execute( + "INSERT INTO principals (id, kind, created_at_unix, is_operator) VALUES ($1, $2, $3, $4)", + &[principal.into(), kind.into(), Arg::from(0_i64), operator.into()], + ) + .await + .unwrap(); + let byte = u8::try_from(index).unwrap() + 1; + let (token, digest) = token_from_bytes(&[byte; 32]); + tx.execute( + "INSERT INTO api_tokens (id, principal_id, token_sha256, created_at_unix, \ + expires_at_unix) VALUES ($1, $2, $3, $4, $5)", + &[ + format!("{byte:02x}").repeat(16).into(), + principal.into(), + digest.into(), + Arg::from(i64::try_from(NOW - 10).unwrap()), + Arg::from(i64::try_from(NOW + 7 * 86_400).unwrap()), + ], + ) + .await + .unwrap(); + tokens.insert(principal, token); + } + tx.commit().await.unwrap(); + + let state = web::Data::new(AppState { + database: database.clone(), + clock: clock.clone(), + random: Arc::new(fleet_server::state::os_random), + authority_id: AUTHORITY.to_owned(), + profile_trust: Some(trust), + }); + let authenticator = auth::shared(Arc::new(DatabaseAuthenticator::new( + database.clone(), + clock.clone(), + ))); + let service = test::init_service(server::app(state, authenticator)).await; + Fleet { + service, + database, + clock, + key, + tokens, + } } -async fn service( - database: Database, - authenticator: Arc, -) -> impl Service< - actix_http::Request, - Response = ServiceResponse, - Error = actix_web::Error, -> { - test::init_service(server::app( - web::Data::new(database), - auth::shared(authenticator), - )) - .await +impl Fleet +where + S: Service, Error = actix_web::Error>, + B: MessageBody, +{ + async fn send( + &self, + method: Method, + path: &str, + token: Option<&str>, + body: Option<&Value>, + ) -> (StatusCode, Value) { + let mut request = test::TestRequest::default().method(method).uri(path); + if let Some(token) = token { + request = request.insert_header((header::AUTHORIZATION, format!("Bearer {token}"))); + } + let request = match body { + Some(body) => request.set_json(body).to_request(), + None => request.to_request(), + }; + let response = test::call_service(&self.service, request).await; + let status = response.status(); + let bytes = test::read_body(response).await; + let value = if bytes.is_empty() { + Value::Null + } else { + serde_json::from_slice(&bytes).unwrap() + }; + if status.is_client_error() || status.is_server_error() { + assert_eq!(value["status"], status.as_u16(), "{value}"); + assert!( + value["detail"] + .as_str() + .is_some_and(|detail| !detail.is_empty()) + ); + } + (status, value) + } + + async fn call( + &self, + as_: &str, + method: Method, + path: &str, + body: Option, + ) -> (StatusCode, Value) { + let token = self.tokens.get(as_).map(String::as_str); + self.send(method, path, token, body.as_ref()).await + } + + fn advance(&self, seconds: u64) { + self.clock.0.fetch_add(seconds, Ordering::SeqCst); + } + + fn now(&self) -> u64 { + self.clock.now_unix() + } + + async fn publish(&self, revision: u64) -> ProfileRef { + let (status, body) = self + .call( + OPERATOR, + Method::PUT, + "/v1/profiles/acme", + Some(publication(&profile_yaml(revision), &self.key)), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{body}"); + serde_json::from_value(body["reference"].clone()).unwrap() + } + + /// A project with an owner, an admin, two members, a viewer, and a worker. + async fn project(&self) -> ProfileRef { + let profile = self.publish(3).await; + let (status, body) = self + .call( + OPERATOR, + Method::POST, + "/v1/projects", + Some(json!({ "project": PROJECT, "owner": OWNER })), + ) + .await; + assert_eq!(status, StatusCode::CREATED, "{body}"); + for (principal, role) in [ + (ADMIN, "admin"), + (MEMBER, "member"), + (BOB, "member"), + (VIEWER, "viewer"), + (WORKER, "member"), + ] { + let (status, body) = self + .call( + OWNER, + Method::POST, + &format!("/v1/projects/{PROJECT_PATH}/roles"), + Some(json!({ "principal": principal, "role": role })), + ) + .await; + assert_eq!(status, StatusCode::OK, "{body}"); + } + profile + } + + async fn request_exception( + &self, + as_: &str, + profile: &ProfileRef, + kind: &str, + value: &str, + ) -> (StatusCode, Value) { + self.call( + as_, + Method::POST, + "/v1/exceptions", + Some(json!({ + "project": PROJECT, + "profile": profile, + "scope": { "kind": kind, "value": value }, + "reason": "Synthetic release window", + "expires_at_unix": self.now() + 3_600, + })), + ) + .await + } + + async fn approved_exception(&self, profile: &ProfileRef) -> ExceptionId { + let (status, body) = self + .request_exception(MEMBER, profile, "domain", "gist.github.com") + .await; + assert_eq!(status, StatusCode::CREATED, "{body}"); + let id: ExceptionId = serde_json::from_value(body["id"].clone()).unwrap(); + let (status, body) = self + .call( + ADMIN, + Method::POST, + &format!("/v1/exceptions/{id}:approve"), + None, + ) + .await; + assert_eq!(status, StatusCode::OK, "{body}"); + id + } + + async fn admit( + &self, + as_: &str, + binding: &GovernanceBinding, + session: &SessionRef, + ) -> (StatusCode, Value) { + self.call( + as_, + Method::POST, + "/v1/sessions:admit", + Some(json!({ "session": session, "binding": binding })), + ) + .await + } + + async fn events(&self, query: &str) -> Vec { + let (status, body) = self + .call( + OPERATOR, + Method::GET, + &format!("/v1/audit/events?{query}"), + None, + ) + .await; + assert_eq!(status, StatusCode::OK, "{body}"); + body["events"].as_array().unwrap().clone() + } } -fn digest(byte: char) -> String { - byte.to_string().repeat(64) +fn binding( + principal: &str, + profile: &ProfileRef, + exceptions: Vec, +) -> GovernanceBinding { + GovernanceBinding { + contract_version: CONTRACT_VERSION, + authority: AuthorityRef { + id: AUTHORITY.to_owned(), + trust_sha256: Sha256Digest::of(b"operator trust"), + }, + profile: profile.clone(), + principal: PrincipalId::new(principal).unwrap(), + project: ProjectId::new(PROJECT).unwrap(), + effective_policy_sha256: Sha256Digest::of(b"effective policy"), + brokered_services: vec![ServiceId::new("anthropic").unwrap()], + exceptions, + } } -fn binding() -> Value { - json!({ - "contract_version": 1, - "authority": { "id": "sendbox-fleet", "trust_sha256": digest('a') }, - "profile": { "id": "example-default", "revision": 3, "sha256": digest('b') }, - "principal": "oidc:alice@example.com", - "project": "github:example/service", - "effective_policy_sha256": digest('c'), - "brokered_services": ["anthropic"] - }) +fn session(byte: char) -> SessionRef { + SessionRef::new(byte.to_string().repeat(32)).unwrap() } -fn grant_request() -> Value { +fn grant_request(binding: &GovernanceBinding, session: &SessionRef) -> Value { json!({ - "principal": "oidc:alice@example.com", - "project": "github:example/service", - "session": SESSION, - "binding": binding(), + "principal": binding.principal, + "project": binding.project, + "session": session, + "binding": binding, "service": "anthropic", "methods": ["POST"], "path_prefixes": ["/v1/messages"], - "max_ttl_seconds": 3600 - }) -} - -fn exception_request() -> Value { - json!({ - "project": "github:example/service", - "profile": { "id": "example-default", "revision": 3, "sha256": digest('b') }, - "scope": { "kind": "network_domain", "value": "registry.example.com" }, - "reason": "Package mirror outage during release", - "expires_at_unix": 1795000000 + "max_ttl_seconds": 3_600, }) } -fn publication() -> Value { +fn context(grant: &Value, path: &str) -> Value { json!({ - "document": PROFILE_YAML, - "signatures": [{ "key_id": "operator-2026", "signature": "c2lnbmF0dXJl" }] + "grant_id": grant["grant_id"], + "principal": grant["principal"], + "project": grant["project"], + "session": grant["session"], + "binding_sha256": grant["binding_sha256"], + "service": "anthropic", + "method": "POST", + "path": path, }) } -struct Route { - method: Method, - path: &'static str, - body: Option, - capability: &'static str, +fn decision(body: &Value) -> &str { + match body["decision"].as_str() { + Some("allow") => "allow", + _ => body["reason"].as_str().unwrap_or("?"), + } } -fn route( - method: Method, - path: &'static str, - body: Option, - capability: &'static str, -) -> Route { - Route { - method, - path, - body, - capability, +#[actix_web::test] +async fn health_and_readiness_report_status() { + let fleet = fleet().await; + for (path, status) in [("/healthz", "ok"), ("/readyz", "ready")] { + let (code, body) = fleet.send(Method::GET, path, None, None).await; + assert_eq!(code, StatusCode::OK, "{path}"); + assert_eq!(body, json!({ "status": status })); } + fleet.database.close().await; + let (code, _) = fleet.send(Method::GET, "/readyz", None, None).await; + assert_eq!(code, StatusCode::SERVICE_UNAVAILABLE); + let (code, _) = fleet.send(Method::GET, "/healthz", None, None).await; + assert_eq!(code, StatusCode::OK); } -/// Every `/v1` operation with a valid synthetic request. -fn v1_routes() -> Vec { - vec![ - route( - Method::POST, - "/v1/sessions:admit", - Some(json!({ "session": SESSION, "binding": binding() })), - "session_admission", - ), - route( +#[actix_web::test] +async fn every_v1_route_requires_a_valid_bearer_token() { + let fleet = fleet().await; + let routes = [ + (Method::GET, "/v1/whoami"), + (Method::POST, "/v1/sessions:admit"), + ( Method::POST, - "/v1/grants", - Some(grant_request()), - "grant_issuance", + "/v1/sessions/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:end", ), - route( + (Method::POST, "/v1/grants"), + ( Method::POST, "/v1/grants/fedcba9876543210fedcba9876543210:renew", - None, - "grant_renewal", ), - route( + ( Method::POST, "/v1/grants/fedcba9876543210fedcba9876543210:revoke", - Some(json!({ "reason": "operator_revoked" })), - "grant_revocation", - ), - route( - Method::POST, - "/v1/authorize", - Some(json!({ - "grant_id": GRANT, - "principal": "oidc:alice@example.com", - "project": "github:example/service", - "session": SESSION, - "binding_sha256": digest('d'), - "service": "anthropic", - "method": "POST", - "path": "/v1/messages" - })), - "request_authorization", ), - route( - Method::GET, - "/v1/profiles/example-default", - None, - "profile_read", - ), - route( - Method::PUT, - "/v1/profiles/example-default", - Some(publication()), - "profile_publication", + (Method::POST, "/v1/authorize"), + (Method::GET, "/v1/profiles/acme"), + (Method::PUT, "/v1/profiles/acme"), + (Method::PUT, "/v1/profiles/acme/minimum-revision"), + (Method::POST, "/v1/projects"), + (Method::GET, "/v1/projects/github:example%2Fservice/roles"), + (Method::POST, "/v1/projects/github:example%2Fservice/roles"), + ( + Method::DELETE, + "/v1/projects/github:example%2Fservice/roles/oidc:bob@example.com", ), - route( + (Method::POST, "/v1/exceptions"), + ( Method::GET, - "/v1/projects/github:example%2Fservice/roles", - None, - "role_listing", - ), - route( - Method::POST, - "/v1/projects/github:example%2Fservice/roles", - Some(json!({ "principal": "oidc:bob@example.com", "role": "member" })), - "role_assignment", + "/v1/exceptions?project=github:example%2Fservice", ), - route( + ( Method::POST, - "/v1/exceptions", - Some(exception_request()), - "exception_request", - ), - route( - Method::GET, - "/v1/audit/events?project=github:example%2Fservice&limit=50", - None, - "audit_query", + "/v1/exceptions/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:approve", ), - ] -} - -fn request( - method: Method, - path: &str, - body: Option<&Value>, - token: Option<&str>, -) -> actix_http::Request { - let mut request = test::TestRequest::default().method(method).uri(path); - if let Some(token) = token { - request = request.insert_header((header::AUTHORIZATION, format!("Bearer {token}"))); + (Method::GET, "/v1/audit/events"), + (Method::GET, "/v1/audit/verify"), + ]; + for (method, path) in routes { + for token in [None, Some("wrong-token"), Some("sbf_unknown")] { + let (status, _) = fleet + .send(method.clone(), path, token, Some(&json!({}))) + .await; + assert_eq!( + status, + StatusCode::UNAUTHORIZED, + "{method} {path} {token:?}" + ); + } } - match body { - Some(body) => request.set_json(body).to_request(), - None => request.to_request(), + for (name, value) in [ + ("x-forwarded-user", MEMBER), + ("x-sendbox-principal", OPERATOR), + ("authorization", "Basic YWxpY2U6c2VjcmV0"), + ] { + let request = test::TestRequest::get() + .uri("/v1/whoami") + .insert_header((name, value)) + .to_request(); + let response = test::call_service(&fleet.service, request).await; + assert_eq!(response.status(), StatusCode::UNAUTHORIZED, "{name}"); } } -async fn problem(response: ServiceResponse) -> (StatusCode, Value) { - let status = response.status(); - let content_type = response - .headers() - .get(header::CONTENT_TYPE) - .and_then(|value| value.to_str().ok()) - .map(str::to_owned); - assert_eq!(content_type.as_deref(), Some("application/problem+json")); - let body: Value = test::read_body_json(response).await; - assert_eq!(body["status"], status.as_u16()); - assert_eq!(body["type"], "about:blank"); - assert!( - body["detail"] - .as_str() - .is_some_and(|detail| !detail.is_empty()) +#[actix_web::test] +async fn tokens_authenticate_until_expired_revoked_or_disabled() { + let fleet = fleet().await; + let (status, body) = fleet.call(OPERATOR, Method::GET, "/v1/whoami", None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + body, + json!({ "principal": OPERATOR, "kind": "user", "operator": true }) ); - (status, body) + let (_, body) = fleet.call(WORKER, Method::GET, "/v1/whoami", None).await; + assert_eq!(body["kind"], "worker"); + + let mut tx = fleet.database.begin_write().await.unwrap(); + tx.execute( + "UPDATE api_tokens SET revoked_at_unix = $2 WHERE principal_id = $1", + &[MEMBER.into(), Arg::from(i64::try_from(NOW).unwrap())], + ) + .await + .unwrap(); + tx.execute( + "UPDATE principals SET disabled_at_unix = 1 WHERE id = $1", + &[BOB.into()], + ) + .await + .unwrap(); + tx.commit().await.unwrap(); + for principal in [MEMBER, BOB] { + let (status, _) = fleet.call(principal, Method::GET, "/v1/whoami", None).await; + assert_eq!(status, StatusCode::UNAUTHORIZED, "{principal}"); + } + fleet.advance(7 * 86_400); + let (status, _) = fleet.call(OPERATOR, Method::GET, "/v1/whoami", None).await; + assert_eq!(status, StatusCode::UNAUTHORIZED, "expired"); } #[actix_web::test] -async fn health_and_readiness_report_status() { - let database = database().await; - let app = service(database.clone(), Arc::new(MockAuthenticator)).await; +async fn only_operators_publish_verified_profiles_and_minimums_only_rise() { + let fleet = fleet().await; + let document = profile_yaml(3); + let (status, _) = fleet + .call( + OWNER, + Method::PUT, + "/v1/profiles/acme", + Some(publication(&document, &fleet.key)), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN); + let other = SigningKeyMaterial::generate().unwrap(); + let (status, _) = fleet + .call( + OPERATOR, + Method::PUT, + "/v1/profiles/acme", + Some(publication(&document, &other)), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "unknown signer"); + let mut tampered = publication(&document, &fleet.key); + tampered["document"] = json!(document.replace("pastebin.com", "example.org")); + let (status, _) = fleet + .call(OPERATOR, Method::PUT, "/v1/profiles/acme", Some(tampered)) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "tampered bytes"); + let (status, _) = fleet + .call( + OPERATOR, + Method::PUT, + "/v1/profiles/other", + Some(publication(&document, &fleet.key)), + ) + .await; + assert_eq!( + status, + StatusCode::BAD_REQUEST, + "path and document ids differ" + ); - for (path, status) in [("/healthz", "ok"), ("/readyz", "ready")] { - let response = test::call_service(&app, request(Method::GET, path, None, None)).await; - assert_eq!(response.status(), StatusCode::OK, "{path}"); - let body: Value = test::read_body_json(response).await; - assert_eq!(body, json!({ "status": status })); - } + let third = fleet.publish(3).await; + assert_eq!(third.sha256, Sha256Digest::of(document.as_bytes())); + let (status, _) = fleet + .call( + OPERATOR, + Method::PUT, + "/v1/profiles/acme", + Some(publication(&document, &fleet.key)), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT, "revisions only increase"); + let fourth = fleet.publish(4).await; + let (status, body) = fleet + .call(MEMBER, Method::GET, "/v1/profiles/acme", None) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["reference"], json!(fourth)); + assert_eq!(body["document"], profile_yaml(4)); + let (_, body) = fleet + .call(MEMBER, Method::GET, "/v1/profiles/acme?revision=3", None) + .await; + assert_eq!(body["reference"], json!(third)); - database.close().await; - let response = test::call_service(&app, request(Method::GET, "/readyz", None, None)).await; - let (status, _) = problem(response).await; - assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE); - let response = test::call_service(&app, request(Method::GET, "/healthz", None, None)).await; - assert_eq!(response.status(), StatusCode::OK); + let minimum = |revision: u64| json!({ "revision": revision, "reason": "Rotate after review" }); + let (status, _) = fleet + .call( + OWNER, + Method::PUT, + "/v1/profiles/acme/minimum-revision", + Some(minimum(4)), + ) + .await; + assert_eq!(status, StatusCode::FORBIDDEN); + let (status, body) = fleet + .call( + OPERATOR, + Method::PUT, + "/v1/profiles/acme/minimum-revision", + Some(minimum(4)), + ) + .await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert_eq!(body["minimum_revision"], 4); + let (status, _) = fleet + .call( + OPERATOR, + Method::PUT, + "/v1/profiles/acme/minimum-revision", + Some(minimum(3)), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT, "minimums never decrease"); } #[actix_web::test] -async fn every_v1_route_requires_a_bearer_token() { - let app = service(database().await, Arc::new(MockAuthenticator)).await; - for route in v1_routes() { - let response = test::call_service( - &app, - request(route.method.clone(), route.path, route.body.as_ref(), None), - ) - .await; - let challenge = response - .headers() - .get(header::WWW_AUTHENTICATE) - .and_then(|value| value.to_str().ok()) - .map(str::to_owned); - let (status, _) = problem(response).await; - assert_eq!( - status, - StatusCode::UNAUTHORIZED, - "{} {}", - route.method, - route.path - ); - assert!(challenge.is_some_and(|value| value.starts_with("Bearer "))); - - let response = test::call_service( - &app, - request( - route.method.clone(), - route.path, - route.body.as_ref(), - Some("wrong-token"), - ), - ) - .await; - let (status, _) = problem(response).await; - assert_eq!( - status, - StatusCode::UNAUTHORIZED, - "{} {}", - route.method, - route.path - ); +async fn project_roles_are_enforced_and_every_change_is_attributed() { + let fleet = fleet().await; + let create = json!({ "project": PROJECT, "owner": OWNER }); + let (status, _) = fleet + .call(OWNER, Method::POST, "/v1/projects", Some(create.clone())) + .await; + assert_eq!( + status, + StatusCode::FORBIDDEN, + "only operators create projects" + ); + fleet.project().await; + let (status, _) = fleet + .call(OPERATOR, Method::POST, "/v1/projects", Some(create)) + .await; + assert_eq!(status, StatusCode::CONFLICT); + + let roles = format!("/v1/projects/{PROJECT_PATH}/roles"); + let assign = + |principal: &str, role: &str| Some(json!({ "principal": principal, "role": role })); + for (caller, status) in [ + (ADMIN, StatusCode::FORBIDDEN), + (MEMBER, StatusCode::FORBIDDEN), + (WORKER, StatusCode::FORBIDDEN), + (OUTSIDER, StatusCode::FORBIDDEN), + ] { + let (code, _) = fleet + .call(caller, Method::POST, &roles, assign(OUTSIDER, "owner")) + .await; + assert_eq!(code, status, "{caller}"); } + let (status, _) = fleet + .call( + OWNER, + Method::POST, + &roles, + assign("local-user:501", "member"), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + let (status, _) = fleet + .call(OWNER, Method::POST, &roles, assign(OWNER, "admin")) + .await; + assert_eq!(status, StatusCode::CONFLICT, "last owner"); + let (status, _) = fleet + .call(OWNER, Method::DELETE, &format!("{roles}/{OWNER}"), None) + .await; + assert_eq!(status, StatusCode::CONFLICT, "last owner"); + let (status, body) = fleet + .call(OWNER, Method::POST, &roles, assign(ADMIN, "owner")) + .await; + assert_eq!(status, StatusCode::OK, "{body}"); + let (status, body) = fleet + .call(ADMIN, Method::DELETE, &format!("{roles}/{BOB}"), None) + .await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert!( + !body["bindings"] + .as_array() + .unwrap() + .iter() + .any(|b| b["principal"] == BOB) + ); + + let (status, body) = fleet.call(VIEWER, Method::GET, &roles, None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(body["bindings"].as_array().unwrap().len(), 5); + let (status, _) = fleet.call(OUTSIDER, Method::GET, &roles, None).await; + assert_eq!(status, StatusCode::FORBIDDEN); + let (status, _) = fleet + .call( + OPERATOR, + Method::GET, + "/v1/projects/github:example%2Fmissing/roles", + None, + ) + .await; + assert_eq!(status, StatusCode::NOT_FOUND); + + let events = fleet.events(&format!("project={PROJECT_PATH}")).await; + let summary = events + .iter() + .map(|event| { + ( + event["event_type"].as_str().unwrap().to_owned(), + event["actor"].as_str().unwrap_or_default().to_owned(), + event["principal"].as_str().unwrap_or_default().to_owned(), + ) + }) + .collect::>(); + assert!(summary.contains(&("project.created".into(), OPERATOR.into(), String::new()))); + assert!(summary.contains(&("role.assigned".into(), OWNER.into(), WORKER.into()))); + assert!(summary.contains(&("role.change_refused".into(), MEMBER.into(), OUTSIDER.into()))); + assert!(summary.contains(&("role.removed".into(), ADMIN.into(), BOB.into()))); } #[actix_web::test] -async fn authenticated_valid_requests_are_not_implemented() { - let app = service(database().await, Arc::new(MockAuthenticator)).await; - for route in v1_routes() { - let response = test::call_service( - &app, - request( - route.method.clone(), - route.path, - route.body.as_ref(), - Some(TEST_TOKEN), - ), - ) - .await; - let (status, body) = problem(response).await; - assert_eq!( - status, - StatusCode::NOT_IMPLEMENTED, - "{} {}: {body}", - route.method, - route.path - ); - assert_eq!(body["title"], "Not Implemented"); - assert_eq!(body["capability"], route.capability); - assert!( - body["detail"] - .as_str() - .unwrap() - .contains("https://github.com/mbianchidev/sendbox/issues/87") - ); +async fn exceptions_need_a_different_authorized_approver_within_the_profile() { + let fleet = fleet().await; + let profile = fleet.project().await; + + for (caller, status) in [ + (VIEWER, StatusCode::FORBIDDEN), + (OUTSIDER, StatusCode::FORBIDDEN), + (WORKER, StatusCode::FORBIDDEN), + ] { + let (code, _) = fleet + .request_exception(caller, &profile, "domain", "gist.github.com") + .await; + assert_eq!(code, status, "{caller}"); } + let (status, _) = fleet + .request_exception(MEMBER, &profile, "domain", "pastebin.com") + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "not liftable in the profile"); + let (status, _) = fleet + .request_exception(MEMBER, &profile, "domain", "*.github.com") + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "not a denial"); + let (status, _) = fleet + .call( + MEMBER, + Method::POST, + "/v1/exceptions", + Some(json!({ + "project": PROJECT, + "profile": profile, + "scope": { "kind": "domain", "value": "gist.github.com" }, + "reason": "Too long", + "expires_at_unix": fleet.now() + 86_401, + })), + ) + .await; + assert_eq!( + status, + StatusCode::BAD_REQUEST, + "beyond the profile's max_ttl_seconds" + ); + + let (status, body) = fleet + .request_exception(MEMBER, &profile, "command", "git push --force *") + .await; + assert_eq!(status, StatusCode::CREATED, "{body}"); + assert_eq!(body["status"], "pending"); + assert_eq!(body["requested_by"], MEMBER); + let id = body["id"].as_str().unwrap().to_owned(); + let approve = format!("/v1/exceptions/{id}:approve"); + for caller in [MEMBER, VIEWER, BOB, WORKER, OPERATOR] { + let (status, _) = fleet.call(caller, Method::POST, &approve, None).await; + assert_eq!(status, StatusCode::FORBIDDEN, "{caller} cannot approve"); + } + let (status, body) = fleet.call(ADMIN, Method::POST, &approve, None).await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert_eq!(body["status"], "approved"); + assert_eq!(body["decided_by"], ADMIN); + let (status, _) = fleet + .call( + OWNER, + Method::POST, + &format!("/v1/exceptions/{id}:reject"), + None, + ) + .await; + assert_eq!(status, StatusCode::CONFLICT, "already decided"); + + let active = format!("/v1/exceptions?project={PROJECT_PATH}&state=active"); + let (_, body) = fleet.call(VIEWER, Method::GET, &active, None).await; + assert_eq!(body["exceptions"].as_array().unwrap().len(), 1); + let (status, _) = fleet.call(OUTSIDER, Method::GET, &active, None).await; + assert_eq!(status, StatusCode::FORBIDDEN); + fleet.advance(3_600); + let (_, body) = fleet.call(VIEWER, Method::GET, &active, None).await; + assert!(body["exceptions"].as_array().unwrap().is_empty(), "expired"); + + let events = fleet.events(&format!("exception={id}")).await; + let types = events + .iter() + .map(|event| { + ( + event["event_type"].as_str().unwrap(), + event["actor"].as_str().unwrap(), + ) + }) + .collect::>(); + assert_eq!(types[0], ("exception.requested", MEMBER)); + assert!(types.contains(&("exception.approval_refused", MEMBER))); + assert!(types.contains(&("exception.approval_refused", VIEWER))); + assert!(types.contains(&("exception.approved", ADMIN))); + assert!(events.iter().all(|event| { + event["detail"] + .as_str() + .unwrap() + .contains("command:git push --force *") + })); } #[actix_web::test] -async fn the_unconfigured_provider_rejects_every_token() { - let app = service(database().await, Arc::new(auth::UnconfiguredAuthenticator)).await; - for route in v1_routes() { - let response = test::call_service( - &app, - request( - route.method.clone(), - route.path, - route.body.as_ref(), - Some(TEST_TOKEN), - ), - ) - .await; - let (status, body) = problem(response).await; - assert_eq!(status, StatusCode::UNAUTHORIZED); - assert_eq!(body["detail"], "authentication provider not configured"); - } +async fn stale_approvals_cannot_authorize_changed_work() { + let fleet = fleet().await; + let third = fleet.project().await; + let (status, body) = fleet + .request_exception(MEMBER, &third, "domain", "gist.github.com") + .await; + assert_eq!(status, StatusCode::CREATED); + let pending = body["id"].as_str().unwrap().to_owned(); + let approved = fleet.approved_exception(&third).await; + let admitted = binding(MEMBER, &third, vec![approved.clone()]); + let (status, body) = fleet.admit(MEMBER, &admitted, &session('a')).await; + assert_eq!(status, StatusCode::OK, "{body}"); + + let fourth = fleet.publish(4).await; + let (status, body) = fleet + .call( + ADMIN, + Method::POST, + &format!("/v1/exceptions/{pending}:approve"), + None, + ) + .await; + assert_eq!(status, StatusCode::CONFLICT, "{body}"); + let (status, _) = fleet.admit(MEMBER, &admitted, &session('b')).await; + assert_eq!(status, StatusCode::CONFLICT, "revision 3 is stale"); + let (status, body) = fleet + .admit( + MEMBER, + &binding(MEMBER, &fourth, vec![approved]), + &session('c'), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT, "{body}"); + assert!(body["detail"].as_str().unwrap().contains("exception")); + let (status, body) = fleet + .admit(MEMBER, &binding(MEMBER, &fourth, vec![]), &session('d')) + .await; + assert_eq!(status, StatusCode::OK, "{body}"); } #[actix_web::test] -async fn identity_headers_are_not_authentication() { - let app = service(database().await, Arc::new(MockAuthenticator)).await; - for (name, value) in [ - ("x-forwarded-user", "oidc:alice@example.com"), - ("x-remote-user", "alice"), - ("x-sendbox-principal", "oidc:alice@example.com"), - ("authorization", "Basic YWxpY2U6c2VjcmV0"), - ] { - let request = test::TestRequest::post() - .uri("/v1/authorize") - .insert_header((name, value)) - .to_request(); - let (status, _) = problem(test::call_service(&app, request).await).await; - assert_eq!(status, StatusCode::UNAUTHORIZED, "{name}"); +async fn admission_requires_the_caller_a_member_role_and_this_authority() { + let fleet = fleet().await; + let profile = fleet.project().await; + let exception = fleet.approved_exception(&profile).await; + + for caller in [VIEWER, OUTSIDER] { + let (status, _) = fleet + .admit(caller, &binding(caller, &profile, vec![]), &session('a')) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "{caller}"); } -} + let (status, _) = fleet + .admit(BOB, &binding(MEMBER, &profile, vec![]), &session('a')) + .await; + assert_eq!( + status, + StatusCode::FORBIDDEN, + "a caller cannot claim another principal" + ); + let (status, _) = fleet + .admit(WORKER, &binding(MEMBER, &profile, vec![]), &session('a')) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "nor can a worker"); + let mut foreign = binding(MEMBER, &profile, vec![]); + foreign.authority.id = "local".to_owned(); + let (status, _) = fleet.admit(MEMBER, &foreign, &session('a')).await; + assert_eq!(status, StatusCode::FORBIDDEN); + let mut unknown_service = binding(MEMBER, &profile, vec![]); + unknown_service.brokered_services = vec![ServiceId::new("openai").unwrap()]; + let (status, _) = fleet.admit(MEMBER, &unknown_service, &session('a')).await; + assert_eq!(status, StatusCode::FORBIDDEN); + let (status, _) = fleet + .admit( + BOB, + &binding(BOB, &profile, vec![ExceptionId::from_bytes([9; 16])]), + &session('a'), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT, "unknown exception"); + + let excepted = binding(MEMBER, &profile, vec![exception.clone()]); + let (status, body) = fleet.admit(MEMBER, &excepted, &session('a')).await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert_eq!(body["binding_sha256"], json!(excepted.digest().unwrap())); + let (status, _) = fleet.admit(MEMBER, &excepted, &session('a')).await; + assert_eq!(status, StatusCode::CONFLICT, "duplicate session"); + let (status, body) = fleet + .admit( + WORKER, + &binding(WORKER, &profile, vec![exception.clone()]), + &session('b'), + ) + .await; + assert_eq!( + status, + StatusCode::OK, + "project-wide exceptions cover the worker: {body}" + ); -/// Returns `value` with the field at `pointer` replaced or added. -fn with(mut value: Value, pointer: &str, replacement: Value) -> Value { - let (parent, key) = pointer.rsplit_once('/').unwrap(); - value.pointer_mut(parent).unwrap()[key] = replacement; - value + let events = fleet.events(&format!("project={PROJECT_PATH}")).await; + let refused = events + .iter() + .filter(|event| event["event_type"] == "session.refused") + .count(); + assert_eq!(refused, 7); + assert!( + events + .iter() + .any(|event| event["event_type"] == "exception.applied" + && event["exception"] == json!(exception) + && event["session"] == json!(session('a'))) + ); } #[actix_web::test] -async fn invalid_contract_bodies_are_rejected_after_authentication() { - let app = service(database().await, Arc::new(MockAuthenticator)).await; - let admit = json!({ "session": SESSION, "binding": binding() }); - let cases: Vec<(Method, &str, Option)> = vec![ - ( +async fn grants_follow_the_session_profile_and_exception_lifecycle() { + let fleet = fleet().await; + let profile = fleet.project().await; + let exception = fleet.approved_exception(&profile).await; + let excepted = binding(MEMBER, &profile, vec![exception.clone()]); + let id = session('a'); + assert_eq!(fleet.admit(MEMBER, &excepted, &id).await.0, StatusCode::OK); + + let (status, _) = fleet + .call( + BOB, Method::POST, - "/v1/sessions:admit", - Some(with(admit.clone(), "/session", json!("not-a-session"))), - ), - ( + "/v1/grants", + Some(grant_request(&excepted, &id)), + ) + .await; + assert_eq!( + status, + StatusCode::FORBIDDEN, + "another member cannot use the session" + ); + let mut wide = grant_request(&excepted, &id); + wide["path_prefixes"] = json!(["/v1/files"]); + let (status, _) = fleet + .call(MEMBER, Method::POST, "/v1/grants", Some(wide)) + .await; + assert_eq!(status, StatusCode::FORBIDDEN, "path outside the profile"); + let (status, grant) = fleet + .call( + MEMBER, Method::POST, - "/v1/sessions:admit", - Some(with(admit.clone(), "/binding/contract_version", json!(2))), - ), - ( + "/v1/grants", + Some(grant_request(&excepted, &id)), + ) + .await; + assert_eq!(status, StatusCode::OK, "{grant}"); + assert_eq!(grant["max_expires_at_unix"], fleet.now() + 3_600); + assert_eq!(grant["lease_expires_at_unix"], fleet.now() + 60); + + let authorize = |grant: &Value, path: &str| Some(context(grant, path)); + let (status, body) = fleet + .call( + MEMBER, Method::POST, - "/v1/sessions:admit", - Some(with(admit, "/binding/principal", json!("Alice"))), - ), - ( + "/v1/authorize", + authorize(&grant, "/v1/messages"), + ) + .await; + assert_eq!((status, decision(&body)), (StatusCode::OK, "allow")); + let (_, body) = fleet + .call( + MEMBER, Method::POST, - "/v1/grants", - Some(with( - grant_request(), - "/binding/brokered_services", - json!(["openai", "anthropic"]), - )), - ), - ( + "/v1/authorize", + authorize(&grant, "/v1/files"), + ) + .await; + assert_eq!(decision(&body), "path_not_granted"); + let (_, body) = fleet + .call( + MEMBER, Method::POST, - "/v1/grants", - Some(with(grant_request(), "/methods", json!(["CONNECT"]))), - ), - ( + "/v1/authorize", + authorize(&grant, "/v1/messages/../files"), + ) + .await; + assert_eq!(decision(&body), "invalid_path"); + let (_, body) = fleet + .call( + BOB, + Method::POST, + "/v1/authorize", + authorize(&grant, "/v1/messages"), + ) + .await; + assert_eq!(decision(&body), "principal_mismatch"); + let mut changed = context(&grant, "/v1/messages"); + changed["binding_sha256"] = json!(Sha256Digest::of(b"changed")); + let (_, body) = fleet + .call(MEMBER, Method::POST, "/v1/authorize", Some(changed)) + .await; + assert_eq!(decision(&body), "binding_mismatch"); + + fleet.advance(30); + let renew = format!("/v1/grants/{}:renew", grant["grant_id"].as_str().unwrap()); + let (status, renewed) = fleet.call(MEMBER, Method::POST, &renew, None).await; + assert_eq!(status, StatusCode::OK, "{renewed}"); + assert_eq!(renewed["generation"], 2); + assert_eq!(renewed["lease_expires_at_unix"], fleet.now() + 60); + + let (status, _) = fleet + .call( + MEMBER, + Method::POST, + &format!("/v1/exceptions/{exception}:revoke"), + None, + ) + .await; + assert_eq!(status, StatusCode::OK, "the requester may revoke"); + let (_, body) = fleet + .call( + MEMBER, + Method::POST, + "/v1/authorize", + authorize(&grant, "/v1/messages"), + ) + .await; + assert_eq!(decision(&body), "stale_policy"); + let (status, _) = fleet.call(MEMBER, Method::POST, &renew, None).await; + assert_eq!(status, StatusCode::CONFLICT); + let (status, _) = fleet + .call( + MEMBER, Method::POST, "/v1/grants", - Some(with( - grant_request(), - "/path_prefixes", - json!(["/v1/../admin"]), - )), - ), - ( + Some(grant_request(&excepted, &id)), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT); + + let plain = binding(MEMBER, &profile, vec![]); + let second = session('b'); + assert_eq!(fleet.admit(MEMBER, &plain, &second).await.0, StatusCode::OK); + let (_, grant) = fleet + .call( + MEMBER, Method::POST, "/v1/grants", - Some(with(grant_request(), "/max_ttl_seconds", json!(0))), - ), - (Method::POST, "/v1/grants/NOT-A-GRANT:renew", None), - ( + Some(grant_request(&plain, &second)), + ) + .await; + let revoke = format!("/v1/grants/{}:revoke", grant["grant_id"].as_str().unwrap()); + let (status, _) = fleet + .call( + MEMBER, Method::POST, - "/v1/grants/fedcba9876543210fedcba9876543210:revoke", - Some(json!({ "reason": "because" })), - ), - ( + &revoke, + Some(json!({ "reason": "operator_revoked" })), + ) + .await; + assert_eq!( + status, + StatusCode::FORBIDDEN, + "members cannot revoke as operators" + ); + let (status, _) = fleet + .call( + MEMBER, + Method::POST, + &format!("/v1/sessions/{second}:end"), + Some(json!({ "outcome": "cancelled" })), + ) + .await; + assert_eq!(status, StatusCode::NO_CONTENT); + let (_, body) = fleet + .call( + MEMBER, Method::POST, "/v1/authorize", - Some(json!({ "grant_id": GRANT })), - ), - (Method::GET, "/v1/profiles/Example", None), - ( - Method::PUT, - "/v1/profiles/other-profile", - Some(publication()), - ), - ( - Method::PUT, - "/v1/profiles/example-default", - Some(with(publication(), "/document", json!("id: ["))), - ), - ( - Method::PUT, - "/v1/profiles/example-default", - Some(with( - publication(), - "/signatures/0/signature", - json!("not base64!"), - )), - ), - ( + authorize(&grant, "/v1/messages"), + ) + .await; + assert_eq!(decision(&body), "revoked"); + let (status, _) = fleet + .call( + MEMBER, + Method::POST, + "/v1/grants", + Some(grant_request(&plain, &second)), + ) + .await; + assert_eq!(status, StatusCode::CONFLICT, "ended sessions get no grants"); + + let events = fleet.events(&format!("session={second}")).await; + let revoked = events + .iter() + .find(|event| event["event_type"] == "grant.revoked") + .unwrap(); + assert_eq!(revoked["detail"], "reason=session_cancelled"); + let authorized = events + .iter() + .filter(|event| event["event_type"] == "request.authorized") + .collect::>(); + assert_eq!(authorized.last().unwrap()["deny_reason"], "revoked"); + assert_eq!( + authorized.last().unwrap()["target"], + "POST anthropic/v1/messages" + ); +} + +#[actix_web::test] +async fn audit_is_role_scoped_attributable_and_verifiable() { + let fleet = fleet().await; + let profile = fleet.project().await; + fleet.approved_exception(&profile).await; + let query = format!("/v1/audit/events?project={PROJECT_PATH}&limit=3"); + let (status, page) = fleet.call(VIEWER, Method::GET, &query, None).await; + assert_eq!(status, StatusCode::OK); + assert_eq!(page["events"].as_array().unwrap().len(), 3); + let cursor = page["next_after_sequence"].as_u64().unwrap(); + let (_, next) = fleet + .call( + VIEWER, Method::GET, - "/v1/projects/gitlab:example%2Fservice/roles", + &format!("{query}&after_sequence={cursor}"), None, - ), + ) + .await; + assert!(next["events"][0]["sequence"].as_u64().unwrap() > cursor); + for (caller, path) in [ + (OUTSIDER, query.as_str()), + (VIEWER, "/v1/audit/events"), + (OWNER, "/v1/audit/verify"), + ] { + let (status, _) = fleet.call(caller, Method::GET, path, None).await; + assert_eq!(status, StatusCode::FORBIDDEN, "{caller} {path}"); + } + + let (status, verification) = fleet + .call(OPERATOR, Method::GET, "/v1/audit/verify", None) + .await; + assert_eq!(status, StatusCode::OK); + assert_eq!(verification["valid"], true); + let all = fleet.events("limit=500").await; + assert_eq!(verification["events"], all.len()); + assert_eq!(verification["head_hash"], all.last().unwrap()["event_hash"]); + let serialized = serde_json::to_string(&all).unwrap(); + for token in fleet.tokens.values() { + assert!(!serialized.contains(token.as_str())); + } + assert!( + !serialized.contains("Synthetic release window"), + "reasons stay in the exception record" + ); +} + +#[actix_web::test] +async fn invalid_contract_bodies_and_transport_errors_are_problems() { + let fleet = fleet().await; + let profile = fleet.project().await; + let mut wrong_version = serde_json::to_value(binding(MEMBER, &profile, vec![])).unwrap(); + wrong_version["contract_version"] = json!(1); + let unsorted = { + let mut binding = binding(MEMBER, &profile, vec![]); + binding.exceptions = vec![ + ExceptionId::from_bytes([2; 16]), + ExceptionId::from_bytes([1; 16]), + ]; + serde_json::to_value(binding).unwrap() + }; + for (method, path, body) in [ ( Method::POST, - "/v1/projects/github:example%2Fservice/roles", - Some(json!({ "principal": "oidc:bob@example.com", "role": "superuser" })), + "/v1/sessions:admit", + json!({ "session": "nope", "binding": unsorted }), ), ( Method::POST, - "/v1/projects/github:example%2Fservice/roles", - Some(json!({ "principal": "local-user:501:bob", "role": "member" })), + "/v1/sessions:admit", + json!({ "session": session('a'), "binding": wrong_version }), ), ( Method::POST, - "/v1/exceptions", - Some(with(exception_request(), "/reason", json!(" "))), + "/v1/sessions:admit", + json!({ "session": session('a'), "binding": unsorted }), ), ( Method::POST, "/v1/exceptions", - Some(with( - exception_request(), - "/scope/value", - json!("two words"), - )), + json!({ "project": PROJECT, "profile": profile, "scope": { "kind": "mcp_tool", "value": "x" }, "reason": "r", "expires_at_unix": NOW + 60 }), ), ( Method::POST, "/v1/exceptions", - Some(with( - exception_request(), - "/approved_by", - json!("oidc:bob@example.com"), - )), + json!({ "project": PROJECT, "profile": profile, "scope": { "kind": "domain", "value": "gist.github.com" }, "reason": "\u{0007}", "expires_at_unix": NOW + 60 }), ), - (Method::GET, "/v1/audit/events?limit=0", None), - (Method::GET, "/v1/audit/events?session=abc", None), ( - Method::GET, - "/v1/audit/events?actor=oidc:alice@example.com", - None, + Method::POST, + "/v1/projects", + json!({ "project": "github:Example/x", "owner": OWNER }), ), - ]; - for (method, path, body) in cases { - let response = test::call_service( - &app, - request(method.clone(), path, body.as_ref(), Some(TEST_TOKEN)), - ) - .await; - let (status, problem_body) = problem(response).await; - assert_eq!( - status, - StatusCode::BAD_REQUEST, - "{method} {path} {body:?}: {problem_body}" - ); - - let response = - test::call_service(&app, request(method.clone(), path, body.as_ref(), None)).await; - let (status, _) = problem(response).await; - assert_eq!( - status, - StatusCode::UNAUTHORIZED, - "{method} {path} without a token" - ); + ] { + let (status, body) = fleet.call(OPERATOR, method.clone(), path, Some(body)).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{method} {path}: {body}"); } -} - -#[actix_web::test] -async fn transport_errors_are_problems() { - let app = service(database().await, Arc::new(MockAuthenticator)).await; - let authorized = |request: test::TestRequest| { - request - .insert_header((header::AUTHORIZATION, format!("Bearer {TEST_TOKEN}"))) - .to_request() - }; - - let response = test::call_service( - &app, - authorized( - test::TestRequest::post() - .uri("/v1/authorize") - .insert_header((header::CONTENT_TYPE, "text/plain")) - .set_payload("{}"), - ), - ) - .await; - assert_eq!( - problem(response).await.0, - StatusCode::UNSUPPORTED_MEDIA_TYPE - ); - + let (status, _) = fleet + .call(OPERATOR, Method::GET, "/v1/audit/events?limit=0", None) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST); + let (status, _) = fleet + .call(OPERATOR, Method::DELETE, "/v1/grants", None) + .await; + assert_eq!(status, StatusCode::METHOD_NOT_ALLOWED); + let (status, _) = fleet.call(OPERATOR, Method::GET, "/v1/unknown", None).await; + assert_eq!(status, StatusCode::NOT_FOUND); let oversized = json!({ "document": "x".repeat(2 * 1024 * 1024), "signatures": [] }); - let response = test::call_service( - &app, - authorized( - test::TestRequest::put() - .uri("/v1/profiles/example-default") - .set_json(oversized), - ), - ) - .await; - assert_eq!(problem(response).await.0, StatusCode::PAYLOAD_TOO_LARGE); - - let response = test::call_service( - &app, - authorized(test::TestRequest::delete().uri("/v1/grants")), - ) - .await; - assert_eq!(problem(response).await.0, StatusCode::METHOD_NOT_ALLOWED); - - let response = test::call_service( - &app, - authorized(test::TestRequest::get().uri("/v1/unknown")), - ) - .await; - assert_eq!(problem(response).await.0, StatusCode::NOT_FOUND); - - let response = - test::call_service(&app, test::TestRequest::get().uri("/unknown").to_request()).await; - assert_eq!(problem(response).await.0, StatusCode::NOT_FOUND); + let (status, _) = fleet + .call(OPERATOR, Method::PUT, "/v1/profiles/acme", Some(oversized)) + .await; + assert_eq!(status, StatusCode::PAYLOAD_TOO_LARGE); + let request = test::TestRequest::post() + .uri("/v1/authorize") + .insert_header(( + header::AUTHORIZATION, + format!("Bearer {}", fleet.tokens[MEMBER]), + )) + .insert_header((header::CONTENT_TYPE, "text/plain")) + .set_payload("{}") + .to_request(); + let response = test::call_service(&fleet.service, request).await; + assert_eq!(response.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE); } diff --git a/crates/fleet-server/tests/migrations.rs b/crates/fleet-server/tests/migrations.rs index 33da231..b65d48a 100644 --- a/crates/fleet-server/tests/migrations.rs +++ b/crates/fleet-server/tests/migrations.rs @@ -8,7 +8,9 @@ use fleet_server::config::{DatabaseKind, DatabaseUrl}; use fleet_server::db::Database; -const TABLES: [&str; 10] = [ +const TABLES: [&str; 12] = [ + "api_tokens", + "session_exceptions", "principals", "projects", "role_bindings", @@ -244,21 +246,77 @@ async fn identities_are_bound_and_lifetimes_bounded() { reject(&database, &revocation(61)).await; accept(&database, &revocation(5)).await; - let exception = |decided_by: &str, expires: i64| { + let exception = |kind: &str, value: &str, decided_by: &str, expires: i64| { format!( "INSERT INTO exceptions (id, project_id, profile_id, profile_revision, profile_sha256, \ scope_kind, scope_value, reason, status, requested_by, requested_at_unix, decided_by, \ decided_at_unix, expires_at_unix) VALUES ('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', \ - 'github:example/service', 'example-default', 3, '{PROFILE_SHA}', 'network_domain', \ - 'registry.example.com', 'Package mirror outage', 'approved', 'oidc:alice@example.com', \ + 'github:example/service', 'example-default', 3, '{PROFILE_SHA}', '{kind}', \ + '{value}', 'Package mirror outage', 'approved', 'oidc:alice@example.com', \ 1790000000, '{decided_by}', 1790000100, {expires})" ) }; - reject(&database, &exception("oidc:alice@example.com", 1790086400)).await; + let domain = |decided_by: &str, expires: i64| { + exception("domain", "registry.example.com", decided_by, expires) + }; + reject(&database, &domain("oidc:alice@example.com", 1790086400)).await; + reject( + &database, + &domain("oidc:bob@example.com", 1790000000 + 604801), + ) + .await; + for (kind, value) in [ + ("network_domain", "registry.example.com"), + ("command", " git push"), + ("domain", "tab\there"), + ] { + reject( + &database, + &exception(kind, value, "oidc:bob@example.com", 1790086400), + ) + .await; + } + accept( + &database, + &exception( + "command", + "git push --force *", + "oidc:bob@example.com", + 1790086400, + ), + ) + .await; + + let session_exception = |exception: &str| { + format!( + "INSERT INTO session_exceptions (session_id, exception_id) VALUES ('{SESSION}', '{exception}')" + ) + }; + reject(&database, &session_exception(&"b".repeat(32))).await; + accept(&database, &session_exception(&"a".repeat(32))).await; +} + +#[actix_web::test] +async fn tokens_are_digests_with_bounded_lifetimes() { + let database = database().await; + seed(&database).await; + let token = |id: char, digest: char, expires: i64| { + format!( + "INSERT INTO api_tokens (id, principal_id, token_sha256, created_at_unix, \ + expires_at_unix) VALUES ('{}', 'oidc:alice@example.com', '{}', 1790000000, {expires})", + id.to_string().repeat(32), + digest.to_string().repeat(64) + ) + }; + reject(&database, &token('a', 'a', 1790000000 + 7776001)).await; + reject(&database, &token('a', 'A', 1790086400)).await; + accept(&database, &token('a', 'a', 1790086400)).await; + reject(&database, &token('b', 'a', 1790086400)).await; reject( &database, - &exception("oidc:bob@example.com", 1790000000 + 604801), + "INSERT INTO api_tokens (id, principal_id, token_sha256, created_at_unix, expires_at_unix) \ + VALUES ('cccccccccccccccccccccccccccccccc', 'oidc:nobody@example.com', \ + 'cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc', 0, 10)", ) .await; - accept(&database, &exception("oidc:bob@example.com", 1790086400)).await; } diff --git a/docker-compose.yml b/docker-compose.yml index f559cd9..5948bff 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -34,6 +34,9 @@ services: FLEET_LOG_DIR: /var/log/sendbox-fleet FLEET_LOG_LEVEL: ${FLEET_LOG_LEVEL:-info} FLEET_LOG_RETENTION_DAYS: ${FLEET_LOG_RETENTION_DAYS:-30} + FLEET_AUTHORITY_ID: ${FLEET_AUTHORITY_ID:-sendbox-fleet} + # Container path of the profile signer file, mounted by a compose override. + FLEET_PROFILE_TRUST: ${FLEET_PROFILE_TRUST:-} ports: - "127.0.0.1:${FLEET_PORT:-8080}:8080" volumes: diff --git a/docs/architecture.md b/docs/architecture.md index ee3194f..44a62c7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -5,10 +5,10 @@ It is increment 2 of that issue: the authenticated, multi-user management API and central authority that increment 1 deliberately left out. -**Status: scaffold.** The service runs, authenticates every `/v1` request, -validates request bodies against the shared contract, and answers every -management operation with `501 Not Implemented`. No governance decision is -made yet. See [roadmap.md](roadmap.md). +It authenticates every `/v1` caller, enforces project-scoped roles, verifies +and publishes operator-signed profiles, admits governed sessions, issues and +checks credential grants, records bounded and expiring exceptions, and keeps a +hash-chained central audit log. See [roadmap.md](roadmap.md) for what remains. ## Relationship to SendBox increment 1 @@ -24,8 +24,12 @@ repository and works on a single host: Increment 2 moves the *authority* off the host, so several hosts and users share one set of profiles, roles, grants, exceptions, and audit evidence. The -fleet implements the same `GrantAuthority` semantics over HTTP; a SendBox host -uses a remote authority client instead of the local one. +fleet implements the same `GrantAuthority` semantics over HTTP (both use +`sendbox_governance::evaluate_request`); a SendBox host whose operator +configuration has a `fleet` section uses its remote authority client instead +of the local one. See SendBox's +[shared governance service](https://github.com/mbianchidev/sendbox/blob/main/docs/architecture/governed-sessions.md#shared-governance-service) +for the host side. ```mermaid flowchart LR @@ -71,33 +75,54 @@ flowchart LR request is rejected with `401` before its body is read. Only `Authorization: Bearer ` is accepted. Identity headers such as `X-Forwarded-User`, `X-Remote-User`, or `X-Sendbox-Principal` are ignored. - The `Authenticator` trait maps a token to a `Caller` (principal and kind). - No identity provider is integrated yet: the production - `UnconfiguredAuthenticator` rejects every token with - `authentication provider not configured`. -- **Authorization** answers "may this caller do this". It will combine the - caller kind (user or worker), project roles (`owner`, `admin`, `member`, - `viewer`), the current profile ceiling, admitted sessions, grants, and - approved exceptions. -- **Workload identity fields are never authoritative.** Principal and project - fields inside request bodies (for example `GovernanceBinding.principal`) are - claims to check against the authenticated caller and stored state, never a - source of identity. `local-user:` principals belong to single-host - increment 1 and are rejected by both the API and the schema. - -## Planned request flow - -| Step | Endpoint | Contract types | Planned checks | -| --- | --- | --- | --- | -| Admit a session | `POST /v1/sessions:admit` | `SessionRef`, `GovernanceBinding` | Caller is a worker; principal holds `member` or higher in the project; profile revision is current (at or above the minimum, inside its validity window, digest matches); binding digest recorded | -| Issue a grant | `POST /v1/grants` | `GrantRequest` to `CredentialGrant` | Session admitted by this worker; binding digest matches; service admitted by the binding; methods and paths inside the profile; bounded lease and TTL | -| Authorize a request | `POST /v1/authorize` | `RequestContext` to `Decision` | Same checks as `LocalGrantAuthority::authorize`, against shared state. Hosts treat any non-200 answer as `authority_unavailable` and deny | -| Renew a lease | `POST /v1/grants/{grant_id}:renew` | `GrantId` to `CredentialGrant` | Not revoked, not expired, profile still current; lease never exceeds the grant's hard expiry | -| Revoke a grant | `POST /v1/grants/{grant_id}:revoke` | `RevocationReason` | New requests denied immediately; open streams may finish within the grace window (at most 60 seconds); completed external effects are not reversed and are audited with outcome `unknown` when unconfirmed | -| Read or publish a profile | `GET` / `PUT /v1/profiles/{profile_id}` | `ProfileId`, `GovernanceProfile`, `ProfileRef` | Publication by an operator; signature verification over the exact bytes | -| List or assign roles | `GET` / `POST /v1/projects/{project_id}/roles` | `ProjectId`, `PrincipalId` | Only `owner` assigns roles | -| Request an exception | `POST /v1/exceptions` | `ProjectId`, `PrincipalId`, `ProfileRef` | Bounded scope, reason, expiry at most 7 days; approval by a different authorized principal; never wider than the profile ceiling; bound to the exact revision | -| Query audit events | `GET /v1/audit/events` | `ProjectId`, `SessionRef`, `PrincipalId`, `DenyReason` | Role-scoped visibility; cursor pagination | + `DatabaseAuthenticator` accepts opaque `sbf_` tokens issued with + `sendbox-fleet admin token issue`: only their SHA-256 is stored, and a token + works while it is unexpired (at most 90 days), unrevoked, and its principal + is not disabled. A failed token lookup is `503`, never an implicit allow. +- **Authorization** answers "may this caller do this". It combines the caller + kind (`user` or `worker`), the fleet-wide `operator` flag, project roles, + the current profile revision, admitted sessions, grants, and exceptions, + all read from the database. +- **Workload identity fields are never authoritative.** A binding or grant + principal must equal the authenticated caller; a host cannot claim another + identity. `local-user:` principals belong to single-host increment 1 and are + rejected by both the API and the schema. + +## Roles + +| Who | May | +| --- | --- | +| Operator (fleet-wide, users only) | Publish profiles, raise minimum revisions, create projects with a first owner, manage any project's roles, revoke grants and exceptions, read and verify all audit | +| `owner` | Assign and remove roles (never leaving the project without an owner), approve or reject exceptions, run sessions | +| `admin` | Approve or reject exceptions, revoke grants (`operator_revoked`, `policy_changed`), run sessions | +| `member` | Run governed sessions, request exceptions | +| `viewer` | Read roles, exceptions, and the project's audit events | + +Workers never manage roles, profiles, or exceptions. A principal runs +sessions as itself: it needs `member` or higher in the project. + +## Request flow + +| Step | Endpoint | Checks | +| --- | --- | --- | +| Identify | `GET /v1/whoami` | Returns the authenticated principal, kind, and operator flag | +| Admit a session | `POST /v1/sessions:admit` | Binding principal is the caller; binding names this authority (`FLEET_AUTHORITY_ID`); caller holds `member` or higher; profile reference is the current revision (at or above the minimum, unexpired, digest matches); brokered services exist in the profile; every bound exception is approved, unrevoked, unexpired, for this project and principal (or project-wide), bound to this exact revision, and permitted by it. Records the canonical binding | +| End a session | `POST /v1/sessions/{session}:end` | Session principal only; revokes every live grant with the matching session reason | +| Issue a grant | `POST /v1/grants` | Caller and request match the admitted session's binding exactly; session not ended; service admitted; methods and path prefixes inside the profile service; profile current; bound exceptions still valid. Lease from the profile; hard expiry capped by the profile TTL, profile expiry, the earliest bound exception expiry, and 7 days | +| Authorize a request | `POST /v1/authorize` | `evaluate_request` against shared state, plus: the caller is the grant principal, the session is not ended, bound exceptions are still valid. Every decision is audited with a redacted target | +| Renew a lease | `POST /v1/grants/{grant}:renew` | Grant principal; not revoked or expired; lease not lapsed; session admitted; profile current; exceptions valid. Lease never exceeds the hard expiry or the earliest exception expiry | +| Revoke a grant | `POST /v1/grants/{grant}:revoke` | Session reasons by the grant principal; `operator_revoked` and `policy_changed` by an `admin`, `owner`, or operator. New requests deny at once; the grace window is the profile's `revocation_grace_seconds` (at most 60) | +| Publish a profile | `PUT /v1/profiles/{profile}` | Operator; body is the exact YAML plus the `sendbox.governance-signatures` bundle that `sendbox governance sign` writes; signatures must satisfy `FLEET_PROFILE_TRUST`; revisions only increase | +| Read a profile | `GET /v1/profiles/{profile}[?revision=N]` | Any caller; the current revision is the newest whose `not_before_unix` has passed | +| Raise the minimum | `PUT /v1/profiles/{profile}/minimum-revision` | Operator; minimums only rise; older revisions, and everything bound to them, become stale | +| Create a project | `POST /v1/projects` | Operator; the owner must be an active principal | +| List or change roles | `GET` / `POST /v1/projects/{project}/roles`, `DELETE …/roles/{principal}` | Listing needs any role (or operator); changes need `owner` (or operator); the last owner cannot be removed or demoted | +| Request an exception | `POST /v1/exceptions` | User with `member` or higher; scope is a denial the current revision lists under `exceptions`; optional principal must be a member; expiry in the future, within the profile's `exceptions.max_ttl_seconds` (at most 7 days) and before the profile expires | +| Decide an exception | `POST /v1/exceptions/{id}:approve` / `:reject` | User with `owner` or `admin`, not the requester; approval only while unexpired and its revision is still current | +| Revoke an exception | `POST /v1/exceptions/{id}:revoke` | Requester, `owner`, `admin`, or operator. Sessions admitted with it are denied on their next request or renewal | +| List exceptions | `GET /v1/exceptions?project=…&state=active\|pending\|all`, `GET /v1/exceptions/{id}` | Any role in the project (or operator) | +| Query audit events | `GET /v1/audit/events` | Operators read everything; others must pass a `project` in which they hold a role. Cursor pagination | +| Verify the chain | `GET /v1/audit/verify` | Operator; recomputes every hash and link | Project identifiers contain a slash (`github:owner/repo`), so clients percent-encode it in paths: `/v1/projects/github:owner%2Frepo/roles`. @@ -105,17 +130,21 @@ percent-encode it in paths: `/v1/projects/github:owner%2Frepo/roles`. ## HTTP responses Errors use RFC 9457 `application/problem+json` with `type: about:blank`, the -standard reason phrase as `title`, and a specific `detail`. `501` responses add -a `capability` member naming the unimplemented increment-2 capability. +standard reason phrase as `title`, and a specific `detail`. | Status | When | | --- | --- | | `400` | Body, path, or query does not match the contract | | `401` | Missing, malformed, or unaccepted bearer token (with `WWW-Authenticate: Bearer`) | -| `404` / `405` | Unknown path or unsupported method | +| `403` | Authenticated, but the role, kind, operator flag, profile, or signer check refuses it | +| `404` / `405` | Unknown resource or path, or unsupported method | +| `409` | Stale profile revision, stale or inactive exception, already-decided exception, ended session, duplicate admission, last owner | | `413` / `415` | Body too large (64 KiB, 1 MiB for profile publication) or not JSON | -| `501` | Valid, authenticated request for an increment-2 capability | -| `503` | `/readyz` cannot reach the database | +| `500` | Internal failure; the cause is logged, never returned | +| `503` | Authentication or `/readyz` cannot reach the database, or profile publication without `FLEET_PROFILE_TRUST` | + +A per-request authorization denial is a `200` with `{"decision": "deny", +"reason": …}`; hosts deny on any other answer. `GET /healthz` (liveness) and `GET /readyz` (database round trip) are unauthenticated and reveal nothing beyond availability. @@ -128,7 +157,8 @@ deployment target; SQLite is for local development and tests. | Table | Holds | | --- | --- | -| `principals` | Authenticated users and workers (never `local-user:`) | +| `principals` | Authenticated users and workers (never `local-user:`), with the operator flag | +| `api_tokens` | SHA-256 of each bearer token, expiry (at most 90 days), revocation | | `projects` | `github:owner/repo` or `path-sha256:` projects | | `role_bindings` | One project-scoped role per principal per project | | `profiles` | Exact signed bytes, digest, signatures, validity window per revision | @@ -136,16 +166,36 @@ deployment target; SQLite is for local development and tests. | `sessions` | Admitted sessions with their canonical binding and digest | | `credential_grants` | Grant scope, lease, hard expiry, generation; no credential material | | `revocations` | Reason, actor, bounded grace window | -| `exceptions` | Scope, reason, requester, approver, expiry, exact profile revision | -| `audit_events` | Append-only, hash-chained evidence with a redacted target | +| `exceptions` | One liftable denial (`command`, `domain`, `network`), reason, requester, approver, expiry, revocation, exact profile revision | +| `session_exceptions` | Exceptions each session was admitted with | +| `audit_events` | Append-only, hash-chained evidence with a redacted target, the exception concerned, and a short non-secret detail | Constraints carry the invariants the database can check: identifier grammar, -7-day grant and exception lifetimes, a 60-second revocation grace, approvers -who differ from requesters, grants whose principal, project, binding, and -profile must equal their session's (composite foreign key), and audit rows that -must extend the chain and can never be updated or deleted (triggers). Each -`event_hash` will be SHA-256 over `previous_hash` and the event's RFC 8785 -canonical JSON, computed by the service. +7-day grant and exception lifetimes, 90-day tokens, a 60-second revocation +grace, approvers who differ from requesters, grants whose principal, project, +binding, and profile must equal their session's (composite foreign key), and +audit rows that must extend the chain and can never be updated or deleted +(triggers). + +Writers are serialized (SQLite `BEGIN IMMEDIATE`, PostgreSQL transaction +advisory lock), so check-then-write decisions cannot race. Every state change +and the audit event that records it commit in one transaction; a refused, +security-relevant request commits only its audit event. + +## Audit + +Each event records the actor (the authenticated caller, or `cli:admin`), the +principal, project, session, grant, exception, and profile revision it +concerns, the decision and deny reason, an outcome, a redacted target +(`METHOD service/path`, never a query string), and a short detail such as +`role=admin` or `scope=domain:gist.github.com`. Credentials, tokens, headers, +request or response bodies, and exception reasons are never recorded. + +`event_hash` is the SHA-256 of the RFC 8785 canonical JSON of the event as +returned by `GET /v1/audit/events` without `event_hash` (so it includes +`previous_hash`). The first event links to 64 zeros. `GET /v1/audit/verify` +recomputes the chain; anchoring chain heads outside the database is on the +roadmap. ## Logging @@ -158,14 +208,18 @@ bodies, headers, and query strings are never logged. Details in ```text crates/fleet-server/src/ - main.rs process entry: config, logging, runtime, exit codes + main.rs process entry: serve (default) or `admin` subcommands + admin.rs bootstrap: principals, tokens, projects (direct database access) server.rs app assembly, startup, graceful shutdown, retention timer - config.rs environment configuration and validation + config.rs environment configuration and profile trust loading + state.rs shared state: database, clock, random ids, authority id, trust logging.rs subscriber setup and request logging middleware logging/retention.rs - db.rs pools, migrations, readiness ping + db.rs pools, migrations, readiness, backend-neutral transactions and rows + governance.rs stored roles, profiles, sessions, grants, and exceptions + audit.rs hash-chained append, queries, chain verification problem.rs RFC 9457 problem responses - auth.rs bearer authentication middleware and Authenticator trait - routes/ health probes and the /v1 scaffold + auth.rs bearer authentication middleware and DatabaseAuthenticator + routes/ health probes and the /v1 API migrations/{postgres,sqlite}/ ``` diff --git a/docs/contract.md b/docs/contract.md index 8189f57..45f48e5 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -27,7 +27,9 @@ sendbox-governance = { git = "https://github.com/mbianchidev/sendbox", branch = depends on `sendbox-core` by path; Cargo resolves both from the same git checkout. - Only `main` is tracked, so the recorded commit cannot disappear when sendbox - feature branches are rewritten or deleted. + feature branches are rewritten or deleted. A pull request that needs an + unmerged contract change may track the sendbox pull request branch while + both are in review; it must move back to `main` before it merges. To move the lockfile by hand, to the latest `main` commit or to a specific one: @@ -41,30 +43,35 @@ cargo test --locked --workspace | Contract type | Used by | | --- | --- | -| `GovernanceBinding`, `AuthorityRef`, `SessionRef` | `POST /v1/sessions:admit` body | +| `api::CallerIdentity` | `GET /v1/whoami` response | +| `api::SessionAdmissionRequest`, `api::SessionAdmission`, `GovernanceBinding` | `POST /v1/sessions:admit` body and response | +| `api::SessionEnd` | `POST /v1/sessions/{session}:end` body | | `GrantRequest`, `CredentialGrant` | `POST /v1/grants` body and response | | `GrantId` | `:renew` and `:revoke` path parameter; renew response is a `CredentialGrant` | -| `RevocationReason` | `:revoke` body | -| `RequestContext`, `Decision`, `DenyReason` | `POST /v1/authorize` body and response | -| `ProfileId`, `ProfileRef`, `GovernanceProfile` | `/v1/profiles/{profile_id}`; publication bodies are parsed with `GovernanceProfile::parse` | +| `api::RevokeGrantRequest`, `RevocationReason` | `:revoke` body | +| `RequestContext`, `Decision`, `DenyReason`, `evaluate_request` | `POST /v1/authorize` body, response, and decision rules | +| `ProfileId`, `ProfileRef`, `GovernanceProfile`, `check_current` | `/v1/profiles/{profile_id}`; publication bodies are parsed with `GovernanceProfile::parse` | +| `PolicyException`, `ExceptionScope`, `ExceptionId`, `api::ExceptionList` | `/v1/exceptions` responses; scopes are checked with `GovernanceProfile::permits_exception` | | `ProjectId`, `PrincipalId` | Role, exception, and audit endpoints | -| `Sha256Digest` | Digests in responses and audit events | +| `Sha256Digest`, `canonical_digest` | Digests in responses, binding storage, and audit event hashes | Validation is the contract's own: identifier grammars, `deny_unknown_fields`, `GovernanceBinding::validate`, `validate_method`, `validate_path_prefix`, and `GovernanceProfile::parse`. Invalid input is a `400` problem. -Types that only exist on the management API live in this repository, in the -route module that uses them: `SessionAdmissionRequest`, `RevokeGrantRequest`, -`ProfilePublication` and `ProfileSignature`, `ProjectRole` and `RoleBinding`, -`ExceptionRequest`, and the audit query and event types. The profile signature -envelope is a placeholder: once increment 1 defines the operator signing -format in `sendbox-governance`, the fleet adopts that type instead. +Wire types a SendBox host also uses live in `sendbox_governance::api`. Types +only people use live here, in the route module that uses them: +`CreateProject`, `ProjectRole` and `RoleBinding`, `ExceptionRequest`, +`ProfilePublication` and `MinimumRevision`, and the audit query, page, and +event types. Profile signatures use SendBox's signing envelope +(`sendbox_security::provenance::DetachedSignature` in a +`sendbox.governance-signatures` bundle), verified with the same trust store +code as hosts. ## Versioning -- `sendbox_governance::CONTRACT_VERSION` (currently `1`) is the wire and digest - version. `GovernanceBinding` and `CredentialGrant` carry it, and validation +- `sendbox_governance::CONTRACT_VERSION` (currently `2`, which added + exceptions to the session binding) is the wire and digest version. `GovernanceBinding` and `CredentialGrant` carry it, and validation rejects any other value. The server logs it at startup. - Contract structs use `deny_unknown_fields`, so adding a field is a breaking change for older peers. Any change to a contract type or to how digests are diff --git a/docs/development.md b/docs/development.md index 8ac7d8f..55b5dac 100644 --- a/docs/development.md +++ b/docs/development.md @@ -18,6 +18,8 @@ with status `2` and a message naming the variable when a value is invalid. | `FLEET_LOG_DIR` | `./logs` | Log directory; relative paths resolve against the working directory at startup | | `FLEET_LOG_LEVEL` | `info,sqlx=warn` | [`EnvFilter`](https://docs.rs/tracing-subscriber/latest/tracing_subscriber/filter/struct.EnvFilter.html) directives | | `FLEET_LOG_RETENTION_DAYS` | `30` | Days to keep rotated log files (1 to 3650) | +| `FLEET_AUTHORITY_ID` | `sendbox-fleet` | Authority id hosts put in `authority:` of their operator configuration and bind into every session; not `local` | +| `FLEET_PROFILE_TRUST` | unset | YAML or JSON file with `threshold` and `signers` (the same shape as a host operator configuration's `trust` section). Profile publication is refused until it is set | Database credentials in `FLEET_DATABASE_URL` are never logged. @@ -36,6 +38,46 @@ Migrations run at startup. Stop the server with Ctrl-C (or `SIGTERM`); it stops accepting connections, gives in-flight requests up to 30 seconds, closes the database pool, and flushes logs. +## Bootstrap principals, tokens, and projects + +`sendbox-fleet admin` acts on the database directly and needs only +`FLEET_DATABASE_URL`. Every change is audited with the actor `cli:admin`. + +```sh +sendbox-fleet admin principal add oidc:olivia@example.com --kind user --operator +sendbox-fleet admin principal add oidc:owen@example.com --kind user +sendbox-fleet admin principal add worker:ci-1 --kind worker +sendbox-fleet admin project create github:example/service --owner oidc:owen@example.com +sendbox-fleet admin token issue oidc:owen@example.com --ttl-days 30 > owen.token +sendbox-fleet admin token list oidc:owen@example.com +sendbox-fleet admin token revoke +sendbox-fleet admin principal disable oidc:owen@example.com +``` + +`token issue` prints the token once on stdout; only its SHA-256 is stored. +People then use the API with `Authorization: Bearer `, for example: + +```sh +T=$(cat owen.token); U=http://127.0.0.1:8080 +curl -H "Authorization: Bearer $T" $U/v1/whoami +curl -H "Authorization: Bearer $T" -H 'Content-Type: application/json' \ + -d '{"principal":"oidc:alice@example.com","role":"member"}' \ + "$U/v1/projects/github:example%2Fservice/roles" +``` + +An operator publishes the exact profile and the signature bundle produced by +`sendbox governance sign`: + +```sh +jq -n --rawfile document acme.yaml --slurpfile signatures acme.yaml.sig.json \ + '{document: $document, signatures: $signatures[0]}' | + curl -X PUT -H "Authorization: Bearer $OPERATOR_TOKEN" \ + -H 'Content-Type: application/json' --data @- $U/v1/profiles/acme +``` + +On each SendBox host, the operator configuration names this service and the +caller stores their own token: `sendbox secrets add SENDBOX_FLEET_TOKEN`. + ## Run with PostgreSQL (Compose) ```sh @@ -57,21 +99,22 @@ cargo test --locked --workspace cargo audit --deny warnings # needs cargo-audit; see .cargo/audit.toml ``` -Tests use in-memory SQLite and synthetic data. To run the migration tests -against PostgreSQL, point `FLEET_TEST_DATABASE_URL` at a disposable database -whose name ends in `_test` (the tests drop and recreate its `public` schema): +Tests use in-memory SQLite and synthetic data. To run the migration and API +tests against PostgreSQL, point `FLEET_TEST_DATABASE_URL` at a disposable +database whose name ends in `_test` (the tests drop and recreate its `public` +schema): ```sh docker run -d --name sendbox-fleet-pg-test -p 127.0.0.1:55432:5432 \ -e POSTGRES_DB=sendbox_fleet_test -e POSTGRES_USER=sendbox_fleet \ -e POSTGRES_HOST_AUTH_METHOD=trust postgres:18.7-alpine3.24 FLEET_TEST_DATABASE_URL=postgres://sendbox_fleet@127.0.0.1:55432/sendbox_fleet_test \ - cargo test --locked --workspace --test migrations -- --test-threads=1 + cargo test --locked --workspace --test migrations --test http -- --test-threads=1 docker rm -f sendbox-fleet-pg-test ``` -CI runs formatting, Clippy, and tests on SQLite; the migration tests plus a -start, probe, and graceful-stop run of the server on PostgreSQL; and +CI runs formatting, Clippy, and tests on SQLite; the migration and API tests +plus a start, probe, and graceful-stop run of the server on PostgreSQL; and `cargo audit`. ## Logs @@ -107,4 +150,6 @@ invariant. | `cannot connect to postgres://***@...` | Database not reachable or wrong credentials | | `cannot listen on ...` | Port already in use; set `FLEET_BIND` or `FLEET_PORT` | | `cannot create log directory` | `FLEET_LOG_DIR` not writable by the server user | -| Every `/v1` call returns `401 authentication provider not configured` | Expected: no identity provider is integrated yet | +| Every `/v1` call returns `401 bearer token was not accepted` | The token is unknown, expired, revoked, or its principal is disabled; issue a new one with `sendbox-fleet admin token issue` | +| `503 profile signers are not configured` on profile publication | Set `FLEET_PROFILE_TRUST` | +| `409 ... is not the current revision` on session admission | The host's local profile differs from the newest published revision; install the same signed bytes on the host | diff --git a/docs/roadmap.md b/docs/roadmap.md index 00fc1b7..eaa4f14 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -18,63 +18,55 @@ Each item names the issue's acceptance criteria (AC) it serves: - **AC8** Standalone workflows stay unchanged unless governance is selected; compatibility and trust boundaries are documented. -The scaffold delivers the service skeleton, contract-validated `/v1` routes -that return `501`, the schema with its database-level invariants, CI, and -these documents. +## Done -## Work items +The scaffold delivered the service skeleton, the schema with its database +invariants, CI, and these documents. Increment 2 then delivered: -1. **Caller authentication** (AC7). Integrate an identity provider for users - and a workload identity for SendBox hosts (for example mTLS or signed, - short-lived worker tokens). Replace `UnconfiguredAuthenticator`; keep the - bearer-only rule and the "authenticate before validating" ordering. - *Done when* users and workers authenticate with expiring credentials and - every `/v1` call records the authenticated actor. -2. **Persistence layer** (all). Repositories over the existing tables, an - injectable clock, random identifiers, and transactions that keep the - database invariants as the only source of truth. -3. **Profiles** (AC1, AC5). Publication with signature verification over the - exact bytes (adopting the signing envelope from `sendbox-governance`), - current-revision lookup, minimum revisions, and a `RevisionSource` - backed by the database. *Done when* a host can only admit sessions under a - current, verified revision. -4. **Project-scoped roles** (AC7). Owner bootstrap, assignment and listing - with role checks, and audit of every change. *Done when* role checks gate - admission, exceptions, and audit visibility. -5. **Session admission** (AC1, AC4). Verify the worker, the principal's role in - the project, the profile revision, and the binding digest; record the - session. *Done when* a host that presents a changed binding or stale - revision is refused. -6. **Grants and revocation** (AC4, AC5, AC6). Issue, renew, and revoke with - bounded leases (profile `lease_seconds`, `max_ttl_seconds`); end all grants - when a session completes, fails, or is cancelled; deny new requests at once - and let open streams finish only within `revocation_grace_seconds` (at most - 60 seconds); record uncertain external effects as outcome `unknown`. - Includes the remote authority client in the sendbox host (sendbox - repository). *Done when* revoked or expired grants deny on the next request - and existing connections close within the grace window. -7. **Per-request authorization** (AC4, AC5). `POST /v1/authorize` with the same - semantics as `LocalGrantAuthority::authorize`, a latency budget, and - fail-closed behaviour on the host (`authority_unavailable`). *Done when* - every cross-identity and stale-policy case from the contract tests denies - through the service. -8. **Exceptions** (AC7). Request, approve, reject, and revoke; approver must be - an authorized principal other than the requester; scope must stay inside - the bound profile revision's ceiling (never above the operator maximum); - expiry at most 7 days. *Done when* an approval bound to an older revision - is rejected after a new revision or minimum revision is published (stale - approval rejection). -9. **Central audit** (AC6, AC7). Compute the hash chain, correlate principal, - project, session, profile revision, redacted target, decision, and outcome - from hosts and the service; role-scoped queries; anchor chain heads outside - the database. *Done when* every decision above produces an attributable, - verifiable event without secret-bearing payloads. -10. **Operations** (AC8). TLS termination guidance, rate limiting, metrics, - backups, database role hardening (no `UPDATE`/`DELETE` on audit), and - deployment docs. Size-based log rotation alongside the daily rotation. -11. **Dependency follow-ups.** Move the contract pin to a merged sendbox - commit; upgrade to sqlx 0.9 once the toolchain moves to Rust 1.94 or later - and drop the `cargo audit` exceptions in `.cargo/audit.toml`. +- **Caller authentication** (AC7). Opaque bearer tokens issued by + `sendbox-fleet admin token issue`, stored only as SHA-256 digests, expiring + within 90 days, revocable, and void when the principal is disabled. The + bearer-only rule and "authenticate before validating" ordering are kept. +- **Persistence** (all). Backend-neutral transactions over PostgreSQL and + SQLite with serialized writers, an injectable clock, random identifiers, + and every change committed with its audit event. +- **Profiles** (AC1, AC5). Publication verified against `FLEET_PROFILE_TRUST` + using the `sendbox.governance-signatures` bundle from `sendbox governance + sign`; monotonic revisions; current-revision lookup; rising minimums. +- **Project-scoped roles** (AC7). Operator project bootstrap, owner-managed + assignment and removal, last-owner guard, audited refusals. Roles gate + admission, exceptions, and audit visibility. +- **Session admission** (AC1, AC4). Caller-bound principal, this authority, + `member` role, current revision, offered services, and valid exceptions. +- **Grants and revocation** (AC4, AC5, AC6). Issue, renew, revoke, and end + sessions with bounded leases, exception-capped expiry, and the profile grace + window. The SendBox host's remote authority client lives in the sendbox + repository. +- **Per-request authorization** (AC4, AC5). Same rules as the local authority + through the shared `evaluate_request`, plus session and exception state. +- **Exceptions** (AC7). Request, approve, reject, revoke; a different + `owner` or `admin` approves; scope limited to denials the signed revision + lists as liftable; expiry at most 7 days; stale approvals rejected after a + new revision or minimum. +- **Central audit** (AC6, AC7). Hash-chained events for every decision with + actor, principal, project, session, grant, exception, revision, decision, + redacted target, and detail; role-scoped queries; chain verification. + +## Remaining + +1. **Identity provider** (AC7 hardening). Replace or complement admin-issued + tokens with OIDC for people and mTLS or signed short-lived tokens for + workers; self-service token issuance. +2. **Live end-to-end runs.** Run Apple and Kata governed sessions against a + deployed fleet and real model providers. +3. **Audit anchoring and outcomes.** Anchor chain heads outside the database; + accept host-reported stream outcomes (`succeeded`, `failed`, `unknown`). +4. **Operations** (AC8). TLS termination guidance, rate limiting, metrics, + backups, database role hardening (no `UPDATE`/`DELETE` on audit), + deployment docs, and size-based log rotation. +5. **Dependency follow-ups.** Move the contract pin to a merged sendbox + commit; upgrade to sqlx 0.9 once the toolchain moves to Rust 1.94 or later + and drop the `cargo audit` exceptions in `.cargo/audit.toml`. ## Non-goals diff --git a/docs/threat-model.md b/docs/threat-model.md index 37df5cd..e061792 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -4,7 +4,7 @@ Scope: the shared governance service in this repository and its interfaces to SendBox hosts, people, and its database. The SendBox VM boundary, host broker, and increment-1 local authority are covered in the sendbox repository. -Status column: **in scaffold** means implemented and tested here; **planned** +Status column: **implemented** means implemented and tested here; **planned** means designed but not implemented (see [roadmap.md](roadmap.md)). ## Assets @@ -22,9 +22,10 @@ SendBox host broker and never reach the fleet. | Actor | Trust | | --- | --- | -| Operator | Trusted to sign and publish profiles | +| Operator | Trusted to sign and publish profiles, create projects, and recover ownership | | Project owner, admin, member, viewer | Trusted within their project role | -| Worker (SendBox host) | Trusted to report its own sessions; untrusted for anything else | +| SendBox host (user or worker token) | Trusted to report sessions of the principal whose token it holds; untrusted for anything else | +| Service host administrator (`sendbox-fleet admin`) | Issues tokens and creates principals; equivalent to database access | | Workload (agent inside a VM) | Untrusted; never talks to the fleet directly | | Network attacker | Untrusted | | Database administrator | Can bypass application controls; mitigated by evidence anchoring | @@ -33,19 +34,19 @@ SendBox host broker and never reach the fleet. | # | Threat | Mitigation | Status | | --- | --- | --- | --- | -| T1 | Caller spoofs identity with headers such as `X-Forwarded-User` | Only bearer tokens authenticate; identity headers are ignored; auth runs before routing | In scaffold (tested) | -| T2 | Workload-supplied identity in a body is trusted | Body principals and projects are claims checked against the authenticated caller and stored state; `local-user:` principals rejected by API and schema | Partly in scaffold; checks planned | -| T3 | Stolen or replayed bearer token | Short-lived tokens from a real identity provider, audience binding, TLS everywhere | Planned (provider not chosen) | -| T4 | Compromised worker acts for sessions it does not run | Workers may only act on sessions they admitted; grants bound to session, principal, project, binding digest, and profile revision (composite foreign key) | Schema in scaffold; logic planned | -| T5 | Stale policy or approval authorizes changed work | Sessions, grants, and exceptions reference an exact profile revision and digest; minimum revisions; stale revisions deny | Schema in scaffold; logic planned | -| T6 | Grant wider than the profile allows | Contract validation of methods and path prefixes at the API; ceiling checks; 7-day TTL bound in the schema | Validation and bounds in scaffold; ceiling checks planned | -| T7 | Audit evidence altered or deleted | Append-only triggers, contiguous hash chain enforced on insert, service role without `UPDATE`/`DELETE`; external anchoring of chain heads against a database administrator | Triggers in scaffold; hashing and anchoring planned | -| T8 | Secrets leak into logs or audit | No request bodies, headers, or query strings logged; database URL credentials redacted; no credential columns; audit keeps a redacted target without query strings (schema check) | In scaffold | -| T9 | Authority outage silently allows requests | Hosts must deny with `authority_unavailable` on any non-200 answer (contract semantics); the scaffold answers `501` | Contract rule; host integration planned | -| T10 | Exception abuse or self-approval | Bounded scope, reason, expiry of at most 7 days, approver differs from requester (schema check), never wider than the profile ceiling | Bounds in scaffold; approval flow planned | -| T11 | Revocation does not stop in-flight traffic | New requests denied at once; open streams bounded by a grace window of at most 60 seconds; uncertain outcomes audited as `unknown` | Schema in scaffold; logic planned | -| T12 | Resource exhaustion | Body limits (64 KiB, 1 MiB for profile publication), bounded connection pool and acquire timeout, non-lossy bounded log queue | In scaffold; rate limiting planned | -| T13 | Supply-chain compromise | Actions pinned by commit SHA, images pinned by digest, `Cargo.lock` committed, contract pinned by git revision, `cargo audit` in CI with documented exceptions | In scaffold | +| T1 | Caller spoofs identity with headers such as `X-Forwarded-User` | Only bearer tokens authenticate; identity headers are ignored; auth runs before routing | Implemented (tested) | +| T2 | Workload-supplied identity in a body is trusted | Binding and grant principals must equal the authenticated caller; projects and sessions are checked against stored state; `local-user:` principals rejected by API and schema | Implemented (tested) | +| T3 | Stolen or replayed bearer token | Tokens stored only as SHA-256, expiring within 90 days, revocable, void when the principal is disabled; TLS in front of the service | Implemented; identity provider and audience binding planned | +| T4 | Compromised worker acts for sessions it does not run | A caller can only admit, use, renew, or end sessions bound to its own principal; grants bound to session, principal, project, binding digest, and profile revision (composite foreign key) | Implemented (tested) | +| T5 | Stale policy or approval authorizes changed work | Sessions, grants, and exceptions reference an exact profile revision and digest; a new revision or raised minimum makes them stale; approvals of stale requests are refused; sessions bound to a revoked or expired exception are denied | Implemented (tested) | +| T6 | Grant wider than the profile allows | Methods and path prefixes must be inside the profile service; lifetime capped by the profile TTL, profile expiry, exception expiry, and 7 days | Implemented (tested) | +| T7 | Audit evidence altered or deleted | Append-only triggers, contiguous hash chain computed by the service and enforced on insert, `GET /v1/audit/verify`; service role without `UPDATE`/`DELETE`; external anchoring of chain heads against a database administrator | Implemented except role hardening and anchoring (planned) | +| T8 | Secrets leak into logs or audit | No request bodies, headers, or query strings logged; database URL credentials redacted; tokens stored only as digests; no credential columns; audit keeps a redacted target without query strings (schema check) and omits exception reasons | Implemented (tested) | +| T9 | Authority outage silently allows requests | Hosts deny with `authority_unavailable` on any non-200 answer, timeout, or redirect; a token lookup failure is `503` | Implemented (host client tested in sendbox) | +| T10 | Exception abuse or self-approval | Only denials the signed revision lists as liftable; reason; expiry at most the profile's `exceptions.max_ttl_seconds` and 7 days; approver is a different `owner` or `admin` (also a schema check); lifting never widens the ceiling; every request, decision, refusal, use, and revocation audited | Implemented (tested) | +| T11 | Revocation does not stop in-flight traffic | New requests denied at once; open streams bounded by the profile grace window (at most 60 seconds) on the host; uncertain outcomes audited on the host as `aborted_uncertain` | Implemented; central outcome reporting planned | +| T12 | Resource exhaustion | Body limits (64 KiB, 1 MiB for profile publication), bounded connection pool and acquire timeout, bounded list sizes, non-lossy bounded log queue | Implemented; rate limiting planned | +| T13 | Supply-chain compromise | Actions pinned by commit SHA, images pinned by digest, `Cargo.lock` committed, contract pinned by git revision, `cargo audit` in CI with documented exceptions | Implemented | ## Known accepted risks diff --git a/migrations/postgres/0002_roles_exceptions.sql b/migrations/postgres/0002_roles_exceptions.sql new file mode 100644 index 0000000..363cfff --- /dev/null +++ b/migrations/postgres/0002_roles_exceptions.sql @@ -0,0 +1,83 @@ +-- SendBox fleet schema, version 2 (PostgreSQL): authentication, operator +-- designation, profile-scoped exceptions, and exception-aware audit. +-- +-- Keep migrations/sqlite/0002_roles_exceptions.sql equivalent. + +-- Fleet-wide operators publish profiles, set minimum revisions, and create +-- projects. Everything else is decided by project-scoped roles. +ALTER TABLE principals ADD COLUMN is_operator BOOLEAN NOT NULL DEFAULT FALSE; + +-- Bearer tokens. Only the SHA-256 of a token is stored, never the token. +CREATE TABLE api_tokens ( + id TEXT PRIMARY KEY CHECK (id ~ '^[0-9a-f]{32}$'), + principal_id TEXT NOT NULL REFERENCES principals (id), + token_sha256 TEXT NOT NULL UNIQUE CHECK (token_sha256 ~ '^[0-9a-f]{64}$'), + description TEXT CHECK (description IS NULL OR char_length(description) BETWEEN 1 AND 200), + created_at_unix BIGINT NOT NULL CHECK (created_at_unix >= 0), + expires_at_unix BIGINT NOT NULL, + revoked_at_unix BIGINT CHECK (revoked_at_unix IS NULL OR revoked_at_unix >= created_at_unix), + -- At most 90 days from issue to expiry. + CHECK (expires_at_unix > created_at_unix AND expires_at_unix - created_at_unix <= 7776000) +); +CREATE INDEX api_tokens_principal ON api_tokens (principal_id); + +-- Version 1 reserved scope kinds that no profile could grant. An exception now +-- lifts exactly one denial the bound profile revision lists as liftable +-- (`command`, `domain`, or `network`); command patterns contain spaces. No +-- version 1 release wrote exceptions, so the table is recreated. +DROP TABLE exceptions; +CREATE TABLE exceptions ( + id TEXT PRIMARY KEY CHECK (id ~ '^[0-9a-f]{32}$'), + project_id TEXT NOT NULL REFERENCES projects (id), + -- NULL covers every principal with a role in the project. + principal_id TEXT REFERENCES principals (id), + profile_id TEXT NOT NULL, + profile_revision BIGINT NOT NULL, + profile_sha256 TEXT NOT NULL, + scope_kind TEXT NOT NULL CHECK (scope_kind IN ('command', 'domain', 'network')), + scope_value TEXT NOT NULL CHECK ( + char_length(scope_value) BETWEEN 1 AND 1024 + AND scope_value ~ '^[ -~]+$' + AND scope_value = btrim(scope_value) + ), + reason TEXT NOT NULL CHECK (char_length(btrim(reason)) BETWEEN 1 AND 1000), + status TEXT NOT NULL CHECK (status IN ('pending', 'approved', 'rejected')), + requested_by TEXT NOT NULL REFERENCES principals (id), + requested_at_unix BIGINT NOT NULL CHECK (requested_at_unix >= 0), + -- The approver (or rejecter); never the requester. + decided_by TEXT REFERENCES principals (id), + decided_at_unix BIGINT, + expires_at_unix BIGINT NOT NULL, + revoked_by TEXT REFERENCES principals (id), + revoked_at_unix BIGINT, + FOREIGN KEY (profile_id, profile_revision, profile_sha256) + REFERENCES profiles (id, revision, sha256), + CHECK (decided_by IS NULL OR decided_by <> requested_by), + CHECK ((status = 'pending') = (decided_by IS NULL)), + CHECK ((decided_by IS NULL) = (decided_at_unix IS NULL)), + CHECK (decided_at_unix IS NULL OR decided_at_unix >= requested_at_unix), + CHECK ((revoked_by IS NULL) = (revoked_at_unix IS NULL)), + CHECK (revoked_at_unix IS NULL OR status = 'approved'), + -- At most 7 days from request to expiry. + CHECK (expires_at_unix > requested_at_unix AND expires_at_unix - requested_at_unix <= 604800) +); +CREATE INDEX exceptions_project ON exceptions (project_id, status); + +-- Exceptions a session was admitted with. Every grant and request of the +-- session is denied once one of them expires or is revoked. +CREATE TABLE session_exceptions ( + session_id TEXT NOT NULL REFERENCES sessions (id), + exception_id TEXT NOT NULL REFERENCES exceptions (id), + PRIMARY KEY (session_id, exception_id) +); +CREATE INDEX session_exceptions_exception ON session_exceptions (exception_id); + +-- Audit events can name the exception they concern and carry a short, +-- non-secret detail such as `role=admin` or a scope. +ALTER TABLE audit_events ADD COLUMN exception_id TEXT CHECK ( + exception_id IS NULL OR exception_id ~ '^[0-9a-f]{32}$' +); +ALTER TABLE audit_events ADD COLUMN detail TEXT CHECK ( + detail IS NULL OR (char_length(detail) BETWEEN 1 AND 1100 AND detail ~ '^[ -~]+$') +); +CREATE INDEX audit_events_exception ON audit_events (exception_id, sequence); diff --git a/migrations/sqlite/0002_roles_exceptions.sql b/migrations/sqlite/0002_roles_exceptions.sql new file mode 100644 index 0000000..8a91ebf --- /dev/null +++ b/migrations/sqlite/0002_roles_exceptions.sql @@ -0,0 +1,85 @@ +-- SendBox fleet schema, version 2 (SQLite): authentication, operator +-- designation, profile-scoped exceptions, and exception-aware audit. +-- +-- Keep equivalent to migrations/postgres/0002_roles_exceptions.sql. + +-- Fleet-wide operators publish profiles, set minimum revisions, and create +-- projects. Everything else is decided by project-scoped roles. +ALTER TABLE principals ADD COLUMN is_operator INTEGER NOT NULL DEFAULT 0 CHECK (is_operator IN (0, 1)); + +-- Bearer tokens. Only the SHA-256 of a token is stored, never the token. +CREATE TABLE api_tokens ( + id TEXT PRIMARY KEY CHECK (length(id) = 32 AND id NOT GLOB '*[^0-9a-f]*'), + principal_id TEXT NOT NULL REFERENCES principals (id), + token_sha256 TEXT NOT NULL UNIQUE CHECK ( + length(token_sha256) = 64 AND token_sha256 NOT GLOB '*[^0-9a-f]*' + ), + description TEXT CHECK (description IS NULL OR length(description) BETWEEN 1 AND 200), + created_at_unix INTEGER NOT NULL CHECK (created_at_unix >= 0), + expires_at_unix INTEGER NOT NULL, + revoked_at_unix INTEGER CHECK (revoked_at_unix IS NULL OR revoked_at_unix >= created_at_unix), + -- At most 90 days from issue to expiry. + CHECK (expires_at_unix > created_at_unix AND expires_at_unix - created_at_unix <= 7776000) +) STRICT; +CREATE INDEX api_tokens_principal ON api_tokens (principal_id); + +-- Version 1 reserved scope kinds that no profile could grant. An exception now +-- lifts exactly one denial the bound profile revision lists as liftable +-- (`command`, `domain`, or `network`); command patterns contain spaces. No +-- version 1 release wrote exceptions, so the table is recreated. +DROP TABLE exceptions; +CREATE TABLE exceptions ( + id TEXT PRIMARY KEY CHECK (length(id) = 32 AND id NOT GLOB '*[^0-9a-f]*'), + project_id TEXT NOT NULL REFERENCES projects (id), + -- NULL covers every principal with a role in the project. + principal_id TEXT REFERENCES principals (id), + profile_id TEXT NOT NULL, + profile_revision INTEGER NOT NULL, + profile_sha256 TEXT NOT NULL, + scope_kind TEXT NOT NULL CHECK (scope_kind IN ('command', 'domain', 'network')), + scope_value TEXT NOT NULL CHECK ( + length(scope_value) BETWEEN 1 AND 1024 + AND scope_value NOT GLOB '*[^ -~]*' + AND scope_value = trim(scope_value) + ), + reason TEXT NOT NULL CHECK (length(trim(reason)) BETWEEN 1 AND 1000), + status TEXT NOT NULL CHECK (status IN ('pending', 'approved', 'rejected')), + requested_by TEXT NOT NULL REFERENCES principals (id), + requested_at_unix INTEGER NOT NULL CHECK (requested_at_unix >= 0), + -- The approver (or rejecter); never the requester. + decided_by TEXT REFERENCES principals (id), + decided_at_unix INTEGER, + expires_at_unix INTEGER NOT NULL, + revoked_by TEXT REFERENCES principals (id), + revoked_at_unix INTEGER, + FOREIGN KEY (profile_id, profile_revision, profile_sha256) + REFERENCES profiles (id, revision, sha256), + CHECK (decided_by IS NULL OR decided_by <> requested_by), + CHECK ((status = 'pending') = (decided_by IS NULL)), + CHECK ((decided_by IS NULL) = (decided_at_unix IS NULL)), + CHECK (decided_at_unix IS NULL OR decided_at_unix >= requested_at_unix), + CHECK ((revoked_by IS NULL) = (revoked_at_unix IS NULL)), + CHECK (revoked_at_unix IS NULL OR status = 'approved'), + -- At most 7 days from request to expiry. + CHECK (expires_at_unix > requested_at_unix AND expires_at_unix - requested_at_unix <= 604800) +) STRICT; +CREATE INDEX exceptions_project ON exceptions (project_id, status); + +-- Exceptions a session was admitted with. Every grant and request of the +-- session is denied once one of them expires or is revoked. +CREATE TABLE session_exceptions ( + session_id TEXT NOT NULL REFERENCES sessions (id), + exception_id TEXT NOT NULL REFERENCES exceptions (id), + PRIMARY KEY (session_id, exception_id) +) STRICT; +CREATE INDEX session_exceptions_exception ON session_exceptions (exception_id); + +-- Audit events can name the exception they concern and carry a short, +-- non-secret detail such as `role=admin` or a scope. +ALTER TABLE audit_events ADD COLUMN exception_id TEXT CHECK ( + exception_id IS NULL OR (length(exception_id) = 32 AND exception_id NOT GLOB '*[^0-9a-f]*') +); +ALTER TABLE audit_events ADD COLUMN detail TEXT CHECK ( + detail IS NULL OR (length(detail) BETWEEN 1 AND 1100 AND detail NOT GLOB '*[^ -~]*') +); +CREATE INDEX audit_events_exception ON audit_events (exception_id, sequence);