exochain-gateway 0.2.0-beta

EXOCHAIN constitutional trust fabric — HTTP gateway server with default-deny pattern
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
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
// Copyright 2026 Exochain Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

//! Authentication middleware — DID-based authentication with signature verification.
//!
//! ## Validation steps
//!
//! `authenticate` validates:
//!   1. DID format (`did:exo:<id>`)
//!   2. Non-empty / non-zero signature bytes
//!   3. Timestamp freshness against trusted gateway observation time (±`FRESHNESS_WINDOW_MS`)
//!   4. Ed25519 signature via `exo_identity::did_verification::verify_did_signature`
//!      over a domain-separated canonical CBOR authentication envelope
//!      against the first active verification method in the resolved DID document
//!
//! ## Multi-credential support
//!
//! `resolve_credential` accepts any [`Credential`] variant (DID signature, API key,
//! or bearer token) and resolves it to an [`AuthenticatedActor`].  Every credential
//! resolves to a DID — there is no identity outside the DID system.
use std::{collections::BTreeMap, fmt};

use exo_core::{Did, Hash256, Signature, Timestamp};
use exo_identity::{did_verification::verify_did_signature, registry::DidRegistry};
use serde::{Deserialize, Serialize};
use zeroize::Zeroizing;

use crate::error::{GatewayError, Result};

/// Maximum age (or future skew) of a request timestamp in milliseconds.
/// Requests outside this window are rejected to prevent replay attacks.
pub(crate) const FRESHNESS_WINDOW_MS: u64 = 300_000; // 5 minutes
const GATEWAY_AUTH_SIGNING_DOMAIN: &str = "exo.gateway.auth.request.v1";

// ---------------------------------------------------------------------------
// Existing types (backward-compatible)
// ---------------------------------------------------------------------------

/// An incoming gateway request with actor identity and signed payload.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Request {
    pub actor_did: String,
    pub action: String,
    pub body_hash: Hash256,
    pub signature: Signature,
    pub timestamp: Timestamp,
}

/// A successfully authenticated actor with their resolved DID and trusted auth timestamp.
#[derive(Debug, Clone)]
pub struct AuthenticatedActor {
    pub did: Did,
    pub authenticated_at: Timestamp,
}

/// Trusted gateway metadata for an authentication attempt.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AuthenticationMetadata {
    observed_at: Timestamp,
}

impl AuthenticationMetadata {
    /// Validate trusted gateway authentication metadata.
    ///
    /// # Errors
    ///
    /// Returns `GatewayError::BadRequest` if `observed_at` is `Timestamp::ZERO`.
    pub(crate) fn new(observed_at: Timestamp) -> Result<Self> {
        if observed_at == Timestamp::ZERO {
            return Err(GatewayError::BadRequest(
                "authentication observed_at must be trusted gateway metadata and non-zero".into(),
            ));
        }
        Ok(Self { observed_at })
    }

    #[must_use]
    pub fn observed_at(&self) -> Timestamp {
        self.observed_at
    }
}

#[derive(Serialize)]
struct RequestSigningPayload<'a> {
    domain: &'static str,
    actor_did: &'a str,
    action: &'a str,
    body_hash: Hash256,
    request_timestamp_physical_ms: u64,
    request_timestamp_logical: u32,
}

/// Build the canonical bytes signed by DID-authenticated gateway requests.
///
/// The signature binds both the signed body hash and security-sensitive request
/// metadata consumed after authentication, so a signature for one action cannot
/// be replayed as a different action with the same body. Trusted gateway
/// observation time is intentionally excluded because it is measured at ingress
/// and must not be supplied or signed by the requester.
///
/// # Errors
///
/// Returns `GatewayError::Internal` if canonical CBOR serialization fails.
pub fn request_signing_payload(request: &Request) -> Result<Vec<u8>> {
    let payload = RequestSigningPayload {
        domain: GATEWAY_AUTH_SIGNING_DOMAIN,
        actor_did: &request.actor_did,
        action: &request.action,
        body_hash: request.body_hash,
        request_timestamp_physical_ms: request.timestamp.physical_ms,
        request_timestamp_logical: request.timestamp.logical,
    };
    let mut encoded = Vec::new();
    ciborium::into_writer(&payload, &mut encoded)
        .map_err(|e| GatewayError::Internal(format!("gateway auth payload CBOR: {e:?}")))?;
    Ok(encoded)
}

// ---------------------------------------------------------------------------
// Credential enum
// ---------------------------------------------------------------------------

/// Supported authentication credential types.
/// All credentials resolve to a DID — there is no identity outside the DID system.
#[derive(Clone, Serialize, Deserialize)]
pub enum Credential {
    /// Direct DID signature authentication (strongest).
    /// The actor signs a challenge with their DID key.
    DidSignature {
        actor_did: String,
        body_hash: Hash256,
        signature: Signature,
        timestamp: Timestamp,
    },
    /// API key authentication (convenience, DID-bound).
    /// The key is a random 256-bit token that maps to a DID in the key registry.
    ApiKey(Zeroizing<String>),
    /// Bearer token authentication (HTTP-friendly, DID-bound).
    /// A bearer token that maps to a DID in the session registry.
    BearerToken(Zeroizing<String>),
}

impl fmt::Debug for Credential {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::DidSignature {
                actor_did,
                body_hash,
                timestamp,
                ..
            } => f
                .debug_struct("DidSignature")
                .field("actor_did", actor_did)
                .field("body_hash", body_hash)
                .field("timestamp", timestamp)
                .field("signature", &"<redacted>")
                .finish(),
            Self::ApiKey(_) => f.debug_tuple("ApiKey").field(&"<redacted>").finish(),
            Self::BearerToken(_) => f.debug_tuple("BearerToken").field(&"<redacted>").finish(),
        }
    }
}

// ---------------------------------------------------------------------------
// API key registry
// ---------------------------------------------------------------------------

/// A registered API key bound to a DID.
#[derive(Clone, Serialize, Deserialize)]
pub struct ApiKeyRecord {
    /// BLAKE3 hash of the plaintext API key.
    pub key_hash: Hash256,
    /// The DID this key is bound to.
    pub did: Did,
    /// Human-readable label for this key.
    pub label: String,
    /// When this key was created (HLC timestamp).
    pub created_at: Timestamp,
    /// Optional expiration timestamp. `None` = never expires.
    pub expires_at: Option<Timestamp>,
    /// Whether this key has been revoked.
    pub revoked: bool,
}

impl fmt::Debug for ApiKeyRecord {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ApiKeyRecord")
            .field("key_hash", &"<redacted>")
            .field("did", &self.did)
            .field("label", &self.label)
            .field("created_at", &self.created_at)
            .field("expires_at", &self.expires_at)
            .field("revoked", &self.revoked)
            .finish()
    }
}

/// Caller-supplied metadata for API key creation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ApiKeyMetadata {
    pub created_at: Timestamp,
}

impl ApiKeyMetadata {
    /// Validate caller-supplied API key metadata.
    ///
    /// # Errors
    ///
    /// Returns `GatewayError::BadRequest` if `created_at` is `Timestamp::ZERO`.
    pub fn new(created_at: Timestamp) -> Result<Self> {
        if created_at == Timestamp::ZERO {
            return Err(GatewayError::BadRequest(
                "API key created_at must be caller-supplied and non-zero".into(),
            ));
        }
        Ok(Self { created_at })
    }
}

/// Registry of API keys mapped to DIDs.
/// Uses `BTreeMap` (not `HashMap`) for deterministic iteration.
#[derive(Debug, Clone, Default)]
pub struct ApiKeyRegistry {
    /// Maps `BLAKE3(api_key)` to `ApiKeyRecord`.
    /// Keys are stored hashed — the plaintext key is only shown once at creation.
    keys: BTreeMap<Hash256, ApiKeyRecord>,
}

impl ApiKeyRegistry {
    /// Create an empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a new API key for `did` with a human-readable `label`.
    ///
    /// Returns `(plaintext_key_hex, record)`.  The plaintext key is shown **once**
    /// at creation and never stored — only its BLAKE3 hash is persisted.
    ///
    /// # Errors
    ///
    /// Returns `GatewayError::Internal` if the OS entropy source fails.
    pub fn register(
        &mut self,
        did: Did,
        label: String,
        metadata: ApiKeyMetadata,
    ) -> Result<(Zeroizing<String>, ApiKeyRecord)> {
        self.register_with_entropy(did, label, metadata, |key_bytes| {
            getrandom::getrandom(key_bytes)
                .map_err(|error| GatewayError::Internal(format!("API key entropy failed: {error}")))
        })
    }

    fn register_with_entropy<F>(
        &mut self,
        did: Did,
        label: String,
        metadata: ApiKeyMetadata,
        fill_entropy: F,
    ) -> Result<(Zeroizing<String>, ApiKeyRecord)>
    where
        F: FnOnce(&mut [u8; 32]) -> Result<()>,
    {
        let mut key_bytes = Zeroizing::new([0u8; 32]);
        fill_entropy(&mut key_bytes)?;

        let plaintext_hex = Zeroizing::new(hex::encode(&key_bytes[..]));
        let key_hash = Hash256::digest(&key_bytes[..]);

        let record = ApiKeyRecord {
            key_hash,
            did,
            label,
            created_at: metadata.created_at,
            expires_at: None,
            revoked: false,
        };

        self.keys.insert(key_hash, record.clone());
        Ok((plaintext_hex, record))
    }

    /// Resolve a plaintext API key (hex-encoded) to its record.
    ///
    /// Returns `None` if the key is not found.
    #[must_use]
    pub fn resolve(&self, api_key: &str) -> Option<&ApiKeyRecord> {
        let key_bytes = Zeroizing::new(hex::decode(api_key).ok()?);
        let key_hash = Hash256::digest(&key_bytes[..]);
        let mut matched = None;
        for record in self.keys.values() {
            if constant_time_eq(key_hash.as_bytes(), record.key_hash.as_bytes()) {
                matched = Some(record);
            }
        }
        matched
    }

    /// Revoke a key by its hash.  Returns `true` if the key existed (and was
    /// marked revoked), `false` if the hash was not found.
    pub fn revoke(&mut self, key_hash: &Hash256) -> bool {
        if let Some(record) = self.keys.get_mut(key_hash) {
            record.revoked = true;
            true
        } else {
            false
        }
    }

    /// List all key records bound to `did`.
    #[must_use]
    pub fn keys_for_did(&self, did: &Did) -> Vec<&ApiKeyRecord> {
        self.keys.values().filter(|r| r.did == *did).collect()
    }
}

// ---------------------------------------------------------------------------
// authenticate() — DID-signature path
// ---------------------------------------------------------------------------

/// Authenticate a request by validating DID format, signature freshness,
/// and cryptographic Ed25519 signature against the registered DID document.
///
/// # Errors
///
/// - `AuthenticationFailed` if the DID format is invalid
/// - `AuthenticationFailed` if the signature is empty
/// - `AuthenticationFailed` if the timestamp is outside the freshness window
/// - `AuthenticationFailed` if the DID is not found in `registry`
/// - `AuthenticationFailed` if the DID has no active verification method
/// - `AuthenticationFailed` if signature verification fails
pub fn authenticate(
    request: &Request,
    registry: &dyn DidRegistry,
    metadata: AuthenticationMetadata,
) -> Result<AuthenticatedActor> {
    // 1. Validate DID format.
    let did = Did::new(&request.actor_did).map_err(|_| GatewayError::AuthenticationFailed {
        reason: "invalid DID".into(),
    })?;

    // 2. Reject empty / all-zero signatures (covers Signature::Empty and
    //    Signature::Ed25519([0u8; 64])).
    if request.signature.is_empty() {
        return Err(GatewayError::AuthenticationFailed {
            reason: "empty signature".into(),
        });
    }

    // 3. Timestamp freshness — guard against replay attacks.
    check_freshness(&request.timestamp, &metadata.observed_at)?;

    // 4. Resolve DID document from the registry.
    let doc = registry
        .resolve(&did)
        .ok_or_else(|| GatewayError::AuthenticationFailed {
            reason: "DID not registered".into(),
        })?;

    // 5. Find the first active verification method.
    let method = doc
        .verification_methods
        .iter()
        .find(|m| m.active)
        .ok_or_else(|| GatewayError::AuthenticationFailed {
            reason: "no active verification method for DID".into(),
        })?;

    // 6. Cryptographically verify the Ed25519 signature over the full
    //    authentication envelope consumed by downstream authorization.
    let signing_payload = request_signing_payload(request)?;
    verify_did_signature(doc, &method.id, &signing_payload, &request.signature).map_err(|e| {
        GatewayError::AuthenticationFailed {
            reason: format!("signature verification failed: {e}"),
        }
    })?;

    Ok(AuthenticatedActor {
        did,
        authenticated_at: metadata.observed_at,
    })
}

// ---------------------------------------------------------------------------
// resolve_credential() — unified entry point
// ---------------------------------------------------------------------------

/// Resolve any credential type to an authenticated actor.
///
/// This is the unified entry point — all downstream code sees only
/// [`AuthenticatedActor`].
///
/// # Errors
///
/// Returns `GatewayError::AuthenticationFailed` with a descriptive reason
/// when the credential is invalid, revoked, expired, or unknown.
pub fn resolve_credential(
    credential: &Credential,
    did_registry: &dyn DidRegistry,
    api_key_registry: &ApiKeyRegistry,
    metadata: AuthenticationMetadata,
) -> Result<AuthenticatedActor> {
    match credential {
        Credential::DidSignature {
            actor_did,
            body_hash,
            signature,
            timestamp,
        } => {
            let request = Request {
                actor_did: actor_did.clone(),
                action: String::new(),
                body_hash: *body_hash,
                signature: signature.clone(),
                timestamp: *timestamp,
            };
            authenticate(&request, did_registry, metadata)
        }

        Credential::ApiKey(key) => {
            resolve_token(key, did_registry, api_key_registry, "API key", metadata)
        }

        Credential::BearerToken(token) => resolve_token(
            token,
            did_registry,
            api_key_registry,
            "bearer token",
            metadata,
        ),
    }
}

/// Shared resolution logic for API key and bearer token credentials.
fn resolve_token(
    token: &str,
    did_registry: &dyn DidRegistry,
    registry: &ApiKeyRegistry,
    kind: &str,
    metadata: AuthenticationMetadata,
) -> Result<AuthenticatedActor> {
    let record = registry
        .resolve(token)
        .ok_or_else(|| GatewayError::AuthenticationFailed {
            reason: format!("unknown {kind}"),
        })?;

    if record.revoked {
        return Err(GatewayError::AuthenticationFailed {
            reason: format!("{kind} has been revoked"),
        });
    }

    if let Some(expires_at) = record.expires_at {
        if metadata.observed_at > expires_at {
            return Err(GatewayError::AuthenticationFailed {
                reason: format!("{kind} has expired"),
            });
        }
    }

    // The credential token may still be live while its bound DID has been
    // revoked. `DidRegistry::resolve` filters out revoked DID documents, so a
    // `None` here means the DID is unknown or revoked — fail closed before
    // constructing an authenticated actor for a defunct identity.
    if did_registry.resolve(&record.did).is_none() {
        return Err(GatewayError::AuthenticationFailed {
            reason: format!("{kind} bound to unregistered or revoked DID"),
        });
    }

    Ok(AuthenticatedActor {
        did: record.did.clone(),
        authenticated_at: metadata.observed_at,
    })
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Reject requests whose timestamp deviates from `observed_at` by more than
/// `FRESHNESS_WINDOW_MS`.
fn check_freshness(ts: &Timestamp, observed_at: &Timestamp) -> Result<()> {
    let now_ms = observed_at.physical_ms;
    let req_ms = ts.physical_ms;
    let skew_ms = now_ms.abs_diff(req_ms);
    if skew_ms > FRESHNESS_WINDOW_MS {
        return Err(GatewayError::AuthenticationFailed {
            reason: format!(
                "request timestamp outside freshness window: skew {skew_ms}ms (max {FRESHNESS_WINDOW_MS}ms)"
            ),
        });
    }
    Ok(())
}

fn constant_time_eq(left: &[u8], right: &[u8]) -> bool {
    if left.len() != right.len() {
        return false;
    }
    let mut diff = 0u8;
    for idx in 0..left.len() {
        diff |= left[idx] ^ right[idx];
    }
    diff == 0
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use exo_core::crypto::{generate_keypair, sign};
    use exo_identity::{
        did::{DidDocument, VerificationMethod},
        registry::{DidRegistry, LocalDidRegistry},
    };

    use super::*;

    fn req_ts() -> Timestamp {
        Timestamp::new(10_000, 0)
    }

    fn auth_metadata() -> AuthenticationMetadata {
        AuthenticationMetadata::new(Timestamp::new(10_000, 0)).unwrap()
    }

    fn api_key_metadata() -> ApiKeyMetadata {
        ApiKeyMetadata::new(Timestamp::new(1_000, 0)).unwrap()
    }

    /// Build an in-memory registry with a single DID `did:exo:alice` registered
    /// under a freshly generated Ed25519 key pair.  Returns the registry and the
    /// signing key so callers can produce valid signatures.
    fn registry_with_alice() -> (LocalDidRegistry, exo_core::SecretKey) {
        let did = Did::new("did:exo:alice").unwrap();
        let (pk, sk) = generate_keypair();
        let multibase = format!("z{}", bs58::encode(pk.as_bytes()).into_string());
        let doc = DidDocument {
            id: did.clone(),
            public_keys: vec![pk],
            authentication: vec![],
            verification_methods: vec![VerificationMethod {
                id: "did:exo:alice#key-1".into(),
                key_type: "Ed25519VerificationKey2020".into(),
                controller: did,
                public_key_multibase: multibase,
                version: 1,
                active: true,
                valid_from: 0,
                revoked_at: None,
            }],
            hybrid_verification_methods: vec![],
            service_endpoints: vec![],
            created: Timestamp::ZERO,
            updated: Timestamp::ZERO,
            revoked: false,
        };
        let mut reg = LocalDidRegistry::new();
        reg.register(doc).unwrap();
        (reg, sk)
    }

    /// Register a minimal active DID document for `did_str` into `reg` so a
    /// bound API/bearer credential resolves to a live DID.
    fn register_did(reg: &mut LocalDidRegistry, did_str: &str) {
        let did = Did::new(did_str).unwrap();
        let (pk, _sk) = generate_keypair();
        let multibase = format!("z{}", bs58::encode(pk.as_bytes()).into_string());
        let doc = DidDocument {
            id: did.clone(),
            public_keys: vec![pk],
            authentication: vec![],
            verification_methods: vec![VerificationMethod {
                id: format!("{did_str}#key-1"),
                key_type: "Ed25519VerificationKey2020".into(),
                controller: did,
                public_key_multibase: multibase,
                version: 1,
                active: true,
                valid_from: 0,
                revoked_at: None,
            }],
            hybrid_verification_methods: vec![],
            service_endpoints: vec![],
            created: Timestamp::ZERO,
            updated: Timestamp::ZERO,
            revoked: false,
        };
        reg.register(doc).unwrap();
    }

    struct StaticDidRegistry {
        did: Did,
        doc: DidDocument,
    }

    impl DidRegistry for StaticDidRegistry {
        fn register(
            &mut self,
            _doc: DidDocument,
        ) -> std::result::Result<(), exo_identity::error::IdentityError> {
            unreachable!("auth tests resolve only")
        }

        fn resolve(&self, did: &Did) -> Option<&DidDocument> {
            if did == &self.did {
                Some(&self.doc)
            } else {
                None
            }
        }

        fn revoke(
            &mut self,
            _did: &Did,
            _proof: &exo_identity::did::RevocationProof,
        ) -> std::result::Result<(), exo_identity::error::IdentityError> {
            unreachable!("auth tests resolve only")
        }

        fn rotate_key(
            &mut self,
            _did: &Did,
            _new_key: &exo_core::PublicKey,
            _proof: &Signature,
            _updated: Timestamp,
        ) -> std::result::Result<(), exo_identity::error::IdentityError> {
            unreachable!("auth tests resolve only")
        }
    }

    fn signed_request(mut request: Request, secret_key: &exo_core::SecretKey) -> Request {
        request.signature = sign(&request_signing_payload(&request).unwrap(), secret_key);
        request
    }

    // -----------------------------------------------------------------------
    // authenticate() tests
    // -----------------------------------------------------------------------

    #[test]
    fn auth_valid() {
        let (reg, sk) = registry_with_alice();
        let body_hash = Hash256::ZERO;
        let r = signed_request(
            Request {
                actor_did: "did:exo:alice".into(),
                action: "read".into(),
                body_hash,
                signature: Signature::Empty,
                timestamp: req_ts(),
            },
            &sk,
        );
        let a = authenticate(&r, &reg, auth_metadata()).unwrap();
        assert_eq!(a.did.as_str(), "did:exo:alice");
        assert_eq!(a.authenticated_at, auth_metadata().observed_at());
    }

    #[test]
    fn auth_rejects_action_changed_after_signing() {
        let (reg, sk) = registry_with_alice();
        let body_hash = Hash256::digest(b"same body, different action");
        let mut request = signed_request(
            Request {
                actor_did: "did:exo:alice".into(),
                action: "read".into(),
                body_hash,
                signature: Signature::Empty,
                timestamp: req_ts(),
            },
            &sk,
        );
        request.action = "submit_governance_vote".into();

        assert!(authenticate(&request, &reg, auth_metadata()).is_err());
    }

    #[test]
    fn auth_accepts_same_signed_request_with_independent_trusted_observation_inside_freshness() {
        let (reg, sk) = registry_with_alice();
        let body_hash = Hash256::digest(b"same body, gateway observed one millisecond later");
        let request = signed_request(
            Request {
                actor_did: "did:exo:alice".into(),
                action: "read".into(),
                body_hash,
                signature: Signature::Empty,
                timestamp: req_ts(),
            },
            &sk,
        );
        let later_trusted_metadata =
            AuthenticationMetadata::new(Timestamp::new(req_ts().physical_ms + 1, 0)).unwrap();

        let actor = authenticate(&request, &reg, later_trusted_metadata).unwrap();

        assert_eq!(
            actor.authenticated_at,
            Timestamp::new(req_ts().physical_ms + 1, 0)
        );
    }

    #[test]
    fn auth_rejects_replayed_request_against_trusted_observation_time() {
        let (reg, sk) = registry_with_alice();
        let request = signed_request(
            Request {
                actor_did: "did:exo:alice".into(),
                action: "read".into(),
                body_hash: Hash256::digest(b"old signed request"),
                signature: Signature::Empty,
                timestamp: req_ts(),
            },
            &sk,
        );
        let trusted_later = AuthenticationMetadata::new(Timestamp::new(
            req_ts().physical_ms + FRESHNESS_WINDOW_MS + 1,
            0,
        ))
        .unwrap();

        let error = authenticate(&request, &reg, trusted_later).unwrap_err();

        assert!(
            error.to_string().contains("freshness window"),
            "replayed request must fail against trusted gateway observation time: {error}"
        );
    }

    #[test]
    fn auth_rejects_timestamp_changed_after_signing() {
        let (reg, sk) = registry_with_alice();
        let body_hash = Hash256::digest(b"same body, different request timestamp");
        let mut request = signed_request(
            Request {
                actor_did: "did:exo:alice".into(),
                action: "read".into(),
                body_hash,
                signature: Signature::Empty,
                timestamp: req_ts(),
            },
            &sk,
        );
        request.timestamp = Timestamp::new(req_ts().physical_ms + 1, 0);

        assert!(authenticate(&request, &reg, auth_metadata()).is_err());
    }

    #[test]
    fn auth_rejects_body_hash_changed_after_signing() {
        let (reg, sk) = registry_with_alice();
        let mut request = signed_request(
            Request {
                actor_did: "did:exo:alice".into(),
                action: "read".into(),
                body_hash: Hash256::digest(b"original body"),
                signature: Signature::Empty,
                timestamp: req_ts(),
            },
            &sk,
        );
        request.body_hash = Hash256::digest(b"tampered body");

        assert!(authenticate(&request, &reg, auth_metadata()).is_err());
    }

    #[test]
    fn request_signing_payload_is_domain_separated_cbor() {
        #[derive(Deserialize)]
        struct DecodedPayload {
            domain: String,
            actor_did: String,
            action: String,
            body_hash: Hash256,
            request_timestamp_physical_ms: u64,
            request_timestamp_logical: u32,
        }

        let body_hash = Hash256::digest(b"canonical body hash");
        let request = Request {
            actor_did: "did:exo:alice".into(),
            action: "read".to_owned(),
            body_hash,
            signature: Signature::Empty,
            timestamp: req_ts(),
        };
        let payload = request_signing_payload(&request).unwrap();
        let decoded: DecodedPayload = ciborium::from_reader(payload.as_slice()).unwrap();

        assert_eq!(decoded.domain, GATEWAY_AUTH_SIGNING_DOMAIN);
        assert_eq!(decoded.actor_did, "did:exo:alice");
        assert_eq!(decoded.action, "read");
        assert_eq!(decoded.body_hash, body_hash);
        assert_eq!(decoded.request_timestamp_physical_ms, req_ts().physical_ms);
        assert_eq!(decoded.request_timestamp_logical, req_ts().logical);
    }

    #[test]
    fn auth_rejects_body_hash_only_signature_for_action_request() {
        let (reg, sk) = registry_with_alice();
        let body_hash = Hash256::digest(b"same body, different action");
        let signature = sign(body_hash.as_bytes(), &sk);
        let request = Request {
            actor_did: "did:exo:alice".into(),
            action: "submit_governance_vote".into(),
            body_hash,
            signature,
            timestamp: req_ts(),
        };

        assert!(authenticate(&request, &reg, auth_metadata()).is_err());
    }

    #[test]
    fn auth_rejects_active_method_not_bound_to_document_key() {
        let did = Did::new("did:exo:alice").unwrap();
        let (declared_pk, _) = generate_keypair();
        let (method_pk, method_sk) = generate_keypair();
        let method_multibase = format!("z{}", bs58::encode(method_pk.as_bytes()).into_string());
        let doc = DidDocument {
            id: did.clone(),
            public_keys: vec![declared_pk],
            authentication: vec![],
            verification_methods: vec![VerificationMethod {
                id: "did:exo:alice#key-1".into(),
                key_type: "Ed25519VerificationKey2020".into(),
                controller: did.clone(),
                public_key_multibase: method_multibase,
                version: 1,
                active: true,
                valid_from: 0,
                revoked_at: None,
            }],
            hybrid_verification_methods: vec![],
            service_endpoints: vec![],
            created: Timestamp::ZERO,
            updated: Timestamp::ZERO,
            revoked: false,
        };
        let reg = StaticDidRegistry {
            did: did.clone(),
            doc,
        };
        let request = signed_request(
            Request {
                actor_did: did.as_str().to_owned(),
                action: "read".into(),
                body_hash: Hash256::digest(b"body"),
                signature: Signature::Empty,
                timestamp: req_ts(),
            },
            &method_sk,
        );

        let err = authenticate(&request, &reg, auth_metadata()).unwrap_err();
        assert!(
            err.to_string().contains("not declared"),
            "auth must fail closed when a custom registry returns an unbound active method: {err}"
        );
    }

    #[test]
    fn auth_invalid_did() {
        let (reg, _) = registry_with_alice();
        let r = Request {
            actor_did: "bad".into(),
            action: "read".into(),
            body_hash: Hash256::ZERO,
            signature: Signature::from_bytes({
                let mut s = [0u8; 64];
                s[0] = 1;
                s
            }),
            timestamp: req_ts(),
        };
        assert!(authenticate(&r, &reg, auth_metadata()).is_err());
    }

    #[test]
    fn authentication_failure_messages_do_not_echo_request_dids() {
        let (reg, _) = registry_with_alice();
        let signature = Signature::from_bytes({
            let mut s = [0u8; 64];
            s[0] = 1;
            s
        });
        let invalid_raw_did = "not-a-did-private-identifier";
        let invalid_request = Request {
            actor_did: invalid_raw_did.into(),
            action: "read".into(),
            body_hash: Hash256::ZERO,
            signature: signature.clone(),
            timestamp: req_ts(),
        };
        let invalid_error = authenticate(&invalid_request, &reg, auth_metadata())
            .expect_err("invalid DID must be rejected")
            .to_string();
        assert!(
            !invalid_error.contains(invalid_raw_did),
            "authentication errors must not echo malformed DID input: {invalid_error}"
        );

        let unregistered_did = "did:exo:privacy-sensitive-subject";
        let unregistered_request = Request {
            actor_did: unregistered_did.into(),
            action: "read".into(),
            body_hash: Hash256::ZERO,
            signature,
            timestamp: req_ts(),
        };
        let unregistered_error = authenticate(&unregistered_request, &reg, auth_metadata())
            .expect_err("unknown DID must be rejected")
            .to_string();
        assert!(
            !unregistered_error.contains(unregistered_did),
            "authentication errors must not echo unknown DIDs: {unregistered_error}"
        );
    }

    #[test]
    fn auth_empty_sig() {
        let (reg, _) = registry_with_alice();
        let r = Request {
            actor_did: "did:exo:alice".into(),
            action: "read".into(),
            body_hash: Hash256::ZERO,
            signature: Signature::from_bytes([0u8; 64]),
            timestamp: req_ts(),
        };
        assert!(authenticate(&r, &reg, auth_metadata()).is_err());
    }

    #[test]
    fn auth_empty_sig_variant() {
        let (reg, _) = registry_with_alice();
        let r = Request {
            actor_did: "did:exo:alice".into(),
            action: "read".into(),
            body_hash: Hash256::ZERO,
            signature: Signature::Empty,
            timestamp: req_ts(),
        };
        assert!(authenticate(&r, &reg, auth_metadata()).is_err());
    }

    #[test]
    fn auth_wrong_signature_fails() {
        let (reg, _sk) = registry_with_alice();
        // Sign with a different key — verification must fail.
        let (_pk2, sk2) = generate_keypair();
        let body_hash = Hash256::ZERO;
        let bad_sig = sign(body_hash.as_bytes(), &sk2);
        let r = Request {
            actor_did: "did:exo:alice".into(),
            action: "read".into(),
            body_hash,
            signature: bad_sig,
            timestamp: req_ts(),
        };
        assert!(authenticate(&r, &reg, auth_metadata()).is_err());
    }

    #[test]
    fn auth_did_not_registered_fails() {
        let (reg, _) = registry_with_alice();
        // bob is not in the registry.
        let (_, sk_bob) = generate_keypair();
        let body_hash = Hash256::ZERO;
        let sig = sign(body_hash.as_bytes(), &sk_bob);
        let r = Request {
            actor_did: "did:exo:bob".into(),
            action: "read".into(),
            body_hash,
            signature: sig,
            timestamp: req_ts(),
        };
        assert!(authenticate(&r, &reg, auth_metadata()).is_err());
    }

    #[test]
    fn request_serde() {
        let r = Request {
            actor_did: "did:exo:a".into(),
            action: "r".into(),
            body_hash: Hash256::ZERO,
            signature: Signature::from_bytes({
                let mut s = [0u8; 64];
                s[0] = 1;
                s
            }),
            timestamp: req_ts(),
        };
        let j = serde_json::to_string(&r).unwrap();
        assert!(!j.is_empty());
    }

    #[test]
    fn freshness_check_passes_recent() {
        let observed_at = Timestamp::new(10_000, 0);
        assert!(check_freshness(&observed_at, &observed_at).is_ok());
    }

    #[test]
    fn freshness_check_rejects_stale() {
        let stale = Timestamp::new(1, 0);
        let observed_at = Timestamp::new(FRESHNESS_WINDOW_MS + 2, 0);
        assert!(check_freshness(&stale, &observed_at).is_err());
    }

    #[test]
    fn authentication_metadata_rejects_zero_observed_at() {
        let metadata = AuthenticationMetadata::new(Timestamp::ZERO);

        assert!(
            matches!(metadata, Err(GatewayError::BadRequest(reason)) if reason.contains("observed_at"))
        );
    }

    #[test]
    fn authenticate_rejects_stale_against_trusted_metadata() {
        let (reg, sk) = registry_with_alice();
        let body_hash = Hash256::ZERO;
        let signature = sign(body_hash.as_bytes(), &sk);
        let r = Request {
            actor_did: "did:exo:alice".into(),
            action: "read".into(),
            body_hash,
            signature,
            timestamp: Timestamp::new(1, 0),
        };
        let metadata =
            AuthenticationMetadata::new(Timestamp::new(FRESHNESS_WINDOW_MS + 2, 0)).unwrap();

        let err = authenticate(&r, &reg, metadata).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("freshness window"),
            "expected freshness-window error in: {msg}"
        );
    }

    #[test]
    fn auth_production_does_not_fabricate_auth_timestamps() {
        let source = include_str!("auth.rs");
        let production = source
            .split("#[cfg(test)]")
            .next()
            .expect("production section");

        let forbidden_timestamp = ["Timestamp", "::now_utc"].concat();
        assert!(
            !production.contains(&forbidden_timestamp),
            "gateway auth must use trusted gateway authentication timestamps"
        );
        let forbidden_system_time = ["SystemTime", "::now"].concat();
        assert!(
            !production.contains(&forbidden_system_time),
            "gateway auth must not read wall-clock time"
        );
        assert!(
            !production.contains("pub observed_at"),
            "authentication observation time must not be a public caller-controlled field"
        );
        assert!(
            !production.contains("observed_at_physical_ms"),
            "DID request signatures must not bind caller-supplied observation time"
        );
    }

    #[test]
    fn auth_production_does_not_verify_raw_body_hash_signatures() {
        let source = include_str!("auth.rs");
        let production = source
            .split("#[cfg(test)]")
            .next()
            .expect("production section");

        assert!(
            !production.contains("request.body_hash.as_bytes()"),
            "gateway auth must bind DID signatures to the canonical request envelope"
        );
        assert!(
            production.contains("request_signing_payload(request)"),
            "gateway auth must route signature verification through the canonical payload helper"
        );
    }

    #[test]
    fn auth_production_does_not_format_request_dids_into_errors() {
        let source = include_str!("auth.rs");
        let production = source
            .split("#[cfg(test)]")
            .next()
            .expect("production section");

        for pattern in [
            r#"format!("invalid DID: {}", request.actor_did)"#,
            r#"format!("DID not registered: {}", request.actor_did)"#,
            r#"format!("no active verification method for DID: {}", request.actor_did)"#,
        ] {
            assert!(
                !production.contains(pattern),
                "authentication diagnostics must not format raw request DIDs: {pattern}"
            );
        }
    }

    // -----------------------------------------------------------------------
    // Credential / resolve_credential tests
    // -----------------------------------------------------------------------

    #[test]
    fn credential_did_signature_valid() {
        let (reg, sk) = registry_with_alice();
        let body_hash = Hash256::ZERO;
        let request = signed_request(
            Request {
                actor_did: "did:exo:alice".into(),
                action: String::new(),
                body_hash,
                signature: Signature::Empty,
                timestamp: req_ts(),
            },
            &sk,
        );
        let cred = Credential::DidSignature {
            actor_did: "did:exo:alice".into(),
            body_hash,
            signature: request.signature,
            timestamp: req_ts(),
        };
        let api_reg = ApiKeyRegistry::new();
        let actor = resolve_credential(&cred, &reg, &api_reg, auth_metadata()).unwrap();
        assert_eq!(actor.did.as_str(), "did:exo:alice");
    }

    #[test]
    fn credential_did_signature_invalid() {
        let (reg, _sk) = registry_with_alice();
        let (_pk2, sk2) = generate_keypair();
        let body_hash = Hash256::ZERO;
        let bad_sig = sign(body_hash.as_bytes(), &sk2);
        let cred = Credential::DidSignature {
            actor_did: "did:exo:alice".into(),
            body_hash,
            signature: bad_sig,
            timestamp: req_ts(),
        };
        let api_reg = ApiKeyRegistry::new();
        assert!(resolve_credential(&cred, &reg, &api_reg, auth_metadata()).is_err());
    }

    #[test]
    fn credential_api_key_valid() {
        let mut did_reg = LocalDidRegistry::new();
        register_did(&mut did_reg, "did:exo:alice");
        let mut api_reg = ApiKeyRegistry::new();
        let did = Did::new("did:exo:alice").unwrap();
        let (plaintext, _record) = api_reg
            .register(did, "test key".into(), api_key_metadata())
            .expect("api key registration");

        let cred = Credential::ApiKey(plaintext);
        let actor = resolve_credential(&cred, &did_reg, &api_reg, auth_metadata()).unwrap();
        assert_eq!(actor.did.as_str(), "did:exo:alice");
    }

    #[test]
    fn credential_api_key_with_revoked_did_fails() {
        // `DidRegistry::resolve` returns `None` both for unknown DIDs and for
        // revoked ones (`LocalDidRegistry::resolve` filters revoked documents),
        // so a registry that does not resolve the key's bound DID models the
        // revoked-DID case. Here the registry only knows a different DID.
        let (reg, _sk) = registry_with_alice();
        let mut api_reg = ApiKeyRegistry::new();
        let revoked_did = Did::new("did:exo:revoked-subject").unwrap();
        let (plaintext, _record) = api_reg
            .register(revoked_did, "test key".into(), api_key_metadata())
            .expect("api key registration");

        // The API key itself is live (not revoked, not expired), but its bound
        // DID does not resolve — authentication must fail closed.
        let cred = Credential::ApiKey(plaintext);
        let err = resolve_credential(&cred, &reg, &api_reg, auth_metadata()).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("unregistered or revoked DID"),
            "expected revoked-DID rejection in: {msg}"
        );
    }

    #[test]
    fn api_key_registry_resolve_does_not_use_tree_lookup_for_secret_hash() {
        let source = include_str!("auth.rs");
        let resolve_start = source
            .find("pub fn resolve(&self, api_key: &str)")
            .expect("resolve source exists");
        let resolve_end = source[resolve_start..]
            .find("/// Revoke a key")
            .expect("revoke marker exists");
        let resolve_body = &source[resolve_start..resolve_start + resolve_end];
        let forbidden = [".keys", ".get(&key_hash)"].concat();
        assert!(
            !resolve_body.contains(&forbidden),
            "API key resolution must not branch through a tree lookup on secret-derived hashes"
        );
        assert!(
            resolve_body.contains("constant_time_eq"),
            "API key resolution must compare stored hashes in constant time"
        );
    }

    #[test]
    fn credential_api_key_revoked() {
        let did_reg = LocalDidRegistry::new();
        let mut api_reg = ApiKeyRegistry::new();
        let did = Did::new("did:exo:alice").unwrap();
        let (plaintext, record) = api_reg
            .register(did, "test key".into(), api_key_metadata())
            .expect("api key registration");
        api_reg.revoke(&record.key_hash);

        let cred = Credential::ApiKey(plaintext);
        let err = resolve_credential(&cred, &did_reg, &api_reg, auth_metadata()).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("revoked"), "expected 'revoked' in: {msg}");
    }

    #[test]
    fn credential_api_key_expired() {
        let did_reg = LocalDidRegistry::new();
        let mut api_reg = ApiKeyRegistry::new();
        let did = Did::new("did:exo:alice").unwrap();
        let (plaintext, record) = api_reg
            .register(did, "test key".into(), api_key_metadata())
            .expect("api key registration");

        // Manually set expiration to the past.
        let key_hash = record.key_hash;
        api_reg.keys.get_mut(&key_hash).unwrap().expires_at = Some(Timestamp::new(1, 0));

        let cred = Credential::ApiKey(plaintext);
        let err = resolve_credential(&cred, &did_reg, &api_reg, auth_metadata()).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("expired"), "expected 'expired' in: {msg}");
    }

    #[test]
    fn credential_api_key_unknown() {
        let did_reg = LocalDidRegistry::new();
        let api_reg = ApiKeyRegistry::new();
        let cred = Credential::ApiKey("deadbeef".repeat(8).into());
        let err = resolve_credential(&cred, &did_reg, &api_reg, auth_metadata()).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("unknown"), "expected 'unknown' in: {msg}");
    }

    #[test]
    fn credential_bearer_valid() {
        let mut did_reg = LocalDidRegistry::new();
        register_did(&mut did_reg, "did:exo:bob");
        let mut api_reg = ApiKeyRegistry::new();
        let did = Did::new("did:exo:bob").unwrap();
        let (plaintext, _record) = api_reg
            .register(did, "bearer session".into(), api_key_metadata())
            .expect("api key registration");

        let cred = Credential::BearerToken(plaintext);
        let actor = resolve_credential(&cred, &did_reg, &api_reg, auth_metadata()).unwrap();
        assert_eq!(actor.did.as_str(), "did:exo:bob");
    }

    #[test]
    fn api_key_registry_register() {
        let mut reg = ApiKeyRegistry::new();
        let did = Did::new("did:exo:carol").unwrap();
        let (plaintext, record) = reg
            .register(did.clone(), "my key".into(), api_key_metadata())
            .expect("api key registration");

        // Plaintext is 64 hex chars (32 bytes).
        assert_eq!(plaintext.len(), 64);
        assert!(hex::decode(plaintext.as_str()).is_ok());

        // Record fields are set correctly.
        assert_eq!(record.did, did);
        assert_eq!(record.label, "my key");
        assert!(!record.revoked);
        assert!(record.expires_at.is_none());

        // The registry contains exactly one entry.
        assert_eq!(reg.keys.len(), 1);
    }

    #[test]
    fn api_key_registry_revoke() {
        let mut reg = ApiKeyRegistry::new();
        let did = Did::new("did:exo:carol").unwrap();
        let (_plaintext, record) = reg
            .register(did, "my key".into(), api_key_metadata())
            .expect("api key registration");

        assert!(reg.revoke(&record.key_hash));
        assert!(reg.keys.get(&record.key_hash).unwrap().revoked);

        // Revoking a non-existent hash returns false.
        assert!(!reg.revoke(&Hash256::ZERO));
    }

    #[test]
    fn api_key_registry_keys_for_did() {
        let mut reg = ApiKeyRegistry::new();
        let alice = Did::new("did:exo:alice").unwrap();
        let bob = Did::new("did:exo:bob").unwrap();

        reg.register(alice.clone(), "alice-1".into(), api_key_metadata())
            .expect("api key registration");
        reg.register(alice.clone(), "alice-2".into(), api_key_metadata())
            .expect("api key registration");
        reg.register(bob.clone(), "bob-1".into(), api_key_metadata())
            .expect("api key registration");

        let alice_keys = reg.keys_for_did(&alice);
        assert_eq!(alice_keys.len(), 2);
        assert!(alice_keys.iter().all(|r| r.did == alice));

        let bob_keys = reg.keys_for_did(&bob);
        assert_eq!(bob_keys.len(), 1);
        assert_eq!(bob_keys[0].did, bob);
    }

    #[test]
    fn api_key_plaintext_shown_once() {
        let mut reg = ApiKeyRegistry::new();
        let did = Did::new("did:exo:alice").unwrap();
        let (plaintext, record) = reg
            .register(did, "test".into(), api_key_metadata())
            .expect("api key registration");

        // The plaintext key, when hashed with BLAKE3, must equal the stored key_hash.
        let key_bytes = hex::decode(plaintext.as_str()).unwrap();
        let computed_hash = Hash256::digest(&key_bytes);
        assert_eq!(computed_hash, record.key_hash);

        // Resolve round-trips through the same hash.
        let resolved = reg.resolve(plaintext.as_str()).unwrap();
        assert_eq!(resolved.key_hash, record.key_hash);
    }

    #[test]
    fn api_key_metadata_rejects_zero_created_at() {
        let metadata = ApiKeyMetadata::new(Timestamp::ZERO);

        assert!(
            matches!(metadata, Err(GatewayError::BadRequest(reason)) if reason.contains("created_at"))
        );
    }

    #[test]
    fn api_key_registry_register_propagates_entropy_failure_without_mutation() {
        let mut reg = ApiKeyRegistry::new();
        let did = Did::new("did:exo:alice").unwrap();
        let err = reg
            .register_with_entropy(did.clone(), "test key".into(), api_key_metadata(), |_| {
                Err(GatewayError::Internal("entropy unavailable".into()))
            })
            .expect_err("entropy failure must propagate");

        assert!(matches!(err, GatewayError::Internal(reason) if reason.contains("entropy")));
        assert!(
            reg.keys_for_did(&did).is_empty(),
            "failed key generation must not insert a partial API key record"
        );
    }

    #[test]
    fn resolve_credential_uses_trusted_authentication_metadata() {
        let mut did_reg = LocalDidRegistry::new();
        register_did(&mut did_reg, "did:exo:alice");
        let mut api_reg = ApiKeyRegistry::new();
        let did = Did::new("did:exo:alice").unwrap();
        let key_metadata = ApiKeyMetadata::new(Timestamp::new(1_000, 0)).unwrap();
        let (plaintext, record) = api_reg
            .register(did, "test key".into(), key_metadata)
            .expect("api key registration");

        assert_eq!(record.created_at, Timestamp::new(1_000, 0));

        let auth_metadata = AuthenticationMetadata::new(Timestamp::new(2_000, 0)).unwrap();
        let cred = Credential::ApiKey(plaintext);
        let actor = resolve_credential(&cred, &did_reg, &api_reg, auth_metadata).unwrap();

        assert_eq!(actor.authenticated_at, Timestamp::new(2_000, 0));
    }

    #[test]
    fn credential_debug_redacts_token_material() {
        let api_key = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
        let bearer = "bearer-token-that-must-not-appear-in-debug";

        let api_debug = format!("{:?}", Credential::ApiKey(api_key.to_owned().into()));
        let bearer_debug = format!("{:?}", Credential::BearerToken(bearer.to_owned().into()));

        assert!(!api_debug.contains(api_key));
        assert!(!bearer_debug.contains(bearer));
        assert!(api_debug.contains("<redacted>"));
        assert!(bearer_debug.contains("<redacted>"));
    }

    #[test]
    fn credential_secret_material_uses_zeroizing_storage() {
        let source = include_str!("auth.rs");
        let production = source
            .split("#[cfg(test)]")
            .next()
            .expect("production section");

        assert!(production.contains("use zeroize::Zeroizing;"));
        assert!(production.contains("ApiKey(Zeroizing<String>)"));
        assert!(production.contains("BearerToken(Zeroizing<String>)"));
        assert!(production.contains(") -> Result<(Zeroizing<String>, ApiKeyRecord)>"));
        assert!(production.contains("let mut key_bytes = Zeroizing::new([0u8; 32]);"));
        assert!(production.contains("let key_bytes = Zeroizing::new(hex::decode(api_key).ok()?);"));
    }

    #[test]
    fn api_key_registry_register_does_not_panic_on_entropy_failure() {
        let source = include_str!("auth.rs");
        let production = source
            .split("#[cfg(test)]")
            .next()
            .expect("production section");

        assert!(!production.contains("expect(\"OS entropy source unavailable\")"));
        assert!(production.contains(") -> Result<(Zeroizing<String>, ApiKeyRecord)>"));
    }
}