From 35e2350dcc4974f2c198c9c273dd1806a0a6b539 Mon Sep 17 00:00:00 2001 From: piquel Date: Mon, 23 Nov 2026 16:01:08 +0100 Subject: [PATCH] feat(ci): add the origin-ci plugin Nothing ran a repository's checks: `checks.toml` had no reader, and results had to be issued by hand with `origin annotate`. This adds the `origin-ci` binary, which `origin ci` runs as a plugin, with its tool mode: `origin ci run []` checks a revision of the repository it runs in, as the user, as the revision's own `checks.toml` defines the checks, and fails if one fails. A check a result already covers, ran or promoted, is skipped, so a docs-only change keeps its results. Each check runs in a fresh checkout and its own process group, without the runner's token, and what it leaves running is killed once it ends, or by the next run if the run was killed. It opens the repository through `Remote::open_for`, the service in-process for a local path, which the working copy now uses too, and a change's revisions are a new `Remote` call, so `` can name a change by its head. --- AGENTS.md | 6 +- Cargo.lock | 2 + README.md | 38 ++- apps/origin-ci/Cargo.toml | 6 + apps/origin-ci/src/lib.rs | 5 + apps/origin-ci/src/main.rs | 125 ++++++++++ apps/origin-ci/tests/ci.rs | 272 ++++++++++++++++++++++ apps/origin-src/benches/permissions.rs | 9 +- apps/origin-src/benches/server.rs | 10 +- apps/origin-src/benches/sync.rs | 21 +- apps/origin-src/src/auth.rs | 33 ++- apps/origin-src/src/config.rs | 45 +++- apps/origin-src/src/permissions/tests.rs | 7 +- apps/origin-src/src/remote.rs | 17 +- apps/origin-src/src/server.rs | 16 +- apps/origin-src/src/service.rs | 71 ++++-- apps/origin-src/src/sync/tests.rs | 7 +- apps/origin-src/src/workspace/annotate.rs | 6 +- apps/origin-src/src/workspace/land.rs | 12 +- apps/origin-src/src/workspace/mod.rs | 30 +-- apps/origin-src/src/workspace/ops.rs | 2 +- apps/origin-src/src/workspace/remote.rs | 10 +- apps/origin-src/tests/cli.rs | 14 ++ apps/origin-src/tests/common/mod.rs | 4 +- apps/origin-src/tests/http.rs | 15 +- budget.toml | 2 +- 26 files changed, 645 insertions(+), 140 deletions(-) create mode 100644 apps/origin-ci/src/main.rs create mode 100644 apps/origin-ci/tests/ci.rs diff --git a/AGENTS.md b/AGENTS.md index 14c34aba..76c7fcea 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,7 +27,11 @@ review bots read and write at the same time, written in Rust. what it reads and checks what it writes, by the rights `policy.rs` resolves from `policy.toml`. `plugin.rs` runs `origin ` as `origin-` from `PATH`, passing the repository in the environment. -- `apps/origin-ci`: the CI plugin, `origin-ci`, which reads `checks.toml`. +- `apps/origin-ci`: the CI plugin, `origin-ci`. It reads `checks.toml` + from the revision it checks (`origin ci run`). It runs each check in a + checkout of the revision of its own, and issues the results. Like every + plugin, it uses only the public API: `Remote`, which is the SDK over HTTP + or the service in-process, never origin-src's internals. - `tools/xtask`: development tasks, run with `cargo xtask`, such as timing origin against git (`just bench-git`). diff --git a/Cargo.lock b/Cargo.lock index ef746b66..f7bae344 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -867,6 +867,8 @@ checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" name = "origin-ci" version = "0.1.0" dependencies = [ + "anyhow", + "clap", "origin-platform", "origin-shared", "origin-src", diff --git a/README.md b/README.md index 8cbc954d..8ffeef72 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,8 @@ origin fetch [--target ] [--change ] # new acceptances, and the records 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 + +origin ci run [] # run the checks of checks.toml, and issue their results ``` Landing rebases a change onto the target's tip, file by file, checks the @@ -119,7 +121,7 @@ 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. -## Plugins +## Plugins and CI `origin ` runs `origin-` from `PATH` when `` isn't a built-in command, with its arguments; its output and exit code are the @@ -129,6 +131,40 @@ the plugin `ORIGIN_REPOSITORY`, the directory holding the repository's store, remote, if there's one. Plugins use origin's public API only: a server's over HTTP, or for a local path, the same service in-process. +The first is [`origin-ci`](apps/origin-ci). It reads the checks from +`checks.toml`: + +```toml +[checks.test] +command = "cargo test" +inputs = ["src", "Cargo.toml", "Cargo.lock"] # the whole snapshot by default +toolchain = "rustc -V" # its output is hashed + +[checks.links] +command = "lychee docs" +inputs = ["docs"] +external = true # reads the network: never promoted +``` + +Each check runs in a checkout of the revision of its own, removed +afterwards, and issues a `ci.` statement: `pass` if the command exits +with 0, with the last 64 KiB of its output as the payload, declaring its +inputs, `checks.toml` always among them, command and toolchain output, so +its result is promoted to every revision where they're the same. A check a +result of the same issuer already covers, ran or promoted, is skipped. +`origin ci run` reads the checks from the revision it checks. +Each command runs in a process group of its own. On Linux, what it leaves +running in that group is killed once it ends, or if the run was killed, by +the next run; a process that leaves the group escapes. +On macOS, where origin can't tell which processes are still the check's, +nothing a check leaves running is killed, so stop it yourself. The +landing queue promotes results without running the toolchain command, so +new tools with unchanged inputs don't stop old results from being +promoted: pin the toolchain in an input, such as `rust-toolchain.toml`. +`origin ci run` checks a revision of this repository as you, and fails if a +check fails. Its checkouts +live in `$XDG_STATE_HOME/origin-ci/` (or `~/.local/state/`). + ## Permissions What each user may do lives in `policy.toml`, so changing it is a landing diff --git a/apps/origin-ci/Cargo.toml b/apps/origin-ci/Cargo.toml index 0478e37b..671fdbbd 100644 --- a/apps/origin-ci/Cargo.toml +++ b/apps/origin-ci/Cargo.toml @@ -7,7 +7,13 @@ rust-version.workspace = true license.workspace = true repository.workspace = true +[[bin]] +name = "origin-ci" +path = "src/main.rs" + [dependencies] +anyhow.workspace = true +clap.workspace = true origin-platform.workspace = true origin-shared.workspace = true origin-src.workspace = true diff --git a/apps/origin-ci/src/lib.rs b/apps/origin-ci/src/lib.rs index b8ecef4a..75e005fe 100644 --- a/apps/origin-ci/src/lib.rs +++ b/apps/origin-ci/src/lib.rs @@ -1,6 +1,11 @@ //! `origin-ci`, origin's CI plugin. It runs the checks a revision's //! `checks.toml` lists and issues their results as statements, which the //! landing queue takes as evidence. +//! +//! As a tool, `origin ci run` checks a revision of the repository it runs +//! in, as the user. It talks to origin only through the public API: the +//! SDK over HTTP, or for a repository on a local path, the same service +//! in-process. pub mod checks; pub mod runner; diff --git a/apps/origin-ci/src/main.rs b/apps/origin-ci/src/main.rs new file mode 100644 index 00000000..5de0c69f --- /dev/null +++ b/apps/origin-ci/src/main.rs @@ -0,0 +1,125 @@ +//! The `origin-ci` binary, which `origin ci` runs. + +use std::process::ExitCode; + +use anyhow::{Context as _, Result, bail}; +use clap::{Parser, Subcommand}; +use origin_ci::runner::{Outcome, Runner}; +use origin_ci::state::State; +use origin_shared::api::At; +use origin_shared::{ChangeId, RecordId, RevisionId}; +use origin_src::config::UserConfig; +use origin_src::output; +use origin_src::plugin::Context; +use origin_src::remote::{Remote, RemoteUrl}; + +/// Run the checks of `checks.toml` and issue their results. +#[derive(Debug, Parser)] +#[command(name = "origin ci", version)] +struct Cli { + #[command(subcommand)] + command: Command, +} + +#[derive(Debug, Subcommand)] +enum Command { + /// Run a revision's checks here, as its own `checks.toml` defines them, + /// and issue their results as you, in this repository. Skips checks that a + /// result of yours, run or promoted, already covers. Fails if a check + /// fails. + Run { + /// The revision: `@` for the working copy, a change's full id for its + /// head, or a revision's full id. + #[arg(default_value = "@")] + rev: String, + }, +} + +fn main() -> ExitCode { + output::exit_quietly_on_broken_pipe(); + match Cli::parse().run() { + Ok(code) => code, + Err(error) => { + eprintln!("error: {error:#}"); + ExitCode::FAILURE + } + } +} + +impl Cli { + fn run(self) -> Result { + let config = UserConfig::load()?; + let context = Context::from_env()?; + match self.command { + Command::Run { rev } => { + let (runner, subject) = Self::here(context.as_ref(), &config, "run", &rev)?; + let outcomes = runner.check(subject, &At::Record(subject), None)?; + Ok(Self::report(&outcomes)) + } + } + } + + /// Creates a runner for the repository `origin ci ` runs in, as + /// the user, and returns it with the record `rev` names there. + fn here( + context: Option<&Context>, + config: &UserConfig, + command: &str, + rev: &str, + ) -> Result<(Runner, RecordId)> { + let Some(context) = context else { + bail!("run `origin ci {command}` in a working copy"); + }; + let url = RemoteUrl::Path(context.repository.clone()); + let runner = Self::runner(&url, config)?; + let subject = Self::subject(&runner, context, rev)?; + Ok((runner, subject)) + } + + /// Prints each outcome, and the output of each failed check. Returns a + /// failing exit code if a check failed. + fn report(outcomes: &[Outcome]) -> ExitCode { + let mut failed = false; + for outcome in outcomes { + println!("{outcome}"); + if let Outcome::Ran { output, .. } = outcome + && outcome.failed() + { + print!("{}", String::from_utf8_lossy(output)); + } + failed |= outcome.failed(); + } + if failed { + ExitCode::FAILURE + } else { + ExitCode::SUCCESS + } + } + + /// Creates a runner for the repository at `url`, as the user. + fn runner(url: &RemoteUrl, config: &UserConfig) -> Result { + let remote = Remote::open_for(url, config).with_context(|| format!("cannot open {url}"))?; + Ok(Runner::new(remote, config.user(), State::open(url)?)?) + } + + /// Returns the record `rev` names: the working copy, a change's head, or a + /// revision. + fn subject(runner: &Runner, context: &Context, rev: &str) -> Result { + if rev == "@" { + return Ok(RecordId::Revision(context.revision)); + } + if let Ok(revision) = rev.parse::() { + return Ok(RecordId::Revision(revision)); + } + let change: ChangeId = rev + .parse() + .with_context(|| format!("`{rev}` is neither `@`, a change's id nor a revision's"))?; + match runner.remote().revisions(change)?.heads[..] { + [head] => Ok(RecordId::Revision(head)), + _ => bail!( + "change {} is divergent: name one of its heads", + change.short() + ), + } + } +} diff --git a/apps/origin-ci/tests/ci.rs b/apps/origin-ci/tests/ci.rs new file mode 100644 index 00000000..bad92eb5 --- /dev/null +++ b/apps/origin-ci/tests/ci.rs @@ -0,0 +1,272 @@ +//! End-to-end tests of `origin ci` as a tool in a working copy, through +//! the real `origin` and `origin-ci` binaries. + +#[path = "../../origin-src/tests/common/mod.rs"] +mod common; + +use std::fs; +use std::path::Path; +use std::thread; +use std::time::{Duration, Instant}; + +use common::Repo; +use origin_platform::{Native, Processes}; + +/// Returns a `checks.toml` whose `test` check reads `src` (and, like every +/// check, `checks.toml`), and appends a line to `log` each time it runs. +fn checks(log: &Path) -> String { + format!( + "[checks.test]\ncommand = \"test -f src/lib.rs && echo tested && echo ran >> {}\"\n\ + inputs = [\"src\"]\ntoolchain = \"echo toolchain 1\"\n", + log.display() + ) +} + +/// Returns how many times the check logging to `log` ran. +fn runs(log: &Path) -> usize { + fs::read_to_string(log).map_or(0, |log| log.lines().count()) +} + +#[test] +fn tool_mode_runs_checks_and_promotes_unchanged_results() { + let repo = Repo::new(); + let dir = tempfile::tempdir().unwrap(); + let log = dir.path().join("log"); + repo.write("src/lib.rs", "fn a() {}\n"); + repo.write( + "checks.toml", + &(checks(&log) + + "[checks.lint]\ncommand = \"echo lint failed; exit 1\"\ninputs = [\"src\"]\n"), + ); + + let output = repo.run(repo.root(), &["ci", "run"]); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert!(!output.status.success(), "lint fails: {stdout}"); + assert!(stdout.contains("ci.lint fail in "), "{stdout}"); + assert!( + stdout.contains("lint failed\n"), + "a failure shows its output: {stdout}" + ); + assert!(stdout.contains("ci.test pass in "), "{stdout}"); + assert_eq!(runs(&log), 1); + let statements = repo.ok(&["statements"]); + assert!( + statements.contains("ci.test pass by user:ada\n"), + "{statements}" + ); + assert!(statements.contains(" payload: tested\n"), "{statements}"); + + let again = repo.run(repo.root(), &["ci", "run"]); + let stdout = String::from_utf8(again.stdout).unwrap(); + assert!(stdout.contains("ci.test pass, already ran"), "{stdout}"); + assert_eq!(runs(&log), 1); + + repo.write("docs/guide.md", "# Guide\n"); + let stdout = String::from_utf8(repo.run(repo.root(), &["ci", "run"]).stdout).unwrap(); + assert!(stdout.contains("ci.test pass, promoted"), "{stdout}"); + assert!(stdout.contains("ci.lint fail, promoted"), "{stdout}"); + assert_eq!(runs(&log), 1); + + repo.write("src/lib.rs", "fn b() {}\n"); + let stdout = String::from_utf8(repo.run(repo.root(), &["ci", "run"]).stdout).unwrap(); + assert!(stdout.contains("ci.test pass in "), "{stdout}"); + assert_eq!(runs(&log), 2); + + repo.ok(&["annotate", "@", "ci.test", "--withdraw"]); + let stdout = String::from_utf8(repo.run(repo.root(), &["ci", "run"]).stdout).unwrap(); + assert!(stdout.contains("ci.test pass in "), "{stdout}"); + assert_eq!(runs(&log), 3); + + let state = repo.config().join("state/origin-ci"); + let [key] = &fs::read_dir(&state).unwrap().collect::>()[..] else { + panic!("one repository's state"); + }; + let runs = key.as_ref().unwrap().path().join("runs"); + assert_eq!(fs::read_dir(runs).unwrap().count(), 0); +} + +#[test] +fn runs_replace_promotions_a_result_there_replaces() { + let repo = Repo::new(); + let dir = tempfile::tempdir().unwrap(); + let log = dir.path().join("log"); + repo.write("src/lib.rs", "fn a() {}\n"); + repo.write("checks.toml", &checks(&log)); + let run = || String::from_utf8(repo.run(repo.root(), &["ci", "run"]).stdout).unwrap(); + assert!(run().contains("ci.test pass in ")); + let promoted = |file: &str| { + repo.ok(&["new"]); + repo.write(file, "docs\n"); + assert!(run().contains("ci.test pass, promoted")); + }; + let ran = |runs_now| { + let stdout = run(); + assert!(stdout.contains("ci.test pass in "), "{stdout}"); + assert_eq!(runs(&log), runs_now); + }; + + promoted("failed.md"); + repo.ok(&["annotate", "@", "ci.test", "--fail"]); + ran(2); + promoted("withdrawn.md"); + repo.ok(&["annotate", "@", "ci.test", "--neutral"]); + repo.ok(&["annotate", "@", "ci.test", "--withdraw"]); + ran(3); +} + +#[test] +fn a_promotion_of_a_result_taken_back_covers_nothing() { + let repo = Repo::new(); + let dir = tempfile::tempdir().unwrap(); + let log = dir.path().join("log"); + repo.write("src/lib.rs", "fn a() {}\n"); + repo.write("checks.toml", &checks(&log)); + let run = || String::from_utf8(repo.run(repo.root(), &["ci", "run"]).stdout).unwrap(); + assert!(run().contains("ci.test pass in ")); + let first = repo.revision(); + repo.ok(&["new"]); + repo.write("docs.md", "docs\n"); + assert!(run().contains("ci.test pass, promoted")); + + repo.ok(&["annotate", &first, "ci.test", "--withdraw"]); + let stdout = run(); + assert!(stdout.contains("ci.test pass in "), "{stdout}"); + assert_eq!(runs(&log), 2); +} + +#[test] +fn checks_run_in_checkouts_of_their_own() { + let repo = Repo::new(); + repo.write("input", "broken\n"); + repo.write( + "checks.toml", + "[checks.fix]\ncommand = \"echo fixed > input\"\n\ + [checks.verify]\ncommand = \"grep -q fixed input\"\n", + ); + let output = repo.run(repo.root(), &["ci", "run"]); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert!(!output.status.success(), "{stdout}"); + assert!(stdout.contains("ci.fix pass in "), "{stdout}"); + assert!( + stdout.contains("ci.verify fail in "), + "it never sees what ci.fix wrote: {stdout}" + ); + assert_eq!(repo.read("input"), "broken\n"); +} + +#[test] +fn toolchains_are_told_apart_by_all_their_output() { + let repo = Repo::new(); + let dir = tempfile::tempdir().unwrap(); + let tools = dir.path().join("tools"); + let version = |version: &str| { + fs::write(&tools, format!("tool {version}\n{}", "x".repeat(100_000))).unwrap(); + }; + version("1"); + repo.write( + "checks.toml", + &format!( + "[checks.test]\ncommand = \"true\"\ntoolchain = \"cat {}\"\n", + tools.display() + ), + ); + let run = || String::from_utf8(repo.run(repo.root(), &["ci", "run"]).stdout).unwrap(); + assert!(run().contains("ci.test pass in ")); + version("2"); + let again = run(); + assert!(again.contains("ci.test pass in "), "{again}"); +} + +#[test] +fn checks_never_see_the_runners_token() { + let repo = Repo::new(); + repo.write( + "checks.toml", + "[checks.token]\ncommand = 'test -z \"$ORIGIN_TOKEN\"'\n", + ); + let output = repo.run(repo.root(), &["ci", "run"]); + let stdout = String::from_utf8(output.stdout).unwrap(); + assert!(stdout.contains("ci.token pass in "), "{stdout}"); +} + +/// Whether the process `pid` is running, as `kill -0` finds it. +fn alive(pid: &str) -> bool { + let probe = std::process::Command::new("kill") + .args(["-0", pid]) + .stderr(std::process::Stdio::null()) + .status(); + probe.unwrap().success() +} + +/// Waits for `path` to be written, once, and returns its content. Fails +/// after a minute. +#[expect(clippy::panic, reason = "A test helper fails by panicking.")] +fn written(path: &Path) -> String { + for _ in 0..3000 { + match fs::read_to_string(path) { + Ok(text) if text.ends_with('\n') => return text.trim_end().to_owned(), + _ => thread::sleep(Duration::from_millis(20)), + } + } + panic!("nothing wrote {}", path.display()); +} + +/// Waits until `pid` is gone. Fails after a few seconds. +#[expect(clippy::panic, reason = "A test helper fails by panicking.")] +fn gone(pid: &str) { + for _ in 0..250 { + if !alive(pid) { + return; + } + thread::sleep(Duration::from_millis(20)); + } + panic!("process {pid} still runs"); +} + +/// Waits until `pid`, which a check left running, is gone. `origin-ci` +/// kills it where the platform tells which group holds which files (see +/// `Processes::SEES_HELD_FILES`); elsewhere the test kills it, so nothing +/// is left running. +fn ended(pid: &str) { + if !Native::SEES_HELD_FILES { + let _ = std::process::Command::new("kill") + .args(["-9", pid]) + .status(); + } + gone(pid); +} + +#[test] +fn checks_leave_nothing_running_once_they_end_or_their_run_is_killed() { + let repo = Repo::new(); + let dir = tempfile::tempdir().unwrap(); + let started = dir.path().join("started"); + let check = |command: &str| { + let command = command.replace("{started}", &started.display().to_string()); + repo.write( + "checks.toml", + &format!("[checks.test]\ncommand = \"{command}\"\n"), + ); + let _ = fs::remove_file(&started); + }; + + check("sleep 60 & echo $! > {started}"); + let ran = Instant::now(); + let output = repo.run(repo.root(), &["ci", "run"]); + assert_eq!(output.status.success(), Native::SEES_HELD_FILES); + assert!( + ran.elapsed() < Duration::from_secs(30), + "it waited for sleep" + ); + ended(&written(&started)); + + check("sleep 60 & echo $! > {started}; wait"); + let (mut run, _) = repo.spawn(&["ci", "run"]); + let sleep = written(&started); + run.kill().unwrap(); + run.wait().unwrap(); + assert!(alive(&sleep), "nothing kills it yet"); + check("true"); + assert!(repo.run(repo.root(), &["ci", "run"]).status.success()); + ended(&sleep); +} diff --git a/apps/origin-src/benches/permissions.rs b/apps/origin-src/benches/permissions.rs index 768de842..856b3768 100644 --- a/apps/origin-src/benches/permissions.rs +++ b/apps/origin-src/benches/permissions.rs @@ -4,7 +4,7 @@ //! and as a user whom path rules withhold one directory from and keep from //! writing another. Landings sync, so run it on a real disk. -use std::sync::{Arc, LazyLock}; +use std::sync::LazyLock; use divan::Bencher; use origin_shared::api::{FetchSnapshot, LandRequest}; @@ -60,11 +60,8 @@ static SETUP: LazyLock = 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() }; diff --git a/apps/origin-src/benches/server.rs b/apps/origin-src/benches/server.rs index 8df953ed..92287786 100644 --- a/apps/origin-src/benches/server.rs +++ b/apps/origin-src/benches/server.rs @@ -4,7 +4,6 @@ //! service that keeps its index open with one that reads the index on each //! landing. Run it 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; @@ -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); @@ -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 { diff --git a/apps/origin-src/benches/sync.rs b/apps/origin-src/benches/sync.rs index 0947fcca..c82dbbea 100644 --- a/apps/origin-src/benches/sync.rs +++ b/apps/origin-src/benches/sync.rs @@ -6,8 +6,8 @@ //! remote's event cursor from the last fetch. Each benchmark includes the //! server's work and the client's durable writes, so run it 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; @@ -63,11 +63,8 @@ struct Setup { static SETUP: LazyLock = 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| { @@ -125,7 +122,10 @@ static SETUP: LazyLock = 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(); @@ -278,11 +278,8 @@ struct History { static HISTORY_SETUP: LazyLock = 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; diff --git a/apps/origin-src/src/auth.rs b/apps/origin-src/src/auth.rs index 6be7b3d5..906abdaa 100644 --- a/apps/origin-src/src/auth.rs +++ b/apps/origin-src/src/auth.rs @@ -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; /// Maps static credentials to principals. The server configuration's tokens are /// one implementation; external identity providers can be others. @@ -47,23 +47,20 @@ impl Authenticator for StaticTokens { } } -/// How a server identifies its callers: its node, which verifies the tokens it -/// signed, and its static credentials. +/// How a server identifies its callers: 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, } impl Credentials { - /// Creates the credentials of `node`'s callers, whose static credentials - /// `authenticator` checks. + /// Creates the credentials for callers of the node whose public key is `key`; + /// `authenticator` checks their static credentials. #[must_use] - pub fn new(node: Node, authenticator: Box) -> Self { - Self { - node, - authenticator, - } + pub fn new(key: NodePublicKey, authenticator: Box) -> Self { + Self { key, authenticator } } /// Returns the caller an `Authorization` header's value stands for, or an @@ -80,7 +77,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 { @@ -102,7 +99,6 @@ impl Credentials { #[cfg(test)] mod tests { - use std::sync::Arc; use std::time::Duration; use origin_shared::NodeKey; @@ -113,17 +109,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); diff --git a/apps/origin-src/src/config.rs b/apps/origin-src/src/config.rs index 06cfc4fe..df740db7 100644 --- a/apps/origin-src/src/config.rs +++ b/apps/origin-src/src/config.rs @@ -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}; @@ -139,7 +140,49 @@ impl UserConfig { /// /// Fails like [`KeyFile::load`]. pub fn node_key(&self) -> Result { - KeyFile(self.dir.join("node.key")).load() + self.key_file().load() + } + + /// Returns 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 a node that never signs never reads or 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), +} + +impl From for LazyKey { + fn from(file: KeyFile) -> Self { + Self::File(file, OnceLock::new()) + } +} + +impl LazyKey { + /// Returns the key, loading it 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)) + } + } } } diff --git a/apps/origin-src/src/permissions/tests.rs b/apps/origin-src/src/permissions/tests.rs index 1949e1d0..4fa9af3a 100644 --- a/apps/origin-src/src/permissions/tests.rs +++ b/apps/origin-src/src/permissions/tests.rs @@ -1,5 +1,3 @@ -use std::sync::Arc; - use origin_platform::Native; use origin_shared::api::{FetchSnapshot, LandRequest}; use origin_shared::landing::{Landing, Proposal}; @@ -60,10 +58,7 @@ impl Fixture { ], ); 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 } } diff --git a/apps/origin-src/src/remote.rs b/apps/origin-src/src/remote.rs index 86752b2c..37816ae0 100644 --- a/apps/origin-src/src/remote.rs +++ b/apps/origin-src/src/remote.rs @@ -10,16 +10,17 @@ use std::fmt; use std::path::{self, Path, PathBuf}; use origin_client::Client; -use origin_shared::Head; use origin_shared::access::Rights; use origin_shared::api::{ Annotation, BrowseQuery, ErrorCode, EventsQuery, FetchRecords, FetchSnapshot, Inventory, InventoryRequest, IssuedToken, LandRequest, Landings, Listing, LogEntry, LogQuery, NewTarget, - PromoteRequest, PutQuery, RepoName, StatementsQuery, Stored, TargetInfo, TokenRequest, + PromoteRequest, PutQuery, RepoName, Revisions, StatementsQuery, Stored, TargetInfo, + TokenRequest, }; use origin_shared::event::Page; use origin_shared::landing::Pending; use origin_shared::pack::{Pack, Part}; +use origin_shared::{ChangeId, Head}; use crate::config::UserConfig; use crate::service::{Caller, Node, OriginService, ServiceError}; @@ -76,6 +77,8 @@ calls! { /// Fetches, in parts, the trees and blobs of a snapshot that the request's /// snapshots lack. fn snapshot(request: &FetchSnapshot) -> Part = fetch_snapshot(request), snapshot(request); + /// Returns the revisions of a change, and its heads. + fn revisions(change: ChangeId) -> Revisions = revisions(change), revisions(change); /// Returns what the remote holds of some changes. fn inventory(request: &InventoryRequest) -> Vec = inventory(request), inventory(request); @@ -111,6 +114,16 @@ calls! { } impl Remote { + /// Opens the remote at `url` for the user of `config`: over HTTP, with their + /// token for its server if they have one, or in-process as their node. + /// + /// # Errors + /// + /// Fails like [`Remote::open`]. + pub fn open_for(url: &RemoteUrl, config: &UserConfig) -> Result { + Self::open(url, Node::of(config), url.token(config)) + } + /// Opens the remote at `url`: an `http://` URL whose last path segment names /// the repository, called with `token` if there is one, or the path of a /// repository, which `node` serves in-process, to its owner. diff --git a/apps/origin-src/src/server.rs b/apps/origin-src/src/server.rs index 5dc1b921..37f20ee2 100644 --- a/apps/origin-src/src/server.rs +++ b/apps/origin-src/src/server.rs @@ -94,10 +94,10 @@ impl ServerConfig { /// /// Fails if the key cannot be read, or generated and saved. pub fn node(&self) -> anyhow::Result { - 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 ]`: creates an empty repository in @@ -110,7 +110,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`", @@ -140,7 +140,7 @@ impl ServerConfig { ttl: Duration, ) -> anyhow::Result { 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 failures @@ -159,7 +159,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() @@ -351,7 +351,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); diff --git a/apps/origin-src/src/service.rs b/apps/origin-src/src/service.rs index acea4bf0..b180cae3 100644 --- a/apps/origin-src/src/service.rs +++ b/apps/origin-src/src/service.rs @@ -36,6 +36,7 @@ use origin_shared::{ use parking_lot::{Condvar, Mutex, MutexGuard}; use crate::annotations::{AnnotateError, Annotations}; +use crate::config::{ConfigError, LazyKey, UserConfig}; use crate::events::{Events, Wakeup}; use crate::index::Index; pub use crate::permissions::Caller; @@ -45,18 +46,46 @@ use crate::queue::{LandError, Queue, Waiting}; use crate::store::{Store, StoreError}; use crate::tree::Snapshots; -/// A node: its name, and the key it signs acceptances with as the authority of -/// the targets its repositories' policies name it for. All repositories on a -/// server share one node. +/// A node: its name, and the key it signs acceptances and tokens with as the +/// authority of the targets its repositories' policies name it for. All +/// repositories on a server share one node. #[derive(Clone, Debug)] pub struct Node { /// The node's name. pub name: PrincipalName, - /// The node's signing key. - pub key: Arc, + key: Arc, } impl Node { + /// Creates the node `name`, with its key in hand. + #[must_use] + pub fn new(name: PrincipalName, key: NodeKey) -> Self { + Self { + name, + key: Arc::new(LazyKey::Loaded(key)), + } + } + + /// Returns the node of the user's configuration. Its key is loaded, or + /// generated, only the first time it signs, so calls that only read never touch + /// it. + #[must_use] + pub fn of(config: &UserConfig) -> Self { + Self { + name: config.node().clone(), + key: Arc::new(config.key_file().into()), + } + } + + /// Returns the node's key, loading or generating it the first time. + /// + /// # Errors + /// + /// Fails if the key cannot be read, or generated and saved. + pub fn key(&self) -> Result<&NodeKey, ConfigError> { + self.key.get() + } + /// Returns the node as a principal: the issuer of the statements it makes. fn principal(&self) -> Principal { Principal::Node(self.name.clone()) @@ -140,7 +169,7 @@ impl OriginService { } let store = Store::new(root, Native::default()); store.init()?; - Queue::new(&store, &node.key, node.name.clone()).init(policy)?; + Queue::new(&store, node.key()?, node.name.clone()).init(policy)?; Ok(Self::new(store, node)) } @@ -279,7 +308,7 @@ impl OriginService { token.expires = token.expires.min(scope.expires); } Ok(IssuedToken { - token: token.sign(&self.node.key), + token: token.sign(self.node.key()?), principal: token.principal, expires: token.expires, }) @@ -1164,7 +1193,7 @@ impl OriginService { Err(ServiceError::from(Forbidden::Land(onto.clone()))) } }; - let queue = Queue::new(&self.store, &self.node.key, self.node.name.clone()) + let queue = Queue::new(&self.store, self.node.key()?, self.node.name.clone()) .submitted_by(caller.clone(), rights.paths.clone()); let landed = self.annotations(|annotations| { let landed = match &request.proposal { @@ -1249,7 +1278,7 @@ impl OriginService { if !self.rights(caller)?.may_land(&request.name) { return Err(Forbidden::Land(request.name.clone()).into()); } - let queue = Queue::new(&self.store, &self.node.key, self.node.name.clone()); + let queue = Queue::new(&self.store, self.node.key()?, self.node.name.clone()); let head = queue.create_target(&request.name, &request.from)?; self.wakeup.notify(); Ok(head) @@ -1671,6 +1700,9 @@ pub enum ServiceError { /// Records cannot be read or written. #[error(transparent)] Store(#[from] StoreError), + /// The node's key, needed to sign, cannot be loaded. + #[error(transparent)] + NodeKey(#[from] ConfigError), } impl From for ServiceError { @@ -1728,7 +1760,9 @@ impl ServiceError { LandError::Policy(_) | LandError::Annotate(_) => ErrorCode::Internal, }, Self::Store(error) => Self::store_code(error), - Self::NotARepository(_) | Self::NotEmpty(_) | Self::Policy(_) => ErrorCode::Internal, + Self::NotARepository(_) | Self::NotEmpty(_) | Self::Policy(_) | Self::NodeKey(_) => { + ErrorCode::Internal + } } } @@ -1758,10 +1792,7 @@ mod tests { /// conflict: its description, the conflict's payload, the revision and the /// conflict. fn conflicted(repo: &crate::queue::tests::Repo) -> (OriginService, [EncodedObject; 4]) { - 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); let description = EncodedObject::attachment(b""); let revision = origin_shared::Revision { @@ -1903,11 +1934,8 @@ mod tests { #[test] fn calls_using_the_index_do_not_wait_for_each_other() { 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("repo"), node, &policy).unwrap(); // A landing holds an index all along: a read meanwhile takes another. let read = service.annotations(|_| { @@ -1947,10 +1975,7 @@ mod tests { "[targets.main]\nauthority = \"node:queue\"\n\ require = [{ kind = \"ci.test\", verdict = \"pass\", issuer = \"user:ci\" }]\n", ); - 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); (repo, service) } diff --git a/apps/origin-src/src/sync/tests.rs b/apps/origin-src/src/sync/tests.rs index 73bc0775..2f69a842 100644 --- a/apps/origin-src/src/sync/tests.rs +++ b/apps/origin-src/src/sync/tests.rs @@ -1,5 +1,3 @@ -use std::sync::Arc; - use origin_platform::Native; use origin_shared::event::Filter; use origin_shared::{AcceptanceBody, Kind, NodeKey, Verdict}; @@ -31,10 +29,7 @@ impl Client { let dir = tempfile::tempdir().unwrap(); let store = Store::new(dir.path().join(".origin"), Native::default()); store.init().unwrap(); - 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(server.store.clone(), node).with_pack_limit(limit); let remote = Remote::Local(Box::new(service)); Self { diff --git a/apps/origin-src/src/workspace/annotate.rs b/apps/origin-src/src/workspace/annotate.rs index a1322952..9e8dc21a 100644 --- a/apps/origin-src/src/workspace/annotate.rs +++ b/apps/origin-src/src/workspace/annotate.rs @@ -159,7 +159,7 @@ impl Workspace { } issued => issued?, }; - self.service(Some(annotations.into_index()))? + self.service(Some(annotations.into_index())) .resume(Some(&HashSet::from([subject])))?; if let Some(verdict) = statement.verdict { println!( @@ -241,7 +241,7 @@ impl Workspace { pub fn statements(&mut self, rev: &str) -> Result<(), WorkspaceError> { let working_copy = self.snapshot()?; let revision = working_copy.find_revision(rev)?; - let service = self.service(Some(working_copy.index))?; + let service = self.service(Some(working_copy.index)); let subject = RecordId::Revision(revision); if !self.print_statements(&service, subject, "", &mut HashSet::new())? { println!("No statements about revision {}", revision.short()); @@ -348,7 +348,7 @@ impl Workspace { let working_copy = self.refresh()?; let revision = working_copy.find_revision(rev)?; let promoted = self - .service(Some(working_copy.index))? + .service(Some(working_copy.index)) .promote(&Caller::Owner, RecordId::Revision(revision))?; if promoted.is_empty() { println!("Nothing to promote to revision {}", revision.short()); diff --git a/apps/origin-src/src/workspace/land.rs b/apps/origin-src/src/workspace/land.rs index 913badb3..2ea3b778 100644 --- a/apps/origin-src/src/workspace/land.rs +++ b/apps/origin-src/src/workspace/land.rs @@ -69,7 +69,7 @@ impl Workspace { landed } None => self - .service(Some(mem::take(&mut working_copy.index)))? + .service(Some(mem::take(&mut working_copy.index))) .land(&Caller::Owner, &request)?, }; for landing in &landings { @@ -108,7 +108,7 @@ impl Workspace { self.sync(remote).fetch_chains(slice::from_ref(onto))?; landed } - None => self.service(None)?.land(&Caller::Owner, &request)?, + None => self.service(None).land(&Caller::Owner, &request)?, }; for landing in &landed.landings { self.print_landing(landing, onto)?; @@ -123,7 +123,7 @@ impl Workspace { /// /// Fails if the queues cannot be read. pub fn land_status(&self) -> Result<(), WorkspaceError> { - let mut pending = self.service(None)?.landings(&Caller::Owner)?; + let mut pending = self.service(None).landings(&Caller::Owner)?; if let Some(remote) = self.remote()? { pending.extend(remote.landings()?); } @@ -154,9 +154,7 @@ impl Workspace { self.sync(remote).fetch_chains(slice::from_ref(name))?; head } - None => self - .service(None)? - .create_target(&Caller::Owner, &request)?, + None => self.service(None).create_target(&Caller::Owner, &request)?, }; let landed = self.store.get(head.acceptance)?.body().landed.clone(); let from = match landed[..] { @@ -176,7 +174,7 @@ impl Workspace { /// /// Fails if the remote fails, or the targets or the policy cannot be read. pub fn targets(&self) -> Result<(), WorkspaceError> { - let mut targets = self.service(None)?.targets(&Caller::Owner)?; + let mut targets = self.service(None).targets(&Caller::Owner)?; if let Some(remote) = self.remote()? { let remote = remote.targets()?; targets.retain(|own| !remote.iter().any(|target| target.name == own.name)); diff --git a/apps/origin-src/src/workspace/mod.rs b/apps/origin-src/src/workspace/mod.rs index 294fc802..3276bda7 100644 --- a/apps/origin-src/src/workspace/mod.rs +++ b/apps/origin-src/src/workspace/mod.rs @@ -34,7 +34,7 @@ use std::fs; use std::io; use std::mem; use std::path::{Path, PathBuf}; -use std::sync::{Arc, OnceLock}; +use std::sync::OnceLock; use origin_platform::{LockMode, LockedFile, Native}; use origin_shared::api::{LogQuery, RevisionEntry, Revisions}; @@ -407,13 +407,14 @@ impl Workspace { /// Returns this repository's service, run by this node. The commands that the /// API also offers go through it. It finds records through `index` if the - /// command already read it, or else reads the index when needed. - fn service(&self, index: Option) -> Result { - let service = OriginService::new(self.store.clone(), self.node()?); - Ok(match index { + /// command already read it, or else reads the index when needed. It loads the + /// node's key only once a call signs. + fn service(&self, index: Option) -> OriginService { + let service = OriginService::new(self.store.clone(), Node::of(&self.config)); + match index { Some(index) => service.with_index(index), None => service, - }) + } } /// Returns what a plugin run in this working copy learns of it, after recording @@ -431,19 +432,6 @@ impl Workspace { }) } - /// Returns this node, with its key. - fn node(&self) -> Result { - Self::node_of(&self.config) - } - - /// Returns the node `config` names, with its key. - fn node_of(config: &UserConfig) -> Result { - Ok(Node { - name: config.node().clone(), - key: Arc::new(config.node_key()?), - }) - } - /// Snapshots the working copy into a draft, recording nothing, for the /// commands that only read it. fn snapshot(&mut self) -> Result { @@ -1396,7 +1384,7 @@ impl Workspace { since, limit: limit.map(|limit| u64::try_from(limit).unwrap_or(u64::MAX)), }; - let log = self.service(None)?.log(&Caller::Owner, &query)?; + let log = self.service(None).log(&Caller::Owner, &query)?; if target.id() == on { for (id, revision) in &stack { let marker = if *id == working_copy.id { '@' } else { '○' }; @@ -1440,7 +1428,7 @@ impl Workspace { let change = working_copy.find_change(change)?; let flags = self.flags(&working_copy.index, change)?; let Revisions { revisions, heads } = self - .service(Some(mem::take(&mut working_copy.index)))? + .service(Some(mem::take(&mut working_copy.index))) .revisions(&Caller::Owner, change)?; println!("Change {}{flags}", change.short()); for RevisionEntry { id, revision } in revisions.iter().rev() { diff --git a/apps/origin-src/src/workspace/ops.rs b/apps/origin-src/src/workspace/ops.rs index 79bd3f7f..7dd29d25 100644 --- a/apps/origin-src/src/workspace/ops.rs +++ b/apps/origin-src/src/workspace/ops.rs @@ -223,7 +223,7 @@ impl Workspace { ) -> Result<(), WorkspaceError> { self.lock = None; let remote = if local { None } else { self.remote()? }; - let service = self.service(None)?; + let service = self.service(None); let mut query = EventsQuery { cursor: since, generation: None, diff --git a/apps/origin-src/src/workspace/remote.rs b/apps/origin-src/src/workspace/remote.rs index 73960b3b..7b6548e9 100644 --- a/apps/origin-src/src/workspace/remote.rs +++ b/apps/origin-src/src/workspace/remote.rs @@ -224,12 +224,12 @@ impl Workspace { Ok(self.remote.get_or_init(|| remote).as_ref()) } - /// Opens the remote at `url` for the user of `config`, with their token for it - /// if they have one. Refuses a repository on a local path that has a remote of - /// its own, such as a clone: it only holds the snapshots it read, but syncing - /// needs a remote that holds the snapshot of every record. + /// Opens the remote at `url` for the user of `config`. Refuses a repository on + /// a local path that has a remote of its own, such as a clone: it only holds + /// the snapshots it read, but syncing needs a remote that holds the snapshot of + /// every record. fn open_remote(url: &RemoteUrl, config: &UserConfig) -> Result { - let remote = Remote::open(url, Self::node_of(config)?, url.token(config))?; + let remote = Remote::open_for(url, config)?; if let Remote::Local(service) = &remote && Self::remote_url(service.store())?.is_some() { diff --git a/apps/origin-src/tests/cli.rs b/apps/origin-src/tests/cli.rs index fb092723..1f50d6e2 100644 --- a/apps/origin-src/tests/cli.rs +++ b/apps/origin-src/tests/cli.rs @@ -516,6 +516,20 @@ fn init_with_a_malformed_key_leaves_no_repository() { assert!(!other.path().join(".origin").exists()); } +#[test] +fn only_commands_that_sign_load_the_node_key() { + let repo = Repo::new(); + let key = repo.config().join("node.key"); + fs::remove_file(&key).unwrap(); + repo.ok(&["targets"]); + assert!(!key.exists(), "reading created a key"); + fs::write(&key, b"short").unwrap(); + repo.ok(&["targets"]); + repo.ok(&["log", "main"]); + let refused = repo.fails(&["land"]); + assert!(refused.contains("is not a node key"), "{refused}"); +} + #[test] fn only_the_creator_of_a_change_or_admins_abandon_it() { let repo = Repo::new(); diff --git a/apps/origin-src/tests/common/mod.rs b/apps/origin-src/tests/common/mod.rs index 58fcd2e2..4f5577ce 100644 --- a/apps/origin-src/tests/common/mod.rs +++ b/apps/origin-src/tests/common/mod.rs @@ -93,13 +93,15 @@ impl User { } /// Builds an `origin` command with `args` that runs in `cwd` as this user, - /// with the plugins built with it on `$PATH`. + /// with the plugins built with it on `$PATH`. Plugins keep their state in + /// the user's configuration directory. pub fn command(&self, cwd: &Path, args: &[&str]) -> Command { let mut command = Command::new(origin()); command .args(args) .current_dir(cwd) .env("ORIGIN_CONFIG_DIR", self.config()) + .env("XDG_STATE_HOME", self.config().join("state")) .env("PATH", path_with_plugins()) .env_remove("ORIGIN_TOKEN"); if let Some(token) = &self.token { diff --git a/apps/origin-src/tests/http.rs b/apps/origin-src/tests/http.rs index 8f820b59..027e09b0 100644 --- a/apps/origin-src/tests/http.rs +++ b/apps/origin-src/tests/http.rs @@ -3,7 +3,6 @@ use std::collections::BTreeMap; use std::slice; -use std::sync::Arc; use std::time::{Duration, Instant}; use origin_client::{Client, Error, Repo}; @@ -51,11 +50,8 @@ impl Server { async fn start() -> Self { let dir = tempfile::tempdir().unwrap(); - let node = Node { - name: "hosted".parse().unwrap(), - key: Arc::new(NodeKey::from_bytes(&[7; 32])), - }; - let open = Policy::initial(&node.name, &node.key.public(), None); + let node = Node::new("hosted".parse().unwrap(), NodeKey::from_bytes(&[7; 32])); + let open = Policy::initial(&node.name, &node.key().unwrap().public(), None); let strict = format!( "[nodes]\nhosted = \"{}\"\n[targets.policy]\nauthority = \"node:hosted\"\n\ [targets.main]\nauthority = \"node:hosted\"\n\ @@ -64,10 +60,13 @@ impl Server { \"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() + node.key().unwrap().public() ); let tokens: StaticTokens = toml::from_str(Self::TOKENS).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), + )); for (name, policy) in [("demo", open), ("strict", strict)] { let service = OriginService::create(dir.path().join(name), node.clone(), &policy).unwrap(); diff --git a/budget.toml b/budget.toml index 397a5bfd..e9498404 100644 --- a/budget.toml +++ b/budget.toml @@ -1,7 +1,7 @@ # Each crate's `#[expect]` lints, which the owner reviews; see the standard's # README. [expect] -origin-ci = 2 +origin-ci = 4 origin-platform = 2 origin-shared = 3 origin-src = 11