From 93381ad1224d517b772142a626d014536aeafc16 Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 16:03:51 +0100 Subject: [PATCH] feat(permissions): tell callers what they may do, and issue scoped tokens With callers told apart, they need a way to see what the policy lets them do, and to hand an agent or a CI runner less than that. `OriginService::rights` resolves a caller's rights from the policy in force, kept until `policy` moves, narrowed by their token's scope: the owner has every right. `GET whoami` returns them, and `POST tokens` issues a token acting for the caller with a scope their rights must cover, refused with the new `forbidden` error code otherwise. A token lasts at most 7 days, and one issued with a scoped token never outlasts it, so no token renews itself. An operator signs tokens for any principal with the server's key, `origin token issue --config --as `, to give agents identities of their own. On the command line, `origin whoami` and `origin permissions` show what the remote says, and `origin token issue --scope ...` asks it for a token. --- AGENTS.md | 6 + README.md | 10 + apps/origin-src/src/cli.rs | 59 +++++- apps/origin-src/src/http.rs | 58 +++++- apps/origin-src/src/permissions.rs | 11 + apps/origin-src/src/remote.rs | 11 +- apps/origin-src/src/server.rs | 49 ++++- apps/origin-src/src/service.rs | 163 ++++++++++++--- apps/origin-src/src/workspace/access.rs | 99 +++++++++ apps/origin-src/src/workspace/mod.rs | 1 + apps/origin-src/src/workspace/remote.rs | 2 +- apps/origin-src/tests/http.rs | 76 ++++++- crates/origin-client/src/lib.rs | 10 +- crates/origin-shared/src/api.rs | 29 ++- docs/openapi.json | 254 ++++++++++++++++++++++++ 15 files changed, 789 insertions(+), 49 deletions(-) create mode 100644 apps/origin-src/src/workspace/access.rs diff --git a/AGENTS.md b/AGENTS.md index 99cad280..48642239 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,6 +25,12 @@ review bots read and write at the same time, written in Rust. - `tools/xtask`: development tasks, run with `cargo xtask`, such as timing origin against git (`just bench-git`). +## API changes + +Every server feature lives in `OriginService`; transports like HTTP only +translate requests. A new HTTP endpoint also takes a line in the SDK's +`endpoints!` macro, and `just openapi` to update `docs/openapi.json`. + ## Testing & Benchmarks Performance is a primary goal, so benchmarks matter as much as tests. A change diff --git a/README.md b/README.md index ad153afa..dba5a33f 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,8 @@ origin remote [] # show or set the remote: http://host:port/< origin push [...] # share changes and the ones below them; lands nothing origin fetch [--target ] [--change ] # new acceptances, and the records of known changes origin pull # fetch, then move the working copy onto its target's tip +origin whoami | permissions # who the remote thinks you are, and what you may do there +origin token issue --scope "write src" [--ttl 1h] # a short-lived token for an agent ``` Landing rebases a change onto the target's tip, file by file, checks the @@ -115,6 +117,14 @@ send each server under `[tokens]`, by its URL (`"http://127.0.0.1:7878" = ""`), or in `$ORIGIN_TOKEN`. See [the design](docs/design.md) for the model. +`origin token issue --scope ... --ttl ` asks the remote +for a token acting for you with a narrower scope, such as `write src`, +`read /`, `annotate ci.*`, `land main` or `admin`; the server verifies it +without storing it. A server's operator signs one for any principal with +`origin token issue --config origin-server.toml --as user:agent-1 --scope +...`. A token never grants more than its principal's rights, lasts at most +7 days, and a token issued with a token expires with it. + `converge` merges the files of a change's heads. A text file two heads changed holds both versions between conflict markers (`<<<<<<<`, `=======`, `>>>>>>>`), and a binary one keeps one side. A `core.conflict` statement diff --git a/apps/origin-src/src/cli.rs b/apps/origin-src/src/cli.rs index 1499ea1e..ef22947d 100644 --- a/apps/origin-src/src/cli.rs +++ b/apps/origin-src/src/cli.rs @@ -9,8 +9,11 @@ use std::str::FromStr; use anyhow::{Context, Result}; use clap::error::ErrorKind; use clap::{Args, CommandFactory, Parser, Subcommand}; +use origin_shared::access::Capability; use origin_shared::policy::KindPattern; -use origin_shared::{ChangeId, Digest, Inputs, Kind, RepoPath, TargetName, Verdict}; +use origin_shared::{ + ChangeId, Digest, Inputs, Kind, Period, Principal, RepoPath, TargetName, Verdict, +}; use crate::config::UserConfig; use crate::oplog::Actor; @@ -54,6 +57,9 @@ enum Command { /// Manage the repositories a server hosts. #[command(subcommand)] Repo(RepoCommand), + /// Manage tokens. + #[command(subcommand)] + Token(TokenCommand), #[command(flatten)] Workspace(WorkspaceCommand), } @@ -71,6 +77,29 @@ enum RepoCommand { }, } +#[derive(Debug, Subcommand)] +enum TokenCommand { + /// Issue a short-lived token with a narrower scope, for an agent or a + /// CI runner: the remote signs one acting for you, or, with + /// `--config`, a server signs one for anyone. + Issue { + /// A capability: `read `, `write `, `annotate `, + /// `land `, `land *` or `admin`. Repeat it for several. + #[arg(long, required = true)] + scope: Vec, + /// How long it lasts, such as `1h` or `7d`, the most a token lasts. + #[arg(long, default_value = "1h")] + ttl: Period, + /// Sign it with the key of the server this configuration file + /// describes, instead of asking the remote. + #[arg(short, long, requires = "principal")] + config: Option, + /// Who it acts for, with `--config`, such as `user:agent-1`. + #[arg(long = "as", requires = "config")] + principal: Option, + }, +} + /// Commands run in the repository containing the current directory. Those /// that read the working copy snapshot it first. Changes are named by a /// unique prefix of their id, or `@` for the working copy's. @@ -206,6 +235,11 @@ enum WorkspaceCommand { /// change went, or onto its target's new tip, with the edits made /// since. Pull, + /// Show who the remote thinks you are. + Whoami, + /// Show what the remote lets you do: the paths you read and write, the + /// statements you issue, and the targets you land on. + Permissions, /// Share changes with the remote, with the changes below them: their /// revisions, files and statements. Lands nothing. Push { @@ -487,7 +521,22 @@ impl Cli { Command::Repo(RepoCommand::Create { path, config }) => { return ServerConfig::load(&config)?.create_repo(&path); } - Command::Init { .. } | Command::Clone { .. } | Command::Workspace(_) => {} + Command::Token(TokenCommand::Issue { + scope, + ttl, + config: Some(config), + principal: Some(principal), + }) => { + println!( + "{}", + ServerConfig::load(&config)?.issue_token(principal, scope, ttl.0)? + ); + return Ok(()); + } + Command::Init { .. } + | Command::Clone { .. } + | Command::Token(_) + | Command::Workspace(_) => {} } let config = UserConfig::load()?; // The op log records the command line, without the program's name, @@ -506,6 +555,10 @@ impl Cli { Workspace::clone(&url, path.as_deref(), &target, config, &actor)?; } Command::Workspace(command) => command.run(config, &actor)?, + Command::Token(TokenCommand::Issue { scope, ttl, .. }) => { + let cwd = env::current_dir().context("cannot read the current directory")?; + Workspace::discover(&cwd, config, &actor)?.issue_token(scope, ttl)?; + } Command::Serve { .. } | Command::Repo(_) => unreachable!("run above"), } Ok(()) @@ -564,6 +617,8 @@ impl WorkspaceCommand { Self::Remote { url } => workspace.set_remote(url.as_deref())?, Self::Fetch { target, change } => workspace.fetch(&target, &change)?, Self::Pull => workspace.pull()?, + Self::Whoami => workspace.whoami()?, + Self::Permissions => workspace.permissions()?, Self::Push { changes } => workspace.push(&changes)?, Self::Watch { kind, diff --git a/apps/origin-src/src/http.rs b/apps/origin-src/src/http.rs index 7245dd99..8f2a6f5e 100644 --- a/apps/origin-src/src/http.rs +++ b/apps/origin-src/src/http.rs @@ -16,11 +16,11 @@ use axum::http::{StatusCode, header}; use axum::response::{IntoResponse, Response}; use origin_shared::ChangeId; use origin_shared::Head; -use origin_shared::access::InvalidToken; +use origin_shared::access::{InvalidToken, Rights}; use origin_shared::api::{ Annotation, ApiError, ErrorCode, EventsQuery, FetchRecords, FetchSnapshot, Inventory, - InventoryRequest, LandRequest, Landings, LogEntry, LogQuery, MORE, NewTarget, PutQuery, - RepoName, RepoSummary, Revisions, StatementsQuery, Stored, TargetInfo, + InventoryRequest, IssuedToken, LandRequest, Landings, LogEntry, LogQuery, MORE, NewTarget, + PutQuery, RepoName, RepoSummary, Revisions, StatementsQuery, Stored, TargetInfo, TokenRequest, }; use origin_shared::event::Page; use origin_shared::landing::Pending; @@ -68,6 +68,8 @@ impl Api { .routes(routes!(land)) .routes(routes!(landings)) .routes(routes!(events)) + .routes(routes!(whoami)) + .routes(routes!(issue_token)) .routes(routes!(openapi_document)) } @@ -152,6 +154,7 @@ impl IntoResponse for HttpError { ErrorCode::Conflict => StatusCode::CONFLICT, ErrorCode::Expired => StatusCode::GONE, ErrorCode::Unauthorized => StatusCode::UNAUTHORIZED, + ErrorCode::Forbidden => StatusCode::FORBIDDEN, ErrorCode::Internal => StatusCode::INTERNAL_SERVER_ERROR, }; (status, Json(ApiError { code, message })).into_response() @@ -515,6 +518,55 @@ async fn events( .map(Json) } +/// Tells the caller who they are and what they may do in the repository. +#[utoipa::path( + get, + path = "/api/v1/repos/{repo}/whoami", + operation_id = "whoami", + params(("repo" = String, Path, description = "The repository")), + responses( + (status = 200, description = "The caller's rights", body = Rights), + (status = 401, description = "The token is invalid or expired", body = ApiError), + (status = 404, description = "The repository does not exist", body = ApiError) + ) +)] +async fn whoami( + repos: Repos, + Path(repo): Path, + caller: Caller, +) -> Result, HttpError> { + call(repos, repo, caller, OriginService::whoami) + .await + .map(Json) +} + +/// Issues a token acting for the caller, with a scope narrowing their +/// rights, signed by the server, which verifies it without storing it. +#[utoipa::path( + post, + path = "/api/v1/repos/{repo}/tokens", + operation_id = "issue_token", + params(("repo" = String, Path, description = "The repository whose policy the scope is checked against")), + request_body = TokenRequest, + responses( + (status = 200, description = "The token", body = IssuedToken), + (status = 403, description = "The caller isn't signed in, or the scope reaches beyond their rights", body = ApiError), + (status = 404, description = "The repository does not exist", body = ApiError) + ) +)] +async fn issue_token( + repos: Repos, + Path(repo): Path, + caller: Caller, + Json(request): Json, +) -> Result, HttpError> { + call(repos, repo, caller, move |service, caller| { + service.issue_token(caller, &request) + }) + .await + .map(Json) +} + /// The OpenAPI document of this API. #[utoipa::path( get, diff --git a/apps/origin-src/src/permissions.rs b/apps/origin-src/src/permissions.rs index 4fec7a4f..8bd7cca4 100644 --- a/apps/origin-src/src/permissions.rs +++ b/apps/origin-src/src/permissions.rs @@ -42,3 +42,14 @@ impl Caller { } } } + +/// Something a caller may not do. +#[derive(Debug, PartialEq, Eq, thiserror::Error)] +pub enum Forbidden { + /// The owner has no principal to issue a token for. + #[error("only a signed-in caller gets a token, for themselves")] + NoPrincipal, + /// A token's scope reaches beyond its issuer's rights. + #[error("a token may only narrow your rights, which don't include `{0}`")] + Scope(Capability), +} diff --git a/apps/origin-src/src/remote.rs b/apps/origin-src/src/remote.rs index 011710f0..1093f7a1 100644 --- a/apps/origin-src/src/remote.rs +++ b/apps/origin-src/src/remote.rs @@ -12,9 +12,11 @@ use std::path::{self, Path, PathBuf}; use origin_client::Client; use origin_shared::Head; +use origin_shared::access::Rights; use origin_shared::api::{ - ErrorCode, EventsQuery, FetchRecords, FetchSnapshot, Inventory, InventoryRequest, LandRequest, - Landings, LogEntry, LogQuery, NewTarget, PutQuery, RepoName, Stored, TargetInfo, + ErrorCode, EventsQuery, FetchRecords, FetchSnapshot, Inventory, InventoryRequest, IssuedToken, + LandRequest, Landings, LogEntry, LogQuery, NewTarget, PutQuery, RepoName, Stored, TargetInfo, + TokenRequest, }; use origin_shared::event::Page; use origin_shared::landing::Pending; @@ -92,6 +94,11 @@ calls! { fn create_target(request: &NewTarget) -> Head = create_target(request), create_target(request); /// The events after a cursor, waiting for some. fn events(query: &EventsQuery) -> Page = events(query), events(query); + /// Who the remote thinks the user is, and what they may do there. + fn whoami() -> Rights = whoami(), whoami(); + /// Issues a token acting for the user, with a narrower scope. + fn issue_token(request: &TokenRequest) -> IssuedToken = + issue_token(request), issue_token(request); } impl Remote { diff --git a/apps/origin-src/src/server.rs b/apps/origin-src/src/server.rs index 38664f03..b0819071 100644 --- a/apps/origin-src/src/server.rs +++ b/apps/origin-src/src/server.rs @@ -14,8 +14,9 @@ use std::thread; use std::time::Duration; use anyhow::Context; -use origin_shared::PrincipalName; +use origin_shared::access::{Capability, Token}; use origin_shared::api::{RepoName, RepoSummary}; +use origin_shared::{Principal, PrincipalName}; use serde::Deserialize; use crate::auth::{Credentials, StaticTokens}; @@ -40,7 +41,8 @@ use crate::store::Store; /// ``` /// /// Paths are relative to the file. Callers without a token are anonymous; -/// the server also takes the scoped tokens it signed. +/// the server also takes the scoped tokens it signed (see +/// [`ServerConfig::issue_token`]). #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct ServerConfig { @@ -119,6 +121,26 @@ impl ServerConfig { Ok(()) } + /// `origin token issue --config --as `: signs a + /// token acting for `principal` with `scope`, valid for `ttl`, at most + /// [`OriginService::MAX_TOKEN_TTL`] as any token, with the server's key, + /// and returns it. The token acts with the principal's rights in each + /// repository, narrowed to the scope, so an operator can hand agents + /// identities of their own. + /// + /// # Errors + /// + /// Fails if the key cannot be read or generated. + pub fn issue_token( + &self, + principal: Principal, + scope: Vec, + ttl: Duration, + ) -> anyhow::Result { + let ttl = ttl.min(OriginService::MAX_TOKEN_TTL); + Ok(Token::new(principal, scope, ttl).sign(&self.node()?.key)) + } + /// `origin serve`: serves the repositories until interrupted, logging /// failures to stderr. Prints the address it listens on, which tells /// callers that chose port 0 where to connect. @@ -267,3 +289,26 @@ impl Repositories { .ok_or_else(|| ServiceError::UnknownRepository(name.clone())) } } + +#[cfg(test)] +mod tests { + use std::time::{SystemTime, UNIX_EPOCH}; + + use super::*; + + #[test] + fn tokens_signed_with_the_key_last_at_most_a_week() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("origin-server.toml"); + fs::write(&path, "listen = \"127.0.0.1:0\"\nnode = \"hosted\"\n").unwrap(); + let config = ServerConfig::load(&path).unwrap(); + let month = Duration::from_hours(30 * 24); + let text = config + .issue_token("user:agent".parse().unwrap(), Vec::new(), month) + .unwrap(); + let token = Token::verify(&text, &config.node().unwrap().key.public()).unwrap(); + let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); + let cap = (now + OriginService::MAX_TOKEN_TTL).as_secs(); + assert!(token.expires <= cap && token.expires + 60 > cap); + } +} diff --git a/apps/origin-src/src/service.rs b/apps/origin-src/src/service.rs index 9f411f2d..dedfcf80 100644 --- a/apps/origin-src/src/service.rs +++ b/apps/origin-src/src/service.rs @@ -14,8 +14,9 @@ //! Landings on one target still go one at a time, through the target's //! queue lock. //! -//! Every method takes the [`Caller`]. Nothing is checked yet: every caller -//! may read and write everything. +//! Every method takes the [`Caller`], whose [`Rights`] the policy in force +//! resolves. Nothing is checked yet: every caller may read and write +//! everything. use std::collections::hash_map::Entry; use std::collections::{HashMap, HashSet}; @@ -25,24 +26,26 @@ use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use std::time::Duration; use origin_platform::Native; +use origin_shared::access::{Rights, Token}; use origin_shared::api::{ Annotation, ErrorCode, EventsQuery, Expected, FetchSnapshot, Inventory, InventoryRequest, - LandRequest, Landings, LogEntry, LogQuery, NewTarget, RevisionEntry, Revisions, Stored, - TargetInfo, + IssuedToken, LandRequest, Landings, LogEntry, LogQuery, NewTarget, RevisionEntry, Revisions, + Stored, TargetInfo, TokenRequest, }; use origin_shared::event::{Filter, Page}; use origin_shared::landing::{Pending, Proposal}; use origin_shared::object::DecodeError; use origin_shared::pack::{Pack, Packer, Part}; use origin_shared::{ - Base, ChangeId, Head, Kind, NodeKey, Object, ObjectId, ObjectKind, Principal, PrincipalName, - RecordId, Statement, StatementId, TargetName, TreeId, + AcceptanceId, Base, ChangeId, Head, Kind, NodeKey, Object, ObjectId, ObjectKind, Principal, + PrincipalName, RecordId, Statement, StatementId, TargetName, TreeId, }; use crate::annotations::{AnnotateError, Annotations}; use crate::events::{Events, Wakeup}; use crate::index::Index; pub use crate::permissions::Caller; +use crate::permissions::Forbidden; use crate::policy::{Policy, PolicyError}; use crate::queue::{LandError, Queue}; use crate::store::{Store, StoreError}; @@ -72,6 +75,9 @@ pub struct OriginService { node: Node, /// The record indexes kept open, but those in use: see the module. indexes: Mutex>, + /// The policy in force, and the acceptance of `policy` holding it, once + /// read. + policy: Mutex)>>, wakeup: Wakeup, /// The most bytes a fetch's answer holds: [`Pack::LIMIT`], but in tests. pack_limit: usize, @@ -81,6 +87,9 @@ impl OriginService { /// The most events a page holds, and how many by default. const MAX_EVENTS: u32 = 1024; + /// The longest a token issued lasts. + pub const MAX_TOKEN_TTL: Duration = Duration::from_hours(7 * 24); + /// The longest an event long-poll waits. pub const MAX_WAIT: Duration = Duration::from_mins(1); @@ -94,6 +103,7 @@ impl OriginService { store, node, indexes: Mutex::default(), + policy: Mutex::default(), wakeup: Wakeup::default(), pack_limit: Pack::LIMIT, } @@ -185,6 +195,95 @@ impl OriginService { self.indexes.lock().unwrap_or_else(PoisonError::into_inner) } + /// The policy in force, read again only once `policy` moved. + fn policy(&self) -> Result, ServiceError> { + let mut kept = self.policy.lock().unwrap_or_else(PoisonError::into_inner); + let head = self.store.head(&TargetName::POLICY)?; + if let (Some(head), Some((at, policy))) = (head, &*kept) + && head.acceptance == *at + { + return Ok(Arc::clone(policy)); + } + let (at, policy) = match Policy::in_force(&self.store) { + Ok((at, policy)) => (at, Arc::new(policy)), + Err(PolicyError::Missing) => return Ok(Arc::new(Policy::default())), + Err(error) => return Err(error.into()), + }; + *kept = Some((at, Arc::clone(&policy))); + Ok(policy) + } + + /// What `caller` may do, under the policy in force. + /// + /// # Errors + /// + /// Fails if the policy cannot be read. + pub fn rights(&self, caller: &Caller) -> Result { + Ok(match caller { + Caller::Owner => Rights::all(), + Caller::Anonymous => self.policy()?.rights(None), + Caller::Principal { principal, scope } => { + let rights = self.policy()?.rights(Some(principal)); + match scope { + Some(scope) => rights.narrowed(scope.capabilities.clone()), + None => rights, + } + } + }) + } + + /// `whoami`: what the caller may do, and who they are. + /// + /// # Errors + /// + /// Fails if the policy cannot be read. + pub fn whoami(&self, caller: &Caller) -> Result { + self.rights(caller) + } + + /// Issues a token acting for the caller, with the request's scope, which + /// their rights must cover, for its `ttl`, at most + /// [`OriginService::MAX_TOKEN_TTL`], and never past the expiry of the + /// caller's own token, if it's a scoped one: so no token renews itself. + /// + /// # Errors + /// + /// Fails if the caller isn't signed in, or the scope reaches beyond + /// their rights. + pub fn issue_token( + &self, + caller: &Caller, + request: &TokenRequest, + ) -> Result { + let Some(principal) = caller.principal() else { + return Err(Forbidden::NoPrincipal.into()); + }; + let rights = self.rights(caller)?; + if let Some(beyond) = request + .scope + .iter() + .find(|&capability| !rights.cover(std::slice::from_ref(capability))) + { + return Err(Forbidden::Scope(beyond.clone()).into()); + } + let mut token = Token::new( + principal.clone(), + request.scope.clone(), + request.ttl.0.min(Self::MAX_TOKEN_TTL), + ); + if let Caller::Principal { + scope: Some(scope), .. + } = caller + { + token.expires = token.expires.min(scope.expires); + } + Ok(IssuedToken { + token: token.sign(&self.node.key), + principal: token.principal, + expires: token.expires, + }) + } + /// The records `ids` name, in their order, as a pack: revisions, /// statements and acceptances, each followed by the attachment it /// carries, if the repository has it: a revision's description, a @@ -855,30 +954,6 @@ pub enum ServiceError { /// A blob, a tree or an attachment was fetched as a record. #[error("{0} is not a record: fetch snapshots by walking them")] NotARecord(ObjectId), - /// A target was proposed for landing without a target to land on. - #[error("landing a target needs a target to land on")] - NoTarget, - /// An object put isn't a well-formed object. - #[error("object {id} is malformed")] - Malformed { - /// The object. - id: ObjectId, - /// What is wrong. - source: DecodeError, - }, - /// An acceptance was put. - #[error( - "acceptance {0} cannot be put: only a target's authority writes acceptances, by landing" - )] - Acceptance(origin_shared::AcceptanceId), - /// An object put needs one neither the batch nor the repository has. - #[error("object {id} needs object {needed}, which neither the batch nor the repository has")] - Missing { - /// The object put. - id: ObjectId, - /// What it needs. - needed: ObjectId, - }, /// An object put refers to one as an object of another kind: a /// snapshot that isn't a tree, a file that is one, a description that /// isn't an attachment. @@ -904,6 +979,33 @@ pub enum ServiceError { /// Its heads now. heads: Vec, }, + /// The caller may not do this. + #[error(transparent)] + Forbidden(#[from] Forbidden), + /// A target was proposed for landing without a target to land on. + #[error("landing a target needs a target to land on")] + NoTarget, + /// An object put isn't a well-formed object. + #[error("object {id} is malformed")] + Malformed { + /// The object. + id: ObjectId, + /// What is wrong. + source: DecodeError, + }, + /// An acceptance was put. + #[error( + "acceptance {0} cannot be put: only a target's authority writes acceptances, by landing" + )] + Acceptance(origin_shared::AcceptanceId), + /// An object put needs one neither the batch nor the repository has. + #[error("object {id} needs object {needed}, which neither the batch nor the repository has")] + Missing { + /// The object put. + id: ObjectId, + /// What it needs. + needed: ObjectId, + }, /// An events cursor is of another op log than the repository's. #[error("the cursor is of another op log, generation {0}: read from the end")] OtherLog(String), @@ -946,6 +1048,7 @@ impl ServiceError { AnnotateError::Store(error) => Self::store_code(error), _ => ErrorCode::BadRequest, }, + Self::Forbidden(_) => ErrorCode::Forbidden, Self::Moved { .. } => ErrorCode::Conflict, Self::OtherLog(_) => ErrorCode::Expired, Self::Land(error) => match error { diff --git a/apps/origin-src/src/workspace/access.rs b/apps/origin-src/src/workspace/access.rs new file mode 100644 index 00000000..0fdf6101 --- /dev/null +++ b/apps/origin-src/src/workspace/access.rs @@ -0,0 +1,99 @@ +//! What the remote lets the user do: `whoami`, `permissions` and `token +//! issue`. + +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use origin_shared::Period; +use origin_shared::access::{Capability, Rights}; +use origin_shared::api::TokenRequest; + +use super::{Workspace, WorkspaceError}; + +impl Workspace { + /// `origin whoami`: prints who the remote thinks the user is. + /// + /// # Errors + /// + /// Fails if the remote cannot be reached. + pub fn whoami(&self) -> Result<(), WorkspaceError> { + let Some(remote) = self.remote()? else { + println!("{}, the owner of this repository", self.config.user()); + return Ok(()); + }; + let rights = remote.whoami()?; + match &rights.principal { + None if rights.paths.writes_all() => { + println!("The owner: the remote is a local repository."); + } + None => println!("Anonymous: set a token for the remote to sign in."), + Some(principal) if rights.groups.is_empty() => println!("{principal}"), + Some(principal) => { + let groups: Vec<_> = rights.groups.iter().map(ToString::to_string).collect(); + println!("{principal} (groups: {})", groups.join(", ")); + } + } + if let Some(scope) = &rights.scope { + let scope: Vec<_> = scope.iter().map(ToString::to_string).collect(); + println!("Token scope: {}", scope.join(", ")); + } + Ok(()) + } + + /// `origin permissions`: prints what the user may do on the remote. + /// + /// # Errors + /// + /// Fails if the remote cannot be reached. + pub fn permissions(&self) -> Result<(), WorkspaceError> { + let rights = match self.remote()? { + Some(remote) => remote.whoami()?, + None => Rights::all(), + }; + for (path, level) in rights.paths.rules() { + println!("{level:<5} {path}"); + } + let list = |items: Vec| { + if items.is_empty() { + "nothing".to_owned() + } else { + items.join(", ") + } + }; + println!( + "annotate: {}", + list(rights.annotate.iter().map(ToString::to_string).collect()) + ); + println!( + "land: {}", + list(rights.land.iter().map(ToString::to_string).collect()) + ); + println!("admin: {}", if rights.admin { "yes" } else { "no" }); + Ok(()) + } + + /// `origin token issue`: asks the remote for a token acting for the + /// user, with `scope`, valid for `ttl`, and prints it. + /// + /// # Errors + /// + /// Fails if there's no remote, it cannot be reached, or it refuses: + /// the scope must be part of the user's rights. + pub fn issue_token(&self, scope: Vec, ttl: Period) -> Result<(), WorkspaceError> { + let issued = self + .require_remote()? + .issue_token(&TokenRequest { scope, ttl })?; + let left = Duration::from_secs(issued.expires).saturating_sub( + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default(), + ); + println!("{}", issued.token); + eprintln!( + "Acts for {} for {} minutes: send it as ORIGIN_TOKEN, or add it to [tokens] in \ + config.toml", + issued.principal, + left.as_secs().div_ceil(60) + ); + Ok(()) + } +} diff --git a/apps/origin-src/src/workspace/mod.rs b/apps/origin-src/src/workspace/mod.rs index 9439fb83..90508bd5 100644 --- a/apps/origin-src/src/workspace/mod.rs +++ b/apps/origin-src/src/workspace/mod.rs @@ -66,6 +66,7 @@ //! which publishes `moving` again first: a crash then finishes taking the //! files back, not the move that failed. +mod access; mod annotate; mod land; mod ops; diff --git a/apps/origin-src/src/workspace/remote.rs b/apps/origin-src/src/workspace/remote.rs index 68a14ecf..d733ca3f 100644 --- a/apps/origin-src/src/workspace/remote.rs +++ b/apps/origin-src/src/workspace/remote.rs @@ -232,7 +232,7 @@ impl Workspace { } /// The repository's remote, which the command needs. - fn require_remote(&self) -> Result<&Remote, WorkspaceError> { + pub(super) fn require_remote(&self) -> Result<&Remote, WorkspaceError> { self.remote()?.ok_or(WorkspaceError::NoRemote) } diff --git a/apps/origin-src/tests/http.rs b/apps/origin-src/tests/http.rs index b32497ae..541047db 100644 --- a/apps/origin-src/tests/http.rs +++ b/apps/origin-src/tests/http.rs @@ -9,7 +9,7 @@ use std::time::{Duration, Instant}; use origin_client::{Client, Error, Repo}; use origin_shared::api::{ ErrorCode, EventsQuery, Expected, FetchRecords, FetchSnapshot, InventoryRequest, LandRequest, - List, LogQuery, NewTarget, PutQuery, RepoName, StatementsQuery, + List, LogQuery, NewTarget, PutQuery, RepoName, StatementsQuery, TokenRequest, }; use origin_shared::event::EventKind; use origin_shared::landing::{Blocked, Landing, Proposal}; @@ -26,13 +26,20 @@ use origin_src::server::Repositories; use origin_src::service::{Node, OriginService}; /// A server hosting `demo`, whose policy requires nothing, and `strict`, -/// whose `main` requires a passing `ci.test` from `user:ci`. The server's -/// node, `hosted`, orders both. `user:ada` and `user:ci` have static tokens. +/// whose `main` requires a passing `ci.test` from `user:ci`, and where +/// only `user:ci` issues `ci.*` statements, `secrets` is withheld from +/// everyone but `user:ada`, and only she lands. The server's node, +/// `hosted`, orders both. `user:ada` and `user:ci` have static tokens. struct Server { _dir: tempfile::TempDir, + /// The server's base URL. + base: String, client: Client, + /// `demo` and `strict`, as `user:ada`. demo: Repo, strict: Repo, + /// `strict`, anonymously. + anonymous: Repo, } impl Server { @@ -48,7 +55,11 @@ impl Server { let strict = format!( "[nodes]\nhosted = \"{}\"\n[targets.policy]\nauthority = \"node:hosted\"\n\ [targets.main]\nauthority = \"node:hosted\"\n\ - require = [{{ kind = \"ci.test\", verdict = \"pass\", issuer = \"user:ci\" }}]\n", + require = [{{ kind = \"ci.test\", verdict = \"pass\", issuer = \"user:ci\" }}]\n\ + [grants]\n\"user:ada\" = [\"land *\", \"annotate review\"]\n\ + \"user:ci\" = [\"annotate ci.*\"]\n\ + [[paths]]\npath = \"/\"\ngrants = {{ all = \"read\", \"user:ada\" = \"write\" }}\n\ + [[paths]]\npath = \"secrets\"\ngrants = {{ all = \"none\", \"user:ada\" = \"write\" }}\n", node.key.public() ); let tokens: StaticTokens = toml::from_str(Self::TOKENS).unwrap(); @@ -62,11 +73,14 @@ impl Server { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = listener.local_addr().unwrap(); tokio::spawn(async move { axum::serve(listener, Api::router(repositories)).await }); - let client = Client::new(&format!("http://{address}")).with_token("ada-token"); + let anonymous = Client::new(&format!("http://{address}")); + let client = anonymous.clone().with_token("ada-token"); Self { _dir: dir, + base: format!("http://{address}"), demo: client.repo("demo".parse().unwrap()), strict: client.repo("strict".parse().unwrap()), + anonymous: anonymous.repo("strict".parse().unwrap()), client, } } @@ -765,6 +779,58 @@ async fn events_long_poll() { ); } +#[tokio::test] +async fn tells_callers_what_they_may_do_and_issues_narrower_tokens() { + let server = Server::start().await; + let path = |path: &str| RepoPath::new(path).unwrap(); + let ada = server.strict.whoami().await.unwrap(); + assert_eq!(ada.principal, Some("user:ada".parse().unwrap())); + assert!(ada.paths.writes(&path("secrets/key")) && ada.may_land(&TargetName::MAIN)); + let anonymous = server.anonymous.whoami().await.unwrap(); + assert_eq!(anonymous.principal, None); + assert!(anonymous.paths.reads(&path("README.md"))); + assert!(!anonymous.paths.reads(&path("secrets/key"))); + let stranger = Client::new(&server.base).with_token("nope"); + assert_eq!( + code(stranger.repos().await.unwrap_err()), + ErrorCode::Unauthorized + ); + + // Ada hands an agent a token that only writes `src`. + let scope = |scope: &[&str]| TokenRequest { + scope: scope + .iter() + .map(|capability| capability.parse().unwrap()) + .collect(), + ttl: Period(Duration::from_hours(1)), + }; + let issued = server + .strict + .issue_token(&scope(&["write src"])) + .await + .unwrap(); + assert_eq!(issued.principal, "user:ada".parse().unwrap()); + let agent = Client::new(&server.base) + .with_token(issued.token) + .repo("strict".parse().unwrap()); + let rights = agent.whoami().await.unwrap(); + assert!(rights.paths.writes(&path("src/lib.rs"))); + assert!(!rights.paths.reads(&path("README.md"))); + assert!(rights.land.is_empty() && !rights.admin); + // Its token only narrows: what it lacks, it cannot pass on. + for wider in [&["write /"][..], &["land main"], &["read secrets"]] { + let error = agent.issue_token(&scope(wider)).await.unwrap_err(); + assert_eq!(code(error), ErrorCode::Forbidden, "{wider:?}"); + } + assert!(agent.issue_token(&scope(&["write src/net"])).await.is_ok()); + let error = server + .anonymous + .issue_token(&scope(&["read /"])) + .await + .unwrap_err(); + assert_eq!(code(error), ErrorCode::Forbidden); +} + #[tokio::test] async fn serves_its_openapi_document() { let server = Server::start().await; diff --git a/crates/origin-client/src/lib.rs b/crates/origin-client/src/lib.rs index 6c76059c..48f319ad 100644 --- a/crates/origin-client/src/lib.rs +++ b/crates/origin-client/src/lib.rs @@ -18,10 +18,11 @@ //! the two cannot disagree on a contract. The server also describes its API //! in `docs/openapi.json`, for other languages. +use origin_shared::access::Rights; use origin_shared::api::{ Annotation, ApiError, EventsQuery, FetchRecords, FetchSnapshot, Inventory, InventoryRequest, - LandRequest, Landings, LogEntry, LogQuery, MORE, NewTarget, PutQuery, RepoName, RepoSummary, - Revisions, StatementsQuery, Stored, TargetInfo, + IssuedToken, LandRequest, Landings, LogEntry, LogQuery, MORE, NewTarget, PutQuery, RepoName, + RepoSummary, Revisions, StatementsQuery, Stored, TargetInfo, TokenRequest, }; use origin_shared::event::Page; use origin_shared::landing::Pending; @@ -110,6 +111,11 @@ endpoints! { /// The events after a cursor, waiting up to the query's `wait` for /// some: pass the page's `next` as the next query's cursor. fn events(query: &EventsQuery) -> Page = GET "events", query(query) => json; + /// Who the server thinks the caller is, and what they may do. + fn whoami() -> Rights = GET "whoami" => json; + /// Issues a token acting for the caller, with a narrower scope. + fn issue_token(request: &TokenRequest) -> IssuedToken = + POST "tokens", json(request) => json; } } diff --git a/crates/origin-shared/src/api.rs b/crates/origin-shared/src/api.rs index d53c3c95..86babad8 100644 --- a/crates/origin-shared/src/api.rs +++ b/crates/origin-shared/src/api.rs @@ -7,12 +7,13 @@ use std::str::FromStr; use serde::{Deserialize, Serialize}; use utoipa::{IntoParams, ToSchema}; +use crate::access::Capability; use crate::landing::{Landing, Proposal}; use crate::policy::{KindPattern, Requirement}; use crate::text::Period; use crate::{ - Acceptance, AcceptanceId, ChangeId, Head, ObjectId, PrincipalName, RecordId, RepoPath, - Revision, RevisionId, Statement, StatementId, TargetName, TreeId, + Acceptance, AcceptanceId, ChangeId, Head, ObjectId, Principal, PrincipalName, RecordId, + RepoPath, Revision, RevisionId, Statement, StatementId, TargetName, TreeId, }; /// The name of a repository on a server: ASCII letters, digits, `.`, `_` @@ -411,6 +412,28 @@ where } } +/// Asks a server for a token with a narrower scope, for an agent or a CI +/// runner. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +pub struct TokenRequest { + /// What it may do: a part of what the caller may do. + pub scope: Vec, + /// How long it lasts, such as `1h`. + #[schema(value_type = String)] + pub ttl: Period, +} + +/// A token a server issued. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] +pub struct IssuedToken { + /// The token, to send as `Authorization: Bearer `. + pub token: String, + /// Who it acts for. + pub principal: Principal, + /// When it expires, in seconds since the Unix epoch. + pub expires: u64, +} + /// What went wrong with a request. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ToSchema)] pub struct ApiError { @@ -444,6 +467,8 @@ pub enum ErrorCode { Expired, /// The credentials are invalid or expired. Unauthorized, + /// The caller may not do this. + Forbidden, /// The server failed. Internal, } diff --git a/docs/openapi.json b/docs/openapi.json index bd6c0f5c..b8e6b374 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -801,6 +801,114 @@ } } } + }, + "/api/v1/repos/{repo}/tokens": { + "post": { + "summary": "Issues a token acting for the caller, with a scope narrowing their\nrights, signed by the server, which verifies it without storing it.", + "operationId": "issue_token", + "parameters": [ + { + "name": "repo", + "in": "path", + "description": "The repository whose policy the scope is checked against", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/TokenRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "The token", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/IssuedToken" + } + } + } + }, + "403": { + "description": "The caller isn't signed in, or the scope reaches beyond their rights", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "The repository does not exist", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + } + }, + "/api/v1/repos/{repo}/whoami": { + "get": { + "summary": "Tells the caller who they are and what they may do in the repository.", + "operationId": "whoami", + "parameters": [ + { + "name": "repo", + "in": "path", + "description": "The repository", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "The caller's rights", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Rights" + } + } + } + }, + "401": { + "description": "The token is invalid or expired", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "The repository does not exist", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + } + } + } } }, "components": { @@ -1037,6 +1145,12 @@ ], "description": "Why a landing waits." }, + "Capability": { + "type": "string", + "examples": [ + "write src" + ] + }, "ChangeId": { "type": "string", "examples": [ @@ -1058,6 +1172,7 @@ "conflict", "expired", "unauthorized", + "forbidden", "internal" ] }, @@ -1380,12 +1495,43 @@ } } }, + "IssuedToken": { + "type": "object", + "description": "A token a server issued.", + "required": [ + "token", + "principal", + "expires" + ], + "properties": { + "expires": { + "type": "integer", + "format": "int64", + "description": "When it expires, in seconds since the Unix epoch.", + "minimum": 0 + }, + "principal": { + "$ref": "#/components/schemas/Principal", + "description": "Who it acts for." + }, + "token": { + "type": "string", + "description": "The token, to send as `Authorization: Bearer `." + } + } + }, "Kind": { "type": "string", "examples": [ "ci.test" ] }, + "KindPattern": { + "type": "string", + "examples": [ + "ci.*" + ] + }, "LandRequest": { "type": "object", "description": "Asks the queue to land something.", @@ -1494,6 +1640,15 @@ } } }, + "Level": { + "type": "string", + "description": "What a caller may do with a path.", + "enum": [ + "none", + "read", + "write" + ] + }, "LogEntry": { "type": "object", "description": "One acceptance of a target's log.", @@ -1563,6 +1718,16 @@ } } }, + "PathAccess": { + "type": "object", + "description": "What a caller may do with every path: the level of the most specific\npath it lists at or above it. The root is always listed.", + "additionalProperties": { + "$ref": "#/components/schemas/Level" + }, + "propertyNames": { + "type": "string" + } + }, "Pending": { "type": "object", "description": "A landing that waits, kept in the queue to be listed and retried.", @@ -1790,6 +1955,68 @@ } } }, + "Rights": { + "type": "object", + "description": "What a caller may do, resolved from the policy in force and narrowed by\ntheir token's scope.", + "required": [ + "paths", + "annotate", + "land", + "admin" + ], + "properties": { + "admin": { + "type": "boolean", + "description": "Whether they may land on `policy`." + }, + "annotate": { + "type": "array", + "items": { + "$ref": "#/components/schemas/KindPattern" + }, + "description": "The kinds of statements they may issue." + }, + "groups": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PrincipalName" + }, + "description": "The policy's groups the caller is a member of." + }, + "land": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Targets" + }, + "description": "The targets they may land on, but `policy`." + }, + "paths": { + "$ref": "#/components/schemas/PathAccess", + "description": "What they may do with each path." + }, + "principal": { + "oneOf": [ + { + "$ref": "#/components/schemas/Principal", + "description": "Who the caller is: `None` for an anonymous caller, or the node's own\nuser." + }, + { + "type": "null" + } + ] + }, + "scope": { + "type": [ + "array", + "null" + ], + "items": { + "$ref": "#/components/schemas/Capability" + }, + "description": "The token's scope, if the caller came with a scoped token." + } + } + }, "Source": { "oneOf": [ { @@ -1969,6 +2196,33 @@ "main" ] }, + "Targets": { + "type": "string", + "examples": [ + "main" + ] + }, + "TokenRequest": { + "type": "object", + "description": "Asks a server for a token with a narrower scope, for an agent or a CI\nrunner.", + "required": [ + "scope", + "ttl" + ], + "properties": { + "scope": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Capability" + }, + "description": "What it may do: a part of what the caller may do." + }, + "ttl": { + "type": "string", + "description": "How long it lasts, such as `1h`." + } + } + }, "TreeId": { "type": "string", "examples": [