hird-server 0.3.0

The central queue: hird served over HTTP for harnesses on other machines.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! Who may connect, and as whom.
//!
//! The local binary reads its identity from the environment it was started in,
//! because that environment belongs to the human running the harness. A server
//! has no such luxury: the environment is the server's, and the far end of a
//! socket can claim anything. The roster is the operator's answer — a file
//! naming each token that may connect and the session it connects as.
//!
//! It is deliberately a file rather than a table in the queue's own database.
//! The queue records what happened; who is allowed to make things happen is a
//! different kind of fact, and keeping it outside means a compromised queue
//! cannot grant access to itself.
//!
//! Capability labels are per worker, and a worker may inherit a set from the
//! harness it pins: `[harness.opencode]` says what every pinned OpenCode
//! worker starts with, and the worker's own `capabilities` add to it. Only a
//! *pinned* harness reaches that table. The name a client gives itself never
//! does, because a label is something a human grants (§25) and a client's name
//! for itself is the one thing the design lets a client be wrong about (§29).

use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

use hird::{capability, identity};
use hird_factory::{Policy, Role, Roles};
use serde::Deserialize;

/// A parsed roster: every token that may connect, and what it connects as.
#[derive(Debug, Clone)]
pub struct Roster {
    workers: BTreeMap<String, Worker>,
    /// The factory policy, when this roster runs a factory: it has a
    /// `[factory]` table, or any worker holds a role. `None` is the plain
    /// shared queue, exactly as before roles existed.
    factory: Option<Policy>,
}

/// One entry: a credential, and the session it resolves to.
#[derive(Debug, Clone)]
pub struct Worker {
    /// The person this token acts for. Recorded on everything it does.
    pub identity: String,
    /// The harness, when the operator wants to pin it. Left unset, the client
    /// names itself — which §29 permits for a harness and never for a person.
    pub harness: Option<String>,
    /// The project this token's calls scope to. Required: the server's working
    /// directory is the server's, and a caller's checkout is somewhere else.
    pub project: String,
    /// Capability labels this token may claim against: the pinned harness's
    /// defaults and the worker's own, normalized, sorted and deduplicated.
    pub capabilities: Vec<String>,
    /// What the operator lets this token do in a factory. Empty outside one,
    /// and empty inside one means it may read the board and nothing else.
    pub roles: Roles,
    /// The model this worker runs, when the operator records it.
    pub model: Option<String>,
}

/// The file as written.
#[derive(Debug, Deserialize)]
struct RosterFile {
    /// Project for workers that do not name their own.
    project: Option<String>,
    /// Defaults per harness type, keyed by the name a worker pins.
    #[serde(default, rename = "harness")]
    harnesses: BTreeMap<String, HarnessFile>,
    #[serde(default, rename = "worker")]
    workers: Vec<WorkerFile>,
    /// The factory policy. Its presence alone turns the factory on.
    factory: Option<Policy>,
}

/// What every worker pinned to one harness type starts with.
#[derive(Debug, Deserialize)]
struct HarnessFile {
    #[serde(default)]
    capabilities: Vec<String>,
}

#[derive(Debug, Deserialize)]
struct WorkerFile {
    token: String,
    identity: String,
    harness: Option<String>,
    project: Option<String>,
    #[serde(default)]
    capabilities: Vec<String>,
    #[serde(default)]
    roles: Vec<String>,
    model: Option<String>,
}

impl Roster {
    /// Read and validate a roster file.
    pub fn load(path: &Path) -> anyhow::Result<Roster> {
        let text = std::fs::read_to_string(path)
            .map_err(|e| anyhow::anyhow!("cannot read roster {}: {e}", path.display()))?;
        Roster::parse(&text)
    }

    /// Parse a roster, refusing the mistakes that would quietly mis-attribute
    /// work: a duplicated token, a missing project, an empty credential, a
    /// capability label the session would refuse, a harness table nobody pins.
    pub fn parse(text: &str) -> anyhow::Result<Roster> {
        let file: RosterFile = toml::from_str(text)?;
        let mut defaults = BTreeMap::new();
        for (raw, harness) in file.harnesses {
            let Some(name) = identity::harness_name(&raw) else {
                anyhow::bail!("a [harness] table is named {raw:?}, which no worker could pin");
            };
            let capabilities = capability::normalize_all(&harness.capabilities)
                .map_err(|e| anyhow::anyhow!("[harness.{name}]: {e}"))?;
            if defaults.insert(name.clone(), capabilities).is_some() {
                anyhow::bail!(
                    "two [harness] tables both name {name:?} once the name is normalized;                      keep one"
                );
            }
        }
        let mut pinned = BTreeSet::new();
        let mut any_roles = false;
        let mut workers = BTreeMap::new();
        for worker in file.workers {
            let token = worker.token.trim().to_string();
            if token.is_empty() {
                anyhow::bail!("worker {:?} has an empty token", worker.identity);
            }
            if token.len() < MIN_TOKEN {
                anyhow::bail!(
                    "the token for {:?} is {} characters; use at least {MIN_TOKEN} \
                     — this is the only thing standing between a stranger and the queue",
                    worker.identity,
                    token.len()
                );
            }
            let identity = worker.identity.trim().to_string();
            if identity.is_empty() {
                anyhow::bail!("a worker entry has no identity");
            }
            let project = worker
                .project
                .or_else(|| file.project.clone())
                .ok_or_else(|| {
                    anyhow::anyhow!(
                        "worker {identity:?} has no project, and the roster sets no default; \
                         a server cannot guess one from its own working directory"
                    )
                })?;
            let harness = match worker.harness {
                Some(raw) => match identity::harness_name(&raw) {
                    Some(name) => Some(name),
                    None => anyhow::bail!(
                        "worker {identity:?} pins harness {raw:?}, which is not a usable name"
                    ),
                },
                None => None,
            };
            let inherited = harness
                .as_ref()
                .and_then(|name| defaults.get(name))
                .map(Vec::as_slice)
                .unwrap_or_default();
            if let Some(name) = &harness {
                pinned.insert(name.clone());
            }
            let capabilities =
                capability::normalize_all(inherited.iter().chain(worker.capabilities.iter()))
                    .map_err(|e| anyhow::anyhow!("worker {identity:?}: {e}"))?;
            let roles = worker
                .roles
                .iter()
                .map(|raw| raw.parse::<Role>())
                .collect::<Result<Vec<_>, _>>()
                .map_err(|e| anyhow::anyhow!("worker {identity:?}: {e}"))?;
            let roles = Roles::new(roles);
            // The different-harness rule is only as good as the harness
            // name, and an unpinned harness is whatever the client says.
            if roles.any(&[Role::Builder, Role::Reviewer]) && harness.is_none() {
                anyhow::bail!(
                    "worker {identity:?} is a {roles} but pins no harness; a builder or \
                     reviewer must pin one, or it could name itself into reviewing its own work"
                );
            }
            any_roles |= !roles.is_empty();
            let model = worker
                .model
                .map(|m| m.trim().to_string())
                .filter(|m| !m.is_empty());
            let entry = Worker {
                identity: identity.clone(),
                harness,
                project,
                capabilities,
                roles,
                model,
            };
            if workers.insert(token, entry).is_some() {
                anyhow::bail!(
                    "two workers share one token; the second would act as {identity:?} \
                     and the queue could not tell them apart"
                );
            }
        }
        if workers.is_empty() {
            anyhow::bail!("the roster names no workers, so nobody could connect");
        }
        if let Some(unused) = defaults.keys().find(|name| !pinned.contains(*name)) {
            anyhow::bail!(
                "[harness.{unused}] grants capabilities, but no worker pins harness {unused:?}; \
                 a client naming itself {unused:?} would not inherit them, so either pin a \
                 worker to it or remove the table"
            );
        }
        let factory = match file.factory {
            Some(policy) => Some(policy),
            None if any_roles => Some(Policy::default()),
            None => None,
        };
        Ok(Roster { workers, factory })
    }

    /// The worker a bearer token resolves to, if any.
    ///
    /// The server does not call this at request time — it builds one endpoint
    /// per token up front and dispatches by map lookup — but resolution is
    /// what a roster *is*, and it is the thing worth asserting about.
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn worker(&self, token: &str) -> Option<&Worker> {
        self.workers.get(token)
    }

    /// The factory policy, if this roster runs a factory.
    pub fn factory(&self) -> Option<&Policy> {
        self.factory.as_ref()
    }

    /// Every (token, worker) pair, for building one service per identity.
    pub fn entries(&self) -> impl Iterator<Item = (&String, &Worker)> {
        self.workers.iter()
    }

    /// How many workers may connect. Never zero: [`Roster::parse`] refuses a
    /// roster nobody could use.
    pub fn len(&self) -> usize {
        self.workers.len()
    }
}

/// Short enough to type, long enough not to guess. A roster is the whole
/// authorization story, so a token that fits in a sticky note is refused.
const MIN_TOKEN: usize = 24;

#[cfg(test)]
mod tests {
    use super::*;

    const OK: &str = r#"
project = "/srv/acme"
[[worker]]
token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaa"
identity = "ana"
capabilities = ["browser"]
[[worker]]
token = "bbbbbbbbbbbbbbbbbbbbbbbbbbbb"
identity = "ben"
harness = "codex"
project = "/srv/other"
"#;

    #[test]
    fn a_roster_resolves_a_token_to_a_person() {
        let roster = Roster::parse(OK).unwrap();
        assert_eq!(roster.len(), 2);
        let ana = roster.worker("aaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
        assert_eq!(ana.identity, "ana");
        assert_eq!(ana.project, "/srv/acme", "the default project applies");
        assert_eq!(ana.capabilities, ["browser"]);
        assert_eq!(ana.harness, None, "unpinned, so the client names itself");
        let ben = roster.worker("bbbbbbbbbbbbbbbbbbbbbbbbbbbb").unwrap();
        assert_eq!(ben.project, "/srv/other", "a worker may override it");
        assert_eq!(ben.harness.as_deref(), Some("codex"));
    }

    #[test]
    fn an_unknown_token_resolves_to_nobody() {
        assert!(Roster::parse(OK).unwrap().worker("nope").is_none());
    }

    #[test]
    fn two_workers_may_not_share_a_token() {
        let text = OK.replace(
            "bbbbbbbbbbbbbbbbbbbbbbbbbbbb",
            "aaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        );
        let err = Roster::parse(&text).unwrap_err().to_string();
        assert!(err.contains("share one token"), "{err}");
    }

    #[test]
    fn a_short_token_is_refused_rather_than_accepted_quietly() {
        let text = OK.replace("aaaaaaaaaaaaaaaaaaaaaaaaaaaa", "short");
        let err = Roster::parse(&text).unwrap_err().to_string();
        assert!(err.contains("at least"), "{err}");
    }

    #[test]
    fn a_worker_without_a_project_is_refused() {
        let text = r#"
[[worker]]
token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaa"
identity = "ana"
"#;
        let err = Roster::parse(text).unwrap_err().to_string();
        assert!(err.contains("no project"), "{err}");
    }

    #[test]
    fn an_empty_roster_is_refused() {
        let err = Roster::parse("").unwrap_err().to_string();
        assert!(err.contains("names no workers"), "{err}");
    }

    #[test]
    fn capability_labels_are_normalized_at_parse_time() {
        let text = OK.replace(r#"["browser"]"#, r#"[" Browser ", "linux", "browser"]"#);
        let roster = Roster::parse(&text).unwrap();
        let ana = roster.worker("aaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
        assert_eq!(ana.capabilities, ["browser", "linux"]);
    }

    /// A label the session would refuse is refused when the server starts,
    /// not when that one worker happens to connect.
    #[test]
    fn a_bad_capability_label_is_refused_at_parse_time() {
        let text = OK.replace(r#"["browser"]"#, r#"["has space"]"#);
        let err = Roster::parse(&text).unwrap_err().to_string();
        assert!(err.contains("\"ana\""), "{err}");
        assert!(err.contains("unsupported character"), "{err}");
    }

    const WITH_DEFAULTS: &str = r#"
project = "/srv/acme"

[harness.opencode]
capabilities = ["browser", "linux"]

[harness.pi]
capabilities = ["linux"]

[[worker]]
token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaa"
identity = "ana"
harness = "opencode"
capabilities = ["macos"]

[[worker]]
token = "bbbbbbbbbbbbbbbbbbbbbbbbbbbb"
identity = "ana"
harness = "pi"

[[worker]]
token = "cccccccccccccccccccccccccccc"
identity = "ben"
capabilities = ["gpu"]
"#;

    #[test]
    fn a_pinned_worker_inherits_its_harness_defaults_and_keeps_its_own() {
        let roster = Roster::parse(WITH_DEFAULTS).unwrap();
        let opencode = roster.worker("aaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
        assert_eq!(opencode.harness.as_deref(), Some("opencode"));
        assert_eq!(opencode.capabilities, ["browser", "linux", "macos"]);
        let pi = roster.worker("bbbbbbbbbbbbbbbbbbbbbbbbbbbb").unwrap();
        assert_eq!(pi.capabilities, ["linux"], "defaults alone, nothing added");
    }

    /// The whole safety argument in one rule: the table is reached by the
    /// harness the operator pinned, never by the name a client gives itself.
    #[test]
    fn an_unpinned_worker_inherits_nothing_whatever_a_client_says() {
        let roster = Roster::parse(WITH_DEFAULTS).unwrap();
        let ben = roster.worker("cccccccccccccccccccccccccccc").unwrap();
        assert_eq!(ben.harness, None);
        assert_eq!(ben.capabilities, ["gpu"]);
    }

    /// The pin and the table key are matched the way the identity records
    /// them, so a stray space or separator does not make the two miss.
    #[test]
    fn a_pin_and_a_table_match_after_the_identity_normalization() {
        let text = WITH_DEFAULTS.replace(r#"harness = "opencode""#, r#"harness = " open:code ""#);
        let roster = Roster::parse(&text).unwrap();
        let ana = roster.worker("aaaaaaaaaaaaaaaaaaaaaaaaaaaa").unwrap();
        assert_eq!(ana.harness.as_deref(), Some("opencode"));
        assert_eq!(ana.capabilities, ["browser", "linux", "macos"]);
    }

    #[test]
    fn a_harness_table_nobody_pins_is_refused_rather_than_ignored() {
        let text = WITH_DEFAULTS.replace(r#"harness = "pi""#, "");
        let err = Roster::parse(&text).unwrap_err().to_string();
        assert!(err.contains("[harness.pi]"), "{err}");
        assert!(err.contains("no worker pins"), "{err}");
    }

    #[test]
    fn a_bad_label_in_a_harness_table_names_the_table() {
        let text = WITH_DEFAULTS.replace(r#"["linux"]"#, r#"["no,commas"]"#);
        let err = Roster::parse(&text).unwrap_err().to_string();
        assert!(err.contains("[harness.pi]"), "{err}");
    }

    /// The example every operator starts from must be one the parser accepts.
    #[test]
    fn the_shipped_example_roster_parses() {
        let text = include_str!("../../examples/roster.toml");
        let roster = Roster::parse(text).unwrap();
        let ana_opencode = roster
            .worker("REPLACE-ME-with-a-third-32-random-bytes")
            .unwrap();
        assert_eq!(ana_opencode.harness.as_deref(), Some("opencode"));
        assert_eq!(ana_opencode.capabilities, ["browser", "linux"]);
    }

    /// The factory example, likewise.
    #[test]
    fn the_shipped_example_factory_roster_parses() {
        let text = include_str!("../../examples/factory-roster.toml");
        let roster = Roster::parse(text).unwrap();
        assert_eq!(roster.factory(), Some(&Policy::default()));
        let ci = roster
            .worker("REPLACE-ME-with-a-third-32-random-bytes")
            .unwrap();
        assert_eq!(ci.roles.to_string(), "ci");
        // The plain example runs no factory.
        let plain = Roster::parse(include_str!("../../examples/roster.toml")).unwrap();
        assert!(plain.factory().is_none());
    }

    #[test]
    fn a_pin_that_sanitizes_to_nothing_is_refused() {
        let text = OK.replace(r#"harness = "codex""#, r#"harness = " : ""#);
        let err = Roster::parse(&text).unwrap_err().to_string();
        assert!(err.contains("not a usable name"), "{err}");
    }
}