From a63d8e016471a924ab74eb1c0abe2ff63aad19b3 Mon Sep 17 00:00:00 2001 From: mbianchidev Date: Sun, 15 Nov 2026 13:40:16 +0100 Subject: [PATCH 1/6] Add PostgreSQL and SQLite schema migrations Tables for principals, projects, project roles, signed profile revisions, minimum revisions, sessions, credential grants, revocations, exceptions, and an append-only hash-chained audit log, with constraints for identifier grammar, bounded lifetimes, separation of duties, and grant-to-session identity binding. --- migrations/postgres/0001_init.sql | 285 +++++++++++++++++++++++++++ migrations/sqlite/0001_init.sql | 314 ++++++++++++++++++++++++++++++ 2 files changed, 599 insertions(+) create mode 100644 migrations/postgres/0001_init.sql create mode 100644 migrations/sqlite/0001_init.sql diff --git a/migrations/postgres/0001_init.sql b/migrations/postgres/0001_init.sql new file mode 100644 index 0000000..4081e60 --- /dev/null +++ b/migrations/postgres/0001_init.sql @@ -0,0 +1,285 @@ +-- SendBox fleet schema, version 1 (PostgreSQL). +-- +-- Keep migrations/sqlite/0001_init.sql equivalent: same tables, columns, and +-- constraints. Timestamps are Unix seconds to match the sendbox-governance +-- contract. Identifier columns repeat the contract's grammar and bounds so a +-- row stays valid whichever client wrote it. No table stores provider +-- credentials, bearer tokens, authorization headers, request bodies, or any +-- other secret-bearing payload. + +-- Authenticated callers: people (`user`) and SendBox hosts (`worker`). +CREATE TABLE principals ( + id TEXT PRIMARY KEY CHECK ( + char_length(id) <= 160 + AND id ~ '^[a-z-]{1,32}:[A-Za-z0-9._@+:-]+$' + -- Local OS accounts belong to single-host increment 1 and are never + -- fleet principals. + AND id NOT LIKE 'local-user:%' + ), + kind TEXT NOT NULL CHECK (kind IN ('user', 'worker')), + display_name TEXT CHECK (display_name IS NULL OR char_length(display_name) BETWEEN 1 AND 200), + created_at_unix BIGINT NOT NULL CHECK (created_at_unix >= 0), + disabled_at_unix BIGINT CHECK (disabled_at_unix IS NULL OR disabled_at_unix >= created_at_unix) +); + +CREATE TABLE projects ( + id TEXT PRIMARY KEY CHECK ( + char_length(id) <= 160 + AND ( + id ~ '^github:[a-z0-9_-][a-z0-9._-]{0,99}/[a-z0-9_-][a-z0-9._-]{0,99}$' + OR id ~ '^path-sha256:[0-9a-f]{64}$' + ) + ), + display_name TEXT CHECK (display_name IS NULL OR char_length(display_name) BETWEEN 1 AND 200), + created_at_unix BIGINT NOT NULL CHECK (created_at_unix >= 0), + archived_at_unix BIGINT CHECK (archived_at_unix IS NULL OR archived_at_unix >= created_at_unix) +); + +-- Project-scoped roles: one role per principal per project. +CREATE TABLE role_bindings ( + project_id TEXT NOT NULL REFERENCES projects (id), + principal_id TEXT NOT NULL REFERENCES principals (id), + role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'member', 'viewer')), + granted_by TEXT NOT NULL REFERENCES principals (id), + granted_at_unix BIGINT NOT NULL CHECK (granted_at_unix >= 0), + PRIMARY KEY (project_id, principal_id) +); +CREATE INDEX role_bindings_principal ON role_bindings (principal_id); + +-- Operator-signed profile revisions. `signed_bytes` are the exact bytes the +-- signatures cover and `sha256` is their digest; rows are never edited, a +-- change is a new revision. +CREATE TABLE profiles ( + id TEXT NOT NULL CHECK (id ~ '^[a-z0-9][a-z0-9._-]{0,63}$'), + revision BIGINT NOT NULL CHECK (revision >= 1), + sha256 TEXT NOT NULL UNIQUE CHECK (sha256 ~ '^[0-9a-f]{64}$'), + signed_bytes BYTEA NOT NULL CHECK (octet_length(signed_bytes) BETWEEN 1 AND 262144), + signatures JSONB NOT NULL CHECK ( + CASE WHEN jsonb_typeof(signatures) = 'array' + THEN jsonb_array_length(signatures) BETWEEN 1 AND 16 + ELSE false + END + ), + not_before_unix BIGINT NOT NULL CHECK (not_before_unix >= 0), + expires_at_unix BIGINT NOT NULL, + published_by TEXT NOT NULL REFERENCES principals (id), + published_at_unix BIGINT NOT NULL CHECK (published_at_unix >= 0), + PRIMARY KEY (id, revision), + UNIQUE (id, revision, sha256), + -- At most 400 days of validity, matching the contract. + CHECK (expires_at_unix > not_before_unix AND expires_at_unix - not_before_unix <= 34560000) +); + +-- Revisions below the minimum are stale: sessions, grants, and exceptions +-- bound to them are denied. +CREATE TABLE profile_minimum_revisions ( + profile_id TEXT PRIMARY KEY, + minimum_revision BIGINT NOT NULL CHECK (minimum_revision >= 1), + reason TEXT NOT NULL CHECK (char_length(btrim(reason)) BETWEEN 1 AND 1000), + set_by TEXT NOT NULL REFERENCES principals (id), + set_at_unix BIGINT NOT NULL CHECK (set_at_unix >= 0), + FOREIGN KEY (profile_id, minimum_revision) REFERENCES profiles (id, revision) +); + +-- Admitted sessions and the exact binding they were admitted with. +CREATE TABLE sessions ( + id TEXT PRIMARY KEY CHECK (id ~ '^[0-9a-f]{32}$'), + principal_id TEXT NOT NULL REFERENCES principals (id), + project_id TEXT NOT NULL REFERENCES projects (id), + authority_id TEXT NOT NULL CHECK (authority_id ~ '^[!-~]{1,128}$'), + profile_id TEXT NOT NULL, + profile_revision BIGINT NOT NULL, + profile_sha256 TEXT NOT NULL, + effective_policy_sha256 TEXT NOT NULL CHECK (effective_policy_sha256 ~ '^[0-9a-f]{64}$'), + -- RFC 8785 canonical JSON of the GovernanceBinding, kept byte-exact; + -- binding_sha256 is its digest. + binding JSON NOT NULL CHECK (json_typeof(binding) = 'object' AND octet_length(binding::text) <= 16384), + binding_sha256 TEXT NOT NULL CHECK (binding_sha256 ~ '^[0-9a-f]{64}$'), + status TEXT NOT NULL CHECK (status IN ('admitted', 'completed', 'cancelled', 'failed')), + -- The worker (SendBox host) that requested admission. + admitted_by TEXT NOT NULL REFERENCES principals (id), + admitted_at_unix BIGINT NOT NULL CHECK (admitted_at_unix >= 0), + ended_at_unix BIGINT, + FOREIGN KEY (profile_id, profile_revision, profile_sha256) + REFERENCES profiles (id, revision, sha256), + UNIQUE (id, principal_id, project_id, binding_sha256, profile_id, profile_revision, profile_sha256), + CHECK ((status = 'admitted') = (ended_at_unix IS NULL)), + CHECK (ended_at_unix IS NULL OR ended_at_unix >= admitted_at_unix) +); +CREATE INDEX sessions_project ON sessions (project_id); +CREATE INDEX sessions_principal ON sessions (principal_id); + +-- Expiring, revocable authorizations for one session to use one brokered +-- service. Deliberately no column can hold credential material: the provider +-- credential stays in the SendBox host broker. +CREATE TABLE credential_grants ( + id TEXT PRIMARY KEY CHECK (id ~ '^[0-9a-f]{32}$'), + session_id TEXT NOT NULL, + principal_id TEXT NOT NULL, + project_id TEXT NOT NULL, + binding_sha256 TEXT NOT NULL, + profile_id TEXT NOT NULL, + profile_revision BIGINT NOT NULL, + profile_sha256 TEXT NOT NULL, + service_id TEXT NOT NULL CHECK (service_id ~ '^[a-z][a-z0-9-]{0,31}$'), + methods JSONB NOT NULL CHECK ( + CASE WHEN jsonb_typeof(methods) = 'array' + THEN jsonb_array_length(methods) BETWEEN 1 AND 7 + ELSE false + END + ), + path_prefixes JSONB NOT NULL CHECK ( + CASE WHEN jsonb_typeof(path_prefixes) = 'array' + THEN jsonb_array_length(path_prefixes) BETWEEN 1 AND 256 + ELSE false + END + ), + issued_at_unix BIGINT NOT NULL CHECK (issued_at_unix >= 0), + lease_expires_at_unix BIGINT NOT NULL, + max_expires_at_unix BIGINT NOT NULL, + generation BIGINT NOT NULL CHECK (generation >= 1), + -- A grant carries exactly its session's identity, binding, and profile. + FOREIGN KEY (session_id, principal_id, project_id, binding_sha256, profile_id, profile_revision, profile_sha256) + REFERENCES sessions (id, principal_id, project_id, binding_sha256, profile_id, profile_revision, profile_sha256), + CHECK (issued_at_unix < lease_expires_at_unix AND lease_expires_at_unix <= max_expires_at_unix), + -- At most 7 days from issue to hard expiry, matching the contract. + CHECK (max_expires_at_unix - issued_at_unix <= 604800) +); +CREATE INDEX credential_grants_session ON credential_grants (session_id); + +-- A revoked grant denies new requests immediately. Already-open upstream +-- streams may finish until `grace_expires_at_unix` (at most 60 seconds); +-- revocation does not undo completed external effects. +CREATE TABLE revocations ( + grant_id TEXT PRIMARY KEY REFERENCES credential_grants (id), + reason TEXT NOT NULL CHECK ( + reason IN ('session_completed', 'session_cancelled', 'session_failed', 'operator_revoked', 'policy_changed') + ), + -- NULL when the service revoked the grant itself, for example at session end. + revoked_by TEXT REFERENCES principals (id), + revoked_at_unix BIGINT NOT NULL CHECK (revoked_at_unix >= 0), + grace_expires_at_unix BIGINT NOT NULL, + generation BIGINT NOT NULL CHECK (generation >= 2), + CHECK (grace_expires_at_unix >= revoked_at_unix AND grace_expires_at_unix - revoked_at_unix <= 60), + CHECK (reason <> 'operator_revoked' OR revoked_by IS NOT NULL) +); + +-- Bounded, expiring exceptions. Each is bound to the exact profile revision it +-- was reviewed against, so a stale approval cannot authorize changed work, and +-- the service rejects any scope outside that revision's ceiling. +CREATE TABLE exceptions ( + id TEXT PRIMARY KEY CHECK (id ~ '^[0-9a-f]{32}$'), + project_id TEXT NOT NULL REFERENCES projects (id), + -- NULL covers every member of 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 ('network_domain', 'command', 'mcp_tool', 'credential_service_path') + ), + scope_value TEXT NOT NULL CHECK (char_length(scope_value) BETWEEN 1 AND 256 AND 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); + +-- Append-only, hash-chained audit log. Each event_hash is computed by the +-- service over previous_hash and the event's canonical JSON. The trigger +-- below enforces contiguous sequences and chain linkage; a second trigger +-- forbids UPDATE, DELETE, and TRUNCATE. Deployments should additionally run +-- the service with a role that lacks those privileges. +CREATE TABLE audit_events ( + sequence BIGINT PRIMARY KEY CHECK (sequence >= 1), + occurred_at_unix BIGINT NOT NULL CHECK (occurred_at_unix >= 0), + recorded_at_unix BIGINT NOT NULL CHECK (recorded_at_unix >= 0), + event_type TEXT NOT NULL CHECK (event_type ~ '^[a-z][a-z0-9_.]{0,63}$'), + -- The authenticated caller that caused the event. + actor_id TEXT CHECK (actor_id IS NULL OR char_length(actor_id) <= 160), + -- Identifiers are copied, not referenced, so evidence outlives its subjects. + principal_id TEXT CHECK (principal_id IS NULL OR char_length(principal_id) <= 160), + project_id TEXT CHECK (project_id IS NULL OR char_length(project_id) <= 160), + session_id TEXT CHECK (session_id IS NULL OR session_id ~ '^[0-9a-f]{32}$'), + grant_id TEXT CHECK (grant_id IS NULL OR grant_id ~ '^[0-9a-f]{32}$'), + profile_id TEXT CHECK (profile_id IS NULL OR char_length(profile_id) <= 64), + profile_revision BIGINT CHECK (profile_revision IS NULL OR profile_revision >= 1), + decision TEXT CHECK (decision IS NULL OR decision IN ('allow', 'deny')), + deny_reason TEXT CHECK ( + deny_reason IS NULL OR deny_reason IN ( + 'unknown_grant', 'revoked', 'expired', 'lease_expired', 'principal_mismatch', + 'project_mismatch', 'session_mismatch', 'binding_mismatch', 'stale_policy', + 'service_not_granted', 'method_not_granted', 'path_not_granted', 'invalid_path', + 'authority_unavailable' + ) + ), + outcome TEXT CHECK (outcome IS NULL OR outcome IN ('succeeded', 'failed', 'unknown')), + -- Method, host, and path prefix only: never a query string or body. + target_redacted TEXT CHECK ( + target_redacted IS NULL OR (char_length(target_redacted) <= 512 AND position('?' in target_redacted) = 0) + ), + previous_hash TEXT NOT NULL CHECK (previous_hash ~ '^[0-9a-f]{64}$'), + event_hash TEXT NOT NULL UNIQUE CHECK (event_hash ~ '^[0-9a-f]{64}$'), + CHECK (deny_reason IS NULL OR decision = 'deny'), + CHECK (decision IS DISTINCT FROM 'deny' OR deny_reason IS NOT NULL), + CHECK ( + (sequence = 1) = (previous_hash = '0000000000000000000000000000000000000000000000000000000000000000') + ) +); +CREATE INDEX audit_events_project ON audit_events (project_id, sequence); +CREATE INDEX audit_events_session ON audit_events (session_id, sequence); +CREATE INDEX audit_events_principal ON audit_events (principal_id, sequence); + +CREATE FUNCTION audit_events_extend_chain() RETURNS trigger LANGUAGE plpgsql AS $$ +DECLARE + last_sequence BIGINT; + last_hash TEXT; +BEGIN + SELECT sequence, event_hash INTO last_sequence, last_hash + FROM audit_events + ORDER BY sequence DESC + LIMIT 1; + IF NEW.sequence <> COALESCE(last_sequence, 0) + 1 + OR NEW.previous_hash <> COALESCE(last_hash, '0000000000000000000000000000000000000000000000000000000000000000') THEN + RAISE EXCEPTION 'audit_events must extend the hash chain' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER audit_events_extend_chain + BEFORE INSERT ON audit_events + FOR EACH ROW EXECUTE FUNCTION audit_events_extend_chain(); + +CREATE FUNCTION audit_events_reject_change() RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'audit_events is append-only' + USING ERRCODE = 'insufficient_privilege'; +END; +$$; + +CREATE TRIGGER audit_events_reject_update_delete + BEFORE UPDATE OR DELETE ON audit_events + FOR EACH ROW EXECUTE FUNCTION audit_events_reject_change(); + +CREATE TRIGGER audit_events_reject_truncate + BEFORE TRUNCATE ON audit_events + FOR EACH STATEMENT EXECUTE FUNCTION audit_events_reject_change(); diff --git a/migrations/sqlite/0001_init.sql b/migrations/sqlite/0001_init.sql new file mode 100644 index 0000000..dad3d56 --- /dev/null +++ b/migrations/sqlite/0001_init.sql @@ -0,0 +1,314 @@ +-- SendBox fleet schema, version 1 (SQLite, for local development and tests). +-- +-- Keep equivalent to migrations/postgres/0001_init.sql: same tables, columns, +-- and constraints. SQLite has no regular expressions by default, so grammar +-- checks use GLOB character classes; tables are STRICT so column types are +-- enforced. The service connects with foreign keys enabled. No table stores +-- provider credentials, bearer tokens, authorization headers, request +-- bodies, or any other secret-bearing payload. + +-- Authenticated callers: people (`user`) and SendBox hosts (`worker`). +CREATE TABLE principals ( + id TEXT PRIMARY KEY CHECK ( + length(id) <= 160 + AND instr(id, ':') BETWEEN 2 AND 33 + AND length(id) > instr(id, ':') + AND substr(id, 1, instr(id, ':') - 1) NOT GLOB '*[^a-z-]*' + AND substr(id, instr(id, ':') + 1) NOT GLOB '*[^A-Za-z0-9._@+:-]*' + -- Local OS accounts belong to single-host increment 1 and are never + -- fleet principals. + AND id NOT GLOB 'local-user:*' + ), + kind TEXT NOT NULL CHECK (kind IN ('user', 'worker')), + display_name TEXT CHECK (display_name IS NULL OR length(display_name) BETWEEN 1 AND 200), + created_at_unix INTEGER NOT NULL CHECK (created_at_unix >= 0), + disabled_at_unix INTEGER CHECK (disabled_at_unix IS NULL OR disabled_at_unix >= created_at_unix) +) STRICT; + +CREATE TABLE projects ( + id TEXT PRIMARY KEY CHECK ( + length(id) <= 160 + AND ( + ( + id GLOB 'github:[a-z0-9_-]*/[a-z0-9_-]*' + AND substr(id, 8) NOT GLOB '*[^a-z0-9._/-]*' + AND length(id) - length(replace(id, '/', '')) = 1 + AND instr(id, '/') - 8 BETWEEN 1 AND 100 + AND length(id) - instr(id, '/') BETWEEN 1 AND 100 + ) + OR ( + id GLOB 'path-sha256:*' + AND length(id) = 76 + AND substr(id, 13) NOT GLOB '*[^0-9a-f]*' + ) + ) + ), + display_name TEXT CHECK (display_name IS NULL OR length(display_name) BETWEEN 1 AND 200), + created_at_unix INTEGER NOT NULL CHECK (created_at_unix >= 0), + archived_at_unix INTEGER CHECK (archived_at_unix IS NULL OR archived_at_unix >= created_at_unix) +) STRICT; + +-- Project-scoped roles: one role per principal per project. +CREATE TABLE role_bindings ( + project_id TEXT NOT NULL REFERENCES projects (id), + principal_id TEXT NOT NULL REFERENCES principals (id), + role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'member', 'viewer')), + granted_by TEXT NOT NULL REFERENCES principals (id), + granted_at_unix INTEGER NOT NULL CHECK (granted_at_unix >= 0), + PRIMARY KEY (project_id, principal_id) +) STRICT; +CREATE INDEX role_bindings_principal ON role_bindings (principal_id); + +-- Operator-signed profile revisions. `signed_bytes` are the exact bytes the +-- signatures cover and `sha256` is their digest; rows are never edited, a +-- change is a new revision. +CREATE TABLE profiles ( + id TEXT NOT NULL CHECK ( + length(id) BETWEEN 1 AND 64 AND id GLOB '[a-z0-9]*' AND id NOT GLOB '*[^a-z0-9._-]*' + ), + revision INTEGER NOT NULL CHECK (revision >= 1), + sha256 TEXT NOT NULL UNIQUE CHECK (length(sha256) = 64 AND sha256 NOT GLOB '*[^0-9a-f]*'), + signed_bytes BLOB NOT NULL CHECK (length(signed_bytes) BETWEEN 1 AND 262144), + signatures TEXT NOT NULL CHECK ( + CASE WHEN json_valid(signatures) + THEN json_type(signatures) = 'array' AND json_array_length(signatures) BETWEEN 1 AND 16 + ELSE 0 + END + ), + not_before_unix INTEGER NOT NULL CHECK (not_before_unix >= 0), + expires_at_unix INTEGER NOT NULL, + published_by TEXT NOT NULL REFERENCES principals (id), + published_at_unix INTEGER NOT NULL CHECK (published_at_unix >= 0), + PRIMARY KEY (id, revision), + UNIQUE (id, revision, sha256), + -- At most 400 days of validity, matching the contract. + CHECK (expires_at_unix > not_before_unix AND expires_at_unix - not_before_unix <= 34560000) +) STRICT; + +-- Revisions below the minimum are stale: sessions, grants, and exceptions +-- bound to them are denied. +CREATE TABLE profile_minimum_revisions ( + profile_id TEXT PRIMARY KEY, + minimum_revision INTEGER NOT NULL CHECK (minimum_revision >= 1), + reason TEXT NOT NULL CHECK (length(trim(reason)) BETWEEN 1 AND 1000), + set_by TEXT NOT NULL REFERENCES principals (id), + set_at_unix INTEGER NOT NULL CHECK (set_at_unix >= 0), + FOREIGN KEY (profile_id, minimum_revision) REFERENCES profiles (id, revision) +) STRICT; + +-- Admitted sessions and the exact binding they were admitted with. +CREATE TABLE sessions ( + id TEXT PRIMARY KEY CHECK (length(id) = 32 AND id NOT GLOB '*[^0-9a-f]*'), + principal_id TEXT NOT NULL REFERENCES principals (id), + project_id TEXT NOT NULL REFERENCES projects (id), + authority_id TEXT NOT NULL CHECK ( + length(authority_id) BETWEEN 1 AND 128 AND authority_id NOT GLOB '*[^!-~]*' + ), + profile_id TEXT NOT NULL, + profile_revision INTEGER NOT NULL, + profile_sha256 TEXT NOT NULL, + effective_policy_sha256 TEXT NOT NULL CHECK ( + length(effective_policy_sha256) = 64 AND effective_policy_sha256 NOT GLOB '*[^0-9a-f]*' + ), + -- RFC 8785 canonical JSON of the GovernanceBinding, kept byte-exact; + -- binding_sha256 is its digest. + binding TEXT NOT NULL CHECK ( + CASE WHEN json_valid(binding) + THEN json_type(binding) = 'object' AND length(CAST(binding AS BLOB)) <= 16384 + ELSE 0 + END + ), + binding_sha256 TEXT NOT NULL CHECK ( + length(binding_sha256) = 64 AND binding_sha256 NOT GLOB '*[^0-9a-f]*' + ), + status TEXT NOT NULL CHECK (status IN ('admitted', 'completed', 'cancelled', 'failed')), + -- The worker (SendBox host) that requested admission. + admitted_by TEXT NOT NULL REFERENCES principals (id), + admitted_at_unix INTEGER NOT NULL CHECK (admitted_at_unix >= 0), + ended_at_unix INTEGER, + FOREIGN KEY (profile_id, profile_revision, profile_sha256) + REFERENCES profiles (id, revision, sha256), + UNIQUE (id, principal_id, project_id, binding_sha256, profile_id, profile_revision, profile_sha256), + CHECK ((status = 'admitted') = (ended_at_unix IS NULL)), + CHECK (ended_at_unix IS NULL OR ended_at_unix >= admitted_at_unix) +) STRICT; +CREATE INDEX sessions_project ON sessions (project_id); +CREATE INDEX sessions_principal ON sessions (principal_id); + +-- Expiring, revocable authorizations for one session to use one brokered +-- service. Deliberately no column can hold credential material: the provider +-- credential stays in the SendBox host broker. +CREATE TABLE credential_grants ( + id TEXT PRIMARY KEY CHECK (length(id) = 32 AND id NOT GLOB '*[^0-9a-f]*'), + session_id TEXT NOT NULL, + principal_id TEXT NOT NULL, + project_id TEXT NOT NULL, + binding_sha256 TEXT NOT NULL, + profile_id TEXT NOT NULL, + profile_revision INTEGER NOT NULL, + profile_sha256 TEXT NOT NULL, + service_id TEXT NOT NULL CHECK ( + length(service_id) BETWEEN 1 AND 32 + AND service_id GLOB '[a-z]*' + AND service_id NOT GLOB '*[^a-z0-9-]*' + ), + methods TEXT NOT NULL CHECK ( + CASE WHEN json_valid(methods) + THEN json_type(methods) = 'array' AND json_array_length(methods) BETWEEN 1 AND 7 + ELSE 0 + END + ), + path_prefixes TEXT NOT NULL CHECK ( + CASE WHEN json_valid(path_prefixes) + THEN json_type(path_prefixes) = 'array' AND json_array_length(path_prefixes) BETWEEN 1 AND 256 + ELSE 0 + END + ), + issued_at_unix INTEGER NOT NULL CHECK (issued_at_unix >= 0), + lease_expires_at_unix INTEGER NOT NULL, + max_expires_at_unix INTEGER NOT NULL, + generation INTEGER NOT NULL CHECK (generation >= 1), + -- A grant carries exactly its session's identity, binding, and profile. + FOREIGN KEY (session_id, principal_id, project_id, binding_sha256, profile_id, profile_revision, profile_sha256) + REFERENCES sessions (id, principal_id, project_id, binding_sha256, profile_id, profile_revision, profile_sha256), + CHECK (issued_at_unix < lease_expires_at_unix AND lease_expires_at_unix <= max_expires_at_unix), + -- At most 7 days from issue to hard expiry, matching the contract. + CHECK (max_expires_at_unix - issued_at_unix <= 604800) +) STRICT; +CREATE INDEX credential_grants_session ON credential_grants (session_id); + +-- A revoked grant denies new requests immediately. Already-open upstream +-- streams may finish until `grace_expires_at_unix` (at most 60 seconds); +-- revocation does not undo completed external effects. +CREATE TABLE revocations ( + grant_id TEXT PRIMARY KEY REFERENCES credential_grants (id), + reason TEXT NOT NULL CHECK ( + reason IN ('session_completed', 'session_cancelled', 'session_failed', 'operator_revoked', 'policy_changed') + ), + -- NULL when the service revoked the grant itself, for example at session end. + revoked_by TEXT REFERENCES principals (id), + revoked_at_unix INTEGER NOT NULL CHECK (revoked_at_unix >= 0), + grace_expires_at_unix INTEGER NOT NULL, + generation INTEGER NOT NULL CHECK (generation >= 2), + CHECK (grace_expires_at_unix >= revoked_at_unix AND grace_expires_at_unix - revoked_at_unix <= 60), + CHECK (reason <> 'operator_revoked' OR revoked_by IS NOT NULL) +) STRICT; + +-- Bounded, expiring exceptions. Each is bound to the exact profile revision it +-- was reviewed against, so a stale approval cannot authorize changed work, and +-- the service rejects any scope outside that revision's ceiling. +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 member of 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 ('network_domain', 'command', 'mcp_tool', 'credential_service_path') + ), + scope_value TEXT NOT NULL CHECK ( + length(scope_value) BETWEEN 1 AND 256 AND scope_value NOT GLOB '*[^!-~]*' + ), + 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); + +-- Append-only, hash-chained audit log. Each event_hash is computed by the +-- service over previous_hash and the event's canonical JSON. The first +-- trigger enforces contiguous sequences and chain linkage; the others forbid +-- UPDATE and DELETE. +CREATE TABLE audit_events ( + sequence INTEGER PRIMARY KEY CHECK (sequence >= 1), + occurred_at_unix INTEGER NOT NULL CHECK (occurred_at_unix >= 0), + recorded_at_unix INTEGER NOT NULL CHECK (recorded_at_unix >= 0), + event_type TEXT NOT NULL CHECK ( + length(event_type) BETWEEN 1 AND 64 + AND event_type GLOB '[a-z]*' + AND event_type NOT GLOB '*[^a-z0-9_.]*' + ), + -- The authenticated caller that caused the event. + actor_id TEXT CHECK (actor_id IS NULL OR length(actor_id) <= 160), + -- Identifiers are copied, not referenced, so evidence outlives its subjects. + principal_id TEXT CHECK (principal_id IS NULL OR length(principal_id) <= 160), + project_id TEXT CHECK (project_id IS NULL OR length(project_id) <= 160), + session_id TEXT CHECK ( + session_id IS NULL OR (length(session_id) = 32 AND session_id NOT GLOB '*[^0-9a-f]*') + ), + grant_id TEXT CHECK ( + grant_id IS NULL OR (length(grant_id) = 32 AND grant_id NOT GLOB '*[^0-9a-f]*') + ), + profile_id TEXT CHECK (profile_id IS NULL OR length(profile_id) <= 64), + profile_revision INTEGER CHECK (profile_revision IS NULL OR profile_revision >= 1), + decision TEXT CHECK (decision IS NULL OR decision IN ('allow', 'deny')), + deny_reason TEXT CHECK ( + deny_reason IS NULL OR deny_reason IN ( + 'unknown_grant', 'revoked', 'expired', 'lease_expired', 'principal_mismatch', + 'project_mismatch', 'session_mismatch', 'binding_mismatch', 'stale_policy', + 'service_not_granted', 'method_not_granted', 'path_not_granted', 'invalid_path', + 'authority_unavailable' + ) + ), + outcome TEXT CHECK (outcome IS NULL OR outcome IN ('succeeded', 'failed', 'unknown')), + -- Method, host, and path prefix only: never a query string or body. + target_redacted TEXT CHECK ( + target_redacted IS NULL OR (length(target_redacted) <= 512 AND instr(target_redacted, '?') = 0) + ), + previous_hash TEXT NOT NULL CHECK ( + length(previous_hash) = 64 AND previous_hash NOT GLOB '*[^0-9a-f]*' + ), + event_hash TEXT NOT NULL UNIQUE CHECK ( + length(event_hash) = 64 AND event_hash NOT GLOB '*[^0-9a-f]*' + ), + CHECK (deny_reason IS NULL OR decision = 'deny'), + CHECK (decision IS NOT 'deny' OR deny_reason IS NOT NULL), + CHECK ( + (sequence = 1) = (previous_hash = '0000000000000000000000000000000000000000000000000000000000000000') + ) +) STRICT; +CREATE INDEX audit_events_project ON audit_events (project_id, sequence); +CREATE INDEX audit_events_session ON audit_events (session_id, sequence); +CREATE INDEX audit_events_principal ON audit_events (principal_id, sequence); + +CREATE TRIGGER audit_events_extend_chain +BEFORE INSERT ON audit_events +WHEN NEW.sequence IS NOT COALESCE((SELECT max(sequence) FROM audit_events), 0) + 1 + OR NEW.previous_hash IS NOT COALESCE( + (SELECT event_hash FROM audit_events ORDER BY sequence DESC LIMIT 1), + '0000000000000000000000000000000000000000000000000000000000000000' + ) +BEGIN + SELECT RAISE(ABORT, 'audit_events must extend the hash chain'); +END; + +CREATE TRIGGER audit_events_reject_update +BEFORE UPDATE ON audit_events +BEGIN + SELECT RAISE(ABORT, 'audit_events is append-only'); +END; + +CREATE TRIGGER audit_events_reject_delete +BEFORE DELETE ON audit_events +BEGIN + SELECT RAISE(ABORT, 'audit_events is append-only'); +END; From dadbea858aa0fb04b0e20547c92e53097f45a82d Mon Sep 17 00:00:00 2001 From: mbianchidev Date: Sun, 15 Nov 2026 13:40:22 +0100 Subject: [PATCH 2/6] Add fleet-server scaffold with authenticated v1 stubs Actix Web service binary sendbox-fleet with environment configuration, JSON logging to stdout and a daily-rotated log file with 30-day retention, health and readiness probes, and versioned /v1 routes. Every /v1 route requires a bearer token before routing, validates bodies against the pinned sendbox-governance contract, and returns an RFC 9457 501 problem naming the increment-2 capability. --- Cargo.lock | 2548 +++++++++++++++++ Cargo.toml | 32 + crates/fleet-server/Cargo.toml | 34 + crates/fleet-server/build.rs | 4 + crates/fleet-server/src/auth.rs | 204 ++ crates/fleet-server/src/config.rs | 273 ++ crates/fleet-server/src/db.rs | 139 + crates/fleet-server/src/lib.rs | 18 + crates/fleet-server/src/logging.rs | 165 ++ crates/fleet-server/src/logging/retention.rs | 177 ++ crates/fleet-server/src/main.rs | 33 + crates/fleet-server/src/problem.rs | 131 + crates/fleet-server/src/routes/health.rs | 41 + crates/fleet-server/src/routes/mod.rs | 64 + crates/fleet-server/src/routes/v1/audit.rs | 90 + .../fleet-server/src/routes/v1/authorize.rs | 24 + .../fleet-server/src/routes/v1/exceptions.rs | 88 + crates/fleet-server/src/routes/v1/grants.rs | 62 + crates/fleet-server/src/routes/v1/mod.rs | 99 + crates/fleet-server/src/routes/v1/profiles.rs | 125 + crates/fleet-server/src/routes/v1/projects.rs | 71 + crates/fleet-server/src/routes/v1/sessions.rs | 40 + crates/fleet-server/src/server.rs | 123 + crates/fleet-server/tests/http.rs | 604 ++++ crates/fleet-server/tests/migrations.rs | 264 ++ rust-toolchain.toml | 4 + 26 files changed, 5457 insertions(+) create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 crates/fleet-server/Cargo.toml create mode 100644 crates/fleet-server/build.rs create mode 100644 crates/fleet-server/src/auth.rs create mode 100644 crates/fleet-server/src/config.rs create mode 100644 crates/fleet-server/src/db.rs create mode 100644 crates/fleet-server/src/lib.rs create mode 100644 crates/fleet-server/src/logging.rs create mode 100644 crates/fleet-server/src/logging/retention.rs create mode 100644 crates/fleet-server/src/main.rs create mode 100644 crates/fleet-server/src/problem.rs create mode 100644 crates/fleet-server/src/routes/health.rs create mode 100644 crates/fleet-server/src/routes/mod.rs create mode 100644 crates/fleet-server/src/routes/v1/audit.rs create mode 100644 crates/fleet-server/src/routes/v1/authorize.rs create mode 100644 crates/fleet-server/src/routes/v1/exceptions.rs create mode 100644 crates/fleet-server/src/routes/v1/grants.rs create mode 100644 crates/fleet-server/src/routes/v1/mod.rs create mode 100644 crates/fleet-server/src/routes/v1/profiles.rs create mode 100644 crates/fleet-server/src/routes/v1/projects.rs create mode 100644 crates/fleet-server/src/routes/v1/sessions.rs create mode 100644 crates/fleet-server/src/server.rs create mode 100644 crates/fleet-server/tests/http.rs create mode 100644 crates/fleet-server/tests/migrations.rs create mode 100644 rust-toolchain.toml diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..9ae60c0 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2548 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "actix-codec" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c13df95297bcf9014dc89162b0cc69431e192e34e3b419612fc124cfcd45dbf" +dependencies = [ + "bitflags", + "bytes", + "futures-core", + "futures-sink", + "memchr", + "pin-project-lite", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "actix-http" +version = "3.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3422032be73eeb15bafdb64086386385875b653eb418a80241d1f98473e86ea6" +dependencies = [ + "actix-codec", + "actix-service", + "actix-utils", + "bitflags", + "bytes", + "bytestring", + "derive_more", + "encoding_rs", + "foldhash 0.2.0", + "futures-core", + "http", + "httparse", + "httpdate", + "itoa", + "language-tags", + "mime", + "percent-encoding", + "pin-project-lite", + "smallvec", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "actix-macros" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "367f814ad4afbac74f07df5001214da65f65e185c90ef56c4dd8df23f8695b9b" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "actix-router" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "125f4331c1f10734a96c038bc7503dff22d8ccd5f82b214e6696728561ef1149" +dependencies = [ + "bytestring", + "cfg-if", + "http", + "regex-lite", + "serde", + "tracing", +] + +[[package]] +name = "actix-rt" +version = "2.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5f794807f82bbd36430c12cd600c73bbab0f52fdde4f0ed49978df113f4807f" +dependencies = [ + "futures-core", + "tokio", +] + +[[package]] +name = "actix-server" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e296908c4d6f3a191e6b9873dbdfec8023350a89129d2b470f61d17233931ee" +dependencies = [ + "actix-rt", + "actix-service", + "futures-core", + "futures-util", + "mio", + "socket2", + "tokio", + "tracing", +] + +[[package]] +name = "actix-service" +version = "2.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e46f36bf0e5af44bdc4bdb36fbbd421aa98c79a9bce724e1edeb3894e10dc7f" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "actix-utils" +version = "3.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0128396dd7313f697ad05b21b1a7be7d4cbb81888704f55996e4a27db196bb4d" +dependencies = [ + "local-waker", + "pin-project-lite", +] + +[[package]] +name = "actix-web" +version = "4.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "acd6966acfcc7b66b37bdeea7d11665d5accac89333767e1784d2cecd33984e7" +dependencies = [ + "actix-codec", + "actix-http", + "actix-macros", + "actix-router", + "actix-rt", + "actix-server", + "actix-service", + "actix-utils", + "actix-web-codegen", + "bytes", + "bytestring", + "cfg-if", + "derive_more", + "encoding_rs", + "foldhash 0.2.0", + "futures-core", + "futures-util", + "impl-more", + "itoa", + "language-tags", + "log", + "mime", + "once_cell", + "pin-project-lite", + "regex-lite", + "serde", + "serde_json", + "serde_urlencoded", + "smallvec", + "socket2", + "time", + "tokio", + "tracing", + "url", +] + +[[package]] +name = "actix-web-codegen" +version = "4.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c9f4c52b954a73c76757a3952d3437fca00a2fbcb49704f8a6ea9f767e73f0" +dependencies = [ + "actix-router", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "atoi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +dependencies = [ + "num-traits", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "bytestring" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca79160522b4aed4a69bab673bee78d3884d44240c78c96cb04b7557d532b4dc" +dependencies = [ + "bytes", +] + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid 0.9.6", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", + "unicode-xid", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "const-oid 0.9.6", + "crypto-common 0.1.7", + "subtle", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.3", + "crypto-common 0.2.2", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" +dependencies = [ + "serde", +] + +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "etcetera" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943" +dependencies = [ + "cfg-if", + "home", + "windows-sys 0.48.0", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fleet-server" +version = "0.1.0" +dependencies = [ + "actix-http", + "actix-web", + "sendbox-governance", + "serde", + "serde_json", + "sqlx", + "tempfile", + "thiserror", + "time", + "tokio", + "tracing", + "tracing-appender", + "tracing-subscriber", +] + +[[package]] +name = "flume" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095" +dependencies = [ + "futures-core", + "futures-sink", + "spin", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-intrusive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hashlink" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "http" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "impl-more" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d3a73c82a0b0747dba739b380c046a140b5ae747234bf701df3460282da7193" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "language-tags" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4345964bb142484797b161f473a503a434de77149dd8c7427788c6e13379388" + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +dependencies = [ + "spin", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "bitflags", + "libc", + "plain", + "redox_syscall 0.9.5", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "libyaml-rs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e126dda6f34391ab7b444f9922055facc83c07a910da3eb16f1e4d9c45dc777" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "local-waker" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88bab6b3971cb9cda8a370672a73e59a442b87552f005fb60ec07b67fa658f13" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest 0.10.7", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint-dig" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e661dda6640fad38e827a6d4a310ff4763082116fe217f279885c97f511bb0b7" +dependencies = [ + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "redox_syscall" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-lite" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rsa" +version = "0.9.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" +dependencies = [ + "const-oid 0.9.6", + "digest 0.10.7", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core", + "signature", + "spki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "ryu-js" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04d056b875a9d2e6cb9a61d127afee9ac5999b9f87bcb32079d1318e505be714" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "sendbox-core" +version = "0.2.7" +source = "git+https://github.com/mbianchidev/sendbox?rev=bd7498ab24c3c9cfd98f80349bee31fed667539b#bd7498ab24c3c9cfd98f80349bee31fed667539b" +dependencies = [ + "serde", +] + +[[package]] +name = "sendbox-governance" +version = "0.2.7" +source = "git+https://github.com/mbianchidev/sendbox?rev=bd7498ab24c3c9cfd98f80349bee31fed667539b#bd7498ab24c3c9cfd98f80349bee31fed667539b" +dependencies = [ + "sendbox-core", + "serde", + "serde_json", + "serde_json_canonicalizer", + "sha2 0.11.1", + "thiserror", + "yaml_serde", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_json_canonicalizer" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe52319a927259afbfa5180c5157cd8167edfd3e8c254f9558c7fef44c5649f2" +dependencies = [ + "ryu-js", + "serde", + "serde_json", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest 0.10.7", + "rand_core", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" +dependencies = [ + "serde", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "sqlx" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc" +dependencies = [ + "sqlx-core", + "sqlx-macros", + "sqlx-mysql", + "sqlx-postgres", + "sqlx-sqlite", +] + +[[package]] +name = "sqlx-core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" +dependencies = [ + "base64", + "bytes", + "crc", + "crossbeam-queue", + "either", + "event-listener", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashbrown 0.15.5", + "hashlink", + "indexmap", + "log", + "memchr", + "once_cell", + "percent-encoding", + "rustls", + "serde", + "serde_json", + "sha2 0.10.9", + "smallvec", + "thiserror", + "tokio", + "tokio-stream", + "tracing", + "url", + "webpki-roots 0.26.11", +] + +[[package]] +name = "sqlx-macros" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2d452988ccaacfbf5e0bdbc348fb91d7c8af5bee192173ac3636b5fb6e6715d" +dependencies = [ + "proc-macro2", + "quote", + "sqlx-core", + "sqlx-macros-core", + "syn 2.0.119", +] + +[[package]] +name = "sqlx-macros-core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19a9c1841124ac5a61741f96e1d9e2ec77424bf323962dd894bdb93f37d5219b" +dependencies = [ + "dotenvy", + "either", + "heck", + "hex", + "once_cell", + "proc-macro2", + "quote", + "serde", + "serde_json", + "sha2 0.10.9", + "sqlx-core", + "sqlx-postgres", + "sqlx-sqlite", + "syn 2.0.119", + "tokio", + "url", +] + +[[package]] +name = "sqlx-mysql" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526" +dependencies = [ + "atoi", + "base64", + "bitflags", + "byteorder", + "bytes", + "crc", + "digest 0.10.7", + "dotenvy", + "either", + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "generic-array", + "hex", + "hkdf", + "hmac", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "percent-encoding", + "rand", + "rsa", + "sha1", + "sha2 0.10.9", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "whoami", +] + +[[package]] +name = "sqlx-postgres" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46" +dependencies = [ + "atoi", + "base64", + "bitflags", + "byteorder", + "crc", + "dotenvy", + "etcetera", + "futures-channel", + "futures-core", + "futures-util", + "hex", + "hkdf", + "hmac", + "home", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "rand", + "serde", + "serde_json", + "sha2 0.10.9", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "whoami", +] + +[[package]] +name = "sqlx-sqlite" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2d12fe70b2c1b4401038055f90f151b78208de1f9f89a7dbfd41587a10c3eea" +dependencies = [ + "atoi", + "flume", + "futures-channel", + "futures-core", + "futures-executor", + "futures-intrusive", + "futures-util", + "libsqlite3-sys", + "log", + "percent-encoding", + "serde", + "serde_urlencoded", + "sqlx-core", + "thiserror", + "tracing", + "url", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "symlink" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-appender" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c" +dependencies = [ + "crossbeam-channel", + "symlink", + "thiserror", + "time", + "tracing-subscriber", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-serde" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" +dependencies = [ + "serde", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "serde", + "serde_json", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", + "tracing-serde", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993ad287eb20e8ba755312801cfe1413e0f25d604075863acaddca10b04c1833" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.12", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "whoami" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d" +dependencies = [ + "libredox", + "wasite", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yaml_serde" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33b729a08a9a6be689bbad3e2bf8015926db54b6622cc89c3a5f7dc174b9e918" +dependencies = [ + "indexmap", + "itoa", + "libyaml-rs", + "ryu", + "serde", +] + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..0dc3745 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,32 @@ +[workspace] +members = ["crates/fleet-server"] +resolver = "3" + +[workspace.package] +version = "0.1.0" +edition = "2024" +rust-version = "1.93.1" +license = "Apache-2.0" +repository = "https://github.com/mbianchidev/sendbox-fleet" +publish = false + +[workspace.dependencies] +actix-http = { version = "3.21.0", default-features = false } +actix-web = { version = "4.19.0", default-features = false, features = ["macros"] } +sendbox-governance = { git = "https://github.com/mbianchidev/sendbox", rev = "bd7498ab24c3c9cfd98f80349bee31fed667539b" } +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"] } +tempfile = "3.27.0" +thiserror = "2.0.21" +time = "0.3.47" +tokio = { version = "1.54.1", features = ["rt", "time"] } +tracing = "0.1.44" +tracing-appender = "0.2.5" +tracing-subscriber = { version = "0.3.23", features = ["env-filter", "json"] } + +[workspace.lints.rust] +unsafe_code = "forbid" + +[workspace.lints.clippy] +all = "deny" diff --git a/crates/fleet-server/Cargo.toml b/crates/fleet-server/Cargo.toml new file mode 100644 index 0000000..bc7a69b --- /dev/null +++ b/crates/fleet-server/Cargo.toml @@ -0,0 +1,34 @@ +[package] +name = "fleet-server" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true +description = "SendBox shared governance service: management API, grant authority, and central audit (scaffold)." + +[[bin]] +name = "sendbox-fleet" +path = "src/main.rs" + +[dependencies] +actix-web.workspace = true +sendbox-governance.workspace = true +serde.workspace = true +serde_json.workspace = true +sqlx.workspace = true +thiserror.workspace = true +time.workspace = true +tokio.workspace = true +tracing.workspace = true +tracing-appender.workspace = true +tracing-subscriber.workspace = true + +[dev-dependencies] +actix-http.workspace = true +tempfile.workspace = true +time = { workspace = true, features = ["macros"] } + +[lints] +workspace = true diff --git a/crates/fleet-server/build.rs b/crates/fleet-server/build.rs new file mode 100644 index 0000000..e683823 --- /dev/null +++ b/crates/fleet-server/build.rs @@ -0,0 +1,4 @@ +// `sqlx::migrate!` embeds the SQL files at compile time; rebuild when they change. +fn main() { + println!("cargo:rerun-if-changed=../../migrations"); +} diff --git a/crates/fleet-server/src/auth.rs b/crates/fleet-server/src/auth.rs new file mode 100644 index 0000000..7f7b6f4 --- /dev/null +++ b/crates/fleet-server/src/auth.rs @@ -0,0 +1,204 @@ +//! Caller authentication for the management API. +//! +//! Authentication (who is calling) is separate from capability authorization +//! (what that caller may do). Every `/v1` request must carry +//! `Authorization: Bearer `; the configured [`Authenticator`] maps the +//! token to a [`Caller`]. Identity claims supplied any other way, such as +//! `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. + +use std::future::{Future, Ready, ready}; +use std::pin::Pin; +use std::sync::Arc; + +use actix_web::body::{EitherBody, MessageBody}; +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 thiserror::Error; + +use crate::problem::Problem; + +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, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)] +pub enum AuthError { + #[error("authentication provider not configured")] + NotConfigured, + #[error("bearer token was not accepted")] + InvalidToken, +} + +pub type AuthFuture<'a> = Pin> + Send + 'a>>; + +/// Verifies a bearer token and returns the caller it identifies. +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; + +impl Authenticator for UnconfiguredAuthenticator { + fn authenticate<'a>(&'a self, _bearer_token: &'a str) -> AuthFuture<'a> { + Box::pin(async { Err(AuthError::NotConfigured) }) + } +} + +/// Shared handle stored in application data. +pub type SharedAuthenticator = web::Data; + +#[must_use] +pub fn shared(authenticator: Arc) -> SharedAuthenticator { + web::Data::from(authenticator) +} + +/// Middleware for the `/v1` scope. It runs before routing to a handler, so an +/// unauthenticated request is rejected before its body is read or validated. +pub async fn require_bearer( + request: ServiceRequest, + next: Next, +) -> Result>, Error> { + match authenticate(&request).await { + Ok(caller) => { + request.extensions_mut().insert(caller); + next.call(request) + .await + .map(ServiceResponse::map_into_left_body) + } + Err(problem) => Ok(request + .into_response(problem.error_response()) + .map_into_right_body()), + } +} + +async fn authenticate(request: &ServiceRequest) -> Result { + let token = bearer_token(request.request())?; + let authenticator = request + .app_data::() + .cloned() + .ok_or_else(|| rejection(AuthError::NotConfigured))?; + authenticator.authenticate(&token).await.map_err(rejection) +} + +fn bearer_token(request: &HttpRequest) -> Result { + let mut values = request.headers().get_all(header::AUTHORIZATION); + let Some(value) = values.next() else { + return Err(Problem::unauthorized( + "authentication required: send `Authorization: Bearer `", + CHALLENGE, + )); + }; + let malformed = || { + Problem::unauthorized( + "the Authorization header must contain exactly one `Bearer ` credential", + CHALLENGE_INVALID_REQUEST, + ) + }; + if values.next().is_some() { + return Err(malformed()); + } + let value = value.to_str().map_err(|_| malformed())?; + let (scheme, token) = value.split_once(' ').ok_or_else(malformed)?; + if !scheme.eq_ignore_ascii_case("bearer") || !valid_token(token) { + return Err(malformed()); + } + Ok(token.to_owned()) +} + +/// RFC 6750 `b64token`: `1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / "+" / "/" ) *"="`. +fn valid_token(token: &str) -> bool { + let body = token.trim_end_matches('='); + !body.is_empty() + && token.len() <= MAX_TOKEN_BYTES + && body + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"-._~+/".contains(&byte)) +} + +fn rejection(error: AuthError) -> Problem { + Problem::unauthorized(error.to_string(), CHALLENGE_INVALID_TOKEN) +} + +/// Extracts the caller authenticated by [`require_bearer`]. Rejects the +/// request when the middleware did not run, so a handler mounted outside the +/// authenticated scope cannot accidentally serve anonymous callers. +#[derive(Debug, Clone)] +pub struct Authenticated(pub Caller); + +impl FromRequest for Authenticated { + type Error = Problem; + type Future = Ready>; + + fn from_request(request: &HttpRequest, _payload: &mut Payload) -> Self::Future { + ready( + request + .extensions() + .get::() + .cloned() + .map(Self) + .ok_or_else(|| Problem::unauthorized("authentication required", CHALLENGE)), + ) + } +} + +#[cfg(test)] +mod tests { + use actix_web::test::TestRequest; + + use super::*; + + #[test] + fn bearer_token_grammar_is_enforced() { + let token = |value: &str| { + bearer_token( + &TestRequest::default() + .insert_header((header::AUTHORIZATION, value)) + .to_http_request(), + ) + }; + assert_eq!( + token("Bearer abc.DEF-123_~+/==").unwrap(), + "abc.DEF-123_~+/==" + ); + assert_eq!(token("bearer abc").unwrap(), "abc"); + for rejected in [ + "Basic dXNlcjpwYXNz", + "Bearer", + "Bearer ", + "Bearer two words", + "Bearer ===", + "Bearer a\"b", + ] { + assert!(token(rejected).is_err(), "{rejected:?} was accepted"); + } + assert!(token(&format!("Bearer {}", "a".repeat(MAX_TOKEN_BYTES + 1))).is_err()); + assert!(bearer_token(&TestRequest::default().to_http_request()).is_err()); + } +} diff --git a/crates/fleet-server/src/config.rs b/crates/fleet-server/src/config.rs new file mode 100644 index 0000000..2ddf155 --- /dev/null +++ b/crates/fleet-server/src/config.rs @@ -0,0 +1,273 @@ +//! Process configuration, read once from the environment and validated at startup. + +use std::ffi::OsString; +use std::fmt; +use std::net::SocketAddr; +use std::path::PathBuf; + +use thiserror::Error; +use tracing_subscriber::EnvFilter; + +pub const BIND_VAR: &str = "FLEET_BIND"; +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"; + +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; + +#[derive(Debug, Clone)] +pub struct Config { + pub bind: SocketAddr, + pub database_url: DatabaseUrl, + pub logging: LogConfig, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LogConfig { + /// Directory for `.log` files. Relative paths resolve against the process + /// working directory at startup. + pub dir: PathBuf, + /// `tracing_subscriber::EnvFilter` directives, for example `info` or + /// `fleet_server=debug,actix_web=info`. + pub filter: String, + pub retention_days: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum DatabaseKind { + Postgres, + Sqlite, +} + +impl DatabaseKind { + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Postgres => "postgres", + Self::Sqlite => "sqlite", + } + } +} + +/// A database connection URL. Its `Debug` and `Display` forms never include +/// the credentials embedded in the URL. +#[derive(Clone, PartialEq, Eq)] +pub struct DatabaseUrl { + kind: DatabaseKind, + url: String, +} + +impl DatabaseUrl { + pub fn parse(url: &str) -> Result { + let kind = if url.starts_with("postgres://") || url.starts_with("postgresql://") { + DatabaseKind::Postgres + } else if url.starts_with("sqlite:") { + DatabaseKind::Sqlite + } else { + return Err(ConfigError::Invalid { + name: DATABASE_URL_VAR, + reason: "must start with `postgres://`, `postgresql://`, or `sqlite:`".to_owned(), + }); + }; + Ok(Self { + kind, + url: url.to_owned(), + }) + } + + #[must_use] + pub const fn kind(&self) -> DatabaseKind { + self.kind + } + + /// The full URL, including credentials. Never log this value. + #[must_use] + pub fn expose(&self) -> &str { + &self.url + } + + #[must_use] + pub fn redacted(&self) -> String { + let Some((scheme, rest)) = self.url.split_once("://") else { + return self.url.clone(); + }; + let authority_end = rest.find(['/', '?']).unwrap_or(rest.len()); + match rest[..authority_end].rfind('@') { + Some(at) => format!("{scheme}://***@{}", &rest[at + 1..]), + None => self.url.clone(), + } + } +} + +impl fmt::Debug for DatabaseUrl { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_tuple("DatabaseUrl") + .field(&self.redacted()) + .finish() + } +} + +impl fmt::Display for DatabaseUrl { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(&self.redacted()) + } +} + +#[derive(Debug, Error, PartialEq, Eq)] +pub enum ConfigError { + #[error( + "{name} is required, for example `sqlite://sendbox-fleet.db?mode=rwc` for local development or `postgres://user:password@host/sendbox_fleet` for a shared deployment" + )] + Missing { name: &'static str }, + #[error("{name} is invalid: {reason}")] + Invalid { name: &'static str, reason: String }, +} + +impl Config { + pub fn from_env() -> Result { + Self::from_lookup(|name| std::env::var_os(name)) + } + + /// Builds a configuration from an arbitrary variable source so callers + /// and tests do not depend on the process environment. + pub fn from_lookup(lookup: impl Fn(&str) -> Option) -> Result { + let text = |name: &'static str| -> Result, ConfigError> { + lookup(name) + .map(|value| { + value.into_string().map_err(|_| ConfigError::Invalid { + name, + reason: "must be valid UTF-8".to_owned(), + }) + }) + .transpose() + }; + + let bind_text = text(BIND_VAR)?.unwrap_or_else(|| DEFAULT_BIND.to_owned()); + let bind = bind_text.parse().map_err(|_| ConfigError::Invalid { + name: BIND_VAR, + reason: format!("`{bind_text}` is not a socket address such as `127.0.0.1:8080`"), + })?; + + let database_url = text(DATABASE_URL_VAR)? + .filter(|value| !value.is_empty()) + .ok_or(ConfigError::Missing { + name: DATABASE_URL_VAR, + })?; + let database_url = DatabaseUrl::parse(&database_url)?; + + let dir = lookup(LOG_DIR_VAR).map_or_else(|| PathBuf::from(DEFAULT_LOG_DIR), PathBuf::from); + if dir.as_os_str().is_empty() { + return Err(ConfigError::Invalid { + name: LOG_DIR_VAR, + reason: "must not be empty".to_owned(), + }); + } + + let filter = text(LOG_LEVEL_VAR)?.unwrap_or_else(|| DEFAULT_LOG_LEVEL.to_owned()); + EnvFilter::try_new(&filter).map_err(|error| ConfigError::Invalid { + name: LOG_LEVEL_VAR, + reason: error.to_string(), + })?; + + let retention_days = match text(LOG_RETENTION_DAYS_VAR)? { + None => DEFAULT_LOG_RETENTION_DAYS, + Some(value) => value + .parse::() + .ok() + .filter(|days| (1..=MAX_LOG_RETENTION_DAYS).contains(days)) + .ok_or_else(|| ConfigError::Invalid { + name: LOG_RETENTION_DAYS_VAR, + reason: format!( + "must be a whole number of days in 1..={MAX_LOG_RETENTION_DAYS}" + ), + })?, + }; + + Ok(Self { + bind, + database_url, + logging: LogConfig { + dir, + filter, + retention_days, + }, + }) + } +} + +#[cfg(test)] +mod tests { + use std::collections::HashMap; + + use super::*; + + fn config(vars: &[(&str, &str)]) -> Result { + let vars: HashMap = vars + .iter() + .map(|(name, value)| ((*name).to_owned(), OsString::from(value))) + .collect(); + Config::from_lookup(|name| vars.get(name).cloned()) + } + + #[test] + fn defaults_apply_when_only_the_database_is_set() { + let config = config(&[(DATABASE_URL_VAR, "sqlite::memory:")]).unwrap(); + assert_eq!(config.bind, "127.0.0.1:8080".parse().unwrap()); + assert_eq!(config.database_url.kind(), DatabaseKind::Sqlite); + assert_eq!(config.logging.dir, PathBuf::from("./logs")); + assert_eq!(config.logging.retention_days, 30); + } + + #[test] + fn missing_or_unsupported_database_is_rejected() { + assert_eq!( + config(&[]).unwrap_err(), + ConfigError::Missing { + name: DATABASE_URL_VAR + } + ); + assert!(matches!( + config(&[(DATABASE_URL_VAR, "mysql://db/fleet")]), + Err(ConfigError::Invalid { + name: DATABASE_URL_VAR, + .. + }) + )); + } + + #[test] + fn invalid_values_name_the_variable() { + let base = (DATABASE_URL_VAR, "sqlite::memory:"); + for (name, value) in [ + (BIND_VAR, "localhost"), + (LOG_DIR_VAR, ""), + (LOG_LEVEL_VAR, "fleet_server=loud"), + (LOG_RETENTION_DAYS_VAR, "0"), + (LOG_RETENTION_DAYS_VAR, "thirty"), + ] { + match config(&[base, (name, value)]) { + Err(ConfigError::Invalid { name: reported, .. }) => assert_eq!(reported, name), + other => panic!("{name}={value:?} was accepted: {other:?}"), + } + } + } + + #[test] + fn database_credentials_are_redacted() { + let url = + DatabaseUrl::parse("postgres://fleet:hunter2@db:5432/fleet?sslmode=require").unwrap(); + assert_eq!( + url.redacted(), + "postgres://***@db:5432/fleet?sslmode=require" + ); + assert!(!format!("{url:?} {url}").contains("hunter2")); + let url = DatabaseUrl::parse("sqlite://data/fleet.db?mode=rwc").unwrap(); + assert_eq!(url.redacted(), "sqlite://data/fleet.db?mode=rwc"); + } +} diff --git a/crates/fleet-server/src/db.rs b/crates/fleet-server/src/db.rs new file mode 100644 index 0000000..839c758 --- /dev/null +++ b/crates/fleet-server/src/db.rs @@ -0,0 +1,139 @@ +//! Database connection, migrations, and readiness checks. +//! +//! PostgreSQL is the shared deployment target; SQLite serves local +//! development and tests. Each backend has its own migration set under +//! `migrations/` with the same tables and constraints. + +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 thiserror::Error; + +use crate::config::{DatabaseKind, DatabaseUrl}; + +static POSTGRES_MIGRATIONS: Migrator = sqlx::migrate!("../../migrations/postgres"); +static SQLITE_MIGRATIONS: Migrator = sqlx::migrate!("../../migrations/sqlite"); + +const MAX_CONNECTIONS: u32 = 16; +const ACQUIRE_TIMEOUT: Duration = Duration::from_secs(5); + +#[derive(Debug, Error)] +pub enum DbError { + #[error("invalid database URL {url}: {source}")] + Options { url: String, source: sqlx::Error }, + #[error("cannot connect to {url}: {source}")] + Connect { url: String, source: sqlx::Error }, + #[error("database migration failed: {0}")] + Migrate(#[from] MigrateError), + #[error("database query failed: {0}")] + Query(#[from] sqlx::Error), +} + +#[derive(Debug, Clone)] +pub enum Database { + Postgres(PgPool), + Sqlite(SqlitePool), +} + +impl Database { + /// Opens a bounded connection pool and establishes one connection + /// immediately, so a bad URL or unreachable server fails at startup. + pub async fn connect(url: &DatabaseUrl) -> Result { + let redacted = url.redacted(); + match url.kind() { + DatabaseKind::Postgres => { + let options = PgConnectOptions::from_str(url.expose()).map_err(|source| { + DbError::Options { + url: redacted.clone(), + source, + } + })?; + PgPoolOptions::new() + .max_connections(MAX_CONNECTIONS) + .acquire_timeout(ACQUIRE_TIMEOUT) + .connect_with(options) + .await + .map(Self::Postgres) + .map_err(|source| DbError::Connect { + url: redacted, + source, + }) + } + DatabaseKind::Sqlite => { + let in_memory = + url.expose().contains(":memory:") || url.expose().contains("mode=memory"); + let options = SqliteConnectOptions::from_str(url.expose()) + .map_err(|source| DbError::Options { + url: redacted.clone(), + source, + })? + .foreign_keys(true) + .journal_mode(if in_memory { + SqliteJournalMode::Memory + } else { + SqliteJournalMode::Wal + }); + // Every in-memory connection is a separate database, so the + // pool keeps exactly one connection alive for its lifetime. + let pool = if in_memory { + SqlitePoolOptions::new() + .max_connections(1) + .min_connections(1) + .idle_timeout(None) + .max_lifetime(None) + } else { + SqlitePoolOptions::new().max_connections(MAX_CONNECTIONS) + }; + pool.acquire_timeout(ACQUIRE_TIMEOUT) + .connect_with(options) + .await + .map(Self::Sqlite) + .map_err(|source| DbError::Connect { + url: redacted, + source, + }) + } + } + } + + #[must_use] + pub const fn kind(&self) -> DatabaseKind { + match self { + Self::Postgres(_) => DatabaseKind::Postgres, + Self::Sqlite(_) => DatabaseKind::Sqlite, + } + } + + /// Applies pending migrations for this backend. + pub async fn migrate(&self) -> Result<(), DbError> { + match self { + Self::Postgres(pool) => POSTGRES_MIGRATIONS.run(pool).await?, + Self::Sqlite(pool) => SQLITE_MIGRATIONS.run(pool).await?, + } + Ok(()) + } + + /// Round-trips a trivial query; used by the readiness probe. + pub async fn ping(&self) -> Result<(), DbError> { + match self { + Self::Postgres(pool) => { + sqlx::query("SELECT 1").execute(pool).await?; + } + Self::Sqlite(pool) => { + sqlx::query("SELECT 1").execute(pool).await?; + } + } + Ok(()) + } + + pub async fn close(&self) { + match self { + Self::Postgres(pool) => pool.close().await, + Self::Sqlite(pool) => pool.close().await, + } + } +} diff --git a/crates/fleet-server/src/lib.rs b/crates/fleet-server/src/lib.rs new file mode 100644 index 0000000..dfe4a4d --- /dev/null +++ b/crates/fleet-server/src/lib.rs @@ -0,0 +1,18 @@ +#![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. + +pub mod auth; +pub mod config; +pub mod db; +pub mod logging; +pub mod problem; +pub mod routes; +pub mod server; + +pub use sendbox_governance::CONTRACT_VERSION; diff --git a/crates/fleet-server/src/logging.rs b/crates/fleet-server/src/logging.rs new file mode 100644 index 0000000..09ee34c --- /dev/null +++ b/crates/fleet-server/src/logging.rs @@ -0,0 +1,165 @@ +//! Structured logging to stdout and a daily-rotated `.log` file. +//! +//! Both sinks receive the same JSON-lines events. The file sink rotates at +//! each UTC calendar day (`sendbox-fleet.YYYY-MM-DD.log`) and +//! [`retention`] removes inactive files once they are older than the +//! configured retention window. Request bodies, headers, and query strings are +//! never logged. + +pub mod retention; + +use std::io; +use std::path::{Component, Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Instant; + +use actix_web::Error; +use actix_web::body::MessageBody; +use actix_web::dev::{ServiceRequest, ServiceResponse}; +use actix_web::middleware::Next; +use thiserror::Error; +use tracing_appender::non_blocking::{NonBlockingBuilder, WorkerGuard}; +use tracing_appender::rolling::{RollingFileAppender, Rotation}; +use tracing_subscriber::layer::SubscriberExt; +use tracing_subscriber::util::SubscriberInitExt; +use tracing_subscriber::{EnvFilter, fmt}; + +use crate::config::LogConfig; + +pub const LOG_FILE_PREFIX: &str = "sendbox-fleet"; +pub const LOG_FILE_SUFFIX: &str = "log"; +/// Events queued for the file writer before producers wait for it to drain. +/// The writer is not lossy: a full queue applies backpressure instead of +/// silently dropping events. +const FILE_QUEUE_LINES: usize = 16_384; + +#[derive(Debug, Error)] +pub enum LoggingError { + #[error("cannot resolve log directory {path}: {source}")] + Resolve { path: PathBuf, source: io::Error }, + #[error("cannot create log directory {path}: {source}")] + CreateDir { path: PathBuf, source: io::Error }, + #[error("cannot open log file in {path}: {source}")] + Appender { + path: PathBuf, + source: tracing_appender::rolling::InitError, + }, + #[error("invalid log filter: {0}")] + Filter(String), + #[error("a global tracing subscriber is already installed: {0}")] + AlreadyInstalled(String), +} + +/// Keeps the file writer alive; dropping it flushes queued events. +#[must_use = "dropping the guard stops file logging"] +pub struct LoggingGuard { + pub dir: PathBuf, + _file: WorkerGuard, +} + +/// Installs the global subscriber. Call once, before serving requests. +pub fn init(config: &LogConfig) -> Result { + let dir = resolve_dir(&config.dir)?; + create_private_dir(&dir)?; + let appender = RollingFileAppender::builder() + .rotation(Rotation::DAILY) + .filename_prefix(LOG_FILE_PREFIX) + .filename_suffix(LOG_FILE_SUFFIX) + .build(&dir) + .map_err(|source| LoggingError::Appender { + path: dir.clone(), + source, + })?; + let (file_writer, guard) = NonBlockingBuilder::default() + .lossy(false) + .buffered_lines_limit(FILE_QUEUE_LINES) + .thread_name("fleet-log-writer") + .finish(appender); + let filter = EnvFilter::try_new(&config.filter) + .map_err(|error| LoggingError::Filter(error.to_string()))?; + + tracing_subscriber::registry() + .with(filter) + .with( + fmt::layer() + .json() + .with_current_span(false) + .with_writer(io::stdout), + ) + .with( + fmt::layer() + .json() + .with_current_span(false) + .with_ansi(false) + .with_writer(file_writer), + ) + .try_init() + .map_err(|error| LoggingError::AlreadyInstalled(error.to_string()))?; + + Ok(LoggingGuard { dir, _file: guard }) +} + +fn resolve_dir(dir: &Path) -> Result { + let absolute = if dir.is_absolute() { + dir.to_path_buf() + } else { + std::env::current_dir() + .map(|cwd| cwd.join(dir)) + .map_err(|source| LoggingError::Resolve { + path: dir.to_path_buf(), + source, + })? + }; + Ok(absolute + .components() + .filter(|component| !matches!(component, Component::CurDir)) + .collect()) +} + +fn create_private_dir(dir: &Path) -> Result<(), LoggingError> { + let mut builder = std::fs::DirBuilder::new(); + builder.recursive(true); + #[cfg(unix)] + std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700); + builder + .create(dir) + .map_err(|source| LoggingError::CreateDir { + path: dir.to_path_buf(), + source, + }) +} + +static REQUEST_SEQUENCE: AtomicU64 = AtomicU64::new(1); + +/// Logs one event per request with method, path (without query string), +/// status, and latency. Headers and bodies are never recorded. +pub async fn request_log( + request: ServiceRequest, + next: Next, +) -> Result, Error> { + let request_id = REQUEST_SEQUENCE.fetch_add(1, Ordering::Relaxed); + let method = request.method().clone(); + let path = request.path().to_owned(); + let started = Instant::now(); + let response = next.call(request).await; + let latency_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX); + match &response { + Ok(response) => tracing::info!( + request_id, + %method, + path, + status = response.status().as_u16(), + latency_ms, + "request completed" + ), + Err(error) => tracing::warn!( + request_id, + %method, + path, + status = error.as_response_error().status_code().as_u16(), + latency_ms, + "request failed" + ), + } + response +} diff --git a/crates/fleet-server/src/logging/retention.rs b/crates/fleet-server/src/logging/retention.rs new file mode 100644 index 0000000..95876f6 --- /dev/null +++ b/crates/fleet-server/src/logging/retention.rs @@ -0,0 +1,177 @@ +//! Deletes inactive log files older than the retention window. +//! +//! Only regular files named `sendbox-fleet.YYYY-MM-DD.log` directly inside the +//! log directory are candidates; symlinks, directories, and every other file +//! are left untouched. A file's age comes from the UTC date in its name, not +//! its modification time, so copying or touching a file does not extend its +//! retention. A file is deleted when its last possible record (the end of its +//! UTC day) is at or before `now - retention`; the current day's live file is +//! therefore never eligible. + +use std::io; +use std::ops::Range; +use std::path::{Path, PathBuf}; + +use time::{Date, Duration, Month, OffsetDateTime}; + +use super::{LOG_FILE_PREFIX, LOG_FILE_SUFFIX}; + +#[derive(Debug, Default)] +pub struct RetentionReport { + pub deleted: Vec, + pub failures: Vec<(PathBuf, io::Error)>, +} + +/// Applies retention once. Fails only when the directory cannot be listed; +/// individual deletion failures are collected and the remaining eligible files +/// are still processed. +pub fn enforce( + dir: &Path, + retention_days: u32, + now: OffsetDateTime, +) -> io::Result { + let cutoff = now - Duration::days(i64::from(retention_days)); + let mut report = RetentionReport::default(); + for entry in std::fs::read_dir(dir)? { + let entry = match entry { + Ok(entry) => entry, + Err(error) => { + report.failures.push((dir.to_path_buf(), error)); + continue; + } + }; + let Some(day) = entry.file_name().to_str().and_then(log_file_day) else { + continue; + }; + let Some(end_of_day) = day.next_day().map(|next| next.midnight().assume_utc()) else { + continue; + }; + if end_of_day > cutoff { + continue; + } + let path = entry.path(); + match std::fs::symlink_metadata(&path) { + Ok(metadata) if metadata.file_type().is_file() => match std::fs::remove_file(&path) { + Ok(()) => report.deleted.push(path), + Err(error) => report.failures.push((path, error)), + }, + Ok(_) => {} + Err(error) => report.failures.push((path, error)), + } + } + Ok(report) +} + +/// The UTC day encoded in a file name produced by the daily appender. +fn log_file_day(name: &str) -> Option { + let date = name + .strip_prefix(LOG_FILE_PREFIX)? + .strip_prefix('.')? + .strip_suffix(LOG_FILE_SUFFIX)? + .strip_suffix('.')?; + let bytes = date.as_bytes(); + if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' { + return None; + } + let number = |range: Range| -> Option { + let digits = date.get(range)?; + if digits.bytes().all(|byte| byte.is_ascii_digit()) { + digits.parse().ok() + } else { + None + } + }; + let year = i32::from(number(0..4)?); + let month = Month::try_from(u8::try_from(number(5..7)?).ok()?).ok()?; + let day = u8::try_from(number(8..10)?).ok()?; + Date::from_calendar_date(year, month, day).ok() +} + +#[cfg(test)] +mod tests { + use std::fs; + + use time::macros::datetime; + + use super::*; + + fn touch(dir: &Path, name: &str) { + fs::write(dir.join(name), b"{\"message\":\"synthetic\"}\n").unwrap(); + } + + fn deleted_names(report: &RetentionReport) -> Vec { + let mut names: Vec = report + .deleted + .iter() + .map(|path| path.file_name().unwrap().to_string_lossy().into_owned()) + .collect(); + names.sort(); + names + } + + #[test] + fn deletes_only_files_whose_day_ended_by_the_cutoff() { + let dir = tempfile::tempdir().unwrap(); + for name in [ + "sendbox-fleet.2026-09-01.log", + "sendbox-fleet.2026-10-15.log", + "sendbox-fleet.2026-10-16.log", + "sendbox-fleet.2026-11-15.log", + ] { + touch(dir.path(), name); + } + let report = enforce(dir.path(), 30, datetime!(2026-11-15 00:00 UTC)).unwrap(); + assert_eq!( + deleted_names(&report), + [ + "sendbox-fleet.2026-09-01.log", + "sendbox-fleet.2026-10-15.log" + ] + ); + assert!(report.failures.is_empty()); + + let report = enforce(dir.path(), 30, datetime!(2026-11-15 23:59:59 UTC)).unwrap(); + assert!(report.deleted.is_empty()); + + let report = enforce(dir.path(), 30, datetime!(2026-11-16 00:00 UTC)).unwrap(); + assert_eq!(deleted_names(&report), ["sendbox-fleet.2026-10-16.log"]); + assert!(dir.path().join("sendbox-fleet.2026-11-15.log").exists()); + } + + #[test] + fn leaves_unrecognized_entries_and_symlink_targets_alone() { + let dir = tempfile::tempdir().unwrap(); + let outside = tempfile::tempdir().unwrap(); + touch(outside.path(), "sendbox-fleet.2020-01-01.log"); + let target = outside.path().join("sendbox-fleet.2020-01-01.log"); + let keep = [ + "other-app.2020-01-01.log", + "sendbox-fleet.2020-01-01.txt", + "sendbox-fleet.2020-13-01.log", + "sendbox-fleet.2020-1-01.log", + "sendbox-fleet.log", + ]; + for name in keep { + touch(dir.path(), name); + } + fs::create_dir(dir.path().join("sendbox-fleet.2020-01-02.log")).unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink(&target, dir.path().join("sendbox-fleet.2020-01-03.log")) + .unwrap(); + + let report = enforce(dir.path(), 1, datetime!(2026-11-15 12:00 UTC)).unwrap(); + assert!(report.deleted.is_empty(), "{:?}", report.deleted); + assert!(report.failures.is_empty()); + assert!(target.exists()); + for name in keep { + assert!(dir.path().join(name).exists(), "{name} was removed"); + } + assert!(dir.path().join("sendbox-fleet.2020-01-02.log").is_dir()); + } + + #[test] + fn unreadable_directory_is_an_error() { + let dir = tempfile::tempdir().unwrap(); + assert!(enforce(&dir.path().join("absent"), 30, OffsetDateTime::now_utc()).is_err()); + } +} diff --git a/crates/fleet-server/src/main.rs b/crates/fleet-server/src/main.rs new file mode 100644 index 0000000..13134db --- /dev/null +++ b/crates/fleet-server/src/main.rs @@ -0,0 +1,33 @@ +#![forbid(unsafe_code)] + +use std::process::ExitCode; + +use fleet_server::config::Config; +use fleet_server::{logging, server}; + +fn main() -> ExitCode { + let config = match Config::from_env() { + Ok(config) => config, + Err(error) => { + eprintln!("sendbox-fleet: configuration error: {error}"); + return ExitCode::from(2); + } + }; + let logging = match logging::init(&config.logging) { + Ok(guard) => guard, + Err(error) => { + eprintln!("sendbox-fleet: cannot start logging: {error}"); + return ExitCode::FAILURE; + } + }; + let result = actix_web::rt::System::new().block_on(server::run(config, logging.dir.clone())); + let code = match result { + Ok(()) => ExitCode::SUCCESS, + Err(error) => { + tracing::error!(%error, "sendbox-fleet failed"); + ExitCode::FAILURE + } + }; + drop(logging); + code +} diff --git a/crates/fleet-server/src/problem.rs b/crates/fleet-server/src/problem.rs new file mode 100644 index 0000000..37e3e24 --- /dev/null +++ b/crates/fleet-server/src/problem.rs @@ -0,0 +1,131 @@ +//! RFC 9457 problem details (`application/problem+json`). + +use actix_web::http::StatusCode; +use actix_web::http::header::{self, HeaderValue}; +use actix_web::{HttpRequest, HttpResponse, ResponseError}; +use serde::Serialize; +use thiserror::Error; + +pub const PROBLEM_CONTENT_TYPE: &str = "application/problem+json"; +/// Maximum characters of a parser message echoed back in `detail`. +const MAX_DETAIL_CHARS: usize = 512; + +/// A problem response. `type` is always `about:blank`, so `title` is the +/// standard reason phrase for `status` and `detail` explains this occurrence. +#[derive(Debug, Clone, Serialize, Error)] +#[error("{status} {title}: {detail}")] +pub struct Problem { + #[serde(rename = "type")] + pub kind: &'static str, + pub title: &'static str, + pub status: u16, + pub detail: String, + /// Stable identifier of the unimplemented capability for 501 responses. + #[serde(skip_serializing_if = "Option::is_none")] + pub capability: Option<&'static str>, + #[serde(skip)] + challenge: Option<&'static str>, +} + +impl Problem { + fn new(status: StatusCode, detail: impl Into) -> Self { + let mut detail: String = detail.into(); + if let Some((index, _)) = detail.char_indices().nth(MAX_DETAIL_CHARS) { + detail.truncate(index); + detail.push_str("..."); + } + Self { + kind: "about:blank", + title: status.canonical_reason().unwrap_or("Error"), + status: status.as_u16(), + detail, + capability: None, + challenge: None, + } + } + + #[must_use] + pub fn bad_request(detail: impl Into) -> Self { + Self::new(StatusCode::BAD_REQUEST, detail) + } + + /// A 401 carrying a `WWW-Authenticate` challenge (RFC 6750). + #[must_use] + pub fn unauthorized(detail: impl Into, challenge: &'static str) -> Self { + Self { + challenge: Some(challenge), + ..Self::new(StatusCode::UNAUTHORIZED, detail) + } + } + + #[must_use] + pub fn not_found() -> Self { + Self::new(StatusCode::NOT_FOUND, "no resource exists at this path") + } + + #[must_use] + pub fn method_not_allowed() -> Self { + Self::new( + StatusCode::METHOD_NOT_ALLOWED, + "this resource does not support the request method", + ) + } + + #[must_use] + pub fn payload_too_large(detail: impl Into) -> Self { + Self::new(StatusCode::PAYLOAD_TOO_LARGE, detail) + } + + #[must_use] + pub fn unsupported_media_type(detail: impl Into) -> Self { + Self::new(StatusCode::UNSUPPORTED_MEDIA_TYPE, detail) + } + + #[must_use] + pub fn not_implemented(capability: &'static str, detail: impl Into) -> Self { + Self { + capability: Some(capability), + ..Self::new(StatusCode::NOT_IMPLEMENTED, detail) + } + } + + #[must_use] + pub fn service_unavailable(detail: impl Into) -> Self { + Self::new(StatusCode::SERVICE_UNAVAILABLE, detail) + } +} + +impl ResponseError for Problem { + fn status_code(&self) -> StatusCode { + StatusCode::from_u16(self.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR) + } + + fn error_response(&self) -> HttpResponse { + let mut response = HttpResponse::build(self.status_code()); + response + .content_type(PROBLEM_CONTENT_TYPE) + .insert_header((header::CACHE_CONTROL, HeaderValue::from_static("no-store"))); + if let Some(challenge) = self.challenge { + response.insert_header((header::WWW_AUTHENTICATE, challenge)); + } + response.json(self) + } +} + +/// Default service: unknown paths become a 404 problem. +pub async fn not_found(_request: HttpRequest) -> Problem { + Problem::not_found() +} + +/// Per-resource default service: unsupported methods become a 405 problem. +pub async fn method_not_allowed(_request: HttpRequest) -> Problem { + Problem::method_not_allowed() +} + +impl actix_web::Responder for Problem { + type Body = actix_web::body::BoxBody; + + fn respond_to(self, _request: &HttpRequest) -> HttpResponse { + self.error_response() + } +} diff --git a/crates/fleet-server/src/routes/health.rs b/crates/fleet-server/src/routes/health.rs new file mode 100644 index 0000000..2fd032a --- /dev/null +++ b/crates/fleet-server/src/routes/health.rs @@ -0,0 +1,41 @@ +//! Liveness and readiness probes. Both are unauthenticated and reveal only +//! process and database availability. + +use actix_web::http::header::{CACHE_CONTROL, HeaderValue}; +use actix_web::{HttpResponse, web}; +use serde::Serialize; + +use super::resource; +use crate::db::Database; +use crate::problem::Problem; + +#[derive(Debug, Serialize)] +struct Status { + status: &'static str, +} + +pub fn configure(config: &mut web::ServiceConfig) { + config + .service(resource("/healthz").route(web::get().to(healthz))) + .service(resource("/readyz").route(web::get().to(readyz))); +} + +/// The process is running and serving HTTP. +async fn healthz() -> HttpResponse { + status("ok") +} + +/// The service can reach its database. +async fn readyz(database: web::Data) -> Result { + database.ping().await.map_err(|error| { + tracing::warn!(%error, "readiness check failed"); + Problem::service_unavailable("the database is not reachable") + })?; + Ok(status("ready")) +} + +fn status(status: &'static str) -> HttpResponse { + HttpResponse::Ok() + .insert_header((CACHE_CONTROL, HeaderValue::from_static("no-store"))) + .json(Status { status }) +} diff --git a/crates/fleet-server/src/routes/mod.rs b/crates/fleet-server/src/routes/mod.rs new file mode 100644 index 0000000..9d52c67 --- /dev/null +++ b/crates/fleet-server/src/routes/mod.rs @@ -0,0 +1,64 @@ +//! HTTP routes: unauthenticated probes plus the authenticated `/v1` API. + +pub mod health; +pub mod v1; + +use actix_web::error::{JsonPayloadError, PathError, QueryPayloadError}; +use actix_web::middleware::from_fn; +use actix_web::{HttpRequest, Resource, web}; + +use crate::auth; +use crate::problem::{self, Problem}; + +/// Request body limit for ordinary JSON requests. +const JSON_LIMIT_BYTES: usize = 64 * 1024; + +pub fn configure(config: &mut web::ServiceConfig) { + config + .app_data(json_config(JSON_LIMIT_BYTES)) + .app_data(web::PathConfig::default().error_handler(path_error)) + .app_data(web::QueryConfig::default().error_handler(query_error)) + .configure(health::configure) + .service( + web::scope("/v1") + .wrap(from_fn(auth::require_bearer)) + .configure(v1::configure) + .default_service(web::to(problem::not_found)), + ); +} + +/// A resource whose unsupported methods return a 405 problem. +pub(crate) fn resource(path: &str) -> Resource { + web::resource(path).default_service(web::to(problem::method_not_allowed)) +} + +pub(crate) fn json_config(limit: usize) -> web::JsonConfig { + web::JsonConfig::default() + .limit(limit) + .error_handler(json_error) +} + +fn json_error(error: JsonPayloadError, _request: &HttpRequest) -> actix_web::Error { + let problem = match &error { + JsonPayloadError::Overflow { limit } + | JsonPayloadError::OverflowKnownLength { limit, .. } => { + Problem::payload_too_large(format!("request body exceeds {limit} bytes")) + } + JsonPayloadError::ContentType => { + Problem::unsupported_media_type("request body must be `application/json`") + } + JsonPayloadError::Deserialize(error) => { + Problem::bad_request(format!("invalid request body: {error}")) + } + _ => Problem::bad_request("request body could not be read"), + }; + problem.into() +} + +fn path_error(error: PathError, _request: &HttpRequest) -> actix_web::Error { + Problem::bad_request(format!("invalid path parameter: {error}")).into() +} + +fn query_error(error: QueryPayloadError, _request: &HttpRequest) -> actix_web::Error { + Problem::bad_request(format!("invalid query string: {error}")).into() +} diff --git a/crates/fleet-server/src/routes/v1/audit.rs b/crates/fleet-server/src/routes/v1/audit.rs new file mode 100644 index 0000000..a57b3b3 --- /dev/null +++ b/crates/fleet-server/src/routes/v1/audit.rs @@ -0,0 +1,90 @@ +//! `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. + +use actix_web::web; +use sendbox_governance::{ + DenyReason, GrantId, PrincipalId, ProfileRef, ProjectId, SessionRef, Sha256Digest, +}; +use serde::{Deserialize, Serialize}; + +use super::Capability; +use crate::auth::Authenticated; +use crate::problem::Problem; +use crate::routes::resource; + +const MAX_PAGE_SIZE: u32 = 500; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AuditQuery { + pub project: Option, + pub session: Option, + pub principal: 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 { + pub events: Vec, + pub next_after_sequence: Option, +} + +pub fn configure(config: &mut web::ServiceConfig) { + config.service(resource("/audit/events").route(web::get().to(list))); +} + +async fn list( + _caller: Authenticated, + query: web::Query, +) -> Result, Problem> { + if query + .limit + .is_some_and(|limit| !(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()) +} diff --git a/crates/fleet-server/src/routes/v1/authorize.rs b/crates/fleet-server/src/routes/v1/authorize.rs new file mode 100644 index 0000000..2bec05d --- /dev/null +++ b/crates/fleet-server/src/routes/v1/authorize.rs @@ -0,0 +1,24 @@ +//! `POST /v1/authorize`: decide one brokered upstream request. + +use actix_web::web; +use sendbox_governance::{Decision, RequestContext}; + +use super::Capability; +use crate::auth::Authenticated; +use crate::problem::Problem; +use crate::routes::resource; + +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. +async fn authorize( + _caller: Authenticated, + _context: web::Json, +) -> Result, Problem> { + Err(Capability::RequestAuthorization.problem()) +} diff --git a/crates/fleet-server/src/routes/v1/exceptions.rs b/crates/fleet-server/src/routes/v1/exceptions.rs new file mode 100644 index 0000000..f75e1e4 --- /dev/null +++ b/crates/fleet-server/src/routes/v1/exceptions.rs @@ -0,0 +1,88 @@ +//! `POST /v1/exceptions`: request a bounded, expiring policy exception. +//! +//! 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. + +use actix_web::web; +use sendbox_governance::{PrincipalId, ProfileRef, ProjectId}; +use serde::{Deserialize, Serialize}; + +use super::Capability; +use crate::auth::Authenticated; +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, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExceptionRequest { + pub project: ProjectId, + /// 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. + 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(()) + } +} + +pub fn configure(config: &mut web::ServiceConfig) { + config.service(resource("/exceptions").route(web::post().to(request_exception))); +} + +async fn request_exception( + _caller: Authenticated, + request: web::Json, +) -> Result, Problem> { + request.validate()?; + Err(Capability::ExceptionRequest.problem()) +} diff --git a/crates/fleet-server/src/routes/v1/grants.rs b/crates/fleet-server/src/routes/v1/grants.rs new file mode 100644 index 0000000..796b2a8 --- /dev/null +++ b/crates/fleet-server/src/routes/v1/grants.rs @@ -0,0 +1,62 @@ +//! Credential grants: issue, renew, and revoke. Grants authorize one session +//! to use one brokered service; they never carry credential material. + +use actix_web::{HttpResponse, web}; +use sendbox_governance::grant::{validate_method, validate_path_prefix}; +use sendbox_governance::{CredentialGrant, GrantId, GrantRequest, RevocationReason}; +use serde::{Deserialize, Serialize}; + +use super::{Capability, invalid}; +use crate::auth::Authenticated; +use crate::problem::Problem; +use crate::routes::resource; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RevokeGrantRequest { + pub reason: RevocationReason, +} + +pub fn configure(config: &mut web::ServiceConfig) { + config + .service(resource("/grants").route(web::post().to(issue))) + .service(resource("/grants/{grant_id:[^/:]+}:renew").route(web::post().to(renew))) + .service(resource("/grants/{grant_id:[^/:]+}:revoke").route(web::post().to(revoke))); +} + +async fn issue( + _caller: Authenticated, + request: web::Json, +) -> Result, Problem> { + request.binding.validate().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", + )); + } + for method in &request.methods { + validate_method(method).map_err(invalid)?; + } + for prefix in &request.path_prefixes { + validate_path_prefix(prefix).map_err(invalid)?; + } + if request.max_ttl_seconds == 0 { + return Err(Problem::bad_request("max_ttl_seconds must be positive")); + } + Err(Capability::GrantIssuance.problem()) +} + +async fn renew( + _caller: Authenticated, + _grant: web::Path, +) -> Result, Problem> { + Err(Capability::GrantRenewal.problem()) +} + +async fn revoke( + _caller: Authenticated, + _grant: web::Path, + _request: web::Json, +) -> Result { + Err(Capability::GrantRevocation.problem()) +} diff --git a/crates/fleet-server/src/routes/v1/mod.rs b/crates/fleet-server/src/routes/v1/mod.rs new file mode 100644 index 0000000..6634ecf --- /dev/null +++ b/crates/fleet-server/src/routes/v1/mod.rs @@ -0,0 +1,99 @@ +//! 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. + +pub mod audit; +pub mod authorize; +pub mod exceptions; +pub mod grants; +pub mod profiles; +pub mod projects; +pub mod sessions; + +use actix_web::web; +use sendbox_governance::GovernanceError; + +use crate::problem::Problem; + +pub fn configure(config: &mut web::ServiceConfig) { + config + .configure(sessions::configure) + .configure(grants::configure) + .configure(authorize::configure) + .configure(profiles::configure) + .configure(projects::configure) + .configure(exceptions::configure) + .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, +} + +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", + } + } + + 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", + } + } + + #[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() + ), + ) + } +} + +/// Maps a contract validation failure to a 400 problem. +pub(crate) fn invalid(error: GovernanceError) -> Problem { + Problem::bad_request(error.to_string()) +} diff --git a/crates/fleet-server/src/routes/v1/profiles.rs b/crates/fleet-server/src/routes/v1/profiles.rs new file mode 100644 index 0000000..4fbcfb1 --- /dev/null +++ b/crates/fleet-server/src/routes/v1/profiles.rs @@ -0,0 +1,125 @@ +//! Governance profiles: read the current revision or publish a signed one. + +use std::collections::BTreeSet; + +use actix_web::web; +use sendbox_governance::{GovernanceProfile, ProfileId, ProfileRef}; +use serde::{Deserialize, Serialize}; + +use super::{Capability, invalid}; +use crate::auth::Authenticated; +use crate::problem::Problem; +use crate::routes::{json_config, resource}; + +/// 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; + +/// 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. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ProfilePublication { + pub document: String, + pub signatures: Vec, +} + +#[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, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ProfileRecord { + pub reference: ProfileRef, + pub minimum_revision: u64, + pub not_before_unix: u64, + pub expires_at_unix: u64, + pub document: String, + pub signatures: Vec, +} + +impl ProfilePublication { + /// Parses the document with the shared contract and checks the envelope. + pub fn validate(&self, path_id: &ProfileId) -> Result { + let profile = GovernanceProfile::parse(self.document.as_bytes()).map_err(invalid)?; + if &profile.id != path_id { + return Err(Problem::bad_request(format!( + "profile document id `{}` does not match the request path id `{path_id}`", + profile.id + ))); + } + if self.signatures.is_empty() || self.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" + ))); + } + } + 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)), + ); +} + +async fn read( + _caller: Authenticated, + _profile: web::Path, +) -> Result, Problem> { + Err(Capability::ProfileRead.problem()) +} + +async fn publish( + _caller: Authenticated, + profile: web::Path, + publication: web::Json, +) -> Result, Problem> { + publication.validate(&profile)?; + Err(Capability::ProfilePublication.problem()) +} diff --git a/crates/fleet-server/src/routes/v1/projects.rs b/crates/fleet-server/src/routes/v1/projects.rs new file mode 100644 index 0000000..053703f --- /dev/null +++ b/crates/fleet-server/src/routes/v1/projects.rs @@ -0,0 +1,71 @@ +//! Project-scoped roles. Roles authorize what an authenticated caller may do +//! within one project; they are never derived from workload-supplied fields. + +use actix_web::web; +use sendbox_governance::{PrincipalId, ProjectId}; +use serde::{Deserialize, Serialize}; + +use super::Capability; +use crate::auth::Authenticated; +use crate::problem::Problem; +use crate::routes::resource; + +/// 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, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RoleBinding { + pub principal: PrincipalId, + pub role: ProjectRole, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ProjectRoles { + pub project: ProjectId, + 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"; + +pub fn configure(config: &mut web::ServiceConfig) { + config.service( + resource("/projects/{project_id}/roles") + .route(web::get().to(list)) + .route(web::post().to(assign)), + ); +} + +async fn list( + _caller: Authenticated, + _project: web::Path, +) -> Result, Problem> { + Err(Capability::RoleListing.problem()) +} + +async fn assign( + _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", + )); + } + Err(Capability::RoleAssignment.problem()) +} diff --git a/crates/fleet-server/src/routes/v1/sessions.rs b/crates/fleet-server/src/routes/v1/sessions.rs new file mode 100644 index 0000000..b7dbc15 --- /dev/null +++ b/crates/fleet-server/src/routes/v1/sessions.rs @@ -0,0 +1,40 @@ +//! `POST /v1/sessions:admit`: admit a session under a governance profile. + +use actix_web::web; +use sendbox_governance::{GovernanceBinding, SessionRef, Sha256Digest}; +use serde::{Deserialize, Serialize}; + +use super::{Capability, invalid}; +use crate::auth::Authenticated; +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, +} + +pub fn configure(config: &mut web::ServiceConfig) { + config.service(resource("/sessions:admit").route(web::post().to(admit))); +} + +async fn admit( + _caller: Authenticated, + request: web::Json, +) -> Result, Problem> { + request.binding.validate().map_err(invalid)?; + Err(Capability::SessionAdmission.problem()) +} diff --git a/crates/fleet-server/src/server.rs b/crates/fleet-server/src/server.rs new file mode 100644 index 0000000..0170ea4 --- /dev/null +++ b/crates/fleet-server/src/server.rs @@ -0,0 +1,123 @@ +//! Application assembly and the process lifecycle. + +use std::io; +use std::net::SocketAddr; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; + +use actix_web::body::MessageBody; +use actix_web::dev::{ServiceFactory, ServiceRequest, ServiceResponse}; +use actix_web::middleware::from_fn; +use actix_web::{App, HttpServer, web}; +use thiserror::Error; +use time::OffsetDateTime; +use tokio::task::JoinHandle; + +use crate::auth::{self, SharedAuthenticator, UnconfiguredAuthenticator}; +use crate::config::Config; +use crate::db::{Database, DbError}; +use crate::logging::{self, retention}; +use crate::problem; +use crate::routes; + +/// Time in-flight requests get to finish after SIGINT or SIGTERM. +const SHUTDOWN_GRACE_SECONDS: u64 = 30; +const RETENTION_INTERVAL: Duration = Duration::from_secs(60 * 60); + +#[derive(Debug, Error)] +pub enum ServerError { + #[error(transparent)] + Database(#[from] DbError), + #[error("cannot listen on {address}: {source}")] + Bind { + address: SocketAddr, + source: io::Error, + }, + #[error("HTTP server failed: {0}")] + Serve(io::Error), +} + +/// Builds the application. Shared by the server and the HTTP tests. +pub fn app( + database: web::Data, + authenticator: SharedAuthenticator, +) -> App< + impl ServiceFactory< + ServiceRequest, + Config = (), + Response = ServiceResponse, + Error = actix_web::Error, + InitError = (), + >, +> { + App::new() + .app_data(database) + .app_data(authenticator) + .wrap(from_fn(logging::request_log)) + .configure(routes::configure) + .default_service(web::to(problem::not_found)) +} + +/// Connects and migrates the database, then serves until SIGINT or SIGTERM. +pub async fn run(config: Config, log_dir: PathBuf) -> Result<(), ServerError> { + let retention = spawn_retention(log_dir.clone(), config.logging.retention_days); + let database = Database::connect(&config.database_url).await?; + database.migrate().await?; + tracing::info!( + bind = %config.bind, + database = %config.database_url, + log_dir = %log_dir.display(), + contract_version = crate::CONTRACT_VERSION, + "sendbox-fleet starting" + ); + tracing::warn!( + "no authentication provider is configured; every /v1 request is rejected with 401" + ); + + let data = web::Data::new(database.clone()); + let authenticator = auth::shared(Arc::new(UnconfiguredAuthenticator)); + let server = HttpServer::new(move || app(data.clone(), authenticator.clone())) + .shutdown_timeout(SHUTDOWN_GRACE_SECONDS) + .bind(config.bind) + .map_err(|source| ServerError::Bind { + address: config.bind, + source, + })? + .run(); + let served = server.await.map_err(ServerError::Serve); + + retention.abort(); + database.close().await; + tracing::info!("sendbox-fleet stopped"); + served +} + +/// Applies log retention now and then hourly while the server runs. +fn spawn_retention(dir: PathBuf, retention_days: u32) -> JoinHandle<()> { + actix_web::rt::spawn(async move { + let mut interval = tokio::time::interval(RETENTION_INTERVAL); + loop { + interval.tick().await; + let dir = dir.clone(); + let outcome = tokio::task::spawn_blocking(move || { + retention::enforce(&dir, retention_days, OffsetDateTime::now_utc()) + }) + .await; + match outcome { + Ok(Ok(report)) => { + for path in &report.deleted { + tracing::info!(path = %path.display(), "deleted expired log file"); + } + for (path, error) in &report.failures { + tracing::warn!(path = %path.display(), %error, "cannot delete expired log file"); + } + } + Ok(Err(error)) => { + tracing::warn!(%error, "cannot list the log directory for retention") + } + Err(error) => tracing::warn!(%error, "log retention task failed"), + } + } + }) +} diff --git a/crates/fleet-server/tests/http.rs b/crates/fleet-server/tests/http.rs new file mode 100644 index 0000000..e2de432 --- /dev/null +++ b/crates/fleet-server/tests/http.rs @@ -0,0 +1,604 @@ +//! HTTP behaviour of the scaffold: probes, authentication before validation, +//! contract validation, and explicit 501 responses. All data is synthetic. + +use std::sync::Arc; + +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::config::DatabaseUrl; +use fleet_server::db::Database; +use fleet_server::server; +use sendbox_governance::PrincipalId; +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 +version: 1 +id: example-default +revision: 3 +not_before_unix: 1790000000 +expires_at_unix: 1800000000 +ceiling: + runtimes: [apple, kata] + commands: + default_action: deny + 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) + } + }) + } +} + +async fn database() -> Database { + let database = Database::connect(&DatabaseUrl::parse("sqlite::memory:").unwrap()) + .await + .unwrap(); + database.migrate().await.unwrap(); + database +} + +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 +} + +fn digest(byte: char) -> String { + byte.to_string().repeat(64) +} + +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 grant_request() -> Value { + json!({ + "principal": "oidc:alice@example.com", + "project": "github:example/service", + "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 + }) +} + +fn publication() -> Value { + json!({ + "document": PROFILE_YAML, + "signatures": [{ "key_id": "operator-2026", "signature": "c2lnbmF0dXJl" }] + }) +} + +struct Route { + method: Method, + path: &'static str, + body: Option, + capability: &'static str, +} + +fn route( + method: Method, + path: &'static str, + body: Option, + capability: &'static str, +) -> Route { + Route { + method, + path, + body, + capability, + } +} + +/// 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( + Method::POST, + "/v1/grants", + Some(grant_request()), + "grant_issuance", + ), + route( + 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", + ), + route( + 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", + ), + 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", + ), + ] +} + +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}"))); + } + match body { + Some(body) => request.set_json(body).to_request(), + None => request.to_request(), + } +} + +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()) + ); + (status, body) +} + +#[actix_web::test] +async fn health_and_readiness_report_status() { + let database = database().await; + let app = service(database.clone(), Arc::new(MockAuthenticator)).await; + + 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 })); + } + + 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); +} + +#[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 + ); + } +} + +#[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") + ); + } +} + +#[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"); + } +} + +#[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}"); + } +} + +/// 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 +} + +#[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![ + ( + Method::POST, + "/v1/sessions:admit", + Some(with(admit.clone(), "/session", json!("not-a-session"))), + ), + ( + Method::POST, + "/v1/sessions:admit", + Some(with(admit.clone(), "/binding/contract_version", json!(2))), + ), + ( + Method::POST, + "/v1/sessions:admit", + Some(with(admit, "/binding/principal", json!("Alice"))), + ), + ( + Method::POST, + "/v1/grants", + Some(with( + grant_request(), + "/binding/brokered_services", + json!(["openai", "anthropic"]), + )), + ), + ( + Method::POST, + "/v1/grants", + Some(with(grant_request(), "/methods", json!(["CONNECT"]))), + ), + ( + Method::POST, + "/v1/grants", + Some(with( + grant_request(), + "/path_prefixes", + json!(["/v1/../admin"]), + )), + ), + ( + Method::POST, + "/v1/grants", + Some(with(grant_request(), "/max_ttl_seconds", json!(0))), + ), + (Method::POST, "/v1/grants/NOT-A-GRANT:renew", None), + ( + Method::POST, + "/v1/grants/fedcba9876543210fedcba9876543210:revoke", + Some(json!({ "reason": "because" })), + ), + ( + 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!"), + )), + ), + ( + Method::GET, + "/v1/projects/gitlab:example%2Fservice/roles", + None, + ), + ( + Method::POST, + "/v1/projects/github:example%2Fservice/roles", + Some(json!({ "principal": "oidc:bob@example.com", "role": "superuser" })), + ), + ( + Method::POST, + "/v1/projects/github:example%2Fservice/roles", + Some(json!({ "principal": "local-user:501:bob", "role": "member" })), + ), + ( + Method::POST, + "/v1/exceptions", + Some(with(exception_request(), "/reason", json!(" "))), + ), + ( + Method::POST, + "/v1/exceptions", + Some(with( + exception_request(), + "/scope/value", + json!("two words"), + )), + ), + ( + Method::POST, + "/v1/exceptions", + Some(with( + exception_request(), + "/approved_by", + json!("oidc:bob@example.com"), + )), + ), + (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, + ), + ]; + 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" + ); + } +} + +#[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 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); +} diff --git a/crates/fleet-server/tests/migrations.rs b/crates/fleet-server/tests/migrations.rs new file mode 100644 index 0000000..33da231 --- /dev/null +++ b/crates/fleet-server/tests/migrations.rs @@ -0,0 +1,264 @@ +//! Migrations apply cleanly and the schema enforces its invariants. +//! +//! 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 checks +//! against PostgreSQL; its `public` schema is dropped and recreated by every +//! test, so run with `--test-threads=1`. + +use fleet_server::config::{DatabaseKind, DatabaseUrl}; +use fleet_server::db::Database; + +const TABLES: [&str; 10] = [ + "principals", + "projects", + "role_bindings", + "profiles", + "profile_minimum_revisions", + "sessions", + "credential_grants", + "revocations", + "exceptions", + "audit_events", +]; +const ZERO_HASH: &str = "0000000000000000000000000000000000000000000000000000000000000000"; +const SESSION: &str = "0123456789abcdef0123456789abcdef"; +const PROFILE_SHA: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; +const BINDING_SHA: &str = "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"; + +async fn database() -> Database { + 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 +} + +async fn exec(database: &Database, sql: &str) -> Result<(), sqlx::Error> { + match database { + Database::Postgres(pool) => sqlx::raw_sql(sql).execute(pool).await.map(drop), + Database::Sqlite(pool) => sqlx::raw_sql(sql).execute(pool).await.map(drop), + } +} + +async fn count(database: &Database, table: &str) -> i64 { + let sql = format!("SELECT COUNT(*) FROM {table}"); + match database { + Database::Postgres(pool) => sqlx::query_scalar::<_, i64>(&sql).fetch_one(pool).await, + Database::Sqlite(pool) => sqlx::query_scalar::<_, i64>(&sql).fetch_one(pool).await, + } + .unwrap() +} + +async fn accept(database: &Database, sql: &str) { + if let Err(error) = exec(database, sql).await { + panic!("rejected valid statement: {error}\n{sql}"); + } +} + +async fn reject(database: &Database, sql: &str) { + assert!( + exec(database, sql).await.is_err(), + "accepted invalid statement:\n{sql}" + ); +} + +fn bytes_literal(database: &Database, hex: &str) -> String { + match database.kind() { + DatabaseKind::Postgres => format!("decode('{hex}', 'hex')"), + DatabaseKind::Sqlite => format!("X'{hex}'"), + } +} + +/// Synthetic principals, a project, a profile revision, and an admitted session. +async fn seed(database: &Database) { + for (id, kind) in [ + ("oidc:alice@example.com", "user"), + ("oidc:bob@example.com", "user"), + ("worker:host-1", "worker"), + ] { + accept( + database, + &format!("INSERT INTO principals (id, kind, created_at_unix) VALUES ('{id}', '{kind}', 1790000000)"), + ) + .await; + } + accept( + database, + "INSERT INTO projects (id, created_at_unix) VALUES ('github:example/service', 1790000000)", + ) + .await; + accept( + database, + &format!( + "INSERT INTO profiles (id, revision, sha256, signed_bytes, signatures, not_before_unix, \ + expires_at_unix, published_by, published_at_unix) VALUES ('example-default', 3, \ + '{PROFILE_SHA}', {}, '[{{\"key_id\":\"operator-2026\",\"signature\":\"c2ln\"}}]', \ + 1790000000, 1800000000, 'oidc:bob@example.com', 1790000000)", + bytes_literal(database, "69643a206578616d706c65") + ), + ) + .await; + accept( + database, + &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 ('{SESSION}', 'oidc:alice@example.com', \ + 'github:example/service', 'sendbox-fleet', 'example-default', 3, '{PROFILE_SHA}', \ + '{BINDING_SHA}', '{{\"contract_version\":1}}', '{BINDING_SHA}', 'admitted', \ + 'worker:host-1', 1790000100)" + ), + ) + .await; +} + +fn grant_sql(id: &str, principal: &str, issued: i64, max_expires: i64) -> String { + 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 ('{id}', \ + '{SESSION}', '{principal}', 'github:example/service', '{BINDING_SHA}', 'example-default', \ + 3, '{PROFILE_SHA}', 'anthropic', '[\"POST\"]', '[\"/v1/messages\"]', {issued}, {}, \ + {max_expires}, 1)", + issued + 300 + ) +} + +fn audit_sql(sequence: i64, previous: &str, hash: &str) -> String { + format!( + "INSERT INTO audit_events (sequence, occurred_at_unix, recorded_at_unix, event_type, \ + project_id, decision, deny_reason, target_redacted, previous_hash, event_hash) VALUES \ + ({sequence}, 1790000200, 1790000200, 'grant.authorize', 'github:example/service', 'deny', \ + 'stale_policy', 'POST api.anthropic.com /v1/messages', '{previous}', '{hash}')" + ) +} + +#[actix_web::test] +async fn migrations_create_every_table_and_are_idempotent() { + let database = database().await; + database.migrate().await.unwrap(); + database.ping().await.unwrap(); + for table in TABLES { + assert_eq!(count(&database, table).await, 0, "{table}"); + } +} + +#[actix_web::test] +async fn audit_events_form_an_append_only_hash_chain() { + let database = database().await; + let first = "1".repeat(64); + let second = "2".repeat(64); + + reject(&database, &audit_sql(1, &first, &first)).await; + accept(&database, &audit_sql(1, ZERO_HASH, &first)).await; + reject(&database, &audit_sql(2, ZERO_HASH, &second)).await; + reject(&database, &audit_sql(3, &first, &second)).await; + accept(&database, &audit_sql(2, &first, &second)).await; + reject( + &database, + &audit_sql(3, &second, &"3".repeat(64)).replace("'stale_policy'", "NULL"), + ) + .await; + reject( + &database, + &audit_sql(3, &second, &"3".repeat(64)).replace("/v1/messages'", "/v1/messages?key=x'"), + ) + .await; + + reject( + &database, + "UPDATE audit_events SET outcome = 'failed' WHERE sequence = 1", + ) + .await; + reject(&database, "DELETE FROM audit_events WHERE sequence = 2").await; + assert_eq!(count(&database, "audit_events").await, 2); +} + +#[actix_web::test] +async fn identities_are_bound_and_lifetimes_bounded() { + let database = database().await; + seed(&database).await; + + reject( + &database, + "INSERT INTO principals (id, kind, created_at_unix) VALUES ('local-user:501:alice', 'user', 0)", + ) + .await; + reject( + &database, + "INSERT INTO projects (id, created_at_unix) VALUES ('github:example/../etc', 0)", + ) + .await; + reject( + &database, + "INSERT INTO role_bindings (project_id, principal_id, role, granted_by, granted_at_unix) \ + VALUES ('github:example/service', 'oidc:alice@example.com', 'superuser', 'oidc:bob@example.com', 0)", + ) + .await; + + let grant = "fedcba9876543210fedcba9876543210"; + reject( + &database, + &grant_sql(grant, "oidc:bob@example.com", 1790000200, 1790003800), + ) + .await; + reject( + &database, + &grant_sql( + grant, + "oidc:alice@example.com", + 1790000200, + 1790000200 + 604801, + ), + ) + .await; + accept( + &database, + &grant_sql(grant, "oidc:alice@example.com", 1790000200, 1790003800), + ) + .await; + + let revocation = |grace: i64| { + format!( + "INSERT INTO revocations (grant_id, reason, revoked_at_unix, grace_expires_at_unix, generation) \ + VALUES ('{grant}', 'session_completed', 1790000300, {}, 2)", + 1790000300 + grace + ) + }; + reject(&database, &revocation(61)).await; + accept(&database, &revocation(5)).await; + + let exception = |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', \ + 1790000000, '{decided_by}', 1790000100, {expires})" + ) + }; + reject(&database, &exception("oidc:alice@example.com", 1790086400)).await; + reject( + &database, + &exception("oidc:bob@example.com", 1790000000 + 604801), + ) + .await; + accept(&database, &exception("oidc:bob@example.com", 1790086400)).await; +} diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 0000000..f8800ea --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,4 @@ +[toolchain] +channel = "1.93.1" +components = ["clippy", "rustfmt"] +profile = "minimal" From a1069c209d2ee1e95f70ef6ed18121e7ca993b15 Mon Sep 17 00:00:00 2001 From: mbianchidev Date: Sun, 15 Nov 2026 13:40:22 +0100 Subject: [PATCH 3/6] Add container build, compose stack, and CI Multi-stage Dockerfile with digest-pinned bases and a non-root runtime, compose stack with a health-checked PostgreSQL, and CI for formatting, Clippy, SQLite tests, PostgreSQL migrations plus a server smoke run, and cargo audit with documented exceptions. --- .cargo/audit.toml | 15 ++++++ .dockerignore | 9 ++++ .env.example | 14 +++++ .github/workflows/ci.yml | 111 +++++++++++++++++++++++++++++++++++++++ Dockerfile | 25 +++++++++ docker-compose.yml | 54 +++++++++++++++++++ 6 files changed, 228 insertions(+) create mode 100644 .cargo/audit.toml create mode 100644 .dockerignore create mode 100644 .env.example create mode 100644 .github/workflows/ci.yml create mode 100644 Dockerfile create mode 100644 docker-compose.yml diff --git a/.cargo/audit.toml b/.cargo/audit.toml new file mode 100644 index 0000000..9acdb3a --- /dev/null +++ b/.cargo/audit.toml @@ -0,0 +1,15 @@ +# cargo-audit configuration. Every ignored advisory needs a reason and an exit +# condition; revisit them whenever dependencies or the toolchain change. +[advisories] +ignore = [ + # rsa (Marvin attack). Listed in Cargo.lock only because sqlx-macros-core + # declares optional MySQL support; it is never compiled + # (`cargo tree -i rsa` prints nothing). Remove with the sqlx 0.9 upgrade. + "RUSTSEC-2023-0071", + # libsqlite3-sys bundles SQLite < 3.54 (stale page-cache bytes when an + # attacker-written database and -wal file are opened together). SQLite is + # only used for local development and tests, on files the service creates + # itself. The fix needs sqlx 0.9, which requires Rust 1.94; this workspace + # is pinned to Rust 1.93.1 to match SendBox. Remove when the toolchain moves. + "RUSTSEC-2026-0459", +] diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..8044e19 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,9 @@ +.git/ +.github/ +.env +target/ +logs/ +docs/ +*.db +*.db-shm +*.db-wal diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..e63e896 --- /dev/null +++ b/.env.example @@ -0,0 +1,14 @@ +# Copy to `.env` and adjust. These are local development examples, not secrets. + +# docker compose (see docs/development.md) +POSTGRES_DB=sendbox_fleet +POSTGRES_USER=sendbox_fleet +POSTGRES_PASSWORD=local-dev-only-change-me +FLEET_PORT=8080 +FLEET_LOG_LEVEL=info +FLEET_LOG_RETENTION_DAYS=30 + +# 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 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..4fa15db --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,111 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + +concurrency: + group: ci-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + +jobs: + checks: + name: Format, lint, and test (SQLite) + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install the pinned toolchain + run: rustc --version --verbose + + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + + - name: Check formatting + run: cargo fmt --all -- --check + + - name: Run Clippy + run: cargo clippy --locked --workspace --all-targets -- -D warnings + + - name: Run tests + run: cargo test --locked --workspace + + postgres: + name: Migrations and server (PostgreSQL) + runs-on: ubuntu-24.04 + timeout-minutes: 30 + services: + postgres: + image: postgres:18.7-alpine3.24@sha256:b6972e1115a4ff8eba5d7f7d19184926d1e16d7d1136ae1e1a7ebf286da0f015 + env: + POSTGRES_DB: sendbox_fleet_test + POSTGRES_USER: sendbox_fleet + # Ephemeral, job-local database reachable only from this runner. + POSTGRES_HOST_AUTH_METHOD: trust + ports: + - 5432:5432 + options: >- + --health-cmd "pg_isready -U sendbox_fleet -d sendbox_fleet_test" + --health-interval 5s + --health-timeout 5s + --health-retries 12 + env: + FLEET_TEST_DATABASE_URL: postgres://sendbox_fleet@localhost:5432/sendbox_fleet_test + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Install the pinned toolchain + run: rustc --version --verbose + + - 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: Start the server against PostgreSQL and stop it gracefully + env: + FLEET_DATABASE_URL: ${{ env.FLEET_TEST_DATABASE_URL }} + FLEET_LOG_DIR: ${{ runner.temp }}/fleet-logs + run: | + cargo build --locked --bin sendbox-fleet + ./target/debug/sendbox-fleet & + server=$! + for _ in $(seq 1 30); do + curl --fail --silent http://127.0.0.1:8080/readyz >/dev/null && break + sleep 1 + done + curl --fail --silent --show-error http://127.0.0.1:8080/readyz + status=$(curl --silent --output /dev/null --write-out '%{http_code}' \ + --request POST http://127.0.0.1:8080/v1/authorize) + test "$status" = 401 + kill -TERM "$server" + wait "$server" + ls -l "$FLEET_LOG_DIR"/sendbox-fleet.*.log + + audit: + name: Dependency audit + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: taiki-e/install-action@ab49d3c64680143e184118bed66a46419fc15519 # v2.90.5 + with: + tool: cargo-audit@0.23.0 + + - name: Audit Cargo.lock + run: cargo audit --deny warnings diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..5931bcd --- /dev/null +++ b/Dockerfile @@ -0,0 +1,25 @@ +# Multi-stage build for the sendbox-fleet server. +# Base images are pinned by digest; update tag and digest together. + +FROM rust:1.93.1-slim-trixie@sha256:c0a38f5662afdb298898da1d70b909af4bda4e0acff2dc52aea6360a9b9c6956 AS build +WORKDIR /src +# rust-toolchain.toml is intentionally not copied: the image already provides +# the pinned toolchain and the build does not need clippy or rustfmt. +COPY Cargo.toml Cargo.lock ./ +COPY crates ./crates +COPY migrations ./migrations +RUN cargo build --locked --release --bin sendbox-fleet \ + && install -D -m 0755 target/release/sendbox-fleet /out/sendbox-fleet + +FROM debian:trixie-slim@sha256:a72b4433de1cf7d6bae0c4cee74d0547f58601a643b3375f070c51600d63b6b2 AS runtime +RUN groupadd --system --gid 10001 fleet \ + && useradd --system --uid 10001 --gid fleet --no-create-home \ + --home-dir /var/lib/sendbox-fleet --shell /usr/sbin/nologin fleet \ + && install -d -o fleet -g fleet -m 0700 /var/lib/sendbox-fleet /var/log/sendbox-fleet +COPY --from=build /out/sendbox-fleet /usr/local/bin/sendbox-fleet +USER 10001:10001 +WORKDIR /var/lib/sendbox-fleet +ENV FLEET_BIND=0.0.0.0:8080 \ + FLEET_LOG_DIR=/var/log/sendbox-fleet +EXPOSE 8080 +ENTRYPOINT ["/usr/local/bin/sendbox-fleet"] diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..f559cd9 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,54 @@ +# Local stack: PostgreSQL plus the fleet server. +# cp .env.example .env # then set POSTGRES_PASSWORD +# docker compose build --no-cache && docker compose up +name: sendbox-fleet + +services: + postgres: + image: postgres:18.7-alpine3.24@sha256:b6972e1115a4ff8eba5d7f7d19184926d1e16d7d1136ae1e1a7ebf286da0f015 + environment: + POSTGRES_DB: ${POSTGRES_DB:-sendbox_fleet} + POSTGRES_USER: ${POSTGRES_USER:-sendbox_fleet} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env} + volumes: + - postgres-data:/var/lib/postgresql + healthcheck: + test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\""] + interval: 5s + timeout: 3s + retries: 12 + start_period: 10s + networks: + - backend + + fleet: + build: . + image: sendbox-fleet:dev + depends_on: + postgres: + condition: service_healthy + environment: + FLEET_BIND: 0.0.0.0:8080 + # POSTGRES_PASSWORD must be URL-safe or percent-encoded. + FLEET_DATABASE_URL: postgres://${POSTGRES_USER:-sendbox_fleet}:${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}@postgres:5432/${POSTGRES_DB:-sendbox_fleet} + FLEET_LOG_DIR: /var/log/sendbox-fleet + FLEET_LOG_LEVEL: ${FLEET_LOG_LEVEL:-info} + FLEET_LOG_RETENTION_DAYS: ${FLEET_LOG_RETENTION_DAYS:-30} + ports: + - "127.0.0.1:${FLEET_PORT:-8080}:8080" + volumes: + - fleet-logs:/var/log/sendbox-fleet + read_only: true + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + networks: + - backend + +volumes: + postgres-data: + fleet-logs: + +networks: + backend: From f1182a122e16d1e6ae1d3ca94701dfa3c42a7836 Mon Sep 17 00:00:00 2001 From: mbianchidev Date: Sun, 15 Nov 2026 13:40:22 +0100 Subject: [PATCH 4/6] Document architecture, contract, threat model, roadmap, and development --- CONTRIBUTING.md | 14 ++++ README.md | 27 ++++++- SECURITY.md | 10 +++ docs/architecture.md | 171 +++++++++++++++++++++++++++++++++++++++++++ docs/contract.md | 71 ++++++++++++++++++ docs/development.md | 110 ++++++++++++++++++++++++++++ docs/roadmap.md | 83 +++++++++++++++++++++ docs/threat-model.md | 60 +++++++++++++++ 8 files changed, 545 insertions(+), 1 deletion(-) create mode 100644 CONTRIBUTING.md create mode 100644 SECURITY.md create mode 100644 docs/architecture.md create mode 100644 docs/contract.md create mode 100644 docs/development.md create mode 100644 docs/roadmap.md create mode 100644 docs/threat-model.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..f5b41f5 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,14 @@ +# Contributing + +1. Read [docs/architecture.md](docs/architecture.md) and the + [threat model](docs/threat-model.md); changes must keep the trust boundaries + (no provider credentials in this service, bearer-only authentication, + workload-supplied identity never authoritative). +2. Contract types come from `sendbox-governance`. Change them in the sendbox + repository first, then update the pin ([docs/contract.md](docs/contract.md)). +3. Schema changes need matching PostgreSQL and SQLite migrations and a test. +4. Before opening a pull request, run the checks in + [docs/development.md](docs/development.md#checks). CI runs the same + commands plus PostgreSQL and `cargo audit` jobs. +5. Use synthetic data in tests and examples; never commit real credentials, + tokens, or personal data. diff --git a/README.md b/README.md index 032bbd2..453def8 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,28 @@ # sendbox-fleet -Shared governance service for [SendBox](https://github.com/mbianchidev/sendbox) governed sessions: multi-user, operator-signed policy profiles, project-scoped roles, session admission, credential grant authorization and revocation, and central audit. This repository is currently a scaffold; see the open pull request for the initial structure. +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). + +> **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. + +## Quick start + +```sh +export FLEET_DATABASE_URL='sqlite://sendbox-fleet.db?mode=rwc' +cargo run --bin sendbox-fleet +curl http://127.0.0.1:8080/readyz +``` + +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 +- [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 +- [Contributing](CONTRIBUTING.md) and [security](SECURITY.md) + +## License + +[Apache-2.0](LICENSE) diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..6b4b673 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,10 @@ +# Security + +Please report suspected vulnerabilities privately to the repository owner +([@mbianchidev](https://github.com/mbianchidev)) rather than in issues or pull +requests. A dedicated reporting channel will be defined before this repository +is made public. + +The security design is described in [docs/threat-model.md](docs/threat-model.md). +This service is a scaffold: it authorizes nothing yet and must not be deployed +as a governance authority. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..ee3194f --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,171 @@ +# Architecture + +`sendbox-fleet` is the shared governance service for SendBox governed sessions +([mbianchidev/sendbox#87](https://github.com/mbianchidev/sendbox/issues/87)). +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). + +## Relationship to SendBox increment 1 + +Increment 1 lives in the [sendbox](https://github.com/mbianchidev/sendbox) +repository and works on a single host: + +- An operator signs a governance profile (the maximum a session may do). The + host verifies it and binds its digest and revision into the session plan. +- `LocalGrantAuthority` (in `sendbox-governance`) issues, authorizes, renews, + and revokes credential grants in process. +- The host credential broker holds provider credentials and injects them into + approved upstream requests. Agents only ever see a placeholder. + +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. + +```mermaid +flowchart LR + subgraph host["SendBox host (worker)"] + vm["Agent VM
(untrusted workload)"] + broker["Credential broker
(holds provider credentials)"] + end + fleet["sendbox-fleet
(authenticates, authorizes, audits)"] + db[("PostgreSQL")] + people["Operators and project members"] + provider["Model provider API"] + + vm -- "request with placeholder credential" --> broker + broker -- "admit / grant / authorize / revoke" --> fleet + broker -- "request with injected credential" --> provider + people -- "profiles, roles, exceptions, audit" --> fleet + fleet --> db +``` + +## Trust boundaries + +1. **Workload to host broker.** The agent VM is untrusted. It never receives + provider credentials, and it cannot choose the principal, project, session, + policy revision, or upstream that a request is attributed to. The broker + builds every `RequestContext` from trusted host state. +2. **Host to fleet.** A SendBox host is an authenticated *worker* principal. + The fleet never holds provider credentials: credential injection stays in + the host broker, and the fleet only decides (admission, grants, + per-request authorization) and records evidence. A + compromised fleet can therefore authorize misuse but cannot leak provider + keys; a compromised host is limited to the sessions and grants the fleet + issued to it. +3. **People to fleet.** Operators and project members are authenticated *user* + principals. What they may do is decided by project-scoped roles. +4. **Fleet to database.** The database stores identifiers, digests, signed + profile bytes, and audit evidence. It stores no credentials, tokens, + authorization headers, or request bodies; there are no columns for them. + +## Authentication is separate from authorization + +- **Authentication** answers "who is calling". Every `/v1` request passes + through `auth::require_bearer` *before* routing, so an unauthenticated + 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 | + +Project identifiers contain a slash (`github:owner/repo`), so clients +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. + +| 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 | +| `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 | + +`GET /healthz` (liveness) and `GET /readyz` (database round trip) are +unauthenticated and reveal nothing beyond availability. + +## Persistence + +`migrations/postgres` and `migrations/sqlite` define the same schema; the +server applies the matching set at startup. PostgreSQL is the shared +deployment target; SQLite is for local development and tests. + +| Table | Holds | +| --- | --- | +| `principals` | Authenticated users and workers (never `local-user:`) | +| `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 | +| `profile_minimum_revisions` | Oldest revision still accepted per profile | +| `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 | + +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. + +## Logging + +Structured JSON lines go to stdout and to `sendbox-fleet.YYYY-MM-DD.log` in +`FLEET_LOG_DIR`, rotated at each UTC day and pruned after 30 days. Request +bodies, headers, and query strings are never logged. Details in +[development.md](development.md#logs). + +## Code layout + +```text +crates/fleet-server/src/ + main.rs process entry: config, logging, runtime, exit codes + server.rs app assembly, startup, graceful shutdown, retention timer + config.rs environment configuration and validation + logging.rs subscriber setup and request logging middleware + logging/retention.rs + db.rs pools, migrations, readiness ping + problem.rs RFC 9457 problem responses + auth.rs bearer authentication middleware and Authenticator trait + routes/ health probes and the /v1 scaffold +migrations/{postgres,sqlite}/ +``` diff --git a/docs/contract.md b/docs/contract.md new file mode 100644 index 0000000..b82bb0d --- /dev/null +++ b/docs/contract.md @@ -0,0 +1,71 @@ +# Shared contract + +SendBox hosts and this service must agree byte-for-byte on identities, +profile references, session bindings, grants, request contexts, and +decisions. That agreement lives in one crate, `sendbox-governance`, in the +[sendbox](https://github.com/mbianchidev/sendbox) repository +(`crates/sendbox-governance`). This service depends on it instead of +redefining any of those types. + +## How it is pinned + +```toml +# Cargo.toml (workspace) +sendbox-governance = { git = "https://github.com/mbianchidev/sendbox", rev = "bd7498ab24c3c9cfd98f80349bee31fed667539b" } +``` + +- The dependency is pinned to an exact commit, and `Cargo.lock` records it, so + every build sees the same contract. A contract change is always a deliberate + pin update in a reviewed pull request. +- `sendbox-governance` inherits versions from the sendbox workspace and + depends on `sendbox-core` by path; Cargo resolves both from the same git + checkout. +- The pinned commit is on the increment-1 branch + `cp-desktop-governed-sessions-policy-profiles`. Once that work merges, move + the pin to the merged commit on `main` (or a tag) so the revision cannot + disappear if the branch is rewritten or deleted. + +To update the pin: + +```sh +# edit `rev` in Cargo.toml, then +cargo update -p sendbox-governance +cargo test --locked --workspace +``` + +## What the API reuses + +| Contract type | Used by | +| --- | --- | +| `GovernanceBinding`, `AuthorityRef`, `SessionRef` | `POST /v1/sessions:admit` 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` | +| `ProjectId`, `PrincipalId` | Role, exception, and audit endpoints | +| `Sha256Digest` | Digests in responses and audit events | + +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. + +## Versioning + +- `sendbox_governance::CONTRACT_VERSION` (currently `1`) 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 + computed requires bumping `CONTRACT_VERSION` in the sendbox repository and + then updating this pin; hosts and the fleet must be upgraded together or + support both versions during the transition. +- The `/v1` path prefix versions the HTTP API surface (routes, fleet-only + types, problem format). It changes independently of `CONTRACT_VERSION`. diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..8ac7d8f --- /dev/null +++ b/docs/development.md @@ -0,0 +1,110 @@ +# Development + +## Prerequisites + +- [rustup](https://rustup.rs). The pinned toolchain (Rust 1.93.1 with clippy + and rustfmt) installs automatically from `rust-toolchain.toml`. +- A Docker-compatible engine with Compose, only for the PostgreSQL stack. + +## Configuration + +The server reads its configuration from the environment at startup and exits +with status `2` and a message naming the variable when a value is invalid. + +| Variable | Default | Meaning | +| --- | --- | --- | +| `FLEET_DATABASE_URL` | required | `sqlite://path.db?mode=rwc`, `sqlite::memory:`, or `postgres://user:password@host:5432/db` | +| `FLEET_BIND` | `127.0.0.1:8080` | Listen address | +| `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) | + +Database credentials in `FLEET_DATABASE_URL` are never logged. + +## Run locally with SQLite + +```sh +export FLEET_DATABASE_URL='sqlite://sendbox-fleet.db?mode=rwc' +cargo run --bin sendbox-fleet + +curl -i http://127.0.0.1:8080/healthz +curl -i http://127.0.0.1:8080/readyz +curl -i -X POST http://127.0.0.1:8080/v1/authorize # 401: authentication required +``` + +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. + +## Run with PostgreSQL (Compose) + +```sh +cp .env.example .env # set POSTGRES_PASSWORD (URL-safe characters) +docker compose build --no-cache && docker compose up +``` + +The server listens on `127.0.0.1:${FLEET_PORT:-8080}`. The container runs as +an unprivileged user with a read-only root filesystem; logs go to the +`fleet-logs` volume. `docker compose down` stops the stack and keeps data; +`docker compose down --volumes` also deletes the database and logs. + +## Checks + +```sh +cargo fmt --all -- --check +cargo clippy --locked --workspace --all-targets -- -D warnings +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): + +```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 +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 +`cargo audit`. + +## Logs + +- Every event is a JSON line written to stdout and to + `FLEET_LOG_DIR/sendbox-fleet.YYYY-MM-DD.log`. The live file is the one for + the current UTC date; a new file starts at each UTC midnight. +- Retention runs at startup and then hourly. It deletes only regular files + named `sendbox-fleet.YYYY-MM-DD.log` whose UTC day ended at least + `FLEET_LOG_RETENTION_DAYS` days ago, judged by the date in the name rather + than the modification time. Other files, directories, and symlinks are left + alone; deletion failures are logged and retried at the next run. +- The log directory is created with mode `0700`. +- File writes go through a bounded queue of 16,384 events. When it is full, + logging callers wait instead of dropping events. +- Never logged: request bodies, headers (including `Authorization`), query + strings, and database credentials. +- Rotation is daily only; size-based rotation is a roadmap item. + +## Migrations + +Schema changes need a new, numbered file in **both** `migrations/postgres` and +`migrations/sqlite` with equivalent constraints. Never edit a migration that +has been applied anywhere: sqlx records checksums and refuses to start on a +mismatch. Add a test in `crates/fleet-server/tests/migrations.rs` for any new +invariant. + +## Troubleshooting + +| Symptom | Cause | +| --- | --- | +| `configuration error: FLEET_DATABASE_URL is required` (exit 2) | Export a database URL | +| `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 | diff --git a/docs/roadmap.md b/docs/roadmap.md new file mode 100644 index 0000000..00fc1b7 --- /dev/null +++ b/docs/roadmap.md @@ -0,0 +1,83 @@ +# Roadmap + +Increment-2 work for +[mbianchidev/sendbox#87](https://github.com/mbianchidev/sendbox/issues/87). +Each item names the issue's acceptance criteria (AC) it serves: + +- **AC1** A trusted shared profile is enforced at actual session admission and + execution; project configuration and CLI flags cannot broaden or bypass it. +- **AC4** Cross-principal, project, or session requests, changed policy + bindings, and forbidden destinations, methods, or paths are rejected at the + enforcement boundary. +- **AC5** Expired or revoked grants, stale policy, and unavailable + authorization produce explicit denial without credential export or fallback. +- **AC6** Session cancellation and teardown end grants while preserving + redacted audit evidence and reporting uncertain external outcomes honestly. +- **AC7** The shared-service increment enforces project-scoped roles and + authorized, expiring exceptions with attributable audit records. +- **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. + +## Work items + +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`. + +## Non-goals + +Kubernetes or fleet scheduling, universal TLS interception, formal policy +verification, and replacing SendBox isolation providers (as in the issue). +The service never stores or forwards provider credentials. diff --git a/docs/threat-model.md b/docs/threat-model.md new file mode 100644 index 0000000..37df5cd --- /dev/null +++ b/docs/threat-model.md @@ -0,0 +1,60 @@ +# Threat model + +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** +means designed but not implemented (see [roadmap.md](roadmap.md)). + +## Assets + +- Authorization decisions: session admission, grants, per-request decisions. +- Policy state: signed profile revisions, minimum revisions, project roles, + exceptions. +- Audit evidence and its integrity. +- Availability of authorization for running sessions. + +Provider credentials are **not** an asset of this service: they stay in the +SendBox host broker and never reach the fleet. + +## Actors + +| Actor | Trust | +| --- | --- | +| Operator | Trusted to sign and publish profiles | +| Project owner, admin, member, viewer | Trusted within their project role | +| Worker (SendBox host) | Trusted to report its own sessions; untrusted for anything else | +| 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 | + +## Threats and mitigations + +| # | 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 | + +## Known accepted risks + +- `RUSTSEC-2026-0459` (bundled SQLite older than 3.54): SQLite is used only + for local development and tests on files the service creates. Fixing it + needs sqlx 0.9, which needs Rust 1.94; this workspace matches SendBox's + pinned Rust 1.93.1. Tracked in [roadmap.md](roadmap.md). +- `RUSTSEC-2023-0071` (`rsa`): present in `Cargo.lock` only through sqlx's + optional MySQL support and never compiled. +- Database triggers do not stop a database superuser. Production must run the + service with a least-privilege role, and chain heads must be anchored + outside the database. From 9d0dfeb5e0f810d1f3deee81c6e49ad473b817d8 Mon Sep 17 00:00:00 2001 From: mbianchidev Date: Sun, 15 Nov 2026 14:52:15 +0100 Subject: [PATCH 5/6] Pin sendbox-governance to merged sendbox main commit --- Cargo.lock | 4 ++-- Cargo.toml | 2 +- docs/contract.md | 10 +++++----- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9ae60c0..d8e4516 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1447,7 +1447,7 @@ checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" [[package]] name = "sendbox-core" version = "0.2.7" -source = "git+https://github.com/mbianchidev/sendbox?rev=bd7498ab24c3c9cfd98f80349bee31fed667539b#bd7498ab24c3c9cfd98f80349bee31fed667539b" +source = "git+https://github.com/mbianchidev/sendbox?rev=98172513625384ad2f79c238aaefb7d6e0dde752#98172513625384ad2f79c238aaefb7d6e0dde752" dependencies = [ "serde", ] @@ -1455,7 +1455,7 @@ dependencies = [ [[package]] name = "sendbox-governance" version = "0.2.7" -source = "git+https://github.com/mbianchidev/sendbox?rev=bd7498ab24c3c9cfd98f80349bee31fed667539b#bd7498ab24c3c9cfd98f80349bee31fed667539b" +source = "git+https://github.com/mbianchidev/sendbox?rev=98172513625384ad2f79c238aaefb7d6e0dde752#98172513625384ad2f79c238aaefb7d6e0dde752" dependencies = [ "sendbox-core", "serde", diff --git a/Cargo.toml b/Cargo.toml index 0dc3745..643bf39 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ publish = false [workspace.dependencies] actix-http = { version = "3.21.0", default-features = false } actix-web = { version = "4.19.0", default-features = false, features = ["macros"] } -sendbox-governance = { git = "https://github.com/mbianchidev/sendbox", rev = "bd7498ab24c3c9cfd98f80349bee31fed667539b" } +sendbox-governance = { git = "https://github.com/mbianchidev/sendbox", rev = "98172513625384ad2f79c238aaefb7d6e0dde752" } 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/docs/contract.md b/docs/contract.md index b82bb0d..e22ca9d 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -11,7 +11,7 @@ redefining any of those types. ```toml # Cargo.toml (workspace) -sendbox-governance = { git = "https://github.com/mbianchidev/sendbox", rev = "bd7498ab24c3c9cfd98f80349bee31fed667539b" } +sendbox-governance = { git = "https://github.com/mbianchidev/sendbox", rev = "98172513625384ad2f79c238aaefb7d6e0dde752" } ``` - The dependency is pinned to an exact commit, and `Cargo.lock` records it, so @@ -20,10 +20,10 @@ sendbox-governance = { git = "https://github.com/mbianchidev/sendbox", rev = "bd - `sendbox-governance` inherits versions from the sendbox workspace and depends on `sendbox-core` by path; Cargo resolves both from the same git checkout. -- The pinned commit is on the increment-1 branch - `cp-desktop-governed-sessions-policy-profiles`. Once that work merges, move - the pin to the merged commit on `main` (or a tag) so the revision cannot - disappear if the branch is rewritten or deleted. +- The pinned commit is the merge of increment 1 + ([mbianchidev/sendbox#93](https://github.com/mbianchidev/sendbox/pull/93)) + on sendbox `main`, so the revision cannot disappear when feature branches + are rewritten or deleted. Only pin to commits on `main` or to release tags. To update the pin: From 11bea9268b04d0dc8437450788095093b29618c0 Mon Sep 17 00:00:00 2001 From: mbianchidev Date: Sun, 15 Nov 2026 14:57:00 +0100 Subject: [PATCH 6/6] Track sendbox main for the contract with Dependabot auto-merge Cargo.toml tracks sendbox main; Cargo.lock keeps the exact commit (9817251, the increment-1 merge). Dependabot moves the lockfile daily and an auto-merge workflow merges those updates once required CI passes. SECURITY.md now points to GitHub private vulnerability reporting. --- .github/dependabot.yml | 12 +++++++++ .github/workflows/dependabot-auto-merge.yml | 28 +++++++++++++++++++++ Cargo.lock | 4 +-- Cargo.toml | 2 +- SECURITY.md | 8 +++--- docs/contract.md | 24 ++++++++++-------- 6 files changed, 61 insertions(+), 17 deletions(-) create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/dependabot-auto-merge.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..1a02152 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +version: 2 +updates: + # Keeps the sendbox-governance contract on the latest sendbox `main` commit. + # See docs/contract.md. + - package-ecosystem: cargo + directory: / + schedule: + interval: daily + allow: + - dependency-name: sendbox-governance + commit-message: + prefix: "Bump contract" diff --git a/.github/workflows/dependabot-auto-merge.yml b/.github/workflows/dependabot-auto-merge.yml new file mode 100644 index 0000000..7cdb818 --- /dev/null +++ b/.github/workflows/dependabot-auto-merge.yml @@ -0,0 +1,28 @@ +name: Dependabot auto-merge + +on: pull_request + +permissions: + contents: read + +jobs: + contract-pin: + name: Auto-merge sendbox-governance pin updates + if: github.event.pull_request.user.login == 'dependabot[bot]' && github.repository == 'mbianchidev/sendbox-fleet' + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: write + pull-requests: write + steps: + - name: Read Dependabot metadata + id: metadata + uses: dependabot/fetch-metadata@25dd0e34f4fe68f24cc83900b1fe3fe149efef98 # v3.1.0 + + # Branch protection holds the merge until every required CI job passes. + - name: Enable auto-merge + if: steps.metadata.outputs.dependency-names == 'sendbox-governance' + run: gh pr merge --auto --squash "$PR_URL" + env: + PR_URL: ${{ github.event.pull_request.html_url }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/Cargo.lock b/Cargo.lock index d8e4516..07f304d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1447,7 +1447,7 @@ checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" [[package]] name = "sendbox-core" version = "0.2.7" -source = "git+https://github.com/mbianchidev/sendbox?rev=98172513625384ad2f79c238aaefb7d6e0dde752#98172513625384ad2f79c238aaefb7d6e0dde752" +source = "git+https://github.com/mbianchidev/sendbox?branch=main#98172513625384ad2f79c238aaefb7d6e0dde752" dependencies = [ "serde", ] @@ -1455,7 +1455,7 @@ dependencies = [ [[package]] name = "sendbox-governance" version = "0.2.7" -source = "git+https://github.com/mbianchidev/sendbox?rev=98172513625384ad2f79c238aaefb7d6e0dde752#98172513625384ad2f79c238aaefb7d6e0dde752" +source = "git+https://github.com/mbianchidev/sendbox?branch=main#98172513625384ad2f79c238aaefb7d6e0dde752" dependencies = [ "sendbox-core", "serde", diff --git a/Cargo.toml b/Cargo.toml index 643bf39..ff81e29 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ publish = false [workspace.dependencies] actix-http = { version = "3.21.0", default-features = false } actix-web = { version = "4.19.0", default-features = false, features = ["macros"] } -sendbox-governance = { git = "https://github.com/mbianchidev/sendbox", rev = "98172513625384ad2f79c238aaefb7d6e0dde752" } +sendbox-governance = { git = "https://github.com/mbianchidev/sendbox", branch = "main" } 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/SECURITY.md b/SECURITY.md index 6b4b673..242b5a2 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,9 +1,9 @@ # Security -Please report suspected vulnerabilities privately to the repository owner -([@mbianchidev](https://github.com/mbianchidev)) rather than in issues or pull -requests. A dedicated reporting channel will be defined before this repository -is made public. +Please report suspected vulnerabilities privately through +[GitHub private vulnerability reporting](https://github.com/mbianchidev/sendbox-fleet/security/advisories/new) +(the repository's **Security** tab, then **Report a vulnerability**). Do not +open public issues or pull requests for vulnerabilities. The security design is described in [docs/threat-model.md](docs/threat-model.md). This service is a scaffold: it authorizes nothing yet and must not be deployed diff --git a/docs/contract.md b/docs/contract.md index e22ca9d..8189f57 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -11,25 +11,29 @@ redefining any of those types. ```toml # Cargo.toml (workspace) -sendbox-governance = { git = "https://github.com/mbianchidev/sendbox", rev = "98172513625384ad2f79c238aaefb7d6e0dde752" } +sendbox-governance = { git = "https://github.com/mbianchidev/sendbox", branch = "main" } ``` -- The dependency is pinned to an exact commit, and `Cargo.lock` records it, so - every build sees the same contract. A contract change is always a deliberate - pin update in a reviewed pull request. +- The dependency tracks sendbox `main`, and `Cargo.lock` records the exact + commit. CI builds with `--locked`, so every build sees the same contract + until the lockfile moves. +- [Dependabot](../.github/dependabot.yml) checks sendbox `main` daily and opens + a pull request that moves `Cargo.lock` to the latest commit. The + [auto-merge workflow](../.github/workflows/dependabot-auto-merge.yml) enables + auto-merge on those pull requests, and branch protection merges them only + after every CI job passes. A contract change that breaks this service leaves + the pull request open with failing checks for a maintainer to fix. - `sendbox-governance` inherits versions from the sendbox workspace and depends on `sendbox-core` by path; Cargo resolves both from the same git checkout. -- The pinned commit is the merge of increment 1 - ([mbianchidev/sendbox#93](https://github.com/mbianchidev/sendbox/pull/93)) - on sendbox `main`, so the revision cannot disappear when feature branches - are rewritten or deleted. Only pin to commits on `main` or to release tags. +- Only `main` is tracked, so the recorded commit cannot disappear when sendbox + feature branches are rewritten or deleted. -To update the pin: +To move the lockfile by hand, to the latest `main` commit or to a specific one: ```sh -# edit `rev` in Cargo.toml, then cargo update -p sendbox-governance +cargo update -p sendbox-governance --precise cargo test --locked --workspace ```