Skip to main content

universal_exports/
roster.rs

1//! Roster administration: the Operations, Agents, Agent roles, cover policies and Moneypenny's
2//! settings every Station reads, edited through a roster source that takes changes (a SQL
3//! roster).
4//!
5//! Every Station polls the same source, so an accepted change reaches each without a restart.
6//! The source checks the whole roster before it keeps a change: a refused edit changes
7//! nothing, and is audited as an accepted one is. The routes need `roster.read` or
8//! `roster.manage` on the resource `config:roster`. A write may name the revision of the record
9//! it read in `If-Match`, so an edit made meanwhile is not overwritten.
10
11use ai6::{
12    AssistantSettings, AuditRecord, ConfigRecord, Person, RosterError, RosterErrorKind,
13    StoredRecord,
14};
15use axum::Json;
16use axum::extract::{Path, Query, State};
17use axum::http::{HeaderMap, StatusCode};
18use axum::response::{IntoResponse, Response};
19use serde::{Deserialize, Serialize};
20use uuid::Uuid;
21
22use crate::access_admin::token;
23use crate::{
24    ApiError, Gateway, GatewayError, bearer, resolve_user, resource_action_allowed, unix_timestamp,
25};
26
27/// The authorization resource of the roster.
28pub(crate) const ROSTER_RESOURCE: &str = "config:roster";
29/// One roster record as its source holds it.
30#[non_exhaustive]
31#[derive(Debug, Clone, PartialEq, Serialize)]
32pub struct RosterRecord {
33    /// The Operation key, Agent codename, role ID, cover name, or `assistant`.
34    pub key: String,
35    /// The keys of the record's table in the configuration files.
36    pub definition: StoredRecord,
37    /// A digest of the stored record, for `If-Match` on a write.
38    pub revision: String,
39    /// Effective settings that differ from their defaults.
40    #[serde(skip_serializing_if = "Vec::is_empty")]
41    pub settings_differ: Vec<String>,
42}
43
44/// The records of one kind.
45#[non_exhaustive]
46#[derive(Debug, Clone, PartialEq, Serialize)]
47pub struct RosterRecords {
48    /// `operations`, `agents`, `roles`, `covers` or `assistant` (at most one record, keyed
49    /// `settings`).
50    pub kind: String,
51    /// The roster revision they were read at, in decimal; Stations report the revision they
52    /// run at check-in.
53    pub revision: String,
54    /// Whether the source takes edits.
55    pub writable: bool,
56    /// The records, by key.
57    pub records: Vec<RosterRecord>,
58}
59
60/// One Operation as its Stations resolve it: its definition with its ancestors' keys layered
61/// in, and which Operation wrote each key.
62#[non_exhaustive]
63#[derive(Debug, Clone, PartialEq, Serialize)]
64pub struct EffectiveOperation {
65    /// Operation codename.
66    pub operation_id: String,
67    /// The Operations it is subordinate to, nearest first.
68    pub lineage: Vec<String>,
69    /// Whether it takes policy from its ancestors.
70    pub inherit: bool,
71    /// The keys of its `[operation.<id>]` table with its ancestors' layered in, before
72    /// presets and defaults; a key no Operation wrote has its default and is absent.
73    pub definition: StoredRecord,
74    /// Each written key, dotted (`green_ink.kinds`), and the Operation that wrote it.
75    pub origins: std::collections::BTreeMap<String, String>,
76    /// The roster revision it was read at, in decimal.
77    pub revision: String,
78}
79
80/// An accepted edit.
81#[non_exhaustive]
82#[derive(Debug, Clone, PartialEq, Serialize)]
83pub struct RosterChange {
84    /// The roster revision the edit moved to, in decimal.
85    pub revision: String,
86    /// What the stored `assistant` record loosens or redirects against the settings in force
87    /// before it ([`AssistantSettings::changes_from`]); omitted when there is nothing.
88    #[serde(skip_serializing_if = "Vec::is_empty")]
89    pub weakened: Vec<String>,
90}
91
92/// Why the source refused an edit (HTTP 422).
93#[derive(Serialize)]
94pub(crate) struct Refused {
95    pub(crate) refused: String,
96}
97
98/// An edit named a revision the record no longer has (HTTP 409).
99#[derive(Serialize)]
100pub(crate) struct Changed {
101    /// The record's revision now; `0` when it is gone.
102    changed: String,
103}
104
105/// A kind of record the routes serve, and what a person needs to read or change it.
106#[derive(Clone)]
107struct Family {
108    record: ConfigRecord,
109    /// The resource the actions are held on.
110    resource: String,
111    read: &'static str,
112    manage: &'static str,
113}
114
115/// The route kinds gated by `config.read` and `config.manage` on `config:<family>`, and the
116/// family each names.
117pub(crate) const CONFIG_KINDS: [(&str, ConfigRecord); 15] = [
118    ("station", ConfigRecord::Station),
119    ("plugins", ConfigRecord::Plugin),
120    ("tls", ConfigRecord::Tls),
121    ("cables", ConfigRecord::Cables),
122    ("unex", ConfigRecord::Unex),
123    ("charges", ConfigRecord::Charge),
124    ("registry", ConfigRecord::Registry),
125    ("theaters", ConfigRecord::Theater),
126    ("loadouts", ConfigRecord::Loadout),
127    ("sandboxes", ConfigRecord::Sandbox),
128    ("mcps", ConfigRecord::Mcp),
129    ("overlays", ConfigRecord::Overlay),
130    ("secrets", ConfigRecord::Secret),
131    ("secret_providers", ConfigRecord::SecretProvider),
132    ("pools", ConfigRecord::Pool),
133];
134
135/// The route kinds gated by `roster.read` and `roster.manage` on `config:roster`.
136const ROSTER_KINDS: [(&str, ConfigRecord); 8] = [
137    ("operations", ConfigRecord::Operation),
138    ("agents", ConfigRecord::Agent),
139    ("roles", ConfigRecord::Role),
140    ("fragments", ConfigRecord::Fragment),
141    ("covers", ConfigRecord::Cover),
142    ("reviews", ConfigRecord::Review),
143    ("assistant", ConfigRecord::Assistant),
144    ("roster", ConfigRecord::Roster),
145];
146
147/// The family a route kind names, in the family's name or its plural (`charge`, `charges`).
148fn family_of(kind: &str) -> Result<Family, ApiError> {
149    let record =
150        ai6::directorates::m::config::family_of_kind(kind).ok_or_else(ApiError::not_found)?;
151    if CONFIG_KINDS.iter().any(|(_, served)| *served == record) {
152        return Ok(Family {
153            record,
154            resource: format!("config:{}", record.name()),
155            read: "config.read",
156            manage: "config.manage",
157        });
158    }
159    if ROSTER_KINDS.iter().any(|(_, served)| *served == record) {
160        return Ok(Family {
161            record,
162            resource: ROSTER_RESOURCE.to_owned(),
163            read: "roster.read",
164            manage: "roster.manage",
165        });
166    }
167    Err(ApiError::not_found())
168}
169
170/// Refuses a person who does not hold `action` on the family's resource, naming the family.
171async fn require(
172    gateway: &Gateway,
173    person: &Person,
174    family: &Family,
175    action: &'static str,
176) -> Result<(), ApiError> {
177    // What code every Station loads is decided by the `plugin` family, so changing it takes
178    // `plugin.manage` as well, whichever route it comes through.
179    if family.record == ConfigRecord::Plugin && action == family.manage {
180        crate::libraries::require_manage(gateway, person, "a write to the plugin family").await?;
181    }
182    if resource_action_allowed(gateway, person.clone(), family.resource.clone(), action).await? {
183        Ok(())
184    } else {
185        Err(ApiError::refused(
186            StatusCode::FORBIDDEN,
187            format!(
188                "the {} family needs {action} on {}",
189                family.record.name(),
190                family.resource
191            ),
192        ))
193    }
194}
195
196/// The audit target of a record: `charge operation:G`, or with a Station's own `loadout 007 (station:x)`.
197fn target_of(record: ConfigRecord, scope: &ai6::ConfigScope, key: &str) -> String {
198    match scope {
199        ai6::ConfigScope::Global => format!("{} {key}", record.name()),
200        scope => format!("{} {key} ({scope})", record.name()),
201    }
202}
203
204/// The Station a request names, for a family that may have records of its own per Station.
205#[derive(Debug, Default, Deserialize)]
206pub(crate) struct Scoped {
207    station: Option<String>,
208    /// For a removal: go ahead though another record names this one.
209    #[serde(default)]
210    force: bool,
211    /// For a write: store a record of a trust-root family though it loosens what is in force.
212    #[serde(default)]
213    confirm: bool,
214}
215
216fn scope_of(record: ConfigRecord, scoped: &Scoped) -> Result<ai6::ConfigScope, ApiError> {
217    match scoped.station.as_deref() {
218        None => Ok(ai6::ConfigScope::Global),
219        Some(id) if record.station_scoped() && ai6::ConfigScope::is_plain(id) => {
220            Ok(ai6::ConfigScope::Station(id.to_owned()))
221        }
222        Some(_) => Err(ApiError::bad_request()),
223    }
224}
225
226/// What the changed records of a trust-root family give up that the family's stored records
227/// do not already give up.
228pub(crate) fn loosened(
229    source: &dyn ai6::ConfigProvider,
230    record: ConfigRecord,
231    scope: &ai6::ConfigScope,
232    changes: &[(String, StoredRecord)],
233) -> Result<Vec<String>, RosterError> {
234    if !ai6::directorates::m::config::TRUST_ROOT.contains(&record) {
235        return Ok(Vec::new());
236    }
237    let current = source.definitions(record, scope)?.records;
238    let mut after = current.clone();
239    for (key, definition) in changes {
240        match after.iter_mut().find(|(found, _)| found == key) {
241            Some(held) => held.1 = definition.clone(),
242            None => after.push((key.clone(), definition.clone())),
243        }
244    }
245    let before = ai6::directorates::m::config::record_weakenings(record, &current);
246    Ok(
247        ai6::directorates::m::config::record_weakenings(record, &after)
248            .into_iter()
249            .filter(|line| !before.contains(line))
250            .collect(),
251    )
252}
253
254fn checked_key(key: &str, bytes: ai6::Limit) -> Result<(), ApiError> {
255    if key.trim().is_empty() || !bytes.allows(key.len()) || key.chars().any(char::is_control) {
256        Err(ApiError::bad_request())
257    } else {
258        Ok(())
259    }
260}
261
262fn source(gateway: &Gateway) -> Result<std::sync::Arc<dyn ai6::ConfigProvider>, ApiError> {
263    gateway.roster.clone().ok_or_else(ApiError::unavailable)
264}
265
266/// `text` on one line, cut to the audit target's bound at a character boundary.
267pub(crate) fn bounded(text: &str, bytes: ai6::Limit) -> String {
268    let mut line = text
269        .chars()
270        .map(|character| {
271            if character.is_control() {
272                ' '
273            } else {
274                character
275            }
276        })
277        .collect::<String>();
278    if !bytes.allows(line.len()) {
279        let mut end = bytes.or_max().saturating_sub('…'.len_utf8());
280        while !line.is_char_boundary(end) {
281            end -= 1;
282        }
283        line.truncate(end);
284        line.push('…');
285    }
286    line
287}
288
289pub(crate) async fn audit(
290    gateway: &Gateway,
291    person: &Person,
292    resource: &str,
293    action: &str,
294    target: &str,
295) -> Result<(), ApiError> {
296    let registry = gateway.registry.clone().ok_or_else(ApiError::unavailable)?;
297    let record = AuditRecord {
298        id: Uuid::new_v4().to_string(),
299        actor: crate::actor_of(person),
300        action: action.to_owned(),
301        operation: String::new(),
302        resource: Some(resource.to_owned()),
303        target: bounded(target, gateway.config.unex().text.roster_target_bytes),
304        at: unix_timestamp()?,
305    };
306    tokio::task::spawn_blocking(move || registry.record_audit(&record))
307        .await
308        .map_err(|_| ApiError::internal())?
309        .map_err(|_| ApiError::internal())
310}
311
312/// `GET /v1/user/roster/{kind}`: needs `roster.read`.
313pub(crate) async fn records(
314    State(gateway): State<Gateway>,
315    headers: HeaderMap,
316    Path(kind): Path<String>,
317    Query(scoped): Query<Scoped>,
318) -> Result<Json<RosterRecords>, ApiError> {
319    let person = resolve_user(&gateway, bearer(&headers)?).await?;
320    let family = family_of(&kind)?;
321    let scope = scope_of(family.record, &scoped)?;
322    require(&gateway, &person, &family, family.read).await?;
323    let source = source(&gateway)?;
324    let record = family.record;
325    let definitions = tokio::task::spawn_blocking(move || source.definitions(record, &scope))
326        .await
327        .map_err(|_| ApiError::internal())?
328        .map_err(|error| match error.kind() {
329            RosterErrorKind::ReadOnly => ApiError::from(GatewayError::Conflict),
330            _ => ApiError::unavailable(),
331        })?;
332    Ok(Json(RosterRecords {
333        kind,
334        revision: definitions.revision.get().to_string(),
335        writable: definitions.writable,
336        records: definitions
337            .records
338            .into_iter()
339            .map(|(key, mut definition)| RosterRecord {
340                // The revision is of what is stored; what is shown holds no credential.
341                revision: token(Some(&definition)),
342                settings_differ: if record == ConfigRecord::Assistant {
343                    definition
344                        .read::<AssistantSettings>()
345                        .map(|settings| {
346                            settings
347                                .weakenings()
348                                .into_iter()
349                                .map(|line| {
350                                    ai6::station::settings_status::SettingsNotice::assistant(&line)
351                                        .text
352                                })
353                                .collect()
354                        })
355                        .unwrap_or_default()
356                } else {
357                    Vec::new()
358                },
359                key,
360                definition: {
361                    if record == ConfigRecord::Unex {
362                        crate::config_secrets::redact_unex(&mut definition);
363                    }
364                    definition
365                },
366            })
367            .collect(),
368    }))
369}
370
371/// `GET /v1/user/roster/{kind}/schema`: needs `roster.read`. The record's schema, the form that
372/// shows it and how its key is asked for, as its type declares them.
373pub(crate) async fn form(
374    State(gateway): State<Gateway>,
375    headers: HeaderMap,
376    Path(kind): Path<String>,
377) -> Result<Json<ai6::RecordForm>, ApiError> {
378    let person = resolve_user(&gateway, bearer(&headers)?).await?;
379    let family = family_of(&kind)?;
380    require(&gateway, &person, &family, family.read).await?;
381    match family.record.form() {
382        Ok(Some(form)) => Ok(Json(form)),
383        Ok(None) => Err(ApiError::not_found()),
384        Err(_) => Err(ApiError::internal()),
385    }
386}
387
388/// The revision a write names in `If-Match`, when it names one.
389fn expected_revision(headers: &HeaderMap) -> Option<String> {
390    headers
391        .get("if-match")
392        .and_then(|value| value.to_str().ok())
393        .map(|value| value.trim().trim_matches('"').to_owned())
394}
395
396/// Stores `definition` under `key`. With `expected`, only while the stored record has that
397/// revision (`0`: there is none); otherwise whatever is there is replaced.
398pub(crate) fn store(
399    source: &dyn ai6::ConfigProvider,
400    record: ConfigRecord,
401    scope: &ai6::ConfigScope,
402    key: &str,
403    expected: Option<&str>,
404    definition: &StoredRecord,
405) -> Result<Result<ai6::ConfigRevision, Changed>, ai6::RosterError> {
406    let Some(expected) = expected else {
407        return source.put(record, scope, key, definition).map(Ok);
408    };
409    let stored = stored_record(source, record, scope, key)?;
410    let now = token(stored.as_ref());
411    if now != expected {
412        return Ok(Err(Changed { changed: now }));
413    }
414    match source.put_if(record, scope, key, stored.as_ref(), definition) {
415        Err(error) if error.kind() == RosterErrorKind::Conflict => {
416            let now = stored_record(source, record, scope, key)?;
417            Ok(Err(Changed {
418                changed: token(now.as_ref()),
419            }))
420        }
421        outcome => outcome.map(Ok),
422    }
423}
424
425pub(crate) fn stored_record(
426    source: &dyn ai6::ConfigProvider,
427    record: ConfigRecord,
428    scope: &ai6::ConfigScope,
429    key: &str,
430) -> Result<Option<StoredRecord>, ai6::RosterError> {
431    Ok(source
432        .definitions(record, scope)?
433        .records
434        .into_iter()
435        .find(|(stored, _)| stored == key)
436        .map(|(_, definition)| definition))
437}
438
439pub(crate) fn changed_response(changed: Changed) -> Response {
440    (StatusCode::CONFLICT, Json(changed)).into_response()
441}
442
443/// `PUT` on the path the schema route holds: a record may be keyed `schema`.
444pub(crate) async fn put_record_keyed_schema(
445    state: State<Gateway>,
446    headers: HeaderMap,
447    Path(kind): Path<String>,
448    scoped: Query<Scoped>,
449    definition: Json<StoredRecord>,
450) -> Result<Response, ApiError> {
451    put_record(
452        state,
453        headers,
454        Path((kind, "schema".to_owned())),
455        scoped,
456        definition,
457    )
458    .await
459}
460
461/// `DELETE` on the path the schema route holds: a record may be keyed `schema`.
462pub(crate) async fn remove_record_keyed_schema(
463    state: State<Gateway>,
464    headers: HeaderMap,
465    Path(kind): Path<String>,
466    scoped: Query<Scoped>,
467) -> Result<Response, ApiError> {
468    remove_record(state, headers, Path((kind, "schema".to_owned())), scoped).await
469}
470
471/// `GET /v1/user/roster/operation/{id}/effective`: needs `roster.read`.
472pub(crate) async fn effective(
473    State(gateway): State<Gateway>,
474    headers: HeaderMap,
475    Path(id): Path<String>,
476) -> Result<Json<EffectiveOperation>, ApiError> {
477    let person = resolve_user(&gateway, bearer(&headers)?).await?;
478    checked_key(&id, gateway.config.unex().text.roster_key_bytes)?;
479    if !resource_action_allowed(&gateway, person, ROSTER_RESOURCE.to_owned(), "roster.read").await?
480    {
481        return Err(ApiError::forbidden());
482    }
483    let source = source(&gateway)?;
484    let snapshot = tokio::task::spawn_blocking(move || source.load(""))
485        .await
486        .map_err(|_| ApiError::internal())?
487        .map_err(|_| ApiError::unavailable())?;
488    let operation = snapshot
489        .roster
490        .operation(&id)
491        .map_err(|_| ApiError::not_found())?;
492    Ok(Json(EffectiveOperation {
493        operation_id: operation.id.clone(),
494        lineage: snapshot
495            .roster
496            .lineage(&operation.id)
497            .into_iter()
498            .map(str::to_owned)
499            .collect(),
500        inherit: operation.inherit,
501        definition: StoredRecord::from_value(&guatiao::Value::from(operation.definition().clone()))
502            .unwrap_or_default(),
503        origins: operation.origins().clone(),
504        revision: snapshot.revision.get().to_string(),
505    }))
506}
507
508/// What an edit came to: accepted at a revision, refused with a reason, or a failure.
509/// `weakened` is what an accepted edit loosens.
510pub(crate) async fn settle(
511    gateway: &Gateway,
512    person: &Person,
513    resource: &str,
514    target: String,
515    outcome: Result<Option<ai6::ConfigRevision>, ai6::RosterError>,
516    accepted: &str,
517    weakened: Vec<String>,
518) -> Result<Response, ApiError> {
519    match outcome {
520        Ok(Some(revision)) => {
521            audit(gateway, person, resource, accepted, &target).await?;
522            Ok(Json(RosterChange {
523                revision: revision.get().to_string(),
524                weakened,
525            })
526            .into_response())
527        }
528        Ok(None) => Err(ApiError::not_found()),
529        Err(error) => match error.kind() {
530            RosterErrorKind::Invalid => {
531                let reason = error.to_string();
532                audit(
533                    gateway,
534                    person,
535                    resource,
536                    "roster.refused",
537                    &format!("{target}: {reason}"),
538                )
539                .await?;
540                Ok((
541                    StatusCode::UNPROCESSABLE_ENTITY,
542                    Json(Refused { refused: reason }),
543                )
544                    .into_response())
545            }
546            RosterErrorKind::ReadOnly => Err(ApiError::from(GatewayError::Conflict)),
547            _ => Err(ApiError::unavailable()),
548        },
549    }
550}
551
552/// Why `definition` names settings that are not those of the provider it chose, against what the
553/// hosts report; `None` when it is fine, or when the family has no form to judge it by.
554async fn provider_refusal(
555    gateway: &Gateway,
556    record: ConfigRecord,
557    definition: &StoredRecord,
558) -> Result<Option<String>, ApiError> {
559    let Ok(Some(form)) = record.form() else {
560        return Ok(None);
561    };
562    // A schema that cannot be read as a value is one nobody can judge a record by.
563    let Ok(schema) = form.schema.to_value() else {
564        return Ok(None);
565    };
566    let reports = crate::providers::every_host(gateway).await?;
567    Ok(ai6::providers::check_provider_settings(&schema, definition, &reports).err())
568}
569
570/// `PUT /v1/user/roster/{kind}/{key}` with the record's definition as a JSON object: needs
571/// `roster.manage`. 200 with the new revision, and for the `assistant` record what it loosens
572/// or redirects against the settings in force (`weakened`);
573/// 422 with the reason when the roster it would leave is not acceptable; 409 when the source
574/// takes no edits, or with `changed` when `If-Match` names a revision the record no longer has.
575pub(crate) async fn put_record(
576    State(gateway): State<Gateway>,
577    headers: HeaderMap,
578    Path((kind, key)): Path<(String, String)>,
579    Query(scoped): Query<Scoped>,
580    Json(mut definition): Json<StoredRecord>,
581) -> Result<Response, ApiError> {
582    let person = resolve_user(&gateway, bearer(&headers)?).await?;
583    let family = family_of(&kind)?;
584    let record = family.record;
585    let scope = scope_of(record, &scoped)?;
586    checked_key(&key, gateway.config.unex().text.roster_key_bytes)?;
587    if !definition.is_object() {
588        return Err(ApiError::bad_request());
589    }
590    require(&gateway, &person, &family, family.manage).await?;
591    let source = source(&gateway)?;
592    let target = target_of(record, &scope, &key);
593    if let Some(refused) = provider_refusal(&gateway, record, &definition).await? {
594        audit(
595            &gateway,
596            &person,
597            &family.resource,
598            "roster.refused",
599            &format!("{target}: {refused}"),
600        )
601        .await?;
602        return Ok((StatusCode::UNPROCESSABLE_ENTITY, Json(Refused { refused })).into_response());
603    }
604    let expected = expected_revision(&headers);
605    let confirm = scoped.confirm;
606    let outcome = tokio::task::spawn_blocking(move || {
607        // A record read and written back sends `<redacted>` where a credential was: that leaves
608        // the stored one as it was.
609        if record == ConfigRecord::Unex
610            && let Some(stored) = stored_record(source.as_ref(), record, &scope, &key)?
611        {
612            crate::config_secrets::keep_redacted_unex(&mut definition, &stored);
613        }
614        if !confirm {
615            let held = loosened(
616                source.as_ref(),
617                record,
618                &scope,
619                &[(key.clone(), definition.clone())],
620            )?;
621            if !held.is_empty() {
622                return Ok(Ok((None, held)));
623            }
624        }
625        // What an `assistant` record changes is told against the settings in force just
626        // before it, and only for an accepted edit, whose definition the source parsed the
627        // same way.
628        let current = (record == ConfigRecord::Assistant)
629            .then(|| source.load(""))
630            .transpose()?
631            .map(|snapshot| snapshot.roster.assistant().clone());
632        let revision = match store(
633            source.as_ref(),
634            record,
635            &scope,
636            &key,
637            expected.as_deref(),
638            &definition,
639        )? {
640            Ok(revision) => revision,
641            Err(changed) => return Ok(Err(changed)),
642        };
643        let weakened = current
644            .zip(definition.read::<AssistantSettings>().ok())
645            .map(|(current, settings)| settings.changes_from(&current))
646            .unwrap_or_default();
647        Ok(Ok((Some(revision), weakened)))
648    })
649    .await
650    .map_err(|_| ApiError::internal())?;
651    let (outcome, weakened) = match outcome {
652        Ok(Ok((None, weakened))) => {
653            return Ok(Json(Held {
654                applied: false,
655                weakened,
656            })
657            .into_response());
658        }
659        Ok(Ok((Some(revision), weakened))) => (Ok(Some(revision)), weakened),
660        Ok(Err(changed)) => return Ok(changed_response(changed)),
661        Err(error) => (Err(error), Vec::new()),
662    };
663    settle(
664        &gateway,
665        &person,
666        &family.resource,
667        target,
668        outcome,
669        "roster.update",
670        weakened,
671    )
672    .await
673}
674
675/// `DELETE /v1/user/roster/{kind}/{key}`: needs `roster.manage`. 200 with the new revision;
676/// 404 when there is no such record; 422 when the roster left would not be acceptable (an
677/// Agent another extends, say); 409 with `changed` as for `PUT`.
678pub(crate) async fn remove_record(
679    State(gateway): State<Gateway>,
680    headers: HeaderMap,
681    Path((kind, key)): Path<(String, String)>,
682    Query(scoped): Query<Scoped>,
683) -> Result<Response, ApiError> {
684    let person = resolve_user(&gateway, bearer(&headers)?).await?;
685    let family = family_of(&kind)?;
686    let record = family.record;
687    let scope = scope_of(record, &scoped)?;
688    checked_key(&key, gateway.config.unex().text.roster_key_bytes)?;
689    require(&gateway, &person, &family, family.manage).await?;
690    let source = source(&gateway)?;
691    let target = target_of(record, &scope, &key);
692    let expected = expected_revision(&headers);
693    let force = scoped.force;
694    let outcome = tokio::task::spawn_blocking(move || -> Result<Removal, RosterError> {
695        if let Some(expected) = expected {
696            let now = token(stored_record(source.as_ref(), record, &scope, &key)?.as_ref());
697            if now != expected {
698                return Ok(Removal::Stale(Changed { changed: now }));
699            }
700        }
701        let names = match ai6::directorates::m::config::references_to(
702            source.as_ref(),
703            record,
704            &scope,
705            &key,
706        ) {
707            Ok(names) => names,
708            Err(error) if error.kind() == RosterErrorKind::Invalid => return Ok(Removal::Gone),
709            Err(error) => return Err(error),
710        };
711        let names: Vec<String> = names.iter().map(ToString::to_string).collect();
712        if !names.is_empty() && !force {
713            return Ok(Removal::Named(names));
714        }
715        Ok(match source.remove(record, &scope, &key)? {
716            Some(revision) => Removal::Removed(revision, names),
717            None => Removal::Gone,
718        })
719    })
720    .await
721    .map_err(|_| ApiError::internal())?;
722    match outcome {
723        Ok(Removal::Stale(changed)) => Ok(changed_response(changed)),
724        Ok(Removal::Gone) => Err(ApiError::not_found()),
725        Ok(Removal::Named(names)) => {
726            let reason = format!("still named by {}; change those first", names.join(", "));
727            audit(
728                &gateway,
729                &person,
730                &family.resource,
731                "roster.refused",
732                &format!("{target}: {reason}"),
733            )
734            .await?;
735            Ok((
736                StatusCode::UNPROCESSABLE_ENTITY,
737                Json(Refused { refused: reason }),
738            )
739                .into_response())
740        }
741        Ok(Removal::Removed(revision, names)) => {
742            let target = if names.is_empty() {
743                target
744            } else {
745                format!("{target}, forced: still named by {}", names.join(", "))
746            };
747            settle(
748                &gateway,
749                &person,
750                &family.resource,
751                target,
752                Ok(Some(revision)),
753                "roster.remove",
754                Vec::new(),
755            )
756            .await
757        }
758        Err(error) => {
759            settle(
760                &gateway,
761                &person,
762                &family.resource,
763                target,
764                Err(error),
765                "roster.remove",
766                Vec::new(),
767            )
768            .await
769        }
770    }
771}
772
773/// What a removal came to.
774enum Removal {
775    /// The record has another revision than `If-Match` named.
776    Stale(Changed),
777    /// There is no such record.
778    Gone,
779    /// Other records name it, and the request did not force.
780    Named(Vec<String>),
781    /// Removed, and what still named it.
782    Removed(ai6::ConfigRevision, Vec<String>),
783}
784
785/// An edit held back because it loosens what is in force; repeat it with `confirm=true`.
786#[derive(Serialize)]
787struct Held {
788    applied: bool,
789    weakened: Vec<String>,
790}
791
792/// A request to store records of any served families together.
793#[derive(Debug, Deserialize)]
794#[serde(deny_unknown_fields)]
795pub(crate) struct ApplyRequest {
796    /// A Station's own records, for the families that have them; absent: the global ones.
797    station: Option<String>,
798    /// Check and report; store nothing.
799    #[serde(default)]
800    dry_run: bool,
801    /// Store though the records loosen what is in force.
802    #[serde(default)]
803    confirm: bool,
804    records: Vec<ApplyRecord>,
805}
806
807#[derive(Debug, Deserialize)]
808#[serde(deny_unknown_fields)]
809struct ApplyRecord {
810    /// The family's name or its plural.
811    kind: String,
812    key: String,
813    definition: StoredRecord,
814}
815
816/// One record of an apply, and what it came to.
817#[derive(Serialize)]
818struct AppliedRecord {
819    kind: String,
820    key: String,
821    /// `created`, `changed` or `unchanged`.
822    change: &'static str,
823    /// The record's revision once stored.
824    revision: String,
825}
826
827/// What an apply came to.
828#[derive(Serialize)]
829struct Applied {
830    /// Whether the records are stored: false for a dry run, and for records that loosen what is
831    /// in force until the request is repeated with `confirm`.
832    applied: bool,
833    /// The configuration revision stored at; absent when nothing was stored.
834    #[serde(skip_serializing_if = "Option::is_none")]
835    revision: Option<String>,
836    records: Vec<AppliedRecord>,
837    /// What the records loosen or redirect against what is in force.
838    #[serde(skip_serializing_if = "Vec::is_empty")]
839    weakened: Vec<String>,
840    /// Pins the stored records leave unable to take what they are pinned to (a sleeper's Agent
841    /// that lost the role it asks for); the records are stored all the same.
842    #[serde(skip_serializing_if = "Vec::is_empty")]
843    warnings: Vec<String>,
844}
845
846/// `POST /v1/user/resources/apply`: stores records of any served families in one transaction,
847/// all or none. Needs the family's manage action for each family named, and audits each record
848/// stored or refused. 200 with what each came to; 422 with the reason when the configuration it
849/// would leave is not acceptable; 409 when the source takes no edits.
850pub(crate) async fn apply(
851    State(gateway): State<Gateway>,
852    headers: HeaderMap,
853    Json(request): Json<ApplyRequest>,
854) -> Result<Response, ApiError> {
855    let person = resolve_user(&gateway, bearer(&headers)?).await?;
856    if request.records.is_empty() {
857        return Err(ApiError::invalid("the request holds no records".to_owned()));
858    }
859    let key_bytes = gateway.config.unex().text.roster_key_bytes;
860    let mut records: Vec<(Family, String, StoredRecord)> = Vec::new();
861    for entry in request.records {
862        let family = family_of(&entry.kind)
863            .map_err(|_| ApiError::invalid(format!("no kind {:?} is managed here", entry.kind)))?;
864        checked_key(&entry.key, key_bytes)?;
865        if !entry.definition.is_object() {
866            return Err(ApiError::invalid(format!(
867                "{} {}: a record is a table",
868                family.record, entry.key
869            )));
870        }
871        if records
872            .iter()
873            .any(|(other, key, _)| other.record == family.record && *key == entry.key)
874        {
875            return Err(ApiError::invalid(format!(
876                "{} {} is given twice",
877                family.record, entry.key
878            )));
879        }
880        records.push((family, entry.key, entry.definition));
881    }
882    let scoped = Scoped {
883        station: request.station,
884        force: false,
885        confirm: false,
886    };
887    let mut seen = Vec::new();
888    for (family, _, _) in &records {
889        if !seen.contains(&family.record) {
890            seen.push(family.record);
891            require(&gateway, &person, family, family.manage).await?;
892            scope_of(family.record, &scoped).map_err(|_| {
893                ApiError::invalid(format!(
894                    "{} has no records of a Station's own",
895                    family.record
896                ))
897            })?;
898        }
899    }
900    for (family, key, definition) in &records {
901        if let Some(refused) = provider_refusal(&gateway, family.record, definition).await? {
902            let target = format!("{} {key}", family.record.name());
903            audit(
904                &gateway,
905                &person,
906                &family.resource,
907                "roster.refused",
908                &format!("{target}: {refused}"),
909            )
910            .await?;
911            return Ok((
912                StatusCode::UNPROCESSABLE_ENTITY,
913                Json(Refused {
914                    refused: format!("{target}: {refused}"),
915                }),
916            )
917                .into_response());
918        }
919    }
920    let scope = match scoped.station.as_deref() {
921        Some(id) => ai6::ConfigScope::Station(id.to_owned()),
922        None => ai6::ConfigScope::Global,
923    };
924    let source = source(&gateway)?;
925    let held: Vec<(ConfigRecord, String, StoredRecord)> = records
926        .iter()
927        .map(|(family, key, definition)| (family.record, key.clone(), definition.clone()))
928        .collect();
929    let (dry_run, confirm) = (request.dry_run, request.confirm);
930    let read_scope = scope.clone();
931    let outcome = tokio::task::spawn_blocking(move || -> Result<Applying, RosterError> {
932        let mut changes = Vec::new();
933        let mut stored = Vec::new();
934        for (record, key, definition) in &held {
935            let now = stored_record(source.as_ref(), *record, &read_scope, key)?;
936            let change = match &now {
937                None => "created",
938                Some(now) if now == definition => "unchanged",
939                Some(_) => "changed",
940            };
941            changes.push((*record, key.clone(), change, token(Some(definition))));
942            if change != "unchanged" {
943                stored.push((*record, key.clone(), definition.clone()));
944            }
945        }
946        // What an `assistant` record changes is told against the settings in force just before it.
947        let mut weakened = Vec::new();
948        for (record, _, definition) in &stored {
949            if *record == ConfigRecord::Assistant
950                && let Ok(settings) = definition.read::<AssistantSettings>()
951            {
952                let current = source.load("")?.roster.assistant().clone();
953                weakened.extend(settings.changes_from(&current));
954            }
955        }
956        for trusted in ai6::directorates::m::config::TRUST_ROOT {
957            let changes: Vec<(String, StoredRecord)> = stored
958                .iter()
959                .filter(|(record, _, _)| *record == trusted)
960                .map(|(_, key, definition)| (key.clone(), definition.clone()))
961                .collect();
962            if !changes.is_empty() {
963                weakened.extend(loosened(source.as_ref(), trusted, &read_scope, &changes)?);
964            }
965        }
966        if stored.is_empty() {
967            return Ok(Applying::Done(changes, None, weakened, Vec::new()));
968        }
969        if dry_run {
970            source.check_all(&read_scope, &stored)?;
971            return Ok(Applying::Held(changes, weakened));
972        }
973        if !weakened.is_empty() && !confirm {
974            source.check_all(&read_scope, &stored)?;
975            return Ok(Applying::Held(changes, weakened));
976        }
977        let now = i64::try_from(
978            std::time::SystemTime::now()
979                .duration_since(std::time::UNIX_EPOCH)
980                .map_or(0, |since| since.as_secs()),
981        )
982        .unwrap_or(0);
983        let lines = |roster: &ai6::Roster| -> Vec<String> {
984            roster
985                .pin_problems(now)
986                .iter()
987                .map(ai6::PinProblem::line)
988                .collect()
989        };
990        let before = source
991            .load("")
992            .map(|held| lines(&held.roster))
993            .unwrap_or_default();
994        let revision = source.put_all(&read_scope, &stored)?;
995        let warnings = source
996            .load("")
997            .map(|held| lines(&held.roster))
998            .unwrap_or_default()
999            .into_iter()
1000            .filter(|line| !before.contains(line))
1001            .collect();
1002        Ok(Applying::Done(changes, revision, weakened, warnings))
1003    })
1004    .await
1005    .map_err(|_| ApiError::internal())?;
1006    let targets: Vec<(String, String)> = records
1007        .iter()
1008        .map(|(family, key, _)| {
1009            (
1010                family.resource.clone(),
1011                target_of(family.record, &scope, key),
1012            )
1013        })
1014        .collect();
1015    let view = |changes: Vec<(ConfigRecord, String, &'static str, String)>| {
1016        changes
1017            .into_iter()
1018            .map(|(record, key, change, revision)| AppliedRecord {
1019                kind: record.name().to_owned(),
1020                key,
1021                change,
1022                revision,
1023            })
1024            .collect::<Vec<_>>()
1025    };
1026    match outcome {
1027        Ok(Applying::Held(changes, weakened)) => Ok(Json(Applied {
1028            applied: false,
1029            revision: None,
1030            records: view(changes),
1031            weakened,
1032            warnings: Vec::new(),
1033        })
1034        .into_response()),
1035        Ok(Applying::Done(changes, revision, weakened, warnings)) => {
1036            for ((resource, target), (_, _, change, _)) in targets.iter().zip(&changes) {
1037                if *change != "unchanged" {
1038                    audit(&gateway, &person, resource, "roster.update", target).await?;
1039                }
1040            }
1041            Ok(Json(Applied {
1042                applied: true,
1043                revision: revision.map(|revision| revision.get().to_string()),
1044                records: view(changes),
1045                weakened,
1046                warnings,
1047            })
1048            .into_response())
1049        }
1050        Err(error) => match error.kind() {
1051            RosterErrorKind::Invalid => {
1052                let reason = error.to_string();
1053                for (resource, target) in &targets {
1054                    audit(
1055                        &gateway,
1056                        &person,
1057                        resource,
1058                        "roster.refused",
1059                        &format!("{target}: {reason}"),
1060                    )
1061                    .await?;
1062                }
1063                Ok((
1064                    StatusCode::UNPROCESSABLE_ENTITY,
1065                    Json(Refused { refused: reason }),
1066                )
1067                    .into_response())
1068            }
1069            RosterErrorKind::ReadOnly => Err(ApiError::from(GatewayError::Conflict)),
1070            _ => Err(ApiError::unavailable()),
1071        },
1072    }
1073}
1074
1075/// What an apply did before it answered.
1076enum Applying {
1077    /// Checked, and not stored: a dry run, or records that loosen something.
1078    Held(
1079        Vec<(ConfigRecord, String, &'static str, String)>,
1080        Vec<String>,
1081    ),
1082    /// Stored at a revision (none when nothing differed).
1083    Done(
1084        Vec<(ConfigRecord, String, &'static str, String)>,
1085        Option<ai6::ConfigRevision>,
1086        Vec<String>,
1087        Vec<String>,
1088    ),
1089}
1090
1091/// One kind the routes serve.
1092#[derive(Serialize)]
1093pub(crate) struct Resource {
1094    /// The family's name: what a document's table and a command's kind are called.
1095    kind: &'static str,
1096    /// The kind in a route (`/v1/user/roster/{route}`).
1097    route: &'static str,
1098    /// The resource the actions are held on.
1099    resource: String,
1100    read: &'static str,
1101    manage: &'static str,
1102    /// Which of the two the person holds.
1103    allowed: Vec<&'static str>,
1104    /// Whether a Station may have records of its own (`?station=`).
1105    station_scoped: bool,
1106    /// Whether the family has one record, keyed `settings`.
1107    singleton: bool,
1108    /// Whether a running Station applies a change without a restart.
1109    live: bool,
1110}
1111
1112/// `GET /v1/user/resources`: the kinds of record this gateway manages, the action each needs
1113/// and which the person holds.
1114pub(crate) async fn resources(
1115    State(gateway): State<Gateway>,
1116    headers: HeaderMap,
1117) -> Result<Json<Vec<Resource>>, ApiError> {
1118    let person = resolve_user(&gateway, bearer(&headers)?).await?;
1119    let mut listed = Vec::new();
1120    for (route, record) in ROSTER_KINDS.into_iter().chain(CONFIG_KINDS) {
1121        let family = family_of(route)?;
1122        let mut allowed = Vec::new();
1123        for action in [family.read, family.manage] {
1124            if resource_action_allowed(&gateway, person.clone(), family.resource.clone(), action)
1125                .await?
1126                && (record != ConfigRecord::Plugin
1127                    || action != family.manage
1128                    || resource_action_allowed(
1129                        &gateway,
1130                        person.clone(),
1131                        crate::libraries::RESOURCE.to_owned(),
1132                        "plugin.manage",
1133                    )
1134                    .await?)
1135            {
1136                allowed.push(action);
1137            }
1138        }
1139        listed.push(Resource {
1140            kind: record.name(),
1141            route,
1142            resource: family.resource,
1143            read: family.read,
1144            manage: family.manage,
1145            allowed,
1146            station_scoped: record.station_scoped(),
1147            singleton: record.is_singleton(),
1148            live: record.applies_live(),
1149        });
1150    }
1151    Ok(Json(listed))
1152}
1153
1154#[cfg(test)]
1155mod tests {
1156    use std::sync::Arc;
1157
1158    use ai6::directorates::registry::backend::*;
1159    use axum::http::StatusCode;
1160    use serde_json::json;
1161
1162    use crate::controls::tests::{Served, served_with_roster};
1163
1164    const ROLES: &str = r#"
1165        [role.roster-readers]
1166        actions = ["roster.read"]
1167
1168        [[rule]]
1169        subject = "person:viewer-007"
1170        scope = "config:roster"
1171        role = "roster-readers"
1172
1173        [role.roster-managers]
1174        actions = ["roster.read", "roster.manage", "audit.read"]
1175
1176        [[rule]]
1177        subject = "person:operator-007"
1178        scope = "config:roster"
1179        role = "roster-managers"
1180    "#;
1181
1182    async fn call(
1183        served: &Served,
1184        token: &str,
1185        method: reqwest::Method,
1186        path: &str,
1187        body: Option<serde_json::Value>,
1188    ) -> reqwest::Response {
1189        let request = reqwest::Client::new()
1190            .request(method, format!("{}/v1/user/{path}", served.base))
1191            .bearer_auth(token);
1192        match body {
1193            Some(body) => request.json(&body),
1194            None => request,
1195        }
1196        .send()
1197        .await
1198        .unwrap()
1199    }
1200
1201    fn audits(served: &Served, action: &str) -> Vec<ai6::AuditRecord> {
1202        served
1203            .registry
1204            .list_audit(100)
1205            .unwrap()
1206            .into_iter()
1207            .filter(|record| record.action == action)
1208            .collect()
1209    }
1210
1211    #[tokio::test]
1212    async fn without_a_roster_source_the_routes_are_unavailable() {
1213        let served = served_with_roster(ROLES, None).await;
1214        let response = call(
1215            &served,
1216            &served.operator,
1217            reqwest::Method::GET,
1218            "roster/agents",
1219            None,
1220        )
1221        .await;
1222        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
1223    }
1224
1225    const SETTINGS_ROLES: &str = r#"
1226        [role.readers]
1227        actions = ["roster.read", "config.read"]
1228
1229        [[rule]]
1230        subject = "person:viewer-007"
1231        scope = "config:roster"
1232        role = "readers"
1233
1234        [[rule]]
1235        subject = "person:viewer-007"
1236        scope = "config:theater"
1237        role = "readers"
1238    "#;
1239
1240    #[tokio::test]
1241    async fn fixed_json_provider_settings_in_theater_and_source_records_are_served_as_stored() {
1242        let directory = tempfile::tempdir().unwrap();
1243        std::fs::write(
1244            directory.path().join("theaters.toml"),
1245            "[theater.lab]\naccess = { transport = { provider = \"mock-box\", config = { zeta = \"last\", alpha = 1, big = 9007199254740993, ratio = 1.5, whole = 2.0, on = true, list = [1, \"two\", { k = [] }], nested = { z = 1, a = { y = \"x\" } }, text = \"caf\u{e9}\" } } }\n\
1246             [theater.maker]\naccess = { ephemeral = { provider = \"container\", config = { image = \"fedora:44\", limit = 4096 }, keep_failed = 2 } }\n",
1247        )
1248        .unwrap();
1249        std::fs::write(
1250            directory.path().join("operations.toml"),
1251            "[operation.G]\npath = \"/srv/g\"\n\
1252             [operation.G.sources]\njira = \"GUA\"\n\
1253             [operation.G.sources.board]\nprovider = \"github\"\nrepo = \"o/board\"\nzeta = \"last\"\nalpha = 1\nratio = 1.5\nwhole = 2.0\non = true\nlabels = [\"ai6:ready\", \"triage\"]\nnested = { z = 1, a = { y = \"x\" } }\ninterval_secs = 120\nretakes = 2\n",
1254        )
1255        .unwrap();
1256        let source = Arc::new(ai6::FileProvider::new(directory.path()));
1257        let served = served_with_roster(SETTINGS_ROLES, Some(source)).await;
1258        let get = |path: &'static str| {
1259            let served = &served;
1260            async move {
1261                let response = call(served, &served.viewer, reqwest::Method::GET, path, None).await;
1262                assert_eq!(response.status(), StatusCode::OK, "{path}");
1263                response.json::<serde_json::Value>().await.unwrap()
1264            }
1265        };
1266        let theaters = get("roster/theaters").await;
1267        let operations = get("roster/operations").await;
1268        let effective = get("roster/operation/G/effective").await;
1269        let form = get("roster/theaters/schema").await;
1270        let operation_form = get("roster/operations/schema").await;
1271        let pick = |value: &serde_json::Value, key: &str| value[key].clone();
1272        assert_eq!(
1273            serde_json::json!({
1274                "theaters": theaters["records"],
1275                "operations": operations["records"],
1276                "effective": pick(&effective, "definition"),
1277                "origins": pick(&effective, "origins"),
1278            }),
1279            serde_json::json!({
1280                "theaters": [
1281                    {
1282                        "key": "lab",
1283                        "definition": {"access": {"transport": {
1284                            "provider": "mock-box",
1285                            "config": {
1286                                "zeta": "last", "alpha": 1, "big": 9_007_199_254_740_993_i64,
1287                                "ratio": 1.5, "whole": 2.0, "on": true,
1288                                "list": [1, "two", {"k": []}],
1289                                "nested": {"z": 1, "a": {"y": "x"}},
1290                                "text": "caf\u{e9}"
1291                            }
1292                        }}},
1293                        "revision": "2c73de8cad9369c3a6dd4f5b"
1294                    },
1295                    {
1296                        "key": "maker",
1297                        "definition": {"access": {"ephemeral": {
1298                            "provider": "container",
1299                            "config": {"image": "fedora:44", "limit": 4096},
1300                            "keep_failed": 2
1301                        }}},
1302                        "revision": "7e97ed5d91e0dad61fa53d1c"
1303                    }
1304                ],
1305                "operations": [{
1306                    "key": "G",
1307                    "definition": {"path": "/srv/g", "sources": {
1308                        "jira": "GUA",
1309                        "board": {
1310                            "provider": "github", "repo": "o/board", "zeta": "last", "alpha": 1,
1311                            "ratio": 1.5, "whole": 2.0, "on": true,
1312                            "labels": ["ai6:ready", "triage"],
1313                            "nested": {"z": 1, "a": {"y": "x"}},
1314                            "interval_secs": 120, "retakes": 2
1315                        }
1316                    }},
1317                    "revision": "0484686e05975648ca587dad"
1318                }],
1319                "effective": {"path": "/srv/g", "sources": {
1320                    "jira": "GUA",
1321                    "board": {
1322                        "provider": "github", "repo": "o/board", "zeta": "last", "alpha": 1,
1323                        "ratio": 1.5, "whole": 2.0, "on": true,
1324                        "labels": ["ai6:ready", "triage"],
1325                        "nested": {"z": 1, "a": {"y": "x"}},
1326                        "interval_secs": 120, "retakes": 2
1327                    }
1328                }},
1329                "origins": {
1330                    "path": "G",
1331                    "sources.board.alpha": "G", "sources.board.interval_secs": "G",
1332                    "sources.board.labels": "G", "sources.board.nested.a.y": "G",
1333                    "sources.board.nested.z": "G", "sources.board.on": "G",
1334                    "sources.board.provider": "G", "sources.board.ratio": "G",
1335                    "sources.board.repo": "G", "sources.board.retakes": "G",
1336                    "sources.board.whole": "G", "sources.board.zeta": "G",
1337                    "sources.jira": "G"
1338                }
1339            })
1340        );
1341        // The forms the routes serve are the ones the app ships, which a stale copy fails to match.
1342        let shipped: serde_json::Value = serde_json::from_str(include_str!(
1343            "../../../clients/outer-office/assets/record_forms.json"
1344        ))
1345        .unwrap();
1346        assert_eq!(form, shipped["theaters"]);
1347        assert_eq!(operation_form, shipped["operations"]);
1348    }
1349
1350    #[tokio::test]
1351    async fn a_configuration_directory_is_listed_but_takes_no_edits() {
1352        let directory = tempfile::tempdir().unwrap();
1353        std::fs::write(
1354            directory.path().join("agents.toml"),
1355            "[agent.007]\nhandler = \"mock-agent\"\n",
1356        )
1357        .unwrap();
1358        let source = Arc::new(ai6::FileProvider::new(directory.path()));
1359        let served = served_with_roster(ROLES, Some(source)).await;
1360        let listed: serde_json::Value = call(
1361            &served,
1362            &served.viewer,
1363            reqwest::Method::GET,
1364            "roster/agents",
1365            None,
1366        )
1367        .await
1368        .json()
1369        .await
1370        .unwrap();
1371        assert_eq!(listed["writable"], false);
1372        assert_eq!(listed["records"][0]["key"], "007");
1373        assert_eq!(listed["records"][0]["definition"]["handler"], "mock-agent");
1374        let refused = call(
1375            &served,
1376            &served.operator,
1377            reqwest::Method::PUT,
1378            "roster/agents/007",
1379            Some(json!({"handler": "mock-agent", "priority": 2})),
1380        )
1381        .await;
1382        assert_eq!(refused.status(), StatusCode::CONFLICT);
1383        assert!(audits(&served, "roster.update").is_empty());
1384    }
1385
1386    #[cfg(feature = "cli")]
1387    #[tokio::test]
1388    async fn an_edit_writes_through_the_source_and_a_bad_one_is_refused_and_audited() {
1389        use ai6::{ConfigProvider, ConfigRecord, SqlProvider};
1390
1391        let directory = tempfile::tempdir().unwrap();
1392        let location = format!("sqlite:{}", directory.path().join("roster.db").display());
1393        let source = Arc::new(SqlProvider::open(&location).unwrap());
1394        source
1395            .put(
1396                ConfigRecord::Operation,
1397                &ai6::ConfigScope::Global,
1398                "G",
1399                &crate::rec(json!({"roster": ["007"]})),
1400            )
1401            .unwrap();
1402        source
1403            .put(
1404                ConfigRecord::Agent,
1405                &ai6::ConfigScope::Global,
1406                "007",
1407                &crate::rec(json!({"handler": "mock-agent", "priority": 1})),
1408            )
1409            .unwrap();
1410        let served = served_with_roster(ROLES, Some(source.clone())).await;
1411
1412        let profile: serde_json::Value = call(
1413            &served,
1414            &served.operator,
1415            reqwest::Method::GET,
1416            "profile",
1417            None,
1418        )
1419        .await
1420        .json()
1421        .await
1422        .unwrap();
1423        assert_eq!(
1424            profile["roster"],
1425            json!(["roster.read", "roster.manage", "audit.read"])
1426        );
1427
1428        let listed: serde_json::Value = call(
1429            &served,
1430            &served.viewer,
1431            reqwest::Method::GET,
1432            "roster/agents",
1433            None,
1434        )
1435        .await
1436        .json()
1437        .await
1438        .unwrap();
1439        assert_eq!(listed["kind"], "agents");
1440        assert_eq!(listed["writable"], true);
1441        assert_eq!(
1442            listed["records"],
1443            json!([{
1444                "key": "007",
1445                "definition": {"handler": "mock-agent", "priority": 1},
1446                "revision": listed["records"][0]["revision"].clone(),
1447            }])
1448        );
1449        let viewer_edit = call(
1450            &served,
1451            &served.viewer,
1452            reqwest::Method::PUT,
1453            "roster/agents/007",
1454            Some(json!({"handler": "mock-agent", "priority": 9})),
1455        )
1456        .await;
1457        assert_eq!(viewer_edit.status(), StatusCode::FORBIDDEN);
1458
1459        let edited = call(
1460            &served,
1461            &served.operator,
1462            reqwest::Method::PUT,
1463            "roster/agents/007",
1464            Some(json!({"handler": "mock-agent", "priority": 9})),
1465        )
1466        .await;
1467        assert_eq!(edited.status(), StatusCode::OK);
1468        let edited: serde_json::Value = edited.json().await.unwrap();
1469        let revision = source.revision("").unwrap();
1470        assert_eq!(edited["revision"], revision.get().to_string());
1471        assert_eq!(
1472            source
1473                .load("")
1474                .unwrap()
1475                .roster
1476                .agent(Some("G"), "007")
1477                .unwrap()
1478                .priority,
1479            9
1480        );
1481        let updates = audits(&served, "roster.update");
1482        assert_eq!(updates.len(), 1);
1483        assert_eq!(updates[0].actor, "operator-007");
1484        assert_eq!(updates[0].resource.as_deref(), Some("config:roster"));
1485        assert_eq!(updates[0].target, "agent 007");
1486
1487        let refused = call(
1488            &served,
1489            &served.operator,
1490            reqwest::Method::PUT,
1491            "roster/agents/009",
1492            Some(json!({"clearance": "root"})),
1493        )
1494        .await;
1495        assert_eq!(refused.status(), StatusCode::UNPROCESSABLE_ENTITY);
1496        let refused: serde_json::Value = refused.json().await.unwrap();
1497        assert!(
1498            refused["refused"].as_str().unwrap().contains("clearance"),
1499            "{refused}"
1500        );
1501        assert_eq!(source.revision("").unwrap(), revision, "nothing changed");
1502        let refusals = audits(&served, "roster.refused");
1503        assert_eq!(refusals.len(), 1);
1504        assert!(
1505            refusals[0].target.starts_with("agent 009: "),
1506            "{refusals:?}"
1507        );
1508
1509        let audit: serde_json::Value = call(
1510            &served,
1511            &served.operator,
1512            reqwest::Method::GET,
1513            "audit",
1514            None,
1515        )
1516        .await
1517        .json()
1518        .await
1519        .unwrap();
1520        let actions = audit
1521            .as_array()
1522            .unwrap()
1523            .iter()
1524            .map(|record| record["action"].as_str().unwrap())
1525            .collect::<Vec<_>>();
1526        assert!(actions.contains(&"roster.refused"), "{actions:?}");
1527
1528        let missing = call(
1529            &served,
1530            &served.operator,
1531            reqwest::Method::DELETE,
1532            "roster/roles/nobody",
1533            None,
1534        )
1535        .await;
1536        assert_eq!(missing.status(), StatusCode::NOT_FOUND);
1537        let unknown = call(
1538            &served,
1539            &served.operator,
1540            reqwest::Method::GET,
1541            "roster/compartments",
1542            None,
1543        )
1544        .await;
1545        assert_eq!(unknown.status(), StatusCode::NOT_FOUND);
1546    }
1547
1548    #[tokio::test]
1549    async fn the_form_of_each_kind_is_served_to_a_person_who_may_read_the_roster() {
1550        let directory = tempfile::tempdir().unwrap();
1551        let source = Arc::new(ai6::FileProvider::new(directory.path()));
1552        let served = served_with_roster(ROLES, Some(source)).await;
1553        for kind in [
1554            "operations",
1555            "agents",
1556            "roles",
1557            "covers",
1558            "reviews",
1559            "assistant",
1560            "roster",
1561        ] {
1562            let path = format!("roster/{kind}/schema");
1563            let answer = call(&served, &served.viewer, reqwest::Method::GET, &path, None).await;
1564            assert_eq!(answer.status(), StatusCode::OK, "{kind}");
1565            let answer: serde_json::Value = answer.json().await.unwrap();
1566            assert_eq!(answer["schema"]["type"], "object", "{kind}: {answer}");
1567            assert!(answer["form"].is_object(), "{kind}: {answer}");
1568            assert!(answer["key"]["title"].is_string(), "{kind}: {answer}");
1569        }
1570        let agent: serde_json::Value = call(
1571            &served,
1572            &served.viewer,
1573            reqwest::Method::GET,
1574            "roster/agents/schema",
1575            None,
1576        )
1577        .await
1578        .json()
1579        .await
1580        .unwrap();
1581        assert_eq!(agent["schema"]["properties"]["handler"]["title"], "Handler");
1582
1583        let unknown = call(
1584            &served,
1585            &served.viewer,
1586            reqwest::Method::GET,
1587            "roster/compartments/schema",
1588            None,
1589        )
1590        .await;
1591        assert_eq!(unknown.status(), StatusCode::NOT_FOUND);
1592    }
1593
1594    #[tokio::test]
1595    async fn the_form_is_refused_without_roster_read() {
1596        let directory = tempfile::tempdir().unwrap();
1597        let source = Arc::new(ai6::FileProvider::new(directory.path()));
1598        let served = served_with_roster("", Some(source)).await;
1599        let refused = call(
1600            &served,
1601            &served.viewer,
1602            reqwest::Method::GET,
1603            "roster/agents/schema",
1604            None,
1605        )
1606        .await;
1607        assert_eq!(refused.status(), StatusCode::FORBIDDEN);
1608    }
1609
1610    #[cfg(feature = "cli")]
1611    #[tokio::test]
1612    async fn a_write_that_names_a_stale_revision_changes_nothing() {
1613        use ai6::{ConfigProvider, SqlProvider};
1614
1615        let directory = tempfile::tempdir().unwrap();
1616        let location = format!("sqlite:{}", directory.path().join("roster.db").display());
1617        let source = Arc::new(SqlProvider::open(&location).unwrap());
1618        let served = served_with_roster(ROLES, Some(source.clone())).await;
1619        let put = |path: &'static str, revision: Option<String>, body: serde_json::Value| {
1620            let served = &served;
1621            async move {
1622                let mut request = reqwest::Client::new()
1623                    .put(format!("{}/v1/user/{path}", served.base))
1624                    .bearer_auth(&served.operator)
1625                    .json(&body);
1626                if let Some(revision) = revision {
1627                    request = request.header("if-match", format!("\"{revision}\""));
1628                }
1629                request.send().await.unwrap()
1630            }
1631        };
1632
1633        // `0` adds: it refuses a record that is there.
1634        let added = put(
1635            "roster/agents/007",
1636            Some("0".to_owned()),
1637            json!({"handler": "mock-agent", "priority": 1}),
1638        )
1639        .await;
1640        assert_eq!(added.status(), StatusCode::OK);
1641        let again = put(
1642            "roster/agents/007",
1643            Some("0".to_owned()),
1644            json!({"handler": "mock-agent", "priority": 9}),
1645        )
1646        .await;
1647        assert_eq!(again.status(), StatusCode::CONFLICT);
1648
1649        let listed: serde_json::Value = call(
1650            &served,
1651            &served.viewer,
1652            reqwest::Method::GET,
1653            "roster/agents",
1654            None,
1655        )
1656        .await
1657        .json()
1658        .await
1659        .unwrap();
1660        let read = listed["records"][0]["revision"]
1661            .as_str()
1662            .unwrap()
1663            .to_owned();
1664        let first = put(
1665            "roster/agents/007",
1666            Some(read.clone()),
1667            json!({"handler": "mock-agent", "priority": 2}),
1668        )
1669        .await;
1670        assert_eq!(first.status(), StatusCode::OK);
1671        let stale = put(
1672            "roster/agents/007",
1673            Some(read.clone()),
1674            json!({"handler": "mock-agent", "priority": 3}),
1675        )
1676        .await;
1677        assert_eq!(stale.status(), StatusCode::CONFLICT);
1678        let stale: serde_json::Value = stale.json().await.unwrap();
1679        assert_ne!(stale["changed"], read, "{stale}");
1680        assert_eq!(
1681            source
1682                .load("")
1683                .unwrap()
1684                .roster
1685                .agent(None, "007")
1686                .unwrap()
1687                .priority,
1688            2
1689        );
1690
1691        let stale_remove = reqwest::Client::new()
1692            .delete(format!("{}/v1/user/roster/agents/007", served.base))
1693            .bearer_auth(&served.operator)
1694            .header("if-match", format!("\"{read}\""))
1695            .send()
1696            .await
1697            .unwrap();
1698        assert_eq!(stale_remove.status(), StatusCode::CONFLICT);
1699        assert!(source.load("").unwrap().roster.agent(None, "007").is_ok());
1700
1701        // Named or not, a person who holds it can still write without one.
1702        let unconditional = put(
1703            "roster/agents/007",
1704            None,
1705            json!({"handler": "mock-agent", "priority": 4}),
1706        )
1707        .await;
1708        assert_eq!(unconditional.status(), StatusCode::OK);
1709    }
1710
1711    #[cfg(feature = "cli")]
1712    #[tokio::test]
1713    async fn a_record_keyed_schema_is_edited_and_removed_like_any_other() {
1714        use ai6::SqlProvider;
1715
1716        let directory = tempfile::tempdir().unwrap();
1717        let location = format!("sqlite:{}", directory.path().join("roster.db").display());
1718        let source = Arc::new(SqlProvider::open(&location).unwrap());
1719        let served = served_with_roster(ROLES, Some(source)).await;
1720        let edited = call(
1721            &served,
1722            &served.operator,
1723            reqwest::Method::PUT,
1724            "roster/agents/schema",
1725            Some(json!({"handler": "mock-agent"})),
1726        )
1727        .await;
1728        assert_eq!(edited.status(), StatusCode::OK);
1729        let removed = call(
1730            &served,
1731            &served.operator,
1732            reqwest::Method::DELETE,
1733            "roster/agents/schema",
1734            None,
1735        )
1736        .await;
1737        assert_eq!(removed.status(), StatusCode::OK);
1738    }
1739
1740    #[cfg(feature = "cli")]
1741    #[tokio::test]
1742    async fn the_assistant_record_is_edited_like_any_other_and_reports_its_weakenings() {
1743        use ai6::{ConfigProvider, SqlProvider};
1744
1745        let directory = tempfile::tempdir().unwrap();
1746        let location = format!("sqlite:{}", directory.path().join("roster.db").display());
1747        let source = Arc::new(SqlProvider::open(&location).unwrap());
1748        let served = served_with_roster(ROLES, Some(source.clone())).await;
1749
1750        let listed: serde_json::Value = call(
1751            &served,
1752            &served.viewer,
1753            reqwest::Method::GET,
1754            "roster/assistant",
1755            None,
1756        )
1757        .await
1758        .json()
1759        .await
1760        .unwrap();
1761        assert_eq!(listed["kind"], "assistant");
1762        assert_eq!(listed["writable"], true);
1763        assert_eq!(listed["records"], json!([]));
1764
1765        let viewer_edit = call(
1766            &served,
1767            &served.viewer,
1768            reqwest::Method::PUT,
1769            "roster/assistant/settings",
1770            Some(json!({"allow_elevated": true})),
1771        )
1772        .await;
1773        assert_eq!(viewer_edit.status(), StatusCode::FORBIDDEN);
1774
1775        let strict = call(
1776            &served,
1777            &served.operator,
1778            reqwest::Method::PUT,
1779            "roster/assistant/settings",
1780            Some(json!({"personal_repo": "/srv/mp/{person_digest}.git"})),
1781        )
1782        .await;
1783        assert_eq!(strict.status(), StatusCode::OK);
1784        let strict: serde_json::Value = strict.json().await.unwrap();
1785        // Looser than nothing in force, but it moves where people's memory goes.
1786        assert_eq!(
1787            strict["weakened"].as_array().map(Vec::len),
1788            Some(1),
1789            "{strict}"
1790        );
1791        assert!(
1792            strict["weakened"][0]
1793                .as_str()
1794                .unwrap()
1795                .starts_with("assistant.personal_repo changes"),
1796            "{strict}"
1797        );
1798
1799        let loose = call(
1800            &served,
1801            &served.operator,
1802            reqwest::Method::PUT,
1803            "roster/assistant/settings",
1804            Some(json!({"allow_elevated": true, "org": {"repo": "/srv/org.git", "write": true}})),
1805        )
1806        .await;
1807        assert_eq!(loose.status(), StatusCode::OK);
1808        let loose: serde_json::Value = loose.json().await.unwrap();
1809        let weakened = loose["weakened"].as_array().unwrap();
1810        assert_eq!(weakened.len(), 4, "{loose}");
1811        assert!(
1812            weakened[0]
1813                .as_str()
1814                .unwrap()
1815                .contains("assistant.allow_elevated"),
1816            "{loose}"
1817        );
1818        // The same record again changes nothing in force, so nothing is reported.
1819        let again = call(
1820            &served,
1821            &served.operator,
1822            reqwest::Method::PUT,
1823            "roster/assistant/settings",
1824            Some(json!({"allow_elevated": true, "org": {"repo": "/srv/org.git", "write": true}})),
1825        )
1826        .await;
1827        assert_eq!(again.status(), StatusCode::OK);
1828        let again: serde_json::Value = again.json().await.unwrap();
1829        assert!(again.get("weakened").is_none(), "{again}");
1830        let settings = source.load("").unwrap().roster.assistant().clone();
1831        assert!(settings.allow_elevated());
1832        assert_eq!(
1833            settings.personal_repo(),
1834            None,
1835            "the record is replaced whole"
1836        );
1837        let revision = source.revision("").unwrap();
1838
1839        for (key, definition, reason) in [
1840            ("moneypenny", json!({}), "\"settings\""),
1841            (
1842                "settings",
1843                json!({"personal_repo": "ext::sh"}),
1844                "assistant.personal_repo",
1845            ),
1846        ] {
1847            let refused = call(
1848                &served,
1849                &served.operator,
1850                reqwest::Method::PUT,
1851                &format!("roster/assistant/{key}"),
1852                Some(definition),
1853            )
1854            .await;
1855            assert_eq!(refused.status(), StatusCode::UNPROCESSABLE_ENTITY);
1856            let refused: serde_json::Value = refused.json().await.unwrap();
1857            assert!(
1858                refused["refused"].as_str().unwrap().contains(reason),
1859                "{refused}"
1860            );
1861        }
1862        assert_eq!(source.revision("").unwrap(), revision, "nothing changed");
1863        assert_eq!(audits(&served, "roster.refused").len(), 2);
1864        assert_eq!(
1865            audits(&served, "roster.update")[0].target,
1866            "assistant settings"
1867        );
1868
1869        let removed = call(
1870            &served,
1871            &served.operator,
1872            reqwest::Method::DELETE,
1873            "roster/assistant/settings",
1874            None,
1875        )
1876        .await;
1877        assert_eq!(removed.status(), StatusCode::OK);
1878        assert_eq!(
1879            source.load("").unwrap().roster.assistant(),
1880            &ai6::AssistantSettings::default()
1881        );
1882    }
1883
1884    const CONFIG_ROLES: &str = r#"
1885        [role.config-readers]
1886        actions = ["config.read"]
1887
1888        [[rule]]
1889        subject = "person:viewer-007"
1890        scope = "config:charge"
1891        role = "config-readers"
1892
1893        [role.config-managers]
1894        actions = ["config.read", "config.manage"]
1895
1896        [[rule]]
1897        subject = "person:operator-007"
1898        scope = "config:charge"
1899        role = "config-managers"
1900    "#;
1901
1902    async fn with_header(
1903        served: &Served,
1904        token: &str,
1905        method: reqwest::Method,
1906        path: &str,
1907        revision: &str,
1908    ) -> reqwest::Response {
1909        reqwest::Client::new()
1910            .request(method, format!("{}/v1/user/{path}", served.base))
1911            .bearer_auth(token)
1912            .header("if-match", format!("\"{revision}\""))
1913            .send()
1914            .await
1915            .unwrap()
1916    }
1917
1918    #[cfg(feature = "cli")]
1919    /// The `unex` record's credentials are shown as `<redacted>` wherever it is read, a reference
1920    /// as it is, and a record read and written back keeps what it stored.
1921    #[tokio::test]
1922    async fn a_unex_record_is_shown_without_its_credentials_and_written_back_keeps_them() {
1923        use ai6::{ConfigProvider, ConfigRecord, ConfigScope, SqlProvider};
1924
1925        let roles = CONFIG_ROLES.replace("config:charge", "config:unex");
1926        let directory = tempfile::tempdir().unwrap();
1927        let location = format!("sqlite:{}", directory.path().join("roster.db").display());
1928        let source = Arc::new(SqlProvider::open(&location).unwrap());
1929        let served = served_with_roster(&roles, Some(source.clone())).await;
1930        let planted = "hunter2-planted";
1931        let stored = json!({
1932            "secret_fields": ["bind_password"],
1933            "directory_config": {"url": "ldaps://dc", "bind_password": planted},
1934            "authorizer_config": {"bind_password": {"provider": "file", "key": "ldap-bind"}},
1935        });
1936        let set = call(
1937            &served,
1938            &served.operator,
1939            reqwest::Method::PUT,
1940            "roster/unex/settings?confirm=true",
1941            Some(stored.clone()),
1942        )
1943        .await;
1944        assert_eq!(
1945            set.status(),
1946            StatusCode::OK,
1947            "{}",
1948            set.text().await.unwrap()
1949        );
1950        let shown: serde_json::Value = call(
1951            &served,
1952            &served.viewer,
1953            reqwest::Method::GET,
1954            "roster/unex",
1955            None,
1956        )
1957        .await
1958        .json()
1959        .await
1960        .unwrap();
1961        let definition = shown["records"][0]["definition"].clone();
1962        assert!(!shown.to_string().contains(planted), "{shown}");
1963        assert_eq!(
1964            definition["directory_config"]["bind_password"], "<redacted>",
1965            "{shown}"
1966        );
1967        assert_eq!(definition["directory_config"]["url"], "ldaps://dc");
1968        assert_eq!(
1969            definition["authorizer_config"]["bind_password"],
1970            stored["authorizer_config"]["bind_password"]
1971        );
1972
1973        // The person changes the URL and writes the record back as shown.
1974        let mut edited = definition;
1975        edited["directory_config"]["url"] = json!("ldaps://other");
1976        let set = call(
1977            &served,
1978            &served.operator,
1979            reqwest::Method::PUT,
1980            "roster/unex/settings?confirm=true",
1981            Some(edited),
1982        )
1983        .await;
1984        assert_eq!(
1985            set.status(),
1986            StatusCode::OK,
1987            "{}",
1988            set.text().await.unwrap()
1989        );
1990        let held = source
1991            .definitions(ConfigRecord::Unex, &ConfigScope::Global)
1992            .unwrap()
1993            .records
1994            .remove(0)
1995            .1;
1996        let held = serde_json::to_value(held).unwrap();
1997        assert_eq!(held["directory_config"]["bind_password"], planted);
1998        assert_eq!(held["directory_config"]["url"], "ldaps://other");
1999    }
2000
2001    #[tokio::test]
2002    async fn the_registry_record_is_listed_set_and_audited_under_its_own_action() {
2003        use ai6::{ConfigProvider, SqlProvider};
2004
2005        let roles = CONFIG_ROLES.replace("config:charge", "config:registry");
2006        let directory = tempfile::tempdir().unwrap();
2007        let location = format!("sqlite:{}", directory.path().join("roster.db").display());
2008        let source = Arc::new(SqlProvider::open(&location).unwrap());
2009        // A Station reads the same database through a handle of its own.
2010        let station = SqlProvider::open(&location).unwrap();
2011        let served = served_with_roster(&roles, Some(source.clone())).await;
2012
2013        for (token, held) in [
2014            (&served.operator, json!(["config.read", "config.manage"])),
2015            (&served.viewer, json!(["config.read"])),
2016        ] {
2017            let profile: serde_json::Value =
2018                call(&served, token, reqwest::Method::GET, "profile", None)
2019                    .await
2020                    .json()
2021                    .await
2022                    .unwrap();
2023            assert_eq!(profile["config"]["registry"], held);
2024        }
2025        let form: serde_json::Value = call(
2026            &served,
2027            &served.viewer,
2028            reqwest::Method::GET,
2029            "roster/registry/schema",
2030            None,
2031        )
2032        .await
2033        .json()
2034        .await
2035        .unwrap();
2036        assert!(form["schema"]["properties"]["limits"].is_object(), "{form}");
2037        assert_eq!(form["key"]["fixed"], "settings");
2038
2039        let before = station.revision("").unwrap();
2040        let denied = call(
2041            &served,
2042            &served.viewer,
2043            reqwest::Method::PUT,
2044            "roster/registry/settings",
2045            Some(json!({"limits": {"runs": {"records": 50}}})),
2046        )
2047        .await;
2048        assert_eq!(denied.status(), StatusCode::FORBIDDEN);
2049        let denied = denied.text().await.unwrap();
2050        assert!(
2051            denied.contains("registry family needs config.manage"),
2052            "{denied}"
2053        );
2054        assert_eq!(station.revision("").unwrap(), before, "nothing was stored");
2055
2056        let set = call(
2057            &served,
2058            &served.operator,
2059            reqwest::Method::PUT,
2060            "roster/registry/settings",
2061            Some(json!({"limits": {"runs": {"records": 50}}, "provider": {"replace_retry": 5}})),
2062        )
2063        .await;
2064        assert_eq!(set.status(), StatusCode::OK);
2065        let set: serde_json::Value = set.json().await.unwrap();
2066        assert_eq!(
2067            set["revision"],
2068            station.revision("").unwrap().get().to_string()
2069        );
2070        let record = station.load("").unwrap().settings.registry;
2071        assert_eq!(record.limits.runs.records, ai6::Limit::at(50));
2072        assert_eq!(record.provider.replace_retry, ai6::TimeLimit::secs(5));
2073
2074        let listed: serde_json::Value = call(
2075            &served,
2076            &served.viewer,
2077            reqwest::Method::GET,
2078            "roster/registry",
2079            None,
2080        )
2081        .await
2082        .json()
2083        .await
2084        .unwrap();
2085        assert_eq!(listed["kind"], "registry");
2086        assert_eq!(listed["records"][0]["key"], "settings");
2087        assert_eq!(
2088            listed["records"][0]["definition"]["limits"]["runs"]["records"],
2089            50
2090        );
2091        let updates = audits(&served, "roster.update");
2092        assert_eq!(updates.len(), 1);
2093        assert_eq!(updates[0].resource.as_deref(), Some("config:registry"));
2094        assert_eq!(updates[0].target, "registry settings");
2095
2096        let refused = call(
2097            &served,
2098            &served.operator,
2099            reqwest::Method::PUT,
2100            "roster/registry/settings",
2101            Some(json!({"limits": {"runs": {"recordz": 1}}})),
2102        )
2103        .await;
2104        assert_eq!(refused.status(), StatusCode::UNPROCESSABLE_ENTITY);
2105        assert_eq!(audits(&served, "roster.refused").len(), 1);
2106        assert_eq!(
2107            station
2108                .load("")
2109                .unwrap()
2110                .settings
2111                .registry
2112                .limits
2113                .runs
2114                .records,
2115            ai6::Limit::at(50),
2116            "a refused record changes nothing"
2117        );
2118    }
2119
2120    #[cfg(feature = "cli")]
2121    #[tokio::test]
2122    async fn a_charge_is_listed_set_and_removed_under_its_own_action_and_audited() {
2123        use ai6::{ConfigProvider, ConfigRecord, SqlProvider};
2124
2125        let directory = tempfile::tempdir().unwrap();
2126        let location = format!("sqlite:{}", directory.path().join("roster.db").display());
2127        let source = Arc::new(SqlProvider::open(&location).unwrap());
2128        let global = ai6::ConfigScope::Global;
2129        source
2130            .put(
2131                ConfigRecord::Operation,
2132                &global,
2133                "G",
2134                &crate::rec(json!({"roster": ["007"]})),
2135            )
2136            .unwrap();
2137        source
2138            .put(
2139                ConfigRecord::Agent,
2140                &global,
2141                "007",
2142                &crate::rec(json!({"handler": "mock-agent", "clearance": "00"})),
2143            )
2144            .unwrap();
2145        // A Station reads the same database through a handle of its own.
2146        let station = SqlProvider::open(&location).unwrap();
2147        let served = served_with_roster(CONFIG_ROLES, Some(source.clone())).await;
2148
2149        for (token, held) in [
2150            (&served.operator, json!(["config.read", "config.manage"])),
2151            (&served.viewer, json!(["config.read"])),
2152        ] {
2153            let profile: serde_json::Value =
2154                call(&served, token, reqwest::Method::GET, "profile", None)
2155                    .await
2156                    .json()
2157                    .await
2158                    .unwrap();
2159            assert_eq!(profile["config"]["charges"], held);
2160        }
2161
2162        let form = call(
2163            &served,
2164            &served.viewer,
2165            reqwest::Method::GET,
2166            "roster/charges/schema",
2167            None,
2168        )
2169        .await;
2170        assert_eq!(form.status(), StatusCode::OK);
2171        let form: serde_json::Value = form.json().await.unwrap();
2172        assert!(form["schema"]["properties"]["agent"].is_object(), "{form}");
2173        assert_eq!(form["key"]["title"], "Scope");
2174
2175        let before = station.revision("").unwrap();
2176        let denied = call(
2177            &served,
2178            &served.viewer,
2179            reqwest::Method::PUT,
2180            "roster/charges/operation:G",
2181            Some(json!({"agent": "007"})),
2182        )
2183        .await;
2184        assert_eq!(denied.status(), StatusCode::FORBIDDEN);
2185        let other_family = call(
2186            &served,
2187            &served.operator,
2188            reqwest::Method::GET,
2189            "roster/agents",
2190            None,
2191        )
2192        .await;
2193        assert_eq!(
2194            other_family.status(),
2195            StatusCode::FORBIDDEN,
2196            "config.manage on config:charge opens no other family"
2197        );
2198        assert_eq!(station.revision("").unwrap(), before);
2199
2200        let set = call(
2201            &served,
2202            &served.operator,
2203            reqwest::Method::PUT,
2204            "roster/charges/operation:G",
2205            Some(json!({"agent": "007", "max_turns_per_hour": 4})),
2206        )
2207        .await;
2208        assert_eq!(set.status(), StatusCode::OK);
2209        let set: serde_json::Value = set.json().await.unwrap();
2210        assert_ne!(station.revision("").unwrap(), before);
2211        assert_eq!(
2212            set["revision"],
2213            station.revision("").unwrap().get().to_string()
2214        );
2215        let held = station.load("").unwrap();
2216        let charge = &held.roster.charges()["operation:G"];
2217        assert_eq!(charge.settings.agent, "007");
2218        assert_eq!(charge.settings.max_turns_per_hour, ai6::Limit::at(4));
2219
2220        let listed: serde_json::Value = call(
2221            &served,
2222            &served.viewer,
2223            reqwest::Method::GET,
2224            "roster/charges",
2225            None,
2226        )
2227        .await
2228        .json()
2229        .await
2230        .unwrap();
2231        assert_eq!(listed["kind"], "charges");
2232        assert_eq!(listed["writable"], true);
2233        assert_eq!(listed["records"][0]["key"], "operation:G");
2234        let revision = listed["records"][0]["revision"]
2235            .as_str()
2236            .unwrap()
2237            .to_owned();
2238        let updates = audits(&served, "roster.update");
2239        assert_eq!(updates.len(), 1);
2240        assert_eq!(updates[0].resource.as_deref(), Some("config:charge"));
2241        assert_eq!(updates[0].target, "charge operation:G");
2242
2243        let refused = call(
2244            &served,
2245            &served.operator,
2246            reqwest::Method::PUT,
2247            "roster/charges/operation:G",
2248            Some(json!({"agent": "no-such-agent"})),
2249        )
2250        .await;
2251        assert_eq!(refused.status(), StatusCode::UNPROCESSABLE_ENTITY);
2252        assert_eq!(audits(&served, "roster.refused").len(), 1);
2253        assert_eq!(
2254            station.load("").unwrap().roster.charges()["operation:G"]
2255                .settings
2256                .agent,
2257            "007"
2258        );
2259
2260        let stale = with_header(
2261            &served,
2262            &served.operator,
2263            reqwest::Method::DELETE,
2264            "roster/charges/operation:G",
2265            "0",
2266        )
2267        .await;
2268        assert_eq!(stale.status(), StatusCode::CONFLICT);
2269        let removed = with_header(
2270            &served,
2271            &served.operator,
2272            reqwest::Method::DELETE,
2273            "roster/charges/operation:G",
2274            &revision,
2275        )
2276        .await;
2277        assert_eq!(removed.status(), StatusCode::OK);
2278        assert!(station.load("").unwrap().roster.charges().is_empty());
2279        let removals = audits(&served, "roster.remove");
2280        assert_eq!(removals[0].resource.as_deref(), Some("config:charge"));
2281        assert_eq!(removals[0].target, "charge operation:G");
2282    }
2283
2284    #[cfg(feature = "cli")]
2285    #[tokio::test]
2286    async fn the_usage_settings_are_served_with_the_roster_record_and_apply_what_is_set() {
2287        use ai6::{ConfigProvider, SqlProvider};
2288
2289        let directory = tempfile::tempdir().unwrap();
2290        let location = format!("sqlite:{}", directory.path().join("roster.db").display());
2291        let source = Arc::new(SqlProvider::open(&location).unwrap());
2292        let station = SqlProvider::open(&location).unwrap();
2293        let served = served_with_roster(ROLES, Some(source)).await;
2294
2295        let form = call(
2296            &served,
2297            &served.operator,
2298            reqwest::Method::GET,
2299            "roster/roster/schema",
2300            None,
2301        )
2302        .await;
2303        assert_eq!(form.status(), StatusCode::OK);
2304        let form: serde_json::Value = form.json().await.unwrap();
2305        let usage = &form["schema"]["properties"]["usage"]["properties"]["keep"];
2306        assert_eq!(
2307            usage["title"], "Keep a reading of an account's usage for",
2308            "{form}"
2309        );
2310
2311        let set = call(
2312            &served,
2313            &served.operator,
2314            reqwest::Method::PUT,
2315            "roster/roster/settings",
2316            Some(json!({"usage": {"keep": 45}})),
2317        )
2318        .await;
2319        assert_eq!(set.status(), StatusCode::OK);
2320        let usage = station.load("").unwrap().roster.settings().usage.clone();
2321        assert_eq!(usage.keep.0.as_secs(), 45);
2322        let refused = call(
2323            &served,
2324            &served.operator,
2325            reqwest::Method::PUT,
2326            "roster/roster/settings",
2327            Some(json!({"usage": {"keep": -1}})),
2328        )
2329        .await;
2330        assert_eq!(refused.status(), StatusCode::UNPROCESSABLE_ENTITY);
2331    }
2332
2333    #[cfg(feature = "cli")]
2334    fn sql_source(directory: &tempfile::TempDir) -> (Arc<ai6::SqlProvider>, String) {
2335        let location = format!("sqlite:{}", directory.path().join("roster.db").display());
2336        (
2337            Arc::new(ai6::SqlProvider::open(&location).unwrap()),
2338            location,
2339        )
2340    }
2341
2342    #[cfg(feature = "cli")]
2343    #[tokio::test]
2344    async fn an_apply_stores_records_of_several_families_together_or_not_at_all() {
2345        use ai6::{ConfigProvider, SqlProvider};
2346
2347        let directory = tempfile::tempdir().unwrap();
2348        let (source, location) = sql_source(&directory);
2349        let station = SqlProvider::open(&location).unwrap();
2350        let roles = format!("{ROLES}{CONFIG_ROLES}");
2351        let served = served_with_roster(&roles, Some(source.clone())).await;
2352        let apply = |token: String, body: serde_json::Value| {
2353            let served = &served;
2354            async move {
2355                call(
2356                    served,
2357                    &token,
2358                    reqwest::Method::POST,
2359                    "resources/apply",
2360                    Some(body),
2361                )
2362                .await
2363            }
2364        };
2365        let documents = json!({"records": [
2366            {"kind": "charges", "key": "operation:G", "definition": {"agent": "007"}},
2367            {"kind": "agent", "key": "007", "definition": {"handler": "mock-agent", "clearance": "00"}},
2368            {"kind": "operations", "key": "G", "definition": {"roster": ["007"]}},
2369        ]});
2370
2371        let before = station.revision("").unwrap();
2372        let denied = apply(served.viewer.clone(), documents.clone()).await;
2373        assert_eq!(denied.status(), StatusCode::FORBIDDEN);
2374        let reason = denied.text().await.unwrap();
2375        assert!(
2376            reason.contains("family needs") && reason.contains("on config:"),
2377            "the family is named: {reason}"
2378        );
2379        assert_eq!(station.revision("").unwrap(), before);
2380
2381        let dry = apply(
2382            served.operator.clone(),
2383            json!({"dry_run": true, "records": documents["records"]}),
2384        )
2385        .await;
2386        assert_eq!(dry.status(), StatusCode::OK);
2387        let dry: serde_json::Value = dry.json().await.unwrap();
2388        assert_eq!(dry["applied"], false);
2389        assert_eq!(dry["records"][0]["change"], "created");
2390        assert_eq!(station.revision("").unwrap(), before);
2391        assert!(audits(&served, "roster.update").is_empty());
2392
2393        // One record the roster cannot hold keeps the others out, and each is audited refused.
2394        let bad = json!({"records": [
2395            {"kind": "operations", "key": "G", "definition": {"roster": ["007"]}},
2396            {"kind": "agents", "key": "007", "definition": {"handler": "mock-agent", "extends": "absent"}},
2397        ]});
2398        let refused = apply(served.operator.clone(), bad).await;
2399        assert_eq!(refused.status(), StatusCode::UNPROCESSABLE_ENTITY);
2400        assert!(refused.json::<serde_json::Value>().await.unwrap()["refused"].is_string());
2401        assert_eq!(station.revision("").unwrap(), before);
2402        assert_eq!(audits(&served, "roster.refused").len(), 2);
2403
2404        let applied = apply(served.operator.clone(), documents.clone()).await;
2405        assert_eq!(applied.status(), StatusCode::OK);
2406        let applied: serde_json::Value = applied.json().await.unwrap();
2407        assert_eq!(applied["applied"], true);
2408        assert_eq!(
2409            applied["revision"],
2410            station.revision("").unwrap().get().to_string()
2411        );
2412        assert_eq!(
2413            station.load("").unwrap().roster.charges()["operation:G"]
2414                .settings
2415                .agent,
2416            "007"
2417        );
2418        let updates = audits(&served, "roster.update");
2419        assert_eq!(updates.len(), 3);
2420        let resources: Vec<_> = updates
2421            .iter()
2422            .map(|record| record.resource.clone().unwrap())
2423            .collect();
2424        assert!(resources.contains(&"config:charge".to_owned()));
2425        assert!(resources.contains(&"config:roster".to_owned()));
2426
2427        let same = apply(served.operator.clone(), documents).await;
2428        let same: serde_json::Value = same.json().await.unwrap();
2429        assert_eq!(same["records"][0]["change"], "unchanged");
2430        assert!(same.get("revision").is_none(), "nothing stored: {same}");
2431        assert_eq!(audits(&served, "roster.update").len(), 3);
2432
2433        for body in [
2434            json!({"records": []}),
2435            json!({"records": [{"kind": "access", "key": "settings", "definition": {}}]}),
2436            json!({"station": "x", "records": [{"kind": "agent", "key": "007", "definition": {}}]}),
2437            json!({"records": [
2438                {"kind": "agent", "key": "007", "definition": {}},
2439                {"kind": "agents", "key": "007", "definition": {}},
2440            ]}),
2441        ] {
2442            let bad = apply(served.operator.clone(), body.clone()).await;
2443            assert_eq!(bad.status(), StatusCode::BAD_REQUEST, "{body}");
2444        }
2445    }
2446
2447    #[cfg(feature = "cli")]
2448    #[tokio::test]
2449    async fn an_apply_that_removes_a_pinned_agents_role_answers_a_warning_and_still_applies() {
2450        use ai6::{ConfigProvider, SqlProvider};
2451
2452        let directory = tempfile::tempdir().unwrap();
2453        let (source, location) = sql_source(&directory);
2454        let station = SqlProvider::open(&location).unwrap();
2455        let roles = format!("{ROLES}{CONFIG_ROLES}");
2456        let served = served_with_roster(&roles, Some(source)).await;
2457        let apply = |body: serde_json::Value| {
2458            let served = &served;
2459            async move {
2460                call(
2461                    served,
2462                    &served.operator,
2463                    reqwest::Method::POST,
2464                    "resources/apply",
2465                    Some(body),
2466                )
2467                .await
2468                .json::<serde_json::Value>()
2469                .await
2470                .unwrap()
2471            }
2472        };
2473        let agent = |roles: &[&str]| {
2474            json!({"kind": "agent", "key": "007", "definition":
2475                {"handler": "mock-agent", "roles": roles}})
2476        };
2477        let first = apply(json!({"records": [
2478            {"kind": "role", "key": "intake", "definition": {"purpose": "Take in.", "policy": "Report."}},
2479            {"kind": "role", "key": "review", "definition": {"purpose": "Review.", "policy": "Report."}},
2480            agent(&["intake"]),
2481            {"kind": "operations", "key": "G", "definition": {"roster": ["007"], "sleepers": {
2482                "nightly": {"schedule": "0 3 * * *", "title": "Night", "agent": "007", "role": "intake"}}}},
2483        ]}))
2484        .await;
2485        assert_eq!(first["applied"], true, "{first}");
2486        assert!(first.get("warnings").is_none(), "{first}");
2487
2488        let second = apply(json!({"records": [agent(&["review"])]})).await;
2489        assert_eq!(second["applied"], true, "the records are applied: {second}");
2490        let warning = second["warnings"][0].as_str().unwrap();
2491        assert!(
2492            warning.contains("Agent 007")
2493                && warning.contains("role intake")
2494                && warning.contains("sleeper nightly of G"),
2495            "{warning}"
2496        );
2497        assert!(
2498            station
2499                .load("")
2500                .unwrap()
2501                .roster
2502                .agent(None, "007")
2503                .unwrap()
2504                .has_role("review"),
2505            "stored all the same"
2506        );
2507        // Said once: the same pin is not news the next time.
2508        let third = apply(json!({"records": [agent(&["review"])]})).await;
2509        assert!(third.get("warnings").is_none(), "{third}");
2510    }
2511
2512    #[cfg(feature = "cli")]
2513    #[tokio::test]
2514    async fn an_apply_of_a_looser_assistant_waits_for_confirmation() {
2515        use ai6::{ConfigProvider, SqlProvider};
2516
2517        let directory = tempfile::tempdir().unwrap();
2518        let (source, location) = sql_source(&directory);
2519        let station = SqlProvider::open(&location).unwrap();
2520        let served = served_with_roster(ROLES, Some(source)).await;
2521        let body = |confirm: bool| {
2522            json!({"confirm": confirm, "records": [
2523                {"kind": "assistant", "key": "settings", "definition": {"allow_elevated": true}},
2524            ]})
2525        };
2526        let before = station.revision("").unwrap();
2527        let held: serde_json::Value = call(
2528            &served,
2529            &served.operator,
2530            reqwest::Method::POST,
2531            "resources/apply",
2532            Some(body(false)),
2533        )
2534        .await
2535        .json()
2536        .await
2537        .unwrap();
2538        assert_eq!(held["applied"], false);
2539        assert!(
2540            held["weakened"][0]
2541                .as_str()
2542                .unwrap()
2543                .contains("assistant.allow_elevated")
2544        );
2545        assert_eq!(station.revision("").unwrap(), before);
2546        assert!(audits(&served, "roster.update").is_empty());
2547
2548        let done: serde_json::Value = call(
2549            &served,
2550            &served.operator,
2551            reqwest::Method::POST,
2552            "resources/apply",
2553            Some(body(true)),
2554        )
2555        .await
2556        .json()
2557        .await
2558        .unwrap();
2559        assert_eq!(done["applied"], true);
2560        assert!(
2561            done["weakened"]
2562                .as_array()
2563                .is_some_and(|weakened| !weakened.is_empty())
2564        );
2565        assert!(
2566            station
2567                .load("")
2568                .unwrap()
2569                .roster
2570                .assistant()
2571                .allow_elevated()
2572        );
2573    }
2574
2575    #[cfg(feature = "cli")]
2576    #[tokio::test]
2577    async fn a_record_another_names_is_not_removed_and_the_kinds_are_listed_with_what_is_held() {
2578        use ai6::{ConfigProvider, ConfigRecord, SqlProvider};
2579
2580        let directory = tempfile::tempdir().unwrap();
2581        let (source, location) = sql_source(&directory);
2582        let station = SqlProvider::open(&location).unwrap();
2583        let global = ai6::ConfigScope::Global;
2584        source
2585            .put(
2586                ConfigRecord::Operation,
2587                &global,
2588                "G",
2589                &crate::rec(json!({"roster": ["007"]})),
2590            )
2591            .unwrap();
2592        source
2593            .put(
2594                ConfigRecord::Agent,
2595                &global,
2596                "007",
2597                &crate::rec(json!({"handler": "mock-agent", "clearance": "00"})),
2598            )
2599            .unwrap();
2600        source
2601            .put(
2602                ConfigRecord::Cover,
2603                &global,
2604                "house",
2605                &crate::rec(json!({"description": "House style."})),
2606            )
2607            .unwrap();
2608        let roles = format!("{ROLES}{CONFIG_ROLES}");
2609        let served = served_with_roster(&roles, Some(source)).await;
2610
2611        let listed: serde_json::Value = call(
2612            &served,
2613            &served.viewer,
2614            reqwest::Method::GET,
2615            "resources",
2616            None,
2617        )
2618        .await
2619        .json()
2620        .await
2621        .unwrap();
2622        let kind = |name: &str| {
2623            listed
2624                .as_array()
2625                .unwrap()
2626                .iter()
2627                .find(|kind| kind["kind"] == name)
2628                .unwrap()
2629                .clone()
2630        };
2631        assert_eq!(kind("charge")["route"], "charges");
2632        assert_eq!(kind("charge")["allowed"], json!(["config.read"]));
2633        assert_eq!(kind("charge")["resource"], "config:charge");
2634        assert_eq!(kind("agent")["allowed"], json!(["roster.read"]));
2635        // The Station record is served like the other station-scoped families.
2636        assert_eq!(kind("station")["route"], "station");
2637        assert_eq!(kind("station")["station_scoped"], true);
2638        assert_eq!(kind("station")["singleton"], true);
2639
2640        // The singular name routes like the plural.
2641        let by_name = call(
2642            &served,
2643            &served.viewer,
2644            reqwest::Method::GET,
2645            "roster/agent",
2646            None,
2647        )
2648        .await;
2649        assert_eq!(by_name.status(), StatusCode::OK);
2650
2651        let refused = call(
2652            &served,
2653            &served.operator,
2654            reqwest::Method::DELETE,
2655            "roster/agents/007",
2656            None,
2657        )
2658        .await;
2659        assert_eq!(refused.status(), StatusCode::UNPROCESSABLE_ENTITY);
2660        let reason = refused.json::<serde_json::Value>().await.unwrap()["refused"]
2661            .as_str()
2662            .unwrap()
2663            .to_owned();
2664        assert!(reason.contains("operation G"), "{reason}");
2665        assert_eq!(audits(&served, "roster.refused").len(), 1);
2666        assert!(
2667            station
2668                .load("")
2669                .unwrap()
2670                .roster
2671                .agent_ids()
2672                .any(|id| id == "007")
2673        );
2674
2675        let forced = call(
2676            &served,
2677            &served.operator,
2678            reqwest::Method::DELETE,
2679            "roster/covers/house",
2680            None,
2681        )
2682        .await;
2683        assert_eq!(forced.status(), StatusCode::OK);
2684        let gone = call(
2685            &served,
2686            &served.operator,
2687            reqwest::Method::DELETE,
2688            "roster/covers/house",
2689            None,
2690        )
2691        .await;
2692        assert_eq!(gone.status(), StatusCode::NOT_FOUND);
2693    }
2694
2695    const PROVIDER_ROLES: &str = r#"
2696        [role.roster-managers]
2697        actions = ["roster.read", "roster.manage", "audit.read"]
2698
2699        [[rule]]
2700        subject = "person:operator-007"
2701        scope = "config:roster"
2702        role = "roster-managers"
2703
2704        [role.station-readers]
2705        actions = ["station.read"]
2706
2707        [[rule]]
2708        subject = "person:operator-007"
2709        scope = "station:worker"
2710        role = "station-readers"
2711
2712        [role.roster-readers]
2713        actions = ["roster.read"]
2714
2715        [[rule]]
2716        subject = "person:viewer-007"
2717        scope = "config:roster"
2718        role = "roster-readers"
2719    "#;
2720
2721    fn provider(id: &str, kind: &str, schema: Option<serde_json::Value>) -> serde_json::Value {
2722        let mut entry = json!({
2723            "id": id, "name": id, "version": "1", "kinds": [kind],
2724            "digest": format!("sha256:{id}")
2725        });
2726        if let Some(schema) = schema {
2727            entry["schema"] = schema;
2728            entry["form"] = json!({"fields": {}});
2729        }
2730        entry
2731    }
2732
2733    #[cfg(feature = "cli")]
2734    #[tokio::test]
2735    async fn a_hosts_providers_are_reported_and_a_record_holding_another_providers_settings_is_refused()
2736     {
2737        use ai6::{ConfigProvider, SqlProvider};
2738
2739        let directory = tempfile::tempdir().unwrap();
2740        let location = format!("sqlite:{}", directory.path().join("roster.db").display());
2741        let source = Arc::new(SqlProvider::open(&location).unwrap());
2742        let served = served_with_roster(PROVIDER_ROLES, Some(source.clone())).await;
2743        served
2744            .registry
2745            .check_in(
2746                "worker",
2747                serde_json::from_value(serde_json::json!({
2748                    "providers": [
2749                        provider(
2750                            "claude",
2751                            "ai6_agent_handler",
2752                            Some(json!({"type": "object", "properties": {
2753                                            "allowed_tools": {"x-section": "agent"},
2754                                            "program": {"x-section": "station"}
2755                            }}))
2756                        ),
2757                        provider(
2758                            "git",
2759                            "ai6_safehouse",
2760                            Some(json!({"type": "object", "properties": {"base": {}}}))
2761                        ),
2762                        provider("copy", "ai6_safehouse", None),
2763                    ]
2764                }))
2765                .unwrap(),
2766            )
2767            .unwrap();
2768
2769        // The Station's providers, with the schema and form of each one's configuration.
2770        let reported: serde_json::Value = call(
2771            &served,
2772            &served.operator,
2773            reqwest::Method::GET,
2774            "stations/worker/providers",
2775            None,
2776        )
2777        .await
2778        .json()
2779        .await
2780        .unwrap();
2781        assert_eq!(reported["host"], "worker");
2782        let ids: Vec<&str> = reported["providers"]
2783            .as_array()
2784            .unwrap()
2785            .iter()
2786            .map(|entry| entry["id"].as_str().unwrap())
2787            .collect();
2788        assert_eq!(ids, ["claude", "git", "copy"]);
2789        assert_eq!(
2790            reported["providers"][1]["schema"]["properties"]["base"],
2791            json!({})
2792        );
2793        assert_eq!(reported["providers"][1]["form"], json!({"fields": {}}));
2794
2795        // Merged across the hosts the person may read, narrowed to a kind.
2796        let merged: serde_json::Value = call(
2797            &served,
2798            &served.operator,
2799            reqwest::Method::GET,
2800            "providers?kind=ai6_safehouse",
2801            None,
2802        )
2803        .await
2804        .json()
2805        .await
2806        .unwrap();
2807        let ids: Vec<&str> = merged["providers"]
2808            .as_array()
2809            .unwrap()
2810            .iter()
2811            .map(|entry| entry["id"].as_str().unwrap())
2812            .collect();
2813        assert_eq!(ids, ["copy", "git"]);
2814        assert_eq!(merged["providers"][1]["hosts"], json!(["worker"]));
2815
2816        // A person who may not read the Station reads none of its providers.
2817        let hidden = call(
2818            &served,
2819            &served.viewer,
2820            reqwest::Method::GET,
2821            "stations/worker/providers",
2822            None,
2823        )
2824        .await;
2825        assert_eq!(hidden.status(), StatusCode::FORBIDDEN);
2826
2827        // An Agent's settings must be the chosen handler's, and only those an Agent may set.
2828        let put = |key: &'static str, body: serde_json::Value| {
2829            let served = &served;
2830            async move {
2831                call(
2832                    served,
2833                    &served.operator,
2834                    reqwest::Method::PUT,
2835                    &format!("roster/agents/{key}"),
2836                    Some(body),
2837                )
2838                .await
2839            }
2840        };
2841        let ok = put(
2842            "007",
2843            json!({"handler": "claude", "handler_settings": {"allowed_tools": ["Read"]}}),
2844        )
2845        .await;
2846        assert_eq!(ok.status(), StatusCode::OK);
2847        let refused = put(
2848            "008",
2849            json!({"handler": "claude", "handler_settings": {"program": "/bin/sh"}}),
2850        )
2851        .await;
2852        assert_eq!(refused.status(), StatusCode::UNPROCESSABLE_ENTITY);
2853        let reason: serde_json::Value = refused.json().await.unwrap();
2854        let reason = reason["refused"].as_str().unwrap();
2855        assert!(
2856            reason.contains("\"claude\"") && reason.contains("\"program\""),
2857            "{reason}"
2858        );
2859        let unknown = put("009", json!({"handler": "codex-typo"})).await;
2860        assert_eq!(unknown.status(), StatusCode::UNPROCESSABLE_ENTITY);
2861        assert!(
2862            unknown.text().await.unwrap().contains("codex-typo"),
2863            "names the provider it does not find"
2864        );
2865
2866        // An Operation's safe house is one the hosts report.
2867        let copy = call(
2868            &served,
2869            &served.operator,
2870            reqwest::Method::PUT,
2871            "roster/operations/G",
2872            Some(json!({"roster": ["007"], "workspace": {"provider": "worktree"}})),
2873        )
2874        .await;
2875        assert_eq!(copy.status(), StatusCode::UNPROCESSABLE_ENTITY);
2876        assert!(copy.text().await.unwrap().contains("worktree"));
2877        assert_eq!(audits(&served, "roster.refused").len(), 3);
2878        assert!(
2879            source
2880                .load("")
2881                .unwrap()
2882                .roster
2883                .agent_ids()
2884                .any(|id| id == "007")
2885        );
2886    }
2887
2888    #[cfg(feature = "cli")]
2889    #[tokio::test]
2890    async fn the_station_record_pairing_options_are_edited_through_the_gateway_with_weakening_confirmation()
2891     {
2892        use ai6::{ConfigProvider, SqlProvider};
2893
2894        let roles = CONFIG_ROLES.replace("config:charge", "config:station");
2895        let directory = tempfile::tempdir().unwrap();
2896        let location = format!("sqlite:{}", directory.path().join("roster.db").display());
2897        let source = Arc::new(SqlProvider::open(&location).unwrap());
2898        let served = served_with_roster(&roles, Some(source.clone())).await;
2899
2900        let looser = json!({
2901            "peers": {
2902                "pin": true,
2903                "pin_attempts": 3,
2904                "pin_ttl": null,
2905                "device_ttl": 1200,
2906                "invitation": false,
2907                "device": false,
2908                "max_connections": 64,
2909                "handshake_timeout": 5
2910            }
2911        });
2912        let held = call(
2913            &served,
2914            &served.operator,
2915            reqwest::Method::PUT,
2916            "roster/station/settings",
2917            Some(looser.clone()),
2918        )
2919        .await;
2920        assert_eq!(held.status(), StatusCode::OK);
2921        let held: serde_json::Value = held.json().await.unwrap();
2922        assert_eq!(held["applied"], false, "{held}");
2923        let weakened = held["weakened"].as_array().unwrap();
2924        let text = serde_json::to_string(weakened).unwrap();
2925        for expected in [
2926            "station.peers.pin",
2927            "station.peers.pin_attempts",
2928            "station.peers.pin_ttl",
2929            "station.peers.device_ttl",
2930        ] {
2931            assert!(text.contains(expected), "{expected}: {held}");
2932        }
2933        assert_eq!(
2934            source.load("").unwrap().settings.station.peers,
2935            ai6::station::limits::PeerLimits::default(),
2936            "held until confirmed"
2937        );
2938
2939        let confirmed = call(
2940            &served,
2941            &served.operator,
2942            reqwest::Method::PUT,
2943            "roster/station/settings?confirm=true",
2944            Some(looser),
2945        )
2946        .await;
2947        assert_eq!(confirmed.status(), StatusCode::OK);
2948        let confirmed: serde_json::Value = confirmed.json().await.unwrap();
2949        assert!(confirmed["revision"].is_string(), "{confirmed}");
2950        assert_eq!(audits(&served, "roster.update").len(), 1);
2951        let loaded = source.load("").unwrap().settings.station.peers;
2952        assert!(loaded.pin && !loaded.invitation && !loaded.device);
2953        assert_eq!(loaded.pin_attempts, 3);
2954        assert_eq!(loaded.pin_ttl.get(), None);
2955        assert_eq!(
2956            loaded.device_ttl.get(),
2957            Some(std::time::Duration::from_secs(1200))
2958        );
2959        assert_eq!(loaded.max_connections, 64);
2960        assert_eq!(
2961            loaded.handshake_timeout.0,
2962            std::time::Duration::from_secs(5)
2963        );
2964
2965        // Tightening back to defaults needs no confirmation.
2966        let strict = call(
2967            &served,
2968            &served.operator,
2969            reqwest::Method::PUT,
2970            "roster/station/settings",
2971            Some(json!({"peers": {"invitation": false, "handshake_timeout": 3}})),
2972        )
2973        .await;
2974        assert_eq!(strict.status(), StatusCode::OK);
2975        let strict: serde_json::Value = strict.json().await.unwrap();
2976        assert!(strict["revision"].is_string(), "{strict}");
2977        assert!(!source.load("").unwrap().settings.station.peers.pin);
2978    }
2979}