polyc-crypto 2026.8.3

Provenance signatures (commonware-cryptography ed25519) for polychrome tool calls.
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
//! Stateless, signed web-session tokens and their logout denylist.
//!
//! A session token binds a [`SessionSubject`] — a persona-credential login
//! (a `persona_id`) or a wallet-passkey login (a `wallet_address`, and
//! optionally the persona it currently resolves to) — plus the [`SessionScope`]s
//! it carries, to an issue/expiry window, and is signed by a dedicated
//! [`SessionSigner`]. Verification needs only the role's public
//! key, so a session survives a cold restart of whatever process minted it:
//! nothing here reads or writes a server-side session store. [`mint_session`]
//! and [`verify_session`] are the mint/verify pair; [`RevokedTokens`] is the
//! best-effort, in-memory logout denylist [`verify_session`] consults.
//!
//! This module owns only the token's cryptographic shape and the denylist —
//! it mints no challenges, runs no login ceremony, and knows nothing about
//! cookies or HTTP. A caller that needs those (e.g. a passkey-authenticated
//! login flow) builds them on top, choosing its own token TTL and calling
//! [`mint_session`]/[`verify_session`] directly.
//!
//! C1.4 adds the replacement protocol through [`mint_authorized_session`] and
//! [`verify_authorized_session`]. Its signed claims bind a stable bearer id and
//! authorization epoch to the same subject/scopes/time window. Verification
//! remains deliberately pure: a caller must check the resulting id and epoch
//! against current State before authorizing a request. The v2 path remains
//! live only until the coordinated caller cutover removes it.
//!
//! See ADR 0007 (`docs/decisions/0007-web-sessions-rooted-in-either-passkey.md`)
//! for why a session may be rooted in either credential, and why
//! `explorer-read`/`wallet-manage`/`agent-turn` are independent claims rather
//! than one all-or-nothing grant: revoking a persona-credential must never
//! revoke a wallet's own sessions, and vice versa.

use std::collections::HashSet;
use std::sync::Mutex;

use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;

use crate::signing_role::{RoleTrustSet, SessionRole, SessionSigner, SigningRole as _};

/// Domain-separation prefix prepended to a session token's signed bytes.
///
/// The session role has its own private key. The prefix below additionally
/// prevents one session-shaped artifact from being interpreted as another
/// artifact under that role. Without an
/// artifact-local prefix, a captured signed payload of a different kind
/// could be replayed as a forged session token (or vice versa) whenever the
/// byte shapes happened to coincide. This prefix (with a trailing NUL so no
/// legal JSON body can extend it into a prefix collision) makes that
/// impossible: [`verify_session`] only accepts bytes that begin with it, and
/// no other signed-artifact kind in this codebase ever prepends it.
///
/// `.v2\0`, not `.v1\0`: this is a new prefix (ADR 0007), deliberately
/// distinct from the pre-existing `polychrome.explorer-session.v1\0` a
/// persona-only session token used — so that changeover invalidates every
/// live session at deploy (one re-login each, bounded by the TTL) rather
/// than needing a dual-accept shim for a widened payload shape, per this
/// repo's no-legacy-code doctrine. The exact bytes are load-bearing: changing
/// them again invalidates every session minted under this prefix.
const SESSION_DOMAIN_PREFIX: &[u8] = b"polychrome.web-session.v2\0";

/// Domain for State-authorized bearer sessions.
///
/// Version 3 binds the signed bearer to a stable State row and the
/// authorization epoch at which State minted that row. It is deliberately
/// disjoint from v2: the C1.4 cutover invalidates old stateless sessions
/// instead of running a dual-accept compatibility window.
const AUTHORIZED_SESSION_DOMAIN_PREFIX: &[u8] = b"polychrome.web-session.v3\0";

/// Which credential rooted a session.
///
/// A persona-credential login always resolves a persona (enrollment requires
/// one). A wallet-passkey login may resolve to a linked, `STATUS_LINKED`
/// persona, or to none at all — a wallet with no persona is a standing,
/// permanent state (ADR 0007), not a transitional or error one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SessionSubject {
    /// Rooted in a `PersonaCredential` login.
    Persona {
        /// The persona this session is bound to.
        persona_id: String,
    },
    /// Rooted in a wallet-passkey login (a stateless signature-recovery
    /// check — see `polyc-wallet-delegation`'s envelope verification, ADR
    /// 0007 — never a control-plane-held credential registry).
    Wallet {
        /// The wallet address the presented signature recovered to.
        wallet_address: String,
        /// The persona this address currently resolves to locally, if any
        /// (`crate::persona`'s `wallet_link_by_address` directory —
        /// instance-local persona resolution, never identity).
        persona_id: Option<String>,
    },
}

impl SessionSubject {
    /// The persona this subject is bound to, if any — `Some` for every
    /// [`Self::Persona`] and for a [`Self::Wallet`] that currently resolves
    /// to one.
    #[must_use]
    pub fn persona_id(&self) -> Option<&str> {
        match self {
            Self::Persona { persona_id } => Some(persona_id),
            Self::Wallet { persona_id, .. } => persona_id.as_deref(),
        }
    }

    /// The wallet address this subject is bound to, if it is a wallet-rooted
    /// session.
    #[must_use]
    pub fn wallet_address(&self) -> Option<&str> {
        match self {
            Self::Persona { .. } => None,
            Self::Wallet { wallet_address, .. } => Some(wallet_address),
        }
    }
}

/// A capability a session token carries.
///
/// Checked independently of any other scope the same token carries (ADR
/// 0007: possession of a wallet passkey must never implicitly grant
/// explorer read, and vice versa). Which scopes a given ceremony mints
/// TOGETHER is a policy decision recorded in that ADR; that two of them
/// commonly arrive on the same token never licenses a gate to infer one from
/// another — every gate names the exact scope it requires.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SessionScope {
    /// Read access to the subject's own persona's conversations/data in the
    /// explorer (never fleet-wide — see `crate::control-plane`'s
    /// participation-scoped read gate).
    ExplorerRead,
    /// Manage the subject's own linked wallet (spend authorization, linking,
    /// revocation ceremonies).
    WalletManage,
    /// Dispatch an agent turn as the subject's own persona.
    ///
    /// Separate from [`Self::ExplorerRead`] because a turn is a write, not a
    /// read: it spends provider tokens and can trigger tool side effects. The
    /// two are minted together by POLICY wherever a login ceremony resolves a
    /// persona (ADR 0007's Consequences records that choice), never by
    /// implication — a gate authorizing a turn names this scope explicitly and
    /// infers it from nothing, so the policy is revisable without touching
    /// every call site, and a future token kind that should read without
    /// spending (a share link, a machine session) can be minted without it.
    AgentTurn,
}

impl SessionScope {
    /// The wire string this scope serializes to. A fixed, explicit mapping
    /// (not `serde`'s default enum-tag rendering) so the wire shape is
    /// independent of Rust identifier casing and stable across a refactor of
    /// the variant names.
    const fn as_str(self) -> &'static str {
        match self {
            Self::ExplorerRead => "explorer-read",
            Self::WalletManage => "wallet-manage",
            Self::AgentTurn => "agent-turn",
        }
    }

    /// Parse a scope from its wire string. `None` on anything else — an
    /// unrecognized scope string in a token must never be silently dropped
    /// into "no scopes" or, worse, upgraded to every scope; the caller
    /// ([`decode_session_payload`]) rejects the whole token instead.
    fn from_str(s: &str) -> Option<Self> {
        match s {
            "explorer-read" => Some(Self::ExplorerRead),
            "wallet-manage" => Some(Self::WalletManage),
            "agent-turn" => Some(Self::AgentTurn),
            _ => None,
        }
    }
}

/// A verified session's claims: who it's bound to, what it authorizes, and
/// its issue/expiry window.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionClaims {
    /// Stable signing-role issuer.
    pub issuer: String,
    /// Exact key identity selected from the session trust set.
    pub key_id: String,
    /// Which credential rooted this session, and what it resolves to.
    pub subject: SessionSubject,
    /// The capabilities this token carries. Never empty — [`mint_session`]
    /// requires at least one scope, since a session that authorizes nothing
    /// has no reason to exist.
    pub scopes: Vec<SessionScope>,
    /// When this session was minted (unix ms).
    pub issued_ms: u64,
    /// When this session stops verifying (unix ms).
    pub expires_ms: u64,
}

impl SessionClaims {
    /// Whether this session carries `scope`.
    #[must_use]
    pub fn has_scope(&self, scope: SessionScope) -> bool {
        self.scopes.contains(&scope)
    }
}

/// The wire shape of a session token's payload segment — a plain,
/// unencrypted JSON object (readable by anyone who holds the token; it
/// carries no secret), canonicalized field-by-field on the verify side
/// rather than trusted as raw bytes (see [`session_canonical`]).
#[derive(serde::Serialize, serde::Deserialize)]
struct WirePayload {
    issuer: String,
    key_id: String,
    #[serde(flatten)]
    subject: WireSubject,
    scopes: Vec<String>,
    issued_ms: u64,
    expires_ms: u64,
}

#[derive(serde::Serialize, serde::Deserialize)]
#[serde(tag = "sub_kind", rename_all = "snake_case")]
enum WireSubject {
    Persona {
        persona_id: String,
    },
    Wallet {
        wallet_address: String,
        #[serde(skip_serializing_if = "Option::is_none", default)]
        persona_id: Option<String>,
    },
}

impl From<&SessionSubject> for WireSubject {
    fn from(subject: &SessionSubject) -> Self {
        match subject {
            SessionSubject::Persona { persona_id } => Self::Persona {
                persona_id: persona_id.clone(),
            },
            SessionSubject::Wallet {
                wallet_address,
                persona_id,
            } => Self::Wallet {
                wallet_address: wallet_address.clone(),
                persona_id: persona_id.clone(),
            },
        }
    }
}

impl From<WireSubject> for SessionSubject {
    fn from(wire: WireSubject) -> Self {
        match wire {
            WireSubject::Persona { persona_id } => Self::Persona { persona_id },
            WireSubject::Wallet {
                wallet_address,
                persona_id,
            } => Self::Wallet {
                wallet_address,
                persona_id,
            },
        }
    }
}

/// Build the exact bytes [`mint_session`] signs and [`verify_session`]
/// recomputes and checks the signature against: [`SESSION_DOMAIN_PREFIX`]
/// followed by the canonical JSON of the payload fields.
///
/// Recomputed from PARSED fields on the verify side (never the raw decoded
/// payload bytes trusted as-is), so a canonical can never be re-serialized
/// into a byte-identical-looking but differently-keyed JSON object.
fn session_canonical(payload: &WirePayload) -> Vec<u8> {
    let body =
        serde_json::to_string(payload).expect("WirePayload serializes (no non-finite floats)");
    let mut bytes = Vec::with_capacity(SESSION_DOMAIN_PREFIX.len() + body.len());
    bytes.extend_from_slice(SESSION_DOMAIN_PREFIX);
    bytes.extend_from_slice(body.as_bytes());
    bytes
}

/// Mint a stateless, signed session token bound to `subject`, carrying
/// `scopes`.
///
/// The token is `base64url(payload_json) ++ "." ++ base64url(signature)`: the
/// payload segment is plain (unprefixed) JSON, readable by anyone who holds
/// the token but unforgeable — [`verify_session`] recomputes the
/// domain-prefixed canonical from the parsed fields and checks `signer`'s
/// ed25519 signature over it. `expires_ms` is `now_ms + ttl_ms`, saturating
/// (never wraps on a pathological `ttl_ms`).
///
/// # Panics
///
/// Panics if `scopes` is empty — a session that authorizes nothing has no
/// reason to exist; every caller names at least one scope explicitly.
#[must_use]
pub fn mint_session(
    signer: &SessionSigner,
    subject: &SessionSubject,
    scopes: &[SessionScope],
    now_ms: u64,
    ttl_ms: u64,
) -> String {
    assert!(
        !scopes.is_empty(),
        "mint_session requires at least one scope"
    );
    let issued_ms = now_ms;
    let expires_ms = now_ms.saturating_add(ttl_ms);
    let payload = WirePayload {
        issuer: SessionRole::ISSUER.to_owned(),
        key_id: signer.identity().key_id().to_owned(),
        subject: subject.into(),
        scopes: scopes.iter().map(|s| s.as_str().to_owned()).collect(),
        issued_ms,
        expires_ms,
    };
    let payload_json =
        serde_json::to_string(&payload).expect("WirePayload serializes (no non-finite floats)");
    let signed_bytes = session_canonical(&payload);
    let signature = signer.sign(&signed_bytes);
    format!(
        "{}.{}",
        URL_SAFE_NO_PAD.encode(payload_json.as_bytes()),
        URL_SAFE_NO_PAD.encode(signature)
    )
}

/// Decode a session token's `.`-separated payload/signature segments into
/// the parsed payload plus its raw signature bytes, or `None` on any
/// malformed shape/base64/JSON/field/unrecognized-scope — the parse half of
/// [`verify_session`], factored out so [`RevokedTokens::reap`] can read a
/// denylisted token's own `expires_ms` without duplicating this decode.
fn decode_session_payload(token: &str) -> Option<(WirePayload, Vec<SessionScope>, Vec<u8>)> {
    let (payload_b64, signature_b64) = token.split_once('.')?;
    if payload_b64.is_empty() || signature_b64.is_empty() || signature_b64.contains('.') {
        return None;
    }
    let payload_bytes = URL_SAFE_NO_PAD.decode(payload_b64).ok()?;
    let signature = URL_SAFE_NO_PAD.decode(signature_b64).ok()?;
    let payload: WirePayload = serde_json::from_slice(&payload_bytes).ok()?;
    // An unrecognized scope string fails the whole token closed rather than
    // being silently dropped (which could shrink an attacker-visible scope
    // list to look benign) or ignored (which could let a not-yet-understood
    // future scope slip through unchecked on an old binary).
    let scopes = payload
        .scopes
        .iter()
        .map(|s| SessionScope::from_str(s))
        .collect::<Option<Vec<_>>>()?;
    Some((payload, scopes, signature))
}

/// Verify a session token minted by [`mint_session`], returning its
/// [`SessionClaims`] on success.
///
/// Fail-closed on ALL of: malformed shape (not exactly one `.`), undecodable
/// base64/JSON, a missing/wrong-typed/unrecognized-scope field, a signature
/// that does not verify against `signer_public_key` under the
/// domain-separated canonical (`session_canonical` — so a signature minted
/// for any OTHER artifact kind this signer produces can never verify here),
/// `now_ms >= expires_ms` (expiry is checked against the PARSED
/// `expires_ms`, not trusted from wall-clock drift elsewhere), or the token
/// being present in `denylist` (logout). No naive secret comparison happens
/// here — unforgeability comes from the ed25519 signature check, not from
/// string equality, so the denylist membership check needs no
/// constant-time treatment: a token that fails to verify or fails the
/// denylist check reveals nothing an attacker could use to forge a
/// different one.
///
/// Needs only `signer_public_key` — no server-side session store, so this
/// survives a cold restart of whatever process minted the token unchanged.
#[must_use]
pub fn verify_session(
    signer_public_key: &[u8],
    token: &str,
    now_ms: u64,
    denylist: &RevokedTokens,
) -> Option<SessionClaims> {
    let trusted_signers =
        RoleTrustSet::<SessionRole>::from_public_keys(vec![signer_public_key.to_vec()]).ok()?;
    verify_session_with_trust(&trusted_signers, token, now_ms, denylist)
}

/// Verifies a session against the role's current and retired trust set.
#[must_use]
pub fn verify_session_with_trust(
    trusted_signers: &RoleTrustSet<SessionRole>,
    token: &str,
    now_ms: u64,
    denylist: &RevokedTokens,
) -> Option<SessionClaims> {
    let (payload, scopes, signature) = decode_session_payload(token)?;
    let signed_bytes = session_canonical(&payload);
    if payload.issuer != SessionRole::ISSUER
        || !trusted_signers.verify(&payload.key_id, &signed_bytes, &signature)
    {
        return None;
    }
    if now_ms >= payload.expires_ms {
        return None;
    }
    if denylist.contains(token) {
        return None;
    }
    Some(SessionClaims {
        issuer: payload.issuer,
        key_id: payload.key_id,
        subject: payload.subject.into(),
        scopes,
        issued_ms: payload.issued_ms,
        expires_ms: payload.expires_ms,
    })
}

/// Claims signed into a bearer whose current authorization lives in State.
///
/// Signature verification proves only that these claims came from the
/// session signer and remain inside their time window. An admission boundary
/// must additionally read the `session_id` and credential-root epoch from
/// State and fail closed unless both still authorize this bearer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthorizedSessionClaims {
    /// Stable signing-role issuer.
    pub issuer: String,
    /// Exact key identity selected from the session trust set.
    pub key_id: String,
    /// Stable identifier of the bearer record in State.
    pub session_id: String,
    /// Credential-root epoch recorded when State minted the bearer.
    pub authorization_epoch: u64,
    /// Credential root and its current persona resolution.
    pub subject: SessionSubject,
    /// Independently checked capabilities.
    pub scopes: Vec<SessionScope>,
    /// Writer-attested mint time.
    pub issued_ms: u64,
    /// Natural expiry; durable revocation may refuse it earlier.
    pub expires_ms: u64,
}

impl AuthorizedSessionClaims {
    /// Whether this bearer carries `scope`.
    #[must_use]
    pub fn has_scope(&self, scope: SessionScope) -> bool {
        self.scopes.contains(&scope)
    }
}

#[derive(serde::Serialize, serde::Deserialize)]
struct AuthorizedWirePayload {
    issuer: String,
    key_id: String,
    session_id: String,
    authorization_epoch: u64,
    #[serde(flatten)]
    subject: WireSubject,
    scopes: Vec<String>,
    issued_ms: u64,
    expires_ms: u64,
}

fn authorized_session_canonical(payload: &AuthorizedWirePayload) -> Vec<u8> {
    let body = serde_json::to_string(payload)
        .expect("AuthorizedWirePayload serializes (no non-finite floats)");
    let mut bytes = Vec::with_capacity(AUTHORIZED_SESSION_DOMAIN_PREFIX.len() + body.len());
    bytes.extend_from_slice(AUTHORIZED_SESSION_DOMAIN_PREFIX);
    bytes.extend_from_slice(body.as_bytes());
    bytes
}

/// Mints a signed bearer bound to the durable record State already accepted.
///
/// The caller obtains `session_id` and `authorization_epoch` from the exact
/// State mint command/receipt before signing. This function never invents
/// either authority fact and performs no storage I/O.
///
/// # Panics
///
/// Panics for an empty session identity or scope set; neither can represent an
/// authorizable bearer.
#[must_use]
pub fn mint_authorized_session(
    signer: &SessionSigner,
    session_id: &str,
    authorization_epoch: u64,
    subject: &SessionSubject,
    scopes: &[SessionScope],
    now_ms: u64,
    ttl_ms: u64,
) -> String {
    assert!(!session_id.is_empty(), "authorized session id is not empty");
    assert!(
        !scopes.is_empty(),
        "mint_authorized_session requires at least one scope"
    );
    let payload = AuthorizedWirePayload {
        issuer: SessionRole::ISSUER.to_owned(),
        key_id: signer.identity().key_id().to_owned(),
        session_id: session_id.to_owned(),
        authorization_epoch,
        subject: subject.into(),
        scopes: scopes
            .iter()
            .map(|scope| scope.as_str().to_owned())
            .collect(),
        issued_ms: now_ms,
        expires_ms: now_ms.saturating_add(ttl_ms),
    };
    let body = serde_json::to_string(&payload)
        .expect("AuthorizedWirePayload serializes (no non-finite floats)");
    let signature = signer.sign(&authorized_session_canonical(&payload));
    format!(
        "{}.{}",
        URL_SAFE_NO_PAD.encode(body.as_bytes()),
        URL_SAFE_NO_PAD.encode(signature)
    )
}

/// Verifies only the signed and time-bounded half of a State-backed bearer.
///
/// A successful return is not authorization. The caller must derive the State
/// principal from [`AuthorizedSessionClaims::subject`], then require the
/// durable bearer record to be live and minted at
/// [`AuthorizedSessionClaims::authorization_epoch`]. Keeping this function
/// pure prevents a crypto primitive from hiding an unbounded network call.
#[must_use]
pub fn verify_authorized_session(
    signer_public_key: &[u8],
    token: &str,
    now_ms: u64,
) -> Option<AuthorizedSessionClaims> {
    let trusted_signers =
        RoleTrustSet::<SessionRole>::from_public_keys(vec![signer_public_key.to_vec()]).ok()?;
    verify_authorized_session_with_trust(&trusted_signers, token, now_ms)
}

/// Verifies a State-backed bearer against current and retired session keys.
#[must_use]
pub fn verify_authorized_session_with_trust(
    trusted_signers: &RoleTrustSet<SessionRole>,
    token: &str,
    now_ms: u64,
) -> Option<AuthorizedSessionClaims> {
    let (payload_b64, signature_b64) = token.split_once('.')?;
    if payload_b64.is_empty() || signature_b64.is_empty() || signature_b64.contains('.') {
        return None;
    }
    let payload_bytes = URL_SAFE_NO_PAD.decode(payload_b64).ok()?;
    let signature = URL_SAFE_NO_PAD.decode(signature_b64).ok()?;
    let payload: AuthorizedWirePayload = serde_json::from_slice(&payload_bytes).ok()?;
    if payload.session_id.is_empty() || now_ms >= payload.expires_ms {
        return None;
    }
    let scopes = payload
        .scopes
        .iter()
        .map(|scope| SessionScope::from_str(scope))
        .collect::<Option<Vec<_>>>()?;
    if scopes.is_empty()
        || payload.issuer != SessionRole::ISSUER
        || !trusted_signers.verify(
            &payload.key_id,
            &authorized_session_canonical(&payload),
            &signature,
        )
    {
        return None;
    }
    Some(AuthorizedSessionClaims {
        issuer: payload.issuer,
        key_id: payload.key_id,
        session_id: payload.session_id,
        authorization_epoch: payload.authorization_epoch,
        subject: payload.subject.into(),
        scopes,
        issued_ms: payload.issued_ms,
        expires_ms: payload.expires_ms,
    })
}

/// Best-effort, in-memory logout denylist for session tokens.
///
/// Deliberately NOT durable: a stateless token's only revocation cost is the
/// window between logout and its natural expiry, bounded by the caller's own
/// TTL policy; losing this set on restart means a logged-out token near the
/// end of its TTL might verify again after a restart, which callers of this
/// module accept as the tradeoff for a session that needs no durable store.
pub struct RevokedTokens {
    /// Revoked token strings. A full-token set (not a derived "stable token
    /// id") — simplest correct shape, and the whole token is what
    /// [`verify_session`] has in hand to check.
    tokens: Mutex<HashSet<String>>,
}

impl RevokedTokens {
    /// An empty denylist.
    #[must_use]
    pub fn new() -> Self {
        Self {
            tokens: Mutex::new(HashSet::new()),
        }
    }

    /// Adds `token` to the denylist (logout). Idempotent.
    pub fn revoke(&self, token: &str) {
        if let Ok(mut tokens) = self.tokens.lock() {
            tokens.insert(token.to_owned());
        }
    }

    /// Whether `token` has been revoked.
    #[must_use]
    fn contains(&self, token: &str) -> bool {
        self.tokens
            .lock()
            .is_ok_and(|tokens| tokens.contains(token))
    }

    /// Evict every denylisted token that could never verify again anyway: a
    /// token past its OWN embedded `expires_ms` already fails
    /// [`verify_session`]'s expiry check regardless of denylist membership,
    /// so keeping it here forever only grows the set. A token that fails to
    /// even PARSE (`decode_session_payload` returns `None` — never
    /// produced by [`mint_session`], but [`Self::revoke`] accepts whatever
    /// string a caller posts) can likewise never match a real session and is
    /// dropped too. Bounds this set's memory to sessions logged out within
    /// their own TTL window, not the lifetime of the process.
    pub fn reap(&self, now_ms: u64) {
        if let Ok(mut tokens) = self.tokens.lock() {
            tokens.retain(|token| {
                decode_session_payload(token)
                    .is_some_and(|(payload, _, _)| now_ms < payload.expires_ms)
            });
        }
    }

    /// Count of denylisted tokens currently stored — test-only.
    #[cfg(test)]
    fn len(&self) -> usize {
        self.tokens.lock().map_or(0, |t| t.len())
    }
}

impl Default for RevokedTokens {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::pedantic, clippy::nursery, missing_docs)]

    use super::*;

    const NOW: u64 = 1_700_000_000_000;
    /// Arbitrary TTL for tests that don't exercise expiry itself.
    const TEST_TTL_MS: u64 = 8 * 60 * 60 * 1000;

    fn test_signer() -> SessionSigner {
        SessionSigner::from_key_bytes(&[7u8; 32]).expect("valid 32-byte ed25519 key material")
    }

    fn persona_subject(persona_id: &str) -> SessionSubject {
        SessionSubject::Persona {
            persona_id: persona_id.to_owned(),
        }
    }

    fn mint_persona_session(
        signer: &SessionSigner,
        persona_id: &str,
        now_ms: u64,
        ttl_ms: u64,
    ) -> String {
        mint_session(
            signer,
            &persona_subject(persona_id),
            &[SessionScope::ExplorerRead],
            now_ms,
            ttl_ms,
        )
    }

    fn mint_authorized_persona(signer: &SessionSigner) -> String {
        mint_authorized_session(
            signer,
            "session-1",
            7,
            &persona_subject("persona-1"),
            &[SessionScope::ExplorerRead, SessionScope::AgentTurn],
            NOW,
            TEST_TTL_MS,
        )
    }

    #[test]
    fn authorized_bearer_round_trips_every_state_binding() {
        let signer = test_signer();
        let token = mint_authorized_persona(&signer);
        let claims = verify_authorized_session(&signer.public_key_bytes(), &token, NOW)
            .expect("fresh State-backed bearer verifies cryptographically");
        assert_eq!(claims.session_id, "session-1");
        assert_eq!(claims.authorization_epoch, 7);
        assert_eq!(claims.subject, persona_subject("persona-1"));
        assert!(claims.has_scope(SessionScope::ExplorerRead));
        assert!(claims.has_scope(SessionScope::AgentTurn));
        assert_eq!(claims.issued_ms, NOW);
        assert_eq!(claims.expires_ms, NOW + TEST_TTL_MS);
    }

    #[test]
    fn authorized_wallet_keeps_wallet_as_its_independent_root() {
        let signer = test_signer();
        let subject = SessionSubject::Wallet {
            wallet_address: "0xabc".into(),
            persona_id: Some("persona-1".into()),
        };
        let token = mint_authorized_session(
            &signer,
            "wallet-session",
            3,
            &subject,
            &[SessionScope::WalletManage, SessionScope::ExplorerRead],
            NOW,
            TEST_TTL_MS,
        );
        let claims = verify_authorized_session(&signer.public_key_bytes(), &token, NOW)
            .expect("wallet bearer verifies");
        assert_eq!(claims.subject.wallet_address(), Some("0xabc"));
        assert_eq!(claims.subject.persona_id(), Some("persona-1"));
        assert_eq!(claims.authorization_epoch, 3);
    }

    #[test]
    fn every_authority_field_is_covered_by_the_signature() {
        let signer = test_signer();
        let token = mint_authorized_persona(&signer);
        let (payload_b64, signature) = token.split_once('.').expect("token shape");
        let original: serde_json::Value =
            serde_json::from_slice(&URL_SAFE_NO_PAD.decode(payload_b64).expect("payload base64"))
                .expect("payload json");
        let mutations = [
            ("session_id", serde_json::json!("session-2")),
            ("authorization_epoch", serde_json::json!(8)),
            ("persona_id", serde_json::json!("persona-2")),
            ("scopes", serde_json::json!(["wallet-manage"])),
            ("issued_ms", serde_json::json!(NOW + 1)),
            ("expires_ms", serde_json::json!(NOW + TEST_TTL_MS + 1)),
        ];
        for (field, replacement) in mutations {
            let mut changed = original.clone();
            changed[field] = replacement;
            let forged = format!(
                "{}.{}",
                URL_SAFE_NO_PAD.encode(serde_json::to_vec(&changed).expect("json")),
                signature
            );
            assert!(
                verify_authorized_session(&signer.public_key_bytes(), &forged, NOW).is_none(),
                "changing {field} kept the signature valid"
            );
        }
    }

    #[test]
    fn valid_signatures_with_unknown_role_identity_fail_closed() {
        let signer = test_signer();
        let token = mint_authorized_persona(&signer);
        let (payload_b64, _) = token.split_once('.').expect("token shape");
        let payload_bytes = URL_SAFE_NO_PAD.decode(payload_b64).expect("payload base64");
        for (issuer, key_id) in [
            (Some("polychrome.control.approval"), None),
            (None, Some("unknown-key-id")),
        ] {
            let mut payload: AuthorizedWirePayload =
                serde_json::from_slice(&payload_bytes).expect("payload json");
            if let Some(issuer) = issuer {
                payload.issuer = issuer.to_owned();
            }
            if let Some(key_id) = key_id {
                payload.key_id = key_id.to_owned();
            }
            let body = serde_json::to_vec(&payload).expect("payload json");
            let signature = signer.sign(&authorized_session_canonical(&payload));
            let forged = format!(
                "{}.{}",
                URL_SAFE_NO_PAD.encode(body),
                URL_SAFE_NO_PAD.encode(signature)
            );
            assert!(verify_authorized_session(&signer.public_key_bytes(), &forged, NOW).is_none());
        }
    }

    #[test]
    fn v2_and_v3_are_never_cross_accepted() {
        let signer = test_signer();
        let v2 = mint_persona_session(&signer, "persona-1", NOW, TEST_TTL_MS);
        let v3 = mint_authorized_persona(&signer);
        assert!(verify_authorized_session(&signer.public_key_bytes(), &v2, NOW).is_none());
        assert!(
            verify_session(&signer.public_key_bytes(), &v3, NOW, &RevokedTokens::new()).is_none()
        );
    }

    #[test]
    fn authorized_bearer_expiry_and_malformed_shapes_fail_closed() {
        let signer = test_signer();
        let token = mint_authorized_session(
            &signer,
            "session-1",
            0,
            &persona_subject("persona-1"),
            &[SessionScope::ExplorerRead],
            NOW,
            1,
        );
        assert!(verify_authorized_session(&signer.public_key_bytes(), &token, NOW).is_some());
        assert!(verify_authorized_session(&signer.public_key_bytes(), &token, NOW + 1).is_none());
        for malformed in ["", ".", "a.b.c", "not-base64.signature"] {
            assert!(
                verify_authorized_session(&signer.public_key_bytes(), malformed, NOW).is_none()
            );
        }
    }

    // ---- session token: tamper / expiry / domain confusion ------------------

    #[test]
    fn tampered_payload_is_rejected() {
        let signer = test_signer();
        let denylist = RevokedTokens::new();
        let token = mint_persona_session(&signer, "persona-1", NOW, TEST_TTL_MS);
        let (payload_b64, sig_b64) = token.split_once('.').expect("shape");
        let mut payload = URL_SAFE_NO_PAD.decode(payload_b64).expect("decodes");
        // Flip a byte inside the persona_id string.
        let last = payload.len() - 1;
        payload[last] ^= 0xFF;
        let tampered = format!("{}.{sig_b64}", URL_SAFE_NO_PAD.encode(payload));

        assert!(
            verify_session(&signer.public_key_bytes(), &tampered, NOW, &denylist).is_none(),
            "a tampered payload must not verify"
        );
    }

    #[test]
    fn tampered_signature_is_rejected() {
        let signer = test_signer();
        let denylist = RevokedTokens::new();
        let token = mint_persona_session(&signer, "persona-1", NOW, TEST_TTL_MS);
        let (payload_b64, sig_b64) = token.split_once('.').expect("shape");
        let mut sig = URL_SAFE_NO_PAD.decode(sig_b64).expect("decodes");
        let last = sig.len() - 1;
        sig[last] ^= 0xFF;
        let tampered = format!("{payload_b64}.{}", URL_SAFE_NO_PAD.encode(sig));

        assert!(
            verify_session(&signer.public_key_bytes(), &tampered, NOW, &denylist).is_none(),
            "a tampered signature must not verify"
        );
    }

    #[test]
    fn expired_session_is_rejected() {
        let signer = test_signer();
        let denylist = RevokedTokens::new();
        let token = mint_persona_session(&signer, "persona-1", NOW, 1_000);

        assert!(
            verify_session(&signer.public_key_bytes(), &token, NOW + 1_000, &denylist).is_none(),
            "now_ms == expires_ms must already be rejected (boundary, not just past it)"
        );
        assert!(
            verify_session(&signer.public_key_bytes(), &token, NOW + 999, &denylist).is_some(),
            "one ms before expiry must still verify"
        );
    }

    #[test]
    fn domain_confusion_is_rejected() {
        // A signature minted from the same raw key over a non-session message (the
        // `approval_response` family's canonical shape) must never verify as
        // a session token — proves the domain-separation prefix actually
        // separates artifact kinds, not just that signatures verify at all.
        let signer = test_signer();
        let denylist = RevokedTokens::new();
        let (payload, signature, _pk) = crate::approval::response_payload(
            "req-1",
            "some_tool",
            "{}",
            "",
            true,
            false,
            &[],
            "persona-1",
            "",
            "default",
            "",
            "",
            "conv-1",
            "nonce-1",
            "",
            &signer.relabel_for_test(),
        );
        let _ = payload; // the full approval payload is irrelevant here
        let forged = format!(
            "{}.{}",
            URL_SAFE_NO_PAD.encode(
                serde_json::json!({
                    "issuer": SessionRole::ISSUER,
                    "key_id": signer.identity().key_id(),
                    "sub_kind": "persona",
                    "persona_id": "persona-1",
                    "scopes": ["explorer-read"],
                    "issued_ms": NOW,
                    "expires_ms": NOW + TEST_TTL_MS,
                })
                .to_string()
            ),
            URL_SAFE_NO_PAD.encode(signature)
        );

        assert!(
            verify_session(&signer.public_key_bytes(), &forged, NOW, &denylist).is_none(),
            "an approval_response signature must not verify as a session token"
        );
    }

    #[test]
    fn a_v1_session_token_from_before_adr_0007_no_longer_verifies() {
        // Hand-built under the OLD domain prefix + payload shape
        // (`polychrome.explorer-session.v1\0`, `{persona_id, issued_ms,
        // expires_ms}`, no scopes/sub_kind) — this is what a live session
        // minted before this change looks like. It must fail closed under
        // the new verifier rather than silently mis-parsing into some
        // default subject/scope, per the no-legacy-code, no-dual-accept
        // choice documented on `SESSION_DOMAIN_PREFIX`.
        let signer = test_signer();
        let denylist = RevokedTokens::new();
        let old_prefix = b"polychrome.explorer-session.v1\0";
        let old_body = serde_json::json!({
            "persona_id": "persona-1",
            "issued_ms": NOW,
            "expires_ms": NOW + TEST_TTL_MS,
        })
        .to_string();
        let mut signed_bytes = Vec::new();
        signed_bytes.extend_from_slice(old_prefix);
        signed_bytes.extend_from_slice(old_body.as_bytes());
        let signature = signer.sign(&signed_bytes);
        let old_token = format!(
            "{}.{}",
            URL_SAFE_NO_PAD.encode(old_body.as_bytes()),
            URL_SAFE_NO_PAD.encode(signature)
        );

        assert!(
            verify_session(&signer.public_key_bytes(), &old_token, NOW, &denylist).is_none(),
            "a pre-ADR-0007 v1 session token must not verify under the new prefix/shape"
        );
    }

    // ---- wallet subject + scopes ------------------------------------------

    #[test]
    fn a_wallet_session_with_no_linked_persona_verifies_wallet_manage_only() {
        let signer = test_signer();
        let denylist = RevokedTokens::new();
        let subject = SessionSubject::Wallet {
            wallet_address: "0xabc".to_owned(),
            persona_id: None,
        };
        let token = mint_session(
            &signer,
            &subject,
            &[SessionScope::WalletManage],
            NOW,
            TEST_TTL_MS,
        );

        let claims = verify_session(&signer.public_key_bytes(), &token, NOW, &denylist)
            .expect("a fresh wallet-only session verifies");
        assert_eq!(claims.subject.persona_id(), None);
        assert_eq!(claims.subject.wallet_address(), Some("0xabc"));
        assert!(claims.has_scope(SessionScope::WalletManage));
        assert!(!claims.has_scope(SessionScope::ExplorerRead));
    }

    #[test]
    fn a_wallet_session_with_a_linked_persona_can_carry_both_scopes() {
        let signer = test_signer();
        let denylist = RevokedTokens::new();
        let subject = SessionSubject::Wallet {
            wallet_address: "0xabc".to_owned(),
            persona_id: Some("persona-1".to_owned()),
        };
        let token = mint_session(
            &signer,
            &subject,
            &[SessionScope::ExplorerRead, SessionScope::WalletManage],
            NOW,
            TEST_TTL_MS,
        );

        let claims =
            verify_session(&signer.public_key_bytes(), &token, NOW, &denylist).expect("verifies");
        assert_eq!(claims.subject.persona_id(), Some("persona-1"));
        assert!(claims.has_scope(SessionScope::ExplorerRead));
        assert!(claims.has_scope(SessionScope::WalletManage));
    }

    // ---- agent-turn scope --------------------------------------------------

    #[test]
    fn an_agent_turn_scope_round_trips_through_its_wire_string() {
        // Pins the wire string itself, not just the enum: `agent-turn` is what
        // a live token carries, so renaming the variant must not move it.
        let signer = test_signer();
        let denylist = RevokedTokens::new();
        let token = mint_session(
            &signer,
            &persona_subject("persona-1"),
            &[SessionScope::ExplorerRead, SessionScope::AgentTurn],
            NOW,
            TEST_TTL_MS,
        );
        let (payload_b64, _) = token.split_once('.').expect("shape");
        let payload = URL_SAFE_NO_PAD.decode(payload_b64).expect("decodes");
        let json: serde_json::Value = serde_json::from_slice(&payload).expect("json");
        assert_eq!(
            json["scopes"],
            serde_json::json!(["explorer-read", "agent-turn"]),
            "the on-the-wire scope string must be exactly `agent-turn`"
        );

        let claims =
            verify_session(&signer.public_key_bytes(), &token, NOW, &denylist).expect("verifies");
        assert!(claims.has_scope(SessionScope::AgentTurn));
    }

    #[test]
    fn explorer_read_alone_does_not_carry_agent_turn() {
        // The load-bearing one: a turn is a write that spends money, so a
        // read-only session must answer `false` for `AgentTurn` rather than
        // having it fall out of "holds any scope at all". ADR 0007's
        // independence rule lives or dies here.
        let signer = test_signer();
        let denylist = RevokedTokens::new();
        let token = mint_persona_session(&signer, "persona-1", NOW, TEST_TTL_MS);

        let claims =
            verify_session(&signer.public_key_bytes(), &token, NOW, &denylist).expect("verifies");
        assert!(claims.has_scope(SessionScope::ExplorerRead));
        assert!(
            !claims.has_scope(SessionScope::AgentTurn),
            "an explorer-read session must never imply turn dispatch"
        );
    }

    #[test]
    fn an_unrecognized_scope_string_fails_the_whole_token_closed() {
        // A hand-built payload with a scope string this binary doesn't
        // recognize (e.g. a scope a NEWER binary minted) must refuse the
        // whole token, not silently drop the unknown scope and verify with
        // whatever scopes it DOES recognize.
        let signer = test_signer();
        let denylist = RevokedTokens::new();
        let body = serde_json::json!({
            "issuer": SessionRole::ISSUER,
            "key_id": signer.identity().key_id(),
            "sub_kind": "persona",
            "persona_id": "persona-1",
            "scopes": ["explorer-read", "some-future-scope"],
            "issued_ms": NOW,
            "expires_ms": NOW + TEST_TTL_MS,
        })
        .to_string();
        let mut signed_bytes = Vec::new();
        signed_bytes.extend_from_slice(SESSION_DOMAIN_PREFIX);
        signed_bytes.extend_from_slice(body.as_bytes());
        let signature = signer.sign(&signed_bytes);
        let token = format!(
            "{}.{}",
            URL_SAFE_NO_PAD.encode(body.as_bytes()),
            URL_SAFE_NO_PAD.encode(signature)
        );

        assert!(
            verify_session(&signer.public_key_bytes(), &token, NOW, &denylist).is_none(),
            "an unrecognized scope must refuse the whole token, not drop just that scope"
        );
    }

    #[test]
    fn a_session_minted_before_rotation_verifies_only_with_historical_trust() {
        let retired = SessionSigner::from_seed(91);
        let current = SessionSigner::from_seed(92);
        let token = mint_authorized_session(
            &retired,
            "session-before-rotation",
            4,
            &persona_subject("persona-1"),
            &[SessionScope::ExplorerRead],
            NOW,
            TEST_TTL_MS,
        );
        let current_only = RoleTrustSet::<SessionRole>::current(&current);
        let historical =
            RoleTrustSet::<SessionRole>::checked(vec![current.identity(), retired.identity()])
                .expect("valid rotation history");

        assert!(verify_authorized_session_with_trust(&current_only, &token, NOW).is_none());
        assert!(verify_authorized_session_with_trust(&historical, &token, NOW).is_some());
    }

    #[test]
    #[should_panic(expected = "at least one scope")]
    fn mint_session_panics_on_an_empty_scope_list() {
        let signer = test_signer();
        let _ = mint_session(
            &signer,
            &persona_subject("persona-1"),
            &[],
            NOW,
            TEST_TTL_MS,
        );
    }

    // ---- reaper ---------------------------------------------------------------

    #[test]
    fn reap_evicts_an_expired_denylisted_token_but_keeps_a_live_one() {
        let signer = test_signer();
        let denylist = RevokedTokens::new();
        let expired = mint_persona_session(&signer, "persona-1", NOW, 1_000);
        let live = mint_persona_session(&signer, "persona-2", NOW, TEST_TTL_MS);
        denylist.revoke(&expired);
        denylist.revoke(&live);
        assert_eq!(
            denylist.len(),
            2,
            "both revoked tokens are stored before reap"
        );

        // `expired`'s own embedded `expires_ms` (NOW + 1_000) has passed at
        // this instant; `live`'s (NOW + TEST_TTL_MS) has not.
        denylist.reap(NOW + 1_000);

        assert_eq!(
            denylist.len(),
            1,
            "reap must drop the token whose own expiry has passed and keep the still-live one"
        );
    }

    #[test]
    fn reap_drops_an_unparseable_denylisted_entry() {
        // `revoke` accepts whatever string a caller posts (no `mint_session`
        // origin check), so the denylist can hold garbage a malicious or
        // buggy caller revoked. Such an entry can never match a real session
        // anyway, so `reap` treats "fails to parse" the same as "expired".
        let denylist = RevokedTokens::new();
        denylist.revoke("not-a-real-session-token");
        assert_eq!(denylist.len(), 1);

        denylist.reap(NOW);

        assert_eq!(
            denylist.len(),
            0,
            "an unparseable entry is reaped unconditionally"
        );
    }
}