ops: Add age secrets

`slop secret keys|set|generate|rekey|read` work with an agenix secret
in the requester's checkout: it sends the ciphertext, and the broker
decrypts it with its own age identity and returns new ciphertext.
Field edits work on env and JSON secrets.

The path and recipients are the requester's, so before approval the
builder reads the protected main branch: it looks the ciphertext's
blob up there, so approvers see which file it really is, and
evaluates that branch's rules file to compare the recipients.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jackos1998andClaude Opus 5.5 committed 2026-11-24 00:56:17 +00:00
1 parent f94ad9ab9e
commit 005e3d32df
22 files changed
+2646 -116

No files matched your search

+2 -2
View File
@@ -14,8 +14,8 @@ them.
## Overview
`slop-broker` runs privileged operations (SSH commands, deploys, builds, and later secrets, DNS and
previews) for coding agents, under a policy and usually after a human approves each one. Agents use
`slop-broker` runs privileged operations (SSH commands, deploys, builds and age secrets, and later
DNS and previews) for coding agents, under a policy and usually after a human approves each one. Agents use
the `slop` CLI; approvers use `slop-approve`, Home Assistant notifications or the web app. It's a
Rust crate (one library, the `slop-broker` and `slop` binaries) plus NixOS and home-manager modules,
all in this flake.
Generated
+873 -31
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -6,6 +6,7 @@ description = "Approval broker that runs privileged operations for coding agents
license = "MIT"
[dependencies]
age = { version = "0.12.1", features = ["ssh", "armor"] }
anyhow = "1"
askama = "0.16"
async-trait = "0.1.92"
@@ -25,7 +26,9 @@ rustls = { version = "0.23", default-features = false, features = ["ring", "std"
serde = { version = "1", features = ["derive"] }
serde_bytes = "0.11"
serde_json = "1"
sha1 = "0.11"
sha2 = "0.11.1"
ssh-key = { version = "0.6.7", default-features = false, features = ["ed25519", "std", "alloc"] }
tokio = { version = "1", features = ["full"] }
tokio-tungstenite = { version = "0.27", features = ["rustls-tls-webpki-roots"] }
tokio-util = { version = "0.7", features = ["codec"] }
@@ -35,6 +38,7 @@ tower-sessions = "0.15"
tower-sessions-rusqlite-store = "0.15"
url = "2"
web-push = { version = "0.11", default-features = false }
x25519-dalek = { version = "3.0.0", features = ["static_secrets"] }
[dev-dependencies]
tempfile = "3"
+2 -2
View File
@@ -1,7 +1,7 @@
# slop-broker
An approval broker that runs privileged operations (SSH commands, deploys, builds, and later
secrets, DNS and previews) for coding agents, under a policy and usually after a human approves
An approval broker that runs privileged operations (SSH commands, deploys, builds and age
secrets, and later DNS and previews) for coding agents, under a policy and usually after a human approves
each one. Agents use the `slop` CLI; approvers use `slop-approve`, a web app (sign-in with OpenID
Connect, passkeys, Web Push) or Home Assistant notifications.
+5 -1
View File
@@ -16,7 +16,8 @@ How the code is put together, and how to extend it. The design and its rationale
| `src/exec.rs` | Running processes on the requester's framed stdio; cancellation |
| `src/ops/mod.rs` | `plan` (request → `Parsed`: scope, approval text), `execute`, quoting |
| `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/builder.rs` | Both sides of the builder: the worker (forced command) and the broker's client |
| `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/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/ha.rs` | Home Assistant Companion notifications |
@@ -160,6 +161,9 @@ Arguments from the requester are validated so none can be read as an option.
exactly what an approval should cover, and an `execute` arm.
- Put anything shown but not part of the approval (commands, diffs) in `detail`.
- Set `limits` and `sensitive` where the operation reveals or redistributes secrets.
- If approvers need something looked up first (as secrets do, on the main branch), list the
operation in `prepares` and fill in `detail` in a `prepare` arm; it runs before approval and
only if policy wouldn't refuse.
3. Add the client subcommand in `src/bin/slop.rs` (clap parses validated types directly through
`FromStr`), and how to print its `OpResult`.
4. Tests: parsing in the module, behaviour in `tests/broker.rs` with fakes of what it calls.
+44 -22
View File
@@ -36,6 +36,9 @@ together is in [`architecture.md`](architecture.md); the NixOS and home-manager
activates the results.
- The broker's box should already be trusted with what the broker holds. With deploys, the deploy
key is root on every box it reaches, so also giving the broker access to secrets adds little.
- The repository's main branch is trusted: only people can push to it. Approvals show changes
relative to it, and secrets are checked against it, so requesters' Git credentials must not be
able to push to it (protect the branch).
## Transport
@@ -93,7 +96,7 @@ then streams the output.
| `slop ssh <node> -- <cmd>`, `slop ssh --host user@host[:port] -- <cmd>` | Any command over SSH | ask |
| `slop deploy <node[.profile]>… [--commit <rev>] [--boot]` | Build a pushed commit and deploy it, to all targets at once | ask |
| `slop build <attr>… [--commit <rev>]` | Build flake attributes of a pushed commit and push them to a binary cache | ask |
| `slop secret keys\|set\|generate\|rekey\|read …` (planned) | Work with age secrets | `keys` auto, `read` always ask, others ask |
| `slop secret keys\|set\|generate\|rekey\|read <file> …` | Work with age secrets in the requester's checkout | `keys` auto, `read` always ask, others ask |
| `slop dns list\|set\|delete …` (planned) | Change records in public DNS zones | `list` auto, others ask |
| `slop preview <port> [--name n] [--public] [--auth basic\|sso] [--ttl 4h]` (planned) | Publish a dev server | ask |
| `slop requests` | Show this requester's pending requests and active leases | always allowed |
@@ -221,8 +224,8 @@ worker answers with the session like the page does. Requests that need a passkey
Each request, decision, approver, lease use and result is an event with the request's ID. The
broker writes it to the journal as a line of text and to `audit.jsonl` in its state directory as a
line of JSON. `slop-approve log [-n 50] [--json]` shows the recent events through the approve
socket, with each request's full detail. Secret operations will record the file and a hash of the
ciphertext before and after, never values.
socket, with each request's full detail. Secret operations record the file and the blob ID of the
ciphertext they were sent, never values.
## Operations
@@ -327,32 +330,51 @@ a real derivation. So the cache is filled only from builds done by the builder (
(`services.slop-broker-cache`), and the store's next collection takes the paths: agent builds are
for sharing for a while, not for keeping.
## Planned operations
### Secrets
The broker gets its own age identity, added as a recipient of the secrets it may handle (next to
the people's keys), so no person's key goes to the broker's box. Adding it to an existing
repository needs one full rekey.
The broker has its own age identity, added as a recipient of the secrets it may handle next to
the people's keys, so no person's key goes to the broker's box. Adding it to an existing repository
needs one full rekey.
The agent sends the current `.age` file with each request, and the broker returns new ciphertext.
The broker never writes to a checkout.
The requester sends the current `.age` file with each request, and the broker returns new
ciphertext. The broker never writes to a checkout.
| Command | Result | Value enters VM? |
| Command | Result | Value reaches the requester? |
|---|---|---|
| `keys <file>` | Key names of an env, JSON or YAML secret | No |
| `set <file> <key>` (value on stdin) | That field replaced, re-encrypted | Only what the agent sent |
| `set <file> --whole` | Whole file replaced | Only what the agent sent |
| `generate <file> <key> --type password\|hex\|base64\|wireguard\|ssh-ed25519\|age` | Value created by the broker; keypair types return the public half | No |
| `rekey <file> -r <recipient>…` | Re-encrypted to the given recipients | No |
| `keys <file>` | Key names of an env or JSON secret | No |
| `set <file> [<key>]` (value on stdin) | That field, or the whole file, replaced and re-encrypted | Only what it sent |
| `generate <file> [<key>] --kind password\|hex\|base64\|wireguard\|ssh-ed25519\|age` | A value the broker creates; keypair kinds return the public half | No |
| `rekey <file>` | Re-encrypted to the given recipients | No |
| `read <file>` | Plaintext | Yes, so always `ask`, never leased |
- The requester lists the recipients. The broker names each one from a trusted list of known keys
(such as host keys and people's keys on the main branch), and shows changes from the file's
current recipients. An unknown key is flagged in the approval. This avoids evaluating
agent-written Nix just to get a recipient list.
- Encrypting to new recipients is done offline (`rage -r`) and needs no broker.
- The operations work for any repository that uses age files with the broker as a recipient.
Field edits work on env files (`.env.age`, keeping every other line as it was) and JSON objects
of strings (`.json.age`). Anything else is changed whole.
#### What approvers see
The path in a request is only the requester's name for the file, and the ciphertext and the
recipients come from the requester too. Before approval, the builder fetches the main branch,
which only people should be able to push to, and the approval shows what that branch says:
- **What the content is.** The builder looks the ciphertext's Git blob ID up on the branch. The
approval says the file is the named path as on the branch, the same as *another* path (flagged:
an agent could otherwise send a sensitive file's ciphertext under a harmless name, and have it
read or re-encrypted to a key of its own), or not on the branch at all (new, or changed on a
branch). A pushed commit wouldn't prove anything here, since any branch can copy a blob to any
path.
- **Whether the recipients are right.** The builder evaluates the branch's own agenix rules file
(`secrets.rules`, cached per commit) for the path, and the approval says the requested
recipients match it, or lists what's added and removed, or that the path isn't in the rules.
Only the protected branch's Nix is evaluated, never a requester's commit, so this doesn't need
the builder approval. `secrets.names` labels well-known keys (such as people's); other keys are
shown abbreviated.
- The broker always adds its own key to the recipients, and says so, so it can change the file
later.
Requests that read a secret, change who can read one or name content as another file are marked
sensitive. The audit log records the approval's text, including the blob ID, never values.
## Planned operations
### DNS
+21 -1
View File
@@ -11,6 +11,7 @@ let
cfg = config.services.slop-broker;
ha = cfg.homeAssistant;
web = cfg.web;
secrets = cfg.secrets;
isRuntimePath = p: hasPrefix "/" p && !(hasPrefix "/nix/store/" p);
hasLocalRequesters = any (r: r.uid != null) (attrValues cfg.requesters);
@@ -127,6 +128,11 @@ let
client_secret = "oidc-secret";
state_dir = "/var/lib/slop-broker/web";
} else null;
secrets = if secrets.enable then {
identity = "age-identity";
inherit (secrets) rules names;
} else null;
});
in
{
@@ -197,6 +203,15 @@ in
clientSecretFile = mkOpt' str "" "Runtime path to the client secret; never a Nix store path.";
group = mkOpt' str "slop-approvers" "Group (the ID token's `groups` claim) whose members may approve.";
};
secrets = {
enable = mkBoolOpt' false
"Whether to work with age secrets (`slop secret`); needs `deploy`, whose builder reads the main branch.";
identityFile = mkOpt' str "" "Runtime path to the broker's age identity; never a Nix store path.";
rules = mkOpt' str "secrets.nix" "The agenix rules file, relative to the repository's root.";
names = mkOpt' (attrsOf str) { }
"Names for well-known recipients (such as people's keys), only used to label them in approvals.";
};
};
config = mkIf cfg.enable {
@@ -229,6 +244,10 @@ in
assertion = web.enable -> (web.url != "" && web.issuer != "" && isRuntimePath web.clientSecretFile);
message = "slop-broker's web app needs a URL, an issuer and a runtime client secret file.";
}
{
assertion = secrets.enable -> (cfg.deploy.enable && isRuntimePath secrets.identityFile);
message = "slop-broker secrets need `deploy` and a runtime identity file.";
}
];
users = mkMerge [
@@ -269,7 +288,8 @@ in
optional cfg.ssh.enable "ssh-key:${cfg.ssh.keyFile}" ++
optional cfg.cache.enable "cache-key:${cfg.cache.keyFile}" ++
optional ha.enable "ha-token:${ha.tokenFile}" ++
optional web.enable "oidc-secret:${web.clientSecretFile}";
optional web.enable "oidc-secret:${web.clientSecretFile}" ++
optional secrets.enable "age-identity:${secrets.identityFile}";
User = "slop-broker";
Group = "slop-broker";
+2 -1
View File
@@ -27,7 +27,8 @@ in
description = "slop-broker package; the flake's modules default to its own.";
};
repository = mkOpt' str "" "Git repository to fetch commits from.";
branch = mkOpt' str "master" "Branch that approvals list commits relative to.";
branch = mkOpt' str "master"
"Branch that approvals list commits relative to, and that secrets are checked against; only people should be able to push to it.";
keyFile = mkOpt' str "" "Runtime path to a read-only key for `repository`, readable by the builder.";
brokerKeys = mkOpt' (listOf str) [ ] "SSH public keys of brokers that may run builds.";
};
+22
View File
@@ -27,6 +27,7 @@ applies a policy, and asks a human to approve most requests.
| `slop ssh <node> -- <command>…` | Any command over SSH, as the node's configured user | asks |
| `slop deploy <node>… [--commit <rev>] [--boot]` | Build a pushed commit and deploy it to all the nodes at once | asks |
| `slop build <attr>… [--commit <rev>]` | Build flake attributes of a pushed commit and push them to the binary cache | asks |
| `slop secret keys\|set\|generate\|rekey\|read <file> …` | Work with an age secret in your checkout | `keys` usually none; others ask |
| `slop requests` | Your pending requests and active leases | none |
- Prefer `status`, `logs` and `failed` to `slop ssh` for looking at a box: they don't wait for a
@@ -65,6 +66,27 @@ applies a policy, and asks a human to approve most requests.
`nixosConfigurations.host.config.system.build.toplevel`; names containing dots can't be built.
- Once pushed, it prints the output paths, one per line.
### Secrets
`slop secret` works with agenix secrets in your checkout: it sends the `.age` file to the broker,
which holds a key that can decrypt it, and writes the new file back. Commit the rewritten file
like any other change.
- `slop secret keys <file>` lists the keys of an env (`.env.age`) or JSON (`.json.age`) secret.
- `slop secret set <file> [KEY] < value` sets one key, or the whole file without `KEY`, to the value
on stdin. Pipe the value from wherever it is; don't put it on the command line.
- `slop secret generate <file> [KEY] --kind password|hex|base64|wireguard|ssh-ed25519|age` has the
broker generate the value, which never reaches you; keypair kinds print the public key.
- `slop secret rekey <file>` re-encrypts to the recipients the rules file lists now, for example
after adding a box to a secret.
- `slop secret read <file>` prints the plaintext. It always asks, so only use it when the task
needs the value itself, and don't print it anywhere else.
- Recipients come from the agenix rules file (`secrets.nix`, found above the file, or `--rules`),
evaluated in your checkout; `-r <key>` overrides them. Approvers see whether they match the
rules on the main branch, so change `secrets.nix` in the same commit as the secret and expect
an approver to look closely at differences.
- A file that doesn't exist yet is created by `set` and `generate`.
## Don't
- Don't try to find, read or copy the broker's credentials, or use deploy tools or keys directly.
+249 -10
View File
@@ -1,5 +1,6 @@
//! `slop`: the agents' client for the broker.
use std::num::NonZeroU16;
use std::path::PathBuf;
use std::process::exit;
use anyhow::{Context, Result, bail};
@@ -9,12 +10,14 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::mpsc;
use slop_broker::proto::{
ApprovedBy, ClientMessage, DEFAULT_VSOCK_PORT, Destination, HOST_CID, OpResult, Operation, PROTOCOL_VERSION, Query,
Request, ServerMessage, decode, encode, transport,
ApprovedBy, ClientMessage, DEFAULT_VSOCK_PORT, Destination, GenKind, HOST_CID, OpResult, Operation,
PROTOCOL_VERSION, Query, Request, SecretFile, SecretOp, ServerMessage, Target as SecretTarget, decode, encode,
transport,
};
use slop_broker::remote::{self, Role, Stream};
use slop_broker::types::{
Arg, CommitId, DeployTarget, FlakeAttr, HostName, Lines, NodeName, Since, UnitName, UserName,
Arg, CommitId, DeployTarget, FlakeAttr, HostName, Lines, NodeName, Recipient, SecretKey, SecretPath, Since,
UnitName, UserName,
};
/// Exit status when the broker didn't run the operation (denied, expired, invalid or failed).
@@ -126,12 +129,230 @@ enum Command {
#[arg(long, default_value = "HEAD")]
commit: String,
},
/// Work with an age secret: list its keys, set or generate a value, re-encrypt or read it.
Secret {
#[command(subcommand)]
action: SecretCommand,
},
/// Show your pending requests and active leases.
Requests,
/// Print the guide for agents.
Guide,
}
#[derive(Args)]
struct SecretArgs {
/// The .age file; the result is written back to it.
file: PathBuf,
/// The agenix rules file; by default $RULES, or the nearest secrets.nix above FILE.
#[arg(long, env = "RULES")]
rules: Option<PathBuf>,
}
#[derive(Args)]
struct Recipients {
/// Encrypt to these keys instead of the ones the rules file lists.
#[arg(short = 'r', long = "recipient")]
recipients: Vec<String>,
}
#[derive(Subcommand)]
enum SecretCommand {
/// The keys of an env (.env.age) or JSON (.json.age) secret.
Keys {
#[command(flatten)]
secret: SecretArgs,
},
/// Print the plaintext. Always asks an approver; only use it when the task needs the value.
Read {
#[command(flatten)]
secret: SecretArgs,
},
/// Set one key of an env or JSON secret, or the whole file without KEY, to the value on stdin.
Set {
#[command(flatten)]
secret: SecretArgs,
key: Option<SecretKey>,
#[command(flatten)]
recipients: Recipients,
},
/// Set one key, or the whole file without KEY, to a value the broker generates; prints the
/// public half of keypairs.
Generate {
#[command(flatten)]
secret: SecretArgs,
key: Option<SecretKey>,
#[arg(long, value_enum)]
kind: Kind,
#[command(flatten)]
recipients: Recipients,
},
/// Re-encrypt to the recipients the rules file lists now (or -r).
Rekey {
#[command(flatten)]
secret: SecretArgs,
#[command(flatten)]
recipients: Recipients,
},
}
#[derive(Clone, Copy, clap::ValueEnum)]
enum Kind {
/// 32 letters and digits.
Password,
/// 32 random bytes in hex.
Hex,
/// 32 random bytes in base64.
Base64,
/// A WireGuard private key; prints the public key.
Wireguard,
/// An OpenSSH ed25519 private key; prints the public key.
SshEd25519,
/// An age identity; prints its recipient.
Age,
}
impl From<Kind> for GenKind {
fn from(kind: Kind) -> GenKind {
match kind {
Kind::Password => GenKind::Password,
Kind::Hex => GenKind::Hex,
Kind::Base64 => GenKind::Base64,
Kind::Wireguard => GenKind::Wireguard,
Kind::SshEd25519 => GenKind::SshEd25519,
Kind::Age => GenKind::Age,
}
}
}
/// A secret file as the rules file names it.
struct Located {
file: PathBuf,
rules: PathBuf,
path: SecretPath,
}
impl SecretArgs {
fn locate(&self) -> Result<Located> {
let name = self.file.file_name().context("FILE has no file name")?;
let directory = match self.file.parent() {
Some(parent) if !parent.as_os_str().is_empty() => parent.to_owned(),
_ => PathBuf::from("."),
};
let directory = directory.canonicalize().with_context(|| format!("finding {}", directory.display()))?;
let file = directory.join(name);
let rules = match &self.rules {
Some(rules) => rules.canonicalize().with_context(|| format!("finding {}", rules.display()))?,
None => directory
.ancestors()
.map(|d| d.join("secrets.nix"))
.find(|r| r.is_file())
.context("no secrets.nix above the file; pass --rules")?,
};
let base = rules.parent().context("the rules file has no directory")?;
let relative =
file.strip_prefix(base).with_context(|| format!("{} isn't under {}", file.display(), base.display()))?;
let path = parse::<SecretPath>(&relative.to_string_lossy())?;
Ok(Located { file, rules, path })
}
}
impl Located {
fn read(&self) -> Result<Vec<u8>> {
std::fs::read(&self.file).with_context(|| format!("reading {}", self.file.display()))
}
/// The current file, or none if it doesn't exist yet.
fn base(&self) -> Result<Option<Vec<u8>>> {
match std::fs::read(&self.file) {
Ok(data) => Ok(Some(data)),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(error).with_context(|| format!("reading {}", self.file.display())),
}
}
fn secret_file(&self) -> Result<SecretFile> {
Ok(SecretFile { path: self.path.clone(), ciphertext: self.read()? })
}
/// `-r`, or the recipients the rules file lists for this path.
fn recipients(&self, given: &Recipients) -> Result<Vec<Recipient>> {
if !given.recipients.is_empty() {
return given.recipients.iter().map(|r| Recipient::normalize(r).map_err(anyhow::Error::msg)).collect();
}
let output = std::process::Command::new("nix")
.args(["--extra-experimental-features", "nix-command flakes", "eval", "--json", "--file"])
.arg(&self.rules)
.args(["--apply", "rules: builtins.mapAttrs (_: v: v.publicKeys or [ ]) rules"])
.output()
.context("running nix to read the rules file")?;
if !output.status.success() {
bail!("evaluating {}: {}", self.rules.display(), String::from_utf8_lossy(&output.stderr).trim());
}
let rules: std::collections::BTreeMap<String, Vec<String>> = serde_json::from_slice(&output.stdout)?;
let keys = rules
.get(&*self.path)
.with_context(|| format!("{} isn't in {}; add it there, or pass -r", self.path, self.rules.display()))?;
keys.iter().map(|k| Recipient::normalize(k).map_err(anyhow::Error::msg)).collect()
}
/// Replaces the file, never leaving it half-written.
fn write(&self, ciphertext: &[u8]) -> Result<()> {
let name = self.file.file_name().unwrap().to_string_lossy();
let temporary = self.file.with_file_name(format!(".{name}.slop"));
std::fs::write(&temporary, ciphertext).with_context(|| format!("writing {}", temporary.display()))?;
std::fs::rename(&temporary, &self.file).with_context(|| format!("replacing {}", self.file.display()))
}
}
fn target(key: Option<SecretKey>) -> SecretTarget {
key.map_or(SecretTarget::Whole, SecretTarget::Field)
}
/// The operation, and the file a returned ciphertext goes to.
fn secret_operation(action: SecretCommand) -> Result<(Operation, Located)> {
let (op, located) = match action {
SecretCommand::Keys { secret } => {
let located = secret.locate()?;
(SecretOp::Keys { file: located.secret_file()? }, located)
}
SecretCommand::Read { secret } => {
let located = secret.locate()?;
(SecretOp::Read { file: located.secret_file()? }, located)
}
SecretCommand::Set { secret, key, recipients } => {
let located = secret.locate()?;
let op = SecretOp::Set {
path: located.path.clone(),
base: located.base()?,
target: target(key),
recipients: located.recipients(&recipients)?,
};
(op, located)
}
SecretCommand::Generate { secret, key, kind, recipients } => {
let located = secret.locate()?;
let op = SecretOp::Generate {
path: located.path.clone(),
base: located.base()?,
target: target(key),
kind: kind.into(),
recipients: located.recipients(&recipients)?,
};
(op, located)
}
SecretCommand::Rekey { secret, recipients } => {
let located = secret.locate()?;
let op = SecretOp::Rekey { file: located.secret_file()?, recipients: located.recipients(&recipients)? };
(op, located)
}
};
Ok((Operation::Secret(op), located))
}
fn operation(command: Command) -> Result<Operation> {
Ok(match command {
Command::Ssh { target, command } => Operation::Ssh { destination: target.destination()?, command },
@@ -145,7 +366,7 @@ fn operation(command: Command) -> Result<Operation> {
Command::Deploy { targets, commit, boot } => Operation::Deploy { targets, commit: resolve(&commit)?, boot },
Command::Build { attrs, commit } => Operation::Build { attrs, commit: resolve(&commit)? },
Command::Requests => Operation::Requests,
Command::Guide => unreachable!(),
Command::Guide | Command::Secret { .. } => unreachable!(),
})
}
@@ -203,11 +424,14 @@ async fn run(cli: Cli) -> Result<i32> {
return Ok(0);
}
let request = Request {
version: PROTOCOL_VERSION,
label: cli.label.or_else(default_label),
operation: operation(cli.command)?,
let (operation, secret) = match cli.command {
Command::Secret { action } => {
let (operation, located) = secret_operation(action)?;
(operation, Some(located))
}
command => (operation(command)?, None),
};
let request = Request { version: PROTOCOL_VERSION, label: cli.label.or_else(default_label), operation };
let (mut sink, mut source) = transport(connect().await?).split();
@@ -250,8 +474,17 @@ async fn run(cli: Cli) -> Result<i32> {
stderr.flush().await?;
}
ServerMessage::Finished { exit, result } => {
if let Some(result) = result {
show(&result, cli.json)?;
match (result, &secret) {
// New ciphertext goes back into the file, never to the terminal.
(Some(OpResult::Secret { ciphertext, public }), Some(located)) => {
located.write(&ciphertext)?;
eprintln!("slop: wrote {}", located.file.display());
if let Some(public) = public {
println!("{public}");
}
}
(Some(result), _) => show(&result, cli.json)?,
(None, _) => {}
}
return Ok(exit);
}
@@ -278,6 +511,12 @@ fn show(result: &OpResult, json: bool) -> Result<()> {
}
match result {
OpResult::SecretKeys(keys) => {
for key in keys {
println!("{key}");
}
}
OpResult::Secret { .. } => bail!("the broker returned a secret for a request that didn't ask for one"),
OpResult::Requests { pending, leases } => {
if pending.is_empty() && leases.is_empty() {
println!("No pending requests or leases.");
+134 -6
View File
@@ -7,6 +7,7 @@
//! 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.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Stdio;
@@ -23,7 +24,7 @@ use tokio_util::sync::CancellationToken;
use crate::exec::Output;
use crate::proto::{ServerMessage, codec, decode, encode};
use crate::types::{CommitId, DeployTarget, FlakeAttr};
use crate::types::{CommitId, DeployTarget, FlakeAttr, ObjectId, RulesPath, SecretPath};
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
@@ -52,6 +53,32 @@ pub enum BuilderRequest {
/// Fetch a commit and describe it; runs only Git.
Describe(CommitId),
Build(BuildRequest),
/// What the main branch says about a secret.
Secret(SecretRequest),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SecretRequest {
/// The blob ID of the requester's ciphertext, if it sent one.
pub blob: Option<ObjectId>,
/// Relative to the rules file's directory, as the rules file names it.
pub path: SecretPath,
pub rules: RulesPath,
}
/// The main branch's view of a secret. 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 SecretContext {
pub branch: String,
/// The branch's commit it was read at.
pub commit: CommitId,
/// Every path on the branch, from the repository's root, whose content is the blob.
pub paths: Vec<String>,
/// The path's recipients in the branch's rules file, or `None` if it has no entry.
pub recipients: Option<Vec<String>>,
}
/// A commit as approvers see it before anything is built. Everything but `on_branch` is
@@ -165,6 +192,17 @@ pub async fn build(
Ok(result)
}
/// What the main branch says about a secret. Its progress goes to `out`.
pub async fn secret(
ssh: &crate::config::SshConfig,
deploy: &crate::config::DeployConfig,
request: &SecretRequest,
out: &Output,
cancel: &CancellationToken,
) -> Result<SecretContext> {
call(ssh, deploy, &BuilderRequest::Secret(request.clone()), out, cancel).await
}
async fn call<R: DeserializeOwned>(
ssh: &crate::config::SshConfig,
deploy: &crate::config::DeployConfig,
@@ -220,6 +258,7 @@ pub async fn worker(config: &Path) -> Result<()> {
result = async {
match &request {
BuilderRequest::Describe(commit) => encode(&describe_commit(&config, commit).await?),
BuilderRequest::Secret(request) => encode(&secret_context(&config, request).await?),
BuilderRequest::Build(request) => {
let _lock = lock(&config.directory.join("build.lock")).await?;
encode(&run(&config, request).await?)
@@ -352,8 +391,17 @@ async fn has_commit(config: &BuilderConfig, commit: &CommitId) -> bool {
output(git(config, &mirror(config)).args(["cat-file", "-e", &format!("{commit}^{{commit}}")])).await.is_ok()
}
/// Fetches every branch into the mirror; one fetch at a time, separately from builds.
/// Fetches every branch into the mirror and checks it has `commit`.
async fn fetch(config: &BuilderConfig, commit: &CommitId) -> Result<()> {
fetch_all(config).await?;
if !has_commit(config, commit).await {
bail!("commit {commit} isn't on any branch of {}; push it first", config.repository);
}
Ok(())
}
/// Fetches every branch into the mirror; one fetch at a time, separately from builds.
async fn fetch_all(config: &BuilderConfig) -> Result<()> {
let _lock = lock_saying(&config.directory.join("fetch.lock"), "Waiting for another fetch…").await?;
let repository = mirror(config);
if !repository.exists() {
@@ -371,10 +419,6 @@ async fn fetch(config: &BuilderConfig, commit: &CommitId) -> Result<()> {
]))
.await
.context("fetching")?;
if !has_commit(config, commit).await {
bail!("commit {commit} isn't on any branch of {}; push it first", config.repository);
}
Ok(())
}
@@ -419,6 +463,79 @@ async fn describe_commit(config: &BuilderConfig, commit: &CommitId) -> Result<De
}
}
/// 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 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?;
blob_paths(&tree, blob)
}
None => Vec::new(),
};
let rules = rules(config, &commit, &request.rules).await?;
let recipients = rules.get(&*request.path).cloned();
Ok(SecretContext { branch: config.branch.clone(), commit, paths, recipients })
}
/// Paths in `git ls-tree -r -z` output whose object is `blob`.
fn blob_paths(tree: &str, blob: &ObjectId) -> Vec<String> {
tree.split('\0')
.filter_map(|entry| {
let (info, path) = entry.split_once('\t')?;
let mut fields = info.split(' ');
(fields.nth(1) == Some("blob") && fields.next() == Some(&**blob)).then(|| path.to_owned())
})
.collect()
}
/// The rules file's recipients by path, at `commit`. Evaluated once per commit, since that can
/// mean evaluating every system that declares secrets.
async fn rules(config: &BuilderConfig, commit: &CommitId, rules: &RulesPath) -> Result<BTreeMap<String, Vec<String>>> {
let cache = config.directory.join("secret-rules");
let file = cache.join(format!("{commit}-{}.json", hex::encode(rules.as_bytes())));
if let Ok(text) = std::fs::read_to_string(&file) {
return Ok(serde_json::from_str(&text)?);
}
eprintln!("Evaluating {rules} on {}…", config.branch);
// The values come from the environment, so none of them is ever Nix syntax.
let expression = "let \
env = builtins.getEnv; \
source = builtins.fetchGit { \
url = \"file://${env \"SLOP_REPOSITORY\"}\"; rev = env \"SLOP_REV\"; allRefs = true; \
}; \
in builtins.mapAttrs (_: v: v.publicKeys or [ ]) (import (source + \"/${env \"SLOP_RULES\"}\"))";
let evaluated = output(
command(config, "nix")
.args(["eval", "--json", "--impure"])
.args(NIX_OPTIONS)
.args(["--expr", expression])
.env("SLOP_REPOSITORY", mirror(config))
.env("SLOP_REV", &**commit)
.env("SLOP_RULES", &**rules),
)
.await
.with_context(|| format!("evaluating {rules}"))?;
let parsed: BTreeMap<String, Vec<String>> = serde_json::from_str(&evaluated).context("reading the rules")?;
// Only the newest commit's rules are worth keeping.
let _ = std::fs::remove_dir_all(&cache);
std::fs::create_dir_all(&cache)?;
std::fs::write(&file, &evaluated)?;
Ok(parsed)
}
async fn run(config: &BuilderConfig, request: &BuildRequest) -> Result<BuildResult> {
let commit = &request.commit;
let repository = mirror(config);
@@ -522,6 +639,17 @@ mod tests {
}
}
#[test]
fn finds_paths_of_a_blob() {
let blob: ObjectId = "0123456789abcdef0123456789abcdef01234567".parse().unwrap();
let tree = format!(
"100644 blob {blob}\tsecrets/a.age\0100644 blob {}\tsecrets/b.age\0\
100644 blob {blob}\tsecrets/copy of a.age\0160000 commit {blob}\tsub\0",
"f".repeat(40)
);
assert_eq!(blob_paths(&tree, &blob), ["secrets/a.age", "secrets/copy of a.age"]);
}
#[test]
fn selects_profiles_like_deploy_rs() {
let node: NodeProfiles = serde_json::from_str(
+24
View File
@@ -45,6 +45,26 @@ pub struct Config {
pub cache: Option<CacheConfig>,
#[serde(default)]
pub web: Option<WebConfig>,
#[serde(default)]
pub secrets: Option<SecretsConfig>,
}
/// Age secrets (see [`crate::ops::secret`]). Needs `deploy`, whose builder reads the main branch.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SecretsConfig {
/// The broker's age identity; relative paths are resolved in `$CREDENTIALS_DIRECTORY`.
pub identity: PathBuf,
/// The agenix rules file in the repository the builder fetches.
#[serde(default = "default_rules")]
pub rules: crate::types::RulesPath,
/// Names for well-known recipients, only used to label them in approvals.
#[serde(default)]
pub names: BTreeMap<String, crate::types::Recipient>,
}
fn default_rules() -> crate::types::RulesPath {
"secrets.nix".parse().unwrap()
}
/// The approvals web app (see [`crate::web`]): approvers sign in through an OpenID Connect
@@ -266,6 +286,10 @@ impl Config {
requester.policy
);
}
anyhow::ensure!(
self.secrets.is_none() || (self.ssh.is_some() && self.deploy.is_some()),
"secrets need ssh and deploy, whose builder reads the main branch"
);
Ok(())
}
+1
View File
@@ -60,6 +60,7 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
builtin: false,
prepared: None,
description: None,
secret: None,
operation,
})
}
+1
View File
@@ -74,6 +74,7 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
builtin: false,
prepared: None,
description: None,
secret: None,
operation,
})
}
+17 -1
View File
@@ -13,6 +13,7 @@ use crate::types::CommitId;
pub mod build;
pub mod deploy;
pub mod query;
pub mod secret;
pub mod ssh;
pub struct Parsed {
@@ -35,6 +36,8 @@ pub struct Parsed {
pub prepared: Option<crate::builder::BuildResult>,
/// The commit, as [`describe`] found it, for operations that build.
pub description: Option<Description>,
/// What the main branch says about a secret, as [`prepare`] found it.
pub secret: Option<crate::builder::SecretContext>,
pub operation: Operation,
}
@@ -76,6 +79,7 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
rule_scopes: Vec::new(),
prepared: None,
description: None,
secret: None,
operation,
})
}
@@ -97,11 +101,13 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
rule_scopes: Vec::new(),
prepared: None,
description: None,
secret: None,
operation,
})
}
Operation::Deploy { .. } => deploy::plan(broker, operation),
Operation::Build { .. } => build::plan(broker, operation),
Operation::Secret(_) => secret::plan(broker, operation),
Operation::Requests => Ok(Parsed {
op: "requests",
scope: Map::new(),
@@ -114,6 +120,7 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
rule_scopes: Vec::new(),
prepared: None,
description: None,
secret: None,
operation,
}),
}
@@ -124,6 +131,11 @@ pub fn builds(parsed: &Parsed) -> bool {
matches!(parsed.operation, Operation::Deploy { .. } | Operation::Build { .. })
}
/// Operations that look things up before approval without building, so approvers see more.
pub fn prepares(parsed: &Parsed) -> bool {
matches!(parsed.operation, Operation::Secret(_))
}
fn commit(operation: &Operation) -> Result<&CommitId> {
match operation {
Operation::Deploy { commit, .. } | Operation::Build { commit, .. } => Ok(commit),
@@ -170,6 +182,7 @@ pub fn builder_gate(parsed: &Parsed, description: &Description) -> Result<Parsed
builtin: false,
prepared: None,
description: None,
secret: None,
operation: parsed.operation.clone(),
})
}
@@ -189,6 +202,7 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
match parsed.operation {
Operation::Deploy { .. } => deploy::prepare(broker, parsed, io).await,
Operation::Build { .. } => build::prepare(broker, parsed, io).await,
Operation::Secret(_) => secret::prepare(broker, parsed, io).await,
_ => Ok(()),
}
}
@@ -197,6 +211,7 @@ pub async fn execute(broker: &Broker, requester: &str, parsed: Parsed, io: &mut
match parsed.operation {
Operation::Deploy { .. } => return deploy::execute(broker, &parsed, io).await.map(Into::into),
Operation::Build { .. } => return build::execute(broker, &parsed, io).await.map(Into::into),
Operation::Secret(_) => return secret::execute(broker, &parsed, io).await,
_ => {}
}
@@ -223,7 +238,7 @@ pub async fn execute(broker: &Broker, requester: &str, parsed: Parsed, io: &mut
.collect();
Ok(Outcome { exit: 0, result: Some(OpResult::Requests { pending, leases }) })
}
Operation::Deploy { .. } | Operation::Build { .. } => unreachable!(),
Operation::Deploy { .. } | Operation::Build { .. } | Operation::Secret(_) => unreachable!(),
}
}
@@ -282,6 +297,7 @@ mod tests {
builtin: false,
prepared: None,
description: None,
secret: None,
operation: Operation::Build { attrs: vec!["hello".parse().unwrap()], commit },
};
let description = Description {
+523
View File
@@ -0,0 +1,523 @@
//! Age secrets. The requester sends a secret's ciphertext, and the broker decrypts it with its
//! own identity, changes it and returns new ciphertext; it never writes to a checkout.
//!
//! The path a requester gives is only its name for the file. Before approval, the builder looks
//! the ciphertext up on the main branch, which only people can push to, and evaluates that
//! branch's rules file. Approvers see which file the content really is and whether the
//! recipients match the branch's rules.
use std::collections::BTreeMap;
use std::io::{Read, Write};
use anyhow::{Context, Result, bail, ensure};
use serde_json::{Map, Value};
use crate::builder::{SecretContext, SecretRequest};
use crate::config::SecretsConfig;
use crate::exec::Io;
use crate::policy::Limits;
use crate::proto::{GenKind, OpResult, Operation, SecretOp, ServerMessage, Target};
use crate::server::Broker;
use crate::types::{ObjectId, Recipient, RulesPath, SecretPath};
use super::{Outcome, Parsed};
pub mod format;
use format::Format;
/// Larger than any age file a repository keeps, and well within a message.
const MAX_CIPHERTEXT: usize = 256 * 1024;
/// The most a requester may send as a new value.
const MAX_VALUE: usize = 64 * 1024;
pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
let Operation::Secret(op) = &operation else { bail!("not a secret operation") };
broker.config.secrets.as_ref().context("secrets are not configured on this broker")?;
if let Some(ciphertext) = op.ciphertext() {
ensure!(ciphertext.len() <= MAX_CIPHERTEXT, "the secret is larger than {MAX_CIPHERTEXT} bytes");
ensure!(is_age(ciphertext), "{} isn't an age file", op.path());
}
if let Some(recipients) = op.recipients() {
ensure!(!recipients.is_empty(), "no recipients to encrypt to");
}
// Fields only exist in formats that have them.
let field = match op {
SecretOp::Keys { .. } => true,
SecretOp::Set { target, .. } | SecretOp::Generate { target, .. } => matches!(target, Target::Field(_)),
SecretOp::Read { .. } | SecretOp::Rekey { .. } => false,
};
if field {
Format::require(op.path())?;
}
let mut scope = Map::new();
scope.insert("action".into(), Value::from(op.action()));
scope.insert("path".into(), Value::from(op.path().to_string()));
let read = matches!(op, SecretOp::Read { .. });
Ok(Parsed {
op: "secret",
scope,
summary: summary(op),
detail: String::new(),
// The plaintext reaches the requester, so a person decides each time.
limits: if read { Limits { never_auto: true, never_lease: true } } else { Limits::default() },
sensitive: read,
stdin: matches!(op, SecretOp::Set { .. }),
builtin: false,
rule_scopes: Vec::new(),
prepared: None,
description: None,
secret: None,
operation,
})
}
fn summary(op: &SecretOp) -> String {
let path = op.path();
match op {
SecretOp::Keys { .. } => format!("list the keys of {path}"),
SecretOp::Read { .. } => format!("read {path}"),
SecretOp::Set { target: Target::Whole, .. } => format!("replace {path}"),
SecretOp::Set { target: Target::Field(key), .. } => format!("set {key} in {path}"),
SecretOp::Generate { target: Target::Whole, kind, .. } => format!("generate {path} ({})", kind.name()),
SecretOp::Generate { target: Target::Field(key), kind, .. } => {
format!("generate {key} in {path} ({})", kind.name())
}
SecretOp::Rekey { .. } => format!("re-encrypt {path}"),
}
}
/// Armored (as agenix writes them) or binary age files.
fn is_age(data: &[u8]) -> bool {
data.starts_with(b"-----BEGIN AGE ENCRYPTED FILE-----") || data.starts_with(b"age-encryption.org/")
}
/// Asks the builder what the main branch says about the secret, and writes the approval's detail.
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 deploy = broker.config.deploy.as_ref().context("the builder is not configured on this broker")?;
let own = own_recipient(config)?;
let request = SecretRequest {
blob: op.ciphertext().map(ObjectId::blob),
path: op.path().clone(),
rules: config.rules.clone(),
};
io.out.info("checking the secret against the main branch").await;
let context = crate::builder::secret(ssh, deploy, &request, &io.out, &io.cancel).await?;
let (detail, sensitive) = describe(op, &context, config, &own);
parsed.detail = detail;
parsed.sensitive |= sensitive;
parsed.secret = Some(context);
Ok(())
}
/// What approvers see, and whether anything in it needs their attention.
fn describe(op: &SecretOp, context: &SecretContext, config: &SecretsConfig, own: &Recipient) -> (String, bool) {
let path = op.path();
let branch = &context.branch;
let mut sensitive = false;
let mut lines = vec![format!("File: {path}"), format!("Checked against {branch} at {}", context.commit.short())];
// What the content really is, whatever the requester called it
let claimed = repository_path(&config.rules, path);
lines.push(match op.ciphertext() {
None => "Content: a new file".into(),
Some(ciphertext) if context.paths.contains(&claimed) => {
format!("Content: {path} as on {branch} (blob {})", ObjectId::blob(ciphertext).short())
}
Some(_) if !context.paths.is_empty() => {
sensitive = true;
format!("⚠ Content: the same as {} on {branch}, not {path}", context.paths.join(", "))
}
Some(ciphertext) => {
format!(
"Content: not on {branch}: new, or changed on a branch (blob {})",
ObjectId::blob(ciphertext).short()
)
}
});
match op {
SecretOp::Set { target, .. } => lines.push(describe_target(target)),
SecretOp::Generate { target, kind, .. } => {
lines.push(describe_target(target));
lines.push(format!("Generates: {}", kind.name()));
}
_ => {}
}
if let Some(requested) = op.recipients() {
let (recipients, added) = with_own(requested, own);
let rules = &config.rules;
let label = |r: &Recipient| label(r, &config.names);
match context.recipients.as_ref().map(|keys| expected(keys)) {
Some(expected) if same(&expected, &recipients) => {
lines.push(format!("Recipients: as in {rules} on {branch}: {}", join(&recipients, label)));
}
Some(expected) => {
sensitive = true;
lines.push(format!("⚠ Recipients differ from {rules} on {branch}:"));
for r in recipients.iter().filter(|r| !expected.contains(r)) {
lines.push(format!(" + {}", label(r)));
}
for r in expected.iter().filter(|r| !recipients.contains(r)) {
lines.push(format!(" − {}", label(r)));
}
let kept: Vec<&Recipient> = recipients.iter().filter(|r| expected.contains(r)).collect();
if !kept.is_empty() {
lines
.push(format!(" unchanged: {}", kept.iter().map(|r| label(r)).collect::<Vec<_>>().join(", ")));
}
}
None => {
sensitive = true;
lines.push(format!("⚠ Recipients ({path} isn't in {rules} on {branch}): {}", join(&recipients, label)));
}
}
if added {
lines.push(format!("The broker adds its own key ({}) so it can change the file later.", label(own)));
}
}
(lines.join("\n"), sensitive)
}
fn describe_target(target: &Target) -> String {
match target {
Target::Whole => "Replaces: the whole file".into(),
Target::Field(key) => format!("Field: {key}"),
}
}
/// A path the rules file names, from the repository's root, as the builder lists them.
fn repository_path(rules: &RulesPath, path: &SecretPath) -> String {
match rules.rsplit_once('/') {
Some((directory, _)) => format!("{directory}/{path}"),
None => path.to_string(),
}
}
/// The rules file's keys, in their plain form; any it can't read are left out.
fn expected(keys: &[String]) -> Vec<Recipient> {
keys.iter().filter_map(|k| Recipient::normalize(k).ok()).collect()
}
fn same(a: &[Recipient], b: &[Recipient]) -> bool {
a.iter().all(|r| b.contains(r)) && b.iter().all(|r| a.contains(r))
}
fn label(recipient: &Recipient, names: &BTreeMap<String, Recipient>) -> String {
names.iter().find(|(_, r)| *r == recipient).map_or_else(|| recipient.abbreviated(), |(name, _)| name.clone())
}
fn join(recipients: &[Recipient], label: impl Fn(&Recipient) -> String) -> String {
recipients.iter().map(label).collect::<Vec<_>>().join(", ")
}
/// The recipients with the broker's own key, and whether it had to be added.
fn with_own(recipients: &[Recipient], own: &Recipient) -> (Vec<Recipient>, bool) {
let mut all = recipients.to_vec();
all.dedup();
if all.contains(own) {
return (all, false);
}
all.push(own.clone());
(all, true)
}
pub async fn execute(broker: &Broker, parsed: &Parsed, io: &mut Io) -> Result<Outcome> {
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 identity = identity(config)?;
let own = Recipient::normalize(&identity.to_public().to_string()).map_err(anyhow::Error::msg)?;
let path = op.path();
match op {
SecretOp::Keys { file } => {
let text = text(decrypt(&identity, path, &file.ciphertext)?)?;
let keys = Format::require(path)?.keys(&text)?;
Ok(Outcome { exit: 0, result: Some(OpResult::SecretKeys(keys)) })
}
SecretOp::Read { file } => {
let plaintext = decrypt(&identity, path, &file.ciphertext)?;
io.out.send(ServerMessage::Stdout(plaintext)).await;
Ok(0.into())
}
SecretOp::Set { base, target, recipients, .. } => {
let value = read_stdin(io).await?;
let plaintext = apply(&identity, path, base.as_deref(), target, value)?;
let ciphertext = encrypt(&with_own(recipients, &own).0, &plaintext)?;
Ok(Outcome { exit: 0, result: Some(OpResult::Secret { ciphertext, public: None }) })
}
SecretOp::Generate { base, target, kind, recipients, .. } => {
let (mut value, public) = generate(*kind)?;
if matches!(target, Target::Whole) && !value.ends_with('\n') {
value.push('\n');
}
let plaintext = apply(&identity, path, base.as_deref(), target, value.into_bytes())?;
let ciphertext = encrypt(&with_own(recipients, &own).0, &plaintext)?;
Ok(Outcome { exit: 0, result: Some(OpResult::Secret { ciphertext, public }) })
}
SecretOp::Rekey { file, recipients } => {
let plaintext = decrypt(&identity, path, &file.ciphertext)?;
let ciphertext = encrypt(&with_own(recipients, &own).0, &plaintext)?;
Ok(Outcome { exit: 0, result: Some(OpResult::Secret { ciphertext, public: None }) })
}
}
}
/// The new plaintext: the value itself, or the current file with one field changed.
fn apply(
identity: &age::x25519::Identity,
path: &SecretPath,
base: Option<&[u8]>,
target: &Target,
value: Vec<u8>,
) -> Result<Vec<u8>> {
let Target::Field(key) = target else { return Ok(value) };
let format = Format::require(path)?;
let current = match base {
Some(ciphertext) => text(decrypt(identity, path, ciphertext)?)?,
None => String::new(),
};
// A value piped in usually ends with a newline that isn't part of it.
let value = text(value)?;
let value = value.strip_suffix('\n').map(|v| v.strip_suffix('\r').unwrap_or(v)).unwrap_or(&value);
Ok(format.set(&current, key, value)?.into_bytes())
}
fn text(data: Vec<u8>) -> Result<String> {
String::from_utf8(data).context("the secret isn't UTF-8 text")
}
async fn read_stdin(io: &mut Io) -> Result<Vec<u8>> {
let mut value = Vec::new();
while let Some(chunk) = io.stdin.recv().await {
value.extend_from_slice(&chunk);
ensure!(value.len() <= MAX_VALUE, "the value is larger than {MAX_VALUE} bytes");
}
Ok(value)
}
/// The broker's age identity, from the first `AGE-SECRET-KEY-` line of its file.
fn identity(config: &SecretsConfig) -> Result<age::x25519::Identity> {
let path = crate::config::credential(&config.identity);
let text = std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
let line =
text.lines().map(str::trim).find(|l| l.starts_with("AGE-SECRET-KEY-")).context("no age identity in it")?;
line.parse().map_err(|e: &str| anyhow::anyhow!("reading the age identity: {e}"))
}
fn own_recipient(config: &SecretsConfig) -> Result<Recipient> {
Recipient::normalize(&identity(config)?.to_public().to_string()).map_err(anyhow::Error::msg)
}
fn decrypt(identity: &age::x25519::Identity, path: &SecretPath, ciphertext: &[u8]) -> Result<Vec<u8>> {
let reader = age::armor::ArmoredReader::new(ciphertext);
let decryptor = age::Decryptor::new_buffered(reader).with_context(|| format!("reading {path}"))?;
let mut plaintext = Vec::new();
match decryptor.decrypt(std::iter::once(identity as &dyn age::Identity)) {
Ok(mut stream) => stream.read_to_end(&mut plaintext).with_context(|| format!("decrypting {path}"))?,
Err(age::DecryptError::NoMatchingKeys) => {
bail!("the broker isn't a recipient of {path}; re-encrypt it to include the broker's key first")
}
Err(error) => return Err(error).with_context(|| format!("decrypting {path}")),
};
Ok(plaintext)
}
/// Encrypts to every recipient, armored as agenix writes files.
fn encrypt(recipients: &[Recipient], plaintext: &[u8]) -> Result<Vec<u8>> {
let mut parsed: Vec<Box<dyn age::Recipient + Send>> = Vec::new();
for recipient in recipients {
if recipient.starts_with("age1") {
parsed.push(Box::new(recipient.parse::<age::x25519::Recipient>().map_err(anyhow::Error::msg)?));
} else {
let key: age::ssh::Recipient =
recipient.parse().map_err(|e| anyhow::anyhow!("reading recipient {recipient}: {e:?}"))?;
parsed.push(Box::new(key));
}
}
let encryptor = age::Encryptor::with_recipients(parsed.iter().map(|r| r.as_ref() as &dyn age::Recipient))?;
let mut ciphertext = Vec::new();
let armor = age::armor::ArmoredWriter::wrap_output(&mut ciphertext, age::armor::Format::AsciiArmor)?;
let mut writer = encryptor.wrap_output(armor)?;
writer.write_all(plaintext)?;
writer.finish()?.finish()?;
Ok(ciphertext)
}
/// A new value, and the public half of keypairs.
fn generate(kind: GenKind) -> Result<(String, Option<String>)> {
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use rand::Rng;
Ok(match kind {
GenKind::Password => {
(rand::rng().sample_iter(rand::distr::Alphanumeric).take(32).map(char::from).collect(), None)
}
GenKind::Hex => (hex::encode(rand::random::<[u8; 32]>()), None),
GenKind::Base64 => (STANDARD.encode(rand::random::<[u8; 32]>()), None),
GenKind::Wireguard => {
// Clamped as `wg genkey` does
let mut key = rand::random::<[u8; 32]>();
key[0] &= 248;
key[31] = (key[31] & 127) | 64;
let public = x25519_dalek::PublicKey::from(&x25519_dalek::StaticSecret::from(key));
(STANDARD.encode(key), Some(STANDARD.encode(public.as_bytes())))
}
GenKind::SshEd25519 => {
let keypair = ssh_key::private::Ed25519Keypair::from_seed(&rand::random::<[u8; 32]>());
let key = ssh_key::PrivateKey::from(keypair);
let private = key.to_openssh(ssh_key::LineEnding::LF)?;
(private.to_string(), Some(key.public_key().to_openssh()?))
}
GenKind::Age => {
use age::secrecy::ExposeSecret;
let identity = age::x25519::Identity::generate();
(identity.to_string().expose_secret().to_owned(), Some(identity.to_public().to_string()))
}
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::proto::SecretFile;
fn recipient(identity: &age::x25519::Identity) -> Recipient {
identity.to_public().to_string().parse().unwrap()
}
fn config(dev: &Recipient) -> SecretsConfig {
SecretsConfig {
identity: "unused".into(),
rules: "secrets.nix".parse().unwrap(),
names: BTreeMap::from([("dev".to_owned(), dev.clone())]),
}
}
fn context(paths: &[&str], recipients: Option<Vec<String>>) -> SecretContext {
SecretContext {
branch: "master".into(),
commit: "0123456789abcdef0123456789abcdef01234567".parse().unwrap(),
paths: paths.iter().map(|p| p.to_string()).collect(),
recipients,
}
}
#[test]
fn round_trips_and_needs_the_broker_as_a_recipient() {
let (broker, other) = (age::x25519::Identity::generate(), age::x25519::Identity::generate());
let path: SecretPath = "secrets/a.env.age".parse().unwrap();
let ciphertext = encrypt(&[recipient(&broker)], b"A=1\n").unwrap();
assert!(ciphertext.starts_with(b"-----BEGIN AGE ENCRYPTED FILE-----"));
assert_eq!(decrypt(&broker, &path, &ciphertext).unwrap(), b"A=1\n");
let foreign = encrypt(&[recipient(&other)], b"x").unwrap();
let error = decrypt(&broker, &path, &foreign).unwrap_err().to_string();
assert!(error.contains("isn't a recipient"), "{error}");
}
#[test]
fn sets_fields_in_the_current_file() {
let broker = age::x25519::Identity::generate();
let path: SecretPath = "secrets/a.env.age".parse().unwrap();
let base = encrypt(&[recipient(&broker)], b"A=1\nB=2\n").unwrap();
let field = Target::Field("B".parse().unwrap());
assert_eq!(apply(&broker, &path, Some(&base), &field, b"3\n".to_vec()).unwrap(), b"A=1\nB=3\n");
assert_eq!(apply(&broker, &path, None, &field, b"3".to_vec()).unwrap(), b"B=3\n");
assert_eq!(apply(&broker, &path, Some(&base), &Target::Whole, b"raw".to_vec()).unwrap(), b"raw");
let whole_only: SecretPath = "secrets/wg.key.age".parse().unwrap();
assert!(apply(&broker, &whole_only, None, &field, b"x".to_vec()).is_err());
}
#[test]
fn generates_every_kind() {
use base64::Engine;
let decode = |s: &str| base64::engine::general_purpose::STANDARD.decode(s).unwrap();
let (password, public) = generate(GenKind::Password).unwrap();
assert!(password.len() == 32 && password.bytes().all(|c| c.is_ascii_alphanumeric()) && public.is_none());
assert_eq!(generate(GenKind::Hex).unwrap().0.len(), 64);
assert_eq!(decode(&generate(GenKind::Base64).unwrap().0).len(), 32);
let (private, public) = generate(GenKind::Wireguard).unwrap();
let key: [u8; 32] = decode(&private).try_into().unwrap();
let derived = x25519_dalek::PublicKey::from(&x25519_dalek::StaticSecret::from(key));
assert_eq!(decode(&public.unwrap()), derived.as_bytes());
let (private, public) = generate(GenKind::SshEd25519).unwrap();
assert!(private.starts_with("-----BEGIN OPENSSH PRIVATE KEY-----"));
assert!(Recipient::normalize(&public.unwrap()).is_ok());
let (private, public) = generate(GenKind::Age).unwrap();
let identity: age::x25519::Identity = private.parse().unwrap();
assert_eq!(identity.to_public().to_string(), public.unwrap());
}
#[test]
fn approvals_say_what_the_content_is() {
let (broker, dev) = (age::x25519::Identity::generate(), age::x25519::Identity::generate());
let (own, dev) = (recipient(&broker), recipient(&dev));
let config = config(&dev);
let file =
SecretFile { path: "secrets/test.age".parse().unwrap(), ciphertext: b"age-encryption.org/v1".to_vec() };
let read = SecretOp::Read { file };
let (detail, sensitive) = describe(&read, &context(&["secrets/test.age"], None), &config, &own);
assert!(detail.contains("Content: secrets/test.age as on master") && !sensitive, "{detail}");
let (detail, sensitive) = describe(&read, &context(&["secrets/colony/borg.age"], None), &config, &own);
assert!(detail.contains("the same as secrets/colony/borg.age on master, not secrets/test.age") && sensitive);
let (detail, _) = describe(&read, &context(&[], None), &config, &own);
assert!(detail.contains("not on master"), "{detail}");
}
#[test]
fn approvals_compare_recipients_with_the_rules() {
let (broker, dev, host) =
(age::x25519::Identity::generate(), age::x25519::Identity::generate(), age::x25519::Identity::generate());
let (own, dev, host) = (recipient(&broker), recipient(&dev), recipient(&host));
let config = config(&dev);
let set = |recipients: Vec<Recipient>| SecretOp::Set {
path: "secrets/a.age".parse().unwrap(),
base: None,
target: Target::Whole,
recipients,
};
let rules = Some(vec![dev.to_string(), own.to_string()]);
let (detail, sensitive) = describe(&set(vec![dev.clone()]), &context(&[], rules.clone()), &config, &own);
assert!(detail.contains("Content: a new file") && detail.contains("Recipients: as in secrets.nix"), "{detail}");
assert!(detail.contains("The broker adds its own key") && !sensitive, "{detail}");
let (detail, sensitive) = describe(&set(vec![host.clone(), own.clone()]), &context(&[], rules), &config, &own);
assert!(sensitive && detail.contains(&format!(" + {}", host.abbreviated())) && detail.contains(" − dev"));
let (detail, sensitive) = describe(&set(vec![dev.clone()]), &context(&[], None), &config, &own);
assert!(sensitive && detail.contains("isn't in secrets.nix"), "{detail}");
}
#[test]
fn rules_paths_are_relative_to_the_rules_file() {
let path: SecretPath = "secrets/a.age".parse().unwrap();
assert_eq!(repository_path(&"secrets.nix".parse().unwrap(), &path), "secrets/a.age");
assert_eq!(repository_path(&"infra/secrets.nix".parse().unwrap(), &path), "infra/secrets/a.age");
}
}
+170
View File
@@ -0,0 +1,170 @@
//! Fields of env and JSON secrets: listing their keys and replacing one value, leaving the rest
//! of the file as it was where the format allows.
use anyhow::{Result, bail};
use crate::types::{SecretKey, SecretPath};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
/// `KEY=value` lines, as systemd's `EnvironmentFile=` and most `.env` readers take them.
Env,
/// An object of strings.
Json,
}
impl Format {
/// The format named by the extension before `.age`, if it has fields.
pub fn of(path: &SecretPath) -> Option<Format> {
let name = path.strip_suffix(".age")?;
if name.ends_with(".env") {
Some(Format::Env)
} else if name.ends_with(".json") {
Some(Format::Json)
} else {
None
}
}
/// The format, or an error saying only whole-file changes work.
pub fn require(path: &SecretPath) -> Result<Format> {
match Format::of(path) {
Some(format) => Ok(format),
None => bail!("{path} isn't an env (.env.age) or JSON (.json.age) secret; use the whole file"),
}
}
pub fn keys(self, text: &str) -> Result<Vec<String>> {
match self {
Format::Env => Ok(env_lines(text).filter_map(|line| line.key.map(str::to_owned)).collect()),
Format::Json => Ok(json_object(text)?.keys().cloned().collect()),
}
}
/// `text` with `key` set to `value`, added if it isn't there yet.
pub fn set(self, text: &str, key: &SecretKey, value: &str) -> Result<String> {
match self {
Format::Env => set_env(text, key, value),
Format::Json => {
let mut object = if text.trim().is_empty() { Default::default() } else { json_object(text)? };
object.insert(key.to_string(), serde_json::Value::String(value.to_owned()));
Ok(serde_json::to_string_pretty(&object)? + "\n")
}
}
}
}
struct EnvLine<'a> {
text: &'a str,
key: Option<&'a str>,
}
/// Each line, with the key it assigns if it's an assignment.
fn env_lines(text: &str) -> impl Iterator<Item = EnvLine<'_>> {
text.lines().map(|line| {
let trimmed = line.trim_start();
let assignment = trimmed.strip_prefix("export ").unwrap_or(trimmed);
let key = match assignment.split_once('=') {
Some((key, _)) if !trimmed.starts_with('#') && key.parse::<SecretKey>().is_ok() => Some(key.trim()),
_ => None,
};
EnvLine { text: line, key }
})
}
fn set_env(text: &str, key: &SecretKey, value: &str) -> Result<String> {
let assignment = format!("{key}={}", env_value(value)?);
let mut replaced = false;
let mut lines = Vec::new();
for line in env_lines(text) {
if line.key == Some(&**key) {
if !replaced {
lines.push(assignment.clone());
}
replaced = true;
} else {
lines.push(line.text.to_owned());
}
}
if !replaced {
lines.push(assignment);
}
Ok(lines.join("\n") + "\n")
}
/// A value as an env file writes it: bare if it's plain, otherwise double-quoted.
fn env_value(value: &str) -> Result<String> {
if value.contains(['\n', '\r', '\0']) {
bail!("env values can't span lines; set the whole file instead");
}
if !value.is_empty() && value.bytes().all(|c| c.is_ascii_alphanumeric() || b"_./:@+=,%-".contains(&c)) {
return Ok(value.to_owned());
}
let mut quoted = String::from("\"");
for c in value.chars() {
if matches!(c, '"' | '\\' | '$' | '`') {
quoted.push('\\');
}
quoted.push(c);
}
quoted.push('"');
Ok(quoted)
}
fn json_object(text: &str) -> Result<serde_json::Map<String, serde_json::Value>> {
match serde_json::from_str(text) {
Ok(serde_json::Value::Object(object)) => Ok(object),
Ok(_) => bail!("the secret isn't a JSON object"),
Err(error) => bail!("the secret isn't valid JSON: {error}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn key(k: &str) -> SecretKey {
k.parse().unwrap()
}
#[test]
fn detects_formats() {
assert_eq!(Format::of(&"secrets/a.env.age".parse().unwrap()), Some(Format::Env));
assert_eq!(Format::of(&"b.json.age".parse().unwrap()), Some(Format::Json));
assert_eq!(Format::of(&"secrets/c.yaml.age".parse().unwrap()), None);
assert!(Format::require(&"wg.key.age".parse().unwrap()).is_err());
}
#[test]
fn env_edits_keep_other_lines() {
let text = "# database\nexport HOST=db\nPASSWORD=old\n\nOTHER=\"a b\"\n";
assert_eq!(Format::Env.keys(text).unwrap(), ["HOST", "PASSWORD", "OTHER"]);
let set = Format::Env.set(text, &key("PASSWORD"), "new").unwrap();
assert_eq!(set, "# database\nexport HOST=db\nPASSWORD=new\n\nOTHER=\"a b\"\n");
let added = Format::Env.set(text, &key("TOKEN"), "a b$c\"").unwrap();
assert!(added.ends_with("OTHER=\"a b\"\nTOKEN=\"a b\\$c\\\"\"\n"));
assert_eq!(Format::Env.set("", &key("A"), "1").unwrap(), "A=1\n");
assert!(Format::Env.set(text, &key("A"), "two\nlines").is_err());
}
#[test]
fn env_duplicates_collapse_into_one() {
assert_eq!(Format::Env.set("A=1\nB=2\nA=3\n", &key("A"), "x").unwrap(), "A=x\nB=2\n");
}
#[test]
fn json_edits_set_string_fields() {
let text = "{\"user\": \"u\", \"port\": 5432}";
assert_eq!(Format::Json.keys(text).unwrap(), ["port", "user"]);
let set: serde_json::Value =
serde_json::from_str(&Format::Json.set(text, &key("password"), "p").unwrap()).unwrap();
assert_eq!(set, serde_json::json!({ "user": "u", "port": 5432, "password": "p" }));
assert_eq!(Format::Json.set("", &key("a"), "b").unwrap(), "{\n \"a\": \"b\"\n}\n");
assert!(Format::Json.keys("[1]").is_err());
}
}
+134 -2
View File
@@ -15,7 +15,10 @@ use tokio_util::codec::{Framed, LengthDelimitedCodec};
use crate::audit::Record;
use crate::queue::{Decision, PendingInfo};
use crate::types::{Arg, CommitId, DeployTarget, FlakeAttr, HostName, Lines, NodeName, Since, UnitName, UserName};
use crate::types::{
Arg, CommitId, DeployTarget, FlakeAttr, HostName, Lines, NodeName, Recipient, SecretKey, SecretPath, Since,
UnitName, UserName,
};
/// Bumped on any incompatible change; the broker refuses other versions.
pub const PROTOCOL_VERSION: u32 = 1;
@@ -60,6 +63,124 @@ pub enum Operation {
/// Builds flake attributes of a pushed commit and, once approved, pushes them to the binary
/// cache.
Build { attrs: Vec<FlakeAttr>, commit: CommitId },
/// Works with an age secret the requester sends; the broker returns new ciphertext and never
/// writes to a checkout.
Secret(SecretOp),
}
/// What to do with a secret. Each action carries only what it uses; the path is the requester's
/// name for the file, which the broker checks against the main branch.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum SecretOp {
/// Key names of an env or JSON secret.
Keys { file: SecretFile },
/// The plaintext, on stdout.
Read { file: SecretFile },
/// A value from stdin. `base` is the current file; a new file has none.
Set {
path: SecretPath,
#[serde(with = "serde_bytes")]
base: Option<Vec<u8>>,
target: Target,
recipients: Vec<Recipient>,
},
/// A value the broker makes; keypair kinds return the public half.
Generate {
path: SecretPath,
#[serde(with = "serde_bytes")]
base: Option<Vec<u8>>,
target: Target,
kind: GenKind,
recipients: Vec<Recipient>,
},
/// The same plaintext, encrypted to these recipients.
Rekey { file: SecretFile, recipients: Vec<Recipient> },
}
impl SecretOp {
pub fn path(&self) -> &SecretPath {
match self {
Self::Keys { file } | Self::Read { file } | Self::Rekey { file, .. } => &file.path,
Self::Set { path, .. } | Self::Generate { path, .. } => path,
}
}
/// The current file, if there is one.
pub fn ciphertext(&self) -> Option<&[u8]> {
match self {
Self::Keys { file } | Self::Read { file } | Self::Rekey { file, .. } => Some(&file.ciphertext),
Self::Set { base, .. } | Self::Generate { base, .. } => base.as_deref(),
}
}
/// Who the new file is encrypted to, for actions that write one.
pub fn recipients(&self) -> Option<&[Recipient]> {
match self {
Self::Keys { .. } | Self::Read { .. } => None,
Self::Set { recipients, .. } | Self::Generate { recipients, .. } | Self::Rekey { recipients, .. } => {
Some(recipients)
}
}
}
pub fn action(&self) -> &'static str {
match self {
Self::Keys { .. } => "keys",
Self::Read { .. } => "read",
Self::Set { .. } => "set",
Self::Generate { .. } => "generate",
Self::Rekey { .. } => "rekey",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SecretFile {
pub path: SecretPath,
#[serde(with = "serde_bytes")]
pub ciphertext: Vec<u8>,
}
/// Which part of a secret a value replaces.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum Target {
Whole,
/// A key of an env or JSON file.
Field(SecretKey),
}
/// Values the broker can generate.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum GenKind {
/// 32 letters and digits.
Password,
/// 32 random bytes in hex.
Hex,
/// 32 random bytes in base64.
Base64,
/// A WireGuard private key; returns the public key.
Wireguard,
/// An OpenSSH private key; returns the public key.
SshEd25519,
/// An age identity; returns its recipient.
Age,
}
impl GenKind {
pub fn name(self) -> &'static str {
match self {
Self::Password => "password",
Self::Hex => "hex",
Self::Base64 => "base64",
Self::Wireguard => "wireguard",
Self::SshEd25519 => "ssh-ed25519",
Self::Age => "age",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -134,7 +255,18 @@ pub enum ApprovedBy {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub enum OpResult {
Requests { pending: Vec<PendingSummary>, leases: Vec<LeaseSummary> },
Requests {
pending: Vec<PendingSummary>,
leases: Vec<LeaseSummary>,
},
/// The keys of an env or JSON secret.
SecretKeys(Vec<String>),
/// A secret's new ciphertext, and the public half of a generated keypair.
Secret {
#[serde(with = "serde_bytes")]
ciphertext: Vec<u8>,
public: Option<String>,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+30 -28
View File
@@ -197,9 +197,9 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
// Operations that build run agent-written Nix in the builder, which needs its own approval;
// approvers first see the commits and their diff, which only takes Git. Then they build, so
// the request's own approval can show what it changes. None of it happens if policy would
// refuse anyway.
if ops::builds(&parsed) {
// the request's own approval can show what it changes. Others look things up the same way
// without building. None of it happens if policy would refuse anyway.
if ops::builds(&parsed) || ops::prepares(&parsed) {
let refused = match verdict(broker, requester, &parsed) {
Ok(verdict) if verdict.action == Action::Deny => Some(denied("denied by policy")),
Ok(_) => None,
@@ -226,32 +226,34 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
Some(ServerMessage::Error(error))
};
let description = match ops::describe(broker, &parsed, io).await {
Ok(description) => description,
Err(error) => return failed(error),
};
let gate = match ops::builder_gate(&parsed, &description) {
Ok(gate) => gate,
Err(error) => return failed(error),
};
log(Event::Prepared { id: id.clone(), detail: gate.detail.clone() });
if ops::builds(&parsed) {
let description = match ops::describe(broker, &parsed, io).await {
Ok(description) => description,
Err(error) => return failed(error),
};
let gate = match ops::builder_gate(&parsed, &description) {
Ok(gate) => gate,
Err(error) => return failed(error),
};
log(Event::Prepared { id: id.clone(), detail: gate.detail.clone() });
let (by, approver) = match authorize(broker, &id, requester, &gate, label.clone(), io).await {
Ok(Some(approval)) => approval,
Ok(None) => {
log(Event::Disconnected { id });
return None;
}
Err(message) => {
log(refusal(&id, &message));
return Some(message);
}
};
log(Event::Approved { id: id.clone(), by, approver: approver.clone(), step: Some("builder".into()) });
io.out
.info(format!("use of the builder approved by {}", approver.as_deref().unwrap_or(approved_by_name(by))))
.await;
parsed.description = Some(description);
let (by, approver) = match authorize(broker, &id, requester, &gate, label.clone(), io).await {
Ok(Some(approval)) => approval,
Ok(None) => {
log(Event::Disconnected { id });
return None;
}
Err(message) => {
log(refusal(&id, &message));
return Some(message);
}
};
log(Event::Approved { id: id.clone(), by, approver: approver.clone(), step: Some("builder".into()) });
io.out
.info(format!("use of the builder approved by {}", approver.as_deref().unwrap_or(approved_by_name(by))))
.await;
parsed.description = Some(description);
}
if let Err(error) = ops::prepare(broker, &mut parsed, io).await {
return failed(error);
+130
View File
@@ -121,6 +121,28 @@ impl CommitId {
}
}
validated_string!(
/// A Git object ID, SHA-1 or SHA-256, in lowercase hex.
ObjectId,
"object ID",
|s| matches!(s.len(), 40 | 64) && s.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c))
);
impl ObjectId {
/// The ID Git gives `data` as a blob, in a SHA-1 repository.
pub fn blob(data: &[u8]) -> ObjectId {
use sha1::Digest;
let mut hasher = sha1::Sha1::new();
hasher.update(format!("blob {}\0", data.len()));
hasher.update(data);
ObjectId(hex::encode(hasher.finalize()))
}
pub fn short(&self) -> &str {
&self.0[..12]
}
}
validated_string!(
/// What to deploy: a node (all its profiles, as `deploy .#node` does) or `node.profile`.
DeployTarget,
@@ -174,6 +196,83 @@ validated_string!(
|s| !s.contains('\0')
);
/// A relative path within a repository: plain components, none of them `.` or `..`.
fn is_repository_path(s: &str) -> bool {
s.len() <= 512
&& s.split('/').all(|part| {
let b = part.as_bytes();
!b.is_empty()
&& part != "."
&& part != ".."
&& b[0] != b'-'
&& b.iter().all(|&c| c.is_ascii_alphanumeric() || b"_.+@=,-".contains(&c))
})
}
validated_string!(
/// An age file, relative to the rules file's directory, such as `secrets/web/db.env.age`.
SecretPath,
"secret path (use a relative path ending in .age)",
|s| is_repository_path(s) && s.len() > 4 && s.ends_with(".age")
);
validated_string!(
/// A Nix file in a repository, such as the agenix rules file.
RulesPath,
"rules file path (use a relative path ending in .nix)",
|s| is_repository_path(s) && s.ends_with(".nix")
);
validated_string!(
/// A field of an env or JSON secret: a variable name, or a JSON key of the same characters.
SecretKey,
"secret key (letters, digits, _, . and -, not starting with a digit)",
|s| {
let b = s.as_bytes();
!b.is_empty()
&& b.len() <= 128
&& (b[0].is_ascii_alphabetic() || b[0] == b'_')
&& b.iter().all(|&c| c.is_ascii_alphanumeric() || b"_.-".contains(&c))
}
);
validated_string!(
/// An age recipient in its plain form: `age1…`, or an SSH key's type and key without a
/// comment.
Recipient,
"recipient (use age1… or an ssh-ed25519/ssh-rsa key without a comment)",
|s| {
if s.starts_with("age1") {
return s.parse::<age::x25519::Recipient>().is_ok();
}
let mut words = s.split(' ');
matches!(words.next(), Some("ssh-ed25519" | "ssh-rsa"))
&& words.next().is_some()
&& words.next().is_none()
&& s.parse::<age::ssh::Recipient>().is_ok()
}
);
impl Recipient {
/// The plain form of a recipient as people write it, dropping an SSH key's comment.
pub fn normalize(text: &str) -> Result<Recipient, String> {
let words: Vec<&str> = text.split_whitespace().collect();
match words.as_slice() {
[key] => key.parse(),
[kind, key, ..] if kind.starts_with("ssh-") => format!("{kind} {key}").parse(),
_ => Err(format!("invalid recipient: {text:?}")),
}
}
/// A short form for approvals: an age key's start, an SSH key's end.
pub fn abbreviated(&self) -> String {
match self.0.split_once(' ') {
Some((kind, key)) => format!("{kind} …{}", &key[key.len().saturating_sub(8)..]),
None => format!("{}…", &self.0[..self.0.len().min(16)]),
}
}
}
validated_string!(
/// A journal start: a duration back from now (`30m`, `2h`, `1d`) or a date
/// (`YYYY-MM-DD[ HH:MM[:SS]]`).
@@ -258,6 +357,37 @@ mod tests {
}
}
#[test]
fn secret_paths_keys_and_recipients() {
for good in ["secrets/web/db.env.age", "a.age", "secrets/x@y+z.age"] {
assert!(good.parse::<SecretPath>().is_ok(), "{good}");
}
for bad in [".age", "a.txt", "/etc/a.age", "../a.age", "a/../b.age", "a//b.age", "-a.age", "a b.age", "./a.age"]
{
assert!(bad.parse::<SecretPath>().is_err(), "{bad}");
}
assert!("infra/secrets.nix".parse::<RulesPath>().is_ok());
assert!("../secrets.nix".parse::<RulesPath>().is_err());
for good in ["DB_PASSWORD", "_x", "api.key", "a-b"] {
assert!(good.parse::<SecretKey>().is_ok(), "{good}");
}
for bad in ["", "1A", "a b", "a=b", "$A"] {
assert!(bad.parse::<SecretKey>().is_err(), "{bad}");
}
let age = age::x25519::Identity::generate().to_public().to_string();
assert!(age.parse::<Recipient>().is_ok());
let ssh = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIHzVJpoDz/AAYLJGzU8t6DgZ2sY3oehRqrlSO7C+GWiK";
assert!(ssh.parse::<Recipient>().is_ok());
assert!(format!("{ssh} root@palace").parse::<Recipient>().is_err());
assert_eq!(Recipient::normalize(&format!("{ssh} root@palace")).unwrap().to_string(), ssh);
assert_eq!(Recipient::normalize(ssh).unwrap().abbreviated(), "ssh-ed25519 …O7C+GWiK");
for bad in ["age1nope", "ssh-dss AAAA", "", "ssh-ed25519"] {
assert!(Recipient::normalize(bad).is_err(), "{bad}");
}
}
#[test]
fn names() {
assert!("river".parse::<NodeName>().is_ok());
+179 -2
View File
@@ -13,8 +13,8 @@ use tokio::io::DuplexStream;
use slop_broker::config::Config;
use slop_broker::proto::{ApproveRequest, ApproveResponse, receive, send};
use slop_broker::proto::{
ApprovedBy, ClientMessage, Destination, OpResult, Operation, PROTOCOL_VERSION, Query, Request, ServerMessage,
Transport, decode, encode, transport,
ApprovedBy, ClientMessage, Destination, OpResult, Operation, PROTOCOL_VERSION, Query, Request, SecretFile,
SecretOp, ServerMessage, Target, Transport, decode, encode, transport,
};
use slop_broker::queue::Decision;
use slop_broker::remote::{Hello, Role, write_hello};
@@ -381,3 +381,180 @@ async fn remote_requesters_and_approvers_use_one_socket() {
assert!(receive::<_, ApproveResponse>(&mut stream).await.map_or(true, |r| r.is_none()));
}
}
/// The directory holding `program`, if it's installed.
fn program_directory(program: &str) -> Option<std::path::PathBuf> {
let output = std::process::Command::new("sh").args(["-c", &format!("command -v {program}")]).output().ok()?;
let path = std::path::PathBuf::from(String::from_utf8(output.stdout).ok()?.trim());
output.status.success().then(|| path.parent().map(Path::to_owned)).flatten()
}
fn run_git(directory: &Path, args: &[&str]) {
let status = std::process::Command::new("git")
.arg("-C")
.arg(directory)
.args(["-c", "user.name=dev", "-c", "user.email=dev@example", "-c", "commit.gpgsign=false"])
.args(args)
.status()
.unwrap();
assert!(status.success(), "git {args:?}");
}
fn encrypt(recipients: &[&age::x25519::Identity], plaintext: &[u8]) -> Vec<u8> {
use std::io::Write;
let public: Vec<age::x25519::Recipient> = recipients.iter().map(|i| i.to_public()).collect();
let encryptor = age::Encryptor::with_recipients(public.iter().map(|r| r as &dyn age::Recipient)).unwrap();
let mut ciphertext = Vec::new();
let armor = age::armor::ArmoredWriter::wrap_output(&mut ciphertext, age::armor::Format::AsciiArmor).unwrap();
let mut writer = encryptor.wrap_output(armor).unwrap();
writer.write_all(plaintext).unwrap();
writer.finish().unwrap().finish().unwrap();
ciphertext
}
/// A broker with secrets, whose builder is `slop-broker builder` (reached through a fake `ssh`)
/// on a local repository. Its main branch has `secrets/a.env.age` (`A=1`), encrypted to `dev` and
/// the broker, and rules naming both.
struct Secrets {
broker: Arc<Broker>,
dev: age::x25519::Identity,
file: Vec<u8>,
}
fn secrets_broker(directory: &Path) -> Option<Secrets> {
let (git, nix) = (program_directory("git")?, program_directory("nix")?);
let (own, dev) = (age::x25519::Identity::generate(), age::x25519::Identity::generate());
let work = directory.join("work");
std::fs::create_dir_all(work.join("secrets")).unwrap();
run_git(&work, &["init", "--quiet", "--initial-branch=master"]);
let file = encrypt(&[&dev, &own], b"A=1\n");
std::fs::write(work.join("secrets/a.env.age"), &file).unwrap();
let rules =
format!("{{ \"secrets/a.env.age\".publicKeys = [ \"{}\" \"{}\" ]; }}\n", dev.to_public(), own.to_public());
std::fs::write(work.join("secrets.nix"), rules).unwrap();
run_git(&work, &["add", "."]);
run_git(&work, &["commit", "--quiet", "-m", "Secrets"]);
let state = directory.join("state");
std::fs::create_dir(&state).unwrap();
let builder = directory.join("builder.toml");
let builder_config = format!(
"repository = {:?}\nkey = \"/nonexistent\"\ndirectory = {:?}\npath = [{:?}, {:?}]\n",
work.display().to_string(),
state.display().to_string(),
git.display().to_string(),
nix.display().to_string(),
);
std::fs::write(&builder, builder_config).unwrap();
let ssh = directory.join("ssh");
let script = format!("#!/bin/sh\nexec {:?} builder --config {:?}\n", env!("CARGO_BIN_EXE_slop-broker"), builder);
std::fs::write(&ssh, script).unwrap();
std::fs::set_permissions(&ssh, std::fs::Permissions::from_mode(0o755)).unwrap();
use age::secrecy::ExposeSecret;
let identity = directory.join("identity");
std::fs::write(&identity, format!("# the broker\n{}\n", own.to_string().expose_secret())).unwrap();
let config: Config = serde_json::from_value(json!({
"requesters": { "agent": { "remote": true, "policy": "agent" } },
"policies": { "agent": { "ops": { "secret": {
"action": "ask",
"leases": [300],
"rules": [{ "match": { "action": "keys" }, "action": "auto" }],
} } } },
"timeout": 5,
"approve_socket": "/unused",
"approver_group": "root",
"audit_log": directory.join("audit.jsonl"),
"remote": { "socket": "/unused", "user": "root", "approvers": [] },
"ssh": { "ssh": ssh, "key": "/key", "known_hosts": "/kh", "targets": {} },
"deploy": {
"builder": { "hostname": "builder.example.org", "user": "builder", "ssh_opts": [] },
"nix": "/unused",
"cache": directory.join("cache"),
},
"secrets": { "identity": identity, "names": { "dev": dev.to_public().to_string() } },
}))
.unwrap();
Some(Secrets { broker: Arc::new(Broker::new(config).unwrap()), dev, file })
}
impl Client {
/// The next message other than output and progress.
async fn next_quiet(&mut self, output: &mut String) -> ServerMessage {
loop {
match self.next(output).await {
ServerMessage::Info(_) => {}
message => return message,
}
}
}
}
fn secret_file(path: &str, ciphertext: &[u8]) -> SecretFile {
SecretFile { path: path.parse().unwrap(), ciphertext: ciphertext.to_vec() }
}
#[tokio::test]
async fn secrets_are_checked_against_the_branch_and_read_always_asks() {
let directory = tempfile::tempdir().unwrap();
let Some(Secrets { broker, dev, file }) = secrets_broker(directory.path()) else {
eprintln!("skipped: git or nix isn't installed");
return;
};
let mut output = String::new();
// Listing keys is allowed by policy.
let keys = Operation::Secret(SecretOp::Keys { file: secret_file("secrets/a.env.age", &file) });
let mut client = Client::start(&broker, keys).await;
assert_eq!(client.next_quiet(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Policy, stdin: false });
let keys = ServerMessage::Finished { exit: 0, result: Some(OpResult::SecretKeys(vec!["A".into()])) };
assert_eq!(client.next_quiet(&mut output).await, keys);
// Setting a field shows what the file is and whom it's for, then takes the value on stdin.
let set = Operation::Secret(SecretOp::Set {
path: "secrets/a.env.age".parse().unwrap(),
base: Some(file.clone()),
target: Target::Field("B".parse().unwrap()),
recipients: vec![dev.to_public().to_string().parse().unwrap()],
});
let mut client = Client::start(&broker, set).await;
let ServerMessage::Pending { id, .. } = client.next_quiet(&mut output).await else { panic!("expected pending") };
let pending = broker.queue.list();
let detail = &pending[0].detail;
assert!(detail.contains("Content: secrets/a.env.age as on master"), "{detail}");
assert!(detail.contains("Recipients: as in secrets.nix on master"), "{detail}");
assert!(detail.contains("The broker adds its own key") && !pending[0].sensitive, "{detail}");
slop_broker::approve::approve(&broker, &id, Decision::Once, "test", false).unwrap();
assert_eq!(client.next_quiet(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Approver, stdin: true });
client.send(ClientMessage::Stdin(b"2\n".to_vec())).await;
client.send(ClientMessage::StdinEnd).await;
let ServerMessage::Finished { exit: 0, result: Some(OpResult::Secret { ciphertext, public: None }) } =
client.next_quiet(&mut output).await
else {
panic!("expected a secret")
};
assert_eq!(age::decrypt(&dev, &ciphertext).unwrap(), b"A=1\nB=2\n");
// Reading never offers a lease, and a copy of a file under another name is called out.
let read = Operation::Secret(SecretOp::Read { file: secret_file("secrets/harmless.age", &file) });
let mut client = Client::start(&broker, read).await;
let ServerMessage::Pending { id, .. } = client.next_quiet(&mut output).await else { panic!("expected pending") };
let pending = broker.queue.list();
assert_eq!(pending[0].offers, [Decision::Once, Decision::Deny]);
assert!(pending[0].sensitive);
assert!(pending[0].detail.contains("the same as secrets/a.env.age on master, not secrets/harmless.age"));
slop_broker::approve::approve(&broker, &id, Decision::Once, "test", false).unwrap();
assert_eq!(
client.next_quiet(&mut output).await,
ServerMessage::Approved { by: ApprovedBy::Approver, stdin: false }
);
assert_eq!(client.next_quiet(&mut output).await, finished(0));
// After the builder's progress on stderr
assert!(output.ends_with("\nA=1\n"), "{output}");
}
+79 -7
View File
@@ -1,14 +1,20 @@
//! The builder's describe stage against a local Git repository. Skipped where `git` isn't
//! installed, such as the package build's sandbox.
//! 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.
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use slop_broker::builder::{BuilderRequest, Description, MAX_DIFF};
use serde::de::DeserializeOwned;
use slop_broker::builder::{BuilderRequest, Description, MAX_DIFF, SecretContext, SecretRequest};
use slop_broker::proto::{decode, encode};
use slop_broker::types::ObjectId;
fn git_directory() -> Option<PathBuf> {
let output = Command::new("sh").args(["-c", "command -v git"]).output().ok()?;
program_directory("git")
}
fn program_directory(program: &str) -> Option<PathBuf> {
let output = Command::new("sh").args(["-c", &format!("command -v {program}")]).output().ok()?;
if !output.status.success() {
return None;
}
@@ -29,7 +35,7 @@ fn git(directory: &Path, args: &[&str]) -> String {
}
/// Sends one request to `slop-broker builder` and reads its one-frame answer.
fn ask(config: &Path, request: &BuilderRequest) -> Description {
fn ask<T: DeserializeOwned>(config: &Path, request: &BuilderRequest) -> T {
let mut child = Command::new(env!("CARGO_BIN_EXE_slop-broker"))
.args(["builder", "--config"])
.arg(config)
@@ -91,13 +97,79 @@ fn describes_commits_with_git_alone() {
)
.unwrap();
let described = ask(&config, &BuilderRequest::Describe(agent.parse().unwrap()));
let described: Description = ask(&config, &BuilderRequest::Describe(agent.parse().unwrap()));
assert!(!described.on_branch);
assert!(described.log.contains("Add \x1b[2Ksomething"), "{}", described.log);
assert!(described.stat.contains("flake.nix"), "{}", described.stat);
assert!(described.diff.contains("builtins.trace") && described.diff.ends_with("(diff cut short)\n"));
assert!(described.diff.len() < MAX_DIFF + 100);
let described = ask(&config, &BuilderRequest::Describe(reviewed.parse().unwrap()));
let described: Description = ask(&config, &BuilderRequest::Describe(reviewed.parse().unwrap()));
assert!(described.on_branch && described.diff.is_empty());
}
#[test]
fn secrets_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;
};
// The branch has a secret, a copy of it under another name, and rules for the first.
let directory = tempfile::tempdir().unwrap();
let work = directory.path().join("work");
std::fs::create_dir_all(work.join("secrets")).unwrap();
git(&work, &["init", "--quiet", "--initial-branch=master"]);
std::fs::write(work.join("secrets/a.age"), "age-encryption.org/v1\nreal\n").unwrap();
std::fs::write(work.join("secrets/copy.age"), "age-encryption.org/v1\nreal\n").unwrap();
std::fs::write(work.join("secrets.nix"), "{ \"secrets/a.age\".publicKeys = [ \"age1dev\" ]; }\n").unwrap();
git(&work, &["add", "."]);
git(&work, &["commit", "--quiet", "-m", "Secrets"]);
// An agent's branch can't change what the main branch says.
git(&work, &["checkout", "--quiet", "-b", "agent"]);
std::fs::write(work.join("secrets.nix"), "{ \"secrets/a.age\".publicKeys = [ \"age1agent\" ]; }\n").unwrap();
git(&work, &["commit", "--quiet", "-am", "Change the rules"]);
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 request = SecretRequest {
blob: Some(ObjectId::blob(b"age-encryption.org/v1\nreal\n")),
path: "secrets/a.age".parse().unwrap(),
rules: "secrets.nix".parse().unwrap(),
};
let context: SecretContext = ask(&config, &BuilderRequest::Secret(request.clone()));
assert_eq!(context.paths, ["secrets/a.age", "secrets/copy.age"]);
assert_eq!(context.recipients, Some(vec!["age1dev".to_owned()]));
assert_eq!(&*context.commit, git(&work, &["rev-parse", "master"]));
let unknown = SecretRequest { blob: None, path: "secrets/new.age".parse().unwrap(), ..request };
let context: SecretContext = ask(&config, &BuilderRequest::Secret(unknown));
assert!(context.paths.is_empty() && context.recipients.is_none());
}
#[test]
fn blob_ids_match_git() {
let Some(_) = git_directory() else {
eprintln!("skipped: git isn't installed");
return;
};
let directory = tempfile::tempdir().unwrap();
let file = directory.path().join("blob");
std::fs::write(&file, b"some\0bytes\n").unwrap();
let output = Command::new("git").arg("hash-object").arg(&file).output().unwrap();
assert_eq!(&*ObjectId::blob(b"some\0bytes\n"), String::from_utf8(output.stdout).unwrap().trim());
}