Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 = "<name>"`
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" = "<token>"`), 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
Expand Down Expand Up @@ -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
Expand All @@ -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 <token>`; without one, they are anonymous.

## Development

Expand Down
1 change: 1 addition & 0 deletions apps/origin-src/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 7 additions & 2 deletions apps/origin-src/benches/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -97,15 +98,19 @@ 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();
let address = listener.local_addr().unwrap();
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)
}
}
Expand Down
20 changes: 11 additions & 9 deletions apps/origin-src/benches/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -83,11 +84,11 @@ static SETUP: LazyLock<Setup> = 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();
Expand All @@ -108,11 +109,12 @@ static SETUP: LazyLock<Setup> = 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();
Expand Down Expand Up @@ -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()
}
}

Expand Down Expand Up @@ -284,11 +286,11 @@ static HISTORY_SETUP: LazyLock<History> = 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);
Expand Down
151 changes: 151 additions & 0 deletions apps/origin-src/src/auth.rs
Original file line number Diff line number Diff line change
@@ -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<Principal>;
}

/// 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<Principal, String>);

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<Principal> {
// 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<dyn Authenticator>,
}

impl Credentials {
/// Callers of `node`, whose static credentials `authenticator` checks.
#[must_use]
pub fn new(node: Node, authenticator: Box<dyn Authenticator>) -> 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<Caller, InvalidToken> {
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");
}
}
42 changes: 39 additions & 3 deletions apps/origin-src/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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<String, String>);

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`.
Expand All @@ -33,6 +47,8 @@ pub struct UserConfig {
struct ConfigFile {
user: Option<String>,
node: Option<String>,
#[serde(default)]
tokens: Tokens,
}

impl UserConfig {
Expand Down Expand Up @@ -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<String> {
env::var("ORIGIN_TOKEN")
.ok()
.or_else(|| self.tokens.0.get(base.trim_end_matches('/')).cloned())
}

/// The user, who authors revisions and issues statements.
Expand Down
Loading