ssh: Find deploy targets on the main branch
SSH targets are the deploy-rs nodes on the main branch, so adding a box takes a commit there rather than a new broker config, and a target can't drift from its node. The builder evaluates the branch's `deploy` output (hostname, SSH user and options, `sudo`), cached per commit, and the broker looks it up again when stale or when a request names a node it doesn't know. Only the protected branch's Nix is evaluated, as for secrets. SSH therefore needs `deploy`. The VM test gets a real builder and a repository with the nodes, and the demo's targets move into its repository's flake. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2af7c55a17
commit
6933750dc5
20 files changed
+452
-91
No files matched your search
@@ -35,7 +35,7 @@ The flake provides:
|
||||
|
||||
`nixosModules.default` imports all three NixOS modules. The modules default their `package` to this
|
||||
flake's build. Deployment-specific concerns (persisting state on an ephemeral root, the firewall in
|
||||
front of the web app, SSH targets, policies) are left to the configuration that imports them;
|
||||
front of the web app, policies) are left to the configuration that imports them;
|
||||
[nixfiles](https://git.nul.ie/dev/nixfiles) is the reference deployment.
|
||||
|
||||
## Developing
|
||||
|
||||
+2
-6
@@ -98,11 +98,6 @@ let
|
||||
ssh = "${ssh}";
|
||||
key = "${state}/broker-key";
|
||||
known_hosts = "${state}/known_hosts";
|
||||
targets = lib.genAttrs [ "box" "web" "router" "vault" ] (_: {
|
||||
hostname = "localhost";
|
||||
user = "box";
|
||||
ssh_opts = [ "-p" (toString demo.ports.boxSsh) ];
|
||||
});
|
||||
};
|
||||
|
||||
deploy = {
|
||||
@@ -240,7 +235,7 @@ in
|
||||
exec = ''
|
||||
set -eu
|
||||
umask 077
|
||||
export PATH=${lib.makeBinPath (with pkgs; [ coreutils git rage openssl wireguard-tools jq ])}
|
||||
export PATH=${lib.makeBinPath (with pkgs; [ coreutils gnused git rage openssl wireguard-tools jq ])}
|
||||
|
||||
if [ ! -d ${repositories}/repo.git ]; then
|
||||
for name in dev broker; do
|
||||
@@ -252,6 +247,7 @@ in
|
||||
work=$(mktemp -d)
|
||||
cp -r ${./nix/demo/repo}/. "$work"
|
||||
chmod -R u+w "$work"
|
||||
sed -i "s/@boxSsh@/${toString demo.ports.boxSsh}/" "$work/flake.nix"
|
||||
mkdir "$work/secrets"
|
||||
# nixpkgs as this repository locks it, so the builder already has it
|
||||
jq '{nodes: {root: {inputs: {nixpkgs: "nixpkgs"}}, nixpkgs: .nodes[.nodes.root.inputs.nixpkgs]}, root: "root", version: 7}' \
|
||||
|
||||
+10
-6
@@ -15,10 +15,11 @@ How the code is put together, and how to extend it. The design and its rationale
|
||||
| `src/server.rs` | Listeners (vsock, Unix), the per-connection handler, `authorize` |
|
||||
| `src/exec.rs` | Running processes on the requester's framed stdio; cancellation |
|
||||
| `src/ops/mod.rs` | `plan` (request → `Parsed`: scope, approval detail), `execute`, quoting |
|
||||
| `src/targets.rs` | SSH targets: the main branch's deploy-rs nodes from the builder, looked up again when stale or when a request names an unknown node |
|
||||
| `src/detail.rs` | What approvers see of a request (`Detail`: fields, tables, lists, text) and its text rendering |
|
||||
| `src/ops/ssh.rs`, `src/ops/query.rs`, `src/ops/deploy.rs`, `src/ops/build.rs` | Operations; `deploy.rs` also has the `INSPECT` comparison script and its parser |
|
||||
| `src/ops/secret.rs`, `src/ops/secret/format.rs` | Age secrets: what approvers see, encryption, generated values; env and JSON fields |
|
||||
| `src/builder.rs` | Both sides of the builder: the worker (forced command) and the broker's client; also looks secrets up on the main branch |
|
||||
| `src/builder.rs` | Both sides of the builder: the worker (forced command) and the broker's client; also reads secrets and deploy nodes on the main branch |
|
||||
| `src/approve.rs` | Approver connections (many requests each), `slop-approve` client, `approve()` used by every approver |
|
||||
| `src/remote.rs` | SSH transport: the `slop-broker remote` forced command, the remote socket, `connect` for both clients, and `address` (environment, then `~/.config/slop/config.toml`, then the default) |
|
||||
| `src/audit.rs` | Typed audit events: a text line to the journal, a JSON line to the file; `tail` for `slop-approve log` |
|
||||
@@ -40,7 +41,8 @@ How the code is put together, and how to extend it. The design and its rationale
|
||||
that forwards `Stdin` to a channel (closing it at `StdinEnd`) and cancels a `CancellationToken`
|
||||
when the connection closes or misbehaves. A writer task sends every `ServerMessage` from an
|
||||
`mpsc` channel, in order.
|
||||
3. The protocol version is checked. `ops::plan` checks the already-typed `Operation` against config
|
||||
3. The protocol version is checked, and `targets::refresh` looks the main branch's nodes up again
|
||||
if the operation names a node and they're stale or don't include it. `ops::plan` checks the already-typed `Operation` against config
|
||||
(does the node exist?) and returns `Parsed`: the scope, what approvers are shown, limits, whether
|
||||
stdin is used, and the operation. For operations that build (`ops::builds`), a policy pre-check
|
||||
(deny stops here), then `ops::describe` (the builder's Git-only stage), then `authorize` of the
|
||||
@@ -140,9 +142,11 @@ Arguments from the requester are validated so none can be read as an option.
|
||||
- Builds: `services.slop-broker.cache` (broker side) and `services.slop-broker-cache` on the cache's
|
||||
box, whose forced command allows `nix-daemon --stdio` (exactly what `ssh-ng` sends) and
|
||||
`root <path>…`. The broker adds roots before copying, in case the store collects garbage often.
|
||||
- Targets: every deploy-rs node on the main branch, so adding a box needs a commit there rather
|
||||
than a new broker config; SSH therefore needs `deploy`.
|
||||
- What the modules leave to the deployment: persisting `/var/lib/slop-broker` and the builder's
|
||||
home on an ephemeral root, the firewall in front of the web app's port, which boxes are SSH
|
||||
targets, and the policies. [nixfiles](https://git.nul.ie/dev/nixfiles) is the reference, and
|
||||
home on an ephemeral root, the firewall in front of the web app's port, and the policies.
|
||||
[nixfiles](https://git.nul.ie/dev/nixfiles) is the reference, and
|
||||
[`nix/vm-test.nix`](../nix/vm-test.nix) a minimal example.
|
||||
|
||||
## Adding an operation
|
||||
@@ -198,5 +202,5 @@ Arguments from the requester are validated so none can be read as an option.
|
||||
|
||||
## Known gaps
|
||||
|
||||
- `nix/vm-test.nix` needs KVM; run `vm-test` in the devenv shell. It doesn't cover deploys or the
|
||||
web app; the demo covers the web app by hand.
|
||||
- `nix/vm-test.nix` needs KVM; run `vm-test` in the devenv shell. It looks the nodes up through a
|
||||
real builder, but doesn't cover deploys or the web app; the demo covers the web app by hand.
|
||||
+7
-3
@@ -237,9 +237,13 @@ ciphertext they were sent, never values.
|
||||
|
||||
### Box queries and SSH
|
||||
|
||||
- Targets are named in trusted config (`services.slop-broker.ssh.targets`), normally the
|
||||
deployment's deploy-rs nodes. `--host` covers boxes outside them (OpenWrt, switches) with an
|
||||
explicit `user@host` and port.
|
||||
- **Targets** are the deploy-rs nodes on the main branch, by name, so a new box needs a commit
|
||||
there rather than a new broker config. SSH therefore needs deploys set up.
|
||||
- The builder evaluates each node's `hostname`, `sshUser`, `sshOpts` and `sudo`, falling back to
|
||||
the flake-wide `sshUser` and `sudo`. Only the protected branch's Nix runs, as for secrets.
|
||||
- The broker looks them up again when they're stale, or when a request names a node it doesn't
|
||||
know.
|
||||
- `--host` covers boxes outside them (OpenWrt, switches) with an explicit `user@host` and port.
|
||||
- SSH runs with options fixed by the broker: `-F none`, the key with `IdentitiesOnly`, no agent,
|
||||
`BatchMode`, no forwarding or local commands, and the broker's own `known_hosts`.
|
||||
- `ssh` joins its arguments into a string that the remote shell runs. Because of that, a
|
||||
|
||||
+22
-11
@@ -1,5 +1,6 @@
|
||||
# The demo's repository, which the agent clones, changes and pushes. `devenv up` seeds it once,
|
||||
# with `secrets.nix`, the secrets and `flake.lock` beside this file.
|
||||
# with `secrets.nix`, the secrets and `flake.lock` beside this file, and the box's SSH port for
|
||||
# `@boxSsh@`.
|
||||
{
|
||||
description = "slop-broker demo repository";
|
||||
|
||||
@@ -22,6 +23,8 @@
|
||||
'';
|
||||
};
|
||||
|
||||
node = { hostname = "localhost"; sshOpts = [ "-p" "@boxSsh@" ]; };
|
||||
|
||||
# A profile deploy-rs can activate, as `deploy-rs.lib.<system>.activate.custom` makes them,
|
||||
# with nixpkgs' build of deploy-rs so nothing needs compiling
|
||||
activatable = base: activate: pkgs.buildEnv {
|
||||
@@ -57,16 +60,24 @@
|
||||
{
|
||||
packages.x86_64-linux.default = app;
|
||||
|
||||
# The broker reaches nodes by its own SSH targets, so `hostname` isn't used
|
||||
deploy.nodes.box = {
|
||||
hostname = "localhost";
|
||||
profiles.demo = {
|
||||
user = "root";
|
||||
path = activatable app ''
|
||||
mkdir -p /run/demo
|
||||
echo ${version} > /run/demo/version
|
||||
echo "demo app ${version} is active"
|
||||
'';
|
||||
# The broker's SSH targets, which it reads from `master`. They're all the box VM, whose SSH
|
||||
# port `devenv up` forwards to the host's loopback; only `box` has something to deploy.
|
||||
deploy = {
|
||||
sshUser = "box";
|
||||
nodes = {
|
||||
web = node;
|
||||
router = node;
|
||||
vault = node;
|
||||
box = node // {
|
||||
profiles.demo = {
|
||||
user = "root";
|
||||
path = activatable app ''
|
||||
mkdir -p /run/demo
|
||||
echo ${version} > /run/demo/version
|
||||
echo "demo app ${version} is active"
|
||||
'';
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
@@ -92,7 +92,6 @@ let
|
||||
ssh = "${pkgs.openssh}/bin/ssh";
|
||||
key = "ssh-key";
|
||||
known_hosts = "/var/lib/slop-broker/known_hosts";
|
||||
targets = mapAttrs (_: t: { inherit (t) hostname user sudo; ssh_opts = t.sshOpts; }) cfg.ssh.targets;
|
||||
} else null;
|
||||
|
||||
deploy = if cfg.deploy.enable then {
|
||||
@@ -146,16 +145,9 @@ in
|
||||
requesters = mkOpt' (attrsOf (submodule requesterOpts)) { } "Who may send requests, and which policy applies.";
|
||||
|
||||
ssh = {
|
||||
enable = mkBoolOpt' false "Whether to run approved SSH commands.";
|
||||
enable = mkBoolOpt' false
|
||||
"Whether to run approved SSH commands. The targets are the deploy-rs nodes on the builder's main branch, so this needs `deploy`.";
|
||||
keyFile = mkOpt' str "" "Runtime path to the SSH private key; never a Nix store path.";
|
||||
targets = mkOpt' (attrsOf (submodule {
|
||||
options = {
|
||||
hostname = mkOpt' str null "Host to connect to.";
|
||||
user = mkOpt' str null "Remote user.";
|
||||
sshOpts = mkOpt' (listOf str) [ ] "Extra SSH arguments (trusted).";
|
||||
sudo = mkOpt' str "sudo -u" "How the user becomes root for deploys, followed by `root`.";
|
||||
};
|
||||
})) { } "Named SSH targets (nodes), which `slop ssh`, the box queries and deploys address by name.";
|
||||
};
|
||||
|
||||
deploy = {
|
||||
@@ -203,6 +195,10 @@ in
|
||||
assertion = cfg.ssh.enable -> isRuntimePath cfg.ssh.keyFile;
|
||||
message = "slop-broker SSH needs a runtime key file.";
|
||||
}
|
||||
{
|
||||
assertion = cfg.ssh.enable -> cfg.deploy.enable;
|
||||
message = "slop-broker SSH needs `deploy`, whose builder reads the main branch's deploy-rs nodes.";
|
||||
}
|
||||
{
|
||||
assertion = cfg.deploy.enable -> cfg.ssh.enable;
|
||||
message = "slop-broker deploys need `ssh`.";
|
||||
|
||||
+32
-2
@@ -9,11 +9,31 @@ let
|
||||
for k in key requester approver; do ssh-keygen -q -t ed25519 -N "" -f $out/$k; done
|
||||
'';
|
||||
publicKey = name: builtins.readFile "${key}/${name}.pub";
|
||||
|
||||
# The builder's repository: a flake whose deploy-rs nodes are the broker's SSH targets
|
||||
repository = pkgs.runCommand "test-repository" { nativeBuildInputs = [ pkgs.git ]; } ''
|
||||
mkdir $out
|
||||
cat > $out/flake.nix <<'EOF'
|
||||
{
|
||||
outputs = _: {
|
||||
deploy.sshUser = "deploy";
|
||||
deploy.nodes = {
|
||||
local.hostname = "localhost";
|
||||
other.hostname = "localhost";
|
||||
denied.hostname = "localhost";
|
||||
};
|
||||
};
|
||||
}
|
||||
EOF
|
||||
git -C $out init --quiet --initial-branch=master
|
||||
git -C $out add flake.nix
|
||||
git -C $out -c user.name=test -c user.email=test@example.org commit --quiet -m "Add nodes"
|
||||
'';
|
||||
in
|
||||
pkgs.testers.runNixOSTest {
|
||||
name = "slop-broker";
|
||||
nodes.machine = { ... }: {
|
||||
imports = [ ./modules/nixos/broker.nix ];
|
||||
imports = [ ./modules/nixos/broker.nix ./modules/nixos/builder.nix ];
|
||||
|
||||
config = {
|
||||
boot.kernelModules = [ "vsock_loopback" ];
|
||||
@@ -55,9 +75,19 @@ pkgs.testers.runNixOSTest {
|
||||
ssh = {
|
||||
enable = true;
|
||||
keyFile = "/etc/slop-broker-test/key";
|
||||
targets = lib.genAttrs [ "local" "other" "denied" ] (_: { hostname = "localhost"; user = "deploy"; });
|
||||
};
|
||||
deploy.enable = true;
|
||||
};
|
||||
|
||||
# Only reads the repository, so its key is never used
|
||||
services.slop-broker-builder = {
|
||||
enable = true;
|
||||
package = slop-broker;
|
||||
repository = "/var/lib/slop-test-repository";
|
||||
keyFile = "/etc/slop-broker-test/key";
|
||||
brokerKeys = [ (publicKey "key") ];
|
||||
};
|
||||
systemd.tmpfiles.rules = [ "C /var/lib/slop-test-repository - - - - ${repository}" "Z /var/lib/slop-test-repository - slop-broker-build - - -" ];
|
||||
};
|
||||
};
|
||||
testScript = ''
|
||||
|
||||
+82
-8
@@ -7,7 +7,8 @@
|
||||
//! the source. [`BuilderRequest::Describe`] runs only Git, so approvers can see the commits before
|
||||
//! anything agent-written runs; [`BuilderRequest::Build`] evaluates and builds, which runs
|
||||
//! agent-written Nix and is why it happens here and not in the broker.
|
||||
//! [`BuilderRequest::Secret`] reads the main branch, evaluating only that branch's rules file.
|
||||
//! [`BuilderRequest::Secret`] and [`BuilderRequest::Nodes`] read the main branch, evaluating only
|
||||
//! that branch's Nix.
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Stdio;
|
||||
@@ -55,6 +56,29 @@ pub enum BuilderRequest {
|
||||
Build(BuildRequest),
|
||||
/// What the main branch says about a secret.
|
||||
Secret(SecretRequest),
|
||||
/// The main branch's deploy-rs nodes, as SSH targets.
|
||||
Nodes,
|
||||
}
|
||||
|
||||
/// The main branch's deploy-rs nodes. Nothing in it is agent-written, as long as only people can
|
||||
/// push to the branch.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Nodes {
|
||||
/// The branch's commit they were read at.
|
||||
pub commit: CommitId,
|
||||
pub nodes: BTreeMap<String, Node>,
|
||||
}
|
||||
|
||||
/// How deploy-rs reaches a node: the node's settings, else the flake's `deploy` defaults.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields, rename_all = "camelCase")]
|
||||
pub struct Node {
|
||||
pub hostname: String,
|
||||
pub ssh_user: Option<String>,
|
||||
/// Only the node's own: the flake-wide ones usually name the operator's key.
|
||||
pub ssh_opts: Vec<String>,
|
||||
pub sudo: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
@@ -192,6 +216,16 @@ pub async fn build(
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// The main branch's deploy-rs nodes. Its progress goes to `out`.
|
||||
pub async fn nodes(
|
||||
ssh: &crate::config::SshConfig,
|
||||
deploy: &crate::config::DeployConfig,
|
||||
out: &Output,
|
||||
cancel: &CancellationToken,
|
||||
) -> Result<Nodes> {
|
||||
call(ssh, deploy, &BuilderRequest::Nodes, out, cancel).await
|
||||
}
|
||||
|
||||
/// What the main branch says about a secret. Its progress goes to `out`.
|
||||
pub async fn secret(
|
||||
ssh: &crate::config::SshConfig,
|
||||
@@ -259,6 +293,7 @@ pub async fn worker(config: &Path) -> Result<()> {
|
||||
match &request {
|
||||
BuilderRequest::Describe(commit) => encode(&describe_commit(&config, commit).await?),
|
||||
BuilderRequest::Secret(request) => encode(&secret_context(&config, request).await?),
|
||||
BuilderRequest::Nodes => encode(&branch_nodes(&config).await?),
|
||||
BuilderRequest::Build(request) => {
|
||||
let _lock = lock(&config.directory.join("build.lock")).await?;
|
||||
encode(&run(&config, request).await?)
|
||||
@@ -463,18 +498,22 @@ async fn describe_commit(config: &BuilderConfig, commit: &CommitId) -> Result<De
|
||||
}
|
||||
}
|
||||
|
||||
/// The main branch's commit, freshly fetched.
|
||||
async fn branch_tip(config: &BuilderConfig) -> Result<CommitId> {
|
||||
fetch_all(config).await?;
|
||||
let branch = format!("refs/remotes/origin/{}", config.branch);
|
||||
let commit = output(git(config, &mirror(config)).args(["rev-parse", "--verify", &format!("{branch}^{{commit}}")]))
|
||||
.await
|
||||
.with_context(|| format!("finding {}", config.branch))?;
|
||||
commit.trim().parse().map_err(anyhow::Error::msg)
|
||||
}
|
||||
|
||||
/// Where a blob lives on the main branch, and the branch's recipients for a path. Runs Git, and
|
||||
/// evaluates the branch's rules file, never a requester's commit.
|
||||
async fn secret_context(config: &BuilderConfig, request: &SecretRequest) -> Result<SecretContext> {
|
||||
fetch_all(config).await?;
|
||||
let commit = branch_tip(config).await?;
|
||||
let repository = mirror(config);
|
||||
|
||||
let branch = format!("refs/remotes/origin/{}", config.branch);
|
||||
let commit = output(git(config, &repository).args(["rev-parse", "--verify", &format!("{branch}^{{commit}}")]))
|
||||
.await
|
||||
.with_context(|| format!("finding {}", config.branch))?;
|
||||
let commit: CommitId = commit.trim().parse().map_err(anyhow::Error::msg)?;
|
||||
|
||||
let paths = match &request.blob {
|
||||
Some(blob) => {
|
||||
let tree = output(git(config, &repository).args(["ls-tree", "-r", "-z", &commit])).await?;
|
||||
@@ -536,6 +575,41 @@ async fn rules(config: &BuilderConfig, commit: &CommitId, rules: &RulesPath) ->
|
||||
Ok(parsed)
|
||||
}
|
||||
|
||||
/// The main branch's deploy-rs nodes, evaluated once per commit.
|
||||
async fn branch_nodes(config: &BuilderConfig) -> Result<Nodes> {
|
||||
let commit = branch_tip(config).await?;
|
||||
let cache = config.directory.join("deploy-nodes");
|
||||
let file = cache.join(format!("{commit}.json"));
|
||||
if let Ok(text) = std::fs::read_to_string(&file) {
|
||||
return Ok(Nodes { commit, nodes: serde_json::from_str(&text)? });
|
||||
}
|
||||
|
||||
eprintln!("Evaluating deploy.nodes on {}…", config.branch);
|
||||
let flake = format!("git+file://{}?rev={commit}", mirror(config).display());
|
||||
let apply = "d: builtins.mapAttrs (_: n: { \
|
||||
hostname = n.hostname; \
|
||||
sshUser = n.sshUser or d.sshUser or null; \
|
||||
sshOpts = n.sshOpts or [ ]; \
|
||||
sudo = n.sudo or d.sudo or null; \
|
||||
}) d.nodes";
|
||||
let evaluated = output(
|
||||
command(config, "nix")
|
||||
.args(["eval", "--json"])
|
||||
.args(NIX_OPTIONS)
|
||||
.arg(format!("{flake}#deploy"))
|
||||
.args(["--apply", apply]),
|
||||
)
|
||||
.await
|
||||
.context("evaluating deploy.nodes")?;
|
||||
let nodes = serde_json::from_str(&evaluated).context("reading deploy.nodes")?;
|
||||
|
||||
// Only the newest commit's nodes are worth keeping.
|
||||
let _ = std::fs::remove_dir_all(&cache);
|
||||
std::fs::create_dir_all(&cache)?;
|
||||
std::fs::write(&file, &evaluated)?;
|
||||
Ok(Nodes { commit, nodes })
|
||||
}
|
||||
|
||||
async fn run(config: &BuilderConfig, request: &BuildRequest) -> Result<BuildResult> {
|
||||
let commit = &request.commit;
|
||||
let repository = mirror(config);
|
||||
|
||||
+11
-3
@@ -182,10 +182,13 @@ pub struct SshConfig {
|
||||
/// Private key; relative paths are resolved in `$CREDENTIALS_DIRECTORY`.
|
||||
pub key: PathBuf,
|
||||
pub known_hosts: PathBuf,
|
||||
/// Named targets (deploy-rs nodes).
|
||||
/// The main branch's deploy-rs nodes, by name. Never configured: `targets::Targets` fills it
|
||||
/// in from the builder.
|
||||
#[serde(skip)]
|
||||
pub targets: BTreeMap<String, SshTarget>,
|
||||
}
|
||||
|
||||
/// A box as SSH reaches it: a node, the builder or the cache.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SshTarget {
|
||||
@@ -193,12 +196,13 @@ pub struct SshTarget {
|
||||
pub user: String,
|
||||
#[serde(default)]
|
||||
pub ssh_opts: Vec<String>,
|
||||
/// How `user` becomes root, followed by the user name (deploy-rs's `sudo`).
|
||||
/// How `user` becomes root, followed by the user name (deploy-rs's `sudo`); nodes only.
|
||||
#[serde(default = "default_sudo")]
|
||||
pub sudo: String,
|
||||
}
|
||||
|
||||
fn default_sudo() -> String {
|
||||
/// deploy-rs's default.
|
||||
pub fn default_sudo() -> String {
|
||||
"sudo -u".into()
|
||||
}
|
||||
|
||||
@@ -277,6 +281,10 @@ impl Config {
|
||||
self.secrets.is_none() || (self.ssh.is_some() && self.deploy.is_some()),
|
||||
"secrets need ssh and deploy, whose builder reads the main branch"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
self.ssh.is_none() || self.deploy.is_some(),
|
||||
"ssh needs deploy, whose builder reads the main branch's deploy-rs nodes"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -12,5 +12,6 @@ pub mod proto;
|
||||
pub mod queue;
|
||||
pub mod remote;
|
||||
pub mod server;
|
||||
pub mod targets;
|
||||
pub mod types;
|
||||
pub mod web;
|
||||
+6
-2
@@ -6,6 +6,8 @@
|
||||
//! agents can't upload paths they built themselves.
|
||||
use std::path::Path;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context, Result, bail, ensure};
|
||||
use serde_json::json;
|
||||
use tokio::process::Command;
|
||||
@@ -23,8 +25,8 @@ use crate::server::Broker;
|
||||
|
||||
const MAX_ATTRS: usize = 32;
|
||||
|
||||
fn configs(broker: &Broker) -> Result<(&SshConfig, &DeployConfig, &CacheConfig)> {
|
||||
let ssh = broker.config.ssh.as_ref().context("SSH is not configured on this broker")?;
|
||||
fn configs(broker: &Broker) -> Result<(Arc<SshConfig>, &DeployConfig, &CacheConfig)> {
|
||||
let ssh = broker.targets.ssh()?;
|
||||
let deploy = broker.config.deploy.as_ref().context("the builder is not configured on this broker")?;
|
||||
let cache = broker.config.cache.as_ref().context("the binary cache is not configured on this broker")?;
|
||||
Ok((ssh, deploy, cache))
|
||||
@@ -70,6 +72,7 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
|
||||
pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()> {
|
||||
let Operation::Build { attrs, commit } = &parsed.operation else { return Ok(()) };
|
||||
let (ssh, deploy, _) = configs(broker)?;
|
||||
let ssh = &*ssh;
|
||||
|
||||
let request = BuildRequest { commit: commit.clone(), targets: Vec::new(), attrs: attrs.clone() };
|
||||
io.out.info(format!("{}; output follows", parsed.summary)).await;
|
||||
@@ -100,6 +103,7 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
|
||||
|
||||
pub async fn execute(broker: &Broker, parsed: &Parsed, io: &mut Io) -> Result<i32> {
|
||||
let (ssh, deploy, cache) = configs(broker)?;
|
||||
let ssh = &*ssh;
|
||||
let built = parsed.prepared.as_ref().context("nothing was built")?;
|
||||
let paths: Vec<&str> = built.outputs.iter().flat_map(|o| &o.paths).map(String::as_str).collect();
|
||||
|
||||
|
||||
+19
-14
@@ -7,6 +7,8 @@
|
||||
//! only once approved, in a transient unit, so it finishes even if the connection drops.
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context, Result, bail, ensure};
|
||||
use futures_util::future::join_all;
|
||||
use serde_json::json;
|
||||
@@ -23,8 +25,8 @@ use crate::server::Broker;
|
||||
|
||||
const MAX_TARGETS: usize = 32;
|
||||
|
||||
fn configs(broker: &Broker) -> Result<(&SshConfig, &DeployConfig)> {
|
||||
let ssh = broker.config.ssh.as_ref().context("SSH is not configured on this broker")?;
|
||||
fn configs(broker: &Broker) -> Result<(Arc<SshConfig>, &DeployConfig)> {
|
||||
let ssh = broker.targets.ssh()?;
|
||||
let deploy = broker.config.deploy.as_ref().context("deploys are not configured on this broker")?;
|
||||
Ok((ssh, deploy))
|
||||
}
|
||||
@@ -36,6 +38,7 @@ fn mode(boot: bool) -> &'static str {
|
||||
pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
|
||||
let Operation::Deploy { targets, commit, boot } = &operation else { unreachable!() };
|
||||
let (ssh, _) = configs(broker)?;
|
||||
let ssh = &*ssh;
|
||||
|
||||
ensure!(!targets.is_empty(), "nothing to deploy");
|
||||
ensure!(targets.len() <= MAX_TARGETS, "at most {MAX_TARGETS} targets at once");
|
||||
@@ -91,6 +94,7 @@ pub fn building(commit: &crate::types::CommitId, label: &str) -> Detail {
|
||||
pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()> {
|
||||
let Operation::Deploy { targets, commit, boot } = &parsed.operation else { return Ok(()) };
|
||||
let (ssh, deploy) = configs(broker)?;
|
||||
let ssh = &*ssh;
|
||||
|
||||
let request = BuildRequest { commit: commit.clone(), targets: targets.clone(), attrs: Vec::new() };
|
||||
io.out.info(format!("building {} for {}; output follows", commit.short(), parsed.summary)).await;
|
||||
@@ -125,14 +129,15 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
|
||||
pub async fn execute(broker: &Broker, parsed: &Parsed, io: &mut Io) -> Result<i32> {
|
||||
let Operation::Deploy { boot, .. } = &parsed.operation else { unreachable!() };
|
||||
let (ssh, _) = configs(broker)?;
|
||||
let ssh = &*ssh;
|
||||
let built = parsed.prepared.as_ref().context("nothing was built")?;
|
||||
|
||||
let run = &crate::queue::new_id();
|
||||
let (out, cancel) = (&io.out, &io.cancel);
|
||||
let results = join_all(group(&built.profiles).into_iter().map(|(node, profiles)| async move {
|
||||
for profile in profiles {
|
||||
let remote = [shell_quote(&activate_command(ssh, &node, profile, *boot, run))];
|
||||
let command = ssh::command(ssh, &Destination::Node(node.parse().unwrap()), &remote);
|
||||
let remote = [shell_quote(&activate_command(ssh, &node, profile, *boot, run)?)];
|
||||
let command = ssh::command(ssh, &Destination::Node(node.parse().unwrap()), &remote)?;
|
||||
let prefix = format!("[{node}.{}] ", profile.profile);
|
||||
|
||||
let exit = exec::run_prefixed(command, out, &prefix, cancel).await?;
|
||||
@@ -177,8 +182,8 @@ async fn copy(
|
||||
out: &Output,
|
||||
cancel: &tokio_util::sync::CancellationToken,
|
||||
) -> Result<()> {
|
||||
let target = &ssh.targets[node];
|
||||
let options = copy_options(ssh, node);
|
||||
let target = ssh::target(ssh, node)?;
|
||||
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 ssh_directory = ssh.ssh.parent().map(|p| p.display().to_string()).unwrap_or_default();
|
||||
@@ -209,8 +214,8 @@ async fn copy(
|
||||
/// and waits for that line, but ssh keeps the first value of an option, so the broker's
|
||||
/// `PermitLocalCommand=no` would leave it waiting forever. With `-F none`, nothing else can set a
|
||||
/// local command anyway.
|
||||
fn copy_options(ssh: &SshConfig, node: &str) -> Vec<String> {
|
||||
nix_ssh_options(ssh::options(ssh), &ssh.targets[node].ssh_opts)
|
||||
fn copy_options(ssh: &SshConfig, node: &str) -> Result<Vec<String>> {
|
||||
Ok(nix_ssh_options(ssh::options(ssh), &ssh::target(ssh, node)?.ssh_opts))
|
||||
}
|
||||
|
||||
/// The broker's SSH options, made usable by `nix copy` as described above, then `extra`.
|
||||
@@ -255,7 +260,7 @@ async fn inspect(
|
||||
cancel: &tokio_util::sync::CancellationToken,
|
||||
) -> Result<Changes> {
|
||||
let words = ["bash", "-c", INSPECT, "bash", &profile.profile_path, &profile.path];
|
||||
let command = ssh::command(ssh, &Destination::Node(node.parse().unwrap()), &[shell_quote(&words)]);
|
||||
let command = ssh::command(ssh, &Destination::Node(node.parse().unwrap()), &[shell_quote(&words)])?;
|
||||
|
||||
let (exit, stdout, stderr) = exec::capture(command, cancel).await?;
|
||||
if exit != 0 {
|
||||
@@ -264,8 +269,8 @@ async fn inspect(
|
||||
Ok(Changes::parse(&String::from_utf8_lossy(&stdout)))
|
||||
}
|
||||
|
||||
fn activate_command(ssh: &SshConfig, node: &str, profile: &BuiltProfile, boot: bool, run: &str) -> Vec<String> {
|
||||
let mut words: Vec<String> = ssh.targets[node].sudo.split_whitespace().map(Into::into).collect();
|
||||
fn activate_command(ssh: &SshConfig, node: &str, profile: &BuiltProfile, boot: bool, run: &str) -> Result<Vec<String>> {
|
||||
let mut words: Vec<String> = ssh::target(ssh, node)?.sudo.split_whitespace().map(Into::into).collect();
|
||||
words.push("root".into());
|
||||
|
||||
// A transient unit, so activation finishes even if this connection drops
|
||||
@@ -290,7 +295,7 @@ fn activate_command(ssh: &SshConfig, node: &str, profile: &BuiltProfile, boot: b
|
||||
if boot {
|
||||
words.push("--boot".into());
|
||||
}
|
||||
words
|
||||
Ok(words)
|
||||
}
|
||||
|
||||
/// Drops terminal escape sequences, which `nix` can print even into a pipe.
|
||||
@@ -497,7 +502,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn copies_can_run_their_local_command() {
|
||||
let options = copy_options(&ssh::tests::config(), "river");
|
||||
let options = copy_options(&ssh::tests::config(), "river").unwrap();
|
||||
assert!(!options.iter().any(|o| o.starts_with("PermitLocalCommand")), "{options:?}");
|
||||
assert!(options.contains(&"IdentitiesOnly=yes".to_owned()));
|
||||
assert_eq!(&options[options.len() - 2..], ["-p", "2222"]);
|
||||
@@ -513,7 +518,7 @@ mod tests {
|
||||
path: "/nix/store/0123456789abcdfghijklmnpqrsvwxyz-system".into(),
|
||||
profile_path: "/nix/var/nix/profiles/system".into(),
|
||||
};
|
||||
let words = activate_command(&config, "river", &profile, true, "0123456789abcdef");
|
||||
let words = activate_command(&config, "river", &profile, true, "0123456789abcdef").unwrap();
|
||||
assert_eq!(&words[..3], ["doas", "-u", "root"]);
|
||||
assert!(words.contains(&"--unit=slop-deploy-01234567-system".to_owned()));
|
||||
assert_eq!(words.last().unwrap(), "--boot");
|
||||
|
||||
+3
-3
@@ -63,7 +63,7 @@ impl From<i32> for Outcome {
|
||||
pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
|
||||
match &operation {
|
||||
Operation::Ssh { destination, command } => {
|
||||
let config = broker.config.ssh.as_ref().context("SSH is not configured on this broker")?;
|
||||
let config = &broker.targets.ssh()?;
|
||||
ssh::check(config, destination)?;
|
||||
let shown =
|
||||
if command.is_empty() { "(no command)".to_owned() } else { truncate(&shell_quote(command), 1000) };
|
||||
@@ -85,7 +85,7 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
|
||||
})
|
||||
}
|
||||
Operation::Query { destination, query } => {
|
||||
let config = broker.config.ssh.as_ref().context("SSH is not configured on this broker")?;
|
||||
let config = &broker.targets.ssh()?;
|
||||
ssh::check(config, destination)?;
|
||||
let mut scope = ssh::scope(destination);
|
||||
scope.insert("query".into(), Value::from(query::name(query)));
|
||||
@@ -147,7 +147,7 @@ fn commit(operation: &Operation) -> Result<&CommitId> {
|
||||
/// Fetches and describes the commit an operation builds; runs only Git.
|
||||
pub async fn describe(broker: &Broker, parsed: &Parsed, io: &Io) -> Result<Description> {
|
||||
let commit = commit(&parsed.operation)?;
|
||||
let ssh = broker.config.ssh.as_ref().context("SSH is not configured on this broker")?;
|
||||
let ssh = &broker.targets.ssh()?;
|
||||
let deploy = broker.config.deploy.as_ref().context("the builder is not configured on this broker")?;
|
||||
|
||||
io.out.info(format!("fetching {}; it's built once its use of the builder is approved", commit.short())).await;
|
||||
|
||||
+2
-2
@@ -36,10 +36,10 @@ pub fn remote_command(query: &Query) -> Vec<String> {
|
||||
}
|
||||
|
||||
pub async fn execute(broker: &Broker, destination: &Destination, query: &Query, io: &mut Io) -> Result<i32> {
|
||||
let config = broker.config.ssh.as_ref().unwrap();
|
||||
let config = broker.targets.ssh()?;
|
||||
// One quoted string, so the remote login shell (POSIX or fish) sees exactly these words.
|
||||
let remote = [shell_quote(&remote_command(query))];
|
||||
exec::run(ssh::command(config, destination, &remote), io, false).await
|
||||
exec::run(ssh::command(&config, destination, &remote)?, io, false).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+1
-1
@@ -100,7 +100,7 @@ fn is_age(data: &[u8]) -> bool {
|
||||
pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()> {
|
||||
let Operation::Secret(op) = &parsed.operation else { bail!("not a secret operation") };
|
||||
let config = broker.config.secrets.as_ref().context("secrets are not configured on this broker")?;
|
||||
let ssh = broker.config.ssh.as_ref().context("SSH is not configured on this broker")?;
|
||||
let ssh = &broker.targets.ssh()?;
|
||||
let deploy = broker.config.deploy.as_ref().context("the builder is not configured on this broker")?;
|
||||
let own = own_recipient(config)?;
|
||||
|
||||
|
||||
+15
-8
@@ -1,4 +1,5 @@
|
||||
//! Commands over SSH with the broker's key, to configured targets or explicit `user@host`s.
|
||||
//! Commands over SSH with the broker's key, to the main branch's deploy-rs nodes or explicit
|
||||
//! `user@host`s.
|
||||
use anyhow::{Result, bail};
|
||||
use serde_json::{Map, Value, json};
|
||||
use tokio::process::Command;
|
||||
@@ -14,7 +15,7 @@ pub fn check(config: &SshConfig, destination: &Destination) -> Result<()> {
|
||||
if let Destination::Node(node) = destination
|
||||
&& !config.targets.contains_key(&**node)
|
||||
{
|
||||
bail!("unknown node {node}; use --host for other boxes");
|
||||
bail!("unknown node {node}; nodes are the main branch's deploy-rs nodes, and --host reaches other boxes");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -64,14 +65,14 @@ pub fn options_with_key(config: &SshConfig, key: &std::path::Path) -> Vec<String
|
||||
}
|
||||
|
||||
/// The `ssh` invocation; every option comes from here or trusted target config.
|
||||
pub fn command<S: AsRef<str>>(config: &SshConfig, destination: &Destination, remote: &[S]) -> Command {
|
||||
pub fn command<S: AsRef<str>>(config: &SshConfig, destination: &Destination, remote: &[S]) -> Result<Command> {
|
||||
let mut command = Command::new(&config.ssh);
|
||||
command.env_clear().env("PATH", "/run/current-system/sw/bin").env("HOME", "/var/empty");
|
||||
command.arg("-T").args(options(config));
|
||||
|
||||
match destination {
|
||||
Destination::Node(node) => {
|
||||
let target = &config.targets[&**node];
|
||||
let target = target(config, node)?;
|
||||
command.args(&target.ssh_opts).args(["-l", &target.user, "--", &target.hostname]);
|
||||
}
|
||||
Destination::Host { user, host, port } => {
|
||||
@@ -80,7 +81,13 @@ pub fn command<S: AsRef<str>>(config: &SshConfig, destination: &Destination, rem
|
||||
}
|
||||
|
||||
command.args(remote.iter().map(AsRef::as_ref));
|
||||
command
|
||||
Ok(command)
|
||||
}
|
||||
|
||||
/// A node's settings. Nodes can disappear from the main branch between planning a request and
|
||||
/// running it.
|
||||
pub fn target<'a>(config: &'a SshConfig, node: &str) -> Result<&'a SshTarget> {
|
||||
config.targets.get(node).ok_or_else(|| anyhow::anyhow!("unknown node {node}"))
|
||||
}
|
||||
|
||||
/// The same, to a target that isn't a node (such as the builder).
|
||||
@@ -94,8 +101,8 @@ pub fn command_to<S: AsRef<str>>(config: &SshConfig, target: &SshTarget, remote:
|
||||
}
|
||||
|
||||
pub async fn execute(broker: &Broker, destination: &Destination, remote: &[Arg], io: &mut Io) -> Result<i32> {
|
||||
let config = broker.config.ssh.as_ref().unwrap();
|
||||
exec::run(command(config, destination, remote), io, true).await
|
||||
let config = broker.targets.ssh()?;
|
||||
exec::run(command(&config, destination, remote)?, io, true).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -125,7 +132,7 @@ pub(crate) mod tests {
|
||||
|
||||
#[test]
|
||||
fn trusted_options_come_before_the_destination() {
|
||||
let command = command(&config(), &Destination::Node("river".parse().unwrap()), &["-oProxyCommand=x"]);
|
||||
let command = command(&config(), &Destination::Node("river".parse().unwrap()), &["-oProxyCommand=x"]).unwrap();
|
||||
let args: Vec<_> = command.as_std().get_args().map(|a| a.to_string_lossy().into_owned()).collect();
|
||||
let separator = args.iter().position(|a| a == "--").unwrap();
|
||||
assert_eq!(&args[separator - 3..], ["2222", "-l", "deploy", "--", "river.example.org", "-oProxyCommand=x"]);
|
||||
|
||||
+5
-1
@@ -21,11 +21,13 @@ use crate::ops;
|
||||
use crate::policy::{self, Action};
|
||||
use crate::proto::{ApprovedBy, ClientMessage, PROTOCOL_VERSION, Request, ServerMessage, decode, encode, transport};
|
||||
use crate::queue::{NewRequest, Outcome, Queue, new_id};
|
||||
use crate::targets::Targets;
|
||||
|
||||
pub struct Broker {
|
||||
pub config: Config,
|
||||
pub queue: Queue,
|
||||
pub audit: Audit,
|
||||
pub targets: Targets,
|
||||
}
|
||||
|
||||
impl Broker {
|
||||
@@ -33,7 +35,8 @@ impl Broker {
|
||||
config.validate()?;
|
||||
let queue = Queue::new(Duration::from_secs(config.timeout), config.max_pending);
|
||||
let audit = Audit::new(config.audit_log.as_deref())?;
|
||||
Ok(Broker { config, queue, audit })
|
||||
let targets = Targets::new(&config);
|
||||
Ok(Broker { config, queue, audit, targets })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,6 +172,7 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
|
||||
|
||||
let id = new_id();
|
||||
let label = request.label.as_deref().map(|l| ops::truncate(l.trim(), 200)).filter(|l| !l.is_empty());
|
||||
broker.targets.refresh(&broker.config, &request.operation).await;
|
||||
let mut parsed = match ops::plan(broker, request.operation) {
|
||||
Ok(parsed) => parsed,
|
||||
Err(error) => {
|
||||
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
//! SSH targets: the main branch's deploy-rs nodes. The builder reads them from the branch only
|
||||
//! people can push to, so a new box needs a commit there rather than a new broker config.
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use tokio::sync::{Mutex, mpsc};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::builder::Node;
|
||||
use crate::config::{Config, SshConfig, SshTarget, default_sudo};
|
||||
use crate::exec::Output;
|
||||
use crate::proto::{Destination, Operation};
|
||||
|
||||
/// How long the branch's nodes are used before they're looked up again.
|
||||
const FRESH: Duration = Duration::from_secs(60);
|
||||
/// The shortest time between lookups, so unknown names can't make the builder fetch nonstop.
|
||||
const RETRY: Duration = Duration::from_secs(10);
|
||||
|
||||
pub struct Targets {
|
||||
/// The SSH settings with the branch's nodes; `None` without SSH.
|
||||
current: RwLock<Option<Arc<SshConfig>>>,
|
||||
/// When the branch was last looked up, held while looking so lookups don't pile up.
|
||||
looked: Mutex<Option<(Instant, bool)>>,
|
||||
}
|
||||
|
||||
impl Targets {
|
||||
pub fn new(config: &Config) -> Targets {
|
||||
Targets { current: RwLock::new(config.ssh.clone().map(Arc::new)), looked: Mutex::new(None) }
|
||||
}
|
||||
|
||||
/// The SSH settings with every target known now.
|
||||
pub fn ssh(&self) -> Result<Arc<SshConfig>> {
|
||||
self.current.read().unwrap().clone().context("SSH is not configured on this broker")
|
||||
}
|
||||
|
||||
/// Looks the branch's nodes up again if they're stale, or if `operation` names a node that
|
||||
/// isn't known yet. A failed lookup keeps the last nodes, and is only logged: the request
|
||||
/// then fails on its own if its node is still unknown.
|
||||
pub async fn refresh(&self, config: &Config, operation: &Operation) {
|
||||
let (Some(ssh), Some(deploy)) = (&config.ssh, &config.deploy) else { return };
|
||||
let names = nodes(operation);
|
||||
if names.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut looked = self.looked.lock().await;
|
||||
let known = self.ssh().is_ok_and(|ssh| names.iter().all(|n| ssh.targets.contains_key(*n)));
|
||||
let due = match *looked {
|
||||
None => true,
|
||||
Some((at, succeeded)) => {
|
||||
let age = at.elapsed();
|
||||
(succeeded && age > FRESH) || (!succeeded && age > RETRY) || (!known && age > RETRY)
|
||||
}
|
||||
};
|
||||
if !due {
|
||||
return;
|
||||
}
|
||||
|
||||
// Nobody sees the builder's progress: this is the broker's own business.
|
||||
let out = Output(mpsc::channel(1).0);
|
||||
let result = crate::builder::nodes(ssh, deploy, &out, &CancellationToken::new()).await;
|
||||
*looked = Some((Instant::now(), result.is_ok()));
|
||||
match result {
|
||||
Ok(found) => self.set(ssh, found.nodes),
|
||||
Err(error) => eprintln!("<4>Couldn't look the main branch's deploy nodes up ({error:#})"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces the nodes, as a lookup does.
|
||||
fn set(&self, ssh: &SshConfig, nodes: BTreeMap<String, Node>) {
|
||||
*self.current.write().unwrap() = Some(Arc::new(with_nodes(ssh, nodes)));
|
||||
}
|
||||
|
||||
/// Replaces the nodes as if they had just been looked up, so none are looked up for a while;
|
||||
/// for tests, which have no builder to ask.
|
||||
pub fn assume(&self, config: &Config, nodes: BTreeMap<String, Node>) {
|
||||
let ssh = config.ssh.as_ref().expect("SSH is configured");
|
||||
self.set(ssh, nodes);
|
||||
*self.looked.try_lock().expect("nothing is looking nodes up") = Some((Instant::now(), true));
|
||||
}
|
||||
}
|
||||
|
||||
/// The node names an operation reaches.
|
||||
fn nodes(operation: &Operation) -> Vec<&str> {
|
||||
match operation {
|
||||
Operation::Ssh { destination: Destination::Node(node), .. }
|
||||
| Operation::Query { destination: Destination::Node(node), .. } => vec![&**node],
|
||||
Operation::Deploy { targets, .. } => targets.iter().map(|t| t.node()).collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The SSH settings with `nodes` as targets. Nodes without an SSH user or with an invalid name are
|
||||
/// left out, since nothing could reach them.
|
||||
fn with_nodes(ssh: &SshConfig, nodes: BTreeMap<String, Node>) -> SshConfig {
|
||||
let mut targets = BTreeMap::new();
|
||||
for (name, node) in nodes {
|
||||
if name.parse::<crate::types::NodeName>().is_err() {
|
||||
continue;
|
||||
}
|
||||
let Some(user) = node.ssh_user else { continue };
|
||||
let sudo = node.sudo.unwrap_or_else(default_sudo);
|
||||
targets.insert(name, SshTarget { hostname: node.hostname, user, ssh_opts: node.ssh_opts, sudo });
|
||||
}
|
||||
SshConfig { targets, ..ssh.clone() }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn node(user: Option<&str>, sudo: Option<&str>) -> Node {
|
||||
Node {
|
||||
hostname: "box.example".into(),
|
||||
ssh_user: user.map(Into::into),
|
||||
ssh_opts: vec!["-p".into(), "2222".into()],
|
||||
sudo: sudo.map(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreachable_nodes_are_left_out() {
|
||||
let ssh =
|
||||
SshConfig { ssh: "ssh".into(), key: "/key".into(), known_hosts: "/kh".into(), targets: BTreeMap::new() };
|
||||
|
||||
let mut nodes = BTreeMap::new();
|
||||
nodes.insert("web".to_owned(), node(Some("deploy"), Some("doas -u")));
|
||||
nodes.insert("plain".to_owned(), node(Some("deploy"), None));
|
||||
nodes.insert("nobody".to_owned(), node(None, None));
|
||||
nodes.insert("-oProxyCommand=x".to_owned(), node(Some("deploy"), None));
|
||||
|
||||
let ssh = with_nodes(&ssh, nodes);
|
||||
assert_eq!(ssh.targets.keys().collect::<Vec<_>>(), ["plain", "web"]);
|
||||
assert_eq!(ssh.targets["web"].sudo, "doas -u");
|
||||
assert_eq!(ssh.targets["plain"].sudo, "sudo -u");
|
||||
assert_eq!(ssh.targets["web"].ssh_opts, ["-p", "2222"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_node_operations_look_nodes_up() {
|
||||
let deploy: Operation = Operation::Deploy {
|
||||
targets: vec!["web".parse().unwrap(), "river.system".parse().unwrap()],
|
||||
commit: "0123456789abcdef0123456789abcdef01234567".parse().unwrap(),
|
||||
boot: false,
|
||||
};
|
||||
assert_eq!(nodes(&deploy), ["web", "river"]);
|
||||
assert!(nodes(&Operation::Requests).is_empty());
|
||||
}
|
||||
}
|
||||
+14
-8
@@ -10,6 +10,7 @@ use nix::unistd::{Pid, geteuid};
|
||||
use serde_json::json;
|
||||
use tokio::io::DuplexStream;
|
||||
|
||||
use slop_broker::builder::Node;
|
||||
use slop_broker::config::Config;
|
||||
use slop_broker::proto::{ApproveRequest, ApproveResponse, receive, send};
|
||||
use slop_broker::proto::{
|
||||
@@ -45,16 +46,21 @@ fn broker(directory: &Path, ops: serde_json::Value) -> Arc<Broker> {
|
||||
"approver_group": "root",
|
||||
"audit_log": directory.join("audit.jsonl"),
|
||||
"remote": { "socket": "/unused", "user": "root", "approvers": ["laptop"] },
|
||||
"ssh": {
|
||||
"ssh": ssh,
|
||||
"key": "/key",
|
||||
"known_hosts": "/kh",
|
||||
"targets": { "river": { "hostname": "river.example.org", "user": "deploy", "ssh_opts": [] } },
|
||||
"ssh": { "ssh": ssh, "key": "/key", "known_hosts": "/kh" },
|
||||
"deploy": {
|
||||
"builder": { "hostname": "builder.example.org", "user": "builder", "ssh_opts": [] },
|
||||
"nix": "/unused",
|
||||
"cache": directory.join("cache"),
|
||||
},
|
||||
}))
|
||||
.unwrap();
|
||||
|
||||
Arc::new(Broker::new(config).unwrap())
|
||||
// The main branch's nodes, as the builder would have found them
|
||||
let broker = Broker::new(config).unwrap();
|
||||
let river =
|
||||
Node { hostname: "river.example.org".into(), ssh_user: Some("deploy".into()), ssh_opts: vec![], sudo: None };
|
||||
broker.targets.assume(&broker.config, [("river".to_owned(), river)].into());
|
||||
Arc::new(broker)
|
||||
}
|
||||
|
||||
struct Client {
|
||||
@@ -152,7 +158,7 @@ async fn unknown_nodes_and_versions_are_rejected() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn builds_need_a_builder_and_a_cache() {
|
||||
async fn builds_need_a_cache() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let broker = broker(directory.path(), json!({ "build": { "action": "auto" } }));
|
||||
|
||||
@@ -469,7 +475,7 @@ fn secrets_broker(directory: &Path) -> Option<Secrets> {
|
||||
"approver_group": "root",
|
||||
"audit_log": directory.join("audit.jsonl"),
|
||||
"remote": { "socket": "/unused", "user": "root", "approvers": [] },
|
||||
"ssh": { "ssh": ssh, "key": "/key", "known_hosts": "/kh", "targets": {} },
|
||||
"ssh": { "ssh": ssh, "key": "/key", "known_hosts": "/kh" },
|
||||
"deploy": {
|
||||
"builder": { "hostname": "builder.example.org", "user": "builder", "ssh_opts": [] },
|
||||
"nix": "/unused",
|
||||
|
||||
+62
-2
@@ -1,11 +1,11 @@
|
||||
//! The builder's Git-only stages against a local Git repository. Skipped where `git` (or, for
|
||||
//! secrets, `nix`) isn't installed, such as the package build's sandbox.
|
||||
//! secrets and deploy nodes, `nix`) isn't installed, such as the package build's sandbox.
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
use serde::de::DeserializeOwned;
|
||||
use slop_broker::builder::{BuilderRequest, Description, MAX_DIFF, SecretContext, SecretRequest};
|
||||
use slop_broker::builder::{BuilderRequest, Description, MAX_DIFF, Nodes, SecretContext, SecretRequest};
|
||||
use slop_broker::proto::{decode, encode};
|
||||
use slop_broker::types::ObjectId;
|
||||
|
||||
@@ -161,6 +161,66 @@ fn secrets_are_looked_up_on_the_branch() {
|
||||
assert!(context.paths.is_empty() && context.recipients.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deploy_nodes_are_looked_up_on_the_branch() {
|
||||
let (Some(git_path), Some(nix_path)) = (git_directory(), program_directory("nix")) else {
|
||||
eprintln!("skipped: git or nix isn't installed");
|
||||
return;
|
||||
};
|
||||
|
||||
// Flake-wide defaults, which a node can override; the flake-wide `sshOpts` aren't used.
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let work = directory.path().join("work");
|
||||
std::fs::create_dir_all(&work).unwrap();
|
||||
git(&work, &["init", "--quiet", "--initial-branch=master"]);
|
||||
let flake = |web: &str| {
|
||||
format!(
|
||||
"{{ outputs = _: {{ deploy = {{ sshUser = \"deploy\"; sudo = \"doas -u\"; sshOpts = [ \"-i\" \"key\" ];\n\
|
||||
nodes.web = {{ hostname = \"{web}\"; sshOpts = [ \"-p\" \"2222\" ]; profiles = {{ }}; }};\n\
|
||||
nodes.box = {{ hostname = \"box.example\"; sshUser = \"root\"; sudo = \"sudo -u\"; profiles = {{ }}; }};\n\
|
||||
}}; }}; }}\n"
|
||||
)
|
||||
};
|
||||
std::fs::write(work.join("flake.nix"), flake("web.example")).unwrap();
|
||||
git(&work, &["add", "."]);
|
||||
git(&work, &["commit", "--quiet", "-m", "Nodes"]);
|
||||
|
||||
// An agent's branch can't move a node.
|
||||
git(&work, &["checkout", "--quiet", "-b", "agent"]);
|
||||
std::fs::write(work.join("flake.nix"), flake("attacker.example")).unwrap();
|
||||
git(&work, &["commit", "--quiet", "-am", "Move web"]);
|
||||
|
||||
let state = directory.path().join("state");
|
||||
std::fs::create_dir(&state).unwrap();
|
||||
let config = directory.path().join("builder.toml");
|
||||
std::fs::write(
|
||||
&config,
|
||||
format!(
|
||||
"repository = {:?}\nkey = \"/nonexistent\"\ndirectory = {:?}\npath = [{:?}, {:?}]\n",
|
||||
work.display().to_string(),
|
||||
state.display().to_string(),
|
||||
git_path.display().to_string(),
|
||||
nix_path.display().to_string(),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let found: Nodes = ask(&config, &BuilderRequest::Nodes);
|
||||
assert_eq!(&*found.commit, git(&work, &["rev-parse", "master"]));
|
||||
let web = &found.nodes["web"];
|
||||
assert_eq!(web.hostname, "web.example");
|
||||
assert_eq!(web.ssh_user.as_deref(), Some("deploy"));
|
||||
assert_eq!(web.ssh_opts, ["-p", "2222"]);
|
||||
assert_eq!(web.sudo.as_deref(), Some("doas -u"));
|
||||
let other = &found.nodes["box"];
|
||||
assert_eq!((other.ssh_user.as_deref(), other.sudo.as_deref()), (Some("root"), Some("sudo -u")));
|
||||
assert!(other.ssh_opts.is_empty());
|
||||
|
||||
// Asked again at the same commit, the cached answer is the same.
|
||||
let again: Nodes = ask(&config, &BuilderRequest::Nodes);
|
||||
assert_eq!(again, found);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blob_ids_match_git() {
|
||||
let Some(_) = git_directory() else {
|
||||
|
||||
Reference in new issue
Block a user