vouch-core 4.1.0

Vouch Protocol canonical core: JCS canonicalization, Ed25519 + ML-DSA proofs, did:key/multikey, Data Integrity (eddsa-jcs-2022), credentials, delegation, revocation. One byte-exact implementation shared by every language SDK via WASM and UniFFI/C-FFI.
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
1592
1593
1594
1595
1596
1597
//! SessionVoucher verification and the guard's freshness checks, as the
//! Python reference decides them (`vouch.heartbeat.voucher`,
//! `vouch.heartbeat.trust`, `vouch.guard._freshness`).
//!
//! A SessionVoucher is a short-lived credential a heartbeat validator issues
//! to an agent that keeps proving it is live. A verifier checks it was issued
//! by a validator it trusts (one, or M of N), is inside its window, was not
//! issued by the agent to itself, and that its trust, which decays with time,
//! still reaches the threshold the action needs.
//!
//! Nothing here does I/O: the host passes the keys, the clock and what its
//! authority source said.

use std::collections::BTreeMap;

use serde_json::{json, Map, Value};

use crate::authority_state::{self, FreshnessRule, MAX_AUTHORITY_EPOCH};
use crate::data_integrity;
use crate::error::{CoreError, Result};
use crate::grant_chain::{py_repr, py_repr_float};
use crate::time::{check_clock_skew, parse_protocol_time_ns};

/// The credential type every SessionVoucher carries.
pub const SESSION_VOUCHER_TYPE: &str = "SessionVoucher";
/// At most this many proofs on a voucher, and copies in a quorum check.
pub const MAX_VOUCHER_PROOFS: usize = 64;
/// The guard's refusal when no live session backs the call.
pub const REASON_NO_SESSION: &str = "no live session";
/// The guard's refusal when the voucher's decayed trust is too low.
pub const REASON_LOW_TRUST: &str = "trust below threshold";
/// The guard's refusal when the caller's authority is not fresh.
pub const REASON_AUTHORITY: &str = "authority not fresh";

const MICROS: i128 = 1_000_000;

fn bad(msg: impl Into<String>) -> CoreError {
    CoreError::Json(msg.into())
}

/// Python `datetime` precision: microseconds, later digits dropped.
fn micros_of(text: &str) -> Result<i128> {
    Ok(parse_protocol_time_ns(text)?.div_euclid(1000))
}

/// `float(x)` as Python reads a JSON value: a number, a boolean, or text
/// that spells a number. None for anything else.
fn py_float(v: &Value) -> Option<f64> {
    match v {
        Value::Number(n) => n.as_f64(),
        Value::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),
        // Rust reads "inf", "infinity" and "nan" (any case, signed) as
        // Python's float() does.
        Value::String(s) => s.trim().parse::<f64>().ok(),
        _ => None,
    }
}

fn float_member(subject: &Map<String, Value>, name: &str) -> Result<f64> {
    match subject.get(name) {
        None => Err(bad(format!(
            "credentialSubject.{name} must be a number: '{name}'"
        ))),
        Some(v) => py_float(v).ok_or_else(|| {
            bad(format!(
                "credentialSubject.{name} must be a number: could not convert {} to float",
                py_repr(Some(v))
            ))
        }),
    }
}

/// What [`compute_trust_at`] reads from a voucher.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TrustInputs {
    pub initial_trust: f64,
    pub decay_lambda: f64,
    /// `validFrom`, in microseconds since the epoch.
    pub issued_at_us: i128,
}

/// The trust parameters of a voucher, refused as the reference refuses them
/// (the error text is the reference's `TrustEntropyError`).
pub fn trust_inputs(voucher: &Value) -> Result<TrustInputs> {
    let obj = voucher
        .as_object()
        .ok_or_else(|| bad("session_voucher must be a dict"))?;
    let types: Vec<Value> = match obj.get("type") {
        None => Vec::new(),
        Some(Value::String(s)) => vec![Value::String(s.clone())],
        Some(Value::Array(a)) => a.clone(),
        Some(other) => vec![other.clone()],
    };
    if !types
        .iter()
        .any(|t| t.as_str() == Some(SESSION_VOUCHER_TYPE))
    {
        return Err(bad(format!(
            "credential type must include {SESSION_VOUCHER_TYPE}, got {}",
            py_repr(Some(&Value::Array(types)))
        )));
    }
    let subject = obj
        .get("credentialSubject")
        .and_then(Value::as_object)
        .ok_or_else(|| bad("credentialSubject is required"))?;
    let initial_trust = float_member(subject, "initialTrust")?;
    let decay_lambda = float_member(subject, "decayLambda")?;
    for (name, value) in [
        ("initialTrust", initial_trust),
        ("decayLambda", decay_lambda),
    ] {
        if !value.is_finite() {
            return Err(bad(format!(
                "{name} must be a finite number, got {}",
                py_repr_float(value)
            )));
        }
    }
    if initial_trust < 0.0 {
        return Err(bad(format!(
            "initialTrust must be non-negative, got {}",
            py_repr_float(initial_trust)
        )));
    }
    if decay_lambda < 0.0 {
        return Err(bad(format!(
            "decayLambda must be non-negative, got {}",
            py_repr_float(decay_lambda)
        )));
    }
    let valid_from = obj.get("validFrom");
    let truthy = match valid_from {
        None | Some(Value::Null) | Some(Value::Bool(false)) => false,
        Some(Value::String(s)) => !s.is_empty(),
        Some(Value::Number(n)) => n.as_f64() != Some(0.0),
        Some(Value::Array(a)) => !a.is_empty(),
        Some(Value::Object(o)) => !o.is_empty(),
        Some(Value::Bool(true)) => true,
    };
    if !truthy {
        return Err(bad("validFrom is required"));
    }
    let text = valid_from
        .and_then(Value::as_str)
        .ok_or_else(|| bad("malformed validFrom: not a protocol time"))?;
    let issued_at_us =
        micros_of(text).map_err(|_| bad(format!("malformed validFrom: {}", not_a_time(text))))?;
    Ok(TrustInputs {
        initial_trust,
        decay_lambda,
        issued_at_us,
    })
}

/// Elapsed seconds from `validFrom` to `at_us`, never below zero.
fn elapsed_seconds(inputs: &TrustInputs, at_us: i128) -> f64 {
    let elapsed = (at_us - inputs.issued_at_us) as f64 / MICROS as f64;
    if elapsed < 0.0 {
        0.0
    } else {
        elapsed
    }
}

fn trust_of(inputs: &TrustInputs, elapsed: f64) -> f64 {
    let exponent = -inputs.decay_lambda * elapsed;
    if exponent < -700.0 {
        return 0.0;
    }
    inputs.initial_trust * det_exp(exponent)
}

/// e^x computed the same way on every target.
///
/// `f64::exp` calls the platform's math library: the C library on native
/// builds, a different implementation on wasm32, and the two can differ in
/// the last bit. This is the FreeBSD / musl `exp` (fdlibm e_exp.c, under 1
/// ulp of error), written with only IEEE 754 addition, subtraction,
/// multiplication, division and exact bit operations, so every build of the
/// core (Python, Go, the C ABI and the WebAssembly the TypeScript SDK runs)
/// gets the same bits.
fn det_exp(x: f64) -> f64 {
    const HALF: [f64; 2] = [0.5, -0.5];
    const LN2HI: f64 = 6.931_471_803_691_238_164_90e-01; // 0x3fe62e42 fee00000
    const LN2LO: f64 = 1.908_214_929_270_587_700_02e-10; // 0x3dea39ef 35793c76
    const INVLN2: f64 = 1.442_695_040_888_963_387_00e+00; // 0x3ff71547 652b82fe
    const P1: f64 = 1.666_666_666_666_660_190_37e-01; // 0x3FC55555 5555553E
    const P2: f64 = -2.777_777_777_701_559_338_42e-03; // 0xBF66C16C 16BEBD93
    const P3: f64 = 6.613_756_321_437_934_361_17e-05; // 0x3F11566A AF25DE2C
    const P4: f64 = -1.653_390_220_546_525_153_90e-06; // 0xBEBBBD41 C5D26BF1
    const P5: f64 = 4.138_136_797_057_238_460_39e-08; // 0x3E663769 72BEA4D0
    let x1p1023 = f64::from_bits(0x7fe0_0000_0000_0000);

    let mut x = x;
    let mut hx = (x.to_bits() >> 32) as u32;
    let sign = (hx >> 31) as i32;
    hx &= 0x7fff_ffff;

    // Special cases: NaN, overflow, underflow.
    if hx >= 0x4086_232b {
        if x.is_nan() {
            return x;
        }
        if x > 709.782_712_893_383_973_096 {
            return x * x1p1023;
        }
        if x < -745.133_219_101_941_108_42 {
            return 0.0;
        }
    }

    // Argument reduction: x = k*ln2 + r, |r| <= 0.5*ln2.
    let (hi, lo, k): (f64, f64, i32);
    if hx > 0x3fd6_2e42 {
        if hx >= 0x3ff0_a2b2 {
            k = (INVLN2 * x + HALF[sign as usize]) as i32;
        } else {
            k = 1 - sign - sign;
        }
        hi = x - k as f64 * LN2HI;
        lo = k as f64 * LN2LO;
        x = hi - lo;
    } else if hx > 0x3e30_0000 {
        k = 0;
        hi = x;
        lo = 0.0;
    } else {
        return 1.0 + x;
    }

    let xx = x * x;
    let c = x - xx * (P1 + xx * (P2 + xx * (P3 + xx * (P4 + xx * P5))));
    let y = 1.0 + (x * c / (2.0 - c) - lo + hi);
    if k == 0 {
        y
    } else {
        det_scalbn(y, k)
    }
}

/// x * 2^n, exactly as musl's scalbn does it.
fn det_scalbn(x: f64, mut n: i32) -> f64 {
    let x1p1023 = f64::from_bits(0x7fe0_0000_0000_0000);
    let x1p53 = f64::from_bits(0x4340_0000_0000_0000);
    let x1p_1022 = f64::from_bits(0x0010_0000_0000_0000);
    let mut y = x;
    if n > 1023 {
        y *= x1p1023;
        n -= 1023;
        if n > 1023 {
            y *= x1p1023;
            n -= 1023;
            if n > 1023 {
                n = 1023;
            }
        }
    } else if n < -1022 {
        // Keep the final n below -53, so the subnormal range is not rounded twice.
        y *= x1p_1022 * x1p53;
        n += 1022 - 53;
        if n < -1022 {
            y *= x1p_1022 * x1p53;
            n += 1022 - 53;
            if n < -1022 {
                n = -1022;
            }
        }
    }
    y * f64::from_bits(((0x3ff + n) as u64) << 52)
}

/// The voucher's trust at `at_us`: initialTrust * exp(-decayLambda *
/// seconds since validFrom) (Specification 11.5).
pub fn compute_trust_at(voucher: &Value, at_us: i128) -> Result<f64> {
    let inputs = trust_inputs(voucher)?;
    Ok(trust_of(&inputs, elapsed_seconds(&inputs, at_us)))
}

/// The trust a voucher has at a moment, and whether it reaches a threshold.
#[derive(Debug, Clone, PartialEq)]
pub struct TrustEvaluation {
    pub trust: f64,
    pub threshold: f64,
    pub passed: bool,
    pub elapsed_seconds: f64,
    pub initial_trust: f64,
    pub decay_lambda: f64,
    pub evaluated_at_us: i128,
}

/// [`compute_trust_at`] with the parameters that gave it.
pub fn evaluate_trust(voucher: &Value, threshold: f64, at_us: i128) -> Result<TrustEvaluation> {
    if threshold < 0.0 {
        return Err(bad(format!(
            "threshold must be non-negative, got {}",
            py_repr_float(threshold)
        )));
    }
    let inputs = trust_inputs(voucher)?;
    let elapsed = elapsed_seconds(&inputs, at_us);
    let trust = trust_of(&inputs, elapsed);
    Ok(TrustEvaluation {
        trust,
        threshold,
        passed: trust >= threshold,
        elapsed_seconds: elapsed,
        initial_trust: inputs.initial_trust,
        decay_lambda: inputs.decay_lambda,
        evaluated_at_us: at_us,
    })
}

// ---------------------------------------------------------------------------
// Keys
// ---------------------------------------------------------------------------

/// An Ed25519 key given as text or JSON: a `did:key` DID (fragment allowed),
/// a Multikey, or a JWK (object or text). Also returns the DID when the key
/// was given as a did:key. None when it is none of these.
pub fn key_from_json(v: &Value) -> Option<(Vec<u8>, Option<String>)> {
    if let Some(s) = v.as_str() {
        if s.starts_with("did:key:") {
            let did = s.split('#').next().unwrap_or(s).to_string();
            return authority_state::did_key_ed25519(&did).map(|k| (k, Some(did)));
        }
    }
    match crate::decision::key_entry_from_json(v) {
        crate::decision::KeyEntry::Ed25519(k) if k.len() == 32 => Some((k, None)),
        _ => None,
    }
}

/// The trusted validators, `{DID: key}` (a key may be null for a did:key,
/// whose key is read from the DID) or a list of did:key DIDs, as
/// `validator_key_map` reads them: every entry is a DID with a usable key,
/// the key given for a did:key is the key it carries, and no two validators
/// share a key.
pub fn validator_key_map(value: &Value) -> Result<Vec<(String, Vec<u8>)>> {
    let items: Vec<(String, Option<&Value>)> = match value {
        Value::Object(m) => m.iter().map(|(d, k)| (d.clone(), Some(k))).collect(),
        Value::Array(a) => a
            .iter()
            .map(|d| match d.as_str() {
                Some(s) => Ok((s.to_string(), None)),
                None => Err(bad(format!(
                    "expected validator {} is not a DID",
                    py_repr(Some(d))
                ))),
            })
            .collect::<Result<_>>()?,
        _ => {
            return Err(bad(
                "expected validators must be a {DID: key} mapping or a list of did:keys",
            ))
        }
    };
    if items.is_empty() {
        return Err(bad("expected validators must name at least one validator"));
    }
    let mut out: Vec<(String, Vec<u8>)> = Vec::new();
    for (did, given) in items {
        if !did.starts_with("did:") {
            return Err(bad(format!(
                "expected validator {} is not a DID",
                crate::grant_chain::py_repr_str(&did)
            )));
        }
        let own = if did.starts_with("did:key:") {
            authority_state::did_key_ed25519(&did)
        } else {
            None
        };
        let key = match given.filter(|g| !g.is_null()) {
            None => own.clone(),
            Some(g) => key_from_json(g).map(|(k, _)| k),
        };
        let Some(key) = key else {
            return Err(bad(format!(
                "no usable Ed25519 key for expected validator {did}"
            )));
        };
        if let Some(own) = &own {
            if own != &key {
                return Err(bad(format!(
                    "the key given for {did} is not the key that DID carries"
                )));
            }
        }
        if let Some((other, _)) = out.iter().find(|(_, k)| k == &key) {
            return Err(bad(format!("{did} and {other} share one key")));
        }
        out.push((did, key));
    }
    Ok(out)
}

// ---------------------------------------------------------------------------
// Verifying a voucher
// ---------------------------------------------------------------------------

fn issuer_list(voucher: &Map<String, Value>) -> Vec<Value> {
    match voucher.get("issuer") {
        Some(Value::Array(a)) => a.clone(),
        other => vec![other.cloned().unwrap_or(Value::Null)],
    }
}

fn proofs_of(voucher: &Map<String, Value>) -> Vec<Value> {
    match voucher.get("proof") {
        Some(Value::Array(a)) => a.clone(),
        other => vec![other.cloned().unwrap_or(Value::Null)],
    }
}

fn is_epoch(v: &Value) -> bool {
    v.as_u64().is_some_and(|e| e <= MAX_AUTHORITY_EPOCH as u64)
        || v.as_i64().is_some_and(|e| e == 0)
}

/// The shape checks both voucher checks share: Err(reason) or the window
/// in microseconds.
fn voucher_basics(voucher: &Value, at_us: i128) -> std::result::Result<(i128, i128), String> {
    let Some(obj) = voucher.as_object() else {
        return Err("voucher_malformed:not an object".into());
    };
    if let Err(e) = compute_trust_at(voucher, at_us) {
        return Err(format!("voucher_malformed:{}", short(&message(&e), 200)));
    }
    let until = match obj.get("validUntil") {
        Some(Value::String(s)) if !s.is_empty() => s,
        _ => return Err("voucher_malformed:validUntil is required".into()),
    };
    let from = obj.get("validFrom").and_then(Value::as_str).unwrap_or("");
    let read = |t: &str| micros_of(t).map_err(|_| not_a_time(t));
    let (from, until) = match read(from).and_then(|f| Ok((f, read(until)?))) {
        Ok(w) => w,
        Err(e) => return Err(format!("voucher_malformed:{}", short(&e, 200))),
    };
    if proofs_of(obj).len() > MAX_VOUCHER_PROOFS {
        return Err("voucher_malformed:too many proofs".into());
    }
    let subject = obj.get("credentialSubject");
    if let Some(epoch) = subject.and_then(|s| s.get("authorityEpoch")) {
        if !is_epoch(epoch) {
            return Err("voucher_malformed:authorityEpoch must be 0 to 2^53 - 1".into());
        }
    }
    if let Some(problem) = subject.and_then(authority_state::voucher_authority_problem) {
        return Err(format!("voucher_malformed:{problem}"));
    }
    Ok((from, until))
}

/// An error's own text, without the "json error: " prefix of its display.
fn message(e: &CoreError) -> String {
    match e {
        CoreError::Json(m) => m.clone(),
        other => other.to_string(),
    }
}

/// The reference's refusal for text that is not a protocol time.
fn not_a_time(text: &str) -> String {
    format!(
        "not a protocol time: {}",
        crate::grant_chain::py_repr_str(text)
    )
}

fn short(s: &str, n: usize) -> String {
    s.chars().take(n).collect()
}

fn subject_id(voucher: &Value) -> Option<&str> {
    voucher.get("credentialSubject")?.get("id")?.as_str()
}

/// True when the voucher's subject is one of its own issuers.
fn self_issued(voucher: &Map<String, Value>) -> bool {
    let subject = voucher
        .get("credentialSubject")
        .and_then(|s| s.get("id"))
        .and_then(Value::as_str);
    subject.is_some_and(|id| issuer_list(voucher).iter().any(|i| i.as_str() == Some(id)))
}

/// The keys the voucher's subject (the agent) signs with: the one the
/// caller passed, and the key a did:key subject carries.
fn subject_keys(voucher: Option<&Value>, subject_key: Option<&[u8]>) -> Vec<Vec<u8>> {
    let mut keys: Vec<Vec<u8>> = subject_key.map(|k| vec![k.to_vec()]).unwrap_or_default();
    if let Some(id) = voucher.and_then(subject_id) {
        if id.starts_with("did:key:") {
            let did = id.split('#').next().unwrap_or(id);
            if let Some(k) = authority_state::did_key_ed25519(did) {
                keys.push(k);
            }
        }
    }
    keys
}

/// True when one of `proofs` is an assertionMethod proof by one of the
/// issuers (by `only_did` when given) that verifies under `key`.
fn proof_verifies(
    unsigned: &Map<String, Value>,
    proofs: &[Value],
    issuers: &[Value],
    key: &[u8],
    only_did: Option<&str>,
) -> bool {
    for proof in proofs {
        let Some(p) = proof.as_object() else { continue };
        if p.get("proofPurpose").and_then(Value::as_str) != Some("assertionMethod") {
            continue;
        }
        let Some(vm) = p.get("verificationMethod").and_then(Value::as_str) else {
            continue;
        };
        let vm_did = vm.split('#').next().unwrap_or(vm);
        if !issuers.iter().any(|i| i.as_str() == Some(vm_did)) {
            continue;
        }
        if only_did.is_some_and(|d| d != vm_did) {
            continue;
        }
        let mut candidate = unsigned.clone();
        candidate.insert("proof".into(), proof.clone());
        if matches!(
            data_integrity::verify_proof(&Value::Object(candidate), key),
            Ok(true)
        ) {
            return true;
        }
    }
    false
}

fn window_reason(from: i128, until: i128, at_us: i128, skew: i128) -> Option<&'static str> {
    // `skew` is in nanoseconds (check_clock_skew).
    let skew_us = skew / 1000;
    if at_us - until > skew_us {
        return Some("voucher_expired");
    }
    if from - at_us > skew_us {
        return Some("voucher_not_yet_valid");
    }
    None
}

fn unsigned_of(voucher: &Map<String, Value>) -> Map<String, Value> {
    let mut out = voucher.clone();
    out.remove("proof");
    out
}

/// One validator's voucher: `Ok(Ok(()))`, `Ok(Err(reason))`, or an error
/// for a caller mistake (a skew outside 0..120). `validator_key` is the
/// key as given (a did:key DID, a Multikey or a JWK); `subject_key` is the
/// agent's own key (the key its credential verified under).
pub fn verify_session_voucher(
    voucher: &Value,
    validator_key: Option<&Value>,
    at_us: i128,
    clock_skew_seconds: i64,
    allow_self_issued: bool,
    subject_key: Option<&[u8]>,
) -> Result<std::result::Result<(), String>> {
    let skew = check_clock_skew(clock_skew_seconds)?;
    let agent_keys = subject_keys(Some(voucher), subject_key);
    let (from, until) = match voucher_basics(voucher, at_us) {
        Ok(w) => w,
        Err(reason) => return Ok(Err(reason)),
    };
    let obj = voucher.as_object().expect("checked by voucher_basics");
    let Some(given) = validator_key.filter(|k| !k.is_null()) else {
        return Ok(Err("voucher_unverified:no validator key supplied".into()));
    };
    let Some((key, key_did)) = key_from_json(given) else {
        return Ok(Err(
            "voucher_unverified:validator key is not an Ed25519 key".into(),
        ));
    };
    if !proof_verifies(
        &unsigned_of(obj),
        &proofs_of(obj),
        &issuer_list(obj),
        &key,
        key_did.as_deref(),
    ) {
        return Ok(Err("voucher_signature_invalid".into()));
    }
    if let Some(reason) = window_reason(from, until, at_us, skew) {
        return Ok(Err(reason.into()));
    }
    if !allow_self_issued && (self_issued(obj) || agent_keys.contains(&key)) {
        return Ok(Err("voucher_self_issued".into()));
    }
    Ok(Ok(()))
}

/// At least `threshold` of the trusted validators signed the voucher (one
/// voucher with a proof set, or a list of copies of one voucher, each with
/// its own proofs). Errors for a caller mistake: a skew outside 0..120, a
/// validator map that cannot be read, a threshold outside 1..N.
pub fn verify_session_voucher_quorum(
    voucher: &Value,
    validators: &[(String, Vec<u8>)],
    threshold: i64,
    at_us: i128,
    clock_skew_seconds: i64,
    subject_key: Option<&[u8]>,
) -> Result<std::result::Result<(), String>> {
    let skew = check_clock_skew(clock_skew_seconds)?;
    if threshold < 1 || threshold as usize > validators.len() {
        return Err(bad(format!(
            "threshold must be a whole number from 1 to {}",
            validators.len()
        )));
    }
    let copies: Vec<&Value> = match voucher {
        Value::Object(_) => vec![voucher],
        Value::Array(a) if !a.is_empty() => a.iter().collect(),
        _ => {
            return Ok(Err(
                "voucher_malformed:not an object or a list of copies".into()
            ))
        }
    };
    if copies.len() > MAX_VOUCHER_PROOFS || !copies.iter().all(|c| c.is_object()) {
        return Ok(Err(
            "voucher_malformed:copies must be 1 to 64 objects".into()
        ));
    }
    let base = copies[0];
    let (from, until) = match voucher_basics(base, at_us) {
        Ok(w) => w,
        Err(reason) => return Ok(Err(reason)),
    };
    let base_obj = base.as_object().expect("checked above");
    let unsigned = unsigned_of(base_obj);
    let canonical = crate::jcs::canonicalize(&Value::Object(unsigned.clone()));
    for other in &copies[1..] {
        let other = unsigned_of(other.as_object().expect("checked above"));
        if crate::jcs::canonicalize(&Value::Object(other)) != canonical {
            return Ok(Err("voucher_copies_differ".into()));
        }
    }
    if self_issued(base_obj) {
        return Ok(Err("voucher_self_issued".into()));
    }
    let mut agent_keys = subject_keys(None, subject_key);
    agent_keys.extend(subject_keys(Some(base), None));
    let proofs: Vec<Value> = copies
        .iter()
        .flat_map(|c| proofs_of(c.as_object().expect("checked above")))
        .collect();
    if proofs.len() > MAX_VOUCHER_PROOFS {
        return Ok(Err("voucher_malformed:too many proofs".into()));
    }
    let issuers = issuer_list(base_obj);
    let mut count = 0i64;
    for (did, key) in validators {
        if issuers.iter().any(|i| i.as_str() == Some(did.as_str()))
            && proof_verifies(&unsigned, &proofs, &issuers, key, Some(did))
        {
            if agent_keys.contains(key) {
                return Ok(Err("voucher_self_issued".into()));
            }
            count += 1;
        }
    }
    if count < threshold {
        return Ok(Err(format!("voucher_quorum_not_met:{count}<{threshold}")));
    }
    if let Some(reason) = window_reason(from, until, at_us, skew) {
        return Ok(Err(reason.into()));
    }
    Ok(Ok(()))
}

// ---------------------------------------------------------------------------
// The guard's freshness step
// ---------------------------------------------------------------------------

/// A refusal of the guard's freshness step: (reason, note for the log).
pub type Refusal = Option<(String, String)>;

fn note(text: &str) -> String {
    if text.chars().count() <= 120 {
        text.to_string()
    } else {
        format!("{}...", text.chars().take(117).collect::<String>())
    }
}

fn refuse(reason: &str, note_text: impl Into<String>) -> Refusal {
    Some((reason.to_string(), note_text.into()))
}

/// The session part of the guard's freshness step
/// (`vouch.guard._freshness._session_refusal`). `voucher` is None when the
/// call came with none. `validators` are the trusted validators' keys;
/// `issuer_key` is the key the caller's credential verified under.
#[allow(clippy::too_many_arguments)]
pub fn session_refusal(
    require_session: bool,
    trust_threshold: f64,
    voucher: Option<&Value>,
    issuer: &str,
    issuer_key: Option<&[u8]>,
    validators: &[(String, Vec<u8>)],
    quorum: i64,
    at_us: i128,
    clock_skew_seconds: i64,
) -> Refusal {
    let Some(voucher) = voucher else {
        return if require_session {
            refuse(REASON_NO_SESSION, "voucher_missing")
        } else {
            None
        };
    };
    if validators.is_empty() {
        return refuse(
            REASON_NO_SESSION,
            "voucher_unverified:no validator key supplied",
        );
    }
    let one = match voucher {
        Value::Array(a) if !a.is_empty() => &a[0],
        v => v,
    };
    let verdict = if validators.len() == 1 && quorum <= 1 && !voucher.is_array() {
        let (did, key) = &validators[0];
        let key_text =
            Value::String(crate::multikey::encode_ed25519_public(key).unwrap_or_default());
        verify_session_voucher(
            voucher,
            Some(&key_text),
            at_us,
            clock_skew_seconds,
            false,
            issuer_key,
        )
        .map(|r| {
            r.and_then(|()| {
                let issuers = voucher.as_object().map(issuer_ids).unwrap_or_default();
                if issuers.iter().any(|i| i == did) {
                    Ok(())
                } else {
                    Err("voucher_signature_invalid".to_string())
                }
            })
        })
    } else {
        verify_session_voucher_quorum(
            voucher,
            validators,
            quorum.min(validators.len() as i64),
            at_us,
            clock_skew_seconds,
            issuer_key,
        )
    };
    match verdict {
        Err(_) => return refuse(REASON_NO_SESSION, "voucher_malformed:ValueError"),
        Ok(Err(why)) => return refuse(REASON_NO_SESSION, note(&why)),
        Ok(Ok(())) => {}
    }
    let subject = subject_id(one).filter(|s| !s.is_empty());
    let Some(subject) = subject else {
        return refuse(REASON_NO_SESSION, "voucher_subject_missing");
    };
    if subject != issuer {
        return refuse(REASON_NO_SESSION, "voucher_subject_mismatch");
    }
    match evaluate_trust(one, trust_threshold, at_us) {
        Err(_) => refuse(REASON_NO_SESSION, "voucher_malformed:TrustEntropyError"),
        Ok(e) if !e.passed => refuse(
            REASON_LOW_TRUST,
            format!(
                "trust_below_threshold:{:.4}<{}",
                e.trust,
                py_repr_float(trust_threshold)
            ),
        ),
        Ok(_) => None,
    }
}

/// The issuer DIDs of a voucher: strings, or the `id` of issuer objects.
fn issuer_ids(voucher: &Map<String, Value>) -> Vec<String> {
    issuer_list(voucher)
        .iter()
        .filter_map(|i| match i {
            Value::String(s) => Some(s.clone()),
            Value::Object(o) => o.get("id").and_then(Value::as_str).map(String::from),
            _ => None,
        })
        .collect()
}

/// What the host's authority source said about the caller (the reference's
/// `AuthorityFacts`), as JSON.
#[derive(Debug, Clone, Default)]
pub struct AuthorityFacts {
    pub last_seen_epoch: Option<Value>,
    pub current_status: Option<String>,
    pub live_cosign_ok: Option<bool>,
    pub state: Option<Value>,
    pub trusted_authorities: Option<Value>,
    pub voucher_epoch: Option<Value>,
    pub equivocations: Option<Value>,
    pub equivocation_keys: BTreeMap<String, Value>,
}

fn equivocated(
    proofs: &Value,
    caller: &str,
    caller_key: Option<&[u8]>,
    chain: &[(String, String)],
    keys: &BTreeMap<String, Value>,
) -> Option<&'static str> {
    let key_of = |did: &str| keys.get(did).and_then(key_from_json).map(|(k, _)| k);
    let mut dids: Vec<(String, Option<Vec<u8>>)> = vec![(
        caller.to_string(),
        caller_key.map(<[u8]>::to_vec).or_else(|| key_of(caller)),
    )];
    for (issuer, subject) in chain {
        for did in [issuer, subject] {
            if !dids.iter().any(|(known, _)| known == did) {
                dids.push((did.clone(), key_of(did)));
            }
        }
    }
    let items: Vec<Value> = match proofs {
        Value::Array(a) => a.clone(),
        other => vec![other.clone()],
    };
    let named: Vec<&str> = items
        .iter()
        .filter_map(|p| p.get("agent").and_then(Value::as_str))
        .collect();
    let mut unknown = false;
    for (did, key) in dids {
        let key = key.or_else(|| {
            did.starts_with("did:key:")
                .then(|| authority_state::did_key_ed25519(&did))
                .flatten()
        });
        let Some(key) = key else {
            unknown = unknown || named.contains(&did.as_str());
            continue;
        };
        if crate::lineage::proof_applies_to(&items, &did, &key).is_some() {
            return Some("agent_equivocated");
        }
    }
    unknown.then_some("equivocation_key_unknown")
}

/// The AuthorityState attached to a call, checked against the trusted
/// authorities and the voucher: Err(reason) or (epoch, status).
fn attached_authority(
    state: Option<&Value>,
    trusted: Option<&Value>,
    voucher: Option<&Value>,
    caller: &str,
    now: &str,
    skew: i64,
) -> Result<std::result::Result<(i64, String), &'static str>> {
    let keys = match trusted {
        Some(t) if !t.is_null() => authority_state::trusted_authorities_from_json(t)?,
        _ => BTreeMap::new(),
    };
    let parsed = match state {
        None | Some(Value::Null) => None,
        Some(Value::String(text)) => authority_state::parse_authority_state_text(text).ok(),
        Some(v) => Some(v.clone()),
    };
    let Some(parsed) = parsed.filter(Value::is_object) else {
        return Ok(Err(authority_state::AUTHORITY_STATE_MISSING));
    };
    if keys.is_empty() {
        return Ok(Err(authority_state::AUTHORITY_ISSUER_UNTRUSTED));
    }
    Ok(authority_state::check_attached_authority_state(
        Some(&parsed),
        &keys,
        voucher,
        Some(caller),
        now,
        skew,
    )?
    .map(|p| (p.authority_epoch, p.status)))
}

/// The authority part of the guard's freshness step
/// (`vouch.guard._freshness._authority_refusal`), after the host asked its
/// authority source. `voucher` is the call's voucher (the first copy of a
/// list); `chain` is the verified passport's delegation links (issuer,
/// subject).
#[allow(clippy::too_many_arguments)]
pub fn authority_refusal(
    tier: &str,
    rule: FreshnessRule,
    voucher: Option<&Value>,
    issuer: &str,
    issuer_key: Option<&[u8]>,
    chain: &[(String, String)],
    facts: &AuthorityFacts,
    now: &str,
    clock_skew_seconds: i64,
) -> Result<Refusal> {
    if let Some(proofs) = facts.equivocations.as_ref().filter(|p| truthy(p)) {
        if let Some(problem) =
            equivocated(proofs, issuer, issuer_key, chain, &facts.equivocation_keys)
        {
            return Ok(refuse(REASON_AUTHORITY, problem));
        }
    }
    let state = facts.state.as_ref().filter(|s| !s.is_null());
    if !rule.enforce_epoch && !rule.require_live_cosign && state.is_none() {
        return Ok(None);
    }
    let mut last_seen: Option<i64> = None;
    if let Some(v) = facts.last_seen_epoch.as_ref().filter(|v| !v.is_null()) {
        if !is_epoch(v) {
            return Ok(refuse(
                REASON_AUTHORITY,
                "the last seen epoch is not a whole number",
            ));
        }
        last_seen = v.as_i64();
    }
    let mut status = facts.current_status.clone();
    let voucher_epoch: Option<i64>;
    let trusted = facts.trusted_authorities.as_ref().filter(|t| !t.is_null());
    if trusted.is_some() || state.is_some() {
        match attached_authority(state, trusted, voucher, issuer, now, clock_skew_seconds)? {
            Err(problem) => {
                if tier != authority_state::CONSEQUENCE_ROUTINE || state.is_some() {
                    return Ok(refuse(REASON_AUTHORITY, problem));
                }
                return Ok(None);
            }
            Ok((epoch, stated_status)) => {
                voucher_epoch = Some(epoch);
                if last_seen.is_none() {
                    last_seen = Some(epoch);
                }
                if status.as_deref().is_none_or(str::is_empty) {
                    status = Some(stated_status);
                }
            }
        }
    } else {
        match facts.voucher_epoch.as_ref().filter(|v| !v.is_null()) {
            Some(v) if !is_epoch(v) => {
                let seen = last_seen.map_or("?".to_string(), |s| s.to_string());
                return Ok(refuse(
                    REASON_AUTHORITY,
                    format!("authority_epoch_unknown:voucher=?,seen={seen}"),
                ));
            }
            Some(v) => voucher_epoch = v.as_i64(),
            None => {
                voucher_epoch = voucher
                    .filter(|v| v.is_object())
                    .and_then(authority_state::voucher_authority)
                    .map(|r| r.epoch);
            }
        }
    }
    if !rule.enforce_epoch && !rule.require_live_cosign {
        return Ok(None);
    }
    let mut policy = BTreeMap::new();
    policy.insert(tier.to_string(), rule);
    let verdict = authority_state::evaluate_authority_freshness_with(
        tier,
        voucher_epoch,
        last_seen,
        status.as_deref(),
        facts.live_cosign_ok,
        &policy,
    )?;
    if verdict.allow {
        Ok(None)
    } else {
        Ok(refuse(REASON_AUTHORITY, note(&verdict.reason)))
    }
}

fn truthy(v: &Value) -> bool {
    match v {
        Value::Null => false,
        Value::Bool(b) => *b,
        Value::Array(a) => !a.is_empty(),
        Value::Object(o) => !o.is_empty(),
        Value::String(s) => !s.is_empty(),
        Value::Number(n) => n.as_f64() != Some(0.0),
    }
}

// ---------------------------------------------------------------------------
// JSON in, JSON out (for the bindings)
// ---------------------------------------------------------------------------

fn now_us(obj: &Map<String, Value>) -> Result<(String, i128)> {
    let now = obj
        .get("now")
        .and_then(Value::as_str)
        .ok_or_else(|| bad("now must be a protocol time"))?;
    Ok((now.to_string(), micros_of(now)?))
}

/// A member that must be a JSON boolean when present.
fn strict_bool(obj: &Map<String, Value>, name: &str) -> Result<Option<bool>> {
    match obj.get(name) {
        None => Ok(None),
        Some(Value::Bool(b)) => Ok(Some(*b)),
        Some(_) => Err(bad(format!("{name} must be true or false"))),
    }
}

/// A member that must be a finite JSON number when present.
fn strict_number(obj: &Map<String, Value>, name: &str) -> Result<Option<f64>> {
    match obj.get(name) {
        None => Ok(None),
        Some(Value::Number(n)) => match n.as_f64() {
            Some(x) if x.is_finite() => Ok(Some(x)),
            _ => Err(bad(format!("{name} must be a finite number"))),
        },
        Some(_) => Err(bad(format!("{name} must be a finite number"))),
    }
}

/// A member that must be a JSON whole number (no fraction, so 2.0 is
/// refused) when present.
fn strict_whole(obj: &Map<String, Value>, name: &str) -> Result<Option<i64>> {
    match obj.get(name) {
        None => Ok(None),
        Some(v) => v
            .as_i64()
            .map(Some)
            .ok_or_else(|| bad(format!("{name} must be a whole number"))),
    }
}

fn skew_of(obj: &Map<String, Value>) -> Result<i64> {
    match obj.get("clockSkewSeconds") {
        None => Ok(30),
        Some(v) => crate::time::clock_skew_from_json(v),
    }
}

fn opt_key(obj: &Map<String, Value>, name: &str) -> Result<Option<Vec<u8>>> {
    match obj.get(name).filter(|v| !v.is_null()) {
        None => Ok(None),
        Some(v) => key_from_json(v)
            .map(|(k, _)| Some(k))
            .ok_or_else(|| bad(format!("{name} is not an Ed25519 key"))),
    }
}

fn refusal_json(r: Refusal) -> Value {
    match r {
        None => json!({ "refusal": null }),
        Some((reason, note)) => json!({ "refusal": { "reason": reason, "note": note } }),
    }
}

/// [`session_refusal`] as JSON: `{"requireSession", "trustThreshold",
/// "voucher", "issuer", "issuerKey", "validators" ({DID: key} or a list of
/// did:keys), "quorum", "now", "clockSkewSeconds"}` to `{"refusal": null
/// or {"reason", "note"}}`.
pub fn session_refusal_json(request: &Value) -> Result<Value> {
    let obj = request
        .as_object()
        .ok_or_else(|| bad("the request must be a JSON object"))?;
    let (_, at) = now_us(obj)?;
    let skew = skew_of(obj)?;
    let validators = match obj.get("validators").filter(|v| !v.is_null()) {
        None => Vec::new(),
        Some(Value::Object(m)) if m.is_empty() => Vec::new(),
        Some(Value::Array(a)) if a.is_empty() => Vec::new(),
        Some(v) => validator_key_map(v)?,
    };
    // With validators named, the threshold and the quorum decide whether a
    // voucher counts, so each must be given; a wrong type is never read as
    // a default.
    let required = |name: &str| bad(format!("{name} is required when validators are named"));
    let threshold = match strict_number(obj, "trustThreshold")? {
        Some(t) => t,
        None if validators.is_empty() => 0.0,
        None => return Err(required("trustThreshold")),
    };
    let quorum = match strict_whole(obj, "quorum")? {
        Some(q) if q >= 1 => q,
        Some(_) => return Err(bad("quorum must be a whole number of at least 1")),
        None if validators.is_empty() => 1,
        None => return Err(required("quorum")),
    };
    let require_session = strict_bool(obj, "requireSession")?.unwrap_or(false);
    let issuer = obj.get("issuer").and_then(Value::as_str).unwrap_or("");
    let voucher = obj.get("voucher").filter(|v| !v.is_null());
    Ok(refusal_json(session_refusal(
        require_session,
        threshold,
        voucher,
        issuer,
        opt_key(obj, "issuerKey")?.as_deref(),
        &validators,
        quorum,
        at,
        skew,
    )))
}

/// [`authority_refusal`] as JSON: `{"tier", "enforceEpoch",
/// "requireLiveCosign", "voucher", "issuer", "issuerKey", "chain" ([{issuer,
/// subject}]), "facts" ({lastSeenEpoch, currentStatus, liveCosignOk, state,
/// trustedAuthorities, voucherEpoch, equivocations, equivocationKeys}),
/// "now", "clockSkewSeconds"}` to `{"refusal"}`.
pub fn authority_refusal_json(request: &Value) -> Result<Value> {
    let obj = request
        .as_object()
        .ok_or_else(|| bad("the request must be a JSON object"))?;
    let (now, _) = now_us(obj)?;
    let skew = skew_of(obj)?;
    let rule = FreshnessRule {
        enforce_epoch: strict_bool(obj, "enforceEpoch")?.unwrap_or(false),
        require_live_cosign: strict_bool(obj, "requireLiveCosign")?.unwrap_or(false),
    };
    let chain: Vec<(String, String)> = obj
        .get("chain")
        .and_then(Value::as_array)
        .map(|links| {
            links
                .iter()
                .map(|l| {
                    let text = |k: &str| l.get(k).and_then(Value::as_str).unwrap_or("").to_string();
                    (text("issuer"), text("subject"))
                })
                .collect()
        })
        .unwrap_or_default();
    let f = obj.get("facts").and_then(Value::as_object);
    let member = |k: &str| f.and_then(|m| m.get(k)).filter(|v| !v.is_null()).cloned();
    let facts = AuthorityFacts {
        last_seen_epoch: member("lastSeenEpoch"),
        current_status: member("currentStatus").and_then(|v| v.as_str().map(String::from)),
        live_cosign_ok: member("liveCosignOk").and_then(|v| v.as_bool()),
        state: member("state"),
        trusted_authorities: member("trustedAuthorities"),
        voucher_epoch: member("voucherEpoch"),
        equivocations: member("equivocations"),
        equivocation_keys: member("equivocationKeys")
            .and_then(|v| v.as_object().cloned())
            .map(|m| m.into_iter().collect())
            .unwrap_or_default(),
    };
    let voucher = obj
        .get("voucher")
        .filter(|v| !v.is_null())
        .map(|v| match v {
            Value::Array(a) if !a.is_empty() => &a[0],
            v => v,
        });
    let tier = obj.get("tier").and_then(Value::as_str).unwrap_or("");
    let issuer = obj.get("issuer").and_then(Value::as_str).unwrap_or("");
    Ok(refusal_json(authority_refusal(
        tier,
        rule,
        voucher,
        issuer,
        opt_key(obj, "issuerKey")?.as_deref(),
        &chain,
        &facts,
        &now,
        skew,
    )?))
}

/// A voucher on its own, for any verifier: `{"voucher", "validators" ({DID:
/// key} or a list of did:keys), "threshold" (default 1), "subjectKey",
/// "now", "clockSkewSeconds", "allowSelfIssued"}` to `{"ok", "reason"}`.
/// With one validator, a threshold of 1 and a single voucher, the voucher's
/// one proof is checked (`verify_session_voucher`); otherwise M of N.
pub fn verify_session_voucher_json(request: &Value) -> Result<Value> {
    let obj = request
        .as_object()
        .ok_or_else(|| bad("the request must be a JSON object"))?;
    let (_, at) = now_us(obj)?;
    let skew = skew_of(obj)?;
    let voucher = obj.get("voucher").cloned().unwrap_or(Value::Null);
    let subject = opt_key(obj, "subjectKey")?;
    let validators_value = obj.get("validators").cloned().unwrap_or(Value::Null);
    let threshold = strict_whole(obj, "threshold")?.unwrap_or(1);
    let allow_self_issued = strict_bool(obj, "allowSelfIssued")?.unwrap_or(false);
    let single = match &validators_value {
        Value::String(_) => Some(validators_value.clone()),
        _ => None,
    };
    let verdict = if let Some(key) = single {
        verify_session_voucher(
            &voucher,
            Some(&key),
            at,
            skew,
            allow_self_issued,
            subject.as_deref(),
        )?
    } else {
        let validators = validator_key_map(&validators_value)?;
        verify_session_voucher_quorum(
            &voucher,
            &validators,
            threshold,
            at,
            skew,
            subject.as_deref(),
        )?
    };
    Ok(match verdict {
        Ok(()) => json!({"ok": true, "reason": "voucher_ok"}),
        Err(reason) => json!({"ok": false, "reason": reason}),
    })
}

/// [`evaluate_trust`] as JSON: `{"voucher", "threshold", "now"}` to
/// `{"trust", "threshold", "passed", "elapsedSeconds", "initialTrust",
/// "decayLambda"}`. Errors with the reference's `TrustEntropyError` text.
pub fn evaluate_trust_json(request: &Value) -> Result<Value> {
    let obj = request
        .as_object()
        .ok_or_else(|| bad("the request must be a JSON object"))?;
    let (_, at) = now_us(obj)?;
    let voucher = obj.get("voucher").cloned().unwrap_or(Value::Null);
    let threshold = strict_number(obj, "threshold")?.ok_or_else(|| bad("threshold is required"))?;
    let e = evaluate_trust(&voucher, threshold, at)?;
    Ok(json!({
        "trust": e.trust,
        "threshold": e.threshold,
        "passed": e.passed,
        "elapsedSeconds": e.elapsed_seconds,
        "initialTrust": e.initial_trust,
        "decayLambda": e.decay_lambda,
    }))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data_integrity::BuildProofOptions;

    fn did_key(seed: u8) -> (String, [u8; 32]) {
        let s = [seed; 32];
        let kp = crate::keys::Ed25519KeyPair::from_seed_slice(&s).unwrap();
        (
            format!(
                "did:key:{}",
                crate::multikey::encode_ed25519_public(&kp.public_key()).unwrap()
            ),
            s,
        )
    }

    fn voucher(validator: &str, seed: &[u8; 32], subject: &str) -> Value {
        let unsigned = json!({
            "@context": ["https://www.w3.org/ns/credentials/v2"],
            "type": ["VerifiableCredential", "SessionVoucher"],
            "issuer": validator,
            "validFrom": "2026-01-01T00:00:00Z",
            "validUntil": "2026-01-01T00:05:00Z",
            "credentialSubject": {"id": subject, "initialTrust": 1.0, "decayLambda": 0.001},
        });
        let opts = BuildProofOptions::new(format!("{validator}#key-1"), "2026-01-01T00:00:00Z");
        data_integrity::sign(&unsigned, seed, &opts).unwrap()
    }

    fn at(t: &str) -> i128 {
        micros_of(t).unwrap()
    }

    #[test]
    fn one_validator() {
        let (v, vs) = did_key(1);
        let (agent, _) = did_key(2);
        let doc = voucher(&v, &vs, &agent);
        let key = json!(v.clone());
        let now = at("2026-01-01T00:01:00Z");
        assert_eq!(
            verify_session_voucher(&doc, Some(&key), now, 30, false, None).unwrap(),
            Ok(())
        );
        let late = at("2026-01-01T00:06:00Z");
        assert_eq!(
            verify_session_voucher(&doc, Some(&key), late, 30, false, None).unwrap(),
            Err("voucher_expired".into())
        );
        let (other, _) = did_key(3);
        assert_eq!(
            verify_session_voucher(&doc, Some(&json!(other)), now, 30, false, None).unwrap(),
            Err("voucher_signature_invalid".into())
        );
        let mut tampered = doc.clone();
        tampered["credentialSubject"]["initialTrust"] = json!(0.99);
        assert_eq!(
            verify_session_voucher(&tampered, Some(&key), now, 30, false, None).unwrap(),
            Err("voucher_signature_invalid".into())
        );
    }

    #[test]
    fn self_issued_is_refused() {
        let (agent, seed) = did_key(4);
        let doc = voucher(&agent, &seed, &agent);
        let now = at("2026-01-01T00:01:00Z");
        assert_eq!(
            verify_session_voucher(&doc, Some(&json!(agent)), now, 30, false, None).unwrap(),
            Err("voucher_self_issued".into())
        );
    }

    #[test]
    fn guard_session_checks() {
        let (v, vs) = did_key(5);
        let (agent, _) = did_key(6);
        let doc = voucher(&v, &vs, &agent);
        let validators = validator_key_map(&json!([v])).unwrap();
        let now = at("2026-01-01T00:01:00Z");
        assert_eq!(
            session_refusal(true, 0.5, Some(&doc), &agent, None, &validators, 1, now, 30),
            None
        );
        let (stranger, _) = did_key(7);
        assert_eq!(
            session_refusal(
                true,
                0.5,
                Some(&doc),
                &stranger,
                None,
                &validators,
                1,
                now,
                30
            )
            .unwrap()
            .1,
            "voucher_subject_mismatch"
        );
        let low = session_refusal(
            true,
            0.99,
            Some(&doc),
            &agent,
            None,
            &validators,
            1,
            now,
            30,
        )
        .unwrap();
        assert_eq!(low.0, REASON_LOW_TRUST);
        assert_eq!(
            session_refusal(true, 0.5, None, &agent, None, &validators, 1, now, 30)
                .unwrap()
                .1,
            "voucher_missing"
        );
        assert_eq!(
            session_refusal(false, 0.5, None, &agent, None, &validators, 1, now, 30),
            None
        );
    }

    #[test]
    fn trust_decays() {
        let doc = json!({
            "type": ["VerifiableCredential", "SessionVoucher"],
            "validFrom": "2026-01-01T00:00:00Z",
            "credentialSubject": {"initialTrust": 1.0, "decayLambda": 0.01},
        });
        let t = compute_trust_at(&doc, at("2026-01-01T00:01:40Z")).unwrap();
        assert!((t - 0.36787944117144233).abs() < 1e-15);
        assert!(compute_trust_at(&json!({"type": "X"}), 0).is_err());
    }

    #[test]
    fn trust_parameters_must_be_finite() {
        for (name, value) in [
            ("initialTrust", json!("inf")),
            ("initialTrust", json!("nan")),
            ("decayLambda", json!("inf")),
        ] {
            let mut doc = json!({
                "type": ["VerifiableCredential", "SessionVoucher"],
                "validFrom": "2026-01-01T00:00:00Z",
                "credentialSubject": {"initialTrust": 1.0, "decayLambda": 0.0},
            });
            doc["credentialSubject"][name] = value;
            let err = compute_trust_at(&doc, at("2026-01-01T00:01:00Z")).unwrap_err();
            assert!(err.to_string().contains("must be a finite number"), "{err}");
            let request = json!({"voucher": doc, "threshold": 0.5, "now": "2026-01-01T00:01:00Z"});
            assert!(evaluate_trust_json(&request).is_err());
        }
    }

    #[test]
    fn evaluate_trust_threshold_is_read_strictly() {
        let doc = json!({
            "type": ["VerifiableCredential", "SessionVoucher"],
            "validFrom": "2026-01-01T00:00:00Z",
            "credentialSubject": {"initialTrust": 1.0, "decayLambda": 0.01},
        });
        let ask = |threshold: Option<Value>| {
            let mut request = json!({"voucher": doc.clone(), "now": "2026-01-01T00:01:00Z"});
            if let Some(t) = threshold {
                request["threshold"] = t;
            }
            evaluate_trust_json(&request)
        };
        assert_eq!(ask(Some(json!(0.5))).unwrap()["passed"], json!(true));
        for bad_value in [
            None,
            Some(Value::Null),
            Some(json!("0.5")),
            Some(json!(true)),
            Some(json!(-1.0)),
        ] {
            assert!(ask(bad_value.clone()).is_err(), "{bad_value:?}");
        }
    }

    #[test]
    fn quorum_threshold_is_read_strictly() {
        let (v1, s1) = did_key(8);
        let (v2, _) = did_key(9);
        let (agent, _) = did_key(10);
        let doc = voucher(&v1, &s1, &agent);
        let ask = |threshold: Option<Value>| {
            let mut request = json!({
                "voucher": doc.clone(),
                "validators": [v1.clone(), v2.clone()],
                "now": "2026-01-01T00:01:00Z",
            });
            if let Some(t) = threshold {
                request["threshold"] = t;
            }
            verify_session_voucher_json(&request)
        };
        assert_eq!(ask(None).unwrap()["ok"], json!(true));
        assert_eq!(ask(Some(json!(2))).unwrap()["ok"], json!(false));
        for bad_value in [json!(null), json!(2.5), json!(1.0), json!("2"), json!(true)] {
            assert!(ask(Some(bad_value.clone())).is_err(), "{bad_value}");
        }
    }

    #[test]
    fn guard_session_options_are_read_strictly() {
        let (v, vs) = did_key(11);
        let (agent, _) = did_key(12);
        let doc = voucher(&v, &vs, &agent);
        let base = json!({
            "requireSession": true,
            "trustThreshold": 0.5,
            "voucher": doc,
            "issuer": agent,
            "validators": [v],
            "quorum": 1,
            "now": "2026-01-01T00:01:00Z",
            "clockSkewSeconds": 30,
        });
        assert_eq!(session_refusal_json(&base).unwrap()["refusal"], Value::Null);
        let with = |name: &str, value: Option<Value>| {
            let mut request = base.clone();
            match value {
                Some(v) => request[name] = v,
                None => {
                    request.as_object_mut().unwrap().remove(name);
                }
            }
            session_refusal_json(&request)
        };
        for (name, value) in [
            ("trustThreshold", None),
            ("trustThreshold", Some(json!(null))),
            ("trustThreshold", Some(json!("0.5"))),
            ("quorum", None),
            ("quorum", Some(json!(2.0))),
            ("quorum", Some(json!(0))),
            ("quorum", Some(json!("1"))),
            ("requireSession", Some(json!("yes"))),
            ("requireSession", Some(json!(1))),
        ] {
            assert!(with(name, value.clone()).is_err(), "{name} {value:?}");
        }
        // With no validators named, the threshold and quorum may be left out.
        let mut none = base.clone();
        let m = none.as_object_mut().unwrap();
        m.remove("validators");
        m.remove("trustThreshold");
        m.remove("quorum");
        m.remove("voucher");
        m.insert("requireSession".into(), json!(false));
        assert_eq!(session_refusal_json(&none).unwrap()["refusal"], Value::Null);
    }

    #[test]
    fn guard_authority_flags_are_read_strictly() {
        let request = |flag: Value| {
            json!({
                "tier": "critical",
                "enforceEpoch": flag,
                "voucher": null,
                "issuer": "did:web:a.example",
                "facts": {},
                "now": "2026-01-01T00:01:00Z",
                "clockSkewSeconds": 30,
            })
        };
        assert!(authority_refusal_json(&request(json!(true))).is_ok());
        for flag in [json!("true"), json!(1), json!(null)] {
            assert!(
                authority_refusal_json(&request(flag.clone())).is_err(),
                "{flag}"
            );
        }
    }

    #[test]
    fn det_exp_is_within_one_ulp_of_the_platform_exp() {
        // Exact values first.
        assert_eq!(det_exp(0.0), 1.0);
        assert_eq!(det_exp(-0.0), 1.0);
        assert!(det_exp(f64::NAN).is_nan());
        assert_eq!(det_exp(f64::NEG_INFINITY), 0.0);
        assert_eq!(det_exp(-800.0), 0.0);
        assert!(det_exp(710.0).is_infinite());
        // Then a sweep over the range trust decay uses (and past it).
        let mut worst = 0u64;
        let mut x = -745.0_f64;
        while x < 709.0 {
            for v in [x, x + 1e-9, x * 0.999_999_7] {
                let (a, b) = (det_exp(v), v.exp());
                if a == 0.0 || b == 0.0 || !a.is_normal() || !b.is_normal() {
                    continue;
                }
                worst = worst.max(a.to_bits().abs_diff(b.to_bits()));
            }
            x += 0.013_7;
        }
        assert!(worst <= 1, "det_exp is {worst} ulp from exp");
    }

    #[test]
    fn det_exp_constants_have_the_fdlibm_bits() {
        // The decimal constants above must round to fdlibm's exact bits.
        let bits = |v: f64| v.to_bits();
        assert_eq!(
            bits(6.931_471_803_691_238_164_90e-01),
            0x3fe6_2e42_fee0_0000
        );
        assert_eq!(
            bits(1.908_214_929_270_587_700_02e-10),
            0x3dea_39ef_3579_3c76
        );
        assert_eq!(
            bits(1.442_695_040_888_963_387_00e+00),
            0x3ff7_1547_652b_82fe
        );
        assert_eq!(
            bits(1.666_666_666_666_660_190_37e-01),
            0x3fc5_5555_5555_553e
        );
        assert_eq!(
            bits(-2.777_777_777_701_559_338_42e-03),
            0xbf66_c16c_16be_bd93
        );
        assert_eq!(
            bits(6.613_756_321_437_934_361_17e-05),
            0x3f11_566a_af25_de2c
        );
        assert_eq!(
            bits(-1.653_390_220_546_525_153_90e-06),
            0xbebb_bd41_c5d2_6bf1
        );
        assert_eq!(
            bits(4.138_136_797_057_238_460_39e-08),
            0x3e66_3769_72be_a4d0
        );
    }
}