Files
tessera/crates/tessera-hub/src/auth.rs
Adnan Zahir da46453c13 feat: durable refresh runs from a source to a staging target (auth M6c)
A refresh captures a new dump of the relation's source, then restores exactly that
snapshot onto the relation's target through the existing restore path.

- refresh_runs in SQLite, one active run per target, per-requester idempotency keys,
  a cap on concurrent runs and a TTL that only applies until the restore starts overwriting
- the run and its capture job are created in one transaction; the run follows its own
  capture job, never the latest snapshot, and pins that snapshot until it ends
- the restore is queued and linked in one guarded transaction; every step is safe to repeat
  after a crash; a background driver only reads the database
- authorize_apply re-checks, in the transaction that allows the overwrite, that the relation
  is still usable, the requester is still active, the authorising grant still exists, the
  deadline has not passed and the target is not the source; otherwise the restore is
  cancelled, the run is blocked and the agent gets 409. Administrator restores are untouched
- POST/GET/DELETE /api/v1/refresh-runs: confirmation names source, target and version;
  non-administrators never see the snapshot id, the requester or the database identity
- audit refresh.* per run

Tests drive the agent through the real Outpost endpoints and cover revocation at every
stage; the access matrix gains a RunRow kind.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-14 18:23:13 +07:00

214 lines
7.3 KiB
Rust

//! Server-derived identities and payload-free audit records.
use uuid::Uuid;
#[derive(Clone, Debug)]
pub enum Principal {
Emergency(String),
/// OIDC user, by stable `users.id` (never by a name supplied by the IdP).
Oidc(String),
Service(&'static str),
Outpost(Uuid),
Anonymous,
LocalDevelopment,
}
impl Principal {
pub fn fields(&self) -> (String, &'static str, &'static str) {
match self {
Self::Emergency(name) => (format!("emergency:{name}"), "user", "password"),
Self::Oidc(id) => (format!("oidc:{id}"), "user", "oidc"),
Self::Service(id) => (id.to_string(), "service", "api_token"),
Self::Outpost(id) => (id.to_string(), "outpost", "outpost_token"),
Self::Anonymous => ("anonymous".into(), "anonymous", "none"),
Self::LocalDevelopment => ("local-development".into(), "service", "development"),
}
}
}
pub enum AuditAction {
Authentication,
Authorization,
Login,
Logout,
OutpostBind,
OutpostPair,
CredentialRotate,
CredentialRevoke,
GrantCreate,
GrantDelete,
UserState,
SessionsRevoke,
ExportRequested,
ExportReady,
ExportFinished,
ExportDisconnected,
EnvironmentSet,
RelationCreate,
RelationRetarget,
RelationDeactivate,
RelationGrantCreate,
RelationGrantDelete,
/// One of the refresh run's states or steps; the name is the audit action (`refresh.completed`, ...).
RefreshEvent(&'static str),
}
impl AuditAction {
pub fn as_str(&self) -> &'static str {
match self {
Self::Authentication => "authentication.check",
Self::Authorization => "authorization.check",
Self::Login => "auth.login",
Self::Logout => "auth.logout",
Self::OutpostBind => "orbit.outpost_bind",
Self::OutpostPair => "outpost.pair",
Self::CredentialRotate => "outpost.credential_rotate",
Self::CredentialRevoke => "outpost.credential_revoke",
Self::GrantCreate => "access.grant_create",
Self::GrantDelete => "access.grant_delete",
Self::UserState => "access.user_state",
Self::SessionsRevoke => "access.sessions_revoke",
Self::ExportRequested => "export.requested",
Self::ExportReady => "export.ready",
Self::ExportFinished => "export.finished",
Self::ExportDisconnected => "export.disconnected",
Self::EnvironmentSet => "environment.set",
Self::RelationCreate => "relation.create",
Self::RelationRetarget => "relation.retarget",
Self::RelationDeactivate => "relation.deactivate",
Self::RelationGrantCreate => "relation.grant_create",
Self::RelationGrantDelete => "relation.grant_delete",
Self::RefreshEvent(name) => name,
}
}
}
pub enum AuditOutcome {
Allowed,
Denied,
Succeeded,
Failed,
}
impl AuditOutcome {
pub fn as_str(&self) -> &'static str {
match self {
Self::Allowed => "allowed",
Self::Denied => "denied",
Self::Succeeded => "succeeded",
Self::Failed => "failed",
}
}
}
pub enum AuditResource {
Api,
Session,
Orbit(Uuid),
Outpost(Uuid),
UploadSession(Uuid),
Grant(Uuid),
User(Uuid),
Snapshot(Uuid),
Relation(Uuid),
RestoreTarget(Uuid),
RefreshRun(Uuid),
}
impl AuditResource {
pub fn fields(&self) -> (&'static str, Option<String>) {
match self {
Self::Api => ("api", None),
Self::Session => ("session", None),
Self::Orbit(id) => ("orbit", Some(id.to_string())),
Self::Outpost(id) => ("outpost", Some(id.to_string())),
Self::UploadSession(id) => ("upload_session", Some(id.to_string())),
Self::Grant(id) => ("grant", Some(id.to_string())),
Self::User(id) => ("user", Some(id.to_string())),
Self::Snapshot(id) => ("snapshot", Some(id.to_string())),
Self::Relation(id) => ("relation", Some(id.to_string())),
Self::RestoreTarget(id) => ("restore_target", Some(id.to_string())),
Self::RefreshRun(id) => ("refresh_run", Some(id.to_string())),
}
}
}
/// What a signed-in user may do. Only the first four can be granted to a
/// non-administrator; everything else belongs to the configured administrators
/// (SSO admin mapping, the emergency operator, the legacy admin token). Names are
/// matched exactly, never by prefix.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum Permission {
OrbitRead,
SnapshotRead,
CaptureRun,
SnapshotDownload,
OrbitManage,
OutpostManage,
RetentionManage,
SnapshotDelete,
RecoveryManage,
AccessManage,
/// Configuring environments and relations. Administrators only.
RelationManage,
/// Refreshing a staging target. Never held through `access_grants`: it is granted per relation, in `relation_grants`.
RefreshRun,
}
impl Permission {
pub fn as_str(self) -> &'static str {
match self {
Self::OrbitRead => "orbit.read",
Self::SnapshotRead => "snapshot.read",
Self::CaptureRun => "capture.run",
Self::SnapshotDownload => "snapshot.download",
Self::OrbitManage => "orbit.manage",
Self::OutpostManage => "outpost.manage",
Self::RetentionManage => "retention.manage",
Self::SnapshotDelete => "snapshot.delete",
Self::RecoveryManage => "recovery.manage",
Self::AccessManage => "access.manage",
Self::RelationManage => "relation.manage",
Self::RefreshRun => "refresh.run",
}
}
pub fn parse(text: &str) -> Option<Self> {
[
Self::OrbitRead, Self::SnapshotRead, Self::CaptureRun, Self::SnapshotDownload, Self::OrbitManage,
Self::OutpostManage, Self::RetentionManage, Self::SnapshotDelete, Self::RecoveryManage, Self::AccessManage, Self::RelationManage, Self::RefreshRun,
]
.into_iter()
.find(|permission| permission.as_str() == text)
}
/// May be given to a non-administrator through a grant.
pub fn grantable(self) -> bool {
matches!(self, Self::OrbitRead | Self::SnapshotRead | Self::CaptureRun | Self::SnapshotDownload)
}
}
/// Named bundles that expand into individual grants. Every bundle includes
/// `orbit.read`: without it a resource is invisible and answers 404.
pub fn role(name: &str) -> Option<&'static [Permission]> {
use Permission::*;
match name {
"viewer" => Some(&[OrbitRead, SnapshotRead]),
"capturer" => Some(&[OrbitRead, SnapshotRead, CaptureRun]),
"downloader" => Some(&[OrbitRead, SnapshotRead, SnapshotDownload]),
_ => None,
}
}
pub const ROLE_NAMES: [&str; 3] = ["viewer", "capturer", "downloader"];
/// Who is asking, as far as authorization is concerned.
#[derive(Clone, Debug)]
pub struct Subject {
/// `users.id` for signed-in users; `None` for the legacy token and local development.
pub user_id: Option<String>,
/// Groups verified at sign-in. Changes at the IdP apply at the next sign-in.
pub groups: Vec<String>,
/// Configured administrator: holds every permission everywhere.
pub admin: bool,
}