ic-cli 0.2.5

ic: command-line and MCP-server front end for IronCrypto
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
//! The operations shared by the CLI and the MCP server.
//!
//! Both front ends call into this module, so `ic ontology show sha2-256`
//! and the MCP `ontology_show` tool return the same data from the same code.
//! That is deliberate: a human debugging an agent's behaviour should be able to
//! reproduce it from a shell.

use ic_core::traits::{Aead, Digest, Mac};
use ic_json::Json;
use ic_ontology::frameworks::{self, Control, Framework};
use ic_ontology::select::{recommend, Intent, NoRecommendation, Policy};
use ic_ontology::standards::{self, Compliance, Requirement, Standard};
use ic_ontology::{Entry, ImplStatus};

/// An entry with the relations that point *at* it as well as those it declares.
///
/// The registry stores each relation once, in whichever direction helps the
/// reader: MD5 records that SHA-256 supersedes it, and SHA-256 carries no list
/// of everything it replaced. That keeps the data small and the entries
/// readable, and it means the outgoing edges alone are a half view.
///
/// `ontology show` and the `ontology_show` tool use this rather than
/// [`entry_json`]; `ontology list` does not, because the inbound half is
/// detail nobody wants seventy-five times.
pub fn entry_detail_json(e: &Entry) -> Json {
    let mut inbound = Vec::new();
    for other in ic_ontology::registry::REGISTRY {
        if other.id == e.id {
            continue;
        }
        for edge in other.edges {
            if edge.target == e.id {
                inbound.push(Json::object([
                    ("relation", Json::str(edge.relation.id())),
                    ("source", Json::str(other.id)),
                ]));
            }
        }
    }

    let Json::Object(mut fields) = entry_json(e) else {
        unreachable!("entry_json always returns an object")
    };
    fields.insert("relatedBy".to_string(), Json::Array(inbound));
    Json::Object(fields)
}

/// Render an ontology entry as JSON.
pub fn entry_json(e: &Entry) -> Json {
    Json::object([
        ("id", Json::str(e.id)),
        ("name", Json::str(e.name)),
        ("summary", Json::str(e.summary)),
        ("class", Json::str(e.class.id())),
        ("family", Json::str(e.family)),
        (
            "purposes",
            Json::Array(e.purposes.iter().map(|p| Json::str(p.id())).collect()),
        ),
        (
            "aliases",
            Json::Array(e.aliases.iter().map(|a| Json::str(*a)).collect()),
        ),
        (
            "standards",
            Json::Array(e.standards.iter().map(|s| Json::str(*s)).collect()),
        ),
        (
            "strength",
            Json::object([
                ("classicalBits", Json::num(e.strength.classical)),
                ("quantumBits", Json::num(e.strength.quantum)),
            ]),
        ),
        ("fipsStatus", Json::str(e.fips.id())),
        ("implementationStatus", Json::str(e.status.id())),
        ("approvedModeUsable", Json::Bool(e.approved_mode_ok())),
        ("performance", Json::str(e.performance.id())),
        (
            "parameters",
            Json::Array(
                e.params
                    .iter()
                    .map(|p| {
                        Json::object([
                            ("name", Json::str(p.name)),
                            ("unit", Json::str(p.unit.id())),
                            ("min", Json::num(p.min as f64)),
                            ("max", Json::num(p.max as f64)),
                            ("recommended", Json::num(p.recommended as f64)),
                            ("note", Json::str(p.note)),
                        ])
                    })
                    .collect(),
            ),
        ),
        (
            "constraints",
            Json::Array(
                e.constraints
                    .iter()
                    .map(|c| {
                        Json::object([
                            ("id", Json::str(c.id)),
                            ("severity", Json::str(c.severity.id())),
                            ("requirement", Json::str(c.requirement)),
                            ("consequence", Json::str(c.consequence)),
                        ])
                    })
                    .collect(),
            ),
        ),
        (
            "relations",
            Json::Array(
                e.edges
                    .iter()
                    .map(|edge| {
                        Json::object([
                            ("relation", Json::str(edge.relation.id())),
                            ("target", Json::str(edge.target)),
                        ])
                    })
                    .collect(),
            ),
        ),
        ("rustPath", Json::str(e.rust_path)),
        ("example", Json::str(e.example)),
        ("notes", Json::str(e.notes)),
    ])
}

/// Build a query from optional string filters and run it.
pub fn list(
    class: Option<&str>,
    purpose: Option<&str>,
    fips_only: bool,
    available_only: bool,
) -> Result<Vec<&'static Entry>, String> {
    let mut q = ic_ontology::Query::new();
    if let Some(c) = class {
        let parsed = ic_ontology::Class::from_id(c)
            .ok_or_else(|| format!("unknown class '{c}'; try one of {}", class_list()))?;
        q = q.class(parsed);
    }
    if let Some(p) = purpose {
        let parsed = ic_ontology::Purpose::from_id(p)
            .ok_or_else(|| format!("unknown purpose '{p}'; try one of {}", purpose_list()))?;
        q = q.purpose(parsed);
    }
    if fips_only {
        q = q.fips_approved_only();
    }
    if available_only {
        q = q.available_only();
    }
    Ok(q.run().collect())
}

/// The class vocabulary, comma-separated.
pub fn class_list() -> String {
    ic_ontology::Class::ALL
        .iter()
        .map(|c| c.id())
        .collect::<Vec<_>>()
        .join(", ")
}

/// The purpose vocabulary, comma-separated.
pub fn purpose_list() -> String {
    ic_ontology::Purpose::ALL
        .iter()
        .map(|p| p.id())
        .collect::<Vec<_>>()
        .join(", ")
}

/// The intent vocabulary, comma-separated.
pub fn intent_list() -> String {
    Intent::ALL
        .iter()
        .map(|i| i.id())
        .collect::<Vec<_>>()
        .join(", ")
}

/// Produce a recommendation as JSON, including the honest failure cases.
pub fn recommend_json(
    intent: &str,
    fips: bool,
    post_quantum: bool,
    aes_hardware: bool,
) -> Result<Json, String> {
    let parsed = Intent::from_id(intent)
        .ok_or_else(|| format!("unknown intent '{intent}'; try one of {}", intent_list()))?;

    // `--aes-hardware` forces the assumption on; otherwise it is detected, so
    // the recommendation reflects the machine the command is running on.
    let policy = Policy {
        require_fips: fips,
        min_classical_bits: 128,
        min_quantum_bits: if post_quantum { 128 } else { 0 },
        aes_hardware: aes_hardware || ic_ontology::runtime::backend().fast_bulk_symmetric(),
    };

    match recommend(parsed, policy) {
        Ok(r) => Ok(Json::object([
            ("intent", Json::str(r.intent.id())),
            ("status", Json::str("ok")),
            ("recommended", Json::str(r.primary.id)),
            ("rustPath", Json::str(r.primary.rust_path)),
            ("example", Json::str(r.primary.example)),
            ("rationale", Json::str(r.rationale)),
            (
                "alternative",
                match r.alternative {
                    Some(a) => Json::str(a.id),
                    None => Json::Null,
                },
            ),
            (
                "rejected",
                Json::Array(
                    r.rejected()
                        .map(|x| {
                            Json::object([("id", Json::str(x.id)), ("reason", Json::str(x.reason))])
                        })
                        .collect(),
                ),
            ),
            (
                "mustObserve",
                Json::Array(
                    r.must_observe
                        .iter()
                        .map(|c| {
                            Json::object([
                                ("id", Json::str(c.id)),
                                ("severity", Json::str(c.severity.id())),
                                ("requirement", Json::str(c.requirement)),
                                ("consequence", Json::str(c.consequence)),
                            ])
                        })
                        .collect(),
                ),
            ),
        ])),
        Err(NoRecommendation::KnownButUnavailable { id }) => {
            let e = ic_ontology::get(id);
            Ok(Json::object([
                ("intent", Json::str(parsed.id())),
                ("status", Json::str("unavailable")),
                ("recommended", Json::Null),
                ("correctAnswer", Json::str(id)),
                (
                    "explanation",
                    Json::str(format!(
                        "{id} satisfies this request, but it is not implemented in this build. Do \
                         not substitute a different algorithm to work around this."
                    )),
                ),
                ("notes", Json::str(e.map(|e| e.notes).unwrap_or_default())),
            ]))
        }
        Err(NoRecommendation::NothingSatisfiesPolicy) => Ok(Json::object([
            ("intent", Json::str(parsed.id())),
            ("status", Json::str("impossible")),
            ("recommended", Json::Null),
            (
                "explanation",
                Json::str(
                    "No algorithm in the ontology satisfies this combination of intent and policy.",
                ),
            ),
        ])),
    }
}

/// Run self-tests and render the report as JSON.
pub fn selftest_json(only: Option<&str>) -> Result<Json, String> {
    if let Some(id) = only {
        let ok = ic_fips::selftest::run_self_test(id)
            .map(|_| true)
            .map_err(|e| format!("{id}: {e}"))?;
        return Ok(Json::object([
            ("algorithm", Json::str(id)),
            ("passed", Json::Bool(ok)),
        ]));
    }

    let report = ic_fips::run_all_self_tests();
    Ok(Json::object([
        ("passed", Json::num(report.passed as f64)),
        ("failed", Json::num(report.failed as f64)),
        ("allPassed", Json::Bool(report.all_passed())),
        (
            "outcomes",
            Json::Array(
                report
                    .outcomes
                    .iter()
                    .map(|o| {
                        Json::object([
                            ("algorithm", Json::str(o.algorithm)),
                            ("passed", Json::Bool(o.passed)),
                        ])
                    })
                    .collect(),
            ),
        ),
        (
            "integrityCheck",
            Json::Bool(ic_fips::selftest::integrity_check().is_ok()),
        ),
    ]))
}

/// Describe this build: backend, capabilities, and validation status.
pub fn capabilities_json() -> Json {
    Json::object([
        ("version", Json::str(iron_crypto::VERSION)),
        ("ontologyVersion", Json::str(ic_ontology::ONTOLOGY_VERSION)),
        ("backend", Json::str(ic_ontology::runtime::backend().id())),
        (
            "fastBulkSymmetric",
            Json::Bool(ic_ontology::runtime::backend().fast_bulk_symmetric()),
        ),
        ("moduleState", Json::str(ic_fips::state().id())),
        (
            "validationStatement",
            Json::str(ic_fips::VALIDATION_STATEMENT),
        ),
        (
            "capabilities",
            Json::Array(
                ic_ontology::runtime::capabilities()
                    .map(|c| {
                        Json::object([
                            ("id", Json::str(c.id)),
                            ("present", Json::Bool(c.present)),
                            ("note", Json::str(c.note)),
                        ])
                    })
                    .collect(),
            ),
        ),
        (
            "algorithmCounts",
            Json::object([
                ("total", Json::num(ic_ontology::all().len() as f64)),
                (
                    "available",
                    Json::num(
                        ic_ontology::all()
                            .iter()
                            .filter(|e| e.status == ImplStatus::Available)
                            .count() as f64,
                    ),
                ),
                (
                    "experimental",
                    Json::num(
                        ic_ontology::all()
                            .iter()
                            .filter(|e| e.status == ImplStatus::Experimental)
                            .count() as f64,
                    ),
                ),
                (
                    "planned",
                    Json::num(
                        ic_ontology::all()
                            .iter()
                            .filter(|e| e.status == ImplStatus::Planned)
                            .count() as f64,
                    ),
                ),
            ]),
        ),
    ])
}

/// The error catalog as JSON.
pub fn errors_json() -> Json {
    Json::Array(
        ic_ontology::errors::catalog()
            .map(|d| {
                Json::object([
                    ("id", Json::str(d.id)),
                    ("meaning", Json::str(d.meaning)),
                    ("recovery", Json::str(d.recovery)),
                    ("retryable", Json::Bool(d.retryable)),
                    ("callerCorrectable", Json::Bool(d.caller_correctable)),
                ])
            })
            .collect(),
    )
}

/// Hash `data` with the named digest, returning lowercase hex.
pub fn digest_hex(algorithm: &str, data: &[u8]) -> Result<String, String> {
    use ic_hash::*;
    let hex = |b: &[u8]| ic_core::codec::hex(b);
    Ok(match algorithm {
        "sha2-224" | "sha224" => hex(Sha224::digest(data).as_ref()),
        "sha2-256" | "sha256" => hex(Sha256::digest(data).as_ref()),
        "sha2-384" | "sha384" => hex(Sha384::digest(data).as_ref()),
        "sha2-512" | "sha512" => hex(Sha512::digest(data).as_ref()),
        "sha2-512-224" => hex(Sha512_224::digest(data).as_ref()),
        "sha2-512-256" => hex(Sha512_256::digest(data).as_ref()),
        "sha3-224" => hex(Sha3_224::digest(data).as_ref()),
        "sha3-256" => hex(Sha3_256::digest(data).as_ref()),
        "sha3-384" => hex(Sha3_384::digest(data).as_ref()),
        "sha3-512" => hex(Sha3_512::digest(data).as_ref()),
        other => {
            return Err(match ic_ontology::get(other) {
                Some(e) if e.class != ic_ontology::Class::Hash => {
                    format!("'{other}' is a {}, not a hash", e.class.id())
                }
                Some(e) => format!("'{}' is known but not available here", e.id),
                None => format!("unknown digest '{other}'; try sha2-256 or sha3-256"),
            })
        }
    })
}

/// Compute an HMAC tag, returning lowercase hex.
pub fn hmac_hex(algorithm: &str, key: &[u8], data: &[u8]) -> Result<String, String> {
    use ic_mac::*;
    Ok(match algorithm {
        "hmac-sha2-256" | "hmac-sha256" => ic_core::codec::hex(
            HmacSha256::mac(key, data)
                .map_err(|e| e.to_string())?
                .as_ref(),
        ),
        "hmac-sha2-384" | "hmac-sha384" => ic_core::codec::hex(
            HmacSha384::mac(key, data)
                .map_err(|e| e.to_string())?
                .as_ref(),
        ),
        "hmac-sha2-512" | "hmac-sha512" => ic_core::codec::hex(
            HmacSha512::mac(key, data)
                .map_err(|e| e.to_string())?
                .as_ref(),
        ),
        "hmac-sha3-256" => ic_core::codec::hex(
            HmacSha3_256::mac(key, data)
                .map_err(|e| e.to_string())?
                .as_ref(),
        ),
        "hmac-sha3-512" => ic_core::codec::hex(
            HmacSha3_512::mac(key, data)
                .map_err(|e| e.to_string())?
                .as_ref(),
        ),
        other => return Err(format!("unknown MAC '{other}'; try hmac-sha2-256")),
    })
}

/// Encrypt with an AEAD, returning `(ciphertext_hex, tag_hex)`.
pub fn seal_hex(
    algorithm: &str,
    key: &[u8],
    nonce: &[u8],
    aad: &[u8],
    plaintext: &[u8],
) -> Result<(String, String), String> {
    let mut buf = plaintext.to_vec();
    let mut tag = [0u8; 16];
    match algorithm {
        "aes-128-gcm" => ic_cipher::Aes128Gcm::new(key)
            .and_then(|c| c.seal_detached(nonce, aad, &mut buf, &mut tag)),
        "aes-192-gcm" => ic_cipher::Aes192Gcm::new(key)
            .and_then(|c| c.seal_detached(nonce, aad, &mut buf, &mut tag)),
        "aes-256-gcm" => ic_cipher::Aes256Gcm::new(key)
            .and_then(|c| c.seal_detached(nonce, aad, &mut buf, &mut tag)),
        "chacha20-poly1305" => ic_cipher::ChaCha20Poly1305::new(key)
            .and_then(|c| c.seal_detached(nonce, aad, &mut buf, &mut tag)),
        other => return Err(format!("unknown AEAD '{other}'; try aes-256-gcm")),
    }
    .map_err(|e| e.to_string())?;
    Ok((ic_core::codec::hex(&buf), ic_core::codec::hex(&tag)))
}

/// Generate `n` random bytes from the OS-seeded DRBG, as hex.
use std::collections::BTreeMap;

/// Describe a key given as DER or PEM, without doing anything with it.
///
/// This is the first question anyone has about a key file, human or agent:
/// what is it? Answering it needs no private material and no cryptography, so
/// it is safe to run on anything.
pub fn key_json(input: &[u8]) -> Result<Json, String> {
    let (der, container, label) = unwrap_pem(input)?;

    // Try the public form first, then the private one. A file is one or the
    // other, and the two structures are distinguishable: PrivateKeyInfo starts
    // with a version INTEGER where SubjectPublicKeyInfo starts with a SEQUENCE.
    if let Ok(key) = ic_pkix::PublicKeyInfo::from_der(&der) {
        return Ok(public_key_json(&key, container, label.as_deref()));
    }
    match ic_pkix::PrivateKeyInfo::from_der(&der) {
        Ok(key) => Ok(private_key_json(&key, container, label.as_deref())),
        Err(e) => Err(format!("not a recognizable key: {}", e.kind().id())),
    }
}

/// Strip a PEM wrapper if there is one, returning the DER plus what was around
/// it.
fn unwrap_pem(input: &[u8]) -> Result<(Vec<u8>, &'static str, Option<String>), String> {
    let text = core::str::from_utf8(input).unwrap_or("");
    let Some(begin) = text.find("-----BEGIN ") else {
        return Ok((input.to_vec(), "der", None));
    };
    let rest = &text[begin + 11..];
    let end = rest.find("-----").ok_or("malformed pem header")?;
    let label = rest[..end].to_string();

    let mut out = vec![0u8; input.len()];
    let n = ic_pkix::pem::decode(&label, input, &mut out)
        .map_err(|e| format!("pem: {}", e.kind().id()))?;
    out.truncate(n);
    Ok((out, "pem", Some(label)))
}

fn key_common(
    algorithm: ic_pkix::KeyAlgorithm,
    container: &str,
    label: Option<&str>,
) -> BTreeMap<String, Json> {
    let mut fields = BTreeMap::new();
    fields.insert("algorithm".to_string(), Json::str(algorithm.id()));
    fields.insert("container".to_string(), Json::str(container));
    if let Some(label) = label {
        fields.insert("pemLabel".to_string(), Json::str(label));
    }
    fields
}

fn public_key_json(key: &ic_pkix::PublicKeyInfo<'_>, container: &str, label: Option<&str>) -> Json {
    let mut fields = key_common(key.algorithm(), container, label);
    fields.insert("kind".to_string(), Json::str("public"));
    match key {
        ic_pkix::PublicKeyInfo::Rsa { modulus, exponent } => {
            fields.insert("bits".to_string(), Json::num(modulus_bits(modulus) as f64));
            fields.insert("publicExponent".to_string(), Json::num(*exponent as f64));
        }
        ic_pkix::PublicKeyInfo::Ec { point, .. } => {
            fields.insert("pointBytes".to_string(), Json::num(point.len() as f64));
        }
        ic_pkix::PublicKeyInfo::Unsupported { oid } => {
            fields.insert("oid".to_string(), Json::str(dotted_oid(oid)));
        }
        _ => {}
    }
    if let Some(entry) = ontology_entry(key.algorithm()) {
        fields.insert("ontologyId".to_string(), Json::str(entry));
    }
    Json::Object(fields)
}

fn private_key_json(
    key: &ic_pkix::PrivateKeyInfo<'_>,
    container: &str,
    label: Option<&str>,
) -> Json {
    let mut fields = key_common(key.algorithm(), container, label);
    fields.insert("kind".to_string(), Json::str("private"));
    match key {
        ic_pkix::PrivateKeyInfo::Rsa {
            modulus,
            public_exponent,
            ..
        } => {
            fields.insert("bits".to_string(), Json::num(modulus_bits(modulus) as f64));
            fields.insert(
                "publicExponent".to_string(),
                Json::num(*public_exponent as f64),
            );
        }
        ic_pkix::PrivateKeyInfo::Ec { public_key, .. } => {
            fields.insert("hasPublicKey".to_string(), Json::Bool(public_key.is_some()));
        }
        ic_pkix::PrivateKeyInfo::Unsupported { oid } => {
            fields.insert("oid".to_string(), Json::str(dotted_oid(oid)));
        }
        _ => {}
    }
    if let Some(entry) = ontology_entry(key.algorithm()) {
        fields.insert("ontologyId".to_string(), Json::str(entry));
    }
    Json::Object(fields)
}

/// Bit length of a minimal big-endian integer.
fn modulus_bits(modulus: &[u8]) -> usize {
    match modulus.iter().position(|b| *b != 0) {
        Some(first) => (modulus.len() - first) * 8 - modulus[first].leading_zeros() as usize,
        None => 0,
    }
}

/// Render OID content bytes as a dotted string, so an unrecognized algorithm
/// can be looked up rather than merely reported as unknown.
fn dotted_oid(oid: &[u8]) -> String {
    let mut arcs: Vec<u64> = Vec::new();
    let mut value = 0u64;
    for (i, byte) in oid.iter().enumerate() {
        value = (value << 7) | (*byte & 0x7f) as u64;
        if byte & 0x80 == 0 {
            if i == 0 || arcs.is_empty() {
                // The first byte encodes two arcs: 40 * first + second.
                let first = core::cmp::min(value / 40, 2);
                arcs.push(first);
                arcs.push(value - first * 40);
            } else {
                arcs.push(value);
            }
            value = 0;
        }
    }
    arcs.iter()
        .map(|a| a.to_string())
        .collect::<Vec<_>>()
        .join(".")
}

/// The ontology entry a key algorithm points at, where there is exactly one.
///
/// RSA deliberately has none: a key does not fix the padding, so `rsa-pss-*`
/// and `rsa-pkcs1-*` are both reachable from the same key and the caller has to
/// choose.
fn ontology_entry(algorithm: ic_pkix::KeyAlgorithm) -> Option<&'static str> {
    match algorithm {
        ic_pkix::KeyAlgorithm::EcP256 => Some("ecdsa-p256-sha256"),
        ic_pkix::KeyAlgorithm::EcP384 => Some("ecdsa-p384-sha384"),
        ic_pkix::KeyAlgorithm::EcP521 => Some("ecdsa-p521-sha512"),
        ic_pkix::KeyAlgorithm::Ed25519 => Some("ed25519"),
        ic_pkix::KeyAlgorithm::X25519 => Some("x25519"),
        ic_pkix::KeyAlgorithm::Rsa | ic_pkix::KeyAlgorithm::Unknown => None,
    }
}

pub fn random_hex(n: usize) -> Result<String, String> {
    if n == 0 || n > 1024 {
        return Err("request between 1 and 1024 bytes".to_string());
    }
    let mut rng = ic_drbg::Rng::from_os().map_err(|e| e.to_string())?;
    let mut out = vec![0u8; n];
    rng.fill(&mut out).map_err(|e| e.to_string())?;
    Ok(ic_core::codec::hex(&out))
}

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

    #[test]
    fn entry_json_round_trips_through_the_parser() {
        for e in ic_ontology::all() {
            let text = entry_json(e).to_string();
            let parsed = ic_json::parse(&text)
                .unwrap_or_else(|err| panic!("{} produced invalid JSON: {err}", e.id));
            assert_eq!(parsed.get("id").unwrap().as_str(), Some(e.id));
        }
    }

    #[test]
    fn list_filters_and_rejects_unknown_vocabulary() {
        let aeads = list(Some("aead"), None, false, true).unwrap();
        assert!(aeads.iter().any(|e| e.id == "aes-256-gcm"));
        assert!(list(Some("not-a-class"), None, false, false).is_err());
        assert!(list(None, Some("not-a-purpose"), false, false).is_err());

        let fips_aeads = list(Some("aead"), None, true, true).unwrap();
        assert!(!fips_aeads.iter().any(|e| e.id == "chacha20-poly1305"));
    }

    #[test]
    fn recommend_json_reports_availability_honestly() {
        let ok = recommend_json("encrypt-message", true, false, false).unwrap();
        assert_eq!(ok.get("status").unwrap().as_str(), Some("ok"));
        assert_eq!(ok.get("recommended").unwrap().as_str(), Some("aes-256-gcm"));

        // Under a FIPS policy the approved scheme is chosen, never the
        // available-but-unapproved Ed25519.
        let signing = recommend_json("sign-data", true, false, false).unwrap();
        assert_eq!(signing.get("status").unwrap().as_str(), Some("ok"));
        assert_eq!(
            signing.get("recommended").unwrap().as_str(),
            Some("ecdsa-p256-sha256")
        );

        // Post-quantum key agreement was the example of declining here, because
        // ML-KEM-768 was implemented but not vector-tested. It is checked
        // against ACVP now, so it is offered.
        let pq = recommend_json("agree-key", false, true, false).unwrap();
        assert_eq!(pq.get("status").unwrap().as_str(), Some("ok"));
        assert_eq!(pq.get("recommended").unwrap().as_str(), Some("ml-kem-768"));

        // Something genuinely unsatisfiable still declines, which is the
        // behaviour those lines were really there to protect: this asks for a
        // FIPS-approved signature and gets one, and would rather have nothing
        // than Ed25519.
        let signing = recommend_json("sign-data", true, false, false).unwrap();
        assert_ne!(
            signing.get("recommended").unwrap().as_str(),
            Some("ed25519")
        );
    }

    #[test]
    fn digest_matches_the_library() {
        assert_eq!(
            digest_hex("sha2-256", b"abc").unwrap(),
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
        assert_eq!(
            digest_hex("sha256", b"abc").unwrap(),
            digest_hex("sha2-256", b"abc").unwrap()
        );
    }

    /// Asking for a hash by the name of a cipher should explain the category
    /// error rather than just saying "unknown".
    #[test]
    fn digest_rejects_non_hashes_with_a_useful_message() {
        let err = digest_hex("aes-256-gcm", b"abc").unwrap_err();
        assert!(err.contains("aead"), "got: {err}");
        let err = digest_hex("sha-1", b"abc").unwrap_err();
        assert!(err.contains("not available"), "got: {err}");
    }

    #[test]
    fn hmac_matches_the_library() {
        assert_eq!(
            hmac_hex("hmac-sha2-256", &[0x0b; 20], b"Hi There").unwrap(),
            "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"
        );
        assert!(hmac_hex("hmac-md5", b"k", b"m").is_err());
    }

    #[test]
    fn seal_produces_a_ciphertext_and_tag() {
        let (ct, tag) = seal_hex("aes-256-gcm", &[0u8; 32], &[0u8; 12], b"", b"data").unwrap();
        assert_eq!(ct.len(), 8, "4 bytes of ciphertext in hex");
        assert_eq!(tag.len(), 32);
        assert!(seal_hex("aes-256-gcm", &[0u8; 16], &[0u8; 12], b"", b"x").is_err());
    }

    #[test]
    fn selftest_report_is_complete() {
        let report = selftest_json(None).unwrap();
        assert_eq!(report.get("failed").unwrap().as_i64(), Some(0));
        assert_eq!(report.get("allPassed").unwrap().as_bool(), Some(true));
        assert_eq!(report.get("integrityCheck").unwrap().as_bool(), Some(true));

        let one = selftest_json(Some("sha2-256")).unwrap();
        assert_eq!(one.get("passed").unwrap().as_bool(), Some(true));
        assert!(selftest_json(Some("nope")).is_err());
    }

    #[test]
    fn capabilities_do_not_overclaim() {
        let caps = capabilities_json();
        let text = caps.to_string();
        assert!(text.contains("NOT been submitted"));
        let list = caps.get("capabilities").unwrap();
        match list {
            Json::Array(items) => {
                let fips = items
                    .iter()
                    .find(|c| c.get("id").unwrap().as_str() == Some("fips-validated"))
                    .unwrap();
                assert_eq!(fips.get("present").unwrap().as_bool(), Some(false));
            }
            _ => panic!("expected an array"),
        }
    }

    #[test]
    fn random_respects_its_bounds() {
        assert_eq!(random_hex(16).unwrap().len(), 32);
        assert!(random_hex(0).is_err());
        assert!(random_hex(4096).is_err());
        assert_ne!(random_hex(32).unwrap(), random_hex(32).unwrap());
    }

    #[test]
    fn error_catalog_is_exported() {
        match errors_json() {
            Json::Array(items) => {
                assert!(!items.is_empty());
                assert!(items
                    .iter()
                    .any(|d| d.get("id").unwrap().as_str() == Some("authentication-failed")));
            }
            _ => panic!("expected an array"),
        }
    }
}

#[cfg(test)]
mod key_tests {
    use super::*;

    /// An Ed25519 public key in SPKI form. The base64 prefix `MCowBQYDK2Vw` is
    /// what every Ed25519 public key starts with, which makes this vector
    /// checkable against any other implementation's output.
    const ED25519_PUB: &str = "-----BEGIN PUBLIC KEY-----
        MCowBQYDK2VwAyEAyFOtDwzSthmuqSzuxP1Wok1kmdWEznklfkXP2BObYKc=
        -----END PUBLIC KEY-----
";

    fn field(json: &Json, key: &str) -> String {
        json.get(key)
            .and_then(|v| v.as_str())
            .unwrap_or_default()
            .to_string()
    }

    #[test]
    fn a_pem_public_key_is_identified() {
        let json = key_json(ED25519_PUB.as_bytes()).unwrap();
        assert_eq!(field(&json, "algorithm"), "ed25519");
        assert_eq!(field(&json, "kind"), "public");
        assert_eq!(field(&json, "container"), "pem");
        assert_eq!(field(&json, "pemLabel"), "PUBLIC KEY");
        assert_eq!(field(&json, "ontologyId"), "ed25519");
    }

    /// The same key without its PEM wrapper must identify the same way.
    #[test]
    fn a_bare_der_key_is_identified() {
        let mut der = vec![0u8; 256];
        let n = ic_pkix::pem::decode("PUBLIC KEY", ED25519_PUB.as_bytes(), &mut der).unwrap();
        let json = key_json(&der[..n]).unwrap();
        assert_eq!(field(&json, "algorithm"), "ed25519");
        assert_eq!(field(&json, "container"), "der");
        assert!(json.get("pemLabel").is_none());
    }

    #[test]
    fn a_private_key_is_reported_as_private() {
        let seed = [0x42u8; 32];
        let mut der = [0u8; 128];
        let n = ic_pkix::PrivateKeyInfo::Ed25519(&seed)
            .to_der(&mut der)
            .unwrap();
        let json = key_json(&der[..n]).unwrap();
        assert_eq!(field(&json, "kind"), "private");
        assert_eq!(field(&json, "algorithm"), "ed25519");
    }

    /// Nothing secret may appear in what `key_inspect` hands back.
    ///
    /// The tool tells agents it is "safe to run on an unknown file" because it
    /// "parses structure only". An agent relays that output into a transcript,
    /// a log, or another model's context, so the claim has to be true of the
    /// bytes, not just of the code: a field added later that echoes part of a
    /// key would be caught here and nowhere else.
    ///
    /// Each secret is filled with a byte pattern that occurs nowhere in a
    /// structural answer, and the search is over the serialized response rather
    /// than any particular field, since the risk is a field nobody thought to
    /// look at.
    #[test]
    fn inspecting_a_private_key_reveals_nothing_secret() {
        /// Distinctive enough that a match is not a coincidence: 8 bytes, and
        /// not a length, an exponent, or anything else structural.
        const SECRET: [u8; 8] = [0xde, 0xad, 0xbe, 0xef, 0xfe, 0xed, 0xfa, 0xce];

        fn secret_of(len: usize) -> Vec<u8> {
            let mut v: Vec<u8> = SECRET.iter().copied().cycle().take(len).collect();
            // A leading zero would be stripped as non-minimal; keep it high so
            // the value survives DER encoding intact.
            v[0] = 0xde;
            v
        }

        fn assert_absent(what: &str, json: &Json, secret: &[u8]) {
            let rendered = json.to_string();

            // Hex, both cases, since that is how bytes would most likely be
            // rendered if something did emit them.
            let hex = ic_core::codec::hex(secret);
            assert!(
                !rendered.contains(&hex) && !rendered.contains(&hex.to_uppercase()),
                "{what}: the response contains the secret as hex:\n{rendered}"
            );

            // Base64, as a PEM body would carry it.
            let mut b64 = String::new();
            const ALPHABET: &[u8] =
                b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
            for chunk in secret.chunks(3) {
                let mut block = [0u8; 3];
                block[..chunk.len()].copy_from_slice(chunk);
                let n = u32::from_be_bytes([0, block[0], block[1], block[2]]);
                for i in 0..4 {
                    b64.push(ALPHABET[((n >> (18 - 6 * i)) & 0x3f) as usize] as char);
                }
            }
            // Trimmed, because the secret may be embedded mid-stream and so not
            // aligned to a 3-byte boundary at either end.
            let core = &b64[4..b64.len() - 4];
            assert!(
                !rendered.contains(core),
                "{what}: the response contains the secret as base64:\n{rendered}"
            );

            // And raw, in case a byte string were passed through as text.
            let raw: String = secret.iter().map(|b| *b as char).collect();
            assert!(
                !rendered.contains(&raw),
                "{what}: the response contains the secret verbatim"
            );
        }

        let mut examined = 0;

        // Ed25519: the whole seed is secret.
        let seed = secret_of(32);
        let mut der = [0u8; 128];
        let n = ic_pkix::PrivateKeyInfo::Ed25519(&seed)
            .to_der(&mut der)
            .unwrap();
        let json = key_json(&der[..n]).unwrap();
        assert_eq!(field(&json, "kind"), "private", "the key must have parsed");
        assert_absent("ed25519", &json, &seed);
        examined += 1;

        // X25519: likewise.
        let scalar = secret_of(32);
        let n = ic_pkix::PrivateKeyInfo::X25519(&scalar)
            .to_der(&mut der)
            .unwrap();
        let json = key_json(&der[..n]).unwrap();
        assert_eq!(field(&json, "kind"), "private");
        assert_absent("x25519", &json, &scalar);
        examined += 1;

        // P-256: the scalar is secret, the point is not.
        let scalar = secret_of(32);
        let point = [0x04u8; 65];
        let mut der = [0u8; 256];
        let n = ic_pkix::PrivateKeyInfo::Ec {
            algorithm: ic_pkix::KeyAlgorithm::EcP256,
            private_key: &scalar,
            public_key: Some(&point),
        }
        .to_der(&mut der)
        .unwrap();
        let json = key_json(&der[..n]).unwrap();
        assert_eq!(field(&json, "kind"), "private");
        assert_eq!(
            json.get("hasPublicKey").unwrap().as_bool(),
            Some(true),
            "the point was supplied and should be reported present"
        );
        assert_absent("ec-p256", &json, &scalar);
        examined += 1;

        // RSA: every field but the modulus and the public exponent is secret,
        // and each is checked on its own so one being echoed is not masked by
        // the others.
        let modulus = {
            let mut m = vec![0xa7u8; 256];
            m[0] = 0xd1;
            m
        };
        let private_exponent = secret_of(256);
        let prime1 = secret_of(128);
        let prime2 = {
            let mut v = secret_of(128);
            v[1] = 0xad;
            v
        };
        let exponent1 = secret_of(128);
        let exponent2 = secret_of(128);
        let coefficient = secret_of(128);
        let mut der = vec![0u8; 4096];
        let n = ic_pkix::PrivateKeyInfo::Rsa {
            modulus: &modulus,
            public_exponent: 65537,
            private_exponent: &private_exponent,
            prime1: &prime1,
            prime2: &prime2,
            exponent1: &exponent1,
            exponent2: &exponent2,
            coefficient: &coefficient,
        }
        .to_der(&mut der)
        .unwrap();
        let json = key_json(&der[..n]).unwrap();
        assert_eq!(field(&json, "kind"), "private");
        assert_eq!(
            json.get("bits").unwrap().as_i64(),
            Some(2048),
            "the structural answer must still be right"
        );
        for (name, secret) in [
            ("privateExponent", &private_exponent),
            ("prime1", &prime1),
            ("prime2", &prime2),
            ("exponent1", &exponent1),
            ("exponent2", &exponent2),
            ("coefficient", &coefficient),
        ] {
            assert_absent(&format!("rsa {name}"), &json, secret);
        }
        examined += 1;

        // Every private variant but `Unsupported`, which holds an OID and no
        // key material. A floor, so a variant quietly dropped from this list
        // does not leave the test passing on fewer.
        assert_eq!(examined, 4, "not every private key form was inspected");
    }

    /// RSA reports its size, and deliberately reports no single ontology entry:
    /// the key does not choose between PSS and PKCS#1 v1.5.
    #[test]
    fn an_rsa_key_reports_its_size_but_not_a_padding() {
        let mut modulus = [0xa7u8; 256];
        modulus[0] = 0xd1;
        let mut der = [0u8; 512];
        let n = ic_pkix::PublicKeyInfo::Rsa {
            modulus: &modulus,
            exponent: 65537,
        }
        .to_der(&mut der)
        .unwrap();

        let json = key_json(&der[..n]).unwrap();
        assert_eq!(field(&json, "algorithm"), "rsa");
        assert_eq!(json.get("bits").unwrap().as_i64(), Some(2048));
        assert_eq!(json.get("publicExponent").unwrap().as_i64(), Some(65537));
        assert!(
            json.get("ontologyId").is_none(),
            "an rsa key does not name a padding"
        );
    }

    #[test]
    fn modulus_bits_counts_from_the_top_set_bit() {
        assert_eq!(modulus_bits(&[0x80]), 8);
        assert_eq!(modulus_bits(&[0x01]), 1);
        assert_eq!(modulus_bits(&[0x00, 0x01]), 1);
        assert_eq!(modulus_bits(&[0xff, 0xff]), 16);
        assert_eq!(modulus_bits(&[]), 0);
        assert_eq!(modulus_bits(&[0x00, 0x00]), 0);
    }

    /// The dotted form is what makes an unrecognized algorithm actionable: the
    /// caller can look the number up. Checked against arcs whose encoding is
    /// documented in X.690 and RFC 5480.
    #[test]
    fn unknown_algorithms_report_a_dotted_oid() {
        // DSA, 1.2.840.10040.4.1.
        let dsa: &[u8] = &[0x2a, 0x86, 0x48, 0xce, 0x38, 0x04, 0x01];
        assert_eq!(dotted_oid(dsa), "1.2.840.10040.4.1");
        assert_eq!(dotted_oid(&[0x2b, 0x65, 0x70]), "1.3.101.112");
        assert_eq!(dotted_oid(&[0x88, 0x37, 0x03]), "2.999.3");

        let spki: &[u8] = &[
            0x30, 0x10, 0x30, 0x09, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x38, 0x04, 0x01, 0x03,
            0x03, 0x00, 0x01, 0x02,
        ];
        let json = key_json(spki).unwrap();
        assert_eq!(field(&json, "algorithm"), "unknown");
        assert_eq!(field(&json, "oid"), "1.2.840.10040.4.1");
    }

    #[test]
    fn rubbish_is_an_error_not_a_guess() {
        assert!(key_json(b"not a key at all").is_err());
        assert!(key_json(&[]).is_err());
        assert!(key_json(
            b"-----BEGIN PUBLIC KEY-----
zzzz
-----END PUBLIC KEY-----
"
        )
        .is_err());
    }
}

// ---------------------------------------------------------------------------
// The standards knowledgebase.
// ---------------------------------------------------------------------------

/// One requirement, as JSON.
///
/// `compliance` is a tagged object rather than a bare string because the three
/// cases carry different payloads, and flattening them would lose the reason a
/// requirement is not applicable — which is the part a reader actually needs.
pub fn requirement_json(doc: &Standard, r: &Requirement) -> Json {
    let compliance = match r.compliance {
        Compliance::Met { file, symbol } => Json::object([
            ("state", Json::str("met")),
            ("file", Json::str(file)),
            ("evidence", Json::str(symbol)),
        ]),
        Compliance::Partial { file, symbol, gap } => Json::object([
            ("state", Json::str("partial")),
            ("file", Json::str(file)),
            ("evidence", Json::str(symbol)),
            ("gap", Json::str(gap)),
        ]),
        Compliance::NotApplicable { why } => Json::object([
            ("state", Json::str("not-applicable")),
            ("reason", Json::str(why)),
        ]),
        Compliance::Unmet { why } => {
            Json::object([("state", Json::str("unmet")), ("reason", Json::str(why))])
        }
    };
    Json::object([
        ("id", Json::str(r.id)),
        ("standard", Json::str(doc.id)),
        ("section", Json::str(r.section)),
        ("obligation", Json::str(r.obligation.id())),
        ("mandatory", Json::Bool(r.obligation.is_mandatory())),
        ("statement", Json::str(r.statement)),
        ("rationale", Json::str(r.rationale)),
        (
            "appliesTo",
            Json::Array(r.applies_to.iter().map(|a| Json::str(*a)).collect()),
        ),
        ("compliance", compliance),
    ])
}

/// One document, as JSON.
pub fn standard_json(s: &Standard) -> Json {
    Json::object([
        ("id", Json::str(s.id)),
        ("title", Json::str(s.title)),
        ("body", Json::str(s.body.id())),
        ("scope", Json::str(s.scope.id())),
        ("year", Json::Number(s.year as f64)),
        ("status", Json::str(s.status.id())),
        ("current", Json::Bool(s.status.is_current())),
        (
            "supersededBy",
            Json::Array(s.superseded_by.iter().map(|x| Json::str(*x)).collect()),
        ),
        ("url", Json::str(s.url)),
        ("summary", Json::str(s.summary)),
        (
            "algorithms",
            Json::Array(s.algorithms().map(Json::str).collect()),
        ),
        (
            "requirements",
            Json::Array(
                s.requirements
                    .iter()
                    .map(|r| requirement_json(s, r))
                    .collect(),
            ),
        ),
    ])
}

/// Every document, optionally narrowed to those a given algorithm cites.
pub fn standards_json(algorithm: Option<&str>) -> Result<Json, String> {
    let docs: Vec<Json> = match algorithm {
        None => standards::STANDARDS.iter().map(standard_json).collect(),
        Some(id) => {
            if !ic_ontology::registry::REGISTRY.iter().any(|e| e.id == id) {
                return Err(format!("unknown algorithm '{id}'"));
            }
            standards::standards_for(id).map(standard_json).collect()
        }
    };
    Ok(Json::object([
        ("count", Json::Number(docs.len() as f64)),
        ("standards", Json::Array(docs)),
    ]))
}

/// Look one document up by its citation.
pub fn standard_lookup_json(id: &str) -> Result<Json, String> {
    standards::standard(id)
        .map(standard_json)
        .ok_or_else(|| format!("unknown standard '{id}'"))
}

/// Every requirement, optionally narrowed by compliance state or algorithm.
///
/// The counts come back alongside the list because the first question anyone
/// asks of a conformance view is "how much is outstanding", and making a caller
/// tally it themselves invites them to tally it differently.
pub fn requirements_json(state: Option<&str>, algorithm: Option<&str>) -> Result<Json, String> {
    if let Some(s) = state {
        if !["met", "partial", "unmet", "not-applicable"].contains(&s) {
            return Err(format!(
                "unknown compliance state '{s}'; try met, partial, unmet or not-applicable"
            ));
        }
    }
    let mut items = Vec::new();
    let (mut met, mut partial, mut unmet, mut na) = (0usize, 0usize, 0usize, 0usize);
    for (doc, r) in standards::requirements() {
        match r.compliance.id() {
            "met" => met += 1,
            "partial" => partial += 1,
            "unmet" => unmet += 1,
            _ => na += 1,
        }
        if let Some(s) = state {
            if r.compliance.id() != s {
                continue;
            }
        }
        if let Some(a) = algorithm {
            // An empty applies_to means the whole library, so it matches every
            // algorithm rather than none.
            if !r.applies_to.is_empty() && !r.applies_to.contains(&a) {
                continue;
            }
        }
        items.push(requirement_json(doc, r));
    }
    Ok(Json::object([
        ("count", Json::Number(items.len() as f64)),
        (
            "totals",
            Json::object([
                ("met", Json::Number(met as f64)),
                ("partial", Json::Number(partial as f64)),
                ("unmet", Json::Number(unmet as f64)),
                ("notApplicable", Json::Number(na as f64)),
            ]),
        ),
        ("requirements", Json::Array(items)),
    ]))
}

// ---------------------------------------------------------------------------
// Security frameworks: CWE, MITRE ATT&CK, CMMC 2.0.
// ---------------------------------------------------------------------------

/// One control, as JSON.
pub fn control_json(c: &Control) -> Json {
    let compliance = match c.compliance {
        Compliance::Met { file, symbol } => Json::object([
            ("state", Json::str("met")),
            ("file", Json::str(file)),
            ("evidence", Json::str(symbol)),
        ]),
        Compliance::Partial { file, symbol, gap } => Json::object([
            ("state", Json::str("partial")),
            ("file", Json::str(file)),
            ("evidence", Json::str(symbol)),
            ("gap", Json::str(gap)),
        ]),
        Compliance::NotApplicable { why } => Json::object([
            ("state", Json::str("not-applicable")),
            ("reason", Json::str(why)),
        ]),
        Compliance::Unmet { why } => {
            Json::object([("state", Json::str("unmet")), ("reason", Json::str(why))])
        }
    };
    Json::object([
        ("id", Json::str(c.id)),
        ("framework", Json::str(c.framework.id())),
        ("frameworkName", Json::str(c.framework.name())),
        ("title", Json::str(c.title)),
        ("description", Json::str(c.description)),
        ("bearing", Json::str(c.bearing)),
        (
            "algorithms",
            Json::Array(c.algorithms.iter().map(|a| Json::str(*a)).collect()),
        ),
        (
            "standards",
            Json::Array(c.standards.iter().map(|s| Json::str(*s)).collect()),
        ),
        ("compliance", compliance),
    ])
}

/// Controls, optionally narrowed by framework, algorithm or compliance state.
///
/// The totals come back alongside the list, and the `unmet` list is named
/// separately rather than left for a caller to filter out. A compliance view
/// whose gaps are one filter away from being missed is a compliance view that
/// will be quoted without them.
pub fn controls_json(
    framework: Option<&str>,
    algorithm: Option<&str>,
    state: Option<&str>,
) -> Result<Json, String> {
    let wanted = match framework {
        None => None,
        Some("cwe") => Some(Framework::Cwe),
        Some("attack") => Some(Framework::Attack),
        Some("cmmc") => Some(Framework::Cmmc),
        Some(other) => {
            return Err(format!(
                "unknown framework '{other}'; try cwe, attack or cmmc"
            ))
        }
    };
    if let Some(s) = state {
        if !["met", "partial", "unmet", "not-applicable"].contains(&s) {
            return Err(format!(
                "unknown compliance state '{s}'; try met, partial, unmet or not-applicable"
            ));
        }
    }
    if let Some(a) = algorithm {
        if !ic_ontology::registry::REGISTRY.iter().any(|e| e.id == a) {
            return Err(format!("unknown algorithm '{a}'"));
        }
    }

    let mut items = Vec::new();
    let mut unmet = Vec::new();
    let (mut met, mut partial, mut n_unmet, mut na) = (0usize, 0usize, 0usize, 0usize);

    for c in frameworks::CONTROLS {
        if let Some(f) = wanted {
            if c.framework != f {
                continue;
            }
        }
        if let Some(a) = algorithm {
            if !c.algorithms.is_empty() && !c.algorithms.contains(&a) {
                continue;
            }
        }
        match c.compliance.id() {
            "met" => met += 1,
            "partial" => partial += 1,
            "unmet" => {
                n_unmet += 1;
                unmet.push(Json::str(c.id));
            }
            _ => na += 1,
        }
        if let Some(s) = state {
            if c.compliance.id() != s {
                continue;
            }
        }
        items.push(control_json(c));
    }

    Ok(Json::object([
        ("count", Json::Number(items.len() as f64)),
        (
            "totals",
            Json::object([
                ("met", Json::Number(met as f64)),
                ("partial", Json::Number(partial as f64)),
                ("unmet", Json::Number(n_unmet as f64)),
                ("notApplicable", Json::Number(na as f64)),
            ]),
        ),
        ("unmet", Json::Array(unmet)),
        ("cvePosture", Json::str(frameworks::cve_posture())),
        (
            "fipsValidated",
            Json::Bool(ic_ontology::runtime::has("fips-validated")),
        ),
        ("controls", Json::Array(items)),
    ]))
}

/// Look one control up by its framework identifier.
pub fn control_lookup_json(id: &str) -> Result<Json, String> {
    frameworks::control(id)
        .map(control_json)
        .ok_or_else(|| format!("unknown control '{id}'"))
}