wyrd-runtime 0.3.0

Wyrd runtime singleton and cross-cutting behavior shells.
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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
//! Runtime principal identity model.

use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Serialize};
use uuid::Uuid;
use wyrd_spec::DataTenantId;
use wyrd_spec::auth::PrincipalKindTag;
use wyrd_spec::reference::{CardRef, CardRefScope};

use crate::permission::PermissionSet;

pub use wyrd_spec::auth::PrincipalId;

/// The authenticated identity behind a request.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Principal {
    /// Stable principal id.
    pub id: PrincipalId,
    /// Principal kind.
    pub kind: PrincipalKind,
    /// Tenant isolation key.
    pub tenant_id: DataTenantId,
    /// Role names carried by the verified token.
    pub roles: Vec<RoleRef>,
    /// The token's permission snapshot: resolved from the principal's roles
    /// once at issuance and carried unchanged until the token expires.
    pub effective_permissions: PermissionSet,
    /// Non-secret id of the credential the request authenticated with, when one
    /// was presented.
    ///
    /// Audit records it so a decision names which of a principal's several live
    /// credentials made it. `None` for a federated human session and for an
    /// identity the server minted for itself.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub credential_id: Option<Uuid>,
}

/// Kind of authenticated identity.
///
/// Every variant here is **tenant-scoped**: [`Principal`] carries a required
/// tenant, so this enum is the tenant-plane projection of a principal.
/// Platform-scope principals are a separate projection and are never
/// representable as a [`Principal`], which is what keeps the two control planes
/// from collapsing into one another by accident.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind", deny_unknown_fields)]
pub enum PrincipalKind {
    /// Tenant administrative identity created during tenant provisioning.
    ///
    /// The tenant's headless root of trust. It binds no Card — an
    /// administrative identity is not a registered AI-system component — and it
    /// coexists with any human administrator the tenant later federates.
    TenantAdmin,
    /// Human user identity.
    User,
    /// Machine service identity, optionally bound to a Service card.
    ///
    /// A deployed workload carries its Service card and the emit scope derived
    /// from it. Tenant automation created by a tenant administrator carries no
    /// Card and therefore no emit scope, because Card binding is a property of
    /// a machine principal rather than a precondition for holding a credential.
    Service {
        /// Bound Service card, absent for a Card-free automation identity.
        card_ref: Option<CardRef>,
        /// Transitive card authorization set; contains `card_ref` when one is
        /// bound and is empty otherwise.
        card_ref_scope: CardRefScope,
    },
    /// Card-bound agent identity.
    Agent {
        /// Bound Agent card.
        card_ref: CardRef,
        /// Transitive card authorization set; always contains `card_ref`.
        card_ref_scope: CardRefScope,
    },
    /// Internal credentialless verification-result writer.
    ///
    /// Exactly one exists per tenant. It binds no root Card, holds no roles or
    /// credential, and has no public lifecycle; the server mints it a
    /// short-lived token scoped to the single Verifier whose results it
    /// writes, so ingest authorizes and stamps each result row against that
    /// signed Verifier reference.
    System {
        /// Signed authorization set naming exactly one UID-bearing Verifier.
        card_ref_scope: CardRefScope,
    },
}

impl PrincipalKind {
    /// Projects to the card-free wire discriminator.
    #[must_use]
    pub fn tag(&self) -> PrincipalKindTag {
        match self {
            Self::TenantAdmin => PrincipalKindTag::TenantAdmin,
            Self::User => PrincipalKindTag::User,
            Self::Service { .. } => PrincipalKindTag::Service,
            Self::Agent { .. } => PrincipalKindTag::Agent,
            Self::System { .. } => PrincipalKindTag::System,
        }
    }
}

/// Reference to a role by name.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct RoleRef(String);

impl RoleRef {
    /// Build a validated role reference.
    ///
    /// # Errors
    /// Returns an error when the name does not match `^[a-z0-9_]{1,64}$`.
    pub fn new(value: &str) -> Result<Self, InvalidRoleName> {
        if value.is_empty()
            || value.len() > 64
            || !value
                .bytes()
                .all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'_'))
        {
            return Err(InvalidRoleName);
        }
        Ok(Self(value.to_owned()))
    }

    /// Borrow as a string.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for RoleRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl FromStr for RoleRef {
    type Err = InvalidRoleName;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

/// Invalid role name.
#[derive(Debug, thiserror::Error)]
#[error("role name must match ^[a-z0-9_]{{1,64}}$")]
pub struct InvalidRoleName;

impl Principal {
    /// Construct a principal.
    ///
    /// The authenticating credential is attached separately with
    /// [`Principal::with_credential_id`], because most callers — internal
    /// service identities, federated humans, test fixtures — have no credential
    /// to name and would otherwise all pass `None`.
    #[must_use]
    pub fn new(
        id: PrincipalId,
        kind: PrincipalKind,
        tenant_id: DataTenantId,
        roles: Vec<RoleRef>,
        effective_permissions: PermissionSet,
    ) -> Self {
        Self {
            id,
            kind,
            tenant_id,
            roles,
            effective_permissions,
            credential_id: None,
        }
    }

    /// Name the credential this principal authenticated with.
    #[must_use]
    pub fn with_credential_id(mut self, credential_id: Option<Uuid>) -> Self {
        self.credential_id = credential_id;
        self
    }

    /// Returns the bound card ref, when this principal has one.
    ///
    /// An agent always binds a Card. A service binds one only when it is a
    /// deployed workload; Card-free tenant automation, tenant administrators,
    /// humans, and the tenant SYSTEM principal return `None`.
    #[must_use]
    pub fn card_ref(&self) -> Option<&CardRef> {
        match &self.kind {
            PrincipalKind::Service { card_ref, .. } => card_ref.as_ref(),
            PrincipalKind::Agent { card_ref, .. } => Some(card_ref),
            PrincipalKind::TenantAdmin | PrincipalKind::User | PrincipalKind::System { .. } => None,
        }
    }

    /// The UID of the owner Service Card this principal is deployed as, when
    /// one is available without IO.
    ///
    /// Only a Card-bound Service principal whose bound Card is a resolved
    /// `Service` names an owner. An Agent's Card is never widened to a parent
    /// Service, and Card-free, human, administrator and SYSTEM principals have
    /// none, so their verifications record a null owner.
    #[must_use]
    pub fn owner_service_uid(&self) -> Option<&wyrd_spec::ids::CardUid> {
        match &self.kind {
            PrincipalKind::Service {
                card_ref: Some(card_ref),
                ..
            } if card_ref.kind == wyrd_spec::envelope::CardKind::Service => card_ref.uid.as_ref(),
            _ => None,
        }
    }

    /// Returns the card scope for card-carrying machine principals.
    ///
    /// A Card-free service still reports its (empty) scope, so callers can
    /// distinguish "no emit authority" from "not a machine principal". The
    /// tenant SYSTEM principal reports its in-process scope: exactly the
    /// Verifier a result frame is attributed to, or empty for an input read.
    #[must_use]
    pub fn card_ref_scope(&self) -> Option<&CardRefScope> {
        match &self.kind {
            PrincipalKind::Service { card_ref_scope, .. }
            | PrincipalKind::Agent { card_ref_scope, .. }
            | PrincipalKind::System { card_ref_scope } => Some(card_ref_scope),
            PrincipalKind::TenantAdmin | PrincipalKind::User => None,
        }
    }

    /// The Cards this principal may attribute observations and verifications to.
    ///
    /// A Card-bound Service or Agent and the tenant SYSTEM writer are limited
    /// to their signed scope. A principal bound to no Card — a tenant
    /// administrator, a human user, or Card-free tenant automation — may
    /// attribute evidence to any registered observation-target Card in its own
    /// tenant, which the write path resolves against the tenant registry.
    #[must_use]
    pub fn card_attribution(&self) -> CardAttribution<'_> {
        match &self.kind {
            PrincipalKind::Service {
                card_ref: Some(_),
                card_ref_scope,
            }
            | PrincipalKind::Agent { card_ref_scope, .. }
            | PrincipalKind::System { card_ref_scope } => CardAttribution::Scoped(card_ref_scope),
            PrincipalKind::Service { card_ref: None, .. }
            | PrincipalKind::TenantAdmin
            | PrincipalKind::User => CardAttribution::AnyRegistered,
        }
    }

    /// True when this principal is authorized to emit for `card`.
    #[must_use]
    pub fn authorizes_card(&self, card: &CardRef) -> bool {
        self.card_ref_scope()
            .is_some_and(|scope| scope.authorizes(card))
    }
}

/// Which Cards a principal may attribute observations and verifications to.
///
/// Returned by [`Principal::card_attribution`]. The distinction is explicit so
/// an unbound principal is never mistaken for one with an empty bounded scope.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CardAttribution<'a> {
    /// Only the members of this signed Card scope.
    Scoped(&'a CardRefScope),
    /// Any registered observation-target Card in the principal's tenant.
    AnyRegistered,
}

/// Self-describing projection of a principal for request delegation chains.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PrincipalRef {
    /// Stable principal id.
    pub id: PrincipalId,
    /// Principal kind.
    pub kind: PrincipalKind,
}

impl PrincipalRef {
    /// Project a full principal into a delegation-chain reference.
    #[must_use]
    pub fn from_principal(principal: &Principal) -> Self {
        Self {
            id: principal.id,
            kind: principal.kind.clone(),
        }
    }

    /// Returns the bound card ref, when this principal has one.
    ///
    /// Mirrors [`Principal::card_ref`] for the delegation-chain projection.
    #[must_use]
    pub fn card_ref(&self) -> Option<&CardRef> {
        match &self.kind {
            PrincipalKind::Service { card_ref, .. } => card_ref.as_ref(),
            PrincipalKind::Agent { card_ref, .. } => Some(card_ref),
            PrincipalKind::TenantAdmin | PrincipalKind::User | PrincipalKind::System { .. } => None,
        }
    }

    /// Returns the card scope for card-carrying machine principals.
    ///
    /// Mirrors [`Principal::card_ref_scope`] for the delegation-chain
    /// projection.
    #[must_use]
    pub fn card_ref_scope(&self) -> Option<&CardRefScope> {
        match &self.kind {
            PrincipalKind::Service { card_ref_scope, .. }
            | PrincipalKind::Agent { card_ref_scope, .. }
            | PrincipalKind::System { card_ref_scope } => Some(card_ref_scope),
            PrincipalKind::TenantAdmin | PrincipalKind::User => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{CardAttribution, Principal, PrincipalId, PrincipalKind, PrincipalRef, RoleRef};
    use crate::permission::{Permission, PermissionSet};
    use wyrd_semver::VersionBlock;
    use wyrd_spec::envelope::CardKind;
    use wyrd_spec::ids::{CardName, SpaceName};
    use wyrd_spec::reference::{CardRef, CardRefScope};

    fn service_card_ref() -> CardRef {
        CardRef {
            kind: CardKind::Service,
            name: CardName::new("billing").expect("static card name is valid"),
            version: VersionBlock::parse("1.0.0").expect("static version is valid"),
            space: Some(SpaceName::new("prod").expect("static space is valid")),
            uid: None,
        }
    }

    #[test]
    fn role_ref_accepts_locked_name_shape() {
        let role = RoleRef::new("credential_admin").expect("role name is valid");

        assert_eq!(role.as_str(), "credential_admin");
    }

    #[test]
    fn role_ref_rejects_punctuation_and_uppercase() {
        assert!(RoleRef::new("RuntimeAdmin").is_err());
        assert!(RoleRef::new("runtime-admin").is_err());
    }

    #[test]
    fn principal_id_roundtrips_as_uuid() {
        let uuid = uuid::Uuid::now_v7();
        let id = PrincipalId::new(uuid);

        assert_eq!(id.to_string(), uuid.to_string());
        assert_eq!(id.as_uuid(), uuid);
    }

    #[test]
    fn service_kind_carries_card_ref() {
        let card_ref = service_card_ref();
        let principal = Principal {
            id: PrincipalId::new(uuid::Uuid::now_v7()),
            kind: PrincipalKind::Service {
                card_ref: Some(card_ref.clone()),
                card_ref_scope: CardRefScope::own(&card_ref),
            },
            tenant_id: wyrd_spec::DataTenantId::new_v7(),
            roles: vec![RoleRef::new("agent").expect("static role is valid")],
            effective_permissions: PermissionSet::from_iter([Permission::card_read()]),
            credential_id: None,
        };

        assert_eq!(principal.card_ref(), Some(&card_ref));
    }

    /// Only a Card-bound Service principal with a resolved Service UID names
    /// an owner; an unresolved Service ref and an Agent record none.
    ///
    /// # Panics
    /// Panics when an owner is reported for the wrong principal kind.
    #[test]
    fn owner_service_uid_copies_only_a_resolved_service_card() {
        let principal = |kind| Principal {
            id: PrincipalId::new(uuid::Uuid::now_v7()),
            kind,
            tenant_id: wyrd_spec::DataTenantId::new_v7(),
            roles: Vec::new(),
            effective_permissions: PermissionSet::new(),
            credential_id: None,
        };
        let uid = wyrd_spec::ids::CardUid::from_uuid(uuid::Uuid::now_v7()).expect("v7 Card UID");
        let resolved = CardRef {
            uid: Some(uid.clone()),
            ..service_card_ref()
        };
        let service = |card_ref: CardRef| PrincipalKind::Service {
            card_ref_scope: CardRefScope::own(&card_ref),
            card_ref: Some(card_ref),
        };
        assert_eq!(
            principal(service(resolved.clone())).owner_service_uid(),
            Some(&uid)
        );
        assert_eq!(
            principal(service(service_card_ref())).owner_service_uid(),
            None
        );
        let agent = CardRef {
            kind: CardKind::Agent,
            ..resolved
        };
        assert_eq!(
            principal(PrincipalKind::Agent {
                card_ref_scope: CardRefScope::own(&agent),
                card_ref: agent,
            })
            .owner_service_uid(),
            None
        );
    }

    #[test]
    fn principal_ref_keeps_card_ref_projection() {
        let card_ref = service_card_ref();
        let principal = Principal {
            id: PrincipalId::new(uuid::Uuid::now_v7()),
            kind: PrincipalKind::Service {
                card_ref: Some(card_ref.clone()),
                card_ref_scope: CardRefScope::own(&card_ref),
            },
            tenant_id: wyrd_spec::DataTenantId::new_v7(),
            roles: vec![RoleRef::new("agent").expect("static role is valid")],
            effective_permissions: PermissionSet::new(),
            credential_id: None,
        };

        let principal_ref = PrincipalRef::from_principal(&principal);

        assert_eq!(principal_ref.id, principal.id);
        assert_eq!(principal_ref.card_ref(), Some(&card_ref));
        assert_eq!(
            principal_ref.card_ref_scope(),
            Some(&CardRefScope::own(&card_ref))
        );
        assert_eq!(principal_ref.kind, principal.kind);
    }

    #[test]
    fn principal_authorizes_cards_from_scope() {
        let own = service_card_ref();
        let mut composed = service_card_ref();
        composed.name = CardName::new("composed").expect("static card name is valid");
        let principal = Principal {
            id: PrincipalId::new(uuid::Uuid::now_v7()),
            kind: PrincipalKind::Service {
                card_ref: Some(own.clone()),
                card_ref_scope: CardRefScope::from_root_and_members(&own, [composed.clone()]),
            },
            tenant_id: wyrd_spec::DataTenantId::new_v7(),
            roles: Vec::new(),
            effective_permissions: PermissionSet::new(),
            credential_id: None,
        };

        assert!(principal.authorizes_card(&own));
        assert!(principal.authorizes_card(&composed));

        let mut unrelated = service_card_ref();
        unrelated.name = CardName::new("unrelated").expect("static card name is valid");
        assert!(!principal.authorizes_card(&unrelated));
    }

    /// A Card-bound principal attributes only within its signed scope, while a
    /// tenant administrator, a user, and Card-free automation may attribute to
    /// any registered Card rather than to an empty bounded scope.
    ///
    /// # Panics
    /// Panics when a principal kind projects the wrong attribution.
    #[test]
    fn only_unbound_principals_attribute_to_any_registered_card() {
        let own = service_card_ref();
        let scope = CardRefScope::own(&own);
        let principal = |kind| {
            Principal::new(
                PrincipalId::new(uuid::Uuid::now_v7()),
                kind,
                wyrd_spec::DataTenantId::new_v7(),
                Vec::new(),
                PermissionSet::new(),
            )
        };

        let bound = principal(PrincipalKind::Service {
            card_ref: Some(own),
            card_ref_scope: scope.clone(),
        });
        assert_eq!(bound.card_attribution(), CardAttribution::Scoped(&scope));
        for unbound in [
            PrincipalKind::TenantAdmin,
            PrincipalKind::User,
            PrincipalKind::Service {
                card_ref: None,
                card_ref_scope: CardRefScope::default(),
            },
        ] {
            assert_eq!(
                principal(unbound).card_attribution(),
                CardAttribution::AnyRegistered
            );
        }
    }

    /// Build the UID-bearing Verifier reference a SYSTEM result frame is
    /// scoped to.
    ///
    /// # Panics
    /// Panics when a static identity component is invalid.
    fn verifier_card_ref() -> CardRef {
        CardRef {
            kind: CardKind::Verifier,
            name: CardName::new("drift").expect("static card name is valid"),
            version: VersionBlock::parse("1.0.0").expect("static version is valid"),
            space: Some(SpaceName::new("prod").expect("static space is valid")),
            uid: Some(
                wyrd_spec::ids::CardUid::from_uuid(uuid::Uuid::now_v7())
                    .expect("UUIDv7 is a valid card UID"),
            ),
        }
    }

    /// The tenant SYSTEM principal binds no root Card, yet exposes the one
    /// Verifier scope of a result frame so Scribe can stamp result rows.
    ///
    /// # Panics
    /// Panics when the kind projects a root Card, loses its scope, authorizes
    /// a Card outside that scope, or does not round-trip as `system`.
    #[test]
    fn system_kind_exposes_its_verifier_scope_without_a_root_card() {
        let verifier = verifier_card_ref();
        let principal = Principal::new(
            PrincipalId::new(uuid::Uuid::now_v7()),
            PrincipalKind::System {
                card_ref_scope: CardRefScope::own(&verifier),
            },
            wyrd_spec::DataTenantId::new_v7(),
            Vec::new(),
            PermissionSet::from_iter([Permission::bifrost_record_write()]),
        );

        assert_eq!(
            principal.kind.tag(),
            wyrd_spec::auth::PrincipalKindTag::System
        );
        assert_eq!(principal.card_ref(), None);
        assert_eq!(
            principal.card_ref_scope(),
            Some(&CardRefScope::own(&verifier))
        );
        assert!(principal.authorizes_card(&verifier));
        assert!(!principal.authorizes_card(&service_card_ref()));

        let principal_ref = PrincipalRef::from_principal(&principal);
        assert_eq!(principal_ref.card_ref(), None);
        assert_eq!(principal_ref.card_ref_scope(), principal.card_ref_scope());

        let wire = serde_json::to_value(&principal.kind).expect("kind serializes");
        assert_eq!(wire["kind"], "system");
        assert_eq!(
            serde_json::from_value::<PrincipalKind>(wire).expect("kind deserializes"),
            principal.kind
        );
    }

    #[test]
    fn user_principal_authorizes_no_cards() {
        let principal = Principal {
            id: PrincipalId::new(uuid::Uuid::now_v7()),
            kind: PrincipalKind::User,
            tenant_id: wyrd_spec::DataTenantId::new_v7(),
            roles: Vec::new(),
            effective_permissions: PermissionSet::new(),
            credential_id: None,
        };

        assert!(!principal.authorizes_card(&service_card_ref()));
    }
}

/// Platform-scope authenticated identity.
///
/// Deliberately carries **no tenant**. A platform principal operates the
/// tenant directory — creating, inspecting, suspending, and recovering
/// administration for tenants — and is never implicitly authorized over the
/// resources inside one. Because the type has no tenant to offer, a handler
/// holding one cannot open a tenant-scoped connection at all; the control-plane
/// boundary is enforced by what is representable rather than by a check a
/// caller could forget.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlatformPrincipal {
    /// Stable principal id.
    pub id: PrincipalId,
    /// The kind the platform directory stores for this principal.
    ///
    /// `GlobalAdmin` for a machine root, `User` for a human registered for
    /// federated sign-in. Audit reads it, so a human's decision is never
    /// recorded as a machine's. It is read from the store at session
    /// verification, never inferred from what the principal may do.
    pub kind: PrincipalKindTag,
    /// Permissions resolved from the principal's platform grant.
    ///
    /// Absence of a grant is denial: a platform principal with an empty set
    /// authenticates but authorizes nothing.
    pub effective_permissions: PermissionSet,
    /// Non-secret id of the credential the session was minted from, when one
    /// was presented. `None` for a federated login.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub credential_id: Option<Uuid>,
}

impl PlatformPrincipal {
    /// Construct a platform-scope principal.
    #[must_use]
    pub const fn new(
        id: PrincipalId,
        kind: PrincipalKindTag,
        effective_permissions: PermissionSet,
    ) -> Self {
        Self {
            id,
            kind,
            effective_permissions,
            credential_id: None,
        }
    }

    /// Name the credential this session was minted from.
    #[must_use]
    pub const fn with_credential_id(mut self, credential_id: Option<Uuid>) -> Self {
        self.credential_id = credential_id;
        self
    }
}

/// The authenticated identity behind a request, in exactly one control plane.
///
/// One authentication pipeline produces this, whichever entry path the caller
/// used — a machine credential exchanged for a token, or a human federated
/// login. Everything downstream authorizes against it and never branches on how
/// authentication happened.
///
/// The two variants are closed and carry different payloads, so a platform
/// identity is not representable where a tenant identity is required and the
/// reverse. That mirrors the database tier's `OperatorPool` / `TenantConn`
/// split at the identity tier.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "scope")]
pub enum AuthContext {
    /// Platform control plane: tenant lifecycle and administrative recovery.
    Platform(PlatformPrincipal),
    /// Tenant control plane: the resources of exactly one tenant.
    Tenant(Box<Principal>),
}

impl AuthContext {
    /// Borrow the platform principal, when this context is platform-scoped.
    #[must_use]
    pub fn platform(&self) -> Option<&PlatformPrincipal> {
        match self {
            Self::Platform(principal) => Some(principal),
            Self::Tenant(_) => None,
        }
    }

    /// Borrow the tenant principal, when this context is tenant-scoped.
    #[must_use]
    pub fn tenant(&self) -> Option<&Principal> {
        match self {
            Self::Tenant(principal) => Some(principal),
            Self::Platform(_) => None,
        }
    }

    /// The authenticated principal id, whichever plane this context names.
    ///
    /// Audit uses this so every privileged operation is attributable to a
    /// principal rather than to a credential.
    #[must_use]
    pub fn principal_id(&self) -> PrincipalId {
        match self {
            Self::Platform(principal) => principal.id,
            Self::Tenant(principal) => principal.id,
        }
    }

    /// The kind of principal behind the request, whichever plane it names.
    ///
    /// Audit records this, so it has to be what the store holds rather than a
    /// per-plane constant: a platform plane carrying both machine roots and
    /// registered humans would otherwise attribute every human decision to a
    /// machine.
    #[must_use]
    pub fn principal_kind(&self) -> PrincipalKindTag {
        match self {
            Self::Platform(principal) => principal.kind,
            Self::Tenant(principal) => principal.kind.tag(),
        }
    }

    /// The credential the request authenticated with, on either plane.
    ///
    /// Audit records it beside the principal, because a principal may hold
    /// several live credentials at once and the recorded decision has to say
    /// which one was used.
    #[must_use]
    pub const fn credential_id(&self) -> Option<Uuid> {
        match self {
            Self::Platform(principal) => principal.credential_id,
            Self::Tenant(principal) => principal.credential_id,
        }
    }

    /// The permissions authorization is decided against.
    ///
    /// One vocabulary and one checker serve both planes; only the set differs.
    #[must_use]
    pub fn effective_permissions(&self) -> &PermissionSet {
        match self {
            Self::Platform(principal) => &principal.effective_permissions,
            Self::Tenant(principal) => &principal.effective_permissions,
        }
    }

    /// The tenant this context is scoped to, when it is tenant-scoped.
    ///
    /// Returns `None` for a platform context because a platform principal has
    /// no tenant to return — not because one was withheld.
    #[must_use]
    pub fn tenant_id(&self) -> Option<DataTenantId> {
        match self {
            Self::Tenant(principal) => Some(principal.tenant_id),
            Self::Platform(_) => None,
        }
    }
}

impl From<Principal> for AuthContext {
    /// Lift a verified tenant principal into the shared context.
    ///
    /// Boxed because a tenant principal carries its roles and resolved
    /// permissions, and the platform variant carries far less; keeping the
    /// enum small matters where it is passed by value on every request.
    fn from(principal: Principal) -> Self {
        Self::Tenant(Box::new(principal))
    }
}

impl From<PlatformPrincipal> for AuthContext {
    /// Lift a verified platform principal into the shared context.
    ///
    /// The platform arm is the one that carries no tenant, which is what
    /// downstream tenancy checks read the context for.
    fn from(principal: PlatformPrincipal) -> Self {
        Self::Platform(principal)
    }
}

/// The plane an [`AuthContext`] reports, and the tenancy that follows from it.
#[cfg(test)]
mod auth_context_tests {
    use wyrd_spec::DataTenantId;

    use wyrd_spec::auth::PrincipalKindTag;

    use super::{AuthContext, PlatformPrincipal, Principal, PrincipalId, PrincipalKind};
    use crate::permission::{Permission, PermissionSet};

    /// A platform principal holding tenant-lifecycle authority.
    fn platform() -> PlatformPrincipal {
        PlatformPrincipal::new(
            PrincipalId::new(uuid::Uuid::now_v7()),
            PrincipalKindTag::GlobalAdmin,
            {
                let mut set = PermissionSet::new();
                set.insert(Permission::tenant_create());
                set
            },
        )
    }

    /// A tenant administrative principal in some tenant.
    fn tenant() -> Principal {
        Principal::new(
            PrincipalId::new(uuid::Uuid::now_v7()),
            PrincipalKind::TenantAdmin,
            DataTenantId::new_v7(),
            Vec::new(),
            {
                let mut set = PermissionSet::new();
                set.insert(Permission::card_read());
                set
            },
        )
    }

    /// A platform context has no tenant to offer, so no handler holding one can
    /// reach tenant-scoped data even by mistake.
    #[test]
    fn platform_context_carries_no_tenant() {
        let context = AuthContext::from(platform());

        assert_eq!(context.tenant_id(), None);
        assert!(context.tenant().is_none());
        assert!(context.platform().is_some());
    }

    /// A tenant context names exactly one tenant and never satisfies a
    /// platform-scoped accessor.
    #[test]
    fn tenant_context_carries_exactly_its_tenant() {
        let principal = tenant();
        let expected = principal.tenant_id;
        let context = AuthContext::from(principal);

        assert_eq!(context.tenant_id(), Some(expected));
        assert!(context.platform().is_none());
        assert!(context.tenant().is_some());
    }

    /// Authorization reads one permission set whichever plane produced the
    /// context, so the checker needs no plane-specific branch.
    #[test]
    fn permissions_resolve_from_whichever_plane_authenticated() {
        let platform_context = AuthContext::from(platform());
        let tenant_context = AuthContext::from(tenant());

        assert!(
            platform_context
                .effective_permissions()
                .contains(&Permission::tenant_create())
        );
        assert!(
            !tenant_context
                .effective_permissions()
                .contains(&Permission::tenant_create()),
            "a tenant principal never holds platform authority"
        );
        assert!(
            tenant_context
                .effective_permissions()
                .contains(&Permission::card_read())
        );
    }

    /// Every privileged operation is attributable to a principal, on either
    /// plane.
    #[test]
    fn principal_id_is_available_on_both_planes() {
        let principal = platform();
        let expected = principal.id;
        assert_eq!(AuthContext::from(principal).principal_id(), expected);

        let principal = tenant();
        let expected = principal.id;
        assert_eq!(AuthContext::from(principal).principal_id(), expected);
    }
}