From 659dd5f2dd30edc441fa102ebefcf5c14c92015a Mon Sep 17 00:00:00 2001 From: piquel Date: Sun, 22 Nov 2026 16:03:51 +0100 Subject: [PATCH] feat(auth): authenticate callers by their bearer token Every request to a server was anonymous, so nothing could tell its callers apart, let alone decide what each may do. Requests now carry `Authorization: Bearer `, which `Credentials` turns into a `Caller`: anonymous without a header, a principal with one. A token is either static, from the `[tokens]` of the server's configuration, compared by hash so response times don't reveal how much of it matched, or one the server signed with its node key, scoped and short-lived, verified without storing it. Static tokens go through the `Authenticator` trait, so other identity providers can take their place. A malformed, unknown or expired token is refused with 401 and the new `unauthorized` error code. The SDK's `Client::with_token` sends one on every request, and never shows it in debug output. The command line sends the remote the token `config.toml` names for its URL under `[tokens]`, or `$ORIGIN_TOKEN`; a remote on a local path is always called as its owner. Nothing is enforced yet: callers are told apart, and every one may still do everything. --- Cargo.lock | 1 + README.md | 11 +- apps/origin-src/Cargo.toml | 1 + apps/origin-src/benches/server.rs | 9 +- apps/origin-src/benches/sync.rs | 20 ++-- apps/origin-src/src/auth.rs | 151 ++++++++++++++++++++++++ apps/origin-src/src/config.rs | 42 ++++++- apps/origin-src/src/http.rs | 39 ++++-- apps/origin-src/src/lib.rs | 2 + apps/origin-src/src/permissions.rs | 44 +++++++ apps/origin-src/src/remote.rs | 38 ++++-- apps/origin-src/src/server.rs | 55 ++++++--- apps/origin-src/src/service.rs | 10 +- apps/origin-src/src/workspace/remote.rs | 14 ++- apps/origin-src/tests/common/mod.rs | 50 +++++++- apps/origin-src/tests/http.rs | 10 +- crates/origin-client/src/lib.rs | 34 +++++- crates/origin-shared/src/api.rs | 2 + docs/openapi.json | 11 ++ tools/xtask/src/main.rs | 20 +++- 20 files changed, 490 insertions(+), 74 deletions(-) create mode 100644 apps/origin-src/src/auth.rs create mode 100644 apps/origin-src/src/permissions.rs diff --git a/Cargo.lock b/Cargo.lock index df93b3fc..152fc092 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -860,6 +860,7 @@ version = "0.1.0" dependencies = [ "anyhow", "axum", + "blake3", "clap", "divan", "getrandom", diff --git a/README.md b/README.md index d844cfd5..ad153afa 100644 --- a/README.md +++ b/README.md @@ -110,7 +110,9 @@ Changes are named by a unique prefix of their id, or `@` for the working copy's. A revision is `@`, a change (for its head), or a unique prefix of the revision's id. Your name and node key live in `$ORIGIN_CONFIG_DIR`, or else `origin` in `$XDG_CONFIG_HOME` or `~/.config`: set `user = ""` -in its `config.toml` if `$USER` isn't the name you want. See +in its `config.toml` if `$USER` isn't the name you want, and the token to +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. `converge` merges the files of a change's heads. A text file two heads @@ -142,6 +144,9 @@ key = "node.key" # its secret key, created if missing [repos] demo = "repos/demo" + +[tokens] # static tokens, by principal +"user:alice" = "a long random secret" ``` The HTTP API, under `/api/v1`, puts records in batches, if the changes @@ -157,8 +162,8 @@ generation of the op log it's of: pass it back as `generation`, and a cursor of another log, such as from before the repository was restored, is refused as expired. [`docs/openapi.json`](docs/openapi.json) describes it, and -[`origin-client`](crates/origin-client) is its Rust SDK. Nothing -authenticates callers yet. +[`origin-client`](crates/origin-client) is its Rust SDK. Callers send +`Authorization: Bearer `; without one, they are anonymous. ## Development diff --git a/apps/origin-src/Cargo.toml b/apps/origin-src/Cargo.toml index c4bc359a..2b2cbc20 100644 --- a/apps/origin-src/Cargo.toml +++ b/apps/origin-src/Cargo.toml @@ -18,6 +18,7 @@ fixture = [] [dependencies] anyhow.workspace = true axum.workspace = true +blake3.workspace = true clap.workspace = true getrandom.workspace = true origin-client.workspace = true diff --git a/apps/origin-src/benches/server.rs b/apps/origin-src/benches/server.rs index 910b4e8c..0105e244 100644 --- a/apps/origin-src/benches/server.rs +++ b/apps/origin-src/benches/server.rs @@ -18,6 +18,7 @@ use origin_shared::{ AttachmentId, Base, ChangeId, EncodedObject, EntryKind, EntryName, Kind, NodeKey, Period, Record, RecordId, Revision, RevisionId, Statement, TargetName, Tree, TreeEntry, Verdict, }; +use origin_src::auth::{Credentials, StaticTokens}; use origin_src::http::Api; use origin_src::policy::Policy; use origin_src::server::Repositories; @@ -97,7 +98,9 @@ impl Hosted { /// server and the SDK's handle on the repository. fn serve(&self) -> (Runtime, Repo) { let runtime = Runtime::new().unwrap(); - let mut repositories = Repositories::default(); + let tokens: StaticTokens = toml::from_str("\"node:ci\" = \"bench\"").unwrap(); + let credentials = Credentials::new(self.node.clone(), Box::new(tokens)); + let mut repositories = Repositories::new(credentials); repositories.insert("demo".parse().unwrap(), self.service()); let url = runtime.block_on(async { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -105,7 +108,9 @@ impl Hosted { tokio::spawn(async move { axum::serve(listener, Api::router(repositories)).await }); format!("http://{address}") }); - let repo = origin_client::Client::new(&url).repo("demo".parse().unwrap()); + let repo = origin_client::Client::new(&url) + .with_token("bench") + .repo("demo".parse().unwrap()); (runtime, repo) } } diff --git a/apps/origin-src/benches/sync.rs b/apps/origin-src/benches/sync.rs index 7438d0e7..a081b189 100644 --- a/apps/origin-src/benches/sync.rs +++ b/apps/origin-src/benches/sync.rs @@ -18,6 +18,7 @@ use origin_shared::{ Base, ChangeId, EncodedObject, Kind, NodeKey, Record, RecordId, Revision, Statement, TargetName, TreeId, Verdict, }; +use origin_src::auth::{Credentials, StaticTokens}; use origin_src::fixture::FixtureTree; use origin_src::http::Api; use origin_src::policy::Policy; @@ -83,11 +84,11 @@ static SETUP: LazyLock = LazyLock::new(|| { .map(|version| snapshot_into(service.store(), Some(version))) .collect(); - let (runtime, url) = serve(service); + let (runtime, url) = serve(service, &node); let store = Store::new(client.path().join(".origin"), Native::default()); store.init().unwrap(); - let remote = Remote::open(&url, node.clone()).unwrap(); + let remote = Remote::open(&url, node.clone(), Some("bench".to_owned())).unwrap(); let sync = Sync::new(&store, &remote, "laptop".parse().unwrap()); sync.fetch_chains(&[TargetName::MAIN]).unwrap(); sync.need(snapshot, &[]).unwrap(); @@ -108,11 +109,12 @@ static SETUP: LazyLock = LazyLock::new(|| { } }); -/// Serves `service` over HTTP on localhost as `demo`, on a runtime of its -/// own. -fn serve(service: OriginService) -> (Runtime, RemoteUrl) { +/// Serves `service` over HTTP on localhost as `demo`, where `user:bench`'s +/// token is `bench`, on a runtime of its own. +fn serve(service: OriginService, node: &Node) -> (Runtime, RemoteUrl) { let runtime = Runtime::new().unwrap(); - let mut repositories = Repositories::default(); + let tokens: StaticTokens = toml::from_str("\"user:bench\" = \"bench\"").unwrap(); + let mut repositories = Repositories::new(Credentials::new(node.clone(), Box::new(tokens))); repositories.insert("demo".parse().unwrap(), service); let base = runtime.block_on(async { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); @@ -167,7 +169,7 @@ fn revision(base: Base, snapshot: TreeId) -> (EncodedObject, EncodedObject) { impl Setup { fn remote(&self) -> Remote { - Remote::open(&self.url, self.node.clone()).unwrap() + Remote::open(&self.url, self.node.clone(), Some("bench".to_owned())).unwrap() } } @@ -284,11 +286,11 @@ static HISTORY_SETUP: LazyLock = LazyLock::new(|| { service .put_records(&Caller::Owner, Pack { objects }) .unwrap(); - let (runtime, url) = serve(service); + let (runtime, url) = serve(service, &node); let store = Store::new(client.path().join(".origin"), Native::default()); store.init().unwrap(); - let remote = Remote::open(&url, node).unwrap(); + let remote = Remote::open(&url, node, Some("bench".to_owned())).unwrap(); let sync = Sync::new(&store, &remote, "laptop".parse().unwrap()); let fetch = sync.fetch(&[TargetName::MAIN], &changes, None).unwrap(); assert_eq!(fetch.fetched.revisions, HISTORY as usize); diff --git a/apps/origin-src/src/auth.rs b/apps/origin-src/src/auth.rs new file mode 100644 index 00000000..80e2b3eb --- /dev/null +++ b/apps/origin-src/src/auth.rs @@ -0,0 +1,151 @@ +//! Authenticating callers of the HTTP API by their bearer token: a token +//! the server signed, scoped and short-lived (see [`Token`]), or a static +//! one from its configuration, checked by an [`Authenticator`]. + +use std::collections::BTreeMap; +use std::fmt; + +use origin_shared::Principal; +use origin_shared::access::{InvalidToken, Token}; +use serde::Deserialize; + +use crate::permissions::Scope; +use crate::service::{Caller, Node}; + +/// Turns static credentials into principals. The server configuration's +/// tokens are one implementation; external identity providers can be +/// others. +pub trait Authenticator: Send + Sync + fmt::Debug { + /// The principal a bearer token belongs to, or `None` if no one has it. + fn authenticate(&self, token: &str) -> Option; +} + +/// Static tokens, from the server configuration: +/// +/// ```toml +/// [tokens] +/// "user:alice" = "a long random secret" +/// "node:ci-1" = "another one" +/// ``` +#[derive(Default, Deserialize)] +pub struct StaticTokens(BTreeMap); + +impl fmt::Debug for StaticTokens { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // Never the secrets. + f.debug_list().entries(self.0.keys()).finish() + } +} + +impl Authenticator for StaticTokens { + fn authenticate(&self, token: &str) -> Option { + // Comparing hashes, which compare in constant time, keeps response + // times from revealing how much of a token matched. + let token = blake3::hash(token.as_bytes()); + self.0 + .iter() + .find(|(_, known)| blake3::hash(known.as_bytes()) == token) + .map(|(principal, _)| principal.clone()) + } +} + +/// How a server tells its callers apart: its node, which verifies the +/// tokens it signed, and its static credentials. +#[derive(Debug)] +pub struct Credentials { + node: Node, + authenticator: Box, +} + +impl Credentials { + /// Callers of `node`, whose static credentials `authenticator` checks. + #[must_use] + pub fn new(node: Node, authenticator: Box) -> Self { + Self { + node, + authenticator, + } + } + + /// The caller an `Authorization` header's value stands for: anonymous + /// without one. + /// + /// # Errors + /// + /// Fails if it isn't a bearer token, or no valid one. + pub fn caller(&self, authorization: Option<&str>) -> Result { + let Some(authorization) = authorization else { + return Ok(Caller::Anonymous); + }; + let token = authorization + .strip_prefix("Bearer ") + .ok_or(InvalidToken::Malformed)?; + if Token::is_signed(token) { + let token = Token::verify(token, &self.node.key.public())?; + return Ok(Caller::Principal { + principal: token.principal, + scope: Some(Scope { + capabilities: token.scope, + expires: token.expires, + }), + }); + } + let principal = self + .authenticator + .authenticate(token) + .ok_or(InvalidToken::Unknown)?; + Ok(Caller::Principal { + principal, + scope: None, + }) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + use std::time::Duration; + + use origin_shared::NodeKey; + + use super::*; + + #[test] + fn tells_callers_apart_by_token() { + let tokens: StaticTokens = + toml::from_str("\"user:alice\" = \"a-secret\"\n\"node:ci\" = \"c-secret\"\n").unwrap(); + let node = Node { + name: "hosted".parse().unwrap(), + key: Arc::new(NodeKey::from_bytes(&[5; 32])), + }; + let token = Token::new( + "user:bob".parse().unwrap(), + vec!["write src".parse().unwrap()], + Duration::from_mins(1), + ); + let signed = token.sign(&node.key); + let credentials = Credentials::new(node, Box::new(tokens)); + let caller = |header: Option<&str>| credentials.caller(header); + let principal = |caller: Caller| caller.principal().map(ToString::to_string); + + assert_eq!(caller(None), Ok(Caller::Anonymous)); + assert_eq!( + principal(caller(Some("Bearer a-secret")).unwrap()).as_deref(), + Some("user:alice") + ); + assert_eq!( + principal(caller(Some("Bearer c-secret")).unwrap()).as_deref(), + Some("node:ci") + ); + let Ok(Caller::Principal { principal, scope }) = caller(Some(&format!("Bearer {signed}"))) + else { + panic!("a signed token"); + }; + assert_eq!(principal.to_string(), "user:bob"); + let scope = scope.unwrap(); + assert_eq!(scope.capabilities[0].to_string(), "write src"); + assert_eq!(scope.expires, token.expires, "it carries its expiry"); + assert!(caller(Some("Bearer a-secre")).is_err()); + assert!(caller(Some("a-secret")).is_err(), "not a bearer token"); + } +} diff --git a/apps/origin-src/src/config.rs b/apps/origin-src/src/config.rs index d60f1fce..b75161fa 100644 --- a/apps/origin-src/src/config.rs +++ b/apps/origin-src/src/config.rs @@ -3,11 +3,14 @@ //! `~/.config`: //! //! - `config.toml`: `user = "alice"`, who authors revisions (by default -//! `$USER`), and `node = "laptop"`, this node's name (by default the -//! user's). +//! `$USER`), `node = "laptop"`, this node's name (by default the +//! user's), and `[tokens]`, the token to send each server, by its URL: +//! `"http://127.0.0.1:7878" = "a long random secret"`. `$ORIGIN_TOKEN` +//! overrides them. //! - `node.key`: this node's secret ed25519 key, created by the first //! `origin init`, readable only by its owner. +use std::collections::BTreeMap; use std::env; use std::fs::{self, OpenOptions}; use std::io::{self, Write}; @@ -25,6 +28,17 @@ pub struct UserConfig { dir: PathBuf, user: PrincipalName, node: PrincipalName, + tokens: Tokens, +} + +/// The tokens to send servers, by URL, which never show in debug output. +#[derive(Clone, Default, Deserialize)] +struct Tokens(BTreeMap); + +impl std::fmt::Debug for Tokens { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_list().entries(self.0.keys()).finish() + } } /// `config.toml`. @@ -33,6 +47,8 @@ pub struct UserConfig { struct ConfigFile { user: Option, node: Option, + #[serde(default)] + tokens: Tokens, } impl UserConfig { @@ -73,7 +89,27 @@ impl UserConfig { .map(name) .transpose()? .unwrap_or_else(|| user.clone()); - Ok(Self { dir, user, node }) + let tokens = file + .tokens + .0 + .into_iter() + .map(|(server, token)| (server.trim_end_matches('/').to_owned(), token)) + .collect(); + Ok(Self { + dir, + user, + node, + tokens: Tokens(tokens), + }) + } + + /// The token to send the server at `base`, such as + /// `http://127.0.0.1:7878`: `$ORIGIN_TOKEN`, or the one configured. + #[must_use] + pub fn token(&self, base: &str) -> Option { + env::var("ORIGIN_TOKEN") + .ok() + .or_else(|| self.tokens.0.get(base.trim_end_matches('/')).cloned()) } /// The user, who authors revisions and issues statements. diff --git a/apps/origin-src/src/http.rs b/apps/origin-src/src/http.rs index 6300c739..7245dd99 100644 --- a/apps/origin-src/src/http.rs +++ b/apps/origin-src/src/http.rs @@ -2,8 +2,10 @@ //! calls on the repository they name. Every route is documented with //! `utoipa`, which generates the OpenAPI document; `origin-client` is the //! Rust SDK for it. +//! +//! Callers authenticate with `Authorization: Bearer ` (see +//! [`Credentials`](crate::auth::Credentials)); without it, they are anonymous. -use std::convert::Infallible; use std::sync::Arc; use axum::Json; @@ -14,6 +16,7 @@ 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::api::{ Annotation, ApiError, ErrorCode, EventsQuery, FetchRecords, FetchSnapshot, Inventory, InventoryRequest, LandRequest, Landings, LogEntry, LogQuery, MORE, NewTarget, PutQuery, @@ -81,15 +84,23 @@ impl Api { } } -/// Every request is anonymous: nothing authenticates callers yet. +/// The caller of a request, by its bearer token. impl FromRequestParts> for Caller { - type Rejection = Infallible; + type Rejection = HttpError; fn from_request_parts( - _parts: &mut Parts, - _repositories: &Arc, - ) -> impl Future> + Send { - std::future::ready(Ok(Self::Anonymous)) + parts: &mut Parts, + repositories: &Arc, + ) -> impl Future> + Send { + let authorization = parts + .headers + .get(header::AUTHORIZATION) + .map(|value| value.to_str().map_err(|_| InvalidToken::Malformed)) + .transpose(); + let caller = authorization + .and_then(|authorization| repositories.credentials().caller(authorization)) + .map_err(HttpError::Unauthorized); + std::future::ready(caller) } } @@ -109,9 +120,14 @@ async fn call( } /// A failed request, rendered as an [`ApiError`]. -enum HttpError { +pub enum HttpError { + /// The service refused or failed. Service(ServiceError), + /// The request's pack is invalid. Pack(PackError), + /// The caller's credentials are invalid. + Unauthorized(InvalidToken), + /// The service panicked. Panicked(String), } @@ -124,6 +140,7 @@ impl IntoResponse for HttpError { } Self::Service(error) => (error.code(), error.to_string()), Self::Pack(error) => (ErrorCode::BadRequest, format!("invalid pack: {error}")), + Self::Unauthorized(error) => (ErrorCode::Unauthorized, error.to_string()), Self::Panicked(message) => { tracing::error!(%message, "request panicked"); (ErrorCode::Internal, "internal server error".to_owned()) @@ -134,6 +151,7 @@ impl IntoResponse for HttpError { ErrorCode::NotFound => StatusCode::NOT_FOUND, ErrorCode::Conflict => StatusCode::CONFLICT, ErrorCode::Expired => StatusCode::GONE, + ErrorCode::Unauthorized => StatusCode::UNAUTHORIZED, ErrorCode::Internal => StatusCode::INTERNAL_SERVER_ERROR, }; (status, Json(ApiError { code, message })).into_response() @@ -160,7 +178,10 @@ impl utoipa::ToSchema for Binary {} get, path = "/api/v1/repos", operation_id = "list_repos", - responses((status = 200, description = "The repositories, by name", body = Vec)) + responses( + (status = 200, description = "The repositories, by name", body = Vec), + (status = 401, description = "The token is invalid or expired", body = ApiError) + ) )] async fn list_repos(State(repositories): Repos, caller: Caller) -> Json> { Json(repositories.list(&caller)) diff --git a/apps/origin-src/src/lib.rs b/apps/origin-src/src/lib.rs index 092361e6..f61ef6f0 100644 --- a/apps/origin-src/src/lib.rs +++ b/apps/origin-src/src/lib.rs @@ -3,6 +3,7 @@ pub mod ancestry; pub mod annotations; +pub mod auth; pub mod cli; pub mod config; pub mod conflict; @@ -14,6 +15,7 @@ pub mod http; pub mod index; pub mod oplog; pub mod output; +pub mod permissions; pub mod policy; pub mod queue; pub mod remote; diff --git a/apps/origin-src/src/permissions.rs b/apps/origin-src/src/permissions.rs new file mode 100644 index 00000000..4fec7a4f --- /dev/null +++ b/apps/origin-src/src/permissions.rs @@ -0,0 +1,44 @@ +//! Who calls the service: the node's own user, an anonymous client, or a +//! principal the server [authenticated](crate::auth), whose token may +//! narrow their rights to its scope. + +use origin_shared::Principal; +use origin_shared::access::Capability; + +/// Who calls the service. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Caller { + /// The node's own user, through the command line or a remote on a + /// local path: they may do everything. + Owner, + /// A client of a server that didn't authenticate. + Anonymous, + /// An authenticated client of a server. + Principal { + /// Who they are. + principal: Principal, + /// What their token narrows their rights to, if it's a scoped one. + scope: Option, + }, +} + +/// What a scoped token narrows its bearer's rights to, and until when. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Scope { + /// The capabilities it keeps of its bearer's rights. + pub capabilities: Vec, + /// When it expires, in seconds since the Unix epoch: a token issued + /// with it expires no later. + pub expires: u64, +} + +impl Caller { + /// Who the caller is, unless the owner or anonymous. + #[must_use] + pub fn principal(&self) -> Option<&Principal> { + match self { + Self::Principal { principal, .. } => Some(principal), + Self::Owner | Self::Anonymous => None, + } + } +} diff --git a/apps/origin-src/src/remote.rs b/apps/origin-src/src/remote.rs index 014f8067..011710f0 100644 --- a/apps/origin-src/src/remote.rs +++ b/apps/origin-src/src/remote.rs @@ -20,6 +20,7 @@ use origin_shared::event::Page; use origin_shared::landing::Pending; use origin_shared::pack::{Pack, Part}; +use crate::config::UserConfig; use crate::service::{Caller, Node, OriginService, ServiceError}; use crate::workspace::Workspace; @@ -95,21 +96,28 @@ calls! { impl Remote { /// Opens the remote at `url`: an `http://` URL whose last path segment - /// names the repository, or the path of a repository, which `node` - /// serves in-process. + /// names the repository, called with `token` if there's one, or the + /// path of a repository, which `node` serves in-process, to its owner. /// /// # Errors /// /// Fails if the URL names no repository, or the path holds none. - pub fn open(url: &RemoteUrl, node: Node) -> Result { + pub fn open(url: &RemoteUrl, node: Node, token: Option) -> Result { match url { - RemoteUrl::Http { base, repo } => Ok(Self::Http { - runtime: tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .map_err(RemoteError::Runtime)?, - repo: Client::new(base).repo(repo.clone()), - }), + RemoteUrl::Http { base, repo } => { + let client = Client::new(base); + let client = match token { + Some(token) => client.with_token(token), + None => client, + }; + Ok(Self::Http { + runtime: tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(RemoteError::Runtime)?, + repo: client.repo(repo.clone()), + }) + } RemoteUrl::Path(path) => { // A working copy's repository is in its `.origin`. let meta = path.join(Workspace::META_DIR); @@ -137,6 +145,16 @@ pub enum RemoteUrl { } impl RemoteUrl { + /// The token the user of `config` sends this remote, if any: none to a + /// local path, which serves them as its owner. + #[must_use] + pub fn token(&self, config: &UserConfig) -> Option { + match self { + Self::Http { base, .. } => config.token(base), + Self::Path(_) => None, + } + } + /// Parses a remote URL: `http://host[:port]/`, or a path, /// made absolute, so the URL works from anywhere. /// diff --git a/apps/origin-src/src/server.rs b/apps/origin-src/src/server.rs index 72b107d2..38664f03 100644 --- a/apps/origin-src/src/server.rs +++ b/apps/origin-src/src/server.rs @@ -18,6 +18,7 @@ use origin_shared::PrincipalName; use origin_shared::api::{RepoName, RepoSummary}; use serde::Deserialize; +use crate::auth::{Credentials, StaticTokens}; use crate::config::KeyFile; use crate::http::Api; use crate::policy::Policy; @@ -33,9 +34,13 @@ use crate::store::Store; /// /// [repos] /// origin = "repos/origin" # name = path +/// +/// [tokens] # static tokens, by principal +/// "user:alice" = "a long random secret" /// ``` /// -/// Paths are relative to the file. +/// Paths are relative to the file. Callers without a token are anonymous; +/// the server also takes the scoped tokens it signed. #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct ServerConfig { @@ -49,6 +54,9 @@ pub struct ServerConfig { /// The repositories to serve, by name. #[serde(default)] pub repos: BTreeMap, + /// Static tokens. + #[serde(default)] + pub tokens: StaticTokens, } impl ServerConfig { @@ -127,7 +135,8 @@ impl ServerConfig { .with_writer(std::io::stderr) .init(); let node = self.node()?; - let repositories = Repositories::open(self.repos, &node)?; + let credentials = Credentials::new(node.clone(), Box::new(self.tokens)); + let repositories = Repositories::open(self.repos, &node, credentials)?; repositories.compact_in_background(); let runtime = tokio::runtime::Builder::new_multi_thread() .enable_all() @@ -154,31 +163,49 @@ impl ServerConfig { } /// The repositories a server hosts, each served by the server's node and -/// kept open while it runs. -#[derive(Debug, Default)] +/// kept open while it runs, and how it tells its callers apart. +#[derive(Debug)] pub struct Repositories { repos: BTreeMap, + credentials: Credentials, } impl Repositories { /// How often [`Repositories::compact_in_background`] checks. const COMPACT_EVERY: Duration = Duration::from_mins(1); + /// No repositories yet, for callers `credentials` tells apart. + #[must_use] + pub fn new(credentials: Credentials) -> Self { + Self { + repos: BTreeMap::new(), + credentials, + } + } + /// Opens the repositories at the given paths, served by `node`. /// /// # Errors /// /// Fails if one has no repository. - pub fn open(repos: BTreeMap, node: &Node) -> anyhow::Result { - let repos = repos - .into_iter() - .map(|(name, path)| { - let service = OriginService::open(path, node.clone()) - .with_context(|| format!("cannot serve repository `{name}`"))?; - Ok((name, service)) - }) - .collect::>()?; - Ok(Self { repos }) + pub fn open( + repos: BTreeMap, + node: &Node, + credentials: Credentials, + ) -> anyhow::Result { + let mut repositories = Self::new(credentials); + for (name, path) in repos { + let service = OriginService::open(path, node.clone()) + .with_context(|| format!("cannot serve repository `{name}`"))?; + repositories.insert(name, service); + } + Ok(repositories) + } + + /// How the server tells its callers apart. + #[must_use] + pub fn credentials(&self) -> &Credentials { + &self.credentials } /// Compacts each repository once enough loose objects pile up in it diff --git a/apps/origin-src/src/service.rs b/apps/origin-src/src/service.rs index c34fe589..9f411f2d 100644 --- a/apps/origin-src/src/service.rs +++ b/apps/origin-src/src/service.rs @@ -42,19 +42,11 @@ use origin_shared::{ use crate::annotations::{AnnotateError, Annotations}; use crate::events::{Events, Wakeup}; use crate::index::Index; +pub use crate::permissions::Caller; use crate::policy::{Policy, PolicyError}; use crate::queue::{LandError, Queue}; use crate::store::{Store, StoreError}; -/// Who calls the service. Permissions will decide what each may do by it. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum Caller { - /// The node's own user, through the command line. - Owner, - /// A client of a server that didn't authenticate. - Anonymous, -} - /// A node: its name, and the key it signs acceptances with as the /// authority of the targets its repositories' policies name it for. A /// server's repositories share their node. diff --git a/apps/origin-src/src/workspace/remote.rs b/apps/origin-src/src/workspace/remote.rs index f4346846..68a14ecf 100644 --- a/apps/origin-src/src/workspace/remote.rs +++ b/apps/origin-src/src/workspace/remote.rs @@ -74,7 +74,7 @@ impl Workspace { .take_while(|dir| dir.symlink_metadata().is_err()) .last() .map(Path::to_owned); - let remote = Remote::open(&url, Self::node_of(&config)?)?; + let remote = Self::open_remote(&url, &config)?; let cloned = Self::clone_into(root.clone(), &url, remote, target, config, actor); if cloned.is_err() { // Best effort: the error says what went wrong. @@ -203,6 +203,16 @@ impl Workspace { } } + /// Opens the remote at `url` for the user of `config`, with their + /// token for it, if they have one. + fn open_remote(url: &RemoteUrl, config: &UserConfig) -> Result { + Ok(Remote::open( + url, + Self::node_of(config)?, + url.token(config), + )?) + } + /// The repository's remote, opened the first time it's needed, if it /// has one. pub(super) fn remote(&self) -> Result, WorkspaceError> { @@ -210,7 +220,7 @@ impl Workspace { return Ok(remote.as_ref()); } let remote = match self.remote_url()? { - Some(url) => Some(Remote::open(&url, self.node()?)?), + Some(url) => Some(Self::open_remote(&url, &self.config)?), None => None, }; Ok(self.remote.get_or_init(|| remote).as_ref()) diff --git a/apps/origin-src/tests/common/mod.rs b/apps/origin-src/tests/common/mod.rs index 4bbb0063..1e2865a2 100644 --- a/apps/origin-src/tests/common/mod.rs +++ b/apps/origin-src/tests/common/mod.rs @@ -15,15 +15,25 @@ use std::thread; use std::time::{Duration, Instant}; /// A user, with a configuration directory, and so a node key, of their -/// own. Clones share it. +/// own, and the token they send servers, if any. Clones share it. #[derive(Clone)] pub struct User { config: Arc, + token: Option, } impl User { - /// A user named `name`, whose node is named after them. + /// A user named `name`, whose node is named after them, with the token + /// [`Server`] knows them by. pub fn new(name: &str) -> Self { + Self { + token: Some(Server::token(name)), + ..Self::anonymous(name) + } + } + + /// A user named `name` without a token: servers don't know them. + pub fn anonymous(name: &str) -> Self { let config = tempfile::tempdir().unwrap(); fs::write( config.path().join("config.toml"), @@ -32,6 +42,15 @@ impl User { .unwrap(); Self { config: Arc::new(config), + token: None, + } + } + + /// The user, sending `token` instead. + pub fn with_token(&self, token: &str) -> Self { + Self { + token: Some(token.to_owned()), + ..self.clone() } } @@ -46,7 +65,11 @@ impl User { command .args(args) .current_dir(cwd) - .env("ORIGIN_CONFIG_DIR", self.config()); + .env("ORIGIN_CONFIG_DIR", self.config()) + .env_remove("ORIGIN_TOKEN"); + if let Some(token) = &self.token { + command.env("ORIGIN_TOKEN", token); + } command } } @@ -260,7 +283,8 @@ impl Repo { } /// A running `origin serve` hosting one repository, `demo`, which its node, -/// `hosted`, orders. Killed when dropped. +/// `hosted`, orders. Each of [`Server::USERS`] signs in with +/// [`Server::token`]. Killed when dropped. pub struct Server { dir: tempfile::TempDir, child: Child, @@ -269,12 +293,28 @@ pub struct Server { } impl Server { + /// The users the server knows. + pub const USERS: [&str; 4] = ["ada", "bob", "carol", "alice"]; + + /// The static token of `user`. + pub fn token(user: &str) -> String { + format!("token-{user}") + } + pub fn start() -> Self { let dir = tempfile::tempdir().unwrap(); let config = dir.path().join("origin-server.toml"); + let tokens: Vec<_> = Self::USERS + .iter() + .map(|user| format!("\"user:{user}\" = \"{}\"", Self::token(user))) + .collect(); + let tokens = tokens.join("\n"); fs::write( &config, - "listen = \"127.0.0.1:0\"\nnode = \"hosted\"\n[repos]\ndemo = \"repos/demo\"\n", + format!( + "listen = \"127.0.0.1:0\"\nnode = \"hosted\"\n[repos]\ndemo = \"repos/demo\"\n\ + [tokens]\n{tokens}" + ), ) .unwrap(); let origin = |args: &[&str]| { diff --git a/apps/origin-src/tests/http.rs b/apps/origin-src/tests/http.rs index cb58b601..b32497ae 100644 --- a/apps/origin-src/tests/http.rs +++ b/apps/origin-src/tests/http.rs @@ -19,6 +19,7 @@ use origin_shared::{ NodeKey, Period, Record, RecordId, RepoPath, Revision, RevisionId, Source, Statement, TargetName, Tree, TreeEntry, TreeId, Verdict, }; +use origin_src::auth::{Credentials, StaticTokens}; use origin_src::http::Api; use origin_src::policy::Policy; use origin_src::server::Repositories; @@ -26,7 +27,7 @@ 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. +/// node, `hosted`, orders both. `user:ada` and `user:ci` have static tokens. struct Server { _dir: tempfile::TempDir, client: Client, @@ -35,6 +36,8 @@ struct Server { } impl Server { + const TOKENS: &str = "\"user:ada\" = \"ada-token\"\n\"user:ci\" = \"ci-token\"\n"; + async fn start() -> Self { let dir = tempfile::tempdir().unwrap(); let node = Node { @@ -48,7 +51,8 @@ impl Server { require = [{{ kind = \"ci.test\", verdict = \"pass\", issuer = \"user:ci\" }}]\n", node.key.public() ); - let mut repositories = Repositories::default(); + let tokens: StaticTokens = toml::from_str(Self::TOKENS).unwrap(); + let mut repositories = Repositories::new(Credentials::new(node.clone(), Box::new(tokens))); for (name, policy) in [("demo", open), ("strict", strict)] { let service = OriginService::create(dir.path().join(name), node.clone(), &policy).unwrap(); @@ -58,7 +62,7 @@ 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}")); + let client = Client::new(&format!("http://{address}")).with_token("ada-token"); Self { _dir: dir, demo: client.repo("demo".parse().unwrap()), diff --git a/crates/origin-client/src/lib.rs b/crates/origin-client/src/lib.rs index a1698697..6c76059c 100644 --- a/crates/origin-client/src/lib.rs +++ b/crates/origin-client/src/lib.rs @@ -5,7 +5,7 @@ //! use origin_shared::api::RepoName; //! //! # async fn example() -> Result<(), Box> { -//! let client = Client::new("http://127.0.0.1:7878"); +//! let client = Client::new("http://127.0.0.1:7878").with_token("a long random secret"); //! let repo = client.repo(RepoName::new("demo")?); //! for target in repo.targets().await? { //! println!("{} is at #{}", target.name, target.head.seq); @@ -115,11 +115,23 @@ endpoints! { /// A connection to an origin server. Cloning it is cheap, and clones share /// their connections. -#[derive(Clone, Debug)] +#[derive(Clone)] pub struct Client { http: reqwest::Client, /// The API's base URL, ending with a `/`. api: String, + /// The bearer token every request carries, if any. + token: Option, +} + +impl std::fmt::Debug for Client { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Never the token. + f.debug_struct("Client") + .field("api", &self.api) + .field("authenticated", &self.token.is_some()) + .finish_non_exhaustive() + } } impl Client { @@ -129,6 +141,18 @@ impl Client { Self { http: reqwest::Client::new(), api: format!("{}/api/v1/", url.trim_end_matches('/')), + token: None, + } + } + + /// The client, authenticating every request with `token`: a static + /// one from the server's configuration, or one it issued. Without one, + /// the server treats requests as anonymous, which only read. + #[must_use] + pub fn with_token(self, token: impl Into) -> Self { + Self { + token: Some(token.into()), + ..self } } @@ -143,7 +167,11 @@ impl Client { /// Starts a request to `path`, relative to the API's base URL. fn request(&self, method: Method, path: &str) -> RequestBuilder { - self.http.request(method, format!("{}{path}", self.api)) + let request = self.http.request(method, format!("{}{path}", self.api)); + match &self.token { + Some(token) => request.bearer_auth(token), + None => request, + } } } diff --git a/crates/origin-shared/src/api.rs b/crates/origin-shared/src/api.rs index 70df4920..d53c3c95 100644 --- a/crates/origin-shared/src/api.rs +++ b/crates/origin-shared/src/api.rs @@ -442,6 +442,8 @@ pub enum ErrorCode { Conflict, /// The event cursor is older than anything the server still keeps. Expired, + /// The credentials are invalid or expired. + Unauthorized, /// The server failed. Internal, } diff --git a/docs/openapi.json b/docs/openapi.json index ea949dd1..bd6c0f5c 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -44,6 +44,16 @@ } } } + }, + "401": { + "description": "The token is invalid or expired", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } } } } @@ -1047,6 +1057,7 @@ "not_found", "conflict", "expired", + "unauthorized", "internal" ] }, diff --git a/tools/xtask/src/main.rs b/tools/xtask/src/main.rs index 3649b29f..d7c4c8e5 100644 --- a/tools/xtask/src/main.rs +++ b/tools/xtask/src/main.rs @@ -428,19 +428,29 @@ impl Bench { } } -/// An `origin serve` hosting one empty repository, stopped when dropped. +/// An `origin serve` hosting one empty repository, which the bench user, +/// signed in with [`Server::TOKEN`], writes to. Stopped when dropped. struct Server { child: Child, url: String, } impl Server { + /// The bench user's token. + const TOKEN: &str = "bench-secret"; + + /// Starts the server, and adds its token to the bench user's + /// configuration in `config`. fn start(origin: &Path, base: &Path, config: &Path) -> Result { let dir = base.join("server"); fs::create_dir_all(&dir)?; fs::write( dir.join("origin-server.toml"), - "listen = \"127.0.0.1:0\"\nnode = \"hosted\"\n[repos]\ndemo = \"demo\"\n", + format!( + "listen = \"127.0.0.1:0\"\nnode = \"hosted\"\n[repos]\ndemo = \"demo\"\n\ + [tokens]\n\"user:bench\" = \"{}\"\n", + Self::TOKEN + ), )?; run(Command::new(origin) .args(["repo", "create", "demo"]) @@ -470,6 +480,12 @@ impl Server { .trim() .strip_prefix("Listening on ") .with_context(|| format!("unexpected server output: {line}"))?; + let user = config.join("config.toml"); + let toml = fs::read_to_string(&user)?; + fs::write( + &user, + format!("{toml}[tokens]\n\"{base}\" = \"{}\"\n", Self::TOKEN), + )?; server.url = format!("{base}/demo"); Ok(server) }