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>
399 lines
13 KiB
Rust
399 lines
13 KiB
Rust
//! Broker configuration: TOML, generated by the `my.slop-broker` NixOS module. Durations are
|
|
//! written like `"5m"` or `"1h"` (plain numbers are seconds).
|
|
use std::collections::BTreeMap;
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use anyhow::Context;
|
|
use nix::unistd::{Group, Uid, User};
|
|
use serde::{Deserialize, Deserializer};
|
|
|
|
use crate::policy::{OpName, OpPolicy};
|
|
use crate::queue::parse_duration;
|
|
|
|
#[derive(Debug, Clone, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Config {
|
|
// Who may ask, what they may do, and how long they wait
|
|
pub requesters: BTreeMap<String, Requester>,
|
|
/// Named policies; several requesters can share one.
|
|
#[serde(default)]
|
|
pub policies: BTreeMap<String, Policy>,
|
|
/// Seconds a request waits for an approver.
|
|
#[serde(default = "default_timeout", deserialize_with = "duration")]
|
|
pub timeout: u64,
|
|
/// Pending requests across all requesters.
|
|
#[serde(default = "default_max_pending")]
|
|
pub max_pending: usize,
|
|
|
|
// Where requests arrive
|
|
#[serde(default)]
|
|
pub vsock_port: Option<u32>,
|
|
/// Unix socket for local requesters, identified by UID.
|
|
#[serde(default)]
|
|
pub request_socket: Option<PathBuf>,
|
|
/// Requesters and approvers on other boxes, over SSH.
|
|
#[serde(default)]
|
|
pub remote: Option<RemoteConfig>,
|
|
|
|
// Where approvers answer
|
|
pub approve_socket: PathBuf,
|
|
/// Group whose members may answer requests.
|
|
pub approver_group: String,
|
|
#[serde(default)]
|
|
pub web: Option<WebConfig>,
|
|
|
|
// Operations, each enabled by its section
|
|
#[serde(default)]
|
|
pub ssh: Option<SshConfig>,
|
|
#[serde(default)]
|
|
pub deploy: Option<DeployConfig>,
|
|
#[serde(default)]
|
|
pub cache: Option<CacheConfig>,
|
|
#[serde(default)]
|
|
pub secrets: Option<SecretsConfig>,
|
|
|
|
#[serde(default)]
|
|
pub audit_log: Option<PathBuf>,
|
|
}
|
|
|
|
fn default_timeout() -> u64 {
|
|
300
|
|
}
|
|
|
|
fn default_max_pending() -> usize {
|
|
64
|
|
}
|
|
|
|
/// Age secrets (see [`crate::ops::secret`]). Needs `deploy`, whose builder reads the main branch.
|
|
#[derive(Debug, Clone, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct SecretsConfig {
|
|
/// The broker's age identity; relative paths are resolved in `$CREDENTIALS_DIRECTORY`.
|
|
pub identity: PathBuf,
|
|
/// The agenix rules file in the repository the builder fetches.
|
|
#[serde(default = "default_rules")]
|
|
pub rules: crate::types::RulesPath,
|
|
/// Names for well-known recipients, only used to label them in approvals.
|
|
#[serde(default)]
|
|
pub names: BTreeMap<String, crate::types::Recipient>,
|
|
}
|
|
|
|
fn default_rules() -> crate::types::RulesPath {
|
|
"secrets.nix".parse().unwrap()
|
|
}
|
|
|
|
/// The approvals web app (see [`crate::web`]): approvers sign in through an OpenID Connect
|
|
/// provider, and get Web Push notifications.
|
|
#[derive(Debug, Clone, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct WebConfig {
|
|
/// Address to listen on, like `[::]:8095`; only the reverse proxy should reach it.
|
|
pub listen: std::net::SocketAddr,
|
|
/// Public URL of the app, like `https://approve.example.org`.
|
|
pub url: String,
|
|
|
|
/// OpenID Connect issuer.
|
|
pub issuer: String,
|
|
pub client_id: String,
|
|
/// Client secret; relative paths are resolved in `$CREDENTIALS_DIRECTORY`.
|
|
pub client_secret: PathBuf,
|
|
/// Only members of this group (the ID token's `groups` claim) may sign in.
|
|
pub group: String,
|
|
|
|
/// How long a session lasts without being used.
|
|
#[serde(default = "default_session", deserialize_with = "duration")]
|
|
pub session: u64,
|
|
/// Where sessions, push subscriptions and the push signing key are kept.
|
|
pub state_dir: PathBuf,
|
|
}
|
|
|
|
fn default_session() -> u64 {
|
|
7 * 86400
|
|
}
|
|
|
|
/// Deploys: a builder evaluates and builds commits, then the broker copies and activates them
|
|
/// over SSH like deploy-rs does. Needs `ssh`, whose key and options it uses.
|
|
#[derive(Debug, Clone, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct DeployConfig {
|
|
/// Runs `slop-broker builder` as its forced command, as a user without keys.
|
|
pub builder: SshTarget,
|
|
/// `nix`, for copying closures to nodes.
|
|
pub nix: PathBuf,
|
|
/// Writable directory for `nix`'s cache.
|
|
pub cache: PathBuf,
|
|
}
|
|
|
|
/// The binary cache that `slop build` pushes to: a Nix store reached over SSH (`ssh-ng`), whose
|
|
/// key's forced command allows only the store protocol and adding GC roots. Needs `deploy`, whose
|
|
/// builder it uses.
|
|
#[derive(Debug, Clone, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct CacheConfig {
|
|
pub hostname: String,
|
|
pub user: String,
|
|
#[serde(default)]
|
|
pub ssh_opts: Vec<String>,
|
|
/// Private key; relative paths are resolved in `$CREDENTIALS_DIRECTORY`.
|
|
pub key: PathBuf,
|
|
}
|
|
|
|
/// Requesters and approvers on other boxes, connecting over SSH (see [`crate::remote`]).
|
|
#[derive(Debug, Clone, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct RemoteConfig {
|
|
pub socket: PathBuf,
|
|
/// The SSH user whose forced commands connect to the socket.
|
|
pub user: String,
|
|
/// Approvers by name; requesters opt in with `remote`.
|
|
#[serde(default)]
|
|
pub approvers: Vec<String>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Requester {
|
|
#[serde(default)]
|
|
pub vsock_cid: Option<u32>,
|
|
#[serde(default)]
|
|
pub uid: Option<u32>,
|
|
/// Connects over SSH, with a key that names it.
|
|
#[serde(default)]
|
|
pub remote: bool,
|
|
/// The name of its entry in `policies`.
|
|
pub policy: String,
|
|
}
|
|
|
|
/// What a requester may do. Limits are counted for each requester on its own, as are leases.
|
|
#[derive(Debug, Clone, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Policy {
|
|
#[serde(default = "default_requester_pending")]
|
|
pub max_pending: usize,
|
|
/// Requests per minute that policy approves automatically.
|
|
#[serde(default = "default_auto_per_minute")]
|
|
pub auto_per_minute: usize,
|
|
/// Operations that may be used; anything missing is denied.
|
|
#[serde(default)]
|
|
pub ops: BTreeMap<OpName, OpPolicy>,
|
|
}
|
|
|
|
fn default_requester_pending() -> usize {
|
|
4
|
|
}
|
|
|
|
fn default_auto_per_minute() -> usize {
|
|
60
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct SshConfig {
|
|
pub ssh: PathBuf,
|
|
/// Private key; relative paths are resolved in `$CREDENTIALS_DIRECTORY`.
|
|
pub key: PathBuf,
|
|
pub known_hosts: PathBuf,
|
|
/// The main branch's deploy-rs nodes, by name. Never configured: `targets::Targets` fills it
|
|
/// in from the builder.
|
|
#[serde(skip)]
|
|
pub targets: BTreeMap<String, SshTarget>,
|
|
}
|
|
|
|
/// A box as SSH reaches it: a node, the builder or the cache.
|
|
#[derive(Debug, Clone, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct SshTarget {
|
|
pub hostname: String,
|
|
pub user: String,
|
|
#[serde(default)]
|
|
pub ssh_opts: Vec<String>,
|
|
/// How `user` becomes root, followed by the user name (deploy-rs's `sudo`); nodes only.
|
|
#[serde(default = "default_sudo")]
|
|
pub sudo: String,
|
|
}
|
|
|
|
/// deploy-rs's default.
|
|
pub fn default_sudo() -> String {
|
|
"sudo -u".into()
|
|
}
|
|
|
|
/// A duration in seconds, written as `"5m"` or as a number of seconds.
|
|
pub fn duration<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u64, D::Error> {
|
|
#[derive(Deserialize)]
|
|
#[serde(untagged)]
|
|
enum Raw {
|
|
Seconds(u64),
|
|
Text(String),
|
|
}
|
|
|
|
match Raw::deserialize(deserializer)? {
|
|
Raw::Seconds(0) => Err(serde::de::Error::custom("duration must be positive")),
|
|
Raw::Seconds(seconds) => Ok(seconds),
|
|
Raw::Text(text) => parse_duration(&text)
|
|
.ok_or_else(|| serde::de::Error::custom(format!("invalid duration {text:?}; use e.g. 30s, 5m, 1h or 1d"))),
|
|
}
|
|
}
|
|
|
|
pub fn durations<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u64>, D::Error> {
|
|
#[derive(Deserialize)]
|
|
struct Item(#[serde(deserialize_with = "duration")] u64);
|
|
Ok(Vec::<Item>::deserialize(deserializer)?.into_iter().map(|i| i.0).collect())
|
|
}
|
|
|
|
pub fn optional_durations<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Option<Vec<u64>>, D::Error> {
|
|
durations(deserializer).map(Some)
|
|
}
|
|
|
|
/// Resolves a credential path the way systemd's `LoadCredential` exposes it.
|
|
pub fn credential(path: &std::path::Path) -> PathBuf {
|
|
if path.is_absolute() {
|
|
return path.to_owned();
|
|
}
|
|
let directory = std::env::var_os("CREDENTIALS_DIRECTORY").unwrap_or_default();
|
|
PathBuf::from(directory).join(path)
|
|
}
|
|
|
|
/// Looks up a user's UID and primary GID by name.
|
|
pub fn user_id(name: &str) -> anyhow::Result<(u32, u32)> {
|
|
let user = User::from_name(name)?.with_context(|| format!("unknown user {name:?}"))?;
|
|
Ok((user.uid.as_raw(), user.gid.as_raw()))
|
|
}
|
|
|
|
/// Looks up a group's GID by name.
|
|
pub fn group_id(name: &str) -> anyhow::Result<u32> {
|
|
let group = Group::from_name(name)?.with_context(|| format!("unknown group {name:?}"))?;
|
|
Ok(group.gid.as_raw())
|
|
}
|
|
|
|
/// A user's name, for showing who answered a request.
|
|
pub fn user_name(uid: u32) -> String {
|
|
match User::from_uid(Uid::from_raw(uid)) {
|
|
Ok(Some(user)) => user.name,
|
|
_ => format!("uid {uid}"),
|
|
}
|
|
}
|
|
|
|
impl Config {
|
|
pub fn load(path: &Path) -> anyhow::Result<Config> {
|
|
let text = std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
|
|
toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))
|
|
}
|
|
|
|
/// Checks what the types can't: every requester's policy exists.
|
|
pub fn validate(&self) -> anyhow::Result<()> {
|
|
for (name, requester) in &self.requesters {
|
|
anyhow::ensure!(
|
|
self.policies.contains_key(&requester.policy),
|
|
"requester {name:?} has policy {:?}, which isn't configured",
|
|
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"
|
|
);
|
|
anyhow::ensure!(
|
|
self.ssh.is_none() || self.deploy.is_some(),
|
|
"ssh needs deploy, whose builder reads the main branch's deploy-rs nodes"
|
|
);
|
|
Ok(())
|
|
}
|
|
|
|
pub fn policy(&self, requester: &str) -> Option<&Policy> {
|
|
self.policies.get(&self.requesters.get(requester)?.policy)
|
|
}
|
|
|
|
pub fn requester_by_cid(&self, cid: u32) -> Option<&str> {
|
|
self.requesters.iter().find(|(_, r)| r.vsock_cid == Some(cid)).map(|(n, _)| n.as_str())
|
|
}
|
|
|
|
pub fn requester_by_uid(&self, uid: u32) -> Option<&str> {
|
|
self.requesters.iter().find(|(_, r)| r.uid == Some(uid)).map(|(n, _)| n.as_str())
|
|
}
|
|
|
|
pub fn remote_requester(&self, name: &str) -> bool {
|
|
self.remote.is_some() && self.requesters.get(name).is_some_and(|r| r.remote)
|
|
}
|
|
|
|
pub fn remote_approver(&self, name: &str) -> bool {
|
|
self.remote.as_ref().is_some_and(|r| r.approvers.iter().any(|a| a == name))
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::policy::OpName;
|
|
|
|
/// The layout the NixOS module writes.
|
|
#[test]
|
|
fn parses_generated_config() {
|
|
let config: Config = toml::from_str(
|
|
r#"
|
|
approve_socket = "/run/slop-broker/approve.sock"
|
|
approver_group = "slop-broker-approve"
|
|
timeout = "5m"
|
|
|
|
[requesters.slop-cannon]
|
|
vsock_cid = 3
|
|
policy = "agent"
|
|
|
|
[policies.agent.ops.query]
|
|
action = "auto"
|
|
|
|
[policies.agent.ops.ssh]
|
|
action = "ask"
|
|
leases = ["5m", "1h"]
|
|
|
|
[[policies.agent.ops.ssh.rules]]
|
|
action = "deny"
|
|
leases = [600]
|
|
match = { target = "river" }
|
|
"#,
|
|
)
|
|
.unwrap();
|
|
|
|
config.validate().unwrap();
|
|
assert_eq!(config.timeout, 300);
|
|
|
|
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]));
|
|
|
|
assert!(
|
|
toml::from_str::<Config>("approve_socket = \"/a\"\napprover_group = \"g\"\ntimeout = \"5\"\n").is_err()
|
|
);
|
|
assert!(toml::from_str::<Config>("approve_socket = \"/a\"\napprover_group = \"g\"\nunknown = 1\n").is_err());
|
|
|
|
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}");
|
|
}
|
|
}
|