Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f2f52d5b4d |
No files matched your search
@@ -3,7 +3,6 @@ name: CI
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
check:
|
||||
@@ -19,7 +18,7 @@ jobs:
|
||||
extra-conf: |
|
||||
sandbox-fallback = false
|
||||
|
||||
# Builds the package with its tests, runs clippy, rustfmt, shellcheck and the VM test
|
||||
# (which needs KVM), and evaluates the other outputs
|
||||
# Builds the package with its tests, clippy, rustfmt and the VM test (which needs KVM), and
|
||||
# evaluates the other outputs
|
||||
- name: Check the flake
|
||||
run: nix flake check -L
|
||||
@@ -39,9 +39,8 @@ of devenv's scripts, `devenv test` or the demo's host side.
|
||||
errors) and the tests.
|
||||
- `cargo fmt` — the crate is formatted with `rustfmt` (`rustfmt.toml`); run it on code you change.
|
||||
- `nix build` — the package, which also runs the tests.
|
||||
- CI ([`.gitea/workflows/ci.yaml`](.gitea/workflows/ci.yaml)) runs `nix flake check` for pull
|
||||
requests and pushes to `main`:
|
||||
the package with its tests, `clippy` (warnings as errors), `fmt` (`cargo fmt --check`),
|
||||
- CI ([`.gitea/workflows/ci.yaml`](.gitea/workflows/ci.yaml)) runs `nix flake check` on pushes to
|
||||
`main`: the package with its tests, `clippy` (warnings as errors), `fmt` (`cargo fmt --check`),
|
||||
`shellcheck` on `src/**/*.sh` and the VM test. Keep them passing. `nix flake check --no-build`
|
||||
fails where the VM test's keys haven't been built, because the test reads them at evaluation.
|
||||
- `vm-test` (or `nix build -L .#checks.x86_64-linux.vm`) — the NixOS VM test of the broker module
|
||||
|
||||
Generated
+1
-1
@@ -3859,7 +3859,7 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
||||
|
||||
[[package]]
|
||||
name = "slop-broker"
|
||||
version = "0.2.1"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"age",
|
||||
"anyhow",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "slop-broker"
|
||||
version = "0.2.1"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
description = "Approval broker that runs privileged operations for coding agents"
|
||||
license = "MIT"
|
||||
|
||||
@@ -45,20 +45,6 @@ The development environment is [devenv](https://devenv.sh): direnv with `.envrc`
|
||||
and `cargo clippy --all-targets` work there, `devenv test` runs both, and `vm-test` runs the NixOS
|
||||
VM test (needs KVM). See [`AGENTS.md`](AGENTS.md) for conventions.
|
||||
|
||||
## Releasing
|
||||
|
||||
Use SemVer for the CLI, request protocol and Nix module options. Bump the patch for
|
||||
compatible fixes and the minor for compatible features. While the major is zero,
|
||||
use a minor bump for breaking changes and document how to upgrade. After `1.0.0`,
|
||||
bump the major for breaking changes.
|
||||
|
||||
1. Set `package.version` in `Cargo.toml` and run `cargo check` to refresh
|
||||
`Cargo.lock`. The Nix package reads the version from `Cargo.toml`.
|
||||
2. After the release commit lands on `main` and passes CI, tag it `v<version>` and
|
||||
push the tag. Keep published tags fixed.
|
||||
3. Update the `slop-broker` input in nixfiles to `ref=refs/tags/v<version>` and run
|
||||
`nix flake update slop-broker` there to refresh its lock entry.
|
||||
|
||||
## License
|
||||
|
||||
MIT; see [`LICENSE`](LICENSE).
|
||||
+8
-18
@@ -183,12 +183,9 @@ sections after this one describe each kind on its own.
|
||||
sends `Pending`, and waits for a decision, the timeout or a disconnect.
|
||||
6. **Run.**
|
||||
- The handler sends `Approved { by, stdin }`; the client sends stdin only then, and only if
|
||||
`stdin` is set (`secret set`). `ssh` carries its stdin in the request instead.
|
||||
`stdin` is set.
|
||||
- `ops::execute` runs the operation with `Io` (the stdin channel, the output sender and the
|
||||
cancel token) and returns an exit status and an optional `OpResult`.
|
||||
- If the requester leaves, most operations notice the cancel token and stop. Those
|
||||
`ops::outlives_requester` names (deploys) ignore it: `see_through` logs `detached` and
|
||||
keeps waiting, so the outcome is still audited.
|
||||
7. **Finish.** One terminal message (`Finished`, `Denied`, `Expired` or `Error`), or none if the
|
||||
requester went away, then the connection closes.
|
||||
|
||||
@@ -204,14 +201,11 @@ sections after this one describe each kind on its own.
|
||||
- `ssh::check` refuses a node that isn't one of them.
|
||||
- The scope is the destination: `{ target }`, or `{ host, port }` for `--host`. The command is
|
||||
only in the detail, so a lease covers any command to the same destination.
|
||||
- `ssh::detail` shows the command and all of its stdin, refusing stdin that isn't UTF-8 and
|
||||
requests too long to show whole.
|
||||
2. **Run.**
|
||||
- `ssh::command` builds the `ssh` command with the broker's fixed options (see
|
||||
[Execution](#execution)). The queries build the remote command themselves from validated
|
||||
fields; `ssh` passes the requester's words as they are, for `ssh` to join.
|
||||
- stdout, stderr and the exit status go back to the requester; `ssh`'s stdin is the bytes its
|
||||
request carried.
|
||||
fields; `ssh` quotes the requester's arguments.
|
||||
- stdout, stderr and the exit status go back to the requester; `ssh` forwards stdin.
|
||||
|
||||
### Secrets
|
||||
|
||||
@@ -278,9 +272,7 @@ sequenceDiagram
|
||||
`prepared`.
|
||||
3. **Run.** `ops::deploy::execute` activates every node at once, its profiles in order, as root
|
||||
through `systemd-run`. Each line of output is prefixed with `[node.profile]`; the exit status is
|
||||
the first failure's. Inside the unit, `activate-rs`'s output goes through a `cat` that, once
|
||||
the connection is gone, gives way to one discarding it, so a lost connection can't stop it.
|
||||
Each unit is `slop-deploy-<request ID>-<profile>`.
|
||||
the first failure's.
|
||||
|
||||
### Builds
|
||||
|
||||
@@ -303,8 +295,7 @@ Built in: the requester's own pending requests and leases. Always allowed, and n
|
||||
|
||||
Every step is audited as an `audit::Event` carrying the request's ID (the same ID approvers see):
|
||||
`request`, `prepared`, `approved` (with the approver's name), `decision`, `denied`, `expired`,
|
||||
`finished`, `failed`, `disconnected` (cancelled), `detached` (the requester left an operation
|
||||
that carries on), plus `invalid` and `unknown` peers.
|
||||
`finished`, `failed`, `disconnected`, plus `invalid` and `unknown` peers.
|
||||
|
||||
## Protocol
|
||||
|
||||
@@ -314,8 +305,7 @@ with a 4-byte big-endian length (`LengthDelimitedCodec`, 1 MiB maximum). The typ
|
||||
|
||||
### Requester and broker
|
||||
|
||||
A requester sends one `Request`, then stdin only after an `Approved` that asks for it (`ssh`
|
||||
carries its stdin in the request, so approvers see it). The broker
|
||||
A requester sends one `Request`, then stdin only after an `Approved` that asks for it. The broker
|
||||
sends any number of progress messages and closes after a terminal one.
|
||||
|
||||
```rust
|
||||
@@ -332,7 +322,7 @@ struct Request {
|
||||
}
|
||||
|
||||
enum Operation {
|
||||
Ssh { destination: Destination, command: Vec<Arg>, stdin: Option<bytes> },
|
||||
Ssh { destination: Destination, command: Vec<Arg> },
|
||||
Query { destination: Destination, query: Query },
|
||||
Deploy { targets: Vec<DeployTarget>, commit: CommitId, boot: bool },
|
||||
Build { attrs: Vec<FlakeAttr>, commit: CommitId },
|
||||
@@ -507,7 +497,7 @@ Every process the broker starts goes through `src/exec.rs`:
|
||||
|
||||
| Function | For | Input and output |
|
||||
|---|---|---|
|
||||
| `exec::run` | Operations the requester watches | The given stdin, or none; stdout and stderr as frames |
|
||||
| `exec::run` | Operations the requester watches | stdin from the connection; stdout and stderr as frames |
|
||||
| `exec::capture` | The broker's own steps | Captured, none of the requester's stdio |
|
||||
| `exec::run_prefixed` | Several nodes sharing the output (deploy copies and activations) | No stdin; each line prefixed with its node |
|
||||
|
||||
|
||||
+2
-2
@@ -92,8 +92,8 @@ CID are in [`settings.nix`](../nix/demo/settings.nix). The broker's configuratio
|
||||
passkey when Pocket ID asks, then sign in to <http://localhost:8095>; the passkey also approves
|
||||
`router` requests. Web Push works when the broker can reach the browser's push service.
|
||||
|
||||
A request blocks until it's answered, and `slop ssh` reads stdin to its end before asking. To keep
|
||||
the agent's shell, run requests in the background with stdin closed:
|
||||
A request blocks until it's answered, and `slop ssh` forwards stdin. To keep the agent's shell, run
|
||||
requests in the background with stdin closed:
|
||||
|
||||
```sh
|
||||
slop ssh web -- uptime </dev/null &
|
||||
|
||||
+8
-32
@@ -101,14 +101,11 @@ and `slop-approve`. How the code does it is in
|
||||
- The request carries a protocol version, so a mismatched `slop` gets a clear error.
|
||||
- **One connection per request**, carrying in order:
|
||||
1. the request;
|
||||
2. the operation's stdin, only after approval and only for operations that read it (`ssh`
|
||||
carries its stdin in the request instead, below);
|
||||
2. the operation's stdin, only after approval and only for operations that read it;
|
||||
3. its stdout and stderr;
|
||||
4. a final message with the exit status and any structured result.
|
||||
|
||||
If the connection closes, the broker cancels the request or kills the process it started. A
|
||||
deploy's activation is the exception: stopping it partway would leave boxes half changed, so
|
||||
the broker waits for it and logs how it ended.
|
||||
If the connection closes, the broker cancels the request or kills the process it started.
|
||||
|
||||
### Other requesters and approvers
|
||||
|
||||
@@ -213,8 +210,7 @@ own fields. The module and the broker refuse any other operation or field.
|
||||
a typical use.
|
||||
- **Limits.** `auto` operations are rate-limited per requester, so a looping agent can't hammer
|
||||
boxes or APIs. Pending requests are capped per requester and overall to limit notification spam.
|
||||
- **Restarts** drop pending requests and leases. Deploying the broker's box doesn't restart it;
|
||||
restart `slop-broker.service` for a new version or configuration to take effect.
|
||||
- **Restarts** drop pending requests and leases.
|
||||
|
||||
### Approvals web app
|
||||
|
||||
@@ -328,9 +324,8 @@ operation, and nothing acts on the structure besides showing it.
|
||||
|
||||
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, keeping what approvers were shown with its structure, so the web app's history shows
|
||||
it as the request did. `slop-approve log [-n 50] [--json]` shows the recent events through the
|
||||
approve socket, with each request's full detail. Secret operations record the file and the blob ID of the
|
||||
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 record the file and the blob ID of the
|
||||
ciphertext they were sent, never values.
|
||||
|
||||
## Operations
|
||||
@@ -349,14 +344,6 @@ ciphertext they were sent, never values.
|
||||
accepted, changed ones refused).
|
||||
- **`slop ssh` always asks.** `ssh` joins its arguments into a string that the remote shell runs,
|
||||
so a free-form command's text can't be judged as read-only.
|
||||
- **Approvers see everything that reaches the box.** A script piped to `bash -s` is as much the
|
||||
command as its arguments, so `slop ssh` sends its whole stdin with the request.
|
||||
- Approvers see the line the remote shell runs (the words joined with spaces, as `ssh` sends
|
||||
them) and all of the stdin, and the audit log keeps both.
|
||||
- The command gets exactly that stdin and nothing more.
|
||||
- Stdin must be UTF-8 text, and the command and stdin together are limited
|
||||
([`MAX_SSH_SHOWN`](../src/proto.rs)) so they're always shown whole; anything else is
|
||||
refused.
|
||||
- **The queries can be `auto`.** `status`, `logs` and `failed` validate their arguments (unit
|
||||
names, `--since`, line counts), and the broker builds the quoted remote command. They cover most
|
||||
of what agents need SSH for without prompting.
|
||||
@@ -397,17 +384,8 @@ broker runs it over SSH.
|
||||
6. **Activate.** On every node at once, the broker runs deploy-rs's `activate-rs` on each profile in
|
||||
deploy-rs's order.
|
||||
- It runs as root through the target's `sudo` command (`sudo -u` by default), inside a
|
||||
transient unit (`systemd-run`), so the activation finishes even if the connection drops.
|
||||
Its output streams back until then and is discarded after, since `activate-rs` stops when
|
||||
it can't write.
|
||||
- Switching doesn't restart the broker (`restartIfChanged = false`), so it can deploy its own
|
||||
box and report the result. A new version or configuration of the broker takes effect when
|
||||
it's next restarted.
|
||||
- **If the agent goes away,** the broker keeps waiting for the activations and logs their
|
||||
outcome. The audit log says the requester left, then how the deploy finished.
|
||||
- **If the broker goes away** (a crash, or its box rebooting), the activations still finish.
|
||||
Their units are named `slop-deploy-<request ID>-<profile>`, so the audit record leads to
|
||||
their journals on each node.
|
||||
transient unit (`systemd-run`), so the activation finishes even if the connection drops,
|
||||
including when the broker deploys its own box and restarts.
|
||||
- Output comes back prefixed with the node.
|
||||
- Deploys run in parallel; an agent that needs an order sends separate requests.
|
||||
|
||||
@@ -512,9 +490,7 @@ only people should be able to push to, and the approval shows what that branch s
|
||||
in the rules, added or 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.
|
||||
- Keys are labelled by name from `secrets.names` (well-known keys, such as people's), then from
|
||||
SSH keys' comments anywhere in the branch's rules (`ssh-ed25519 AAAA… shill`, which age
|
||||
ignores). Other keys are shown abbreviated.
|
||||
- `secrets.names` labels well-known keys (such as people's); other keys are shown abbreviated.
|
||||
- **The broker's own key.** The broker always adds it to the recipients, and says so, so it can
|
||||
change the file later.
|
||||
- **Sensitive requests.** Requests that read a secret, change who can read one or name content as
|
||||
|
||||
@@ -270,9 +270,6 @@ in
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
# Switching doesn't restart the broker, so it can deploy its own box and see the deploy
|
||||
# through; a new version or configuration takes effect at the next restart.
|
||||
restartIfChanged = false;
|
||||
serviceConfig = {
|
||||
ExecStart = "${cfg.package}/bin/slop-broker serve --config ${brokerConfig}";
|
||||
LoadCredential =
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ let
|
||||
in
|
||||
rustPlatform.buildRustPackage {
|
||||
pname = "slop-broker";
|
||||
inherit ((builtins.fromTOML (builtins.readFile ../Cargo.toml)).package) version;
|
||||
version = "0.1.0";
|
||||
|
||||
src = toSource {
|
||||
root = ../.;
|
||||
|
||||
+1
-1
@@ -121,7 +121,7 @@ pkgs.testers.runNixOSTest {
|
||||
print(out)
|
||||
assert "Permanently added" not in out, out
|
||||
|
||||
# Covered by the lease now; stdin goes with the request
|
||||
# Covered by the lease now; stdin is forwarded
|
||||
out = machine.succeed(f"echo piped | su agent -c \"{env} slop ssh local -- cat\"")
|
||||
assert "piped" in out, out
|
||||
out = machine.succeed(f"su agent -c \"{env} slop requests\"")
|
||||
|
||||
+1
-3
@@ -40,9 +40,7 @@ applies a policy, and asks a human to approve most requests.
|
||||
through `bash`: `slop ssh <node> -- bash -s < script.sh`.
|
||||
- There is no TTY. Interactive programs won't work; use non-interactive flags (`--no-pager`,
|
||||
`-y`).
|
||||
- `slop ssh` reads all of its stdin (unless it's a terminal) before asking, and the approver sees
|
||||
it with the command. It must be text, and the command and stdin together at most 32 KiB; copy
|
||||
larger or binary files another way.
|
||||
- `slop ssh` forwards stdin once the request is approved.
|
||||
|
||||
### Deploying
|
||||
|
||||
|
||||
+6
-61
@@ -10,7 +10,6 @@ use std::time::SystemTime;
|
||||
use anyhow::Result;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::detail::{Detail, Section};
|
||||
use crate::proto::ApprovedBy;
|
||||
|
||||
/// One line of the audit file.
|
||||
@@ -41,14 +40,14 @@ pub enum Event {
|
||||
requester: String,
|
||||
op: String,
|
||||
summary: String,
|
||||
detail: Shown,
|
||||
detail: String,
|
||||
/// Agent-supplied.
|
||||
label: Option<String>,
|
||||
},
|
||||
/// What approvers are shown once preparing a request (such as building a deploy) finished.
|
||||
Prepared {
|
||||
id: String,
|
||||
detail: Shown,
|
||||
detail: String,
|
||||
},
|
||||
Approved {
|
||||
id: String,
|
||||
@@ -78,11 +77,6 @@ pub enum Event {
|
||||
Disconnected {
|
||||
id: String,
|
||||
},
|
||||
/// The requester left while an operation that can't be stopped partway (a deploy's
|
||||
/// activation) ran; the broker still waits for it and logs how it ended.
|
||||
Detached {
|
||||
id: String,
|
||||
},
|
||||
Finished {
|
||||
id: String,
|
||||
exit: i32,
|
||||
@@ -101,39 +95,6 @@ impl Event {
|
||||
}
|
||||
}
|
||||
|
||||
/// What approvers were shown of a request. Records from before the broker kept the structure
|
||||
/// have its text.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(untagged)]
|
||||
pub enum Shown {
|
||||
Detail(Detail),
|
||||
Text(String),
|
||||
}
|
||||
|
||||
impl Shown {
|
||||
pub fn to_text(&self) -> String {
|
||||
match self {
|
||||
Shown::Detail(detail) => detail.to_text(),
|
||||
Shown::Text(text) => text.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The structure, with old records' text as one text section.
|
||||
pub fn to_detail(&self) -> Detail {
|
||||
match self {
|
||||
Shown::Detail(detail) => detail.clone(),
|
||||
Shown::Text(text) if text.is_empty() => Detail::default(),
|
||||
Shown::Text(text) => Detail { fields: vec![], sections: vec![Section::text("Text", text)] },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Detail> for Shown {
|
||||
fn from(detail: Detail) -> Shown {
|
||||
Shown::Detail(detail)
|
||||
}
|
||||
}
|
||||
|
||||
/// Request IDs are long; approvers type a prefix, and logs show the same.
|
||||
pub fn short(id: &str) -> &str {
|
||||
&id[..id.len().min(6)]
|
||||
@@ -149,7 +110,7 @@ impl fmt::Display for Event {
|
||||
}
|
||||
Event::Request { id, requester, summary, detail, label, .. } => {
|
||||
write!(f, "{} {requester} asks: {summary}", short(id))?;
|
||||
if let Some(line) = detail.to_text().lines().next() {
|
||||
if let Some(line) = detail.lines().next() {
|
||||
write!(f, "; {line}")?;
|
||||
}
|
||||
if let Some(label) = label {
|
||||
@@ -159,7 +120,7 @@ impl fmt::Display for Event {
|
||||
}
|
||||
Event::Prepared { id, detail } => {
|
||||
write!(f, "{} ready for approval", short(id))?;
|
||||
if let Some(line) = detail.to_text().lines().next() {
|
||||
if let Some(line) = detail.lines().next() {
|
||||
write!(f, "; {line}")?;
|
||||
}
|
||||
Ok(())
|
||||
@@ -182,9 +143,6 @@ impl fmt::Display for Event {
|
||||
Event::Denied { id, reason } => write!(f, "{} {reason}", short(id)),
|
||||
Event::Expired { id } => write!(f, "{} expired without an answer", short(id)),
|
||||
Event::Disconnected { id } => write!(f, "{} cancelled: the requester disconnected", short(id)),
|
||||
Event::Detached { id } => {
|
||||
write!(f, "{} the requester disconnected; waiting for it to finish anyway", short(id))
|
||||
}
|
||||
Event::Finished { id, exit, seconds } => {
|
||||
write!(f, "{} finished with exit status {exit} after {seconds:.1}s", short(id))
|
||||
}
|
||||
@@ -199,7 +157,7 @@ impl Record {
|
||||
let time = self.time.replace('T', " ").trim_end_matches('Z').to_owned();
|
||||
let mut text = format!("{time} {}\n", self.event);
|
||||
if let Event::Request { detail, .. } | Event::Prepared { detail, .. } = &self.event {
|
||||
for line in detail.to_text().lines().skip(1) {
|
||||
for line in detail.lines().skip(1) {
|
||||
text += &format!("{:21}{line}\n", "");
|
||||
}
|
||||
}
|
||||
@@ -282,7 +240,7 @@ mod tests {
|
||||
requester: "slop-cannon".into(),
|
||||
op: "ssh".into(),
|
||||
summary: "ssh river".into(),
|
||||
detail: Shown::Text("Command: a\nmore".into()),
|
||||
detail: "Command: a\nmore".into(),
|
||||
label: Some("why".into()),
|
||||
},
|
||||
};
|
||||
@@ -292,17 +250,4 @@ mod tests {
|
||||
\x20 more\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_what_approvers_saw_and_reads_old_text() {
|
||||
let detail = Detail::code("Command", "uptime");
|
||||
let event = Event::Prepared { id: "a".into(), detail: detail.clone().into() };
|
||||
let line = serde_json::to_string(&event).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Event>(&line).unwrap(), event);
|
||||
|
||||
let old: Event = serde_json::from_str(r#"{"event":"prepared","id":"a","detail":"Command: uptime"}"#).unwrap();
|
||||
let Event::Prepared { detail: old, .. } = old else { panic!("{old:?}") };
|
||||
assert_eq!(old, Shown::Text("Command: uptime".into()));
|
||||
assert_eq!(old.to_text(), detail.to_text());
|
||||
}
|
||||
}
|
||||
+2
-25
@@ -10,7 +10,7 @@ use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use slop_broker::proto::{
|
||||
ApprovedBy, ClientMessage, DEFAULT_VSOCK_PORT, Destination, GenKind, HOST_CID, MAX_SSH_SHOWN, OpResult, Operation,
|
||||
ApprovedBy, ClientMessage, DEFAULT_VSOCK_PORT, Destination, GenKind, HOST_CID, OpResult, Operation,
|
||||
PROTOCOL_VERSION, Query, Request, SecretFile, SecretOp, ServerMessage, Target as SecretTarget, decode, encode,
|
||||
transport,
|
||||
};
|
||||
@@ -82,7 +82,6 @@ enum Command {
|
||||
#[command(flatten)]
|
||||
target: Target,
|
||||
/// Remote command, after `--`; joined with spaces and run by the remote shell, as ssh does.
|
||||
/// Stdin, unless it's a terminal, is read in full first and shown to the approver.
|
||||
#[arg(last = true)]
|
||||
command: Vec<Arg>,
|
||||
},
|
||||
@@ -356,9 +355,7 @@ fn secret_operation(action: SecretCommand) -> Result<(Operation, Located)> {
|
||||
|
||||
fn operation(command: Command) -> Result<Operation> {
|
||||
Ok(match command {
|
||||
Command::Ssh { target, command } => {
|
||||
Operation::Ssh { destination: target.destination()?, command, stdin: whole_stdin()? }
|
||||
}
|
||||
Command::Ssh { target, command } => Operation::Ssh { destination: target.destination()?, command },
|
||||
Command::Status { target, unit } => {
|
||||
Operation::Query { destination: target.destination()?, query: Query::Status { unit } }
|
||||
}
|
||||
@@ -373,26 +370,6 @@ fn operation(command: Command) -> Result<Operation> {
|
||||
})
|
||||
}
|
||||
|
||||
/// All of stdin, unless it's a terminal or empty, to send with the request.
|
||||
fn whole_stdin() -> Result<Option<Vec<u8>>> {
|
||||
use std::io::{IsTerminal, Read};
|
||||
|
||||
let stdin = std::io::stdin();
|
||||
if stdin.is_terminal() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let mut data = Vec::new();
|
||||
stdin.lock().take(MAX_SSH_SHOWN as u64 + 1).read_to_end(&mut data).context("reading stdin")?;
|
||||
if data.len() > MAX_SSH_SHOWN {
|
||||
bail!(
|
||||
"stdin is over {} KiB; approvers have to see all of it, so copy large files another way",
|
||||
MAX_SSH_SHOWN / 1024
|
||||
);
|
||||
}
|
||||
Ok((!data.is_empty()).then_some(data))
|
||||
}
|
||||
|
||||
/// A full commit ID, from Git in the working directory unless it already is one.
|
||||
fn resolve(revision: &str) -> Result<CommitId> {
|
||||
if let Ok(commit) = revision.parse() {
|
||||
|
||||
+1
-16
@@ -103,9 +103,6 @@ pub struct SecretContext {
|
||||
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>>,
|
||||
/// Keys by name, from SSH keys' comments anywhere in the rules file.
|
||||
#[serde(default)]
|
||||
pub names: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// A commit as approvers see it before anything is built. Everything but `on_branch` is
|
||||
@@ -527,19 +524,7 @@ async fn secret_context(config: &BuilderConfig, request: &SecretRequest) -> Resu
|
||||
|
||||
let rules = rules(config, &commit, &request.rules).await?;
|
||||
let recipients = rules.get(&*request.path).cloned();
|
||||
let names = commented(rules.values().flatten());
|
||||
Ok(SecretContext { branch: config.branch.clone(), commit, paths, recipients, names })
|
||||
}
|
||||
|
||||
/// SSH keys by their comments, like `ssh-ed25519 AAAA… shill`; age ignores the comment.
|
||||
fn commented<'a>(keys: impl Iterator<Item = &'a String>) -> BTreeMap<String, String> {
|
||||
keys.filter_map(|key| match key.split_whitespace().collect::<Vec<_>>().as_slice() {
|
||||
[kind, key, comment @ ..] if kind.starts_with("ssh-") && !comment.is_empty() => {
|
||||
Some((comment.join(" "), format!("{kind} {key}")))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
Ok(SecretContext { branch: config.branch.clone(), commit, paths, recipients })
|
||||
}
|
||||
|
||||
/// Paths in `git ls-tree -r -z` output whose object is `blob`.
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
//! What approvers are shown of a request: fields, then tables, lists and text. Operations build
|
||||
//! it; every surface renders it. The web app shows the structure (also in the audit history,
|
||||
//! which keeps it), the others [`Detail::to_text`], which passkey confirmations fingerprint.
|
||||
//! it; every surface renders it. The web app shows the structure, the others [`Detail::to_text`],
|
||||
//! which is also what the audit log keeps and passkey confirmations fingerprint.
|
||||
//!
|
||||
//! The structure is the same for every operation, so surfaces don't need to know any of them.
|
||||
//! All of it can carry agent-written text, which every surface makes printable when it shows it.
|
||||
|
||||
+16
-12
@@ -1,5 +1,5 @@
|
||||
//! Runs processes for approved requests, wired to the requester's stdout and stderr (carried as
|
||||
//! messages).
|
||||
//! Runs processes for approved requests, wired to the requester's stdin, stdout and stderr
|
||||
//! (carried as messages).
|
||||
use std::process::{ExitStatus, Stdio};
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -30,8 +30,7 @@ impl Output {
|
||||
|
||||
/// The requester's side of an approved operation.
|
||||
pub struct Io {
|
||||
/// Chunks of the requester's stdin, which it sends after approval for operations that ask for
|
||||
/// it; closed at EOF.
|
||||
/// Chunks of the requester's stdin; closed at EOF.
|
||||
pub stdin: mpsc::Receiver<Vec<u8>>,
|
||||
pub out: Output,
|
||||
/// Cancelled when the requester disconnects.
|
||||
@@ -43,11 +42,11 @@ pub fn exit_code(status: ExitStatus) -> i32 {
|
||||
status.code().unwrap_or_else(|| 128 + status.signal().unwrap_or(0))
|
||||
}
|
||||
|
||||
/// Runs `command` in its own process group with the requester's stdout and stderr, and `stdin` (or
|
||||
/// none) as its whole input. If the requester goes away, the whole group is terminated.
|
||||
pub async fn run(mut command: Command, io: &mut Io, stdin: Option<&[u8]>) -> Result<i32> {
|
||||
/// Runs `command` in its own process group with the requester's stdio. If the requester goes
|
||||
/// away, the whole group is terminated.
|
||||
pub async fn run(mut command: Command, io: &mut Io, with_stdin: bool) -> Result<i32> {
|
||||
command
|
||||
.stdin(if stdin.is_some() { Stdio::piped() } else { Stdio::null() })
|
||||
.stdin(if with_stdin { Stdio::piped() } else { Stdio::null() })
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.process_group(0)
|
||||
@@ -59,12 +58,17 @@ pub async fn run(mut command: Command, io: &mut Io, stdin: Option<&[u8]>) -> Res
|
||||
let stdout = tokio::spawn(pump(child.stdout.take().unwrap(), io.out.clone(), ServerMessage::Stdout));
|
||||
let stderr = tokio::spawn(pump(child.stderr.take().unwrap(), io.out.clone(), ServerMessage::Stderr));
|
||||
|
||||
// Closing the pipe once it's written is the end of the input.
|
||||
let child_stdin = child.stdin.take();
|
||||
let mut child_stdin = child.stdin.take();
|
||||
let stdin_rx = &mut io.stdin;
|
||||
let feed = async move {
|
||||
if let (Some(mut pipe), Some(data)) = (child_stdin, stdin) {
|
||||
let _ = pipe.write_all(data).await;
|
||||
if let Some(pipe) = child_stdin.as_mut() {
|
||||
while let Some(chunk) = stdin_rx.recv().await {
|
||||
if chunk.is_empty() || pipe.write_all(&chunk).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
drop(child_stdin);
|
||||
std::future::pending::<()>().await
|
||||
};
|
||||
tokio::pin!(feed);
|
||||
|
||||
+23
-91
@@ -13,7 +13,6 @@ use anyhow::{Context, Result, bail, ensure};
|
||||
use futures_util::future::join_all;
|
||||
use serde_json::json;
|
||||
use tokio::process::Command;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::{Parsed, shell_quote, ssh};
|
||||
use crate::builder::{self, BuildRequest, BuiltProfile};
|
||||
@@ -118,22 +117,17 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Activates every node; its transient units are named after the request `id`, so its audit
|
||||
/// record leads to their journals. It ignores the requester leaving (see
|
||||
/// [`super::outlives_requester`]).
|
||||
pub async fn execute(broker: &Broker, id: &str, parsed: &Parsed, io: &mut Io) -> Result<i32> {
|
||||
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.build.as_ref().context("nothing was built")?;
|
||||
|
||||
// Never cancelled: activations run to the end, and their output is dropped once the
|
||||
// requester has gone.
|
||||
let never = CancellationToken::new();
|
||||
let (out, cancel) = (&io.out, &never);
|
||||
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, id)?)];
|
||||
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);
|
||||
|
||||
@@ -177,7 +171,7 @@ async fn copy(
|
||||
node: &str,
|
||||
profiles: &[&BuiltProfile],
|
||||
out: &Output,
|
||||
cancel: &CancellationToken,
|
||||
cancel: &tokio_util::sync::CancellationToken,
|
||||
) -> Result<()> {
|
||||
let target = ssh::target(ssh, node)?;
|
||||
let options = copy_options(ssh, node)?;
|
||||
@@ -228,7 +222,12 @@ pub(super) fn nix_ssh_options(mut options: Vec<String>, extra: &[String]) -> Vec
|
||||
/// Compares a profile on a node with the new one; see the script for its output.
|
||||
const INSPECT: &str = include_str!("inspect.sh");
|
||||
|
||||
async fn inspect(ssh: &SshConfig, node: &str, profile: &BuiltProfile, cancel: &CancellationToken) -> Result<Changes> {
|
||||
async fn inspect(
|
||||
ssh: &SshConfig,
|
||||
node: &str,
|
||||
profile: &BuiltProfile,
|
||||
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)])?;
|
||||
|
||||
@@ -239,16 +238,11 @@ async fn inspect(ssh: &SshConfig, node: &str, profile: &BuiltProfile, cancel: &C
|
||||
Ok(Changes::parse(&String::from_utf8_lossy(&stdout)))
|
||||
}
|
||||
|
||||
/// Runs its arguments with their output to stdout until that breaks, then to nowhere, so a lost
|
||||
/// connection can't stop an activation halfway: `activate-rs` panics when it can't write.
|
||||
const UNTIL_DISCONNECTED: &str = r#"set -o pipefail; "$@" 2>&1 | { cat || cat >/dev/null; }"#;
|
||||
|
||||
fn activate_command(ssh: &SshConfig, node: &str, profile: &BuiltProfile, boot: bool, id: &str) -> Result<Vec<String>> {
|
||||
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 or the process
|
||||
// running it is killed
|
||||
// A transient unit, so activation finishes even if this connection drops
|
||||
words.extend(
|
||||
[
|
||||
"/run/current-system/sw/bin/systemd-run",
|
||||
@@ -261,8 +255,7 @@ fn activate_command(ssh: &SshConfig, node: &str, profile: &BuiltProfile, boot: b
|
||||
]
|
||||
.map(Into::into),
|
||||
);
|
||||
words.push(format!("--unit=slop-deploy-{id}-{}", profile.profile));
|
||||
words.extend(["/run/current-system/sw/bin/bash", "-c", UNTIL_DISCONNECTED, "slop-deploy"].map(Into::into));
|
||||
words.push(format!("--unit=slop-deploy-{}-{}", &run[..8], profile.profile));
|
||||
|
||||
// What deploy-rs runs, without magic rollback
|
||||
words.push(format!("{}/activate-rs", profile.path));
|
||||
@@ -415,35 +408,14 @@ impl Changes {
|
||||
|
||||
/// A line of `nix store diff-closures` (`name: 1.0 → 1.1, +3.4 KiB`) as package, version change
|
||||
/// and size change.
|
||||
fn package_cells(line: &str) -> [String; 3] {
|
||||
let Some((name, rest)) = line.split_once(": ") else { return [line.into(), String::new(), String::new()] };
|
||||
if let Some((version, size)) = rest.rsplit_once(", ")
|
||||
&& let Some(size) = package_size(size)
|
||||
{
|
||||
return [name.into(), version.into(), size];
|
||||
fn package_cells(line: &str) -> [&str; 3] {
|
||||
let Some((name, rest)) = line.split_once(": ") else { return [line, "", ""] };
|
||||
let is_size = |s: &str| s.starts_with(['+', '-']);
|
||||
match rest.rsplit_once(", ") {
|
||||
Some((version, size)) if is_size(size) => [name, version, size],
|
||||
_ if is_size(rest) => [name, "", rest],
|
||||
_ => [name, rest, ""],
|
||||
}
|
||||
if let Some(size) = package_size(rest) {
|
||||
return [name.into(), "unchanged".into(), size];
|
||||
}
|
||||
[name.into(), rest.into(), String::new()]
|
||||
}
|
||||
|
||||
/// A size change, signed. Nix versions differ: some sign increases, some only colour them (even
|
||||
/// on piped output), and some do neither; decreases always have a sign.
|
||||
fn package_size(value: &str) -> Option<String> {
|
||||
let plain = value
|
||||
.strip_prefix("\x1b[31;1m")
|
||||
.or_else(|| value.strip_prefix("\x1b[32;1m"))
|
||||
.and_then(|size| size.strip_suffix("\x1b[0m"))
|
||||
.unwrap_or(value);
|
||||
|
||||
let (sign, size) = match plain.strip_prefix(['+', '-']) {
|
||||
Some(size) => (&plain[..1], size),
|
||||
None => ("+", plain),
|
||||
};
|
||||
let (number, unit) = size.split_once(' ')?;
|
||||
let sized = number.parse::<f64>().is_ok() && ["B", "KiB", "MiB", "GiB", "TiB"].contains(&unit);
|
||||
sized.then(|| format!("{sign}{size}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -453,15 +425,7 @@ mod tests {
|
||||
#[test]
|
||||
fn splits_package_lines() {
|
||||
assert_eq!(package_cells("a: 1.0 → 1.1, +3.4 KiB"), ["a", "1.0 → 1.1", "+3.4 KiB"]);
|
||||
assert_eq!(package_cells("b: -12.0 KiB"), ["b", "unchanged", "-12.0 KiB"]);
|
||||
assert_eq!(package_cells("b: \x1b[31;1m12.0 KiB\x1b[0m"), ["b", "unchanged", "+12.0 KiB"]);
|
||||
assert_eq!(package_cells("b: 12.0 KiB"), ["b", "unchanged", "+12.0 KiB"]);
|
||||
assert_eq!(
|
||||
package_cells("slop: 0.1.0, 0.1.0-fish → 0.2.0, 0.2.0-fish, 129.0 KiB"),
|
||||
["slop", "0.1.0, 0.1.0-fish → 0.2.0, 0.2.0-fish", "+129.0 KiB"]
|
||||
);
|
||||
assert_eq!(package_cells("c: 1.0, 2 KiB → 1.1"), ["c", "1.0, 2 KiB → 1.1", ""]);
|
||||
assert_eq!(package_cells("b: 1.0 → 1.1, \x1b[32;1m-12.0 KiB\x1b[0m"), ["b", "1.0 → 1.1", "-12.0 KiB"]);
|
||||
assert_eq!(package_cells("b: -12.0 KiB"), ["b", "", "-12.0 KiB"]);
|
||||
assert_eq!(package_cells("c: ∅ → 2.0"), ["c", "∅ → 2.0", ""]);
|
||||
assert_eq!(package_cells("odd"), ["odd", "", ""]);
|
||||
}
|
||||
@@ -525,39 +489,7 @@ mod tests {
|
||||
};
|
||||
let words = activate_command(&config, "river", &profile, true, "0123456789abcdef").unwrap();
|
||||
assert_eq!(&words[..3], ["doas", "-u", "root"]);
|
||||
assert!(words.contains(&"--unit=slop-deploy-0123456789abcdef-system".to_owned()));
|
||||
assert!(words.contains(&"--unit=slop-deploy-01234567-system".to_owned()));
|
||||
assert_eq!(words.last().unwrap(), "--boot");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn activation_outlives_its_output() {
|
||||
use std::io::Read;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let marker = directory.path().join("finished");
|
||||
let activation = format!("sleep 0.5; for i in $(seq 1000); do echo line $i; done; touch {}", marker.display());
|
||||
|
||||
// The connection's end of the output closes before the activation writes anything.
|
||||
let mut child = Command::new("bash")
|
||||
.args(["-c", UNTIL_DISCONNECTED, "slop-deploy", "bash", "-c", &activation])
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
drop(child.stdout.take());
|
||||
|
||||
assert!(child.wait().unwrap().success());
|
||||
assert!(marker.exists());
|
||||
|
||||
// While it's there, output goes through.
|
||||
let mut child = Command::new("bash")
|
||||
.args(["-c", UNTIL_DISCONNECTED, "slop-deploy", "sh", "-c", "echo out; echo err >&2; exit 3"])
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut output = String::new();
|
||||
child.stdout.take().unwrap().read_to_string(&mut output).unwrap();
|
||||
assert_eq!(output, "out\nerr\n");
|
||||
assert_eq!(child.wait().unwrap().code(), Some(3));
|
||||
}
|
||||
}
|
||||
+9
-14
@@ -100,13 +100,15 @@ fn fields_known(parsed: &Parsed) -> bool {
|
||||
|
||||
fn plan_op(broker: &Broker, operation: Operation) -> Result<Parsed> {
|
||||
match &operation {
|
||||
Operation::Ssh { destination, command, stdin } => {
|
||||
Operation::Ssh { destination, command } => {
|
||||
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) };
|
||||
|
||||
let summary = format!("ssh {}", ssh::describe(destination));
|
||||
let detail = ssh::detail(command, stdin.as_deref())?;
|
||||
Ok(Parsed::new(OpName::Ssh, ssh::scope(destination), summary, detail, operation))
|
||||
let detail = Detail::code("Command", shown);
|
||||
Ok(Parsed { stdin: true, ..Parsed::new(OpName::Ssh, ssh::scope(destination), summary, detail, operation) })
|
||||
}
|
||||
Operation::Query { destination, query } => {
|
||||
let config = &broker.targets.ssh()?;
|
||||
@@ -144,12 +146,6 @@ fn commit(operation: &Operation) -> Result<&CommitId> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Operations that carry on when their requester leaves, since stopping them partway would leave
|
||||
/// boxes half changed: the broker waits for them and logs how they ended.
|
||||
pub fn outlives_requester(parsed: &Parsed) -> bool {
|
||||
matches!(parsed.operation, Operation::Deploy { .. })
|
||||
}
|
||||
|
||||
/// 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)?;
|
||||
@@ -208,18 +204,17 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs an approved request; `id` is its ID.
|
||||
pub async fn execute(broker: &Broker, id: &str, requester: &str, parsed: Parsed, io: &mut Io) -> Result<Outcome> {
|
||||
pub async fn execute(broker: &Broker, requester: &str, parsed: Parsed, io: &mut Io) -> Result<Outcome> {
|
||||
match parsed.operation {
|
||||
Operation::Deploy { .. } => return deploy::execute(broker, id, &parsed, io).await.map(Into::into),
|
||||
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,
|
||||
_ => {}
|
||||
}
|
||||
|
||||
match parsed.operation {
|
||||
Operation::Ssh { destination, command, stdin } => {
|
||||
ssh::execute(broker, &destination, &command, stdin.as_deref(), io).await.map(Into::into)
|
||||
Operation::Ssh { destination, command } => {
|
||||
ssh::execute(broker, &destination, &command, io).await.map(Into::into)
|
||||
}
|
||||
Operation::Query { destination, query } => {
|
||||
query::execute(broker, &destination, &query, io).await.map(Into::into)
|
||||
|
||||
+1
-1
@@ -39,7 +39,7 @@ pub async fn execute(broker: &Broker, destination: &Destination, query: &Query,
|
||||
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, None).await
|
||||
exec::run(ssh::command(&config, destination, &remote)?, io, false).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+1
-22
@@ -152,8 +152,7 @@ fn describe(op: &SecretOp, context: &SecretContext, config: &SecretsConfig, own:
|
||||
if let Some(requested) = op.recipients() {
|
||||
let (recipients, added) = with_own(requested, own);
|
||||
let rules = &config.rules;
|
||||
let names = names(config, context);
|
||||
let label = |r: &Recipient| label(r, &names);
|
||||
let label = |r: &Recipient| label(r, &config.names);
|
||||
|
||||
let rows: Vec<Row> = match context.recipients.as_ref().map(|keys| expected(keys)) {
|
||||
Some(expected) => {
|
||||
@@ -217,17 +216,6 @@ fn same(a: &[Recipient], b: &[Recipient]) -> bool {
|
||||
a.iter().all(|r| b.contains(r)) && b.iter().all(|r| a.contains(r))
|
||||
}
|
||||
|
||||
/// The configured names, then the comments on the main branch's keys.
|
||||
fn names(config: &SecretsConfig, context: &SecretContext) -> BTreeMap<String, Recipient> {
|
||||
let mut names = config.names.clone();
|
||||
for (name, key) in &context.names {
|
||||
if let Ok(key) = Recipient::normalize(key) {
|
||||
names.entry(name.clone()).or_insert(key);
|
||||
}
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
fn label(recipient: &Recipient, names: &BTreeMap<String, Recipient>) -> String {
|
||||
names.iter().find(|(_, r)| *r == recipient).map_or_else(|| recipient.abbreviated(), |(name, _)| name.clone())
|
||||
}
|
||||
@@ -424,7 +412,6 @@ mod tests {
|
||||
commit: "0123456789abcdef0123456789abcdef01234567".parse().unwrap(),
|
||||
paths: paths.iter().map(|p| p.to_string()).collect(),
|
||||
recipients,
|
||||
names: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -541,14 +528,6 @@ mod tests {
|
||||
|
||||
let (detail, sensitive) = describe(&set(vec![dev.clone()]), &context(&[], None), &config, &own);
|
||||
assert!(sensitive && detail.to_text().contains("isn't in secrets.nix"), "{}", detail.to_text());
|
||||
|
||||
// The main branch's key comments name recipients, though not over the configured names.
|
||||
let mut named = context(&[], Some(vec![dev.to_string()]));
|
||||
named.names = BTreeMap::from([("box".into(), host.to_string()), ("not-dev".into(), dev.to_string())]);
|
||||
named.names.insert("bad".into(), "nonsense".into());
|
||||
let (detail, _) = describe(&set(vec![host.clone(), dev.clone()]), &named, &config, &own);
|
||||
let labels: Vec<_> = statuses(&detail).into_iter().map(|(label, ..)| label).collect();
|
||||
assert_eq!(labels, ["box".to_owned(), "dev".to_owned(), own.abbreviated()]);
|
||||
}
|
||||
|
||||
/// Each recipient row's key, status and tone.
|
||||
|
||||
+4
-46
@@ -1,13 +1,12 @@
|
||||
//! Commands over SSH with the broker's key, to the main branch's deploy-rs nodes or explicit
|
||||
//! `user@host`s.
|
||||
use anyhow::{Context, Result, bail};
|
||||
use anyhow::{Result, bail};
|
||||
use serde_json::{Map, Value, json};
|
||||
use tokio::process::Command;
|
||||
|
||||
use crate::config::{SshConfig, SshTarget, credential};
|
||||
use crate::detail::{Detail, Field, Section};
|
||||
use crate::exec::{self, Io};
|
||||
use crate::proto::{Destination, MAX_SSH_SHOWN};
|
||||
use crate::proto::Destination;
|
||||
use crate::server::Broker;
|
||||
use crate::types::Arg;
|
||||
|
||||
@@ -36,41 +35,6 @@ pub fn describe(destination: &Destination) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// What approvers see: the line the remote shell runs and all of its stdin, in full, since nothing
|
||||
/// else reaches the box. Requests too long to show whole are refused.
|
||||
pub fn detail(command: &[Arg], stdin: Option<&[u8]>) -> Result<Detail> {
|
||||
// `ssh` joins the words with spaces, unquoted, and the remote shell runs the result.
|
||||
let line = command.iter().map(|w| &**w).collect::<Vec<_>>().join(" ");
|
||||
let stdin =
|
||||
stdin.map(std::str::from_utf8).transpose().context("stdin isn't UTF-8 text; approvers have to read it")?;
|
||||
|
||||
let size = line.len() + stdin.map_or(0, str::len);
|
||||
if size > MAX_SSH_SHOWN {
|
||||
bail!(
|
||||
"the command and its stdin are over {} KiB; approvers have to see all of them, so copy large files another way",
|
||||
MAX_SSH_SHOWN / 1024
|
||||
);
|
||||
}
|
||||
|
||||
let mut detail = Detail::new();
|
||||
if line.is_empty() {
|
||||
let shown = if stdin.is_some() { "(none: the login shell runs stdin)" } else { "(none)" };
|
||||
detail.field(Field::new("Command", shown));
|
||||
} else if line.contains('\n') || line.chars().count() > 200 {
|
||||
detail.section(Section::text("Command", &line));
|
||||
} else {
|
||||
detail.field(Field::new("Command", &line).code());
|
||||
}
|
||||
|
||||
if let Some(stdin) = stdin {
|
||||
// A field as well as the text, so it shows where sections are folded away.
|
||||
let lines = stdin.lines().count();
|
||||
detail.field(Field::new("Stdin", format!("{lines} lines, {} bytes", stdin.len())));
|
||||
detail.section(Section::text("Stdin", stdin));
|
||||
}
|
||||
Ok(detail)
|
||||
}
|
||||
|
||||
/// Options for every connection; they come before any from target config, so they win.
|
||||
pub fn options(config: &SshConfig) -> Vec<String> {
|
||||
options_with_key(config, &config.key)
|
||||
@@ -136,15 +100,9 @@ pub fn command_to<S: AsRef<str>>(config: &SshConfig, target: &SshTarget, remote:
|
||||
command
|
||||
}
|
||||
|
||||
pub async fn execute(
|
||||
broker: &Broker,
|
||||
destination: &Destination,
|
||||
remote: &[Arg],
|
||||
stdin: Option<&[u8]>,
|
||||
io: &mut Io,
|
||||
) -> Result<i32> {
|
||||
pub async fn execute(broker: &Broker, destination: &Destination, remote: &[Arg], io: &mut Io) -> Result<i32> {
|
||||
let config = broker.targets.ssh()?;
|
||||
exec::run(command(&config, destination, remote)?, io, Some(stdin.unwrap_or_default())).await
|
||||
exec::run(command(&config, destination, remote)?, io, true).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+3
-11
@@ -2,7 +2,7 @@
|
||||
//!
|
||||
//! Each message is CBOR, framed with a 4-byte big-endian length (`LengthDelimitedCodec`). A
|
||||
//! requester sends one [`ClientMessage::Request`], then (only after an `Approved` that asks for
|
||||
//! it) stdin. `ssh` carries its stdin in the request instead, so approvers see it. The broker answers with [`ServerMessage`]s and closes after a terminal one.
|
||||
//! it) stdin. The broker answers with [`ServerMessage`]s and closes after a terminal one.
|
||||
use std::num::NonZeroU16;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
@@ -21,10 +21,8 @@ use crate::types::{
|
||||
};
|
||||
|
||||
/// Bumped on any incompatible change; the broker refuses other versions.
|
||||
pub const PROTOCOL_VERSION: u32 = 2;
|
||||
pub const PROTOCOL_VERSION: u32 = 1;
|
||||
pub const MAX_MESSAGE: usize = 1 << 20;
|
||||
/// Bytes of an `ssh` request's command and stdin together: all of it is shown to approvers.
|
||||
pub const MAX_SSH_SHOWN: usize = 32 * 1024;
|
||||
pub const DEFAULT_VSOCK_PORT: u32 = 6262;
|
||||
/// The host's CID, as seen from a guest.
|
||||
pub const HOST_CID: u32 = 2;
|
||||
@@ -50,13 +48,7 @@ pub struct Request {
|
||||
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
|
||||
pub enum Operation {
|
||||
/// A command over SSH, joined with spaces and run by the remote shell (as `ssh` does).
|
||||
Ssh {
|
||||
destination: Destination,
|
||||
command: Vec<Arg>,
|
||||
/// All of the command's stdin, as UTF-8 text; approvers see it before it runs.
|
||||
#[serde(with = "serde_bytes")]
|
||||
stdin: Option<Vec<u8>>,
|
||||
},
|
||||
Ssh { destination: Destination, command: Vec<Arg> },
|
||||
/// A fixed read-only query, run over SSH with a command the broker builds.
|
||||
Query { destination: Destination, query: Query },
|
||||
/// This requester's pending requests and leases.
|
||||
|
||||
+6
-63
@@ -195,7 +195,7 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
|
||||
requester: requester.to_owned(),
|
||||
op: parsed.op.to_string(),
|
||||
summary: parsed.summary.clone(),
|
||||
detail: parsed.detail.clone().into(),
|
||||
detail: parsed.detail.to_text(),
|
||||
label: label.clone(),
|
||||
});
|
||||
|
||||
@@ -239,7 +239,7 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
|
||||
Ok(gate) => gate,
|
||||
Err(error) => return failed(error),
|
||||
};
|
||||
log(Event::Prepared { id: id.clone(), detail: gate.detail.clone().into() });
|
||||
log(Event::Prepared { id: id.clone(), detail: gate.detail.to_text() });
|
||||
|
||||
let (by, approver) = match authorize(broker, &id, requester, &gate, label.clone(), io).await {
|
||||
Ok(Some(approval)) => approval,
|
||||
@@ -263,7 +263,7 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
|
||||
return failed(error);
|
||||
}
|
||||
|
||||
log(Event::Prepared { id: id.clone(), detail: parsed.detail.clone().into() });
|
||||
log(Event::Prepared { id: id.clone(), detail: parsed.detail.to_text() });
|
||||
}
|
||||
|
||||
let (approved_by, approver) = match authorize(broker, &id, requester, &parsed, label, io).await {
|
||||
@@ -282,18 +282,15 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
|
||||
io.out.send(ServerMessage::Approved { by: approved_by, stdin: parsed.stdin }).await;
|
||||
|
||||
let (start, builtin) = (std::time::Instant::now(), parsed.op.builtin());
|
||||
let result = ops::execute(broker, requester, parsed, io).await;
|
||||
|
||||
let log = |event| {
|
||||
if !builtin {
|
||||
broker.audit.log(event)
|
||||
}
|
||||
};
|
||||
|
||||
// Some operations carry on if the requester leaves, and their outcome is still logged.
|
||||
let (outlives, cancel) = (ops::outlives_requester(&parsed), io.cancel.clone());
|
||||
let execution = ops::execute(broker, &id, requester, parsed, io);
|
||||
let result = see_through(execution, outlives, &cancel, || log(Event::Detached { id: id.clone() })).await;
|
||||
|
||||
if cancel.is_cancelled() && !outlives {
|
||||
if io.cancel.is_cancelled() {
|
||||
log(Event::Disconnected { id });
|
||||
return None;
|
||||
}
|
||||
@@ -311,24 +308,6 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs an operation to the end. If the requester leaves and the operation `outlives` it, this
|
||||
/// calls `detached` and keeps waiting; otherwise the operation notices `cancel` itself.
|
||||
async fn see_through<T>(
|
||||
execution: impl Future<Output = T>,
|
||||
outlives: bool,
|
||||
cancel: &CancellationToken,
|
||||
detached: impl FnOnce(),
|
||||
) -> T {
|
||||
tokio::pin!(execution);
|
||||
tokio::select! {
|
||||
result = &mut execution => result,
|
||||
_ = cancel.cancelled(), if outlives => {
|
||||
detached();
|
||||
execution.await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What policy says about a request.
|
||||
fn verdict(broker: &Broker, requester: &str, parsed: &ops::Parsed) -> Result<policy::Verdict, ServerMessage> {
|
||||
let settings = broker.config.policy(requester).ok_or_else(|| denied("unknown requester"))?;
|
||||
@@ -439,39 +418,3 @@ pub fn check_runtime_dir(path: &Path) -> Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
|
||||
/// Finishes after a while, unless it notices `cancel` first.
|
||||
async fn operation(cancel: CancellationToken) -> &'static str {
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(Duration::from_millis(200)) => "finished",
|
||||
_ = cancel.cancelled() => "stopped",
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn operations_that_outlive_the_requester_are_seen_through() {
|
||||
for (outlives, expected) in [(true, "finished"), (false, "stopped")] {
|
||||
let (cancel, detached) = (CancellationToken::new(), Cell::new(0));
|
||||
let leave = {
|
||||
let cancel = cancel.clone();
|
||||
async move {
|
||||
tokio::time::sleep(Duration::from_millis(50)).await;
|
||||
cancel.cancel();
|
||||
}
|
||||
};
|
||||
|
||||
// Operations that outlive their requester don't watch its token.
|
||||
let watched = if outlives { CancellationToken::new() } else { cancel.clone() };
|
||||
let execution = see_through(operation(watched), outlives, &cancel, || detached.set(detached.get() + 1));
|
||||
let (result, ()) = tokio::join!(execution, leave);
|
||||
|
||||
assert_eq!(result, expected);
|
||||
assert_eq!(detached.get(), usize::from(outlives));
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-28
@@ -1,8 +1,7 @@
|
||||
//! The audit log gathered by request: what was asked, who approved it and how it ended.
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::audit::{Event, Record, Shown};
|
||||
use crate::detail::Detail;
|
||||
use crate::audit::{Event, Record};
|
||||
use crate::proto::ApprovedBy;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
@@ -84,7 +83,6 @@ fn id_of(event: &Event) -> Option<&str> {
|
||||
| Event::Denied { id, .. }
|
||||
| Event::Expired { id }
|
||||
| Event::Disconnected { id }
|
||||
| Event::Detached { id }
|
||||
| Event::Finished { id, .. }
|
||||
| Event::Failed { id, .. } => Some(id),
|
||||
}
|
||||
@@ -158,7 +156,7 @@ fn summarize(id: String, records: Vec<Record>) -> History {
|
||||
Event::Finished { exit: 0, .. } => history.outcome = Outcome::Succeeded,
|
||||
Event::Finished { exit, .. } => history.outcome = Outcome::ExitedWith(*exit),
|
||||
Event::Failed { .. } => history.outcome = Outcome::Failed,
|
||||
Event::Unknown { .. } | Event::Prepared { .. } | Event::Approved { .. } | Event::Detached { .. } => {}
|
||||
Event::Unknown { .. } | Event::Prepared { .. } | Event::Approved { .. } => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,8 +164,8 @@ fn summarize(id: String, records: Vec<Record>) -> History {
|
||||
history
|
||||
}
|
||||
|
||||
/// One event in a request's timeline: what happened, and what approvers were shown with it.
|
||||
pub fn describe(event: &Event) -> (String, Option<Detail>) {
|
||||
/// One event in a request's timeline: what happened, and any longer text to show with it.
|
||||
pub fn describe(event: &Event) -> (String, Option<String>) {
|
||||
match event {
|
||||
Event::Unknown { peer } => (format!("Refused a connection from {peer}"), None),
|
||||
Event::Invalid { error, .. } => (format!("Invalid request: {error}"), None),
|
||||
@@ -176,9 +174,11 @@ pub fn describe(event: &Event) -> (String, Option<Detail>) {
|
||||
if let Some(label) = label {
|
||||
text += &format!(" (label: {label})");
|
||||
}
|
||||
(text, shown(detail))
|
||||
(text, Some(detail.clone()).filter(|d| !d.is_empty()))
|
||||
}
|
||||
Event::Prepared { detail, .. } => {
|
||||
("Prepared for approval".into(), Some(detail.clone()).filter(|d| !d.is_empty()))
|
||||
}
|
||||
Event::Prepared { detail, .. } => ("Prepared for approval".into(), shown(detail)),
|
||||
Event::Approved { by, approver, step, .. } => {
|
||||
let by = match (by, approver) {
|
||||
(ApprovedBy::Policy, _) => "policy".to_owned(),
|
||||
@@ -195,7 +195,6 @@ pub fn describe(event: &Event) -> (String, Option<Detail>) {
|
||||
Event::Denied { reason, .. } => (format!("Refused: {reason}"), None),
|
||||
Event::Expired { .. } => ("Expired without an answer".into(), None),
|
||||
Event::Disconnected { .. } => ("Cancelled: the requester disconnected".into(), None),
|
||||
Event::Detached { .. } => ("The requester disconnected; carried on to the end".into(), None),
|
||||
Event::Finished { exit, seconds, .. } => {
|
||||
(format!("Finished with exit status {exit} after {seconds:.1}s"), None)
|
||||
}
|
||||
@@ -203,10 +202,6 @@ pub fn describe(event: &Event) -> (String, Option<Detail>) {
|
||||
}
|
||||
}
|
||||
|
||||
fn shown(detail: &Shown) -> Option<Detail> {
|
||||
Some(detail.to_detail()).filter(|d| !d.fields.is_empty() || !d.sections.is_empty())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -221,7 +216,7 @@ mod tests {
|
||||
requester: "slop-cannon".into(),
|
||||
op: "ssh".into(),
|
||||
summary: format!("ssh {id}"),
|
||||
detail: Detail::code("Command", "uptime").into(),
|
||||
detail: "Command: uptime".into(),
|
||||
label: None,
|
||||
}
|
||||
}
|
||||
@@ -283,18 +278,4 @@ mod tests {
|
||||
assert_eq!(histories[0].outcome, Outcome::Waiting);
|
||||
assert_eq!(histories[0].approved_by, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_requester_leaving_doesnt_hide_how_a_deploy_ended() {
|
||||
let approved = Event::Approved { id: "a".into(), by: ApprovedBy::Policy, approver: None, step: None };
|
||||
let mut records =
|
||||
vec![record("1", request("a")), record("2", approved), record("3", Event::Detached { id: "a".into() })];
|
||||
|
||||
let (histories, _) = gather(records.clone());
|
||||
assert_eq!(histories[0].outcome, Outcome::Running);
|
||||
|
||||
records.push(record("4", Event::Finished { id: "a".into(), exit: 0, seconds: 30.0 }));
|
||||
let (histories, _) = gather(records);
|
||||
assert_eq!(histories[0].outcome, Outcome::Succeeded);
|
||||
}
|
||||
}
|
||||
+1
-32
@@ -67,7 +67,7 @@ fn section_titles(detail: &Detail) -> String {
|
||||
detail.sections.iter().map(Section::title).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
fn describe(record: &Record) -> (String, Option<Detail>) {
|
||||
fn describe(record: &Record) -> (String, Option<String>) {
|
||||
history::describe(&record.event)
|
||||
}
|
||||
|
||||
@@ -270,35 +270,4 @@ mod tests {
|
||||
assert!(html.contains("needs-passkey"));
|
||||
assert!(html.contains("Needs passkey"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_shows_what_approvers_saw() {
|
||||
use crate::audit::{Event, Record, Shown};
|
||||
|
||||
let mut detail = Detail::code("Command", "uptime");
|
||||
detail.section(Section::diff("Diff", "@@ -1 +1 @@\n-b\n+a"));
|
||||
let records = vec![
|
||||
Record {
|
||||
time: "2026-11-27T10:00:00Z".into(),
|
||||
event: Event::Request {
|
||||
id: "abc".into(),
|
||||
requester: "slop-cannon".into(),
|
||||
op: "ssh".into(),
|
||||
summary: "ssh river".into(),
|
||||
detail: detail.into(),
|
||||
label: None,
|
||||
},
|
||||
},
|
||||
Record {
|
||||
time: "2026-11-27T10:00:01Z".into(),
|
||||
event: Event::Prepared { id: "abc".into(), detail: Shown::Text("Old: text".into()) },
|
||||
},
|
||||
];
|
||||
let (histories, _) = super::history::gather(records);
|
||||
|
||||
let html = request("broker", "token", "abc", None, Some(&histories[0]), 0).0;
|
||||
assert!(html.contains("<dt>Command</dt><dd class=\"neutral\"><code>uptime</code></dd>"), "{html}");
|
||||
assert!(html.contains("<span class=\"diff-add\">+a</span>"), "{html}");
|
||||
assert!(html.contains("Details (Text)") && html.contains("<pre>Old: text</pre>"), "{html}");
|
||||
}
|
||||
}
|
||||
@@ -80,7 +80,7 @@
|
||||
{% for record in records %}
|
||||
{% let (text, detail) = self::describe(record) %}
|
||||
<li>{% call time(record.time) %}{% endcall %} <span>{{ text }}</span>
|
||||
{%- if let Some(detail) = detail %}{% call detail(detail, false) %}{% endcall %}{% endif %}</li>
|
||||
{%- if let Some(detail) = detail %}<details><summary>Details</summary><pre>{{ detail }}</pre></details>{% endif %}</li>
|
||||
{% endfor %}
|
||||
</ol>
|
||||
{% endmacro %}
|
||||
|
||||
+14
-60
@@ -26,7 +26,7 @@ const FAKE_SSH: &str = r#"#!/bin/sh
|
||||
echo $$ > "${0%/*}/pid"
|
||||
echo "args: $*"
|
||||
while read -r line; do
|
||||
[ "$line" = block ] && exec sleep 60
|
||||
[ "$line" = block ] && while read -r _; do :; done
|
||||
echo "in: $line"
|
||||
done
|
||||
echo done >&2
|
||||
@@ -100,14 +100,9 @@ impl Client {
|
||||
}
|
||||
|
||||
fn ssh(command: &[&str]) -> Operation {
|
||||
ssh_with(command, None)
|
||||
}
|
||||
|
||||
fn ssh_with(command: &[&str], stdin: Option<&[u8]>) -> Operation {
|
||||
Operation::Ssh {
|
||||
destination: Destination::Node("river".parse().unwrap()),
|
||||
command: command.iter().map(|c| c.parse::<Arg>().unwrap()).collect(),
|
||||
stdin: stdin.map(<[u8]>::to_vec),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,9 +115,12 @@ async fn auto_runs_with_stdio_and_exit_status() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } }));
|
||||
|
||||
let mut client = Client::start(&broker, ssh_with(&["uptime", "-p"], Some(b"hello\n"))).await;
|
||||
let mut client = Client::start(&broker, ssh(&["uptime", "-p"])).await;
|
||||
let mut output = String::new();
|
||||
assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Policy, stdin: false });
|
||||
assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Policy, stdin: true });
|
||||
|
||||
client.send(ClientMessage::Stdin(b"hello\n".to_vec())).await;
|
||||
client.send(ClientMessage::StdinEnd).await;
|
||||
|
||||
assert_eq!(client.next(&mut output).await, finished(3));
|
||||
assert!(output.contains("-l deploy -- river.example.org uptime -p"), "{output}");
|
||||
@@ -150,8 +148,7 @@ async fn unknown_nodes_and_versions_are_rejected() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } }));
|
||||
|
||||
let operation =
|
||||
Operation::Ssh { destination: Destination::Node("sfh".parse().unwrap()), command: vec![], stdin: None };
|
||||
let operation = Operation::Ssh { destination: Destination::Node("sfh".parse().unwrap()), command: vec![] };
|
||||
let mut client = Client::start(&broker, operation).await;
|
||||
assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Error(e) if e.contains("unknown node")));
|
||||
|
||||
@@ -195,7 +192,7 @@ async fn invalid_messages_are_rejected() {
|
||||
let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } }));
|
||||
|
||||
let raw = |node: &str, extra: bool| {
|
||||
let mut ssh = json!({ "destination": { "node": node }, "command": [], "stdin": null });
|
||||
let mut ssh = json!({ "destination": { "node": node }, "command": [] });
|
||||
if extra {
|
||||
ssh["unexpected"] = json!(true);
|
||||
}
|
||||
@@ -214,52 +211,6 @@ async fn invalid_messages_are_rejected() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn approvers_see_the_whole_command_and_stdin_that_run() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let broker = broker(directory.path(), json!({ "ssh": { "action": "ask" } }));
|
||||
|
||||
// The words go to the remote shell joined with spaces, so that's what approvers see.
|
||||
let script = b"echo one\necho two\n";
|
||||
let mut client = Client::start(&broker, ssh_with(&["bash", "-s", "a b"], Some(script))).await;
|
||||
let id = pending_id(&mut client).await;
|
||||
|
||||
let detail = broker.queue.list()[0].detail.to_text();
|
||||
assert!(detail.starts_with("Command: bash -s a b\nStdin: 2 lines, 18 bytes\n"), "{detail}");
|
||||
assert!(detail.ends_with("Stdin:\necho one\necho two"), "{detail}");
|
||||
|
||||
slop_broker::approve::approve(&broker, &id, Decision::Once, "test", false).unwrap();
|
||||
let mut output = String::new();
|
||||
client.next(&mut output).await;
|
||||
assert_eq!(client.next(&mut output).await, finished(3));
|
||||
assert!(output.contains("in: echo one\nin: echo two\n"), "{output}");
|
||||
|
||||
// So is the audit log.
|
||||
let records = broker.audit.tail(10).unwrap();
|
||||
let slop_broker::audit::Event::Request { detail: logged, .. } = &records[0].event else { panic!("{records:?}") };
|
||||
assert_eq!(logged.to_text(), detail);
|
||||
|
||||
// Multi-line commands are shown as text rather than a one-line field.
|
||||
let mut client = Client::start(&broker, ssh(&["echo one\necho two"])).await;
|
||||
pending_id(&mut client).await;
|
||||
let detail = broker.queue.list()[0].detail.to_text();
|
||||
assert_eq!(detail, "Command:\necho one\necho two");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stdin_that_cant_be_shown_is_refused() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } }));
|
||||
|
||||
let binary = ssh_with(&["tar", "x"], Some(b"\xff\xfe"));
|
||||
let mut client = Client::start(&broker, binary).await;
|
||||
assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Error(e) if e.contains("UTF-8")));
|
||||
|
||||
let large = vec![b'x'; slop_broker::proto::MAX_SSH_SHOWN];
|
||||
let mut client = Client::start(&broker, ssh_with(&["cat"], Some(&large))).await;
|
||||
assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Error(e) if e.contains("KiB")));
|
||||
}
|
||||
|
||||
async fn pending_id(client: &mut Client) -> String {
|
||||
match client.next(&mut String::new()).await {
|
||||
ServerMessage::Pending { id, summary } => {
|
||||
@@ -284,12 +235,14 @@ async fn ask_waits_for_an_approver_and_leases_cover_repeats() {
|
||||
|
||||
slop_broker::approve::approve(&broker, &id, Decision::Lease(300), "test", false).unwrap();
|
||||
let mut output = String::new();
|
||||
assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Approver, stdin: false });
|
||||
assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Approver, stdin: true });
|
||||
|
||||
client.send(ClientMessage::StdinEnd).await;
|
||||
assert_eq!(client.next(&mut output).await, finished(3));
|
||||
|
||||
// Same scope, different command: covered by the lease.
|
||||
let mut client = Client::start(&broker, ssh(&["reboot"])).await;
|
||||
assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Lease, stdin: false });
|
||||
assert_eq!(client.next(&mut output).await, ServerMessage::Approved { by: ApprovedBy::Lease, stdin: true });
|
||||
|
||||
// Every step is in the audit log under the request's ID.
|
||||
let records = broker.audit.tail(10).unwrap();
|
||||
@@ -339,8 +292,9 @@ async fn disconnecting_kills_the_process() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let broker = broker(directory.path(), json!({ "ssh": { "action": "auto" } }));
|
||||
|
||||
let mut client = Client::start(&broker, ssh_with(&["true"], Some(b"block\n"))).await;
|
||||
let mut client = Client::start(&broker, ssh(&["true"])).await;
|
||||
client.next(&mut String::new()).await;
|
||||
client.send(ClientMessage::Stdin(b"block\n".to_vec())).await;
|
||||
|
||||
let pid_file = directory.path().join("pid");
|
||||
let mut pid = None;
|
||||
|
||||
+2
-7
@@ -122,16 +122,13 @@ fn secrets_are_looked_up_on_the_branch() {
|
||||
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();
|
||||
let rules = |keys: &str| {
|
||||
format!("{{ \"secrets/a.age\".publicKeys = [ \"age1dev\" ]; \"secrets/b.age\".publicKeys = [ {keys} ]; }}\n")
|
||||
};
|
||||
std::fs::write(work.join("secrets.nix"), rules("\"ssh-ed25519 AAAA box\"")).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"), rules("\"ssh-ed25519 AAAA box\" \"ssh-ed25519 BBBB box\"")).unwrap();
|
||||
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");
|
||||
@@ -157,8 +154,6 @@ fn secrets_are_looked_up_on_the_branch() {
|
||||
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()]));
|
||||
// Names come from comments on every path's keys.
|
||||
assert_eq!(context.names, std::collections::BTreeMap::from([("box".to_owned(), "ssh-ed25519 AAAA".to_owned())]));
|
||||
assert_eq!(&*context.commit, git(&work, &["rev-parse", "master"]));
|
||||
|
||||
let unknown = SecretRequest { blob: None, path: "secrets/new.age".parse().unwrap(), ..request };
|
||||
|
||||
Reference in new issue
Block a user