Skip to main content

basil_core/core/
state.rs

1// SPDX-FileCopyrightText: 2026 OpenBasil Contributors
2//
3// SPDX-License-Identifier: Apache-2.0
4
5//! Shared broker state: a hot-swappable policy **generation** + the backend
6//! manager, constructed once at startup and shared (`Arc`) across connections.
7//!
8//! [`BrokerState`] is the single object the gRPC service adapters share. It
9//! bundles:
10//!
11//! - the active [`Generation`]: the loaded **catalog**, **resolved policy**
12//!   index, and export-resolved **config** tables that are the inputs to the
13//!   [`Pdp`] (`vault-1l8`), plus a monotonic generation **id**, held behind an
14//!   [`arc_swap::ArcSwap`] so a future reload (`basil-y3e.2`) can atomically swap
15//!   in a fresh generation without restarting the broker, and
16//! - the [`BackendManager`] (`vault-jso`) that routes an allowed op to its backend.
17//!
18//! **Generation pinning.** The catalog/policy/config triple is no longer
19//! immutable for the broker's lifetime: a SIGHUP reload may replace it atomically.
20//! To keep each operation coherent (never deciding with an old catalog but a new
21//! policy), every RPC snapshots the generation **once** at request entry via
22//! [`BrokerState::load_generation`] and uses that one [`Generation`] (its
23//! [`Generation::pdp`], [`Generation::config`], and [`Generation::id`]) for the
24//! whole op. Holding a single snapshot makes cross-generation coherence true by
25//! construction. The manager, limits, audit sink, and event source remain
26//! lifetime-immutable and live directly on [`BrokerState`].
27//!
28//! Today there is exactly one generation (id `1`); this iteration lands only the
29//! pinning plumbing: there is no reload trigger yet (`basil-y3e.2`).
30
31use std::sync::Arc;
32use std::sync::Mutex;
33use std::time::{Duration, Instant};
34
35use arc_swap::{ArcSwap, Guard};
36
37use crate::audit::{AuditLog, ReloadActor};
38use crate::catalog::policy::{Config, ResolvedPolicy};
39use crate::catalog::{Catalog, Pdp};
40use crate::core::crypto_provider::{ProviderAuditEvent, ProviderAuditOutcome};
41use crate::decision::DecisionRecord;
42use crate::event::EventSource;
43use crate::manager::{BackendManager, ManagerError};
44use crate::reload::ReloadInputs;
45use crate::revocation::JwtRevocationStore;
46
47/// The generation id assigned to the broker's first (startup) generation.
48///
49/// The id is a monotonic counter bumped on each successful reload; it starts at
50/// `1` so `0` can never be mistaken for a live generation.
51pub const INITIAL_GENERATION_ID: u64 = 1;
52
53/// One coherent snapshot of the reloadable policy surface.
54///
55/// A `Generation` bundles the [`Catalog`], [`ResolvedPolicy`] index, and
56/// export-resolved [`Config`] tables that together drive a [`Pdp`] decision, plus
57/// a monotonic [`id`](Generation::id) that names this snapshot in the audit trail.
58/// It is the unit that [`BrokerState`] swaps atomically on reload: an operation
59/// that pins one `Generation` sees an internally consistent
60/// `(catalog, policy, config)` triple for its entire lifetime, so a concurrent
61/// reload can never mix an old catalog with a new policy.
62#[derive(Debug)]
63pub struct Generation {
64    /// Monotonic generation id (starts at [`INITIAL_GENERATION_ID`], bumped on
65    /// each successful reload). Carried into the audit record.
66    id: u64,
67    catalog: Arc<Catalog>,
68    policy: ResolvedPolicy,
69    config: Config,
70}
71
72impl Generation {
73    /// Bundle a `(catalog, policy, config)` triple under a generation `id`.
74    #[must_use]
75    pub fn new(
76        id: u64,
77        catalog: impl Into<Arc<Catalog>>,
78        policy: ResolvedPolicy,
79        config: Config,
80    ) -> Self {
81        Self {
82            id,
83            catalog: catalog.into(),
84            policy,
85            config,
86        }
87    }
88
89    /// This generation's monotonic id (for the audit record / status probe).
90    #[must_use]
91    pub const fn id(&self) -> u64 {
92        self.id
93    }
94
95    /// A [`Pdp`] borrowing this generation's catalog/policy/config for one
96    /// decision.
97    ///
98    /// The PDP is `Copy` and holds only shared borrows into this generation, so
99    /// this is a cheap view, not a clone. The borrow ties the PDP to the
100    /// generation snapshot, keeping the whole decision coherent.
101    #[must_use]
102    pub fn pdp(&self) -> Pdp<'_> {
103        Pdp::new(&self.catalog, &self.policy, &self.config)
104    }
105
106    /// The export-resolved config tables (for `name(num)` audit rendering).
107    #[must_use]
108    pub const fn config(&self) -> &Config {
109        &self.config
110    }
111
112    /// This generation's resolved authorization policy.
113    #[must_use]
114    pub const fn policy(&self) -> &ResolvedPolicy {
115        &self.policy
116    }
117
118    /// This generation's loaded [`Catalog`].
119    ///
120    /// Used by the reload engine (`basil-y3e.2`) to compare the candidate's
121    /// restart-only routing shape against the currently-serving generation.
122    #[must_use]
123    pub fn catalog(&self) -> &Catalog {
124        &self.catalog
125    }
126}
127
128/// The default `max_encrypt_size`: 1 MiB (wire-protocol-v2 §2.1).
129pub const DEFAULT_MAX_ENCRYPT_SIZE: usize = 1024 * 1024;
130
131/// The default `max_payload_size`: 1 MiB.
132///
133/// Bounds the `set` value and the `import` key material broker-side
134/// (wire-protocol-v2 §2.1, "same mechanism" as the AEAD cap), returning
135/// `payload_too_large` instead of relying on the u32 frame ceiling (`vault-sao`).
136pub const DEFAULT_MAX_PAYLOAD_SIZE: usize = 1024 * 1024;
137
138/// The default rotation grace window, in key versions (`vault-xhq`).
139///
140/// A ciphertext/signature made up to this many versions back still
141/// decrypts/verifies. `1` honors the single previous version (plus the latest);
142/// raise it for a longer window, or set `0` to honor *only* the newest version
143/// (the compromise/panic setting).
144pub const DEFAULT_ROTATION_GRACE_VERSIONS: u32 = 1;
145
146/// Default SPIFFE SVID lifetime in seconds.
147pub const DEFAULT_SVID_TTL_SECS: u64 = 300;
148
149/// Broker-wide runtime limits + rotation policy, supplied by the binary at
150/// startup and shared (immutable) across connections.
151///
152/// These are *broker* knobs (not catalog/policy data): payload caps, SVID
153/// lifetime, and the rotation grace/retention windows the manager applies on
154/// `rotate` + the retention sweep (`vault-xhq` / `vault-uo1`).
155#[derive(Debug, Clone, Copy)]
156pub struct BrokerLimits {
157    /// Cap (bytes) on the `encrypt` plaintext **and** the `decrypt` ciphertext;
158    /// over-limit → `payload_too_large` (wire §2.1). Default
159    /// [`DEFAULT_MAX_ENCRYPT_SIZE`].
160    pub max_encrypt_size: usize,
161    /// Cap (bytes) on the `set` value and the `import` key material; over-limit →
162    /// `payload_too_large` (wire §2.1, "same mechanism" as the AEAD cap). This is
163    /// the broker-side max that replaces relying on the u32 frame ceiling
164    /// (`vault-sao`). Default [`DEFAULT_MAX_PAYLOAD_SIZE`].
165    pub max_payload_size: usize,
166    /// Rotation grace window in **key versions**: on `rotate`, the manager raises
167    /// the backend's `min_decryption_version` to `new_version - grace_versions`
168    /// (clamped at 1), so versions older than the window stop decrypting/verifying
169    /// while the in-window ones still do. Default
170    /// [`DEFAULT_ROTATION_GRACE_VERSIONS`].
171    pub grace_versions: u32,
172    /// Lifetime, in seconds, for SPIFFE SVIDs minted by the Workload API. Default
173    /// [`DEFAULT_SVID_TTL_SECS`].
174    pub svid_ttl_secs: u64,
175    /// Retention floor in **key versions**: [`BrokerLimits::retention_floor`]
176    /// raises the backend's `min_available_version` to
177    /// `latest - retain_versions` (clamped at 1), irreversibly pruning archived
178    /// key material below it. `None` disables the sweep (retain everything).
179    pub retain_versions: Option<u32>,
180}
181
182impl Default for BrokerLimits {
183    fn default() -> Self {
184        Self {
185            max_encrypt_size: DEFAULT_MAX_ENCRYPT_SIZE,
186            max_payload_size: DEFAULT_MAX_PAYLOAD_SIZE,
187            grace_versions: DEFAULT_ROTATION_GRACE_VERSIONS,
188            svid_ttl_secs: DEFAULT_SVID_TTL_SECS,
189            retain_versions: None,
190        }
191    }
192}
193
194impl BrokerLimits {
195    /// The grace floor (`min_decryption_version`) for a key now at `latest`:
196    /// `latest - grace_versions`, clamped to at least `1`.
197    #[must_use]
198    pub const fn grace_floor(&self, latest: u32) -> u32 {
199        let floor = latest.saturating_sub(self.grace_versions);
200        if floor < 1 { 1 } else { floor }
201    }
202
203    /// The retention floor (`min_available_version`) for a key now at `latest`,
204    /// or `None` when retention is disabled. `latest - retain_versions`, clamped
205    /// to at least `1` (never prunes the only/last version).
206    #[must_use]
207    pub const fn retention_floor(&self, latest: u32) -> Option<u32> {
208        match self.retain_versions {
209            Some(retain) => {
210                let floor = latest.saturating_sub(retain);
211                Some(if floor < 1 { 1 } else { floor })
212            }
213            None => None,
214        }
215    }
216}
217
218/// How long a computed readiness probe is reused before re-fanning-out to the
219/// backend (`basil-8nwy`).
220///
221/// The admin `Readiness` RPC runs one metadata/KV read **per catalog key** against
222/// the backend. It is ungated (any socket peer may call it), so without a cache a
223/// hostile local peer could hammer `basil ready` to amplify N backend reads. A
224/// short TTL bounds that fan-out to at most one probe per window while staying well
225/// under any sane liveness/readiness poll cadence, so a real readiness transition
226/// is still surfaced within [`READINESS_CACHE_TTL`]. A generation change
227/// (hot reload) invalidates the cache immediately regardless of the TTL.
228pub const READINESS_CACHE_TTL: Duration = Duration::from_secs(2);
229
230/// The coarse readiness category a probe resolved to: the proto-free core of the
231/// admin `Readiness` summary (the service layer maps it onto the wire enum).
232#[derive(Debug, Clone, Copy, PartialEq, Eq)]
233pub enum ReadinessState {
234    /// Every `missing=error` key is present and the backend was reachable.
235    Ready,
236    /// At least one `missing=error` key's material is absent: its ops would fail
237    /// closed.
238    RequiredKeyMissing,
239    /// The backend was unreachable/rejecting during the probe (fail closed). The
240    /// per-key counts are unknown in this arm and reported as zero.
241    BackendUnreachable,
242}
243
244/// The non-secret outcome of one readiness probe.
245///
246/// Carries the coarse [`ReadinessState`] plus the key counts the admin summary
247/// reports. It is generation-independent (the serving generation id is stamped on
248/// the wire response by the caller), so a cached outcome is reused only while it
249/// still matches the generation that produced it (see [`CachedReadiness`]).
250#[derive(Debug, Clone, Copy, PartialEq, Eq)]
251pub struct ReadinessOutcome {
252    /// The coarse readiness category.
253    pub state: ReadinessState,
254    /// Total catalog keys probed (`0` when the backend was unreachable).
255    pub keys_total: u32,
256    /// Keys whose material is present.
257    pub keys_present: u32,
258    /// Absent `missing=error` keys (the ones that block readiness).
259    pub keys_required_missing: u32,
260    /// Absent `missing=warn`/`generate` keys (which do not block readiness).
261    pub keys_optional_missing: u32,
262}
263
264impl ReadinessOutcome {
265    /// Whether the broker is ready (no required key absent, backend reachable).
266    #[must_use]
267    pub const fn ready(&self) -> bool {
268        matches!(self.state, ReadinessState::Ready)
269    }
270}
271
272/// A cached readiness probe: the [`ReadinessOutcome`] plus the generation it was
273/// computed for and the [`Instant`] after which it is stale (the TTL deadline).
274#[derive(Debug, Clone, Copy)]
275struct CachedReadiness {
276    outcome: ReadinessOutcome,
277    generation: u64,
278    expires_at: Instant,
279}
280
281/// The shared broker state: the loaded policy surface plus the backend manager.
282///
283/// Construct once with [`BrokerState::new`] and wrap in an `Arc`; the accept loop
284/// clones the `Arc` into every connection handler.
285#[derive(Debug)]
286pub struct BrokerState {
287    /// The active policy generation, swapped atomically on reload (`basil-y3e`).
288    /// Every RPC loads exactly one snapshot of this and pins the whole op to it.
289    generation: ArcSwap<Generation>,
290    manager: BackendManager,
291    /// A stable backend label reported in a `status` response. The manager does
292    /// not expose its backend kinds, so the binary supplies one at construction
293    /// (e.g. `"vault"`); `vault-i9j`'s `list`/metadata work can refine this.
294    backend_label: String,
295    /// Broker-wide payload caps + rotation grace/retention policy.
296    limits: BrokerLimits,
297    /// Optional JSONL audit sink (`vault-vq5`): when `Some`, every recorded
298    /// decision is also appended as one JSON line to an append-only file. `None`
299    /// disables file-audit (the `tracing` log is always emitted regardless). Held
300    /// behind an `Arc` because the sink is shared, immutable, and internally
301    /// synchronized; the field is cloneable into the per-op audit call.
302    audit: Option<Arc<AuditLog>>,
303    events: EventSource,
304    jwt_revocations: JwtRevocationStore,
305    /// The configured on-disk catalog/policy paths the SIGHUP reload engine
306    /// (`basil-y3e.2`) re-reads from. `None` disables reload (the broker has no
307    /// configured paths to re-read); a SIGHUP then only reopens the audit log.
308    reload_inputs: Option<ReloadInputs>,
309    /// A short TTL cache of the last admin readiness probe (`basil-8nwy`), so a
310    /// burst of ungated `Readiness` RPCs re-fans-out to the backend at most once
311    /// per [`READINESS_CACHE_TTL`] instead of per call. Guarded by a `Mutex`; the
312    /// backend probe is never run while the lock is held, and the cache is bypassed
313    /// when the serving generation has changed since the cached probe.
314    readiness_cache: Mutex<Option<CachedReadiness>>,
315}
316
317impl BrokerState {
318    /// Bundle the loaded policy surface (the `load()` 4-tuple's first three
319    /// elements) with an already-constructed [`BackendManager`].
320    ///
321    /// `backend_label` is the name a `status` response advertises (the backend
322    /// `kind()`; with one backend today this is unambiguous). The manager is built
323    /// separately because building backends from credentials is the binary's job
324    /// (`vault-vh1`); this layer only routes + authorizes.
325    #[must_use]
326    pub fn new(
327        catalog: Catalog,
328        policy: ResolvedPolicy,
329        config: Config,
330        manager: BackendManager,
331        backend_label: impl Into<String>,
332    ) -> Self {
333        Self::with_limits(
334            Arc::new(catalog),
335            policy,
336            config,
337            manager,
338            backend_label,
339            BrokerLimits::default(),
340        )
341    }
342
343    /// Like [`BrokerState::new`] but with explicit broker [`BrokerLimits`] (the
344    /// AEAD payload cap + rotation grace/retention policy the binary threads from
345    /// its args). [`BrokerState::new`] uses [`BrokerLimits::default`].
346    #[must_use]
347    pub fn with_limits(
348        catalog: impl Into<Arc<Catalog>>,
349        policy: ResolvedPolicy,
350        config: Config,
351        manager: BackendManager,
352        backend_label: impl Into<String>,
353        limits: BrokerLimits,
354    ) -> Self {
355        let generation = Generation::new(INITIAL_GENERATION_ID, catalog, policy, config);
356        Self {
357            generation: ArcSwap::from_pointee(generation),
358            manager,
359            backend_label: backend_label.into(),
360            limits,
361            audit: None,
362            events: EventSource::new(),
363            jwt_revocations: JwtRevocationStore::default(),
364            reload_inputs: None,
365            readiness_cache: Mutex::new(None),
366        }
367    }
368
369    /// Attach a JSONL audit sink (`vault-vq5`), consuming and returning `self`.
370    ///
371    /// When set, [`BrokerState::audit`] appends one JSONL line per recorded
372    /// decision to the open append-only file; when this is never called, file
373    /// audit is disabled (`tracing` still logs every decision). The binary opens
374    /// the file once at startup and threads the [`AuditLog`] in here.
375    #[must_use]
376    pub fn with_audit_log(mut self, audit: Arc<AuditLog>) -> Self {
377        self.audit = Some(audit);
378        self
379    }
380
381    /// Attach the JWT-SVID revocation deny-list loaded at startup.
382    #[must_use]
383    pub fn with_jwt_revocations(mut self, jwt_revocations: JwtRevocationStore) -> Self {
384        self.jwt_revocations = jwt_revocations;
385        self
386    }
387
388    /// Record the configured on-disk catalog/policy paths so the SIGHUP reload
389    /// engine (`basil-y3e.2`) can re-read from the **same** paths startup used.
390    ///
391    /// Without this, [`BrokerState::reload_inputs`] is `None` and a reload fails
392    /// closed with `ReloadError::NoInputs` (a SIGHUP then only reopens the audit
393    /// log). The broker never reads catalog/policy from an unconfigured source.
394    #[must_use]
395    pub fn with_reload_inputs(mut self, inputs: ReloadInputs) -> Self {
396        self.reload_inputs = Some(inputs);
397        self
398    }
399
400    /// The configured catalog/policy paths the reload engine re-reads, if any.
401    #[must_use]
402    pub const fn reload_inputs(&self) -> Option<&ReloadInputs> {
403        self.reload_inputs.as_ref()
404    }
405
406    /// The id of the **currently serving** generation (observable for the status
407    /// probe, `basil-s7h`, and the reload audit). A monotonic counter bumped on
408    /// each successful reload.
409    #[must_use]
410    pub fn active_generation_id(&self) -> u64 {
411        self.load_generation().id()
412    }
413
414    /// Return the cached readiness outcome if one was computed for the
415    /// currently-serving generation within [`READINESS_CACHE_TTL`] (`basil-8nwy`).
416    ///
417    /// A cache hit lets the admin `Readiness` RPC answer **without** re-fanning-out
418    /// one backend read per catalog key: the amplification a hostile, ungated
419    /// socket peer could otherwise drive. The entry is bypassed (re-probe required)
420    /// when it has expired **or** when the serving generation has changed since it
421    /// was cached, so a hot reload that alters the key set can never be masked
422    /// longer than it takes to recompute, and a stale generation's counts are never
423    /// served. Returns `None` to mean "no usable cache; probe the backend".
424    ///
425    /// The returned outcome is generation-independent; the caller stamps the
426    /// current generation id onto the wire response.
427    #[must_use]
428    pub fn cached_readiness(&self) -> Option<ReadinessOutcome> {
429        let generation = self.active_generation_id();
430        let now = Instant::now();
431        // Copy the small entry out and release the lock immediately; the validity
432        // check (and any caller work) never runs while the mutex is held.
433        let cached = {
434            let guard = self.readiness_cache.lock().ok()?;
435            (*guard)?
436        };
437        (cached.generation == generation && now < cached.expires_at).then_some(cached.outcome)
438    }
439
440    /// Store a freshly-computed readiness `outcome` for `generation`, valid for
441    /// [`READINESS_CACHE_TTL`] from now (`basil-8nwy`). A subsequent
442    /// [`BrokerState::cached_readiness`] within that window (and on the same
443    /// generation) reuses it instead of re-probing the backend.
444    ///
445    /// A poisoned lock is swallowed (the cache is a best-effort optimization, never
446    /// a correctness or liveness dependency): the worst case is a missed cache and
447    /// one extra probe, never a panic on the serving path.
448    pub fn cache_readiness(&self, generation: u64, outcome: ReadinessOutcome) {
449        if let Ok(mut guard) = self.readiness_cache.lock() {
450            *guard = Some(CachedReadiness {
451                outcome,
452                generation,
453                expires_at: Instant::now() + READINESS_CACHE_TTL,
454            });
455        }
456    }
457
458    /// Atomically swap in a new [`Generation`], replacing the currently serving
459    /// one. The **only** mutation point of the reloadable policy surface.
460    ///
461    /// Callers (the reload engine, `basil-y3e.2`) must have already validated the
462    /// new generation; this is the unconditional store. In-flight operations that
463    /// pinned the previous generation via [`BrokerState::load_generation`] keep
464    /// seeing it until they drop their guard. The swap never disturbs an op
465    /// already in progress.
466    pub fn swap_generation(&self, generation: Arc<Generation>) {
467        self.generation.store(generation);
468    }
469
470    /// Snapshot the active [`Generation`] for the lifetime of one operation.
471    ///
472    /// This is the **one** point an RPC pins its generation: call it once at
473    /// request entry, then drive the whole op off the returned guard
474    /// ([`Generation::pdp`], [`Generation::config`], [`Generation::id`]) so the
475    /// `(catalog, policy, config)` triple stays coherent even if a concurrent
476    /// reload swaps in a newer generation mid-op. Hold the guard only as long as
477    /// the op needs it (it pins the snapshot from being reclaimed); if the
478    /// snapshot must survive an `.await`, clone the inner `Arc` out of the guard
479    /// rather than holding the guard across the suspension point.
480    #[must_use]
481    pub fn load_generation(&self) -> Guard<Arc<Generation>> {
482        self.generation.load()
483    }
484
485    /// Record one authorization decision (`vault-vq5`): emit it to `tracing`
486    /// (allow=info, deny=warn) **and**, when a JSONL audit sink is configured,
487    /// append it as one line to the append-only audit file.
488    ///
489    /// The file append is **best-effort**: an IO error is logged and swallowed by
490    /// the sink so an audit-disk problem can never block, deny, or panic the data
491    /// plane: the trustworthy decision already happened and is in `tracing`. This
492    /// is the single hook the handler calls for every gated op, allow or deny.
493    pub fn record_decision(&self, record: &DecisionRecord) {
494        record.record();
495        if let Some(audit) = &self.audit {
496            audit.append(record);
497        }
498    }
499
500    /// Record one software-custody provider operation (`wuj.7`): emit it to
501    /// `tracing` (failure/deny at `warn`, allow/success at `info`) and, when a
502    /// JSONL audit sink is configured, append the secret-free
503    /// [`ProviderAuditEvent`] JSON as one line. The event carries the selected
504    /// provider and algorithm and **never** any seed, signature, plaintext, or
505    /// ciphertext bytes. Best-effort like [`Self::record_decision`]: it can never
506    /// block, fail, or panic the data plane.
507    pub fn record_provider_event(&self, event: &ProviderAuditEvent<'_>) {
508        match event.outcome {
509            ProviderAuditOutcome::Failure | ProviderAuditOutcome::Deny => tracing::warn!(
510                event = "basil.audit.provider_operation",
511                op = event.op,
512                key = event.key_id,
513                algorithm = event.algorithm,
514                outcome = ?event.outcome,
515                reason = event.reason,
516                "software-custody provider operation",
517            ),
518            ProviderAuditOutcome::Allow | ProviderAuditOutcome::Success => tracing::info!(
519                event = "basil.audit.provider_operation",
520                op = event.op,
521                key = event.key_id,
522                algorithm = event.algorithm,
523                outcome = ?event.outcome,
524                reason = event.reason,
525                "software-custody provider operation",
526            ),
527        }
528        if let Some(audit) = &self.audit {
529            audit.append_value(&event.to_json_value());
530        }
531    }
532
533    /// Record a generation reload outcome (`basil-y3e.2`, `basil-atq`): emit it to
534    /// `tracing` and, when a JSONL audit sink is configured, append one
535    /// `basil.audit.reload` line.
536    ///
537    /// `outcome` is one of `"applied"` (a real swap happened, logged at `info`),
538    /// `"checked"` (an admin `--check` dry-run validated, no swap, `info`), or
539    /// `"rejected"` (the candidate failed; previous generation keeps serving,
540    /// `warn`). `reason` is a short, stable, non-secret token (e.g. `signal`,
541    /// `admin_rpc`, or a [`ReloadError`](crate::reload::ReloadError) audit token).
542    /// `actor` attributes the trigger ([`ReloadActor::Sighup`] for the signal path
543    /// or [`ReloadActor::Caller`] with the attested uid for the admin RPC), the
544    /// only field that differs in the audit trail between an otherwise-identical
545    /// SIGHUP and RPC reload (`basil-ftmc`). Like [`BrokerState::record_decision`],
546    /// the file append is best-effort and can never block, fail, or panic the broker.
547    pub fn record_reload(
548        &self,
549        previous_generation: u64,
550        new_generation: u64,
551        outcome: &str,
552        reason: &str,
553        actor: ReloadActor,
554    ) {
555        match outcome {
556            "applied" => tracing::info!(
557                event = "basil.audit.reload",
558                previous_generation,
559                generation = new_generation,
560                outcome,
561                reason,
562                "catalog/policy reload applied",
563            ),
564            "checked" => tracing::info!(
565                event = "basil.audit.reload",
566                previous_generation,
567                generation = new_generation,
568                outcome,
569                reason,
570                "catalog/policy reload dry-run validated; no swap",
571            ),
572            _ => tracing::warn!(
573                event = "basil.audit.reload",
574                previous_generation,
575                generation = new_generation,
576                outcome,
577                reason,
578                "catalog/policy reload rejected; previous generation still serving",
579            ),
580        }
581        if let Some(audit) = &self.audit {
582            audit.append_reload(previous_generation, new_generation, outcome, reason, actor);
583        }
584    }
585
586    /// The backend manager that routes an allowed op to its backend instance.
587    #[must_use]
588    pub const fn manager(&self) -> &BackendManager {
589        &self.manager
590    }
591
592    /// The backend label advertised in a `status` response.
593    #[must_use]
594    pub fn backend_label(&self) -> &str {
595        &self.backend_label
596    }
597
598    /// The broker-wide payload caps + rotation grace/retention policy.
599    #[must_use]
600    pub const fn limits(&self) -> BrokerLimits {
601        self.limits
602    }
603
604    /// Shared broker event source.
605    #[must_use]
606    pub const fn events(&self) -> &EventSource {
607        &self.events
608    }
609
610    /// JWT-SVID revocation deny-list shared by Workload API validation.
611    #[must_use]
612    pub const fn jwt_revocations(&self) -> &JwtRevocationStore {
613        &self.jwt_revocations
614    }
615
616    /// Re-read the catalog-backed JWT-SVID deny-list and merge it into memory.
617    ///
618    /// This stays outside the hot-swapped [`Generation`]: the deny-list is mutable
619    /// serving state, and refresh uses union semantics so a live revocation cannot
620    /// be clobbered by a concurrent reload.
621    ///
622    /// # Errors
623    ///
624    /// Returns [`ManagerError`] if the configured store is malformed, unreadable,
625    /// or the live deny-list locks are poisoned. On error the previous in-memory
626    /// set remains serving.
627    pub async fn refresh_jwt_revocations(&self) -> Result<(), ManagerError> {
628        self.jwt_revocations
629            .refresh_from_manager(&self.manager)
630            .await
631    }
632
633    /// Persist and publish a JWT-SVID revocation.
634    ///
635    /// # Errors
636    ///
637    /// Returns [`crate::manager::ManagerError`] if the optional catalog-backed
638    /// deny-list write fails.
639    pub async fn revoke_jwt_svid(
640        &self,
641        trust_domain: &str,
642        jti: &str,
643        expires_at_unix: u64,
644    ) -> Result<(), crate::manager::ManagerError> {
645        self.jwt_revocations
646            .insert(trust_domain, jti, expires_at_unix)?;
647        self.jwt_revocations.persist(&self.manager).await?;
648        self.events.revoked(trust_domain, jti);
649        Ok(())
650    }
651}
652
653#[cfg(test)]
654mod tests {
655    use std::collections::BTreeMap;
656
657    use arc_swap::ArcSwap;
658
659    use super::{Generation, INITIAL_GENERATION_ID};
660    use crate::catalog::Catalog;
661    use crate::catalog::policy::{Config, Op, ResolvedPolicy};
662
663    /// A minimal, key-less catalog: enough to drive a `Pdp` decision (every key
664    /// is unknown → default-deny), without standing up a backend manager.
665    fn empty_catalog() -> Catalog {
666        Catalog {
667            schema_version: 1,
668            backends: BTreeMap::new(),
669            keys: BTreeMap::new(),
670        }
671    }
672
673    fn generation(id: u64) -> Generation {
674        Generation::new(
675            id,
676            empty_catalog(),
677            ResolvedPolicy::default(),
678            Config::default(),
679        )
680    }
681
682    #[test]
683    fn initial_generation_id_is_one() {
684        assert_eq!(INITIAL_GENERATION_ID, 1);
685        assert_eq!(generation(INITIAL_GENERATION_ID).id(), 1);
686    }
687
688    /// A single `load()` guard yields ONE coherent generation: the id, the PDP
689    /// it hands out, and its config all come from the same snapshot. This is the
690    /// per-request pinning seam: an op drives every decision off one guard.
691    #[test]
692    fn one_snapshot_is_internally_coherent() {
693        let swap = ArcSwap::from_pointee(generation(7));
694        let pinned = swap.load();
695
696        // The id, the PDP, and the config are all read from the SAME guard, so
697        // they cannot disagree even if a concurrent swap lands mid-op.
698        assert_eq!(pinned.id(), 7);
699        // The pinned catalog is the empty one, so any key is unknown → deny.
700        assert!(
701            pinned
702                .pdp()
703                .explain_subject("svc.missing", Op::Get, "any.key")
704                .decision
705                .is_deny()
706        );
707        // The pinned config is the default (no user names), same snapshot.
708        assert!(pinned.config().names.users.is_empty());
709    }
710
711    /// With no swap between two loads, both observe the same generation id: the
712    /// property a future reload (`basil-y3e.2`) will deliberately break by
713    /// bumping the id on swap. Today: byte-identical, monotonic, one generation.
714    #[test]
715    fn repeated_loads_without_swap_see_same_generation() {
716        let swap = ArcSwap::from_pointee(generation(INITIAL_GENERATION_ID));
717        let first = swap.load().id();
718        let second = swap.load().id();
719        assert_eq!(first, second);
720        assert_eq!(first, INITIAL_GENERATION_ID);
721    }
722
723    /// Sanity check that an `ArcSwap` swap is observable by a *later* load while a
724    /// guard taken *before* the swap still sees the old generation: the coherence
725    /// guarantee the per-request pin relies on. (No production swap path exists
726    /// yet; this exercises the primitive the reload engine will use.)
727    #[test]
728    fn pinned_guard_survives_a_later_swap() {
729        let swap = ArcSwap::from_pointee(generation(1));
730        let pinned = swap.load();
731        assert_eq!(pinned.id(), 1);
732
733        swap.store(std::sync::Arc::new(generation(2)));
734
735        // The guard taken before the swap still names the old generation.
736        assert_eq!(pinned.id(), 1);
737        // A fresh load sees the new one.
738        assert_eq!(swap.load().id(), 2);
739    }
740}