diff --git a/docs/architecture.md b/docs/architecture.md index a6efa72..d73ca92 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 the 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..0839336 100644 --- a/docs/design.md +++ b/docs/design.md @@ -402,6 +402,10 @@ 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 broker reads built paths from the builder's store, `nix copy --from ssh-ng://` its + user with the broker's key; the builder key's forced command serves `nix-daemon --stdio` + for that. So the builder can be on another box with a store of its own, and nothing lands + in the broker's store. 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..2f5efa6 100644 --- a/nix/modules/nixos/broker.nix +++ b/nix/modules/nixos/broker.nix @@ -169,7 +169,7 @@ 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."; + "SSH arguments for reaching the builder: only `-p `, which goes in the store URL built paths are copied from."; }; }; 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..9e5c9e5 100644 --- a/src/config.rs +++ b/src/config.rs @@ -124,6 +124,32 @@ pub struct DeployConfig { pub cache: PathBuf, } +impl DeployConfig { + /// The builder's store, which built paths are copied from, as a `nix` store URL reached with + /// the broker's `key`; the builder's forced command serves it. That works whether the builder + /// is on this box (the same store) or another. 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 { + 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!("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(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 /// key's forced command allows only the store protocol and adding GC roots. Needs `deploy`, whose /// builder it uses. @@ -312,6 +338,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 +424,34 @@ 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| DeployConfig { builder, nix: "/nix".into(), cache: "/cache".into() }; + let key = Path::new("/run/key"); + + assert_eq!( + deploy(builder("localhost", &["-p", "2222"])).builder_store(key).unwrap(), + "ssh-ng://build@localhost:2222?ssh-key=/run/key" + ); + assert_eq!( + deploy(builder("builder.example", &[])).builder_store(key).unwrap(), + "ssh-ng://build@builder.example:22?ssh-key=/run/key" + ); + assert_eq!( + deploy(builder("fd00::1", &["-p", "22"])).builder_store(key).unwrap(), + "ssh-ng://build@[fd00::1]:22?ssh-key=/run/key" + ); + assert!(deploy(builder("b", &["-o", "ProxyJump=x"])).builder_store(key).is_err()); + assert!(deploy(builder("b", &[])).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..188de43 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", &from]) .arg("--to") .arg(format!("ssh-ng://{}@{}", cache.user, cache.hostname)) .args(paths); @@ -156,14 +159,17 @@ 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"]); + command.args(["--store", &deploy.builder_store(&ssh.key)?]); command.args(paths); let (exit, stdout, stderr) = exec::capture(command, cancel).await?; @@ -219,6 +225,11 @@ 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())); + + // From the builder's store, with the broker's key + let copy = args(©); + 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..cbfddd9 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", &from]) .arg("--to") .arg(format!("ssh://{}@{}", target.user, target.hostname)) .args(profiles.iter().map(|p| &p.path));