diff --git a/docs/architecture.md b/docs/architecture.md index a6efa72..b5c8094 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -614,6 +614,10 @@ none can be read as an option, and `--` comes before the hostname. - ssh keeps the first value of an option. `nix copy` to `ssh://` adds `PermitLocalCommand=yes` and waits for `echo started`, so the broker's `PermitLocalCommand=no` would hang it forever (see `copy_options`). +- A copy from a remote builder's store to a node has one `NIX_SSHOPTS` for both connections. + The builder's store URL therefore carries its port and key (`ssh-ng://user@host:port?ssh-key=`): + Nix puts them after `NIX_SSHOPTS`, and for `-p` the last value wins (see + `DeployConfig::builder_store`). - A tokio program that reads stdin can't return from `main` while that read blocks; the builder worker calls `std::process::exit` after writing its result. - Session variables from home-manager only reach shells started after the next login diff --git a/docs/design.md b/docs/design.md index a899fde..7577983 100644 --- a/docs/design.md +++ b/docs/design.md @@ -402,6 +402,11 @@ broker runs it over SSH. Nix daemon. - Only `git` gets the repository key, never the evaluator. - Build logs stream to the agent. One build runs at a time. + - The builder can be on another box with a store of its own + (`services.slop-broker.deploy.builder.remoteStore`). The broker then reads built paths from + there, `nix copy --from ssh-ng://` its user with the broker's key. The builder key's forced + command serves `nix-daemon --stdio` for that. Nothing lands in the broker's store, and the + builder never holds a key to the nodes or the cache. 4. **Compare, before approval.** The broker copies the closures to each node, as deploy-rs does, and compares each profile with the one installed. - Nodes substitute what the caches have; progress streams to the agent. diff --git a/nix/modules/nixos/broker.nix b/nix/modules/nixos/broker.nix index 0ee0066..d39357f 100644 --- a/nix/modules/nixos/broker.nix +++ b/nix/modules/nixos/broker.nix @@ -111,6 +111,7 @@ let builder = with cfg.deploy.builder; { inherit hostname user; ssh_opts = sshOpts; }; nix = "${config.nix.package}/bin/nix"; cache = "/var/lib/slop-broker/cache"; + remote_store = cfg.deploy.builder.remoteStore; } else null; cache = if cfg.cache.enable then { @@ -169,7 +170,9 @@ in hostname = mkOpt' str "localhost" "Box running the builder (`services.slop-broker-builder`)."; user = mkOpt' str "slop-broker-build" "The builder's user."; sshOpts = mkOpt' (listOf str) [ "-p" (toString (head config.services.openssh.ports)) ] - "Extra SSH arguments for reaching the builder."; + "Extra SSH arguments for reaching the builder; with `remoteStore`, only `-p `."; + remoteStore = mkBoolOpt' false + "Whether the builder has a Nix store of its own (it's on another box), which the broker copies built paths from over `ssh-ng`. Otherwise it shares this box's."; }; }; diff --git a/nix/vm-test.nix b/nix/vm-test.nix index c5309b7..f7ca7d2 100644 --- a/nix/vm-test.nix +++ b/nix/vm-test.nix @@ -194,6 +194,13 @@ pkgs.testers.runNixOSTest { machine.succeed("su reviewer -c 'SLOP_APPROVE=ssh:slop@localhost slop-approve once'") machine.wait_until_succeeds("grep -q 'remote approval' /tmp/out4") + # A builder with a store of its own serves it to the broker's key as `nix-daemon --stdio` + machine.succeed("install -m600 /etc/slop-broker-test/key /root/builder-key") + system = machine.succeed("readlink -f /run/current-system").strip() + store = "ssh-ng://slop-broker-build@localhost:22?ssh-key=/root/builder-key" + out = machine.succeed(f"nix --extra-experimental-features nix-command path-info --store '{store}' {system}") + assert out.strip() == system, out + audit = machine.succeed("su reviewer -c 'slop-approve log'") print(audit) assert "agent asks: ssh local" in audit and "answered 5m by reviewer" in audit, audit diff --git a/src/builder.rs b/src/builder.rs index 5878c45..bff2f0f 100644 --- a/src/builder.rs +++ b/src/builder.rs @@ -284,11 +284,19 @@ async fn call( // The builder's side -/// The forced command: one build per connection, one at a time. +/// The forced command: one build per connection, one at a time. A broker whose builder has a +/// store of its own also reads built paths from it, as `nix-daemon --stdio` (`ssh-ng`). pub async fn worker(config: &Path) -> Result<()> { let text = std::fs::read_to_string(config).with_context(|| format!("reading {}", config.display()))?; let config: BuilderConfig = toml::from_str(&text)?; + if std::env::var("SSH_ORIGINAL_COMMAND").is_ok_and(|c| c == "nix-daemon --stdio") { + use std::os::unix::process::CommandExt; + let daemon = config.path.iter().map(|d| d.join("nix-daemon")).find(|p| p.exists()); + let daemon = daemon.context("no nix-daemon in the builder's path")?; + return Err(std::process::Command::new(daemon).arg("--stdio").exec()).context("running nix-daemon"); + } + let mut stdin = FramedRead::new(tokio::io::stdin(), codec()); let request: BuilderRequest = decode(&stdin.next().await.context("no request")??)?; // Nothing else comes on stdin; it closing means the broker gave up. diff --git a/src/config.rs b/src/config.rs index 25cede9..dbf917c 100644 --- a/src/config.rs +++ b/src/config.rs @@ -122,6 +122,38 @@ pub struct DeployConfig { pub nix: PathBuf, /// Writable directory for `nix`'s cache. pub cache: PathBuf, + /// The builder has a store of its own (it's on another box), which built paths are copied + /// from; otherwise it shares the broker's. + #[serde(default)] + pub remote_store: bool, +} + +impl DeployConfig { + /// The store that built paths are in, as a `nix` store URL reached with the broker's `key`, or + /// `None` for the broker's own. The port is always given: it comes after `NIX_SSHOPTS`, so a + /// node's `-p` can't send the builder's connection elsewhere when one copy uses both. + pub fn builder_store(&self, key: &Path) -> anyhow::Result> { + if !self.remote_store { + return Ok(None); + } + + let builder = &self.builder; + let port: u16 = match builder.ssh_opts.as_slice() { + [] => 22, + [flag, port] if flag == "-p" => port.parse().context("the builder's port")?, + _ => anyhow::bail!("with remote_store, the builder's ssh_opts can only set a port (-p )"), + }; + let host = + if builder.hostname.contains(':') { format!("[{}]", builder.hostname) } else { builder.hostname.clone() }; + + let key = credential(key); + let key = key.to_str().context("the SSH key's path isn't UTF-8")?; + anyhow::ensure!( + !key.contains(|c: char| c.is_whitespace() || "?&#%".contains(c)), + "the SSH key's path can't go in a store URL: {key}" + ); + Ok(Some(format!("ssh-ng://{}@{host}:{port}?ssh-key={key}", builder.user))) + } } /// The binary cache that `slop build` pushes to: a Nix store reached over SSH (`ssh-ng`), whose @@ -312,6 +344,9 @@ impl Config { self.ssh.is_none() || self.deploy.is_some(), "ssh needs deploy, whose builder reads the main branch's deploy-rs nodes" ); + if let (Some(ssh), Some(deploy)) = (&self.ssh, &self.deploy) { + deploy.builder_store(&ssh.key)?; + } Ok(()) } @@ -395,6 +430,32 @@ mod tests { ); } + #[test] + fn builder_stores() { + let builder = |hostname: &str, ssh_opts: &[&str]| SshTarget { + hostname: hostname.into(), + user: "build".into(), + ssh_opts: ssh_opts.iter().map(|o| o.to_string()).collect(), + sudo: default_sudo(), + containers: Default::default(), + }; + let deploy = + |builder, remote_store| DeployConfig { builder, nix: "/nix".into(), cache: "/cache".into(), remote_store }; + let key = Path::new("/run/key"); + + assert_eq!(deploy(builder("localhost", &["-p", "22"]), false).builder_store(key).unwrap(), None); + assert_eq!( + deploy(builder("builder.example", &[]), true).builder_store(key).unwrap().unwrap(), + "ssh-ng://build@builder.example:22?ssh-key=/run/key" + ); + assert_eq!( + deploy(builder("fd00::1", &["-p", "2222"]), true).builder_store(key).unwrap().unwrap(), + "ssh-ng://build@[fd00::1]:2222?ssh-key=/run/key" + ); + assert!(deploy(builder("b", &["-o", "ProxyJump=x"]), true).builder_store(key).is_err()); + assert!(deploy(builder("b", &[]), true).builder_store(Path::new("/run/a key")).is_err()); + } + #[test] fn unknown_operations_are_refused() { let config = "approve_socket = \"/a\"\napprover_group = \"g\"\n[policies.agent.ops.sssh]\naction = \"ask\"\n"; diff --git a/src/ops/build.rs b/src/ops/build.rs index 1abe826..85cbdc8 100644 --- a/src/ops/build.rs +++ b/src/ops/build.rs @@ -70,7 +70,7 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<() let built = builder::build(ssh, deploy, &request, &io.out, &io.cancel).await?; let paths: Vec<&str> = built.outputs.iter().flat_map(|o| &o.paths).map(String::as_str).collect(); - let sizes = closure_sizes(deploy, &paths, &io.cancel).await?; + let sizes = closure_sizes(ssh, deploy, &paths, &io.cancel).await?; let description = parsed.prepared.description.as_ref().context("the commit wasn't described")?; let mut detail = Detail::new(); @@ -135,10 +135,13 @@ fn copy_command(ssh: &SshConfig, deploy: &DeployConfig, cache: &CacheConfig, pat let options = nix_ssh_options(ssh::options_with_key(ssh, &cache.key), &cache.ssh_opts); ensure!(!options.iter().any(|o| o.contains(char::is_whitespace)), "SSH options can't contain spaces for nix copy"); + let from = deploy.builder_store(&ssh.key)?; + let mut command = nix(deploy, ssh.ssh.parent()); command .env("NIX_SSHOPTS", options.join(" ")) .args(["--extra-experimental-features", "nix-command", "copy", "--no-check-sigs"]) + .args(from.iter().flat_map(|from| ["--from", from])) .arg("--to") .arg(format!("ssh-ng://{}@{}", cache.user, cache.hostname)) .args(paths); @@ -156,14 +159,19 @@ fn nix(deploy: &DeployConfig, ssh_directory: Option<&Path>) -> Command { command } -/// Each path's closure size, human-readable, from the local store. +/// Each path's closure size, human-readable, from the builder's store. async fn closure_sizes( + ssh: &SshConfig, deploy: &DeployConfig, paths: &[&str], cancel: &CancellationToken, ) -> Result> { - let mut command = nix(deploy, None); + let mut command = nix(deploy, ssh.ssh.parent()); + command.env("NIX_SSHOPTS", nix_ssh_options(ssh::options(ssh), &[]).join(" ")); command.args(["--extra-experimental-features", "nix-command", "path-info", "--closure-size", "--human-readable"]); + if let Some(store) = deploy.builder_store(&ssh.key)? { + command.args(["--store", &store]); + } command.args(paths); let (exit, stdout, stderr) = exec::capture(command, cancel).await?; @@ -204,8 +212,12 @@ mod tests { #[test] fn uses_the_cache_key() { let ssh = ssh::tests::config(); - let deploy = - DeployConfig { builder: ssh.targets["river"].clone(), nix: "/bin/nix".into(), cache: "/var/cache".into() }; + let deploy = DeployConfig { + builder: ssh.targets["river"].clone(), + nix: "/bin/nix".into(), + cache: "/var/cache".into(), + remote_store: false, + }; let paths = ["/nix/store/0123456789abcdfghijklmnpqrsvwxyz-hello"]; let root = args(&cache_command(&ssh, &cache(), &[shell_quote(&[&["root"], &paths[..]].concat())])); @@ -219,6 +231,13 @@ mod tests { assert!(options.contains("-i /cache-key") && options.ends_with("-p 2222"), "{options}"); assert!(!options.contains("PermitLocalCommand=no"), "{options}"); assert!(args(©).contains(&"ssh-ng://harmonia@object.example".to_owned())); + assert!(!args(©).contains(&"--from".to_owned())); + + // A builder with a store of its own is copied from, with the broker's key + let remote = DeployConfig { remote_store: true, ..deploy }; + let copy = args(©_command(&ssh, &remote, &cache(), &paths).unwrap()); + let from = copy.iter().position(|a| a == "--from").unwrap(); + assert_eq!(copy[from + 1], "ssh-ng://deploy@river.example.org:2222?ssh-key=/key"); } #[test] diff --git a/src/ops/deploy.rs b/src/ops/deploy.rs index 471d42a..67141f2 100644 --- a/src/ops/deploy.rs +++ b/src/ops/deploy.rs @@ -183,6 +183,8 @@ async fn copy( let options = copy_options(ssh, node)?; ensure!(!options.iter().any(|o| o.contains(char::is_whitespace)), "SSH options can't contain spaces for nix copy"); + let from = deploy.builder_store(&ssh.key)?; + let ssh_directory = ssh.ssh.parent().map(|p| p.display().to_string()).unwrap_or_default(); let mut command = Command::new(&deploy.nix); command @@ -198,6 +200,7 @@ async fn copy( "--no-check-sigs", "--substitute-on-destination", ]) + .args(from.iter().flat_map(|from| ["--from", from])) .arg("--to") .arg(format!("ssh://{}@{}", target.user, target.hostname)) .args(profiles.iter().map(|p| &p.path));