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
13 changes: 6 additions & 7 deletions apps/origin-ci/benches/worker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
use std::cell::RefCell;
use std::path::PathBuf;
use std::process::Command;
use std::sync::Arc;

use divan::Bencher;
use origin_ci::runner::{Outcome, Runner};
Expand Down Expand Up @@ -50,22 +49,22 @@ struct Hosted {
impl Hosted {
fn new() -> Self {
let dir = tempfile::tempdir().unwrap();
let node = Node {
name: "hosted".parse().unwrap(),
key: Arc::new(NodeKey::from_bytes(&[7; 32])),
};
let node = Node::new("hosted".parse().unwrap(), NodeKey::from_bytes(&[7; 32]));
let policy = 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",
node.key.public()
node.key().unwrap().public()
);
let root = dir.path().join("demo");
let service = OriginService::create(root.clone(), node.clone(), &policy).unwrap();

let runtime = Runtime::new().unwrap();
let tokens: StaticTokens = toml::from_str("\"user:ci\" = \"ci\"").unwrap();
let mut repositories = Repositories::new(Credentials::new(node.clone(), Box::new(tokens)));
let mut repositories = Repositories::new(Credentials::new(
node.key().unwrap().public(),
Box::new(tokens),
));
repositories.insert(
"demo".parse().unwrap(),
OriginService::open(root, node.clone()).unwrap(),
Expand Down
9 changes: 3 additions & 6 deletions apps/origin-src/benches/permissions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
//! one whom path rules withhold a directory from and keep from writing
//! another. Landings sync, so run on a real disk.

use std::sync::{Arc, LazyLock};
use std::sync::LazyLock;

use divan::Bencher;
use origin_shared::api::{FetchSnapshot, LandRequest};
Expand Down Expand Up @@ -60,11 +60,8 @@ static SETUP: LazyLock<Setup> = LazyLock::new(|| {
let files = tempfile::tempdir().unwrap();
TREE.write(files.path()).unwrap();
let repos = tempfile::tempdir().unwrap();
let node = Node {
name: "hosted".parse().unwrap(),
key: Arc::new(NodeKey::from_bytes(&[7; 32])),
};
let initial = Policy::initial(&node.name, &node.key.public(), None);
let node = Node::new("hosted".parse().unwrap(), NodeKey::from_bytes(&[7; 32]));
let initial = Policy::initial(&node.name, &node.key().unwrap().public(), None);
let create = |name: &str, policy: &str| {
OriginService::create(repos.path().join(name), node.clone(), policy).unwrap()
};
Expand Down
10 changes: 3 additions & 7 deletions apps/origin-src/benches/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
//! one that reads it per landing. Run on a real disk: syncs are most of the
//! cost of a put.

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;

Expand Down Expand Up @@ -40,11 +39,8 @@ struct Hosted {
impl Hosted {
fn new() -> Self {
let dir = tempfile::tempdir().unwrap();
let node = Node {
name: "hosted".parse().unwrap(),
key: Arc::new(NodeKey::from_bytes(&[7; 32])),
};
let policy = Policy::initial(&node.name, &node.key.public(), None);
let node = Node::new("hosted".parse().unwrap(), NodeKey::from_bytes(&[7; 32]));
let policy = Policy::initial(&node.name, &node.key().unwrap().public(), None);
let service =
OriginService::create(dir.path().join("demo"), node.clone(), &policy).unwrap();
let revision = Self::put_change(&service, 0);
Expand Down Expand Up @@ -99,7 +95,7 @@ impl Hosted {
fn serve(&self) -> (Runtime, Repo) {
let runtime = Runtime::new().unwrap();
let tokens: StaticTokens = toml::from_str("\"node:ci\" = \"bench\"").unwrap();
let credentials = Credentials::new(self.node.clone(), Box::new(tokens));
let credentials = Credentials::new(self.node.key().unwrap().public(), Box::new(tokens));
let mut repositories = Repositories::new(credentials);
repositories.insert("demo".parse().unwrap(), self.service());
let url = runtime.block_on(async {
Expand Down
21 changes: 9 additions & 12 deletions apps/origin-src/benches/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
//! every fetch was before cursors. Each includes the server's work and the
//! client's durable writes, so run on a real disk.

use std::sync::LazyLock;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, LazyLock};

use divan::Bencher;
use origin_platform::Native;
Expand Down Expand Up @@ -63,11 +63,8 @@ struct Setup {
static SETUP: LazyLock<Setup> = LazyLock::new(|| {
let [files, server, client] = [(); 3].map(|()| tempfile::tempdir().unwrap());
TREE.write(files.path()).unwrap();
let node = Node {
name: "hosted".parse().unwrap(),
key: Arc::new(NodeKey::from_bytes(&[7; 32])),
};
let policy = Policy::initial(&node.name, &node.key.public(), None);
let node = Node::new("hosted".parse().unwrap(), NodeKey::from_bytes(&[7; 32]));
let policy = Policy::initial(&node.name, &node.key().unwrap().public(), None);
let service = OriginService::create(server.path().join("demo"), node.clone(), &policy).unwrap();
let mut cache = StatCache::default();
let mut snapshot_into = |store: &Store, version: Option<u64>| {
Expand Down Expand Up @@ -127,7 +124,10 @@ static SETUP: LazyLock<Setup> = LazyLock::new(|| {
fn serve(service: OriginService, node: &Node) -> (Runtime, RemoteUrl) {
let runtime = Runtime::new().unwrap();
let tokens: StaticTokens = toml::from_str("\"user:bench\" = \"bench\"").unwrap();
let mut repositories = Repositories::new(Credentials::new(node.clone(), Box::new(tokens)));
let mut repositories = Repositories::new(Credentials::new(
node.key().unwrap().public(),
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 @@ -279,11 +279,8 @@ struct History {

static HISTORY_SETUP: LazyLock<History> = LazyLock::new(|| {
let [server, client] = [(); 2].map(|()| tempfile::tempdir().unwrap());
let node = Node {
name: "hosted".parse().unwrap(),
key: Arc::new(NodeKey::from_bytes(&[7; 32])),
};
let policy = Policy::initial(&node.name, &node.key.public(), None);
let node = Node::new("hosted".parse().unwrap(), NodeKey::from_bytes(&[7; 32]));
let policy = Policy::initial(&node.name, &node.key().unwrap().public(), None);
let service = OriginService::create(server.path().join("demo"), node.clone(), &policy).unwrap();
let tip = service.store().head(&TargetName::MAIN).unwrap().unwrap();
let state = service.store().get(tip.acceptance).unwrap().body().state;
Expand Down
32 changes: 13 additions & 19 deletions apps/origin-src/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
use std::collections::BTreeMap;
use std::fmt;

use origin_shared::Principal;
use origin_shared::access::{InvalidToken, Token};
use origin_shared::{NodePublicKey, Principal};
use serde::Deserialize;

use crate::permissions::Scope;
use crate::service::{Caller, Node};
use crate::service::Caller;

/// Turns static credentials into principals. The server configuration's
/// tokens are one implementation; external identity providers can be
Expand Down Expand Up @@ -49,22 +49,20 @@ impl Authenticator for StaticTokens {
}
}

/// How a server tells its callers apart: its node, which verifies the
/// tokens it signed, and its static credentials.
/// How a server tells its callers apart: its node's public key, which
/// verifies the tokens it signed, and its static credentials.
#[derive(Debug)]
pub struct Credentials {
node: Node,
key: NodePublicKey,
authenticator: Box<dyn Authenticator>,
}

impl Credentials {
/// Callers of `node`, whose static credentials `authenticator` checks.
/// Callers of the node whose public key is `key`, whose static
/// credentials `authenticator` checks.
#[must_use]
pub fn new(node: Node, authenticator: Box<dyn Authenticator>) -> Self {
Self {
node,
authenticator,
}
pub fn new(key: NodePublicKey, authenticator: Box<dyn Authenticator>) -> Self {
Self { key, authenticator }
}

/// The caller an `Authorization` header's value stands for: anonymous
Expand All @@ -81,7 +79,7 @@ impl Credentials {
.strip_prefix("Bearer ")
.ok_or(InvalidToken::Malformed)?;
if Token::is_signed(token) {
let token = Token::verify(token, &self.node.key.public())?;
let token = Token::verify(token, &self.key)?;
return Ok(Caller::Principal {
principal: token.principal,
scope: Some(Scope {
Expand All @@ -103,7 +101,6 @@ impl Credentials {

#[cfg(test)]
mod tests {
use std::sync::Arc;
use std::time::Duration;

use origin_shared::NodeKey;
Expand All @@ -114,17 +111,14 @@ mod tests {
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 key = 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 signed = token.sign(&key);
let credentials = Credentials::new(key.public(), Box::new(tokens));
let caller = |header: Option<&str>| credentials.caller(header);
let principal = |caller: Caller| caller.principal().map(ToString::to_string);

Expand Down
45 changes: 44 additions & 1 deletion apps/origin-src/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use std::io::{self, Write};
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Path, PathBuf};
use std::process;
use std::sync::OnceLock;

use origin_platform::{Durability, Native};
use origin_shared::{InvalidName, NodeKey, Principal, PrincipalName};
Expand Down Expand Up @@ -130,7 +131,49 @@ impl UserConfig {
///
/// Fails like [`KeyFile::load`].
pub fn node_key(&self) -> Result<NodeKey, ConfigError> {
KeyFile(self.dir.join("node.key")).load()
self.key_file().load()
}

/// The file holding this node's key.
#[must_use]
pub fn key_file(&self) -> KeyFile {
KeyFile(self.dir.join("node.key"))
}
}

/// A node's key: in hand, or in its [`KeyFile`], loaded the first time
/// it's needed, so what never signs never reads, nor creates, the file.
#[derive(Debug)]
pub enum LazyKey {
/// The key.
Loaded(NodeKey),
/// The file holding the key, and the key once loaded.
File(KeyFile, OnceLock<NodeKey>),
}

impl From<KeyFile> for LazyKey {
fn from(file: KeyFile) -> Self {
Self::File(file, OnceLock::new())
}
}

impl LazyKey {
/// The key, loaded from its file the first time.
///
/// # Errors
///
/// Fails like [`KeyFile::load`].
pub fn get(&self) -> Result<&NodeKey, ConfigError> {
match self {
Self::Loaded(key) => Ok(key),
Self::File(file, loaded) => {
if let Some(key) = loaded.get() {
return Ok(key);
}
let key = file.load()?;
Ok(loaded.get_or_init(|| key))
}
}
}
}

Expand Down
7 changes: 1 addition & 6 deletions apps/origin-src/src/permissions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -691,8 +691,6 @@ pub enum PutError {

#[cfg(test)]
mod tests {
use std::sync::Arc;

use origin_platform::Native;
use origin_shared::api::{FetchSnapshot, LandRequest};
use origin_shared::landing::{Landing, Proposal};
Expand Down Expand Up @@ -753,10 +751,7 @@ grants = { all = "none", "user:ada" = "write" }
],
);
repo.land(1);
let node = Node {
name: "queue".parse().unwrap(),
key: Arc::new(NodeKey::from_bytes(&[7; 32])),
};
let node = Node::new("queue".parse().unwrap(), NodeKey::from_bytes(&[7; 32]));
let service = OriginService::new(repo.store.clone(), node);
Self { repo, service }
}
Expand Down
9 changes: 3 additions & 6 deletions apps/origin-src/src/remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use origin_shared::landing::Pending;
use origin_shared::pack::{Pack, Part};
use origin_shared::{ChangeId, Head};

use crate::config::{ConfigError, UserConfig};
use crate::config::UserConfig;
use crate::service::{Caller, Node, OriginService, ServiceError};
use crate::workspace::Workspace;

Expand Down Expand Up @@ -121,9 +121,9 @@ impl Remote {
///
/// # Errors
///
/// Fails like [`Remote::open`], or if the node key cannot be loaded.
/// Fails like [`Remote::open`].
pub fn open_for(url: &RemoteUrl, config: &UserConfig) -> Result<Self, RemoteError> {
Self::open(url, Node::of(config)?, url.token(config))
Self::open(url, Node::of(config), url.token(config))
}

/// Opens the remote at `url`: an `http://` URL whose last path segment
Expand Down Expand Up @@ -241,9 +241,6 @@ pub enum RemoteError {
/// The client has no TLS support yet.
#[error("HTTPS remotes are not supported yet")]
HttpsUnsupported,
/// The user's node key cannot be loaded.
#[error(transparent)]
Config(#[from] ConfigError),
/// The runtime for HTTP requests cannot start.
#[error("cannot start the runtime for HTTP requests")]
Runtime(#[source] std::io::Error),
Expand Down
16 changes: 8 additions & 8 deletions apps/origin-src/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,10 @@ impl ServerConfig {
///
/// Fails if the key cannot be read, or generated and saved.
pub fn node(&self) -> anyhow::Result<Node> {
Ok(Node {
name: self.node.clone(),
key: Arc::new(KeyFile(self.key.clone()).load()?),
})
Ok(Node::new(
self.node.clone(),
KeyFile(self.key.clone()).load()?,
))
}

/// `origin repo create [--admin <principal>]`: creates an empty
Expand All @@ -112,7 +112,7 @@ impl ServerConfig {
/// written.
pub fn create_repo(&self, root: &Path, admin: Option<&Principal>) -> anyhow::Result<()> {
let node = self.node()?;
let policy = Policy::initial(&node.name, &node.key.public(), admin);
let policy = Policy::initial(&node.name, &node.key()?.public(), admin);
OriginService::create(root.to_owned(), node, &policy)?;
println!(
"Created a repository in {}: node:{} is the authority of `policy` and `main`",
Expand Down Expand Up @@ -143,7 +143,7 @@ impl ServerConfig {
ttl: Duration,
) -> anyhow::Result<String> {
let ttl = ttl.min(OriginService::MAX_TOKEN_TTL);
Ok(Token::new(principal, scope, ttl).sign(&self.node()?.key))
Ok(Token::new(principal, scope, ttl).sign(self.node()?.key()?))
}

/// `origin serve`: serves the repositories until interrupted, logging
Expand All @@ -162,7 +162,7 @@ impl ServerConfig {
.with_writer(std::io::stderr)
.init();
let node = self.node()?;
let credentials = Credentials::new(node.clone(), Box::new(self.tokens));
let credentials = Credentials::new(node.key()?.public(), Box::new(self.tokens));
let repositories = Repositories::open(self.repos, &node, credentials)?;
repositories.compact_in_background();
let runtime = tokio::runtime::Builder::new_multi_thread()
Expand Down Expand Up @@ -354,7 +354,7 @@ mod tests {
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 token = Token::verify(&text, &config.node().unwrap().key().unwrap().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);
Expand Down
Loading
Loading