plexus-auth-core 0.1.0

Sealed-type primitives for the Plexus auth framework: AuthContext, VerifiedUser, Principal.
Documentation
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
//! `Tenanted<S>`, `Scoped<'a, S>`, and the sealed `TenantScopedStore` marker
//! trait — the structural foundation for tenant-scoped storage access.
//!
//! Per AUTHZ-0 principle 1 ("trust is structural, not procedural"), an
//! activation must not be able to hold a bare storage handle and call its
//! query API directly. The wrapper introduced here is the load-bearing
//! enforcement: an activation receives a [`Tenanted<S>`], the inner store
//! is unreachable, and the only way to call any storage method is through
//! a tenant-tagged [`Scoped<'a, S>`] borrow obtained by
//! [`Tenanted::scoped`].
//!
//! See `plans/AUTHZ/AUTHZ-DATA-1-WRAPPER.md` for the contract and
//! `plans/AUTHZ/AUTHZ-DATA-S01-output.md` §3 for the design rationale
//! (wrapper-plus-trait, option a with elements of b and c).
//!
//! # Sealing summary
//!
//! | Protection                       | Mechanism                                                |
//! |----------------------------------|----------------------------------------------------------|
//! | Inner store unreachable          | `Tenanted::inner` is module-private                      |
//! | No fabrication of `Tenanted`     | `Tenanted::new_sealed` is `pub(crate)`                   |
//! | Marker trait cannot be implemented externally | `TenantScopedStore: seal::SealedStore` (private super) |
//! | `TenantBoundary` proof unforgeable | `TenantBoundary::new_sealed` is `pub(crate)`           |
//! | No accidental `Default`          | Not derived on any sealed type                           |
//! | No leaky `Deserialize`           | Not derived on any sealed type                           |
//!
//! # The three structural compile-fails (per ticket §"Failing examples")
//!
//! ## 1. Reaching for the inner store directly
//!
//! ```compile_fail
//! use plexus_auth_core::tenant::storage::Tenanted;
//! fn leak<S>(t: &Tenanted<S>)
//! where
//!     S: plexus_auth_core::TenantScopedStore,
//! {
//!     let _ = &t.inner;
//! }
//! ```
//!
//! Diagnostic: `field 'inner' of struct 'Tenanted' is private` (E0616).
//!
//! ## 2. Constructing a `Tenant` from a literal inside an activation
//!
//! ```compile_fail
//! use plexus_auth_core::Tenant;
//! let _ = Tenant::try_new("victim-tenant");
//! ```
//!
//! Diagnostic: `associated function 'try_new' is private` (E0624).
//!
//! ## 3. Implementing `TenantScopedStore` for a sibling-crate type without
//!    the sealed super-trait
//!
//! ```compile_fail
//! struct MyStore;
//! impl plexus_auth_core::TenantScopedStore for MyStore {
//!     type Error = std::io::Error;
//! }
//! ```
//!
//! Diagnostic: `the trait bound 'MyStore: SealedStore' is not satisfied`
//! (E0277), pointing to the private `seal::SealedStore` super-trait.
//!
//! # Canonical happy path (passing doc test)
//!
//! The doc test below demonstrates the end-to-end pattern using the
//! framework-supplied [`reference::InMemoryKvStore`] (a pre-sealed
//! reference store kept in this crate so the canonical pattern is
//! exercise-able from a doc test). In a real activation, the type
//! satisfying [`TenantScopedStore`] is the activation's own storage
//! handle, the impl is generated by `AUTHZ-DATA-2-MACRO`, and domain
//! methods are added by a trait implemented on
//! [`Scoped<'_, MyStore>`] from inside the activation crate (Rust's
//! orphan rule forbids inherent impls on a foreign type — see the
//! run-notes for the design implication).
//!
//! ```
//! use plexus_auth_core::tenant::storage::{
//!     reference::InMemoryKvStore, Scoped, TenantScopedStore, Tenanted,
//! };
//! use plexus_auth_core::Tenant;
//!
//! // 1. The framework hands the activation a `Tenanted<S>`.
//! //    Here we mint one via the framework-blessed reference store.
//! let store = InMemoryKvStore::new();
//! store.put_for_doc_test("acme", "widget-1", b"sprocket".to_vec());
//! store.put_for_doc_test("acme", "widget-2", b"flange".to_vec());
//! store.put_for_doc_test("beta", "widget-1", b"do-not-leak".to_vec());
//! let tenanted: Tenanted<InMemoryKvStore> =
//!     plexus_auth_core::tenant::storage::__doctest_blessed_tenanted(store);
//!
//! // 2. The framework hands the activation a `&Tenant` extension.
//! let tenant: Tenant =
//!     plexus_auth_core::tenant::storage::__doctest_blessed_tenant("acme");
//!
//! // 3. The activation calls `.scoped(tenant)` and invokes domain
//! //    methods on the borrow. For the reference store, those methods
//! //    are pre-defined on `Scoped<'_, InMemoryKvStore>`.
//! let scoped: Scoped<'_, InMemoryKvStore> = tenanted.scoped(&tenant);
//! let names = scoped.list_keys();
//! assert_eq!(names.len(), 2);
//! assert!(names.contains(&"widget-1".to_string()));
//! assert!(names.contains(&"widget-2".to_string()));
//! ```

use crate::tenant::types::Tenant;

// ---------------------------------------------------------------------------
// Sealing module — private super-trait pattern.
//
// `SealedStore` lives in a `pub(crate)` module. The trait itself is `pub`
// inside the module so framework-internal types can implement it via the
// macro `seal_store_impl!`, but the path `seal::SealedStore` is
// `pub(crate)` overall — third-party crates cannot name it and therefore
// cannot satisfy the super-trait bound on `TenantScopedStore`.
//
// AUTHZ-DATA-1-WRAPPER ticket §"`TenantScopedStore` marker trait", row
// "Sealing", names this private re-export pattern.
// ---------------------------------------------------------------------------
pub(crate) mod seal {
    /// Private super-trait that seals [`super::TenantScopedStore`].
    ///
    /// Reachable only from inside `plexus-auth-core`. Third-party crates
    /// cannot name this path and therefore cannot satisfy the
    /// super-trait bound on `TenantScopedStore`.
    pub trait SealedStore {}
}

/// Crate-private macro that emits an empty `SealedStore` impl for a type.
///
/// Friend modules inside `plexus-auth-core` use this when introducing a
/// new `TenantScopedStore` candidate type. Outside crates cannot use it
/// because [`seal::SealedStore`] is unreachable.
///
/// Macros that are referenced via `$crate::tenant::storage::seal::...`
/// do not need an explicit `use seal_store_impl` import inside
/// sub-modules of this crate; rustc resolves the macro by name at the
/// invocation site within the same crate.
macro_rules! seal_store_impl {
    ($t:ty) => {
        impl $crate::tenant::storage::seal::SealedStore for $t {}
    };
}

// ---------------------------------------------------------------------------
// TenantBoundary — zero-sized witness that a tenant boundary was crossed.
// ---------------------------------------------------------------------------

/// Zero-sized witness that a tenant boundary was crossed structurally.
///
/// A `TenantBoundary` value exists if and only if it was minted by
/// `plexus-auth-core` — its constructor is `pub(crate)`. The framework
/// hands a `TenantBoundary` into every [`Tenanted<S>`] at construction;
/// the value rides along on every [`Scoped<'a, S>`] obtained from that
/// wrapper. Downstream audit / observability layers can accept a
/// `TenantBoundary` argument to attest "this code path is structurally
/// downstream of a tenant scoping" without re-deriving the fact.
///
/// # Sealing
///
/// - **No fabrication.** `new_sealed` is `pub(crate)`.
/// - **No backdoor.** No public constructor, no public field, no
///   `From`/`Into`, no `Default`.
/// - **Copy-able.** `Copy` is derived so a `Scoped::boundary()` accessor
///   can return a value without invalidating the parent borrow's
///   witness.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TenantBoundary {
    /// Module-private marker field. Prevents struct-literal fabrication
    /// from outside `plexus-auth-core` even if a future change widens
    /// the constructor visibility by accident.
    _seal: (),
}

impl TenantBoundary {
    /// Mint a `TenantBoundary`. Crate-private — only the framework's
    /// tenant-scoping path constructs one.
    pub(crate) const fn new_sealed() -> Self {
        Self { _seal: () }
    }
}

// ---------------------------------------------------------------------------
// TenantScopedStore — the public marker trait.
// ---------------------------------------------------------------------------

/// Sealed capability marker for types that can be wrapped in a
/// [`Tenanted<S>`].
///
/// Implementing this trait is a structural declaration: "this storage
/// handle's domain methods should be defined on [`Scoped<'_, Self>`], not
/// on `Self` directly." The framework wraps the handle in [`Tenanted<S>`]
/// at activation construction; the activation reaches the methods only
/// through [`Tenanted::scoped`].
///
/// # Bounds
///
/// - `Send + Sync + 'static`: the wrapper crosses async boundaries and
///   is shared across concurrent requests.
/// - `seal::SealedStore`: the private super-trait that seals this trait.
///   Third-party crates cannot name `seal::SealedStore` and therefore
///   cannot implement `TenantScopedStore`.
///
/// # Associated `Error`
///
/// The framework standardizes on a single error type per store so that
/// activation domain methods on [`Scoped<'a, S>`] can name a single
/// failure type. `Error: std::error::Error + Send + Sync + 'static`
/// keeps it compatible with `anyhow::Error`, `tracing` formatting, and
/// the dispatch layer's audit envelope.
///
/// # No required methods
///
/// This trait carries no methods; it is a capability marker. Activation
/// authors will, in `AUTHZ-DATA-2-MACRO` and per-activation tickets,
/// define a domain trait inside their own crate and implement that trait
/// on [`Scoped<'a, MyStore>`]. (Rust's orphan rule for inherent impls
/// forbids `impl Scoped<'_, MyStore>` from outside this crate; the
/// activation pattern uses a trait + impl, generated by the framework
/// macro.)
pub trait TenantScopedStore: seal::SealedStore + Send + Sync + 'static {
    /// The error type returned by domain methods defined on
    /// [`Scoped<'a, Self>`].
    type Error: std::error::Error + Send + Sync + 'static;
}

// ---------------------------------------------------------------------------
// Tenanted<S> — the wrapper.
// ---------------------------------------------------------------------------

/// A tenant-scoped wrapper around a storage handle.
///
/// `Tenanted<S>` is the only legal carrier for a storage handle inside an
/// activation. The inner store is module-private; the constructor is
/// crate-private; the only public access path is [`scoped`](Self::scoped),
/// which requires a `&Tenant`.
///
/// # Construction
///
/// Activation code never constructs a `Tenanted<S>` directly. The
/// framework's hub-builder layer (a follow-up ticket) accepts a bare `S`
/// and hands a `Tenanted<S>` to the activation at startup. Inside
/// `plexus-auth-core`, the crate-private `new_sealed` is the only
/// constructor.
///
/// # Sealing
///
/// - **No fabrication.** Constructor is `pub(crate)`.
/// - **No inner reach.** The `inner` field is module-private; activation
///   code that writes `self.store.inner.method()` fails to compile.
/// - **No `Default`.** Not derived; a default-constructed wrapper would
///   widen the access boundary silently.
/// - **No `Deserialize`.** Not derived; the wrapper is not transport.
pub struct Tenanted<S: TenantScopedStore> {
    /// The wrapped storage handle. Module-private — activation code in
    /// any other module cannot name this field, so
    /// `self.store.inner.foo()` is a compile error.
    inner: S,
    /// Structural witness that a tenant boundary exists at this site.
    boundary: TenantBoundary,
}

impl<S: TenantScopedStore> Tenanted<S> {
    /// Mint a `Tenanted<S>` from a bare storage handle.
    ///
    /// Crate-private — only `plexus-auth-core` (and the framework
    /// hub-builder layer that lives a few crates downstream) constructs
    /// this. Activation code receives a `Tenanted<S>` from the
    /// framework; it does not construct one.
    pub(crate) fn new_sealed(inner: S) -> Self {
        Self {
            inner,
            boundary: TenantBoundary::new_sealed(),
        }
    }

    /// Bind the wrapper to a tenant, returning a [`Scoped<'a, S>`]
    /// borrow.
    ///
    /// The returned borrow's lifetime is the shorter of the wrapper's
    /// borrow and the tenant's borrow. The activation's domain methods,
    /// defined on `Scoped<'_, S>` via a trait (because Rust's orphan
    /// rule forbids inherent impls on a foreign type), read both
    /// `self.store()` and `self.tenant()` to bind the active tenant
    /// into every query.
    pub fn scoped<'a>(&'a self, tenant: &'a Tenant) -> Scoped<'a, S> {
        Scoped {
            inner: &self.inner,
            tenant,
            boundary: self.boundary,
        }
    }
}

impl<S: TenantScopedStore + std::fmt::Debug> std::fmt::Debug for Tenanted<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Intentionally elide the inner store: the type is sealed, and
        // Debug output that exposed inner state would be a leak surface
        // for audit logs that pretty-print extension values.
        f.debug_struct("Tenanted")
            .field("inner", &"<sealed>")
            .finish()
    }
}

// ---------------------------------------------------------------------------
// Scoped<'a, S> — the tenant-tagged borrow.
// ---------------------------------------------------------------------------

/// A tenant-tagged borrow of a storage handle.
///
/// `Scoped<'a, S>` is produced by [`Tenanted::scoped`]. It bundles a
/// borrow of the inner store with a borrow of the active tenant. The
/// activation defines its domain methods via a trait implemented on
/// `Scoped<'a, MyStore>` (Rust's orphan rule forbids inherent impls on a
/// foreign type from another crate; the AUTHZ-DATA-2-MACRO layer
/// generates the trait + impl).
///
/// # Lifetime
///
/// The single `'a` lifetime is the shorter of the parent
/// [`Tenanted<S>`]'s borrow and the supplied `&Tenant`. Both must
/// outlive the `Scoped`. This is what makes "fabricated tenant" and
/// "mismatched tenants" structural failures: the lifetime threads
/// through every call site.
///
/// # Public surface
///
/// The framework supplies only [`store`](Self::store),
/// [`tenant`](Self::tenant), and [`boundary`](Self::boundary). The
/// activation's own domain methods live in a trait implementation on
/// `Scoped<'_, MyStore>` inside the activation's own crate.
///
/// # Sealing
///
/// - **No fabrication.** Constructor is module-private; the only path
///   is [`Tenanted::scoped`].
/// - **No struct-literal.** Fields are module-private.
/// - **No `Default`.** Not derived.
/// - **No `Deserialize`.** Not derived; the borrow is not transport.
pub struct Scoped<'a, S: TenantScopedStore> {
    /// Borrow of the inner store. Module-private — outside crates can
    /// only reach it through [`store`](Self::store), which the
    /// activation reads inside its own domain trait impl on `Scoped`.
    inner: &'a S,
    /// Borrow of the active tenant. Module-private; reached via
    /// [`tenant`](Self::tenant).
    tenant: &'a Tenant,
    /// Witness that this `Scoped` is structurally downstream of a
    /// [`TenantBoundary`].
    boundary: TenantBoundary,
}

impl<'a, S: TenantScopedStore> Scoped<'a, S> {
    /// Borrow the underlying storage handle.
    ///
    /// The activation's domain trait impls on `Scoped` call this to
    /// reach the store's bare API, paired with [`tenant`](Self::tenant)
    /// to bind the active tenant in queries. There is no path to the
    /// bare store that does not require having produced a `Scoped`,
    /// which itself requires a `&Tenant`.
    pub fn store(&self) -> &'a S {
        self.inner
    }

    /// Borrow the active tenant.
    ///
    /// Activation domain methods read this to bind the tenant in every
    /// SQL bind, key prefix, namespace, etc.
    pub fn tenant(&self) -> &'a Tenant {
        self.tenant
    }

    /// Return the structural [`TenantBoundary`] witness for this scope.
    ///
    /// Useful for downstream audit/attestation code that wants a
    /// type-level proof that a tenant boundary was crossed.
    pub fn boundary(&self) -> TenantBoundary {
        self.boundary
    }
}

impl<'a, S: TenantScopedStore> std::fmt::Debug for Scoped<'a, S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Same rationale as Tenanted's Debug: don't pretty-print the
        // inner store. The tenant is printable (already public via
        // `Tenant: Display`); it's safe to surface.
        f.debug_struct("Scoped")
            .field("tenant", &self.tenant.as_str())
            .field("store", &"<sealed>")
            .finish()
    }
}

// ---------------------------------------------------------------------------
// Reference store — `InMemoryKvStore` (the doc-test vehicle).
//
// A pre-sealed example `TenantScopedStore` is required because:
//
// 1. Rust's orphan rule (E0116) forbids `impl Scoped<'_, MyStore>` as an
//    inherent impl from any crate that does not own `Scoped`. Activation
//    code uses a trait + impl pattern (generated by AUTHZ-DATA-2-MACRO);
//    that pattern is also what doc tests must follow.
// 2. The seal on `TenantScopedStore` is strict: no crate outside
//    `plexus-auth-core` can satisfy `seal::SealedStore`. So the
//    canonical happy-path doc test cannot define its own example store
//    inline. The reference store lives inside this crate.
//
// `InMemoryKvStore` is a useful generic K/V example in its own right.
// Per the run-notes, it is the minimal type addition needed to give the
// ticket's acceptance criterion 6 a passing doc test.
// ---------------------------------------------------------------------------

pub mod reference {
    //! Reference [`TenantScopedStore`] implementations.
    //!
    //! These types are pre-sealed inside `plexus-auth-core` so that the
    //! canonical wrapper pattern can be demonstrated without requiring
    //! AUTHZ-DATA-2-* tickets to land first. They are also useful in
    //! their own right for in-memory tests and small dev installs.
    //!
    //! See `plans/AUTHZ/AUTHZ-DATA-1-WRAPPER-RUN-NOTES.md` for why a
    //! reference store is required to satisfy the doc-test acceptance
    //! criterion under Rust's orphan rule.
    use super::{Scoped, TenantScopedStore};
    use crate::tenant::types::Tenant;
    use std::collections::BTreeMap;
    use std::sync::Mutex;

    /// A small thread-safe in-memory key/value store, partitioned by
    /// [`Tenant`].
    ///
    /// The store is intentionally minimal: it serves the canonical
    /// doc-test demonstration of the wrapper pattern. Real backends
    /// (SQL, Redis, vector DBs, etc.) define their own
    /// [`TenantScopedStore`] type inside their own crate; the activation
    /// macro generates the trait + impl on `Scoped<'_, ThatStore>`.
    #[derive(Debug, Default)]
    pub struct InMemoryKvStore {
        /// Per-tenant map of key → value. `Mutex` because the store is
        /// shared across the dispatch (`Send + Sync` is required by
        /// `TenantScopedStore`).
        inner: Mutex<BTreeMap<String, BTreeMap<String, Vec<u8>>>>,
    }

    impl InMemoryKvStore {
        /// Construct an empty store.
        pub fn new() -> Self {
            Self::default()
        }

        /// Pre-populate the store for a doc test or unit test.
        ///
        /// Marked with the `_for_doc_test` suffix because it bypasses
        /// the tenant-scoping ceremony: it directly inserts under a
        /// caller-supplied tenant string. Real production code uses
        /// only the `put` method on [`Scoped<'_, Self>`](super::Scoped),
        /// which goes through `Scoped` and binds the active tenant.
        pub fn put_for_doc_test(&self, tenant: &str, key: &str, value: Vec<u8>) {
            let mut g = self.inner.lock().unwrap();
            g.entry(tenant.to_string())
                .or_default()
                .insert(key.to_string(), value);
        }
    }

    seal_store_impl!(InMemoryKvStore);
    impl TenantScopedStore for InMemoryKvStore {
        type Error = InMemoryKvError;
    }

    /// Error type for [`InMemoryKvStore`] operations.
    ///
    /// The reference store is in-memory and infallible in practice; the
    /// error type exists to satisfy the
    /// [`TenantScopedStore::Error`] associated type bound. The variant
    /// is intentionally empty so
    /// rustc's exhaustiveness checks remain useful.
    #[derive(Debug)]
    pub enum InMemoryKvError {
        /// Reserved for future variants. The reference store never
        /// produces an error today.
        #[doc(hidden)]
        __NonExhaustive,
    }

    impl std::fmt::Display for InMemoryKvError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match self {
                Self::__NonExhaustive => f.write_str("<unreachable>"),
            }
        }
    }

    impl std::error::Error for InMemoryKvError {}

    // Domain methods on `Scoped<'a, InMemoryKvStore>`. These live inside
    // `plexus-auth-core` because Rust's orphan rule for inherent impls
    // requires the impl to live in the crate that owns either `Scoped`
    // or the second generic parameter — and we own both. (Activation
    // crates can satisfy the orphan rule with a trait + impl pattern
    // since they own at least one of the trait or `MyStore`.)
    impl<'a> Scoped<'a, InMemoryKvStore> {
        /// Insert a value under the active tenant's namespace.
        pub fn put(&self, key: &str, value: Vec<u8>) {
            let mut g = self.store().inner.lock().unwrap();
            g.entry(self.tenant().as_str().to_string())
                .or_default()
                .insert(key.to_string(), value);
        }

        /// Look up a value under the active tenant's namespace.
        pub fn get(&self, key: &str) -> Option<Vec<u8>> {
            let g = self.store().inner.lock().unwrap();
            g.get(self.tenant().as_str())
                .and_then(|m| m.get(key).cloned())
        }

        /// List all keys in the active tenant's namespace.
        pub fn list_keys(&self) -> Vec<String> {
            let g = self.store().inner.lock().unwrap();
            g.get(self.tenant().as_str())
                .map(|m| m.keys().cloned().collect())
                .unwrap_or_default()
        }
    }

    // Make `Tenant` reachable inside the doc tests on this submodule.
    #[allow(dead_code)]
    fn _force_tenant_in_scope(_t: &Tenant) {}
}

// ---------------------------------------------------------------------------
// Doc-test helpers (hidden — not part of the public API).
//
// These are `pub` because doc tests compile as external crates; they
// must be reachable. They are `#[doc(hidden)]` because they are NOT the
// framework's normal construction path — they exist solely so the
// canonical happy-path doc test can compile and run.
//
// The structural seal is unchanged: `TenantScopedStore` is still
// implementable only from inside this crate, so these helpers can wrap
// only types that are themselves sealed inside `plexus-auth-core`. A
// third-party crate gains nothing from calling them.
// ---------------------------------------------------------------------------

/// Doc-test helper: wrap a pre-sealed store in a `Tenanted<S>`.
///
/// **Not part of the framework's public construction path.** The
/// hub-builder API in a follow-up ticket is the supported way for an
/// activation to receive a `Tenanted<S>`.
#[doc(hidden)]
pub fn __doctest_blessed_tenanted<S: TenantScopedStore>(inner: S) -> Tenanted<S> {
    Tenanted::new_sealed(inner)
}

/// Doc-test helper: mint a `Tenant` from a string literal.
///
/// **Not part of the framework's public construction path.** Real
/// callers obtain a `Tenant` only via [`crate::TenantResolver`].
#[doc(hidden)]
pub fn __doctest_blessed_tenant(s: &str) -> Tenant {
    Tenant::try_new(s).expect("doc-test tenant identifier should be valid")
}

// ---------------------------------------------------------------------------
// Unit tests.
// ---------------------------------------------------------------------------

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

    // A second in-crate `TenantScopedStore` implementor for unit tests,
    // distinct from the reference store, to confirm the seal works for
    // arbitrary friend types.
    #[derive(Debug)]
    struct TestStore {
        rows: Vec<(String, i64)>,
    }

    seal_store_impl!(TestStore);
    impl TenantScopedStore for TestStore {
        type Error = std::io::Error;
    }

    impl<'a> Scoped<'a, TestStore> {
        fn count_for_tenant(&self) -> i64 {
            let tid = self.tenant().as_str();
            self.store()
                .rows
                .iter()
                .filter(|(t, _)| t == tid)
                .map(|(_, n)| n)
                .sum()
        }
    }

    fn fixture_store() -> TestStore {
        TestStore {
            rows: vec![
                ("acme".into(), 3),
                ("acme".into(), 5),
                ("beta".into(), 11),
            ],
        }
    }

    #[test]
    fn tenanted_wraps_store_via_crate_private_constructor() {
        let _ = Tenanted::new_sealed(fixture_store());
    }

    #[test]
    fn scoped_borrow_threads_tenant_to_domain_method() {
        let store = fixture_store();
        let tenanted = Tenanted::new_sealed(store);
        let tenant = Tenant::try_new("acme").unwrap();

        let scoped = tenanted.scoped(&tenant);
        assert_eq!(scoped.count_for_tenant(), 8);
    }

    #[test]
    fn scoped_isolates_by_tenant() {
        let store = fixture_store();
        let tenanted = Tenanted::new_sealed(store);

        let acme = Tenant::try_new("acme").unwrap();
        let beta = Tenant::try_new("beta").unwrap();

        assert_eq!(tenanted.scoped(&acme).count_for_tenant(), 8);
        assert_eq!(tenanted.scoped(&beta).count_for_tenant(), 11);
    }

    #[test]
    fn scoped_returns_supplied_tenant() {
        let store = fixture_store();
        let tenanted = Tenanted::new_sealed(store);
        let tenant = Tenant::try_new("acme").unwrap();

        let scoped = tenanted.scoped(&tenant);
        assert_eq!(scoped.tenant().as_str(), "acme");
    }

    #[test]
    fn scoped_carries_tenant_boundary_witness() {
        let store = fixture_store();
        let tenanted = Tenanted::new_sealed(store);
        let tenant = Tenant::try_new("acme").unwrap();

        let scoped = tenanted.scoped(&tenant);
        let b1: TenantBoundary = scoped.boundary();
        let b2: TenantBoundary = scoped.boundary();
        assert_eq!(b1, b2);
    }

    #[test]
    fn tenant_boundary_is_copy_and_eq() {
        let a = TenantBoundary::new_sealed();
        let b = a; // Copy
        assert_eq!(a, b);
    }

    #[test]
    fn tenanted_debug_elides_inner_store() {
        let store = fixture_store();
        let tenanted = Tenanted::new_sealed(store);
        let rendered = format!("{tenanted:?}");
        assert!(rendered.contains("Tenanted"));
        assert!(rendered.contains("<sealed>"));
        // The inner row data must NOT appear.
        assert!(!rendered.contains("acme"));
        assert!(!rendered.contains("beta"));
    }

    #[test]
    fn scoped_debug_elides_inner_store_but_surfaces_tenant() {
        let store = fixture_store();
        let tenanted = Tenanted::new_sealed(store);
        let tenant = Tenant::try_new("acme").unwrap();
        let scoped = tenanted.scoped(&tenant);
        let rendered = format!("{scoped:?}");
        assert!(rendered.contains("Scoped"));
        assert!(rendered.contains("<sealed>"));
        // The tenant identifier is safe to surface (Tenant: Display).
        assert!(rendered.contains("acme"));
        // The inner row data must NOT appear.
        assert!(!rendered.contains("beta"));
    }

    #[test]
    fn scoped_lifetime_bounds_to_shorter_of_wrapper_and_tenant() {
        // Compile-only test: both references must outlive `'a`.
        // If either source goes out of scope, the borrow is invalid.
        let store = fixture_store();
        let tenanted = Tenanted::new_sealed(store);
        let tenant = Tenant::try_new("acme").unwrap();
        {
            let scoped: Scoped<'_, TestStore> = tenanted.scoped(&tenant);
            let _ = scoped.tenant();
        }
    }

    #[test]
    fn store_associated_error_is_named_per_impl() {
        // Compile-only assertion that the associated error type is
        // reachable via the trait.
        fn _accepts_err<S: TenantScopedStore>(_e: S::Error) {}
        let _io = std::io::Error::other("test");
        _accepts_err::<TestStore>(_io);
    }

    #[test]
    fn reference_store_round_trip_isolates_tenants() {
        let store = InMemoryKvStore::new();
        let tenanted = Tenanted::new_sealed(store);

        let acme = Tenant::try_new("acme").unwrap();
        let beta = Tenant::try_new("beta").unwrap();

        tenanted.scoped(&acme).put("k", b"acme-value".to_vec());
        tenanted.scoped(&beta).put("k", b"beta-value".to_vec());

        assert_eq!(
            tenanted.scoped(&acme).get("k"),
            Some(b"acme-value".to_vec())
        );
        assert_eq!(
            tenanted.scoped(&beta).get("k"),
            Some(b"beta-value".to_vec())
        );

        // The acme tenant cannot read beta's value: `get("k")` returns
        // only the value under its own namespace.
        assert_ne!(
            tenanted.scoped(&acme).get("k"),
            Some(b"beta-value".to_vec())
        );
    }

    #[test]
    fn reference_store_list_keys_is_tenant_partitioned() {
        let store = InMemoryKvStore::new();
        store.put_for_doc_test("acme", "k1", b"v1".to_vec());
        store.put_for_doc_test("acme", "k2", b"v2".to_vec());
        store.put_for_doc_test("beta", "k3", b"v3".to_vec());
        let tenanted = Tenanted::new_sealed(store);

        let acme = Tenant::try_new("acme").unwrap();
        let beta = Tenant::try_new("beta").unwrap();

        let mut acme_keys = tenanted.scoped(&acme).list_keys();
        acme_keys.sort();
        assert_eq!(acme_keys, vec!["k1".to_string(), "k2".to_string()]);

        assert_eq!(tenanted.scoped(&beta).list_keys(), vec!["k3".to_string()]);
    }
}