policy: Check the fields rules match
CI / Check (push) Successful in 4m57s

Each operation lists the scope fields its rules can match, so a rule
that names any other field, which never matched and so was silently
ignored, is refused: by the module's typed `match` options at
evaluation, and by `Config::validate`. The design doc now shows a
policy's per-operation settings and each operation's fields.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jackos1998andClaude Opus 5.5 committed 2026-11-24 23:12:37 +00:00
1 parent c26a74565c
commit e80b5b60fc
7 files changed
+128 -22

No files matched your search

+12 -7
View File
@@ -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,9 @@ 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. Name it in `OpName` (`src/policy.rs`), which policies are keyed by, and in the NixOS module's
`opNames`.
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.
+39 -9
View File
@@ -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.
+15 -6
View File
@@ -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).";
@@ -51,14 +63,11 @@ let
};
};
# The operations a policy can allow, as the broker names them (`OpName`)
opNames = [ "query" "ssh" "deploy" "builder" "build" "secret" ];
policyOpts = with lib.types; {
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' (submodule { options = genAttrs opNames (op: mkOpt' (nullOr (submodule opOpts)) null "Policy for `${op}`; null denies it."); })
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.";
};
};
+19
View File
@@ -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"
@@ -368,6 +381,12 @@ 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]
+13
View File
@@ -83,6 +83,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()?;
@@ -281,6 +293,7 @@ mod tests {
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!(
+14
View File
@@ -49,6 +49,20 @@ impl OpName {
}
}
/// 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
+16
View File
@@ -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();