vtc-service 0.12.0

Service for Verifiable Trust Communities
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
//! **Break-glass** — separation of duties' escape hatch
//! (`git-ns/right/break-glass/0.1`, `git-ns/right/ratify/0.1`,
//! `git-ns/right/break-glass-notice/0.1`).
//!
//! Fixed rule 7 of `git-ns/right/grant/0.3` forbids anyone granting themselves
//! an elevated right (`git.ns.admin`, `git.repo.create`, `git.repo.own`). This
//! module is the one way to do it anyway, and it is built so that nothing
//! about it is quiet:
//!
//! - **explicit**: its own task, with a mandatory justification;
//! - **step-up**: an operation-bound passkey gesture (aal2, user verification)
//!   is *always* required, bound to this one request by digest
//!   ([`crate::acl::bound_step_up`]). The specification cannot require one
//!   (SPEC §7.3 item 13); this VTC does. Because the real step-up applies, the
//!   `elevated_requires_admin` stand-in ([`super::ops::consent_gate`]) does not;
//! - **immediate, no expiry**: it must work when nobody else is there, so the
//!   right lasts until another administrator ratifies or revokes it;
//! - **visible**: a [`AuditSeverity::Critical`](vti_common::audit::AuditSeverity)
//!   audit row with the justification and the step-up evidence, an activity
//!   entry, a signed notice to every other administrator of the namespace, and
//!   the `breakGlass` flag on every surface that shows the record;
//! - **policy may tighten, never quieten**: the community's `gitNamespace`
//!   policy can disable it, delay its effect or demand a longer justification
//!   ([`super::policy::BreakGlassSettings`]); nothing it says reaches
//!   [`announce`].

use std::collections::BTreeSet;

use chrono::{DateTime, Duration, Utc};
use serde_json::{Value, json};
use tracing::{error, info, warn};
use trust_tasks_rs::specs::git_ns::right::{
    break_glass::v0_1 as break_glass, break_glass_notice::v0_1 as notice, ratify::v0_1 as ratify,
};
use vti_common::audit::{AuditEvent, GitNsBreakGlassData};
use vti_common::capability_client::build_document;
use vti_common::error::AppError;

use crate::acl::bound_step_up::{self, EvidencedGate, StepUpEvidence};
use crate::server::AppState;

use super::model::{BreakGlassMark, Namespace, RepoState, Resource, Right, RightRow, Scope};
use super::ops::{
    self, Audit, BREAK_GLASS_DISABLED, BREAK_GLASS_NOT_HEADLESS, NOT_BREAK_GLASS, OpError,
    OpResult, POLICY_DENIED, PolicyInput, RECORD_CHANGED, REPO_NOT_ACTIVE, SELF_RATIFICATION,
    Standing, audit, declared, now, standing,
};
use super::rules::{self, BreakGlassRefusal};
use super::store::{self, Snapshot};
use super::wire;

/// The type URI a break-glass is served and step-up-bound under.
pub fn break_glass_type() -> &'static str {
    <break_glass::Payload as trust_tasks_rs::Payload>::TYPE_URI
}

/// A `git-ns/right/break-glass-notice` event.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Event {
    BreakGlass,
    Ratified,
    Revoked,
}

impl Event {
    pub fn as_str(self) -> &'static str {
        match self {
            Event::BreakGlass => "breakGlass",
            Event::Ratified => "ratified",
            Event::Revoked => "revoked",
        }
    }
}

/// Whether the namespace is headless: no live `git.ns.admin` record whose
/// subject is a current member (`git-ns/namespace/reseat`, *Definitions*).
pub async fn is_headless(state: &AppState, snap: &Snapshot, ns: &Namespace) -> OpResult<bool> {
    let t = now();
    for row in snap
        .rows(&Scope::Namespace(ns.id.clone()))
        .iter()
        .filter(|r| r.right == Right::NsAdmin && r.is_live(t))
    {
        if standing(state, &row.subject).await?.member {
            return Ok(false);
        }
    }
    Ok(true)
}

/// The administrators of a namespace (`git-ns/right/break-glass/0.1`,
/// *Definitions*): every community administrator, and every live
/// `git.ns.admin` of it — current members only — except `except`, who acted.
///
/// Community policy never reaches this: the audience of a break-glass notice
/// cannot be narrowed (`break-glass-notice/0.1`, producer requirement 2).
pub async fn audience(
    state: &AppState,
    snap: &Snapshot,
    ns: &Namespace,
    except: &str,
) -> OpResult<Vec<String>> {
    let now_epoch = crate::auth::session::now_epoch();
    let mut out = BTreeSet::new();
    for entry in crate::acl::list_acl_entries(&state.acl_ks).await? {
        if entry.can(crate::acl::Capability::GitNsAdmin, None)
            && !entry.is_expired(now_epoch)
            && standing(state, &entry.did).await?.community_admin
        {
            out.insert(entry.did.clone());
        }
    }
    for did in rules::admins(snap, &ns.id, now()) {
        if standing(state, &did).await?.member {
            out.insert(did);
        }
    }
    out.remove(except);
    Ok(out.into_iter().collect())
}

/// Tell every administrator of the namespace, and write the critical audit
/// row. Returns an error only when the audit row could not be written — which
/// a break-glass treats as fatal (step 9: no response before it is durable)
/// and a ratification or revocation, already done, logs.
#[allow(clippy::too_many_arguments)]
pub(super) async fn announce(
    state: &AppState,
    snap: &Snapshot,
    ns: &Namespace,
    resource: &Resource,
    row: &RightRow,
    event: Event,
    by: &str,
    statement: Option<String>,
    entitlement: Option<rules::BreakGlassEntitlement>,
    step_up: Option<StepUpEvidence>,
    policy_version: Option<u32>,
) -> Result<(), AppError> {
    let Some(mark) = row.break_glass.as_ref() else {
        return Ok(());
    };
    let at = match event {
        Event::BreakGlass => mark.at,
        Event::Ratified => mark.ratified_at.unwrap_or_else(now),
        Event::Revoked => now(),
    };
    let recipients = audience(state, snap, ns, by).await.map_err(|e| match e {
        OpError::Internal(e) => e,
        other => AppError::Internal(other.to_string()),
    })?;
    let payload = notice_payload(ns, resource, row, event, by, at, statement.as_deref())?;
    let mut notified = 0u32;
    let mut undeliverable = Vec::new();
    for did in &recipients {
        match send_notice(state, did, &payload).await {
            Ok(()) => notified += 1,
            Err(e) => {
                warn!(
                    recipient = %did,
                    event = event.as_str(),
                    error = %e,
                    "a break-glass notice could not be queued"
                );
                undeliverable.push(did.clone());
            }
        }
    }
    if recipients.is_empty() {
        warn!(
            namespace = %ns.id,
            event = event.as_str(),
            "a break-glass event had nobody to tell: no other community or namespace administrator"
        );
    }
    let data = GitNsBreakGlassData {
        event: event.as_str().to_string(),
        namespace: ns.id.clone(),
        resource: resource.to_string(),
        right: row.right.as_str().to_string(),
        break_glass_at: mark.at,
        justification: mark.justification.clone(),
        statement,
        effective_at: mark.effective_at,
        entitlement: entitlement.map(|e| e.as_str().to_string()),
        step_up: step_up.map(Into::into),
        policy_version,
        notified,
        undeliverable,
    };
    error!(
        event = event.as_str(),
        actor = %by,
        subject = %row.subject,
        right = %row.right,
        resource = %resource,
        notified,
        "BREAK-GLASS on a git right"
    );
    if let Some(writer) = state.audit_writer.as_ref() {
        writer
            .write(by, Some(&row.subject), AuditEvent::GitNsBreakGlass(data))
            .await?;
    }
    Ok(())
}

/// The notice's payload, read back through the generated type so a notice
/// this VTC sends is one the specification admits.
fn notice_payload(
    ns: &Namespace,
    resource: &Resource,
    row: &RightRow,
    event: Event,
    by: &str,
    at: DateTime<Utc>,
    statement: Option<&str>,
) -> Result<Value, AppError> {
    let mut v = json!({
        "event": event.as_str(),
        "namespace": ns.id,
        "record": wire::right_record_full(row, resource, true),
        "by": by,
        "at": wire::timestamp(at),
    });
    if let Some(s) = statement.filter(|s| !s.trim().is_empty()) {
        v["statement"] = json!(s);
    }
    let _checked: notice::Payload = wire::into(v.clone())?;
    Ok(v)
}

/// One signed notice, pushed over whichever transport the recipient speaks
/// (TSP > DIDComm > REST, [`crate::member_push`]) — as
/// [`crate::ceremony::removal_notice`] sends: the VTC composed it, so it is
/// signed with the operational key under `authentication` (VTI-KEY-106).
async fn send_notice(state: &AppState, recipient: &str, payload: &Value) -> Result<(), AppError> {
    let vtc_did = state
        .config
        .read()
        .await
        .vtc_did
        .clone()
        .filter(|d| !d.is_empty())
        .ok_or_else(|| AppError::Internal("VTC DID not configured".into()))?;
    let signer = state
        .credential_signer
        .as_ref()
        .ok_or_else(|| AppError::Internal("credential signer not configured".into()))?;
    let type_uri = <notice::Payload as trust_tasks_rs::Payload>::TYPE_URI;
    let doc = build_document(&vtc_did, recipient, type_uri, payload.clone());
    let mut doc_value = serde_json::to_value(&doc)
        .map_err(|e| AppError::Internal(format!("serialise break-glass notice: {e}")))?;
    signer.sign_operational_doc(&mut doc_value).await?;
    // An administrator who is away still needs to hear of it: the long window.
    crate::member_push::push_trust_task(
        state,
        recipient,
        doc_value,
        crate::server::REMOVAL_NOTICE_DELIVER_BY,
    )
    .await?;
    info!(recipient, "break-glass notice queued");
    Ok(())
}

fn non_whitespace_chars(s: &str) -> usize {
    s.chars().filter(|c| !c.is_whitespace()).count()
}

// ── git-ns/right/break-glass/0.1 ────────────────────────────────────────────

/// `git-ns/right/break-glass/0.1`, *Request*, in order.
pub async fn right_break_glass(
    state: &AppState,
    actor_did: &str,
    p: break_glass::Payload,
) -> OpResult<break_glass::Response> {
    let actor = standing(state, actor_did).await?;
    let payload_json = serde_json::to_value(&p).map_err(AppError::from)?;
    let right = Right::parse(payload_json["right"].as_str().unwrap_or_default())
        .ok_or_else(|| OpError::Malformed("`right` is not a git right".into()))?;
    let resource = ops::parse_resource(payload_json["resource"].as_str().unwrap_or_default())?;
    let justification = payload_json["justification"]
        .as_str()
        .unwrap_or_default()
        .to_string();
    if justification.trim().is_empty() {
        return Err(OpError::Malformed(
            "a break-glass needs a justification: say why nobody else could grant this".into(),
        ));
    }

    let _guard = store::write_lock().await;
    let snap = Snapshot::load(&state.git_ns).await?;
    let t = now();
    // Step 2.
    let ns = ops::bound_namespace_for(&snap, &resource)?.clone();
    let scope = if resource.is_namespace() {
        Scope::Namespace(ns.id.clone())
    } else {
        let repo = ops::repo_at(&snap, &resource)?;
        if !matches!(
            repo.state,
            RepoState::Active | RepoState::Orphaned | RepoState::PendingCreate
        ) {
            return Err(declared(
                REPO_NOT_ACTIVE,
                format!("{resource} is {}; it takes no grants", repo.state.as_str()),
            ));
        }
        Scope::Repo(repo.id.clone())
    };
    // Steps 3–5.
    let headless = if resource.is_namespace() {
        is_headless(state, &snap, &ns).await?
    } else {
        false
    };
    let st = super::policy::active_settings(state).await;
    let (passed, entitlement) = rules::break_glass_admitted(
        &snap,
        &actor.did,
        right,
        &resource,
        actor.member,
        actor.community_admin,
        headless,
        st.rules,
        t,
    )
    .map_err(|r| match r {
        BreakGlassRefusal::Rule(r) => OpError::from(r),
        BreakGlassRefusal::NotHeadless(m) => declared(BREAK_GLASS_NOT_HEADLESS, m),
    })?;
    // Step 6 — a record the actor already holds is returned unchanged, and
    // nothing is recorded, audited or announced.
    if let Some(existing) = snap
        .rows(&scope)
        .iter()
        .find(|r| r.subject == actor.did && r.right == right && r.is_recorded(t))
    {
        return Ok(wire::into(json!({
            "right": wire::right_record_full(existing, &resource, true),
        }))?);
    }
    // Step 7 — policy: disable, tighten, defer. Never quieten.
    if !st.break_glass.enabled {
        return Err(declared(
            BREAK_GLASS_DISABLED,
            format!(
                "this community's gitNamespace policy does not allow break-glass; ask another \
                 administrator to grant {right} on {resource}"
            ),
        ));
    }
    if non_whitespace_chars(&justification) < st.break_glass.min_justification_chars {
        return Err(declared(
            POLICY_DENIED,
            format!(
                "this community's policy asks for a justification of at least {} characters",
                st.break_glass.min_justification_chars
            ),
        ));
    }
    let version = ops::check_policy(
        state,
        PolicyInput {
            action: "right.breakGlass",
            actor: &actor,
            actor_rights: rules::effective_on(&snap, &actor.did, &resource, t)
                .into_iter()
                .collect(),
            resource: &resource,
            right: Some(right),
            subject: Some((
                &actor,
                rules::effective_on(&snap, &actor.did, &resource, t)
                    .into_iter()
                    .collect(),
            )),
            visibility: None,
            expires_at: None,
            namespace: Some(&ns),
            passed,
        },
    )
    .await?;

    // The step-up, after every check that decides whether the act is allowed
    // and before anything is written (`bound_step_up`): a passkey gesture
    // bound to this one document, from the acting member's own passkey.
    let reason = format!(
        "BREAK GLASS: give yourself {right} on {resource}. Every other administrator will be \
         told, with your justification."
    );
    let evidence = match bound_step_up::redeem_or_request_with_evidence(
        state,
        &actor.did,
        break_glass_type(),
        &payload_json,
        &reason,
    )
    .await?
    {
        EvidencedGate::Satisfied(e) => e,
        EvidencedGate::Required(request) => {
            return Err(OpError::StepUpRequired {
                message: "a passkey gesture bound to this break-glass is required".into(),
                request,
            });
        }
    };

    // Step 8.
    let effective_at = (st.break_glass.delay_seconds > 0)
        .then(|| t + Duration::seconds(st.break_glass.delay_seconds as i64));
    let mut set = store::get_rights(&state.git_ns, &scope).await?;
    set.rows
        .retain(|r| !(r.subject == actor.did && r.right == right));
    let mut row = ops::new_row(&actor.did, right, &actor.did, actor.member);
    row.granter_was_member = actor.member;
    row.break_glass = Some(BreakGlassMark {
        by: actor.did.clone(),
        at: t,
        justification: justification.clone(),
        effective_at,
        ratified_by: None,
        ratified_at: None,
    });
    let before = store::get_rights(&state.git_ns, &scope).await?;
    set.rows.push(row.clone());
    store::put_rights(&state.git_ns, &scope, &set).await?;
    if let Scope::Repo(id) = &scope
        && right == Right::RepoOwn
        && effective_at.is_none()
        && let Some(mut repo) = snap.repo(id).cloned()
        && repo.state == RepoState::Orphaned
    {
        repo.state = RepoState::Active;
        store::put_repo(&state.git_ns.ks, &repo).await?;
    }

    // Steps 9 and 10. The critical row must be durable before the response;
    // if it cannot be written, the break-glass is undone rather than left
    // unaudited.
    let after = Snapshot::load(&state.git_ns).await?;
    if let Err(e) = announce(
        state,
        &after,
        &ns,
        &resource,
        &row,
        Event::BreakGlass,
        &actor.did,
        None,
        Some(entitlement),
        Some(evidence),
        version,
    )
    .await
    {
        error!(error = %e, "the break-glass audit row could not be written; undoing the break-glass");
        store::put_rights(&state.git_ns, &scope, &before).await?;
        return Err(OpError::Internal(e));
    }
    audit(
        state,
        &actor.did,
        Some(&actor.did),
        Audit {
            action: "gitNs.right.breakGlass",
            namespace: Some(&ns.id),
            resource: Some(resource.to_string()),
            right: Some(right),
            policy_version: version,
            detail: Some(
                if effective_at.is_some() {
                    "delayed"
                } else {
                    "immediate"
                }
                .into(),
            ),
        },
    )
    .await;
    // The other administrators decide it in their action list: a queue item
    // that never lapses into acceptance (`vtc-action-list.md` §8.2). Raised
    // after the Critical row and the notices, which stay what makes a
    // break-glass visible; the sweeper raises it if this one is lost.
    crate::admin_actions::queues::raise_break_glass(state, &ns, &resource, &row).await;
    Ok(wire::into(json!({
        "right": wire::right_record_full(&row, &resource, true),
    }))?)
}

// ── git-ns/right/ratify/0.1 ─────────────────────────────────────────────────

/// `git-ns/right/ratify/0.1`, *Request*, in order.
pub async fn right_ratify(
    state: &AppState,
    actor_did: &str,
    p: ratify::Payload,
) -> OpResult<ratify::Response> {
    let actor: Standing = standing(state, actor_did).await?;
    let pj = serde_json::to_value(&p).map_err(AppError::from)?;
    let right = Right::parse(pj["right"].as_str().unwrap_or_default())
        .ok_or_else(|| OpError::Malformed("`right` is not a git right".into()))?;
    let resource = ops::parse_resource(pj["resource"].as_str().unwrap_or_default())?;
    let subject = pj["subject"].as_str().unwrap_or_default().to_string();
    ops::did_core("subject", &subject)?;
    let read_at = p.break_glass_at;
    let statement = p.statement.as_ref().map(|s| s.to_string());

    let _guard = store::write_lock().await;
    let snap = Snapshot::load(&state.git_ns).await?;
    let t = now();
    let not_bg = || {
        declared(
            NOT_BREAK_GLASS,
            format!(
                "no unratified break-glass record gives {subject} {right} on {resource}: there is \
                 none, it was never a break-glass, or it is already ratified"
            ),
        )
    };
    // Step 1.
    let scope = ops::scope_for(&snap, &resource)?.ok_or_else(not_bg)?;
    let row = snap
        .rows(&scope)
        .iter()
        .find(|r| {
            r.subject == subject
                && r.right == right
                && r.is_recorded(t)
                && r.is_unratified_break_glass()
        })
        .cloned()
        .ok_or_else(not_bg)?;
    let mark = row.break_glass.clone().ok_or_else(not_bg)?;
    // Step 2 — bound to the break-glass the ratifier read.
    if wire::timestamp(mark.at) != wire::timestamp(read_at) {
        return Err(declared(
            RECORD_CHANGED,
            format!(
                "the break-glass on record was made at {}, not {}; read it and its \
                 justification again before ratifying",
                wire::timestamp(mark.at),
                wire::timestamp(read_at)
            ),
        ));
    }
    // Step 3.
    if subject == actor.did {
        return Err(declared(
            SELF_RATIFICATION,
            "a break-glass is ratified by another administrator, or not at all",
        ));
    }
    let st = super::policy::active_settings(state).await;
    let passed = rules::ratify_admitted(
        &snap,
        &actor.did,
        &row,
        &resource,
        actor.community_admin,
        st.rules,
        t,
    )?;
    ops::consent_gate(state, &actor, "right.grant", Some(right)).await?;
    let ns = snap.scope_namespace(&scope).cloned().ok_or_else(not_bg)?;
    // Step 4.
    let subject_standing = standing(state, &subject).await?;
    let version = ops::check_policy(
        state,
        PolicyInput {
            action: "right.ratify",
            actor: &actor,
            actor_rights: rules::effective_on(&snap, &actor.did, &resource, t)
                .into_iter()
                .collect(),
            resource: &resource,
            right: Some(right),
            subject: Some((&subject_standing, vec![right])),
            visibility: None,
            expires_at: None,
            namespace: Some(&ns),
            passed,
        },
    )
    .await?;
    // Step 5.
    let mut set = store::get_rights(&state.git_ns, &scope).await?;
    let Some(stored) = set
        .rows
        .iter_mut()
        .find(|r| r.subject == subject && r.right == right && r.is_unratified_break_glass())
    else {
        return Err(not_bg());
    };
    if let Some(m) = stored.break_glass.as_mut() {
        m.ratified_by = Some(actor.did.clone());
        m.ratified_at = Some(t);
    }
    let ratified = stored.clone();
    store::put_rights(&state.git_ns, &scope, &set).await?;
    // Step 6.
    let after = Snapshot::load(&state.git_ns).await?;
    if let Err(e) = announce(
        state,
        &after,
        &ns,
        &resource,
        &ratified,
        Event::Ratified,
        &actor.did,
        statement,
        None,
        None,
        version,
    )
    .await
    {
        error!(error = %e, "the ratification's audit row could not be written");
    }
    audit(
        state,
        &actor.did,
        Some(&subject),
        Audit {
            action: "gitNs.right.breakGlassRatified",
            namespace: Some(&ns.id),
            resource: Some(resource.to_string()),
            right: Some(right),
            policy_version: version,
            detail: None,
        },
    )
    .await;
    // The ratification item, if one is open, closes with the decider named —
    // however the ratification arrived (`vtc-action-list.md` §8.2).
    crate::admin_actions::queues::break_glass_ended(
        state,
        &resource.to_string(),
        right.as_str(),
        &subject,
        &wire::timestamp(mark.at),
        true,
        &actor.did,
    )
    .await;
    Ok(wire::into(json!({
        "right": wire::right_record_full(&ratified, &resource, true),
    }))?)
}

// ── The action list's ratification queue (`vtc-action-list.md` §8.2) ───────

/// An unratified break-glass record, as the action list raises it for the
/// other administrators of its namespace to ratify or revoke.
#[derive(Debug, Clone)]
pub struct Unratified {
    pub namespace: Namespace,
    pub resource: Resource,
    pub row: RightRow,
}

/// Every unratified break-glass record held now — what the action list keeps
/// one open ratification item for each of.
pub async fn unratified(state: &AppState) -> Result<Vec<Unratified>, AppError> {
    let snap = Snapshot::load(&state.git_ns).await?;
    let t = now();
    let mut out = Vec::new();
    for (scope, set) in &snap.rights {
        let (Some(ns), Some(resource)) = (snap.scope_namespace(scope), snap.scope_resource(scope))
        else {
            continue;
        };
        for row in set
            .rows
            .iter()
            .filter(|r| r.is_unratified_break_glass() && r.is_recorded(t))
        {
            out.push(Unratified {
                namespace: ns.clone(),
                resource: resource.clone(),
                row: row.clone(),
            });
        }
    }
    Ok(out)
}

/// Where one break-glass record stands, found by what its ratification item
/// recorded: the resource, the right, the subject and its `breakGlass.at`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RecordState {
    /// Held, and nobody has ratified it.
    Unratified,
    /// Ratified, by this administrator.
    Ratified { by: String },
    /// Not held any more: revoked, resigned, or its namespace or repository
    /// changed — or a later break-glass replaced it.
    Gone,
}

/// The state of the break-glass `subject` made for `right` on `resource` at
/// `at` (`wire::timestamp` form).
pub async fn record_state(
    state: &AppState,
    resource: &str,
    right: &str,
    subject: &str,
    at: &str,
) -> Result<RecordState, AppError> {
    let (Ok(resource), Some(right)) = (Resource::parse(resource), Right::parse(right)) else {
        return Ok(RecordState::Gone);
    };
    let snap = Snapshot::load(&state.git_ns).await?;
    let Ok(Some(scope)) = ops::scope_for(&snap, &resource) else {
        return Ok(RecordState::Gone);
    };
    let t = now();
    let Some(row) = snap.rows(&scope).iter().find(|r| {
        r.subject == subject
            && r.right == right
            && r.is_recorded(t)
            && r.break_glass
                .as_ref()
                .is_some_and(|m| wire::timestamp(m.at) == at)
    }) else {
        return Ok(RecordState::Gone);
    };
    Ok(
        match row.break_glass.as_ref().and_then(|m| m.ratified_by.clone()) {
            Some(by) => RecordState::Ratified { by },
            None => RecordState::Unratified,
        },
    )
}

/// The ratification item's record for one break-glass: what the deciders are
/// shown, and what `git-ns/right/ratify` and `git-ns/right/revoke` are then
/// called with.
pub fn review_record(ns: &Namespace, resource: &Resource, row: &RightRow) -> Option<Value> {
    let mark = row.break_glass.as_ref()?;
    let mut v = json!({
        "namespace": ns.id,
        "resource": resource.to_string(),
        "right": row.right.as_str(),
        "subject": row.subject,
        "breakGlassAt": wire::timestamp(mark.at),
        "justification": mark.justification,
    });
    if let Some(at) = mark.effective_at {
        v["effectiveAt"] = json!(wire::timestamp(at));
    }
    Some(v)
}

/// The capability whose holders decide a break-glass on `ns`: `git.ns.admin`
/// at the namespace — its namespace administrators and the community-wide
/// holders (`git-ns/right/break-glass/0.1`, *Definitions*).
pub fn review_stake(ns: &Namespace) -> crate::acl::CapRef {
    crate::acl::CapRef::new(
        crate::acl::Capability::GitNsAdmin,
        Some(crate::acl::resource_grant::namespace_qualifier(
            &ns.forge, &ns.owner,
        )),
    )
}