cpex-hosts-python 0.3.0

CPEX host — runs Python plugins out-of-process in isolated virtualenvs.
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
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
// Location: ./crates/cpex-hosts-python/src/credentials.rs
// Copyright 2026
// SPDX-License-Identifier: Apache-2.0
// Authors: Ted Habeck
//
// Capability-gated credential wire DTO.
//
// # Why this exists
//
// `RawInboundToken.token` and `RawDelegatedToken.token` are `#[serde(skip)]`,
// so serializing an `Extensions` yields no token bytes — which means an
// out-of-process identity resolver or token delegator cannot do its job over
// that channel.
//
// This module is the narrow, documented exception `praxis-policy-core`'s
// `RawCredentialsExtension` points at: a dedicated DTO
// carries the token as a plain string, built only on the capability-gated
// dispatch path for the two hooks whose Python payload models a raw token at
// all. The production types keep their serde guard and are never serialized;
// the FFI, Python-bindings, and audit paths are untouched. The new leak surface
// is one constructor and one serialize site, which is the point.
//
// The DTO is built by reading the in-memory `Zeroizing` token field *directly*.
// A serialize-then-reparse would yield an empty token, because the serde guard
// strips the bytes on the way out — the guard is doing its job, so the only way
// to read the value is to read the field.
//
// # Fail closed
//
// Two rules, both load-bearing:
//
//   1. No declared capability → no DTO, no token material. Not an error; the
//      plugin simply never sees credentials.
//   2. Declared capability that cannot be honored → error, not a silent
//      no-token send. A plugin that asked for a token and got none would
//      otherwise validate an empty bearer, or fall through to a code path that
//      treats "no credential" as "no authentication required".
//
// # Residual exposure
//
// The capability gate controls *which* plugin receives a token. It does not
// constrain what happens next: once the plaintext is resident in the worker
// process, every transitively-installed dependency in that venv can read it.
// That is a materially larger and less audited trust boundary than the
// in-process host, and neither this gate nor the transport can close it. See
// the `worker` module for the transport side.

use std::collections::{HashMap, HashSet};

use praxis_policy_core::delegation::DelegationPayload;
use praxis_policy_core::extensions::Extensions;
use praxis_policy_core::extensions::raw_credentials::{
    DelegationKey, DelegationMode, RawDelegatedToken, RawInboundToken, TokenKind, TokenRole,
};
use praxis_policy_core::hooks::payload::PluginPayload;
use praxis_policy_core::identity::{IdentityPayload, TokenSource};
use serde::Serialize;
use serde_json::Value;

use crate::PayloadKind;
use crate::conversion::payload_kind_for_hook;
use crate::error::HostError;

/// Task field the DTO rides on. Contract with `worker.py`'s
/// `CREDENTIAL_FIELD`; both sides must agree verbatim.
pub const CREDENTIAL_FIELD: &str = "credential";

/// Capability a plugin declares to receive the inbound credential.
pub const CAP_READ_INBOUND: &str = "read_inbound_credentials";

/// Capability a plugin declares to receive a delegated token.
pub const CAP_READ_DELEGATED: &str = "read_delegated_tokens";

/// Placeholder printed instead of token bytes in `Debug`.
const REDACTED: &str = "<redacted>";

/// The `credential` object attached to a task.
///
/// Exactly one sub-object is populated, chosen by hook. `Debug` is
/// hand-written so neither ends up in a log line or panic message.
#[derive(Clone, Default, Serialize)]
pub struct CredentialDto {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inbound: Option<InboundCredential>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub delegated: Option<DelegatedCredential>,
}

impl std::fmt::Debug for CredentialDto {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Which sub-object is present is safe and useful; its contents are not.
        f.debug_struct("CredentialDto")
            .field("inbound", &self.inbound.as_ref().map(|_| REDACTED))
            .field("delegated", &self.delegated.as_ref().map(|_| REDACTED))
            .finish()
    }
}

/// `credential.inbound`: built from `RawInboundToken`, for `identity.resolve`.
///
/// The worker maps these onto `IdentityPayload`: `token` → `raw_token`, `kind`
/// → `source`, `headers` → `headers` (with the plaintext scrubbed out of the
/// values, since `IdentityPayload.headers` does not redact on serialization).
#[derive(Clone, Serialize)]
pub struct InboundCredential {
    /// The plaintext, read straight from the in-memory `Zeroizing` field.
    pub token: String,

    /// Header the credential arrived in.
    pub source_header: String,

    /// Wire-format family — `jwt`, `opaque`, `spiffe_jwt`, `ucan`, `txn_token`.
    pub kind: String,

    /// Headers to forward. Synthesized as `{source_header: token}` when the
    /// extension carries none, so a header-driven extractor still learns which
    /// header carried the credential.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<HashMap<String, String>>,
}

impl std::fmt::Debug for InboundCredential {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InboundCredential")
            .field("token", &REDACTED)
            .field("source_header", &self.source_header)
            .field("kind", &self.kind)
            // Values can embed the token ("Bearer <token>"), so names only.
            .field(
                "header_names",
                &self.headers.as_ref().map(|h| h.keys().collect::<Vec<_>>()),
            )
            .finish()
    }
}

/// `credential.delegated`: built from `RawDelegatedToken`, for
/// `token.delegate`.
///
/// The worker maps `token` → `DelegationPayload.bearer_token`; the rest is
/// audit and validation context.
#[derive(Clone, Serialize)]
pub struct DelegatedCredential {
    /// The plaintext, read straight from the in-memory `Zeroizing` field.
    pub token: String,

    /// Where the consumer should attach the token upstream.
    pub outbound_header: String,

    /// Audience the token was minted for.
    pub audience: String,

    /// Effective scopes on the minted token.
    pub scopes: Vec<String>,
}

impl std::fmt::Debug for DelegatedCredential {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DelegatedCredential")
            .field("token", &REDACTED)
            .field("outbound_header", &self.outbound_header)
            .field("audience", &self.audience)
            .field("scopes", &self.scopes)
            .finish()
    }
}

/// The wire name for a `TokenKind`.
///
/// Matches the `snake_case` serde rename on the enum, which is what
/// `worker.py`'s `_BEARER_TOKEN_KINDS` matches against. Written out rather
/// than round-tripped through serde so the mapping is reviewable next to the
/// contract it implements.
fn token_kind_wire_name(kind: &TokenKind) -> &'static str {
    match kind {
        TokenKind::Jwt => "jwt",
        TokenKind::Opaque => "opaque",
        TokenKind::SpiffeJwt => "spiffe_jwt",
        TokenKind::Ucan => "ucan",
        TokenKind::TxnToken => "txn_token",
        // `TokenKind` is `#[non_exhaustive]`, so a kind added upstream lands
        // here. "opaque" is the safe default: the worker maps unknown kinds to
        // `source: "custom"`, which makes a validator inspect the headers
        // itself rather than trust a source it does not recognize.
        _ => "opaque",
    }
}

/// Attach the `credential` object to a task, when the hook and the plugin's
/// declared capabilities both call for it.
///
/// A no-op for every hook other than `identity.resolve` and `token.delegate`,
/// and for any plugin that declared neither capability.
pub fn attach_credential(
    task: &mut Value,
    hook_name: &str,
    extensions: &Extensions,
    capabilities: &HashSet<String>,
) -> Result<(), HostError> {
    let kind = payload_kind_for_hook(hook_name);

    let dto = match kind {
        PayloadKind::IdentityResolve => {
            if !capabilities.contains(CAP_READ_INBOUND) {
                return Ok(());
            }
            CredentialDto {
                inbound: Some(build_inbound(extensions, hook_name)?),
                delegated: None,
            }
        },
        PayloadKind::TokenDelegate => {
            if !capabilities.contains(CAP_READ_DELEGATED) {
                return Ok(());
            }
            // The audience the hook was actually invoked for. Read from the
            // already-serialized payload, which is the only place the host
            // learns it — `DelegationPayload.target_audience` names the upstream
            // this delegation is for, and a token minted for a *different*
            // audience is the wrong credential to hand over.
            let requested_audience = requested_audience(task);
            CredentialDto {
                inbound: None,
                delegated: Some(build_delegated(
                    extensions,
                    hook_name,
                    requested_audience.as_deref(),
                )?),
            }
        },
        // No other hook has a payload field to receive a token.
        _ => return Ok(()),
    };

    insert_dto(task, &dto)
}

/// Attach the `credential` object for this invocation's payload.
///
/// The entry point the adapter uses. PPE's own payloads carry the credential
/// themselves: `IdentityPayload` holds the inbound token (in `raw_token`, or in
/// its source header when a host deserialized it), and `DelegationPayload`
/// holds the caller's bearer token. For those the token is read from the
/// payload, because it is the credential the hook is about; an extensions
/// token could belong to a different principal. Any other payload goes
/// through [`attach_credential`] and the extensions view.
///
/// The gate is the same either way: no declared capability means no DTO, and
/// a declared capability with no usable token is an error.
pub fn attach_credential_for_payload(
    task: &mut Value,
    hook_name: &str,
    payload: &dyn PluginPayload,
    extensions: &Extensions,
    capabilities: &HashSet<String>,
) -> Result<(), HostError> {
    let any = payload.as_any();
    let dto = match payload_kind_for_hook(hook_name) {
        PayloadKind::IdentityResolve => match any.downcast_ref::<IdentityPayload>() {
            Some(identity) if capabilities.contains(CAP_READ_INBOUND) => CredentialDto {
                inbound: Some(inbound_from_identity(identity, hook_name)?),
                delegated: None,
            },
            Some(_) => return Ok(()),
            None => return attach_credential(task, hook_name, extensions, capabilities),
        },
        // The bearer token on a PPE delegation payload is the caller's inbound
        // credential, sourced from the inbound tokens PPE shows only to a
        // plugin holding `read_inbound_credentials` (its own OAuth delegator
        // declares exactly that). So that is the capability that gates it
        // here too, rather than `read_delegated_tokens`, which names tokens
        // already minted for an upstream.
        PayloadKind::TokenDelegate => match any.downcast_ref::<DelegationPayload>() {
            Some(delegation) if capabilities.contains(CAP_READ_INBOUND) => CredentialDto {
                inbound: None,
                delegated: Some(delegated_from_payload(delegation, hook_name)?),
            },
            Some(_) => return Ok(()),
            None => return attach_credential(task, hook_name, extensions, capabilities),
        },
        _ => return attach_credential(task, hook_name, extensions, capabilities),
    };
    insert_dto(task, &dto)
}

/// `credential.inbound` from a PPE identity payload.
///
/// The header map travels whole, credential headers and all: this is the
/// gated channel, and the worker scrubs the plaintext out of every value
/// before the plugin sees it. The public payload JSON carries no raw header
/// values by default (`credential_payloads::public_headers`).
fn inbound_from_identity(
    identity: &IdentityPayload,
    hook_name: &str,
) -> Result<InboundCredential, HostError> {
    let token = crate::credential_payloads::inbound_token(identity).ok_or_else(|| {
        HostError::Credential {
            message: format!(
                "plugin declared '{CAP_READ_INBOUND}' for hook '{hook_name}' but the identity \
                 payload carries no credential, in `raw_token` or its source header. Refusing \
                 to dispatch without the token it asked for"
            ),
        }
    })?;
    let source_header = crate::credential_payloads::credential_header_name(identity);
    let mut headers = identity.headers().clone();
    if !headers
        .keys()
        .any(|name| name.eq_ignore_ascii_case(&source_header))
    {
        headers.insert(source_header.clone(), token.clone());
    }
    Ok(InboundCredential {
        token,
        source_header,
        kind: token_source_kind(identity.source()).to_string(),
        headers: Some(headers),
    })
}

/// The `kind` wire name for a PPE token source.
///
/// The worker reads `kind` only to fill `source` when the payload left it at
/// the default, and the payload already carries PPE's source, so this only
/// has to land in the right family.
fn token_source_kind(source: &TokenSource) -> &'static str {
    match source {
        TokenSource::SpiffeJwtSvid => "spiffe_jwt",
        _ => "opaque",
    }
}

/// `credential.delegated` from a PPE delegation payload: the caller's bearer
/// token, for the worker to fold onto `DelegationPayload.bearer_token`. The
/// worker reads the delegation hook's token from this sub-object whichever
/// capability gated it.
fn delegated_from_payload(
    delegation: &DelegationPayload,
    hook_name: &str,
) -> Result<DelegatedCredential, HostError> {
    let token = delegation.bearer_token();
    if token.trim().is_empty() {
        return Err(HostError::Credential {
            message: format!(
                "plugin declared '{CAP_READ_INBOUND}' for hook '{hook_name}' but the delegation \
                 payload carries no bearer token. Refusing to dispatch without the token it \
                 asked for"
            ),
        });
    }
    Ok(DelegatedCredential {
        token: token.to_string(),
        outbound_header: "Authorization".into(),
        audience: delegation.target_audience().unwrap_or_default().to_string(),
        scopes: delegation.required_permissions().to_vec(),
    })
}

fn insert_dto(task: &mut Value, dto: &CredentialDto) -> Result<(), HostError> {
    let object = task.as_object_mut().ok_or_else(|| HostError::Protocol {
        message: "task must be a JSON object to carry a credential".into(),
    })?;

    let serialized = serde_json::to_value(dto).map_err(|e| HostError::Credential {
        // The error names the failure, never the value.
        message: format!("could not serialize the credential DTO: {e}"),
    })?;
    object.insert(CREDENTIAL_FIELD.to_string(), serialized);

    Ok(())
}

/// Build `credential.inbound` from the filtered extensions view.
///
/// The plugin declared `read_inbound_credentials`, so a missing or empty token
/// is a fail-closed error rather than an omitted field: sending no token to a
/// plugin that asked for one invites it to treat the request as unauthenticated.
fn build_inbound(extensions: &Extensions, hook_name: &str) -> Result<InboundCredential, HostError> {
    let raw = extensions
        .raw_credentials
        .as_ref()
        .ok_or_else(|| HostError::Credential {
            message: format!(
                "plugin declared '{CAP_READ_INBOUND}' for hook '{hook_name}' but the request \
                 carries no raw-credentials extension — refusing to dispatch without the token \
                 it asked for"
            ),
        })?;

    // Prefer the user token, then the client token, then a workload JWT-SVID.
    // Ordering matters: an identity resolver wants the subject's credential,
    // and falling straight to the client token would resolve the gateway's own
    // identity as if it were the user's.
    let token = [
        TokenRole::User,
        TokenRole::Client,
        TokenRole::CallerWorkload,
    ]
    .iter()
    .find_map(|role| raw.inbound_tokens.get(role))
    .or_else(|| raw.inbound_tokens.values().next())
    .ok_or_else(|| HostError::Credential {
        message: format!(
            "plugin declared '{CAP_READ_INBOUND}' for hook '{hook_name}' but no inbound token \
                 is present — refusing to dispatch without it"
        ),
    })?;

    inbound_from_token(token, hook_name)
}

/// Convert one `RawInboundToken` into its wire form.
fn inbound_from_token(
    token: &RawInboundToken,
    hook_name: &str,
) -> Result<InboundCredential, HostError> {
    // Reading `*token.token` is the whole point: `serde` would give back an
    // empty string here, because the field is `#[serde(skip)]`.
    let plaintext = token.token.as_str();

    // Whitespace-only is rejected as well as empty: "Authorization: Bearer   "
    // is not meaningfully different from an empty bearer downstream, and
    // `worker.py` rejects it on its side too.
    if plaintext.trim().is_empty() {
        return Err(HostError::Credential {
            message: format!(
                "the inbound token for hook '{hook_name}' is empty — refusing to send an empty \
                 credential (an empty bearer authenticates nowhere, and a plugin may read it as \
                 'no authentication required')"
            ),
        });
    }

    Ok(InboundCredential {
        token: plaintext.to_string(),
        source_header: token.source_header.clone(),
        kind: token_kind_wire_name(&token.kind).to_string(),
        // Synthesized so a header-driven extractor learns which header carried
        // the credential. The worker scrubs the plaintext back out of these
        // values before a plugin can echo them onto a serialized payload.
        headers: Some(HashMap::from([(
            token.source_header.clone(),
            plaintext.to_string(),
        )])),
    })
}

/// The audience the `token.delegate` hook was invoked for, if the payload names
/// one.
///
/// `DelegationPayload.target_audience` is optional, so a `None` here means the
/// caller did not scope the delegation and any audience is acceptable.
fn requested_audience(task: &Value) -> Option<String> {
    task.get("payload")?
        .get("target_audience")?
        .as_str()
        .map(str::to_string)
}

/// Build `credential.delegated` from the filtered extensions view.
///
/// # Selection
///
/// `delegated_tokens` is a `HashMap`, so iteration order is unspecified and
/// varies run to run. Selecting on `mode` alone therefore let map order decide
/// *which* token a plugin received whenever more than one candidate shared a
/// mode — including tokens minted for entirely different upstreams. Audience is
/// the field that makes a delegated token the right or wrong credential, so it
/// is filtered on first, and the remaining choice is broken deterministically:
///
///   1. Keep only tokens whose audience matches the hook's `target_audience`
///      (every token, when the payload named no audience).
///   2. Prefer `OnBehalfOfUser` over any other mode — a delegator asked to act
///      for the user must not fall back to the gateway's own identity.
///   3. Within one mode, order by the key's `(subject_id, scopes)` and take the
///      first. Arbitrary but *stable*, so the same request picks the same token
///      every time instead of rotating with the hasher's seed.
///
/// No token matching both audience and mode is a fail-closed error, not a
/// fallback to some other audience's token: handing a plugin a credential
/// minted for a different upstream is worse than handing it none, because it
/// would be attached to a request the audience never authorized it for.
fn build_delegated(
    extensions: &Extensions,
    hook_name: &str,
    requested_audience: Option<&str>,
) -> Result<DelegatedCredential, HostError> {
    let raw = extensions
        .raw_credentials
        .as_ref()
        .ok_or_else(|| HostError::Credential {
            message: format!(
                "plugin declared '{CAP_READ_DELEGATED}' for hook '{hook_name}' but the request \
                 carries no raw-credentials extension — refusing to dispatch without the token \
                 it asked for"
            ),
        })?;

    // Match on the key's audience *and* the token's own, so a token whose two
    // copies of the field disagree is never treated as a match for either.
    let mut candidates: Vec<(&DelegationKey, &RawDelegatedToken)> = raw
        .delegated_tokens
        .iter()
        .filter(|(key, token)| match requested_audience {
            Some(audience) => key.audience == audience && token.audience == audience,
            None => true,
        })
        .collect();

    // Deterministic total order: preferred mode first, then the key's stable
    // fields. Without this the pick rides on `HashMap` iteration order.
    candidates.sort_by(|(left, _), (right, _)| {
        mode_rank(&left.mode)
            .cmp(&mode_rank(&right.mode))
            .then_with(|| left.subject_id.cmp(&right.subject_id))
            .then_with(|| left.scopes.cmp(&right.scopes))
    });

    let (_, token) = candidates.first().ok_or_else(|| {
        // The message names the audience — an identifier for an upstream, not
        // credential material — because "no token" and "no token *for this
        // audience*" call for different operator fixes.
        let scope = match requested_audience {
            Some(audience) => format!(" for audience '{audience}'"),
            None => String::new(),
        };
        HostError::Credential {
            message: format!(
                "plugin declared '{CAP_READ_DELEGATED}' for hook '{hook_name}' but no delegated \
                 token{scope} is present — refusing to dispatch without it, and refusing to \
                 substitute a token minted for a different audience"
            ),
        }
    })?;

    delegated_from_token(token, hook_name)
}

/// Sort key expressing the mode preference. Lower sorts first.
///
/// `DelegationMode` is matched exhaustively-by-fallback rather than listed, so a
/// mode added upstream ranks after the two the host reasons about instead of
/// silently outranking `OnBehalfOfUser`.
fn mode_rank(mode: &DelegationMode) -> u8 {
    match mode {
        DelegationMode::OnBehalfOfUser => 0,
        DelegationMode::AsThisWorkload => 1,
        _ => 2,
    }
}

/// Convert one `RawDelegatedToken` into its wire form.
fn delegated_from_token(
    token: &RawDelegatedToken,
    hook_name: &str,
) -> Result<DelegatedCredential, HostError> {
    let plaintext = token.token.as_str();

    if plaintext.trim().is_empty() {
        return Err(HostError::Credential {
            message: format!(
                "the delegated token for hook '{hook_name}' is empty — refusing to send an empty \
                 credential"
            ),
        });
    }

    Ok(DelegatedCredential {
        token: plaintext.to_string(),
        outbound_header: token.outbound_header.clone(),
        audience: token.audience.clone(),
        scopes: token.scopes.clone(),
    })
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use praxis_policy_core::extensions::raw_credentials::{DelegationKey, RawCredentialsExtension};

    use super::*;

    const INBOUND_SECRET: &str = "eyJhbGciOiJSUzI1NiJ9.INBOUND-SECRET-BYTES.sig";
    const DELEGATED_SECRET: &str = "MINTED-DELEGATED-SECRET-BYTES";

    fn caps(names: &[&str]) -> HashSet<String> {
        names.iter().map(|s| (*s).to_string()).collect()
    }

    /// Extensions carrying both an inbound and a delegated token.
    fn extensions_with_credentials() -> Extensions {
        let mut raw = RawCredentialsExtension::default();
        raw.inbound_tokens.insert(
            TokenRole::User,
            RawInboundToken::new(INBOUND_SECRET, "Authorization", TokenKind::Jwt),
        );
        raw.delegated_tokens.insert(
            DelegationKey::new(
                DelegationMode::OnBehalfOfUser,
                "https://billing.example.com",
                vec!["read".into()],
            )
            .with_subject_id("alice"),
            RawDelegatedToken::new(
                DELEGATED_SECRET,
                "Authorization",
                "https://billing.example.com",
                vec!["read".into()],
                chrono::Utc::now(),
            ),
        );

        Extensions {
            raw_credentials: Some(Arc::new(raw)),
            ..Default::default()
        }
    }

    fn task() -> Value {
        serde_json::json!({ "task_type": "load_and_run_hook" })
    }

    /// A `token.delegate` task whose payload names the audience the delegation
    /// is for — the shape `plugin.rs` actually builds.
    fn delegate_task(target_audience: &str) -> Value {
        serde_json::json!({
            "task_type": "load_and_run_hook",
            "hook_type": "token.delegate",
            "payload": {
                "target_name": "billing",
                "target_type": "tool",
                "target_audience": target_audience,
            },
        })
    }

    /// One delegated token, keyed consistently with its own audience field.
    fn delegated(
        subject: &str,
        audience: &str,
        mode: DelegationMode,
        secret: &str,
    ) -> (DelegationKey, RawDelegatedToken) {
        (
            DelegationKey::new(mode, audience, vec![]).with_subject_id(subject),
            RawDelegatedToken::new(
                secret,
                "Authorization",
                audience,
                vec![],
                chrono::Utc::now(),
            ),
        )
    }

    fn extensions_from(tokens: Vec<(DelegationKey, RawDelegatedToken)>) -> Extensions {
        let mut raw = RawCredentialsExtension::default();
        for (key, token) in tokens {
            raw.delegated_tokens.insert(key, token);
        }
        Extensions {
            raw_credentials: Some(Arc::new(raw)),
            ..Default::default()
        }
    }

    /// The delegated token a `token.delegate` dispatch would carry, or the
    /// fail-closed error.
    fn pick_delegated(extensions: &Extensions, target_audience: &str) -> Result<String, HostError> {
        let mut task = delegate_task(target_audience);
        attach_credential(
            &mut task,
            "token.delegate",
            extensions,
            &caps(&[CAP_READ_DELEGATED]),
        )?;
        Ok(task[CREDENTIAL_FIELD]["delegated"]["token"]
            .as_str()
            .expect("a delegated token was attached")
            .to_string())
    }

    // --- the capability gate -------------------------------------------------

    #[test]
    fn a_declaring_plugin_receives_the_inbound_token() {
        let mut task = task();
        attach_credential(
            &mut task,
            "identity.resolve",
            &extensions_with_credentials(),
            &caps(&[CAP_READ_INBOUND]),
        )
        .expect("a declared capability is honored");

        let credential = &task[CREDENTIAL_FIELD];
        assert_eq!(credential["inbound"]["token"], INBOUND_SECRET);
        assert_eq!(credential["inbound"]["source_header"], "Authorization");
        assert_eq!(credential["inbound"]["kind"], "jwt");
        assert!(
            credential.get("delegated").is_none(),
            "an identity hook must not receive delegated material"
        );
    }

    #[test]
    fn a_non_declaring_plugin_receives_no_token_material() {
        let mut task = task();
        attach_credential(
            &mut task,
            "identity.resolve",
            &extensions_with_credentials(),
            &caps(&[]),
        )
        .expect("declaring nothing is not an error");

        assert!(
            task.get(CREDENTIAL_FIELD).is_none(),
            "no credential field at all"
        );
        assert!(
            !serde_json::to_string(&task)
                .unwrap()
                .contains("INBOUND-SECRET-BYTES"),
            "no token bytes anywhere in the task"
        );
    }

    #[test]
    fn two_plugins_on_one_hook_are_gated_independently() {
        // The capability-gated acceptance example: same hook, same request, one
        // plugin declared the capability and the other did not.
        let extensions = extensions_with_credentials();

        let mut declaring = task();
        attach_credential(
            &mut declaring,
            "identity.resolve",
            &extensions,
            &caps(&[CAP_READ_INBOUND]),
        )
        .unwrap();

        let mut non_declaring = task();
        attach_credential(
            &mut non_declaring,
            "identity.resolve",
            &extensions,
            &caps(&[]),
        )
        .unwrap();

        assert!(
            serde_json::to_string(&declaring)
                .unwrap()
                .contains(INBOUND_SECRET)
        );
        assert!(
            !serde_json::to_string(&non_declaring)
                .unwrap()
                .contains("INBOUND-SECRET-BYTES")
        );
    }

    #[test]
    fn the_wrong_capability_does_not_unlock_a_hook() {
        // `read_delegated_tokens` must not grant inbound material, and vice
        // versa — the two are independently scoped.
        let extensions = extensions_with_credentials();

        let mut identity = task();
        attach_credential(
            &mut identity,
            "identity.resolve",
            &extensions,
            &caps(&[CAP_READ_DELEGATED]),
        )
        .unwrap();
        assert!(identity.get(CREDENTIAL_FIELD).is_none());

        let mut delegate = task();
        attach_credential(
            &mut delegate,
            "token.delegate",
            &extensions,
            &caps(&[CAP_READ_INBOUND]),
        )
        .unwrap();
        assert!(delegate.get(CREDENTIAL_FIELD).is_none());
    }

    #[test]
    fn a_declaring_plugin_receives_the_delegated_token() {
        let mut task = task();
        attach_credential(
            &mut task,
            "token.delegate",
            &extensions_with_credentials(),
            &caps(&[CAP_READ_DELEGATED]),
        )
        .expect("a declared capability is honored");

        let delegated = &task[CREDENTIAL_FIELD]["delegated"];
        assert_eq!(delegated["token"], DELEGATED_SECRET);
        assert_eq!(delegated["outbound_header"], "Authorization");
        assert_eq!(delegated["audience"], "https://billing.example.com");
        assert_eq!(delegated["scopes"][0], "read");
        assert!(task[CREDENTIAL_FIELD].get("inbound").is_none());
    }

    #[test]
    fn non_credential_hooks_never_receive_a_credential() {
        // Even a plugin that declared both capabilities gets nothing on a hook
        // whose payload has nowhere to put a token.
        for hook in [
            "tool_pre_invoke",
            "tool_post_invoke",
            "prompt_pre_fetch",
            "resource_post_fetch",
            "cmf.tool_pre_invoke",
            "cmf.prompt_pre_invoke",
            "http.request",
            "some_custom_hook",
            // The unprefixed names PPE no longer dispatches. A host that
            // registers them gets the generic payload and no credential.
            "identity_resolve",
            "token_delegate",
        ] {
            let mut task = task();
            attach_credential(
                &mut task,
                hook,
                &extensions_with_credentials(),
                &caps(&[CAP_READ_INBOUND, CAP_READ_DELEGATED]),
            )
            .unwrap();

            assert!(
                task.get(CREDENTIAL_FIELD).is_none(),
                "hook '{hook}' must not receive credentials"
            );
        }
    }

    // --- fail closed ---------------------------------------------------------

    #[test]
    fn a_declared_capability_with_no_extension_errors() {
        // Fail closed rather than dispatching without the token: a plugin that
        // asked for a credential and silently got none may treat the request
        // as unauthenticated.
        let err = attach_credential(
            &mut task(),
            "identity.resolve",
            &Extensions::default(),
            &caps(&[CAP_READ_INBOUND]),
        )
        .expect_err("a declared capability that cannot be honored must error");

        assert!(matches!(err, HostError::Credential { .. }), "got {err:?}");
    }

    #[test]
    fn a_declared_capability_with_no_matching_token_errors() {
        // The extension exists but carries only delegated tokens, so the
        // inbound capability cannot be honored.
        let mut raw = RawCredentialsExtension::default();
        raw.delegated_tokens.insert(
            DelegationKey::new(DelegationMode::AsThisWorkload, "aud", vec![])
                .with_subject_id("alice"),
            RawDelegatedToken::new("t", "Authorization", "aud", vec![], chrono::Utc::now()),
        );
        let extensions = Extensions {
            raw_credentials: Some(Arc::new(raw)),
            ..Default::default()
        };

        let err = attach_credential(
            &mut task(),
            "identity.resolve",
            &extensions,
            &caps(&[CAP_READ_INBOUND]),
        )
        .expect_err("no inbound token means the capability cannot be honored");
        assert!(matches!(err, HostError::Credential { .. }));
    }

    #[test]
    fn an_empty_token_is_rejected_rather_than_sent() {
        // A `#[serde(skip)]`-stripped token deserializes to "" — exactly the
        // shape that reaches here if anyone ever reintroduces a
        // serialize-then-reparse. Sending it would authenticate as an empty
        // bearer.
        for token in ["", "   ", "\t\n"] {
            let mut raw = RawCredentialsExtension::default();
            raw.inbound_tokens.insert(
                TokenRole::User,
                RawInboundToken::new(token, "Authorization", TokenKind::Jwt),
            );
            let extensions = Extensions {
                raw_credentials: Some(Arc::new(raw)),
                ..Default::default()
            };

            let err = attach_credential(
                &mut task(),
                "identity.resolve",
                &extensions,
                &caps(&[CAP_READ_INBOUND]),
            )
            .expect_err("an empty or whitespace-only token must be refused");
            assert!(matches!(err, HostError::Credential { .. }));
        }
    }

    #[test]
    fn an_empty_delegated_token_is_rejected() {
        let mut raw = RawCredentialsExtension::default();
        raw.delegated_tokens.insert(
            DelegationKey::new(DelegationMode::OnBehalfOfUser, "aud", vec![])
                .with_subject_id("alice"),
            RawDelegatedToken::new("", "Authorization", "aud", vec![], chrono::Utc::now()),
        );
        let extensions = Extensions {
            raw_credentials: Some(Arc::new(raw)),
            ..Default::default()
        };

        let err = attach_credential(
            &mut task(),
            "token.delegate",
            &extensions,
            &caps(&[CAP_READ_DELEGATED]),
        )
        .expect_err("an empty delegated token must be refused");
        assert!(matches!(err, HostError::Credential { .. }));
    }

    #[test]
    fn a_fail_closed_error_never_names_the_token() {
        let mut raw = RawCredentialsExtension::default();
        raw.inbound_tokens.insert(
            TokenRole::User,
            RawInboundToken::new("   ", "Authorization", TokenKind::Jwt),
        );
        let extensions = Extensions {
            raw_credentials: Some(Arc::new(raw)),
            ..Default::default()
        };

        let err = attach_credential(
            &mut task(),
            "identity.resolve",
            &extensions,
            &caps(&[CAP_READ_INBOUND]),
        )
        .expect_err("errors");
        let message = err.to_string();
        assert!(
            message.contains("identity.resolve"),
            "the message should name the hook: {message}"
        );
        assert!(message.contains("empty"));
    }

    // --- the DTO is the only carrier ----------------------------------------

    #[test]
    fn production_credential_types_still_refuse_to_serialize_tokens() {
        // The guard this module works around must remain intact: nothing here
        // loosened it, so a direct serialize of the production types still
        // strips the bytes. If this ever fails, the DTO stopped being the only
        // path token material can take.
        let inbound = RawInboundToken::new(INBOUND_SECRET, "Authorization", TokenKind::Jwt);
        let json = serde_json::to_string(&inbound).unwrap();
        assert!(
            !json.contains("INBOUND-SECRET-BYTES"),
            "the serde guard regressed: {json}"
        );

        let delegated = RawDelegatedToken::new(
            DELEGATED_SECRET,
            "Authorization",
            "aud",
            vec![],
            chrono::Utc::now(),
        );
        let json = serde_json::to_string(&delegated).unwrap();
        assert!(
            !json.contains("MINTED-DELEGATED"),
            "the serde guard regressed: {json}"
        );

        // And the inbound sub-map, which is what an audit or trace path dumps.
        // (`delegated_tokens` is keyed by a struct, so the extension as a whole
        // is not JSON-serializable — a pre-existing property of the type, not
        // something this host changed.)
        let extensions = extensions_with_credentials();
        let raw = extensions.raw_credentials.as_ref().unwrap();
        let json = serde_json::to_string(&raw.inbound_tokens).unwrap();
        assert!(
            !json.contains("INBOUND-SECRET-BYTES"),
            "the serde guard regressed: {json}"
        );

        for token in raw.delegated_tokens.values() {
            let json = serde_json::to_string(token).unwrap();
            assert!(
                !json.contains("MINTED-DELEGATED"),
                "the serde guard regressed: {json}"
            );
        }
    }

    #[test]
    fn a_serialize_then_reparse_would_have_yielded_an_empty_token() {
        // Documents *why* the DTO reads the in-memory field directly. This is
        // the tempting shortcut, and it silently produces an empty credential.
        let inbound = RawInboundToken::new(INBOUND_SECRET, "Authorization", TokenKind::Jwt);
        let round_tripped: RawInboundToken =
            serde_json::from_str(&serde_json::to_string(&inbound).unwrap()).unwrap();

        assert_eq!(
            &*round_tripped.token, "",
            "the guard strips the bytes on the way out"
        );
        assert_eq!(round_tripped.source_header, "Authorization");
    }

    // --- redaction -----------------------------------------------------------

    #[test]
    fn the_dto_debug_output_hides_the_token() {
        let dto = CredentialDto {
            inbound: Some(InboundCredential {
                token: INBOUND_SECRET.into(),
                source_header: "Authorization".into(),
                kind: "jwt".into(),
                headers: Some(HashMap::from([(
                    "Authorization".into(),
                    format!("Bearer {INBOUND_SECRET}"),
                )])),
            }),
            delegated: None,
        };

        // Both the outer DTO and the inner sub-object are printed, since either
        // could reach a log line on its own.
        let outer = format!("{dto:?}");
        let inner = format!("{:?}", dto.inbound.as_ref().unwrap());

        for debug in [&outer, &inner] {
            assert!(
                !debug.contains("INBOUND-SECRET-BYTES"),
                "token leaked into Debug: {debug}"
            );
        }
        // Non-secret context stays diagnosable.
        assert!(inner.contains("Authorization"));
        assert!(inner.contains("jwt"));
    }

    #[test]
    fn the_delegated_dto_debug_output_hides_the_token() {
        let credential = DelegatedCredential {
            token: DELEGATED_SECRET.into(),
            outbound_header: "Authorization".into(),
            audience: "https://billing.example.com".into(),
            scopes: vec!["read".into()],
        };

        let debug = format!("{credential:?}");
        assert!(
            !debug.contains("MINTED-DELEGATED"),
            "token leaked into Debug: {debug}"
        );
        assert!(debug.contains("billing.example.com"));
        assert!(debug.contains("read"));
    }

    // --- wire contract details ----------------------------------------------

    #[test]
    fn token_kinds_use_the_wire_names_the_worker_matches_on() {
        // worker.py's _BEARER_TOKEN_KINDS is {jwt, opaque, spiffe_jwt, ucan};
        // a mismatch here would silently map a bearer to source "custom".
        assert_eq!(token_kind_wire_name(&TokenKind::Jwt), "jwt");
        assert_eq!(token_kind_wire_name(&TokenKind::Opaque), "opaque");
        assert_eq!(token_kind_wire_name(&TokenKind::SpiffeJwt), "spiffe_jwt");
        assert_eq!(token_kind_wire_name(&TokenKind::Ucan), "ucan");
        assert_eq!(token_kind_wire_name(&TokenKind::TxnToken), "txn_token");
    }

    #[test]
    fn wire_names_match_the_serde_representation() {
        // Guards the hand-written mapping against the enum's own serde rename,
        // so adding a variant upstream cannot silently desync the two.
        for kind in [
            TokenKind::Jwt,
            TokenKind::Opaque,
            TokenKind::SpiffeJwt,
            TokenKind::Ucan,
            TokenKind::TxnToken,
        ] {
            let via_serde = serde_json::to_value(&kind).unwrap();
            assert_eq!(
                via_serde.as_str().unwrap(),
                token_kind_wire_name(&kind),
                "hand-written wire name disagrees with serde for {kind:?}"
            );
        }
    }

    #[test]
    fn the_user_token_is_preferred_over_the_client_token() {
        // An identity resolver wants the subject's credential; resolving the
        // gateway's own token as the user's would be an authorization bug.
        let mut raw = RawCredentialsExtension::default();
        raw.inbound_tokens.insert(
            TokenRole::Client,
            RawInboundToken::new("CLIENT-TOKEN", "X-Client", TokenKind::Opaque),
        );
        raw.inbound_tokens.insert(
            TokenRole::User,
            RawInboundToken::new("USER-TOKEN", "Authorization", TokenKind::Jwt),
        );
        let extensions = Extensions {
            raw_credentials: Some(Arc::new(raw)),
            ..Default::default()
        };

        let mut task = task();
        attach_credential(
            &mut task,
            "identity.resolve",
            &extensions,
            &caps(&[CAP_READ_INBOUND]),
        )
        .unwrap();
        assert_eq!(task[CREDENTIAL_FIELD]["inbound"]["token"], "USER-TOKEN");
    }

    #[test]
    fn headers_are_synthesized_from_the_source_header() {
        let mut task = task();
        attach_credential(
            &mut task,
            "identity.resolve",
            &extensions_with_credentials(),
            &caps(&[CAP_READ_INBOUND]),
        )
        .unwrap();

        // The worker scrubs the plaintext out of these values before a plugin
        // can echo them; the host's job is only to name the carrying header.
        assert_eq!(
            task[CREDENTIAL_FIELD]["inbound"]["headers"]["Authorization"],
            INBOUND_SECRET
        );
    }

    #[test]
    fn an_on_behalf_of_user_token_is_preferred_over_a_gateway_token() {
        let mut raw = RawCredentialsExtension::default();
        raw.delegated_tokens.insert(
            DelegationKey::new(DelegationMode::AsThisWorkload, "aud", vec![]).with_subject_id("gw"),
            RawDelegatedToken::new(
                "GATEWAY-TOKEN",
                "Authorization",
                "aud",
                vec![],
                chrono::Utc::now(),
            ),
        );
        raw.delegated_tokens.insert(
            DelegationKey::new(DelegationMode::OnBehalfOfUser, "aud", vec![])
                .with_subject_id("alice"),
            RawDelegatedToken::new(
                "USER-DELEGATED-TOKEN",
                "Authorization",
                "aud",
                vec![],
                chrono::Utc::now(),
            ),
        );
        let extensions = Extensions {
            raw_credentials: Some(Arc::new(raw)),
            ..Default::default()
        };

        let mut task = task();
        attach_credential(
            &mut task,
            "token.delegate",
            &extensions,
            &caps(&[CAP_READ_DELEGATED]),
        )
        .unwrap();
        assert_eq!(
            task[CREDENTIAL_FIELD]["delegated"]["token"], "USER-DELEGATED-TOKEN",
            "a delegator acting for the user must not fall back to the gateway's identity"
        );
    }

    // --- delegated-token selection ------------------------------------------

    #[test]
    fn the_delegated_pick_matches_the_requested_audience() {
        // The reviewer's finding: filtering on mode alone let `HashMap` order
        // decide which token a plugin got. Three tokens share the preferred
        // mode and differ only by audience, so a mode-only filter picks one of
        // the three at random — and two of those three are credentials minted
        // for a completely different upstream.
        let extensions = extensions_from(vec![
            delegated(
                "alice",
                "https://billing.example.com",
                DelegationMode::OnBehalfOfUser,
                "BILLING-TOKEN",
            ),
            delegated(
                "alice",
                "https://search.example.com",
                DelegationMode::OnBehalfOfUser,
                "SEARCH-TOKEN",
            ),
            delegated(
                "alice",
                "https://payroll.example.com",
                DelegationMode::OnBehalfOfUser,
                "PAYROLL-TOKEN",
            ),
        ]);

        assert_eq!(
            pick_delegated(&extensions, "https://search.example.com").unwrap(),
            "SEARCH-TOKEN",
            "a token minted for another audience must never be substituted"
        );
        assert_eq!(
            pick_delegated(&extensions, "https://billing.example.com").unwrap(),
            "BILLING-TOKEN"
        );
    }

    #[test]
    fn the_delegated_pick_is_stable_across_runs_and_insertion_orders() {
        // `HashMap` seeds its hasher per process *and* orders by insertion
        // history, so the pre-fix selection could differ run to run and between
        // two extensions holding the same tokens. Both are pinned here: every
        // repetition, under every insertion order, yields the same token.
        let forward = vec![
            delegated("alice", "aud-a", DelegationMode::OnBehalfOfUser, "A"),
            delegated("bob", "aud-a", DelegationMode::OnBehalfOfUser, "B"),
            delegated("carol", "aud-a", DelegationMode::OnBehalfOfUser, "C"),
            delegated("dave", "aud-a", DelegationMode::OnBehalfOfUser, "D"),
        ];
        let reversed: Vec<_> = forward.iter().rev().cloned().collect();

        // `alice` sorts first among the equal-mode candidates.
        const EXPECTED: &str = "A";

        for _ in 0..200 {
            let one = extensions_from(forward.clone());
            let other = extensions_from(reversed.clone());
            assert_eq!(pick_delegated(&one, "aud-a").unwrap(), EXPECTED);
            assert_eq!(
                pick_delegated(&other, "aud-a").unwrap(),
                EXPECTED,
                "insertion order must not change the pick"
            );
        }
    }

    #[test]
    fn no_token_for_the_requested_audience_fails_closed() {
        // Fail closed rather than fall back: attaching another audience's token
        // would send a credential to an upstream that never authorized it.
        let extensions = extensions_from(vec![delegated(
            "alice",
            "https://billing.example.com",
            DelegationMode::OnBehalfOfUser,
            "BILLING-TOKEN",
        )]);

        let err = pick_delegated(&extensions, "https://attacker.example.com")
            .expect_err("no matching audience means no token");

        let message = err.to_string();
        assert!(matches!(err, HostError::Credential { .. }), "{message}");
        assert!(
            message.contains("attacker.example.com"),
            "the error should name the audience that had no token: {message}"
        );
        assert!(
            !message.contains("BILLING-TOKEN"),
            "the error must not name the token it declined to substitute: {message}"
        );
    }

    #[test]
    fn the_audience_filter_is_applied_before_the_mode_preference() {
        // Mode preference must not reach across audiences: the only token for
        // the requested audience is `AsThisWorkload`, and the `OnBehalfOfUser` token
        // belongs to a different upstream. Preferring mode first would hand
        // over the wrong-audience token.
        let extensions = extensions_from(vec![
            delegated(
                "alice",
                "https://other.example.com",
                DelegationMode::OnBehalfOfUser,
                "OTHER-AUDIENCE-USER-TOKEN",
            ),
            delegated(
                "gw",
                "https://billing.example.com",
                DelegationMode::AsThisWorkload,
                "BILLING-GATEWAY-TOKEN",
            ),
        ]);

        assert_eq!(
            pick_delegated(&extensions, "https://billing.example.com").unwrap(),
            "BILLING-GATEWAY-TOKEN"
        );
    }

    #[test]
    fn within_one_audience_the_user_token_still_wins() {
        // The original mode preference survives the audience filter: among
        // same-audience candidates, a delegator acting for the user must not
        // get the gateway's own identity — even when the gateway token sorts
        // first by subject.
        let extensions = extensions_from(vec![
            delegated(
                "aaa-gw",
                "aud",
                DelegationMode::AsThisWorkload,
                "GATEWAY-TOKEN",
            ),
            delegated(
                "zzz-user",
                "aud",
                DelegationMode::OnBehalfOfUser,
                "USER-TOKEN",
            ),
        ]);

        assert_eq!(pick_delegated(&extensions, "aud").unwrap(), "USER-TOKEN");
    }

    #[test]
    fn a_key_whose_audience_disagrees_with_its_token_is_not_a_match() {
        // The audience appears on both the cache key and the token. A mismatch
        // means one of the two is wrong, and there is no safe way to guess
        // which — so neither audience matches it.
        let (key, _) = delegated("alice", "aud-key", DelegationMode::OnBehalfOfUser, "T");
        let token = RawDelegatedToken::new(
            "MISMATCHED-TOKEN",
            "Authorization",
            "aud-token",
            vec![],
            chrono::Utc::now(),
        );
        let extensions = extensions_from(vec![(key, token)]);

        for audience in ["aud-key", "aud-token"] {
            assert!(
                pick_delegated(&extensions, audience).is_err(),
                "a self-inconsistent token must not satisfy '{audience}'"
            );
        }
    }

    #[test]
    fn an_unscoped_delegation_accepts_any_audience() {
        // `DelegationPayload.target_audience` is optional. With no audience to
        // filter on there is nothing to be wrong about, so the mode preference
        // and the stable tiebreak carry the pick — but it must still be
        // deterministic.
        let tokens = vec![
            delegated("alice", "aud-a", DelegationMode::OnBehalfOfUser, "A"),
            delegated("bob", "aud-b", DelegationMode::OnBehalfOfUser, "B"),
        ];

        for _ in 0..50 {
            let mut task = serde_json::json!({
                "task_type": "load_and_run_hook",
                "payload": { "target_name": "billing", "target_type": "tool" },
            });
            attach_credential(
                &mut task,
                "token.delegate",
                &extensions_from(tokens.clone()),
                &caps(&[CAP_READ_DELEGATED]),
            )
            .expect("an unscoped delegation is still served");
            assert_eq!(task[CREDENTIAL_FIELD]["delegated"]["token"], "A");
        }
    }

    #[test]
    fn the_mode_rank_puts_the_user_first_and_unknown_modes_last() {
        // An upstream-added mode must not outrank `OnBehalfOfUser` by accident.
        assert!(
            mode_rank(&DelegationMode::OnBehalfOfUser) < mode_rank(&DelegationMode::AsThisWorkload)
        );
    }

    #[test]
    fn the_requested_audience_is_read_from_the_payload() {
        assert_eq!(
            requested_audience(&delegate_task("https://billing.example.com")).as_deref(),
            Some("https://billing.example.com")
        );
        // Absent, non-string, and payload-less tasks all mean "unscoped".
        assert_eq!(requested_audience(&task()), None);
        assert_eq!(
            requested_audience(&serde_json::json!({ "payload": { "target_audience": 7 } })),
            None
        );
        assert_eq!(
            requested_audience(&serde_json::json!({ "payload": {} })),
            None
        );
    }

    #[test]
    fn the_credential_field_name_matches_the_worker_contract() {
        assert_eq!(
            CREDENTIAL_FIELD, "credential",
            "the worker reads task_data['credential']"
        );
    }

    // --- PPE identity and delegation payloads ---------------------------------

    use praxis_policy_core::delegation::DelegationPayload;
    use praxis_policy_core::identity::{IdentityPayload, TokenSource};

    fn identity_payload() -> IdentityPayload {
        IdentityPayload::new(INBOUND_SECRET, TokenSource::Bearer).with_headers(HashMap::from([
            ("authorization".into(), format!("Bearer {INBOUND_SECRET}")),
            ("cookie".into(), "session=abc".into()),
            ("x-tenant".into(), "acme".into()),
        ]))
    }

    #[test]
    fn an_identity_payload_supplies_its_own_token_to_a_declaring_plugin() {
        let mut task = task();
        // No raw-credentials extension: PPE dispatches identity.resolve with the
        // credential on the payload.
        attach_credential_for_payload(
            &mut task,
            "identity.resolve",
            &identity_payload(),
            &Extensions::default(),
            &caps(&[CAP_READ_INBOUND]),
        )
        .expect("the payload's token honors the capability");

        let inbound = &task[CREDENTIAL_FIELD]["inbound"];
        assert_eq!(inbound["token"], INBOUND_SECRET);
        assert_eq!(inbound["source_header"], "authorization");
        assert_eq!(inbound["kind"], "opaque");
        // The gated channel carries the whole header map; the worker scrubs it.
        assert_eq!(inbound["headers"]["cookie"], "session=abc");
        assert_eq!(inbound["headers"]["x-tenant"], "acme");
    }

    #[test]
    fn a_header_borne_identity_credential_is_found() {
        let payload: IdentityPayload = serde_json::from_value(serde_json::json!({
            "source": "bearer",
            "source_header": "X-User-Token",
            "headers": {"x-user-token": INBOUND_SECRET},
        }))
        .unwrap();
        let mut task = task();
        attach_credential_for_payload(
            &mut task,
            "identity.resolve",
            &payload,
            &Extensions::default(),
            &caps(&[CAP_READ_INBOUND]),
        )
        .unwrap();
        assert_eq!(task[CREDENTIAL_FIELD]["inbound"]["token"], INBOUND_SECRET);
        assert_eq!(
            task[CREDENTIAL_FIELD]["inbound"]["source_header"],
            "x-user-token"
        );
    }

    #[test]
    fn an_identity_payload_gives_a_non_declaring_plugin_nothing() {
        let mut task = task();
        attach_credential_for_payload(
            &mut task,
            "identity.resolve",
            &identity_payload(),
            &extensions_with_credentials(),
            &caps(&[CAP_READ_DELEGATED]),
        )
        .unwrap();
        assert!(task.get(CREDENTIAL_FIELD).is_none());
    }

    #[test]
    fn an_identity_payload_without_a_credential_fails_closed() {
        let payload = IdentityPayload::new("", TokenSource::Bearer);
        let mut task = task();
        // The extensions hold a token, but it is not the one this hook is
        // about, so it is not substituted.
        let err = attach_credential_for_payload(
            &mut task,
            "identity.resolve",
            &payload,
            &extensions_with_credentials(),
            &caps(&[CAP_READ_INBOUND]),
        )
        .unwrap_err();
        assert!(matches!(err, HostError::Credential { .. }), "{err:?}");
        assert!(task.get(CREDENTIAL_FIELD).is_none());
    }

    #[test]
    fn a_delegation_payload_supplies_its_bearer_token_to_an_inbound_declaring_plugin() {
        let payload = DelegationPayload::new(INBOUND_SECRET, "billing")
            .with_target_audience("https://billing.example.com")
            .with_required_permissions(vec!["read".into()]);
        let mut gated = task();
        attach_credential_for_payload(
            &mut gated,
            "token.delegate",
            &payload,
            &Extensions::default(),
            &caps(&[CAP_READ_INBOUND]),
        )
        .unwrap();
        let delegated = &gated[CREDENTIAL_FIELD]["delegated"];
        assert_eq!(delegated["token"], INBOUND_SECRET);
        assert_eq!(delegated["audience"], "https://billing.example.com");
        assert_eq!(delegated["scopes"], serde_json::json!(["read"]));

        // The bearer is an inbound credential, so the delegated-token
        // capability alone does not unlock it.
        let mut task = task();
        attach_credential_for_payload(
            &mut task,
            "token.delegate",
            &payload,
            &Extensions::default(),
            &caps(&[CAP_READ_DELEGATED]),
        )
        .unwrap();
        assert!(task.get(CREDENTIAL_FIELD).is_none());
    }

    #[test]
    fn a_delegation_payload_without_a_bearer_token_fails_closed() {
        let payload = DelegationPayload::new("  ", "billing");
        let mut task = task();
        let err = attach_credential_for_payload(
            &mut task,
            "token.delegate",
            &payload,
            &extensions_with_credentials(),
            &caps(&[CAP_READ_INBOUND]),
        )
        .unwrap_err();
        assert!(matches!(err, HostError::Credential { .. }), "{err:?}");
    }

    #[test]
    fn a_legacy_payload_still_reads_the_extensions() {
        let mut task = task();
        attach_credential_for_payload(
            &mut task,
            "identity.resolve",
            &crate::legacy::IdentityResolvePayload::default(),
            &extensions_with_credentials(),
            &caps(&[CAP_READ_INBOUND]),
        )
        .unwrap();
        assert_eq!(task[CREDENTIAL_FIELD]["inbound"]["token"], INBOUND_SECRET);
    }
}