Policies were keyed by any string, and rules could match any field, so a mistyped operation was silently denied and a mistyped field never matched. `OpName` names the operations and the scope fields their rules can match; the broker refuses anything else when loading its config, and the module's typed `ops` and `match` options refuse it first, at evaluation. The design doc shows a policy's per-operation settings and each operation's fields. `Parsed::new` fills in the defaults, so each operation sets only what it uses; what's found before approval moves to `Parsed::prepared`, and whether an operation is built in follows from its name. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e622fe7708
commit
21c2d4715e
11 files changed
+265
-164
No files matched your search
+21
-13
@@ -431,8 +431,8 @@ enum BuilderRequest {
|
||||
|
||||
## Policy, leases and limits
|
||||
|
||||
Policies are named, and each requester picks one, so requesters can share one. The module writes
|
||||
them from `services.slop-broker.policies` into the broker's TOML, for example:
|
||||
What a policy holds is in [the design](design.md#approvals-and-policy). The module writes
|
||||
`services.slop-broker.policies` into the broker's TOML, for example:
|
||||
|
||||
```toml
|
||||
[requesters.agent]
|
||||
@@ -443,7 +443,7 @@ policy = "agents"
|
||||
max_pending = 4
|
||||
auto_per_minute = 60
|
||||
|
||||
[policies.agents.ops.status]
|
||||
[policies.agents.ops.query]
|
||||
action = "auto"
|
||||
|
||||
[policies.agents.ops.ssh]
|
||||
@@ -456,8 +456,12 @@ action = "ask"
|
||||
confirm = "passkey"
|
||||
```
|
||||
|
||||
`Config::validate` (called by `Broker::new`) refuses a requester whose policy is missing, and the
|
||||
module asserts the same.
|
||||
- `OpName` names the operations, and `OpName::fields` the scope fields their rules can match.
|
||||
- serde refuses an unknown operation;
|
||||
- `Config::validate` (called by `Broker::new`) refuses a rule matching an unknown field, and a
|
||||
requester whose policy is missing;
|
||||
- the module types both, and asserts the policy exists;
|
||||
- `ops::plan` asserts, in debug builds, that the scopes it makes only use known fields.
|
||||
|
||||
### Deciding
|
||||
|
||||
@@ -557,8 +561,12 @@ none can be read as an option, and `--` comes before the hostname.
|
||||
1. Add the `Operation` variant in `src/proto.rs`, using validated types from `src/types.rs` (add new
|
||||
ones there), and an `OpResult` variant if it returns data. Bump `PROTOCOL_VERSION` if old clients
|
||||
would misread anything.
|
||||
2. `src/ops/<op>.rs` and a `plan` arm in `src/ops/mod.rs`: the config checks, a scope that is
|
||||
exactly what an approval should cover, and an `execute` arm.
|
||||
2. Name it in `OpName` (`src/policy.rs`), which policies are keyed by, with the fields its rules
|
||||
can match in `OpName::fields`; add both to the NixOS module's `opFields` and to the design's
|
||||
policy table.
|
||||
3. `src/ops/<op>.rs` and a `plan` arm in `src/ops/mod.rs`: the config checks, a scope that is
|
||||
exactly what an approval should cover, and an `execute` arm. `Parsed::new` defaults everything
|
||||
else.
|
||||
- Put anything shown but not part of the approval (commands, diffs) in `detail`: short facts
|
||||
as fields, anything with rows as a table or list, and preformatted text as a text section.
|
||||
Tone a field or row `Warn` when approvers must notice it, and mark the field `headline` if
|
||||
@@ -566,13 +574,13 @@ none can be read as an option, and `--` comes before the hostname.
|
||||
`Section::diff`.
|
||||
- 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
|
||||
operation in `prepares`, and fill in `detail` and `prepared` in a `prepare` arm; it runs
|
||||
before approval and only if policy wouldn't refuse.
|
||||
4. 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.
|
||||
5. Module options and sandbox changes; the deployment's policy entry follows in its own repo.
|
||||
6. Agent guide (`slop-tools.md`) and [`design.md`](design.md).
|
||||
5. Tests: parsing in the module, behaviour in `tests/broker.rs` with fakes of what it calls.
|
||||
6. Module options and sandbox changes; the deployment's policy entry follows in its own repo.
|
||||
7. Agent guide (`slop-tools.md`) and [`design.md`](design.md).
|
||||
|
||||
## Conventions and gotchas
|
||||
|
||||
|
||||
+39
-9
@@ -162,12 +162,43 @@ automatically where it can. Approvals show it marked as agent-supplied.
|
||||
|
||||
## Approvals and policy
|
||||
|
||||
- **Actions.** Each operation has a policy, configured in Nix: `auto`, `ask` or `deny`, plus the
|
||||
lease lengths it allows (`"5m"`, `"1h"`). The module writes the broker's configuration as TOML.
|
||||
- **Rules** override the operation's policy for narrower scopes, for example per node, per DNS
|
||||
name or per secret path.
|
||||
- **Named policies.** Policies are named in `services.slop-broker.policies`, and each requester
|
||||
picks one with `policy`, so several requesters (agents on different boxes, say) can share rules.
|
||||
Policies are named in `services.slop-broker.policies`, and each requester picks one with `policy`,
|
||||
so several requesters (agents on different boxes, say) can share one. A policy has request limits
|
||||
(`maxPending`, `autoPerMinute`) and an entry per operation in `ops`. An operation without an entry
|
||||
is denied; `requests` is always allowed.
|
||||
|
||||
Each operation's entry has its own settings:
|
||||
|
||||
| Option | Meaning |
|
||||
|---|---|
|
||||
| `action` | `auto` runs at once, `ask` waits for an approver, `deny` refuses |
|
||||
| `leases` | The lease lengths approvers are offered, such as `"5m"` or `"1h"` |
|
||||
| `confirm` | `"passkey"`: approving needs a fresh passkey in the web app |
|
||||
| `rules` | Exceptions, checked in order. The first whose `match` fits replaces `action`, and `leases` and `confirm` where it sets them |
|
||||
|
||||
```nix
|
||||
services.slop-broker.policies.agents.ops = {
|
||||
query.action = "auto";
|
||||
ssh = { action = "ask"; leases = [ "5m" "1h" ]; };
|
||||
deploy = {
|
||||
action = "ask";
|
||||
rules = [{ match.node = "router*"; action = "ask"; confirm = "passkey"; }];
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
Rules match fields of the request's scope with globs (`*` and `?`), and each operation has its
|
||||
own fields. The module and the broker refuse any other operation or field.
|
||||
|
||||
| Operation | Fields rules can match |
|
||||
|---|---|
|
||||
| `query` (`status`, `logs`, `failed`) | `target` (a node), or `host` and `port` (`--host`); `query` |
|
||||
| `ssh` | `target`, or `host` and `port` |
|
||||
| `deploy` | `node`, `profile`, `mode` (`switch` or `boot`), `commit`; checked per target, and the strictest answer applies |
|
||||
| `builder` | `commit`, `on_branch` (`true` or `false`), `for` (`deploy` or `build`) |
|
||||
| `build` | `attr`, `commit`; checked per attribute |
|
||||
| `secret` | `action` (`keys`, `read`, `set`, `generate`, `rekey`), `path` |
|
||||
|
||||
- **Answers.** An `ask` request waits for an answer from the [web app](#approvals-web-app) or
|
||||
`slop-approve` (on the broker's box, or over SSH from another), up to
|
||||
`services.slop-broker.timeout`. The answers are:
|
||||
@@ -175,9 +206,8 @@ automatically where it can. Approvals show it marked as agent-supplied.
|
||||
- a **lease**: the same scope is approved for a while, and only lengths the policy allows are
|
||||
offered;
|
||||
- **deny**.
|
||||
- **Passkeys.** An operation or rule can set `confirm = "passkey"`. Approving such a request then
|
||||
needs a fresh passkey in the web app, so `slop-approve` can only deny it. Deploys to routers are a
|
||||
typical use.
|
||||
- **Passkeys.** `slop-approve` can only deny a request that needs a passkey. Deploys to routers are
|
||||
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.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
{ lib, pkgs, config, ... }:
|
||||
let
|
||||
inherit (builtins) any head attrValues attrNames isAttrs isList length concatLists;
|
||||
inherit (lib) mkIf mkMerge mkOption mapAttrs mapAttrsToList filterAttrs optional optionals hasPrefix hasInfix unique concatStringsSep;
|
||||
inherit (lib) mkIf mkMerge mkOption genAttrs mapAttrs mapAttrsToList filterAttrs optional optionals hasPrefix hasInfix unique concatStringsSep;
|
||||
|
||||
mkOpt' = type: default: description: mkOption { inherit type default description; };
|
||||
mkBoolOpt' = default: description: mkOpt' lib.types.bool default description;
|
||||
@@ -34,7 +34,18 @@ let
|
||||
|
||||
duration = lib.types.strMatching "[1-9][0-9]*[smhd]";
|
||||
|
||||
opOpts = with lib.types; {
|
||||
# The operations a policy can allow, as the broker names them (`OpName`), and the scope fields
|
||||
# their rules can match (`OpName::fields`)
|
||||
opFields = {
|
||||
query = [ "target" "host" "port" "query" ];
|
||||
ssh = [ "target" "host" "port" ];
|
||||
deploy = [ "node" "profile" "mode" "commit" ];
|
||||
builder = [ "commit" "on_branch" "for" ];
|
||||
build = [ "attr" "commit" ];
|
||||
secret = [ "action" "path" ];
|
||||
};
|
||||
|
||||
opOpts = op: with lib.types; {
|
||||
options = {
|
||||
action = mkOpt' (enum [ "auto" "ask" "deny" ]) "ask" "What happens to a request.";
|
||||
leases = mkOpt' (listOf duration) [ ] "Lease lengths approvers are offered, like `5m` or `1h`.";
|
||||
@@ -42,7 +53,8 @@ let
|
||||
"Extra proof needed to approve: `passkey` means signing in again with a passkey in the web app.";
|
||||
rules = mkOpt' (listOf (submodule {
|
||||
options = {
|
||||
match = mkOpt' (attrsOf str) { } "Scope fields and the globs they must match.";
|
||||
match = mkOpt' (submodule { options = genAttrs opFields.${op} (field: mkOpt' (nullOr str) null "Glob that `${field}` must match."); })
|
||||
{ } "Scope fields and the globs they must match (`*` and `?`); unset fields match anything.";
|
||||
action = mkOpt' (enum [ "auto" "ask" "deny" ]) null "Action for matching requests.";
|
||||
leases = mkOpt' (nullOr (listOf duration)) null "Leases for matching requests (null keeps the default).";
|
||||
confirm = mkOpt' (nullOr (enum [ "passkey" ])) null "Extra proof for matching requests (null keeps the default).";
|
||||
@@ -55,7 +67,8 @@ let
|
||||
options = {
|
||||
maxPending = mkOpt' ints.positive 4 "Requests that may wait for approval at once, for each requester.";
|
||||
autoPerMinute = mkOpt' ints.positive 60 "Requests per minute that policy approves by itself, for each requester.";
|
||||
ops = mkOpt' (attrsOf (submodule opOpts)) { } "Policy per operation; unlisted operations are denied.";
|
||||
ops = mkOpt' (submodule { options = mapAttrs (op: _: mkOpt' (nullOr (submodule (opOpts op))) null "Policy for `${op}`; null denies it.") opFields; })
|
||||
{ } "Policy per operation; unlisted operations are denied. `requests` is always allowed.";
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
+30
-3
@@ -7,7 +7,7 @@ use anyhow::Context;
|
||||
use nix::unistd::{Group, Uid, User};
|
||||
use serde::{Deserialize, Deserializer};
|
||||
|
||||
use crate::policy::OpPolicy;
|
||||
use crate::policy::{OpName, OpPolicy};
|
||||
use crate::queue::parse_duration;
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
@@ -175,7 +175,7 @@ pub struct Policy {
|
||||
pub auto_per_minute: usize,
|
||||
/// Operations that may be used; anything missing is denied.
|
||||
#[serde(default)]
|
||||
pub ops: BTreeMap<String, OpPolicy>,
|
||||
pub ops: BTreeMap<OpName, OpPolicy>,
|
||||
}
|
||||
|
||||
fn default_requester_pending() -> usize {
|
||||
@@ -288,6 +288,19 @@ impl Config {
|
||||
requester.policy
|
||||
);
|
||||
}
|
||||
|
||||
for (name, policy) in &self.policies {
|
||||
for (op, settings) in &policy.ops {
|
||||
for field in settings.rules.iter().flat_map(|r| r.matches.keys()) {
|
||||
anyhow::ensure!(
|
||||
op.fields().contains(&field.as_str()),
|
||||
"policy {name:?}: {op} rules can't match {field:?}; its fields are {}",
|
||||
op.fields().join(", ")
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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"
|
||||
@@ -323,6 +336,7 @@ impl Config {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::policy::OpName;
|
||||
|
||||
/// The layout the NixOS module writes.
|
||||
#[test]
|
||||
@@ -355,7 +369,7 @@ mod tests {
|
||||
config.validate().unwrap();
|
||||
assert_eq!(config.timeout, 300);
|
||||
|
||||
let ssh = &config.policy("slop-cannon").unwrap().ops["ssh"];
|
||||
let ssh = &config.policy("slop-cannon").unwrap().ops[&OpName::Ssh];
|
||||
assert_eq!(ssh.leases, [300, 3600]);
|
||||
assert_eq!(ssh.rules[0].leases, Some(vec![600]));
|
||||
|
||||
@@ -367,5 +381,18 @@ mod tests {
|
||||
let mut missing = config.clone();
|
||||
missing.policies.clear();
|
||||
assert!(missing.validate().is_err());
|
||||
|
||||
let mut misspelt = config.clone();
|
||||
let rules = &mut misspelt.policies.get_mut("agent").unwrap().ops.get_mut(&OpName::Ssh).unwrap().rules;
|
||||
rules[0].matches = BTreeMap::from([("node".to_owned(), "river".to_owned())]);
|
||||
let error = misspelt.validate().unwrap_err().to_string();
|
||||
assert!(error.contains("ssh rules can't match \"node\"; its fields are target, host, port"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_operations_are_refused() {
|
||||
let config = "approve_socket = \"/a\"\napprover_group = \"g\"\n[policies.agent.ops.sssh]\naction = \"ask\"\n";
|
||||
let error = toml::from_str::<Config>(config).unwrap_err().to_string();
|
||||
assert!(error.contains("unknown variant `sssh`"), "{error}");
|
||||
}
|
||||
}
|
||||
+7
-16
@@ -19,7 +19,7 @@ use crate::builder::{self, BuildRequest};
|
||||
use crate::config::{CacheConfig, DeployConfig, SshConfig};
|
||||
use crate::detail::{Column, Detail, Row, Section, Tone};
|
||||
use crate::exec::{self, Io};
|
||||
use crate::policy::Limits;
|
||||
use crate::policy::OpName;
|
||||
use crate::proto::{Operation, ServerMessage};
|
||||
use crate::server::Broker;
|
||||
|
||||
@@ -51,20 +51,11 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
|
||||
attrs.iter().map(|a| json!({ "attr": &**a, "commit": &**commit }).as_object().unwrap().clone()).collect();
|
||||
let scope = json!({ "attrs": names, "commit": &**commit });
|
||||
|
||||
let summary = format!("build {names} at {}", commit.short());
|
||||
let detail = super::deploy::building(commit, "Outputs");
|
||||
Ok(Parsed {
|
||||
op: "build",
|
||||
scope: scope.as_object().unwrap().clone(),
|
||||
rule_scopes,
|
||||
summary: format!("build {names} at {}", commit.short()),
|
||||
detail: super::deploy::building(commit, "Outputs"),
|
||||
limits: Limits::default(),
|
||||
sensitive: false,
|
||||
stdin: false,
|
||||
builtin: false,
|
||||
prepared: None,
|
||||
description: None,
|
||||
secret: None,
|
||||
operation,
|
||||
..Parsed::new(OpName::Build, scope.as_object().unwrap().clone(), summary, detail, operation)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -81,7 +72,7 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
|
||||
let paths: Vec<&str> = built.outputs.iter().flat_map(|o| &o.paths).map(String::as_str).collect();
|
||||
let sizes = closure_sizes(deploy, &paths, &io.cancel).await?;
|
||||
|
||||
let description = parsed.description.as_ref().context("the commit wasn't described")?;
|
||||
let description = parsed.prepared.description.as_ref().context("the commit wasn't described")?;
|
||||
let mut detail = Detail::new();
|
||||
super::source(&mut detail, commit, description);
|
||||
let rows = built.outputs.iter().flat_map(|output| {
|
||||
@@ -97,14 +88,14 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
|
||||
));
|
||||
|
||||
parsed.detail = detail.limited();
|
||||
parsed.prepared = Some(built);
|
||||
parsed.prepared.build = Some(built);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn execute(broker: &Broker, parsed: &Parsed, io: &mut Io) -> Result<i32> {
|
||||
let (ssh, deploy, cache) = configs(broker)?;
|
||||
let ssh = &*ssh;
|
||||
let built = parsed.prepared.as_ref().context("nothing was built")?;
|
||||
let built = parsed.prepared.build.as_ref().context("nothing was built")?;
|
||||
let paths: Vec<&str> = built.outputs.iter().flat_map(|o| &o.paths).map(String::as_str).collect();
|
||||
|
||||
// Roots first, so the cache's garbage collection can't take the paths as they arrive.
|
||||
|
||||
+7
-16
@@ -19,7 +19,7 @@ use crate::builder::{self, BuildRequest, BuiltProfile};
|
||||
use crate::config::{DeployConfig, SshConfig};
|
||||
use crate::detail::{Column, Detail, Field, Row, Section, Tone};
|
||||
use crate::exec::{self, Io, Output};
|
||||
use crate::policy::Limits;
|
||||
use crate::policy::OpName;
|
||||
use crate::proto::{Destination, Operation};
|
||||
use crate::server::Broker;
|
||||
|
||||
@@ -66,20 +66,11 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
|
||||
.collect();
|
||||
let scope = json!({ "targets": names, "mode": mode(*boot), "commit": &**commit });
|
||||
|
||||
let summary = format!("deploy {names} ({}) at {}", mode(*boot), commit.short());
|
||||
let detail = building(commit, "Changes");
|
||||
Ok(Parsed {
|
||||
op: "deploy",
|
||||
scope: scope.as_object().unwrap().clone(),
|
||||
rule_scopes,
|
||||
summary: format!("deploy {names} ({}) at {}", mode(*boot), commit.short()),
|
||||
detail: building(commit, "Changes"),
|
||||
limits: Limits::default(),
|
||||
sensitive: false,
|
||||
stdin: false,
|
||||
builtin: false,
|
||||
prepared: None,
|
||||
description: None,
|
||||
secret: None,
|
||||
operation,
|
||||
..Parsed::new(OpName::Deploy, scope.as_object().unwrap().clone(), summary, detail, operation)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -114,7 +105,7 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
|
||||
}))
|
||||
.await;
|
||||
|
||||
let description = parsed.description.as_ref().context("the commit wasn't described")?;
|
||||
let description = parsed.prepared.description.as_ref().context("the commit wasn't described")?;
|
||||
let mut detail = Detail::new();
|
||||
super::source(&mut detail, commit, description);
|
||||
for report in reports {
|
||||
@@ -122,7 +113,7 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
|
||||
}
|
||||
|
||||
parsed.detail = detail.limited();
|
||||
parsed.prepared = Some(built);
|
||||
parsed.prepared.build = Some(built);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -130,7 +121,7 @@ pub async fn execute(broker: &Broker, parsed: &Parsed, io: &mut Io) -> Result<i3
|
||||
let Operation::Deploy { boot, .. } = &parsed.operation else { unreachable!() };
|
||||
let (ssh, _) = configs(broker)?;
|
||||
let ssh = &*ssh;
|
||||
let built = parsed.prepared.as_ref().context("nothing was built")?;
|
||||
let built = parsed.prepared.build.as_ref().context("nothing was built")?;
|
||||
|
||||
let run = &crate::queue::new_id();
|
||||
let (out, cancel) = (&io.out, &io.cancel);
|
||||
|
||||
+65
-84
@@ -6,7 +6,7 @@ use serde_json::{Map, Value, json};
|
||||
use crate::builder::Description;
|
||||
use crate::detail::{Detail, Field, Section, Tone};
|
||||
use crate::exec::Io;
|
||||
use crate::policy::Limits;
|
||||
use crate::policy::{Limits, OpName};
|
||||
use crate::proto::{LeaseSummary, OpResult, Operation, PendingSummary};
|
||||
use crate::server::Broker;
|
||||
use crate::types::CommitId;
|
||||
@@ -17,8 +17,14 @@ pub mod query;
|
||||
pub mod secret;
|
||||
pub mod ssh;
|
||||
|
||||
/// A request, checked and ready for policy and approval. Everything after planning (policy, the
|
||||
/// queue, approvers, the audit log, the web app) handles every operation through these fields
|
||||
/// alone; only `operation` and `prepared` are particular to one. Each operation fills in what it
|
||||
/// needs, and [`Parsed::new`] gives the rest their defaults.
|
||||
pub struct Parsed {
|
||||
pub op: &'static str,
|
||||
/// The name policies know it by. Usually it follows from `operation`, but a builder approval
|
||||
/// ([`builder_gate`]) carries the deploy or build it's for, as `builder`.
|
||||
pub op: OpName,
|
||||
/// What an approval covers; also what policy rules match against.
|
||||
pub scope: Map<String, Value>,
|
||||
/// If set, policy rules are checked against each of these instead, and the strictest
|
||||
@@ -31,23 +37,43 @@ pub struct Parsed {
|
||||
pub sensitive: bool,
|
||||
/// Whether the operation reads the requester's stdin.
|
||||
pub stdin: bool,
|
||||
/// Needs no policy or approval.
|
||||
pub builtin: bool,
|
||||
/// What [`prepare`] made before approval.
|
||||
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>,
|
||||
/// What was looked up or built before approval.
|
||||
pub prepared: Prepared,
|
||||
pub operation: Operation,
|
||||
}
|
||||
|
||||
impl Parsed {
|
||||
pub fn new(op: OpName, scope: Map<String, Value>, summary: String, detail: Detail, operation: Operation) -> Parsed {
|
||||
Parsed {
|
||||
op,
|
||||
scope,
|
||||
rule_scopes: Vec::new(),
|
||||
summary,
|
||||
detail,
|
||||
limits: Limits::default(),
|
||||
sensitive: false,
|
||||
stdin: false,
|
||||
prepared: Prepared::default(),
|
||||
operation,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn lease_key(&self) -> String {
|
||||
format!("{} {}", self.op, Value::Object(self.scope.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
/// What the broker found out before approval; each operation uses only its own.
|
||||
#[derive(Default)]
|
||||
pub struct Prepared {
|
||||
/// The commit, as [`describe`] found it, for operations that build.
|
||||
pub description: Option<Description>,
|
||||
/// What the builder built, for operations that build.
|
||||
pub build: Option<crate::builder::BuildResult>,
|
||||
/// What the main branch says about a secret, as [`prepare`] found it.
|
||||
pub secret: Option<crate::builder::SecretContext>,
|
||||
}
|
||||
|
||||
/// What an operation produced: its exit status and any structured result.
|
||||
pub struct Outcome {
|
||||
pub exit: i32,
|
||||
@@ -61,6 +87,18 @@ impl From<i32> for Outcome {
|
||||
}
|
||||
|
||||
pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
|
||||
let parsed = plan_op(broker, operation)?;
|
||||
debug_assert!(fields_known(&parsed), "{} scope fields aren't all in OpName::fields", parsed.op);
|
||||
Ok(parsed)
|
||||
}
|
||||
|
||||
/// Whether rules can name every field they're matched against.
|
||||
fn fields_known(parsed: &Parsed) -> bool {
|
||||
let scopes = if parsed.rule_scopes.is_empty() { std::slice::from_ref(&parsed.scope) } else { &parsed.rule_scopes };
|
||||
scopes.iter().flat_map(|s| s.keys()).all(|k| parsed.op.fields().contains(&k.as_str()))
|
||||
}
|
||||
|
||||
fn plan_op(broker: &Broker, operation: Operation) -> Result<Parsed> {
|
||||
match &operation {
|
||||
Operation::Ssh { destination, command } => {
|
||||
let config = &broker.targets.ssh()?;
|
||||
@@ -68,21 +106,9 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
|
||||
let shown =
|
||||
if command.is_empty() { "(no command)".to_owned() } else { truncate(&shell_quote(command), 1000) };
|
||||
|
||||
Ok(Parsed {
|
||||
op: "ssh",
|
||||
scope: ssh::scope(destination),
|
||||
summary: format!("ssh {}", ssh::describe(destination)),
|
||||
detail: Detail::code("Command", shown),
|
||||
limits: Limits::default(),
|
||||
sensitive: false,
|
||||
stdin: true,
|
||||
builtin: false,
|
||||
rule_scopes: Vec::new(),
|
||||
prepared: None,
|
||||
description: None,
|
||||
secret: None,
|
||||
operation,
|
||||
})
|
||||
let summary = format!("ssh {}", ssh::describe(destination));
|
||||
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()?;
|
||||
@@ -90,40 +116,16 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
|
||||
let mut scope = ssh::scope(destination);
|
||||
scope.insert("query".into(), Value::from(query::name(query)));
|
||||
|
||||
Ok(Parsed {
|
||||
op: "query",
|
||||
scope,
|
||||
summary: format!("{} on {}", query::name(query), ssh::describe(destination)),
|
||||
detail: Detail::code("Command", shell_quote(&query::remote_command(query))),
|
||||
limits: Limits::default(),
|
||||
sensitive: false,
|
||||
stdin: false,
|
||||
builtin: false,
|
||||
rule_scopes: Vec::new(),
|
||||
prepared: None,
|
||||
description: None,
|
||||
secret: None,
|
||||
operation,
|
||||
})
|
||||
let summary = format!("{} on {}", query::name(query), ssh::describe(destination));
|
||||
let detail = Detail::code("Command", shell_quote(&query::remote_command(query)));
|
||||
Ok(Parsed::new(OpName::Query, scope, summary, detail, 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(),
|
||||
summary: "list requests".into(),
|
||||
detail: Detail::new(),
|
||||
limits: Limits::default(),
|
||||
sensitive: false,
|
||||
stdin: false,
|
||||
builtin: true,
|
||||
rule_scopes: Vec::new(),
|
||||
prepared: None,
|
||||
description: None,
|
||||
secret: None,
|
||||
operation,
|
||||
}),
|
||||
Operation::Requests => {
|
||||
Ok(Parsed::new(OpName::Requests, Map::new(), "list requests".into(), Detail::new(), operation))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,7 +164,7 @@ pub fn builder_gate(parsed: &Parsed, description: &Description) -> Result<Parsed
|
||||
let rule_scope = json!({
|
||||
"commit": &**commit,
|
||||
"on_branch": description.on_branch.to_string(),
|
||||
"for": parsed.op,
|
||||
"for": parsed.op.as_str(),
|
||||
});
|
||||
|
||||
let mut detail = Detail::of("For", &parsed.summary);
|
||||
@@ -171,20 +173,10 @@ pub fn builder_gate(parsed: &Parsed, description: &Description) -> Result<Parsed
|
||||
detail.section(Section::diff("Diff", &description.diff));
|
||||
}
|
||||
|
||||
let summary = format!("run the builder for {}", parsed.summary);
|
||||
Ok(Parsed {
|
||||
op: "builder",
|
||||
scope: Map::new(),
|
||||
rule_scopes: vec![rule_scope.as_object().unwrap().clone()],
|
||||
summary: format!("run the builder for {}", parsed.summary),
|
||||
detail: detail.limited(),
|
||||
limits: Limits::default(),
|
||||
sensitive: false,
|
||||
stdin: false,
|
||||
builtin: false,
|
||||
prepared: None,
|
||||
description: None,
|
||||
secret: None,
|
||||
operation: parsed.operation.clone(),
|
||||
..Parsed::new(OpName::Builder, Map::new(), summary, detail.limited(), parsed.operation.clone())
|
||||
})
|
||||
}
|
||||
|
||||
@@ -290,21 +282,9 @@ mod tests {
|
||||
#[test]
|
||||
fn the_builder_gate_shows_the_diff_and_leases_cover_any_commit() {
|
||||
let commit: CommitId = "0123456789abcdef0123456789abcdef01234567".parse().unwrap();
|
||||
let parsed = Parsed {
|
||||
op: "build",
|
||||
scope: Map::new(),
|
||||
rule_scopes: Vec::new(),
|
||||
summary: "build hello at 0123456789ab".into(),
|
||||
detail: Detail::new(),
|
||||
limits: Limits::default(),
|
||||
sensitive: false,
|
||||
stdin: false,
|
||||
builtin: false,
|
||||
prepared: None,
|
||||
description: None,
|
||||
secret: None,
|
||||
operation: Operation::Build { attrs: vec!["hello".parse().unwrap()], commit },
|
||||
};
|
||||
let operation = Operation::Build { attrs: vec!["hello".parse().unwrap()], commit };
|
||||
let parsed =
|
||||
Parsed::new(OpName::Build, Map::new(), "build hello at 0123456789ab".into(), Detail::new(), operation);
|
||||
let description = Description {
|
||||
log: "0123456 pkgs: Add hello\n".into(),
|
||||
stat: " pkgs/hello.nix | 1 +\n".into(),
|
||||
@@ -313,10 +293,11 @@ mod tests {
|
||||
};
|
||||
|
||||
let gate = builder_gate(&parsed, &description).unwrap();
|
||||
assert_eq!(gate.op, "builder");
|
||||
assert_eq!(gate.op, OpName::Builder);
|
||||
assert_eq!(gate.lease_key(), "builder {}");
|
||||
assert_eq!(gate.rule_scopes[0]["on_branch"], "false");
|
||||
assert_eq!(gate.rule_scopes[0]["for"], "build");
|
||||
assert!(fields_known(&gate));
|
||||
assert!(gate.summary.starts_with("run the builder for build hello"));
|
||||
let text = gate.detail.to_text();
|
||||
assert!(
|
||||
|
||||
+3
-12
@@ -15,7 +15,7 @@ use crate::builder::{SecretContext, SecretRequest};
|
||||
use crate::config::SecretsConfig;
|
||||
use crate::detail::{Column, Detail, Field, Row, Section, Tone};
|
||||
use crate::exec::Io;
|
||||
use crate::policy::Limits;
|
||||
use crate::policy::{Limits, OpName};
|
||||
use crate::proto::{GenKind, OpResult, Operation, SecretOp, ServerMessage, Target};
|
||||
use crate::server::Broker;
|
||||
use crate::types::{ObjectId, Recipient, RulesPath, SecretPath};
|
||||
@@ -59,20 +59,11 @@ pub fn plan(broker: &Broker, operation: Operation) -> Result<Parsed> {
|
||||
|
||||
let read = matches!(op, SecretOp::Read { .. });
|
||||
Ok(Parsed {
|
||||
op: "secret",
|
||||
scope,
|
||||
summary: summary(op),
|
||||
detail: Detail::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,
|
||||
..Parsed::new(OpName::Secret, scope, summary(op), Detail::new(), operation)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -115,7 +106,7 @@ pub async fn prepare(broker: &Broker, parsed: &mut Parsed, io: &Io) -> Result<()
|
||||
let (detail, sensitive) = describe(op, &context, config, &own);
|
||||
parsed.detail = detail;
|
||||
parsed.sensitive |= sensitive;
|
||||
parsed.secret = Some(context);
|
||||
parsed.prepared.secret = Some(context);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,59 @@ pub enum Confirm {
|
||||
Passkey,
|
||||
}
|
||||
|
||||
/// An operation, as policies, leases and the audit log name it.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum OpName {
|
||||
Query,
|
||||
Ssh,
|
||||
Deploy,
|
||||
/// Using the builder, which deploys and builds ask for first.
|
||||
Builder,
|
||||
Build,
|
||||
Secret,
|
||||
Requests,
|
||||
}
|
||||
|
||||
impl OpName {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
OpName::Query => "query",
|
||||
OpName::Ssh => "ssh",
|
||||
OpName::Deploy => "deploy",
|
||||
OpName::Builder => "builder",
|
||||
OpName::Build => "build",
|
||||
OpName::Secret => "secret",
|
||||
OpName::Requests => "requests",
|
||||
}
|
||||
}
|
||||
|
||||
/// The scope fields rules can match: for operations with a rule scope per part (a deploy's
|
||||
/// targets, a build's attributes), that scope's fields.
|
||||
pub fn fields(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
OpName::Query => &["target", "host", "port", "query"],
|
||||
OpName::Ssh => &["target", "host", "port"],
|
||||
OpName::Deploy => &["node", "profile", "mode", "commit"],
|
||||
OpName::Builder => &["commit", "on_branch", "for"],
|
||||
OpName::Build => &["attr", "commit"],
|
||||
OpName::Secret => &["action", "path"],
|
||||
OpName::Requests => &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// Needs no policy or approval.
|
||||
pub fn builtin(self) -> bool {
|
||||
self == OpName::Requests
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for OpName {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct OpPolicy {
|
||||
|
||||
+7
-7
@@ -183,7 +183,7 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
|
||||
};
|
||||
|
||||
// Built-in operations only read the broker's own state, so they aren't logged.
|
||||
let builtin = parsed.builtin;
|
||||
let builtin = parsed.op.builtin();
|
||||
let log = |event| {
|
||||
if !builtin {
|
||||
broker.audit.log(event)
|
||||
@@ -193,7 +193,7 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
|
||||
log(Event::Request {
|
||||
id: id.clone(),
|
||||
requester: requester.to_owned(),
|
||||
op: parsed.op.to_owned(),
|
||||
op: parsed.op.to_string(),
|
||||
summary: parsed.summary.clone(),
|
||||
detail: parsed.detail.to_text(),
|
||||
label: label.clone(),
|
||||
@@ -256,7 +256,7 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
|
||||
io.out
|
||||
.info(format!("use of the builder approved by {}", approver.as_deref().unwrap_or(approved_by_name(by))))
|
||||
.await;
|
||||
parsed.description = Some(description);
|
||||
parsed.prepared.description = Some(description);
|
||||
}
|
||||
|
||||
if let Err(error) = ops::prepare(broker, &mut parsed, io).await {
|
||||
@@ -281,7 +281,7 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
|
||||
log(Event::Approved { id: id.clone(), by: approved_by, approver, step: None });
|
||||
io.out.send(ServerMessage::Approved { by: approved_by, stdin: parsed.stdin }).await;
|
||||
|
||||
let (start, builtin) = (std::time::Instant::now(), parsed.builtin);
|
||||
let (start, builtin) = (std::time::Instant::now(), parsed.op.builtin());
|
||||
let result = ops::execute(broker, requester, parsed, io).await;
|
||||
|
||||
let log = |event| {
|
||||
@@ -311,7 +311,7 @@ async fn process(broker: &Broker, requester: &str, request: Request, io: &mut Io
|
||||
/// 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"))?;
|
||||
let op = settings.ops.get(parsed.op);
|
||||
let op = settings.ops.get(&parsed.op);
|
||||
if parsed.rule_scopes.is_empty() {
|
||||
return Ok(policy::evaluate(op, &parsed.scope, parsed.limits));
|
||||
}
|
||||
@@ -328,7 +328,7 @@ async fn authorize(
|
||||
label: Option<String>,
|
||||
io: &mut Io,
|
||||
) -> Result<Option<(ApprovedBy, Option<String>)>, ServerMessage> {
|
||||
if parsed.builtin {
|
||||
if parsed.op.builtin() {
|
||||
return Ok(Some((ApprovedBy::Policy, None)));
|
||||
}
|
||||
|
||||
@@ -351,7 +351,7 @@ async fn authorize(
|
||||
|
||||
let pending = NewRequest {
|
||||
requester: requester.to_owned(),
|
||||
op: parsed.op.to_owned(),
|
||||
op: parsed.op.to_string(),
|
||||
lease_key: key,
|
||||
summary: parsed.summary.clone(),
|
||||
detail: parsed.detail.clone(),
|
||||
|
||||
@@ -170,6 +170,22 @@ async fn builds_need_a_cache() {
|
||||
assert!(matches!(client.next(&mut String::new()).await, ServerMessage::Error(e) if e.contains("not configured")));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn deploys_have_a_rule_scope_per_target() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let broker = broker(directory.path(), json!({ "deploy": { "action": "ask" } }));
|
||||
|
||||
let operation = Operation::Deploy {
|
||||
targets: vec!["river".parse().unwrap()],
|
||||
commit: "0123456789abcdef0123456789abcdef01234567".parse().unwrap(),
|
||||
boot: true,
|
||||
};
|
||||
let parsed = slop_broker::ops::plan(&broker, operation).unwrap();
|
||||
assert_eq!(parsed.rule_scopes.len(), 1);
|
||||
assert_eq!(parsed.rule_scopes[0]["node"], "river");
|
||||
assert_eq!(parsed.rule_scopes[0]["mode"], "boot");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_messages_are_rejected() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
|
||||
Reference in new issue
Block a user