axond 0.3.25

Axond — a stateless, single-binary, self-hosted AI gateway: one place for provider keys, model routing, usage, and telemetry.
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
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
//! The provider-credential body: a durable pointer to secret material (#198).
//!
//! A provider credential is the resource an operator authors when a tenant brings
//! its own provider key (ADR 0003). What makes it unusual among resources is what
//! it must *not* contain: the key. So its body carries a
//! [`SecretRef`] — an opaque, exactly-versioned handle
//! — the [`SecretOwner`] that handle belongs to, and the
//! [`SecretLifecycle`] state of that material. The bytes are behind
//! [`SecretStore`](crate::backends::secrets::SecretStore), which nothing in this
//! module calls.
//!
//! # What a body carries
//!
//! | Field | Meaning |
//! | --- | --- |
//! | `schema` | `axond.provider-credential.v1` |
//! | `credential_id` | its own [`ResourceId`], bound to the envelope's |
//! | `tenant_id` | the owning [`TenantId`] |
//! | `project_id` | the owning project, when the credential is a project's |
//! | `provider_id` | the provider resource this credential authenticates to |
//! | `display_name` | operator-facing prose |
//! | `secret_id` | the opaque secret this credential points at |
//! | `secret_version` | *which* version of that secret, exactly |
//! | `lifecycle` | `staged`, `active`, `disabled`, `revoked`, or `tombstoned` |
//!
//! The material is absent, and so is anything derived from it: no fingerprint, no
//! prefix, no length. A body is canonically encoded into a checksum an operator
//! can read in a manifest, and a "harmless" four-character prefix in there would
//! be a disclosure that no later change could take back.
//!
//! # Rotation is a new version, not an edit
//!
//! Material is immutable per version: rotation stages a *new* secret version
//! ([`ProviderCredentialBody::rotated`]) and publishing that body is a new
//! resource version of the credential. A revision therefore pins the exact
//! material it was compiled against, and a rotation cannot retroactively change
//! what an already-published revision meant. Putting the new material in service
//! is a separate, deliberate lifecycle move
//! ([`ProviderCredentialBody::transitioned`]).
//!
//! # What is checked, and where
//!
//! [`Credentials::of`] reads every credential body in a [`DesiredState`] and
//! [`DesiredState::validate`] calls it, so publication and hydration inherit the
//! rules with no request path involved:
//!
//! - **ownership** — a body's owner is its envelope's scope, not a second opinion
//!   about it ([`CredentialError::OwnerMismatch`]);
//! - **cross-tenant and cross-project references** — one secret belongs to one
//!   owner ([`CredentialError::SecretOwnerConflict`]), and a credential
//!   authenticates to a provider its own owner can reach
//!   ([`CredentialError::ForeignProvider`]);
//! - **an unambiguous serving version** — two credentials cannot declare two
//!   different active versions of one secret
//!   ([`CredentialError::AmbiguousActiveSecret`]), and two references to one
//!   version cannot disagree about its state
//!   ([`CredentialError::LifecycleConflict`]).
//!
//! Stateless mode is untouched by all of this: `[[credential]]` material still
//! comes from TOML, `env:`, or `file:` through [`crate::credentials`], which has
//! no [`SecretRef`] in it and no dependency on this module.

use std::collections::BTreeMap;

use super::canonical::{Canonical, CanonicalValue};
use super::ids::{InvalidId, ProjectId, ResourceId, SecretId, Slug, TenantId};
use super::record::{
    BodyError, DISPLAY_NAME_FIELD, PROJECT_ID_FIELD, Record, SCHEMA_FIELD, TENANT_ID_FIELD,
};
use super::resource::{
    ResourceBody, ResourceKind, ResourceRef, ResourceScope, ResourceVersion, ResourceVersionNumber,
};
use super::revision::DesiredState;
use super::secrets::{
    ForbiddenTransition, LifecycleTransition, SecretLifecycle, SecretOwner, SecretRef,
    SecretVersion,
};
use super::tenancy::{DisplayName, InvalidDisplayName};

/// The provider-credential body schema this build reads and writes.
pub const PROVIDER_CREDENTIAL_SCHEMA: &str = "axond.provider-credential.v1";

const CREDENTIAL_ID_FIELD: &str = "credential_id";
const PROVIDER_ID_FIELD: &str = "provider_id";
const SECRET_ID_FIELD: &str = "secret_id";
const SECRET_VERSION_FIELD: &str = "secret_version";
const LIFECYCLE_FIELD: &str = "lifecycle";

/// Why a provider-credential body, or the set of them in a revision, was refused.
///
/// No arm carries material, because no arm has any: a credential error names
/// references, owners, and states, so every one of these is safe to log verbatim.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum CredentialError {
    #[error("{reference} is a {} resource, not a {}", found.as_str(), expected.as_str())]
    Kind {
        reference: ResourceRef,
        expected: ResourceKind,
        found: ResourceKind,
    },
    #[error("{reference} is a blob body; a provider-credential record is inline")]
    NotInline { reference: ResourceRef },
    #[error("{reference} is not a record")]
    NotARecord { reference: ResourceRef },
    #[error(
        "{reference} declares schema `{found}`, which this build does not read (expected `{expected}`)"
    )]
    Schema {
        reference: ResourceRef,
        expected: &'static str,
        found: String,
    },
    #[error("{reference} has no `{field}`")]
    MissingField {
        reference: ResourceRef,
        field: &'static str,
    },
    #[error("{reference} carries `{field}`, which `{schema}` does not define")]
    UnknownField {
        reference: ResourceRef,
        schema: &'static str,
        field: String,
    },
    #[error(
        "{reference} field `{field}` is not the type `{}` defines",
        PROVIDER_CREDENTIAL_SCHEMA
    )]
    FieldType {
        reference: ResourceRef,
        field: &'static str,
    },
    #[error("{reference} field `{field}` is not an id: {source}")]
    MalformedId {
        reference: ResourceRef,
        field: &'static str,
        #[source]
        source: InvalidId,
    },
    #[error("{reference} field `{field}` is not a display name: {source}")]
    MalformedDisplayName {
        reference: ResourceRef,
        field: &'static str,
        #[source]
        source: InvalidDisplayName,
    },
    #[error("{reference} carries {declared}, but its resource identity is {identity}")]
    IdentityMismatch {
        reference: ResourceRef,
        declared: String,
        identity: ResourceId,
    },
    #[error("{reference} declares owner {declared}, which is not the scope it is filed under")]
    OwnerMismatch {
        reference: ResourceRef,
        declared: SecretOwner,
    },
    /// Version `0`, which no release ever wrote: material is versioned from one.
    #[error("{reference} names secret version {found}; versions start at 1")]
    SecretVersion { reference: ResourceRef, found: u64 },
    /// A lifecycle identifier this build does not know — a state a newer release
    /// defined, so a compatibility refusal rather than damage.
    #[error("{reference} declares lifecycle `{found}`, which this build does not know")]
    UnknownLifecycle {
        reference: ResourceRef,
        found: String,
    },
    /// One secret, two owners. The reference is opaque, so nothing about the
    /// material itself would reveal that a tenant had been handed another
    /// tenant's key — this is the rule that refuses it.
    #[error("{reference} claims secret {secret}, which {conflicting} claims for a different owner")]
    SecretOwnerConflict {
        reference: ResourceRef,
        secret: SecretId,
        conflicting: ResourceRef,
    },
    /// A credential naming a provider resource its owner cannot reach: another
    /// tenant's provider, or another project's.
    #[error("{reference} authenticates to {provider}, which {owner} cannot reach")]
    ForeignProvider {
        reference: ResourceRef,
        provider: ResourceRef,
        owner: SecretOwner,
    },
    /// A `provider_id` that names something in this revision which is not a
    /// provider.
    #[error("{reference} names provider {provider}, which this revision declares as a {}", found.as_str())]
    NotAProvider {
        reference: ResourceRef,
        provider: ResourceId,
        found: ResourceKind,
    },
    /// Two credentials, one secret version, two states: the material would be
    /// both in service and not, depending on which row was read.
    #[error(
        "{reference} declares {secret} `{state}`, but {conflicting} declares it `{conflicting_state}`"
    )]
    LifecycleConflict {
        reference: ResourceRef,
        secret: SecretRef,
        state: SecretLifecycle,
        conflicting: ResourceRef,
        conflicting_state: SecretLifecycle,
    },
    /// Two versions of one secret, both active: which material a request would
    /// be authorized by would depend on iteration order.
    #[error(
        "{reference} activates {secret}, but {conflicting} already activates another version of it"
    )]
    AmbiguousActiveSecret {
        reference: ResourceRef,
        secret: SecretRef,
        conflicting: ResourceRef,
    },
}

impl CredentialError {
    /// Whether this refusal means *this build cannot read the body*, rather than
    /// *these rows do not agree with each other*.
    ///
    /// The same division [`TenancyError::is_incompatible`] draws, and for the same
    /// reason: a compatibility refusal tells an operator that storage is intact
    /// and the fix is a build or a revision, while everything else is real repair
    /// work. A body declaring a schema, a field, or a *lifecycle state* this
    /// release does not know is the newer-build case; a contradiction between two
    /// readable rows is not.
    ///
    /// [`TenancyError::is_incompatible`]: super::tenancy::TenancyError::is_incompatible
    pub fn is_incompatible(&self) -> bool {
        match self {
            Self::Schema { .. }
            | Self::UnknownField { .. }
            | Self::UnknownLifecycle { .. }
            | Self::MalformedDisplayName { .. } => true,
            // Only the schema identifier itself: its absence is a body written
            // before provider credentials had one at all.
            Self::MissingField { field, .. } | Self::FieldType { field, .. } => {
                *field == SCHEMA_FIELD
            }
            Self::Kind { .. }
            | Self::NotInline { .. }
            | Self::NotARecord { .. }
            | Self::MalformedId { .. }
            | Self::IdentityMismatch { .. }
            | Self::OwnerMismatch { .. }
            | Self::SecretVersion { .. }
            | Self::SecretOwnerConflict { .. }
            | Self::ForeignProvider { .. }
            | Self::NotAProvider { .. }
            | Self::LifecycleConflict { .. }
            | Self::AmbiguousActiveSecret { .. } => false,
        }
    }

    /// The resource this refusal is about.
    pub const fn reference(&self) -> ResourceRef {
        match self {
            Self::Kind { reference, .. }
            | Self::NotInline { reference }
            | Self::NotARecord { reference }
            | Self::Schema { reference, .. }
            | Self::MissingField { reference, .. }
            | Self::UnknownField { reference, .. }
            | Self::FieldType { reference, .. }
            | Self::MalformedId { reference, .. }
            | Self::MalformedDisplayName { reference, .. }
            | Self::IdentityMismatch { reference, .. }
            | Self::OwnerMismatch { reference, .. }
            | Self::SecretVersion { reference, .. }
            | Self::UnknownLifecycle { reference, .. }
            | Self::SecretOwnerConflict { reference, .. }
            | Self::ForeignProvider { reference, .. }
            | Self::NotAProvider { reference, .. }
            | Self::LifecycleConflict { reference, .. }
            | Self::AmbiguousActiveSecret { reference, .. } => *reference,
        }
    }
}

impl BodyError for CredentialError {
    fn kind(reference: ResourceRef, expected: ResourceKind, found: ResourceKind) -> Self {
        Self::Kind {
            reference,
            expected,
            found,
        }
    }

    fn not_inline(reference: ResourceRef) -> Self {
        Self::NotInline { reference }
    }

    fn not_a_record(reference: ResourceRef) -> Self {
        Self::NotARecord { reference }
    }

    fn schema(reference: ResourceRef, expected: &'static str, found: String) -> Self {
        Self::Schema {
            reference,
            expected,
            found,
        }
    }

    fn missing_field(reference: ResourceRef, field: &'static str) -> Self {
        Self::MissingField { reference, field }
    }

    fn unknown_field(reference: ResourceRef, schema: &'static str, field: String) -> Self {
        Self::UnknownField {
            reference,
            schema,
            field,
        }
    }

    fn field_type(reference: ResourceRef, field: &'static str) -> Self {
        Self::FieldType { reference, field }
    }

    fn malformed_id(reference: ResourceRef, field: &'static str, source: InvalidId) -> Self {
        Self::MalformedId {
            reference,
            field,
            source,
        }
    }

    fn malformed_display_name(
        reference: ResourceRef,
        field: &'static str,
        source: InvalidDisplayName,
    ) -> Self {
        Self::MalformedDisplayName {
            reference,
            field,
            source,
        }
    }

    fn identity_mismatch(reference: ResourceRef, declared: String, identity: ResourceId) -> Self {
        Self::IdentityMismatch {
            reference,
            declared,
            identity,
        }
    }
}

/// A tenant's or project's credential for one provider: an owner, a provider, and
/// an opaque reference to the material that authenticates to it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProviderCredentialBody {
    credential: ResourceId,
    owner: SecretOwner,
    provider: ResourceId,
    display_name: DisplayName,
    secret: SecretRef,
    lifecycle: SecretLifecycle,
}

impl ProviderCredentialBody {
    /// The schema identifier this body encodes and reads.
    pub const SCHEMA: &'static str = PROVIDER_CREDENTIAL_SCHEMA;

    const KNOWN_FIELDS: &'static [&'static str] = &[
        CREDENTIAL_ID_FIELD,
        TENANT_ID_FIELD,
        PROJECT_ID_FIELD,
        PROVIDER_ID_FIELD,
        DISPLAY_NAME_FIELD,
        SECRET_ID_FIELD,
        SECRET_VERSION_FIELD,
        LIFECYCLE_FIELD,
    ];

    /// A newly authored credential, pointing at freshly staged material.
    ///
    /// Staged rather than active on purpose: material is loaded, then proven by
    /// compiling a candidate revision against it, and only then put in service.
    /// Nothing here can be authored straight into the request path.
    pub const fn staged(
        credential: ResourceId,
        owner: SecretOwner,
        provider: ResourceId,
        display_name: DisplayName,
        secret: SecretRef,
    ) -> Self {
        Self {
            credential,
            owner,
            provider,
            display_name,
            secret,
            lifecycle: SecretLifecycle::Staged,
        }
    }

    pub const fn credential(&self) -> ResourceId {
        self.credential
    }

    /// Who owns this credential and, by construction, its material.
    pub const fn owner(&self) -> SecretOwner {
        self.owner
    }

    pub const fn tenant(&self) -> TenantId {
        self.owner.tenant
    }

    pub const fn project(&self) -> Option<ProjectId> {
        self.owner.project
    }

    pub const fn provider(&self) -> ResourceId {
        self.provider
    }

    pub const fn display_name(&self) -> &DisplayName {
        &self.display_name
    }

    /// The exact material this credential authenticates with.
    pub const fn secret(&self) -> SecretRef {
        self.secret
    }

    pub const fn lifecycle(&self) -> SecretLifecycle {
        self.lifecycle
    }

    /// Whether this credential's material may be unwrapped during snapshot
    /// compilation. Lifecycle only — the store still checks ownership, and it is
    /// the store that holds the material.
    pub const fn permits_resolution(&self) -> bool {
        self.lifecycle.permits_resolution()
    }

    /// The same credential, its material moved to `next`.
    ///
    /// Metadata only: no plaintext is read, written, or returned, so a lifecycle
    /// change never has to touch the secret store. Idempotent moves return an
    /// unchanged body, which is what makes republishing the same desired state a
    /// no-op instead of a conflict.
    pub fn transitioned(&self, next: SecretLifecycle) -> Result<Self, ForbiddenTransition> {
        let transition = self.lifecycle.transition_to(next)?;
        Ok(Self {
            lifecycle: transition.state(),
            display_name: self.display_name.clone(),
            ..*self
        })
    }

    /// What [`ProviderCredentialBody::transitioned`] would do, without doing it.
    pub fn transition_to(
        &self,
        next: SecretLifecycle,
    ) -> Result<LifecycleTransition, ForbiddenTransition> {
        self.lifecycle.transition_to(next)
    }

    /// The same credential, pointing at the next version of the same secret.
    ///
    /// The new version is staged: rotation stores material, and putting it in
    /// service is a separate decision. The previous version keeps whatever state
    /// it had, in the revision that named it.
    ///
    /// One resource names one version, so *this* body no longer names the version
    /// it was serving. A rotation that must not interrupt service is therefore two
    /// credential resources — the serving one untouched, a second one staged
    /// against the new version — and the credential the old one names is withdrawn
    /// only after the new one is active. Publishing this body alone is the
    /// deliberate cut-over, not the overlap.
    pub fn rotated(&self) -> Self {
        Self {
            secret: self.secret.rotated(),
            lifecycle: SecretLifecycle::Staged,
            display_name: self.display_name.clone(),
            ..*self
        }
    }

    /// The resource identity this credential's versions are written under.
    pub const fn resource_id(&self) -> ResourceId {
        self.credential
    }

    pub fn body(&self) -> ResourceBody {
        ResourceBody::Inline(self.canonical())
    }

    /// The scope this credential's versions live at: exactly its owner's.
    pub const fn scope(&self) -> ResourceScope {
        self.owner.scope()
    }

    pub fn version(&self, slug: Slug) -> ResourceVersion {
        self.version_at(slug, ResourceVersionNumber::FIRST)
    }

    pub fn version_at(&self, slug: Slug, version: ResourceVersionNumber) -> ResourceVersion {
        ResourceVersion::new(
            ResourceRef::new(
                ResourceKind::ProviderCredential,
                self.resource_id(),
                version,
            ),
            self.scope(),
            slug,
            self.body(),
        )
    }

    /// Read a provider-credential resource's body, binding it to its envelope:
    /// identity to the reference, ownership to the scope.
    pub fn read(resource: &ResourceVersion) -> Result<Self, CredentialError> {
        let record = Record::<CredentialError>::open(
            resource,
            ResourceKind::ProviderCredential,
            Self::SCHEMA,
            Self::KNOWN_FIELDS,
        )?;
        let credential = record.typed_id(CREDENTIAL_ID_FIELD, ResourceId::parse)?;
        record.identity(credential, credential)?;
        let owner = SecretOwner {
            tenant: record.tenant()?,
            project: record.optional_project()?,
        };
        if resource.scope != owner.scope() {
            return Err(CredentialError::OwnerMismatch {
                reference: resource.reference,
                declared: owner,
            });
        }
        let version = record.integer(SECRET_VERSION_FIELD)?;
        let secret = SecretRef::new(
            record.typed_id(SECRET_ID_FIELD, SecretId::parse)?,
            SecretVersion::new(version).ok_or(CredentialError::SecretVersion {
                reference: resource.reference,
                found: version,
            })?,
        );
        let declared = record.string(LIFECYCLE_FIELD)?;
        let lifecycle =
            SecretLifecycle::parse(declared).ok_or_else(|| CredentialError::UnknownLifecycle {
                reference: resource.reference,
                found: declared.to_owned(),
            })?;
        Ok(Self {
            credential,
            owner,
            provider: record.typed_id(PROVIDER_ID_FIELD, ResourceId::parse)?,
            display_name: record.display_name()?,
            secret,
            lifecycle,
        })
    }
}

impl Canonical for ProviderCredentialBody {
    fn canonical(&self) -> CanonicalValue {
        // `project_id` is absent rather than empty for a tenant-scoped
        // credential: the canonical model has no null, and an empty id would be a
        // second spelling of "none".
        let mut fields = vec![
            (SCHEMA_FIELD, CanonicalValue::string(Self::SCHEMA)),
            (
                CREDENTIAL_ID_FIELD,
                CanonicalValue::string(self.credential.to_string()),
            ),
            (
                TENANT_ID_FIELD,
                CanonicalValue::string(self.owner.tenant.to_string()),
            ),
            (
                PROVIDER_ID_FIELD,
                CanonicalValue::string(self.provider.to_string()),
            ),
            (
                DISPLAY_NAME_FIELD,
                CanonicalValue::string(self.display_name.as_str()),
            ),
            (
                SECRET_ID_FIELD,
                CanonicalValue::string(self.secret.secret.to_string()),
            ),
            (
                SECRET_VERSION_FIELD,
                CanonicalValue::integer(self.secret.version.get()),
            ),
            (
                LIFECYCLE_FIELD,
                CanonicalValue::string(self.lifecycle.as_str()),
            ),
        ];
        if let Some(project) = self.owner.project {
            fields.push((
                PROJECT_ID_FIELD,
                CanonicalValue::string(project.to_string()),
            ));
        }
        CanonicalValue::map(fields)
    }
}

/// A provider credential as a revision holds it: its envelope, its name, and its
/// body.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProviderCredential {
    pub reference: ResourceRef,
    pub slug: Slug,
    pub body: ProviderCredentialBody,
}

/// The credentials of one revision, read once.
///
/// Built by [`Credentials::of`], which is the single place credential bodies are
/// interpreted, so publication and hydration cannot reach different conclusions
/// about the same revision. Ordering is by id, so two replicas iterate the same
/// credentials in the same order.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Credentials {
    credentials: BTreeMap<ResourceId, ProviderCredential>,
    owners: BTreeMap<SecretId, (SecretOwner, ResourceRef)>,
}

impl Credentials {
    /// Read and cross-check every provider credential in a desired state.
    ///
    /// Beyond reading each body strictly, four properties are checked that no
    /// envelope-level rule can see, because the envelope cannot see inside a
    /// body:
    ///
    /// 1. one secret belongs to one owner, so a reference cannot carry material
    ///    across a tenant or project boundary;
    /// 2. a credential authenticates to a provider its owner can reach: its own
    ///    scope, or its tenant's, and never another tenant's or a sibling
    ///    project's;
    /// 3. two references to one secret version agree about that version's state;
    /// 4. at most one version of a secret is active, so what a request would be
    ///    authorized by does not depend on iteration order.
    ///
    /// A `provider_id` naming a resource this revision does not declare is *not*
    /// refused, for the reason [`Tenancy::of`] gives about tenant-scoped
    /// resources: a revision published before this rule existed may name one, and
    /// hydration runs these same checks, so requiring it would stop such a
    /// revision from loading on upgrade. What the reference names is then
    /// unresolvable at the boundary that resolves it, which is not the same thing
    /// as unreadable here.
    ///
    /// [`Tenancy::of`]: super::tenancy::Tenancy::of
    pub fn of(state: &DesiredState) -> Result<Self, CredentialError> {
        let mut credentials = Self::default();
        for resource in state.resources() {
            if resource.reference.kind != ResourceKind::ProviderCredential {
                continue;
            }
            let body = ProviderCredentialBody::read(resource)?;
            let owner = body.owner();
            if let Some((claimed_by, conflicting)) =
                credentials.owners.get(&body.secret().secret).copied()
                && claimed_by != owner
            {
                return Err(CredentialError::SecretOwnerConflict {
                    reference: resource.reference,
                    secret: body.secret().secret,
                    conflicting,
                });
            }
            credentials
                .owners
                .insert(body.secret().secret, (owner, resource.reference));
            credentials.credentials.insert(
                body.credential(),
                ProviderCredential {
                    reference: resource.reference,
                    slug: resource.slug.clone(),
                    body,
                },
            );
        }

        credentials.check_providers(state)?;
        credentials.check_lifecycles()?;
        Ok(credentials)
    }

    /// A credential reaches a provider at its own scope, or at its tenant's.
    fn check_providers(&self, state: &DesiredState) -> Result<(), CredentialError> {
        for credential in self.credentials.values() {
            let owner = credential.body.owner();
            let Some(provider) = state
                .resources()
                .find(|resource| resource.reference.id == credential.body.provider())
            else {
                continue;
            };
            if provider.reference.kind != ResourceKind::Provider {
                return Err(CredentialError::NotAProvider {
                    reference: credential.reference,
                    provider: credential.body.provider(),
                    found: provider.reference.kind,
                });
            }
            let reachable = provider.scope == owner.scope()
                || provider.scope == ResourceScope::Tenant(owner.tenant);
            if !reachable {
                return Err(CredentialError::ForeignProvider {
                    reference: credential.reference,
                    provider: provider.reference,
                    owner,
                });
            }
        }
        Ok(())
    }

    /// One state per secret version, and one active version per secret.
    ///
    /// Two credentials naming the *same* active version are not refused, and the
    /// rule is about ambiguity rather than tidiness: one version's material serves
    /// either way, so nothing depends on which row is read. Refusing it would also
    /// make an alias-style arrangement — two provider resources authenticating with
    /// one key — unpublishable for no safety gain.
    fn check_lifecycles(&self) -> Result<(), CredentialError> {
        let mut states: BTreeMap<SecretRef, (SecretLifecycle, ResourceRef)> = BTreeMap::new();
        let mut active: BTreeMap<SecretId, (SecretRef, ResourceRef)> = BTreeMap::new();
        for credential in self.credentials.values() {
            let secret = credential.body.secret();
            let state = credential.body.lifecycle();
            if let Some((declared, conflicting)) = states.get(&secret).copied()
                && declared != state
            {
                return Err(CredentialError::LifecycleConflict {
                    reference: credential.reference,
                    secret,
                    state,
                    conflicting,
                    conflicting_state: declared,
                });
            }
            states.insert(secret, (state, credential.reference));
            if state != SecretLifecycle::Active {
                continue;
            }
            if let Some((conflicting_secret, conflicting)) = active.get(&secret.secret).copied()
                && conflicting_secret != secret
            {
                return Err(CredentialError::AmbiguousActiveSecret {
                    reference: credential.reference,
                    secret,
                    conflicting,
                });
            }
            active.insert(secret.secret, (secret, credential.reference));
        }
        Ok(())
    }

    /// Every credential, ordered by id.
    pub fn all(&self) -> impl ExactSizeIterator<Item = &ProviderCredential> {
        self.credentials.values()
    }

    pub fn len(&self) -> usize {
        self.credentials.len()
    }

    pub fn is_empty(&self) -> bool {
        self.credentials.is_empty()
    }

    pub fn get(&self, credential: ResourceId) -> Option<&ProviderCredential> {
        self.credentials.get(&credential)
    }

    /// The credentials one owner holds.
    pub fn of_owner(&self, owner: SecretOwner) -> impl Iterator<Item = &ProviderCredential> {
        self.credentials
            .values()
            .filter(move |credential| credential.body.owner() == owner)
    }

    /// The credentials whose material is in service.
    pub fn active(&self) -> impl Iterator<Item = &ProviderCredential> {
        self.credentials
            .values()
            .filter(|credential| credential.body.lifecycle() == SecretLifecycle::Active)
    }

    /// Who owns a secret this revision references, if it references it.
    ///
    /// The reverse lookup a resolver needs: given a reference, the owner it must
    /// be resolved as, taken from the revision rather than from the caller.
    pub fn owner_of(&self, secret: SecretId) -> Option<SecretOwner> {
        self.owners.get(&secret).map(|(owner, _)| *owner)
    }

    /// Every exact secret version this revision's credentials pin, with the owner
    /// each must be resolved as.
    ///
    /// What snapshot compilation iterates: a revision is publishable once every
    /// one of these resolves, and a resolution failure is a rejected candidate
    /// rather than a request-time error.
    pub fn required_secrets(&self) -> impl Iterator<Item = (SecretOwner, SecretRef)> {
        self.credentials
            .values()
            .filter(|credential| credential.body.permits_resolution())
            .map(|credential| (credential.body.owner(), credential.body.secret()))
    }
}

#[cfg(test)]
mod tests {
    use super::super::canonical::SerializerVersion;
    use super::super::fixtures::{
        alias, candidate, credential, credential_body, display_name, legacy_credential,
        project_credential, project_id, provider, provider_id, resource_id, revision_id, secret_id,
        secret_ref, secret_ref_at, state, tenant, tenant_id,
    };
    use super::super::ids::Slug;
    use super::super::mutation::ExpectedRevision;
    use super::super::revision::{
        BodySkew, IntegrityError, LoadedRevision, RevisionManifest, ValidationError,
    };
    use super::*;

    /// The material a test must never be able to find in a body, an error, or a
    /// checksummed encoding — because no type here can hold it.
    const PLAINTEXT: &str = "sk-live-do-not-log";

    fn owner() -> SecretOwner {
        SecretOwner::tenant(tenant_id(1))
    }

    fn slug(name: &str) -> Slug {
        Slug::parse(name).expect("fixture slug")
    }

    /// Rewrite a credential's inline record: how a body no caller could author —
    /// or a newer build's body — is put in front of the reader.
    fn with_fields(
        resource: &ResourceVersion,
        edit: impl FnOnce(&mut Vec<(String, CanonicalValue)>),
    ) -> ResourceVersion {
        let ResourceBody::Inline(CanonicalValue::Map(fields)) = &resource.body else {
            panic!("a credential fixture body is an inline record");
        };
        let mut fields = fields.clone();
        edit(&mut fields);
        ResourceVersion {
            body: ResourceBody::Inline(CanonicalValue::Map(fields)),
            ..resource.clone()
        }
    }

    fn set(fields: &mut Vec<(String, CanonicalValue)>, field: &str, value: CanonicalValue) {
        fields.retain(|(name, _)| name != field);
        fields.push((field.to_owned(), value));
    }

    /// A state holding `resources` and nothing else, for the cases that are about
    /// credential bodies rather than about a whole revision.
    fn state_of(resources: impl IntoIterator<Item = ResourceVersion>) -> DesiredState {
        let mut state = DesiredState::new();
        for resource in resources {
            state.insert(resource).expect("distinct references");
        }
        state
    }

    #[test]
    fn a_body_round_trips_through_its_envelope_and_its_canonical_bytes() {
        let body = credential_body(&tenant_id(1), 3, "primary");
        let resource = credential(&tenant_id(1), 3, "primary");
        assert_eq!(ProviderCredentialBody::read(&resource).unwrap(), body);
        assert_eq!(resource.reference.kind, ResourceKind::ProviderCredential);
        assert_eq!(resource.reference.id, resource_id(3));
        assert_eq!(resource.scope, ResourceScope::Tenant(tenant_id(1)));
        assert_eq!(body.secret(), secret_ref(3));
        assert_eq!(body.owner(), owner());
        assert_eq!(body.tenant(), tenant_id(1));
        assert_eq!(body.project(), None);
        assert_eq!(body.provider(), provider_id(3));
        assert_eq!(body.resource_id(), body.credential());

        let bytes = SerializerVersion::V1.encode(&body.canonical()).unwrap();
        let decoded = SerializerVersion::V1
            .decode(&bytes)
            .expect("a credential body is canonical, so storage returns what it took");
        assert_eq!(SerializerVersion::V1.encode(&decoded).unwrap(), bytes);
        assert_eq!(
            ProviderCredentialBody::read(&ResourceVersion {
                body: ResourceBody::Inline(decoded),
                ..resource
            })
            .unwrap(),
            body,
            "and reads back as the same body"
        );
        assert!(
            String::from_utf8_lossy(&bytes).contains(PROVIDER_CREDENTIAL_SCHEMA),
            "the schema identifier is part of the checksummed body"
        );

        // A project's credential names its project; a tenant's omits the field
        // rather than carrying an empty one.
        let inner = project_credential(&tenant_id(1), &project_id(2), 4, "inner");
        let inner = ProviderCredentialBody::read(&inner).unwrap();
        assert_eq!(
            inner.owner(),
            SecretOwner::project(tenant_id(1), project_id(2))
        );
        assert_eq!(
            inner.scope(),
            ResourceScope::Project {
                tenant: tenant_id(1),
                project: project_id(2)
            }
        );
        let CanonicalValue::Map(fields) = body.canonical() else {
            panic!("a body is a record");
        };
        assert!(
            !fields.iter().any(|(field, _)| field == PROJECT_ID_FIELD),
            "a tenant-scoped credential has no project field at all"
        );
    }

    /// The point of the whole slice: a body is a *reference*, so there is no field
    /// a plaintext, a fingerprint, or a prefix could travel in.
    #[test]
    fn a_body_carries_a_reference_and_nothing_derived_from_the_material() {
        let body = credential_body(&tenant_id(1), 3, "primary");
        let CanonicalValue::Map(fields) = body.canonical() else {
            panic!("a body is a record");
        };
        let mut names: Vec<&str> = fields.iter().map(|(field, _)| field.as_str()).collect();
        names.sort_unstable();
        assert_eq!(
            names,
            [
                "credential_id",
                "display_name",
                "lifecycle",
                "provider_id",
                "schema",
                "secret_id",
                "secret_version",
                "tenant_id",
            ],
            "a new field here is a new disclosure to review"
        );

        // Every rendering of a body, and of the resource that carries it, is
        // material-free — there being no material in it is why.
        let resource = credential(&tenant_id(1), 3, "primary");
        let bytes = SerializerVersion::V1.encode(&body.canonical()).unwrap();
        for rendered in [
            format!("{body:?}"),
            format!("{resource:?}"),
            String::from_utf8_lossy(&bytes).into_owned(),
        ] {
            assert!(!rendered.contains(PLAINTEXT), "{rendered}");
            assert!(!rendered.contains("sk-"), "{rendered}");
        }
        assert!(
            format!("{body:?}").contains(&secret_id(3).uuid().to_string()),
            "the opaque reference is what a diagnostic prints"
        );
    }

    #[test]
    fn material_is_staged_before_it_is_ever_in_service() {
        let body = credential_body(&tenant_id(1), 3, "primary");
        assert_eq!(body.lifecycle(), SecretLifecycle::Staged);
        assert!(
            body.permits_resolution(),
            "staged material resolves so a candidate can be compiled against it"
        );

        let active = body.transitioned(SecretLifecycle::Active).unwrap();
        assert_eq!(active.lifecycle(), SecretLifecycle::Active);
        assert_eq!(active.secret(), body.secret(), "a state change is metadata");
        assert_eq!(active.credential(), body.credential());
        assert_eq!(active.display_name(), body.display_name());

        // Republishing the same desired state is a no-op, not a conflict.
        assert_eq!(
            active.transition_to(SecretLifecycle::Active).unwrap(),
            LifecycleTransition::Unchanged(SecretLifecycle::Active)
        );
        assert_eq!(
            active.transitioned(SecretLifecycle::Active).unwrap(),
            active
        );

        // Withdrawn material stops resolving without being edited or deleted.
        let disabled = active.transitioned(SecretLifecycle::Disabled).unwrap();
        assert!(!disabled.permits_resolution());
        assert_eq!(
            disabled
                .transitioned(SecretLifecycle::Active)
                .unwrap()
                .lifecycle(),
            SecretLifecycle::Active,
            "disabling is reversible; revoking is not"
        );
        let revoked = active.transitioned(SecretLifecycle::Revoked).unwrap();
        assert_eq!(
            revoked.transitioned(SecretLifecycle::Active),
            Err(ForbiddenTransition {
                from: SecretLifecycle::Revoked,
                to: SecretLifecycle::Active
            })
        );
    }

    #[test]
    fn rotation_pins_a_new_version_instead_of_editing_the_old_one() {
        let first = credential_body(&tenant_id(1), 3, "primary")
            .transitioned(SecretLifecycle::Active)
            .unwrap();
        let second = first.rotated();

        assert_eq!(second.secret(), secret_ref_at(3, 2));
        assert!(second.secret().is_same_secret(first.secret()));
        assert_eq!(
            second.lifecycle(),
            SecretLifecycle::Staged,
            "rotation stores material; putting it in service is a separate move"
        );
        assert_eq!(
            first.secret(),
            secret_ref(3),
            "the published body still pins the material it was compiled against"
        );
        assert_eq!(first.lifecycle(), SecretLifecycle::Active);
        assert_eq!(second.credential(), first.credential());
        assert_eq!(second.owner(), first.owner());

        // A rotated body is a new *resource version* of the same credential, so
        // the revision that pinned version 1 is untouched by it.
        let published = second.version_at(slug("primary"), ResourceVersionNumber::FIRST.next());
        assert_eq!(published.reference.id, first.credential());
        assert_eq!(
            ProviderCredentialBody::read(&published).unwrap().secret(),
            secret_ref_at(3, 2)
        );
    }

    /// One resource names one version, so an operator who must not interrupt
    /// service authors the new material *beside* the serving credential and
    /// withdraws the old one after the cut-over. This is the sequence an admin
    /// surface has to produce; every step of it publishes, and the one step that
    /// would make "which key authorizes this" ambiguous does not.
    #[test]
    fn an_uninterrupted_rotation_is_two_credentials_and_a_deliberate_cut_over() {
        let serving = credential_body(&tenant_id(1), 3, "primary")
            .transitioned(SecretLifecycle::Active)
            .unwrap();
        // Step 1: the new version is staged beside the serving one, under its own
        // credential resource, so nothing stops serving while it is proven.
        let incoming = ProviderCredentialBody::staged(
            resource_id(18),
            owner(),
            provider_id(18),
            display_name("Rotating"),
            serving.secret().rotated(),
        );
        let overlap = state_of([
            serving.version(slug("primary")),
            incoming.version(slug("rotating")),
        ]);
        let credentials = Credentials::of(&overlap).expect("staging beside a serving credential");
        assert_eq!(credentials.active().count(), 1, "one version serves");
        assert_eq!(credentials.of_owner(owner()).count(), 2);

        // Step 2: activating the new version *before* withdrawing the old one is
        // the ambiguity the rules exist to refuse, not a valid overlap.
        let contested = state_of([
            serving.version(slug("primary")),
            incoming
                .transitioned(SecretLifecycle::Active)
                .unwrap()
                .version(slug("rotating")),
        ]);
        assert!(matches!(
            Credentials::of(&contested).expect_err("two active versions of one secret"),
            CredentialError::AmbiguousActiveSecret { .. }
        ));

        // Step 3: the cut-over — the old version is withdrawn in the same revision
        // that puts the new one in service, so no revision has either two active
        // versions or none.
        let cut_over = state_of([
            serving
                .transitioned(SecretLifecycle::Revoked)
                .unwrap()
                .version_at(slug("primary"), ResourceVersionNumber::FIRST.next()),
            incoming
                .transitioned(SecretLifecycle::Active)
                .unwrap()
                .version(slug("rotating")),
        ]);
        let credentials = Credentials::of(&cut_over).expect("a cut-over publishes");
        let mut active = credentials.active();
        assert_eq!(
            active.next().expect("one active credential").body.secret(),
            secret_ref_at(3, 2),
            "the new material serves, and only it"
        );
        assert!(active.next().is_none());

        // Repointing the serving credential instead, which `rotated` does, is the
        // same cut-over in one resource: it publishes, and it leaves the revision
        // with no active version until a further move, which is why an
        // uninterrupted rotation is authored as two.
        let repointed = state_of([serving
            .rotated()
            .version_at(slug("primary"), ResourceVersionNumber::FIRST.next())]);
        assert_eq!(
            Credentials::of(&repointed)
                .expect("repointing publishes")
                .active()
                .count(),
            0
        );
    }

    #[test]
    fn a_body_cannot_declare_an_owner_its_envelope_does_not_place_it_under() {
        // Scope and body disagree: the credential is filed under a project, its
        // body claims the tenant.
        let resource = credential(&tenant_id(1), 3, "primary");
        let misfiled = ResourceVersion {
            scope: ResourceScope::Project {
                tenant: tenant_id(1),
                project: project_id(2),
            },
            ..resource.clone()
        };
        assert_eq!(
            ProviderCredentialBody::read(&misfiled),
            Err(CredentialError::OwnerMismatch {
                reference: misfiled.reference,
                declared: owner()
            })
        );
        // Another tenant's scope, same body: ownership is the envelope's.
        let stolen = ResourceVersion {
            scope: ResourceScope::Tenant(tenant_id(9)),
            ..resource.clone()
        };
        assert!(matches!(
            ProviderCredentialBody::read(&stolen),
            Err(CredentialError::OwnerMismatch { .. })
        ));

        // And a body's declared identity is its envelope's.
        let renamed = with_fields(&resource, |fields| {
            set(
                fields,
                CREDENTIAL_ID_FIELD,
                CanonicalValue::string(resource_id(99).to_string()),
            );
        });
        assert_eq!(
            ProviderCredentialBody::read(&renamed),
            Err(CredentialError::IdentityMismatch {
                reference: renamed.reference,
                declared: resource_id(99).to_string(),
                identity: resource_id(3)
            })
        );
    }

    #[test]
    fn a_body_this_build_cannot_read_is_a_compatibility_refusal_not_damage() {
        let resource = credential(&tenant_id(1), 3, "primary");

        // A newer release's schema, and a field it added: both mean "run a build
        // that reads this", not "storage is damaged".
        let newer = with_fields(&resource, |fields| {
            set(
                fields,
                SCHEMA_FIELD,
                CanonicalValue::string("axond.provider-credential.v2"),
            );
        });
        let error = ProviderCredentialBody::read(&newer).expect_err("a v2 body");
        assert_eq!(
            error,
            CredentialError::Schema {
                reference: newer.reference,
                expected: PROVIDER_CREDENTIAL_SCHEMA,
                found: "axond.provider-credential.v2".to_owned()
            }
        );
        assert!(error.is_incompatible());
        assert_eq!(error.reference(), newer.reference);

        let extended = with_fields(&resource, |fields| {
            set(fields, "rotation_policy", CanonicalValue::string("monthly"));
        });
        assert!(
            ProviderCredentialBody::read(&extended)
                .expect_err("an unknown field")
                .is_incompatible()
        );

        // A lifecycle state a newer release defined is the same class: the body is
        // well-formed, this build just does not know what it says.
        let unknown = with_fields(&resource, |fields| {
            set(
                fields,
                LIFECYCLE_FIELD,
                CanonicalValue::string("quarantined"),
            );
        });
        let error = ProviderCredentialBody::read(&unknown).expect_err("an unknown state");
        assert_eq!(
            error,
            CredentialError::UnknownLifecycle {
                reference: unknown.reference,
                found: "quarantined".to_owned()
            }
        );
        assert!(error.is_incompatible());

        // An untyped body a build predating this slice wrote: no schema at all.
        let legacy = legacy_credential(&tenant_id(1), 3, "primary");
        let error = ProviderCredentialBody::read(&legacy).expect_err("an untyped body");
        assert_eq!(
            error,
            CredentialError::MissingField {
                reference: legacy.reference,
                field: SCHEMA_FIELD
            }
        );
        assert!(error.is_incompatible());
    }

    #[test]
    fn a_malformed_body_is_refused_as_malformed_rather_than_as_a_newer_schema() {
        let resource = credential(&tenant_id(1), 3, "primary");
        let cases = [
            with_fields(&resource, |fields| {
                set(fields, SECRET_ID_FIELD, CanonicalValue::string("res_nope"));
            }),
            with_fields(&resource, |fields| {
                set(fields, SECRET_VERSION_FIELD, CanonicalValue::integer(0));
            }),
            with_fields(&resource, |fields| {
                set(fields, SECRET_VERSION_FIELD, CanonicalValue::string("1"));
            }),
            with_fields(&resource, |fields| {
                fields.retain(|(field, _)| field != DISPLAY_NAME_FIELD);
            }),
            ResourceVersion {
                body: ResourceBody::Inline(CanonicalValue::string("primary")),
                ..resource.clone()
            },
            ResourceVersion {
                reference: ResourceRef::new(
                    ResourceKind::Alias,
                    resource_id(3),
                    ResourceVersionNumber::FIRST,
                ),
                ..resource.clone()
            },
        ];
        for case in cases {
            let error = ProviderCredentialBody::read(&case).expect_err("a malformed body");
            assert!(
                !error.is_incompatible(),
                "malformed state is repair work, not a version skew: {error}"
            );
            assert!(!error.to_string().contains(PLAINTEXT));
        }

        // Version zero names itself, so an operator can see what was written.
        let zero = with_fields(&resource, |fields| {
            set(fields, SECRET_VERSION_FIELD, CanonicalValue::integer(0));
        });
        assert_eq!(
            ProviderCredentialBody::read(&zero),
            Err(CredentialError::SecretVersion {
                reference: zero.reference,
                found: 0
            })
        );
    }

    #[test]
    fn one_secret_belongs_to_one_owner() {
        // Two tenants' credentials pointing at the same material: opaque
        // references make this invisible to everything except this rule.
        let mine = credential(&tenant_id(1), 3, "primary");
        let theirs = ProviderCredentialBody::staged(
            resource_id(13),
            SecretOwner::tenant(tenant_id(9)),
            provider_id(13),
            display_name("Borrowed"),
            secret_ref(3),
        )
        .version(slug("borrowed"));
        let error = Credentials::of(&state_of([mine.clone(), theirs.clone()]))
            .expect_err("one secret, two tenants");
        assert_eq!(
            error,
            CredentialError::SecretOwnerConflict {
                reference: theirs.reference,
                secret: secret_id(3),
                conflicting: mine.reference
            }
        );
        assert!(!error.is_incompatible());

        // A project of the *same* tenant is a different owner too: material is
        // owned exactly, not by a hierarchy.
        let inner = ProviderCredentialBody::staged(
            resource_id(14),
            SecretOwner::project(tenant_id(1), project_id(2)),
            provider_id(14),
            display_name("Inner"),
            secret_ref(3),
        )
        .version(slug("inner"));
        assert!(matches!(
            Credentials::of(&state_of([mine.clone(), inner])),
            Err(CredentialError::SecretOwnerConflict { .. })
        ));

        // Two versions of one secret, one owner, is ordinary rotation.
        let rotated = ProviderCredentialBody::staged(
            resource_id(15),
            owner(),
            provider_id(15),
            display_name("Rotated"),
            secret_ref_at(3, 2),
        )
        .version(slug("rotated"));
        let credentials =
            Credentials::of(&state_of([mine, rotated])).expect("one owner, two versions");
        assert_eq!(credentials.len(), 2);
        assert_eq!(credentials.owner_of(secret_id(3)), Some(owner()));
        assert_eq!(credentials.owner_of(secret_id(77)), None);
    }

    #[test]
    fn a_credential_reaches_only_the_providers_its_owner_can_reach() {
        let inner = project_credential(&tenant_id(1), &project_id(2), 4, "inner");

        // Its tenant's provider, and its own project's, are both reachable.
        for scope in [
            ResourceScope::Tenant(tenant_id(1)),
            ResourceScope::Project {
                tenant: tenant_id(1),
                project: project_id(2),
            },
        ] {
            Credentials::of(&state_of([inner.clone(), provider(4, scope, "openai")]))
                .expect("a provider inside the owner's reach");
        }

        // A sibling project's is not, and neither is another tenant's.
        for scope in [
            ResourceScope::Project {
                tenant: tenant_id(1),
                project: project_id(77),
            },
            ResourceScope::Tenant(tenant_id(9)),
        ] {
            let foreign = provider(4, scope, "openai");
            assert_eq!(
                Credentials::of(&state_of([inner.clone(), foreign.clone()])),
                Err(CredentialError::ForeignProvider {
                    reference: inner.reference,
                    provider: foreign.reference,
                    owner: SecretOwner::project(tenant_id(1), project_id(2))
                })
            );
        }

        // A `provider_id` naming something that is not a provider is refused.
        let impostor = alias(&tenant_id(1), 904, "impostor", &[]);
        assert_eq!(
            Credentials::of(&state_of([inner.clone(), impostor])),
            Err(CredentialError::NotAProvider {
                reference: inner.reference,
                provider: provider_id(4),
                found: ResourceKind::Alias
            })
        );

        // A provider this revision does not declare is unresolvable, not
        // unreadable: an older revision must not stop hydrating on upgrade.
        Credentials::of(&state_of([inner]))
            .expect("an absent provider row is resolved elsewhere, or not at all");
    }

    #[test]
    fn one_version_of_a_secret_is_in_service_and_it_is_not_ambiguous() {
        let active = credential_body(&tenant_id(1), 3, "primary")
            .transitioned(SecretLifecycle::Active)
            .unwrap();

        // Two rows, one exact version, two states: the material would be both in
        // service and not, depending on which row was read.
        let staged = ProviderCredentialBody::staged(
            resource_id(16),
            owner(),
            provider_id(16),
            display_name("Shared"),
            secret_ref(3),
        );
        let error = Credentials::of(&state_of([
            active.version(slug("primary")),
            staged.version(slug("shared")),
        ]))
        .expect_err("one version cannot be in two states");
        assert!(matches!(error, CredentialError::LifecycleConflict { .. }));
        assert!(!error.is_incompatible());

        // Two *versions* of one secret, both active: which material authorizes a
        // request would depend on iteration order.
        let second = ProviderCredentialBody::staged(
            resource_id(17),
            owner(),
            provider_id(17),
            display_name("Second"),
            secret_ref_at(3, 2),
        )
        .transitioned(SecretLifecycle::Active)
        .unwrap();
        assert_eq!(
            Credentials::of(&state_of([
                active.version(slug("primary")),
                second.version(slug("second")),
            ])),
            Err(CredentialError::AmbiguousActiveSecret {
                reference: ResourceRef::new(
                    ResourceKind::ProviderCredential,
                    resource_id(17),
                    ResourceVersionNumber::FIRST
                ),
                secret: secret_ref_at(3, 2),
                conflicting: ResourceRef::new(
                    ResourceKind::ProviderCredential,
                    resource_id(3),
                    ResourceVersionNumber::FIRST
                )
            })
        );

        // Rotating is not ambiguous: the new version is staged, the old serves.
        let credentials = Credentials::of(&state_of([
            active.version(slug("primary")),
            second
                .transitioned(SecretLifecycle::Disabled)
                .unwrap()
                .version(slug("second")),
        ]))
        .expect("one active version per secret");
        assert_eq!(credentials.active().count(), 1);
        assert_eq!(credentials.of_owner(owner()).count(), 2);
        assert_eq!(
            credentials
                .of_owner(SecretOwner::tenant(tenant_id(9)))
                .count(),
            0
        );
        // Only material a snapshot may unwrap is required to resolve, so
        // disabling a credential does not make a revision unpublishable.
        assert_eq!(
            credentials.required_secrets().collect::<Vec<_>>(),
            vec![(owner(), secret_ref(3))]
        );
        assert!(
            credentials
                .get(resource_id(3))
                .is_some_and(|credential| credential.slug.as_str() == "primary")
        );

        // Two credentials naming the *same* active version is not ambiguity: one
        // version's material serves either way, so it publishes, and each row is
        // required to resolve as its own owner's.
        let shared = ProviderCredentialBody::staged(
            resource_id(20),
            owner(),
            provider_id(20),
            display_name("Shared"),
            secret_ref(3),
        )
        .transitioned(SecretLifecycle::Active)
        .unwrap();
        let credentials = Credentials::of(&state_of([
            active.version(slug("primary")),
            shared.version(slug("shared")),
        ]))
        .expect("one version, named twice, is unambiguous");
        assert_eq!(credentials.active().count(), 2);
        assert_eq!(
            credentials.required_secrets().collect::<Vec<_>>(),
            vec![(owner(), secret_ref(3)), (owner(), secret_ref(3))]
        );
    }

    #[test]
    fn a_revision_is_refused_before_publication_and_again_on_hydration() {
        // Publication: `validate` reads credential bodies, so a cross-owner
        // reference never reaches storage.
        let mut leaking = state();
        leaking
            .insert(tenant(9, "globex"))
            .and_then(|state| {
                state.insert(
                    ProviderCredentialBody::staged(
                        resource_id(19),
                        SecretOwner::tenant(tenant_id(9)),
                        provider_id(19),
                        display_name("Borrowed"),
                        secret_ref(3),
                    )
                    .version(slug("borrowed")),
                )
            })
            .expect("distinct references");
        let error = leaking
            .validate()
            .expect_err("a cross-tenant secret reference must not publish");
        assert!(matches!(
            error,
            ValidationError::Credential(CredentialError::SecretOwnerConflict { .. })
        ));

        // The valid state publishes, and a project's credential inside its own
        // tenant is valid too.
        let mut valid = state();
        valid
            .insert(project_credential(
                &tenant_id(1),
                &project_id(2),
                4,
                "inner",
            ))
            .expect("a distinct reference")
            .validate()
            .expect("a project's own credential is valid desired state");
        assert_eq!(Credentials::of(&valid).unwrap().len(), 2);

        // Hydration: an untyped credential body from a build predating this slice
        // is a *compatibility* refusal that names the row, not corruption.
        let candidate = candidate(ExpectedRevision::Empty, "hydrate", state());
        let manifest = RevisionManifest::of(
            revision_id(1),
            None,
            std::time::SystemTime::UNIX_EPOCH,
            &candidate,
        )
        .expect("a valid candidate");
        let legacy = legacy_credential(&tenant_id(1), 3, "primary");
        let mut stored = DesiredState::new();
        for resource in candidate.state.resources() {
            let resource = if resource.reference.kind == ResourceKind::ProviderCredential {
                legacy.clone()
            } else {
                resource.clone()
            };
            stored.insert(resource).expect("distinct references");
        }
        for blob in candidate.state.blobs() {
            stored.declare_blob(*blob);
        }
        let error = LoadedRevision::assemble(manifest, stored)
            .expect_err("an untyped credential body must not hydrate");
        assert_eq!(
            error,
            IntegrityError::Incompatible(BodySkew::Credential(CredentialError::MissingField {
                reference: legacy.reference,
                field: SCHEMA_FIELD
            }))
        );
        assert!(error.is_incompatible());
        let IntegrityError::Incompatible(skew) = &error else {
            panic!("an incompatibility");
        };
        assert_eq!(
            skew.reference(),
            legacy.reference,
            "a refusal an operator reads names one row"
        );

        // The other half of the classification: rows this build *can* read that
        // contradict each other are not an upgrade away from working, so they
        // hydrate as invalid desired state rather than as compatibility skew. Only
        // a writer outside the gateway can produce this, because `validate` runs
        // before publication too.
        let mut contradictory = DesiredState::new();
        for resource in candidate.state.resources() {
            contradictory
                .insert(resource.clone())
                .expect("distinct references");
        }
        let borrowed = ProviderCredentialBody::staged(
            resource_id(19),
            SecretOwner::tenant(tenant_id(9)),
            provider_id(19),
            display_name("Borrowed"),
            secret_ref(3),
        )
        .version(slug("borrowed"));
        contradictory
            .insert(tenant(9, "globex"))
            .and_then(|state| state.insert(borrowed))
            .expect("distinct references");
        let manifest = RevisionManifest::of(
            revision_id(1),
            None,
            std::time::SystemTime::UNIX_EPOCH,
            &candidate,
        )
        .expect("a valid candidate");
        let error = LoadedRevision::assemble(manifest, contradictory)
            .expect_err("two owners for one secret is not readable desired state");
        assert!(
            !error.is_incompatible(),
            "a contradiction between readable rows is repair work, not an upgrade"
        );
    }

    /// Nothing a refusal prints could tell a reader anything about material —
    /// there is nothing in the domain that holds any.
    #[test]
    fn no_refusal_can_carry_material() {
        let reference = credential(&tenant_id(1), 3, "primary").reference;
        let errors = [
            CredentialError::OwnerMismatch {
                reference,
                declared: owner(),
            },
            CredentialError::SecretVersion {
                reference,
                found: 0,
            },
            CredentialError::UnknownLifecycle {
                reference,
                found: "quarantined".to_owned(),
            },
            CredentialError::SecretOwnerConflict {
                reference,
                secret: secret_id(3),
                conflicting: reference,
            },
            CredentialError::LifecycleConflict {
                reference,
                secret: secret_ref(3),
                state: SecretLifecycle::Active,
                conflicting: reference,
                conflicting_state: SecretLifecycle::Staged,
            },
            CredentialError::AmbiguousActiveSecret {
                reference,
                secret: secret_ref(3),
                conflicting: reference,
            },
        ];
        for error in errors {
            let rendered = error.to_string();
            assert!(!rendered.contains(PLAINTEXT), "{rendered}");
            assert!(!rendered.contains("sk-"), "{rendered}");
            assert!(!format!("{error:?}").contains(PLAINTEXT));
            assert_eq!(error.reference(), reference);
        }
    }
}