ignition-core 1.6.0

Core library for ign: config, profiles, gateway client, actions, error taxonomy
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
//! API-key adoption wire models + session-tier calls (ADOPT-01).
//!
//! Every shape here is LIVE-CAPTURED on the `ignition-devops` rig,
//! Ignition 8.3.6 (b2026042713), 2026-09-18 — browser-devtools capture
//! while clicking Config → Security → API Keys / General Settings as
//! `admin`, the same method as the trial route. Full bodies + the
//! capture narrative: `.planning/research/ADOPT-RESEARCH.md`.
//!
//! ## The wire (live-proven end-to-end, key minted + used same second)
//!
//! 8.3 API keys are NOT a bespoke route family — they are resource
//! type `ignition/api-token` on the resources API, plus ONE generate
//! endpoint for the key material:
//!
//! 1. `GET  /data/api/v1/resources/list/ignition/api-token` — the
//!    idempotent find-by-name (hash only; the plaintext key appears
//!    NOWHERE in this list).
//! 2. `POST /data/api/v1/api-token/generate` — `{key, hash}`; the
//!    plaintext key is returned HERE AND ONLY HERE.
//! 3. `POST /data/api/v1/resources/ignition/api-token` — array-of-one
//!    resource record carrying the hash (NOT the key).
//! 4. The security-properties singleton — the permissions wiring
//!    (doctor's part-2 diagnosis, made writable). The GET is
//!    `/data/api/v1/resources/singleton/ignition/security-properties`
//!    (carrying `?defaultIfUndefined=true`); the PUT is
//!    `/data/api/v1/resources/ignition/security-properties`.
//!
//! All four ride the native OIDC session cookie + `X-CSRF-Token` —
//! the [`crate::client::idp`] machinery verbatim (tier 1). This is
//! the bootstrap credential path: adopt runs BEFORE any API token
//! exists, so every call is session-tier.
//!
//! ## Live-discovered pitfalls (both documented in ADOPT-RESEARCH)
//!
//! - The security-properties PUT REPLACES the whole singleton config
//!   and carries the GET's `signature` (optimistic concurrency — it
//!   rotates on every write). Merge read-modify-write; never blind.
//! - `securityLevels: []` on an AnyOf permission means PUBLIC
//!   (everyone), not "nobody" — the UI serializes a checked Public
//!   as an empty list. [`merge_level_into`] only ever ADDS.
//! - Security levels are leaf-path TREES: granting
//!   `Authenticated/Roles/Administrator` serializes as ONE root
//!   `{name:"Authenticated", children:[{Roles, children:[{Administrator}]}]}`
//!   ([`level_tree`]).
//! - Pitfall 3, as MEASURED by plan 25-24 (G-25-11; fresh 8.3.6 and 8.3.3,
//!   `25-LIVE-CAPTURES.md` `### API key write admission (G-25-11)`): a
//!   nested write entry for a key's exact three-level path
//!   (`Authenticated>Roles>Administrator`) admits NO key, not even one granted
//!   that path. A nested TWO-level entry that no level definition declares
//!   (`Authenticated>IgnCliWrite`) admits exactly the keys granted that path
//!   and refuses every other key. A bare `Authenticated` write entry admits
//!   EVERY key, so it must never be added to `writePermissions`
//!   ([`merge_write_level_into`], [`write_admits_every_key`],
//!   [`remove_bare_authenticated_from_write`]).

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_json::json;

use crate::client::idp::GatewaySession;
use crate::client::idp::IdpLoginFlow;
use crate::error::CoreError;

/// The key-material generator (live-captured response below).
pub(crate) const GENERATE_PATH: &str = "/data/api/v1/api-token/generate";

/// The api-token resource list (idempotent find-by-name).
pub(crate) const API_TOKEN_LIST_PATH: &str = "/data/api/v1/resources/list/ignition/api-token";

/// The api-token resource CREATE (array-of-one body).
pub(crate) const API_TOKEN_CREATE_PATH: &str = "/data/api/v1/resources/ignition/api-token";

/// The security-properties singleton READ. NOTE: the NON-singleton
/// spelling `/resources/ignition/security-properties` is the PUT target
/// but 404s as a GET on live 8.3.6 (live-observed 2026-09-18; the
/// doctor capability reads the wrong path — see ADOPT-RESEARCH).
pub(crate) const SECURITY_SINGLETON_PATH: &str =
    "/data/api/v1/resources/singleton/ignition/security-properties";

/// The security-properties singleton WRITE (array-of-one + signature).
pub(crate) const SECURITY_PUT_PATH: &str = "/data/api/v1/resources/ignition/security-properties";

/// The api-token resource type string (the create answer's
/// `changes[].type`; asserted against the live answer in the mint).
pub(crate) const API_TOKEN_TYPE: &str = "ignition/api-token";

/// The basic-token profile type string.
pub(crate) const BASIC_TOKEN_TYPE: &str = "basic-token";

/// `POST /data/api/v1/api-token/generate` — the mint. The `key` is the
/// plaintext token, returned here and nowhere else; `hash` is what the
/// resource record stores. Live-captured 8.3.6:
///
/// ```json
/// { "key":  "<43-char urlsafe plaintext — REDACTED, same shape>",
///   "hash": "<43-char urlsafe stored hash — REDACTED, same shape>" }
/// ```
///
/// Redaction discipline: this struct carries the plaintext between the
/// client parse and the action's ONE exposure site (the result model +
/// keyring write). It deliberately implements `Debug` with the fields
/// visible — it lives core-internal for one hop; the ACTION result is
/// the documented exposure boundary.
#[derive(Debug, Clone, Deserialize)]
pub struct GeneratedKeyWire {
    /// The plaintext token (43-char urlsafe) — the only place the
    /// gateway ever returns it.
    #[serde(default)]
    pub key: String,
    /// The stored hash — rides the resource record's
    /// `config.settings.tokenHash`.
    #[serde(default)]
    pub hash: String,
}

/// One `ignition/api-token` resource record — the typed subset adopt
/// reads (find-by-name + config inspection); unknown keys round-trip.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ApiTokenRecord {
    /// The key's name — the find-by-name key AND half of the auth
    /// header value (`<name>:<key>`).
    #[serde(default)]
    pub name: String,
    /// Free-text description, when set.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Disabled keys authenticate as nothing.
    #[serde(default)]
    pub enabled: bool,
    /// The token profile + hash.
    #[serde(default)]
    pub config: ApiTokenConfig,
    /// Unknown keys round-trip (version, signature, attributes, …).
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

/// The record's `config` — `profile` (level + flags) + `settings`
/// (the hash).
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ApiTokenConfig {
    /// The token profile.
    #[serde(default)]
    pub profile: ApiTokenProfile,
    /// The hash store.
    #[serde(default)]
    pub settings: ApiTokenSettings,
}

/// The record's `config.profile` — everything doctor's three-part
/// diagnosis needs.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ApiTokenProfile {
    /// `"basic-token"` (the only extension point today).
    #[serde(rename = "type", default)]
    pub kind: String,
    /// The granted leaf-path trees (see [`level_tree`]).
    #[serde(rename = "securityLevels", default)]
    pub security_levels: Vec<Value>,
    /// The "Require secure connections" flag — MUST be false for
    /// http gateways or every request 403s (three-part cause 3).
    #[serde(rename = "secureChannelRequired", default)]
    pub secure_channel_required: bool,
    /// Creation time, epoch milliseconds.
    #[serde(default)]
    pub timestamp: i64,
}

/// The record's `config.settings` — the hash only, never the key.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ApiTokenSettings {
    /// The stored hash (`config.settings.tokenHash`).
    #[serde(rename = "tokenHash", default)]
    pub token_hash: String,
}

/// The shared resources-API mutation envelope (create + singleton PUT;
/// live-captured on the create — `{success, changes[], problem}`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ResourceMutationWire {
    /// The gateway's verdict — `false` or a non-2xx both refuse.
    #[serde(default)]
    pub success: bool,
    /// What changed (name/type/collection/newSignature).
    #[serde(default)]
    pub changes: Vec<ResourceChangeWire>,
    /// Populated (non-null) when the gateway reports a partial
    /// problem — surfaced verbatim.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub problem: Option<Value>,
}

/// One `changes[]` row.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ResourceChangeWire {
    #[serde(default)]
    pub name: String,
    #[serde(rename = "type", default)]
    pub kind: String,
    #[serde(default)]
    pub collection: String,
    #[serde(rename = "newSignature", default)]
    pub new_signature: String,
}

/// Render one granted level tree as its slash path
/// (`Authenticated/Roles/Administrator`) — the human form for report
/// rows. Walks the first-child chain (a granted tree is a single
/// path by construction). Pure function.
pub fn level_path_string(tree: &Value) -> String {
    let mut segments: Vec<&str> = Vec::new();
    let mut node = tree;
    while let Some(name) = node.get("name").and_then(Value::as_str) {
        segments.push(name);
        node = node
            .get("children")
            .and_then(Value::as_array)
            .and_then(|children| children.first())
            .unwrap_or(&Value::Null);
    }
    segments.join("/")
}

/// The security-properties singleton READ — typed shell (the merge
/// works at `Value` level inside `config`; the config's full shape is
/// passthrough by design, the doctor precedent).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SecuritySingletonWire {
    /// The optimistic-concurrency token — MUST ride the PUT verbatim
    /// or the write refuses (rotates on every write; live-observed).
    #[serde(default)]
    pub signature: String,
    /// `"core"` on every capture.
    #[serde(default = "default_collection")]
    pub collection: String,
    /// The whole config (`readPermissions`/`writePermissions` live
    /// HERE, nested — not at the record's top level).
    #[serde(default)]
    pub config: Value,
    /// Unknown keys round-trip.
    #[serde(flatten)]
    pub extra: BTreeMap<String, Value>,
}

fn default_collection() -> String {
    "core".to_string()
}

/// Build the nested leaf-path tree for one granted level:
/// `["Authenticated","Roles","Administrator"]` →
/// `{name:"Authenticated", children:[{name:"Roles", children:[
/// {name:"Administrator", children:[]}]}]}` — the live-captured
/// encoding (the type descriptor's `defaultConfig` and every
/// permissions list agree). Pure function; the unit test pins the
/// captured shape verbatim.
pub fn level_tree(path: &[&str]) -> Value {
    match path.split_first() {
        // The LEAF: children is the empty array (not [[]] — the
        // recursion stops one level early by construction).
        Some((head, [])) => json!({ "name": head, "children": [] }),
        Some((head, tail)) => json!({
            "name": head,
            "children": [level_tree(tail)],
        }),
        // Degenerate defensive value — adopt always passes a path.
        None => json!([]),
    }
}

/// Build the api-token CREATE body (array-of-one) — pure function,
/// the unit test pins it against the live-captured request VERBATIM.
/// `levels` is the key's granted security-level trees, in order (one
/// tree for a plain key; a write-capable key also holds the write
/// level). `timestamp_ms` is epoch milliseconds (std-only at call
/// sites).
pub fn build_token_create_body(
    name: &str,
    levels: &[Value],
    token_hash: &str,
    timestamp_ms: i64,
) -> Value {
    json!([{
        "name": name,
        "collection": "core",
        "enabled": true,
        "description": "",
        "config": {
            "profile": {
                "securityLevels": levels,
                "secureChannelRequired": false,
                "type": BASIC_TOKEN_TYPE,
                "timestamp": timestamp_ms
            },
            "settings": { "tokenHash": token_hash }
        }
    }])
}

/// Build the security-properties PUT body (array-of-one, whole-config
/// replacement + the GET's signature) — pure function; the unit test
/// pins the captured shape (incl. `gatewayAuditProfile: null`, which
/// the UI sends and the GET omits).
pub fn build_security_put_body(singleton: &SecuritySingletonWire, config: &Value) -> Value {
    json!([{
        "collection": singleton.collection,
        "enabled": true,
        "description": "",
        "signature": singleton.signature,
        "config": config
    }])
}

/// The READ-side merge: ensure a BARE-ROOT entry for the granted
/// level's top segment exists in an AnyOf permission list inside a
/// singleton `config` — add-if-missing, never remove, never mutate
/// existing entries. Returns true when the config changed. Missing
/// permissions objects are CREATED as
/// `{"type":"AnyOf","securityLevels":[bare-root]}`.
///
/// adopt no longer uses this for `writePermissions`: the bare root of
/// any level under `Authenticated` admits every API key, so a check
/// token minted for a read-only level could write (G-25-11). The
/// write side is [`merge_write_level_into`].
///
/// WHY THE BARE ROOT and not the granted leaf-path tree
/// (live-pinned 2026-09-18, ADOPT-RESEARCH pitfall 3): a permission
/// entry serialized as the NESTED tree
/// (`Authenticated>Roles>Administrator`, the UI's own spelling, with
/// or without descriptions) does NOT admit an API token granted that
/// exact path — 403, live-observed both ways, and re-measured by plan
/// 25-24 on 8.3.6 and 8.3.3 — while a BARE-root entry
/// (`{name:"Authenticated",children:[]}`) admits every
/// descendant-granted token (200, live-observed). The bare root is
/// the ANCESTOR form: strictly broader than the nested grant, so
/// adding it can only widen admission, never narrow.
///
/// The `[]` case (the PUBLIC encoding — pitfall 2) gets the bare
/// root ADDED, tightening Public down to root-admitted.
pub fn merge_level_into(config: &mut Value, field: &str, level: &Value) -> bool {
    let Some(incoming_root) = level.get("name").and_then(Value::as_str) else {
        return false;
    };
    let Some(config_object) = config.as_object_mut() else {
        return false;
    };
    let permissions = config_object
        .entry(field)
        .or_insert_with(|| json!({ "type": "AnyOf", "securityLevels": [] }));
    let Some(permissions_object) = permissions.as_object_mut() else {
        return false;
    };
    let levels = permissions_object
        .entry("securityLevels")
        .or_insert_with(|| Value::Array(Vec::new()));
    let Some(levels_array) = levels.as_array_mut() else {
        return false;
    };
    // Present = a BARE-root entry exists (children empty). A nested
    // same-root entry does NOT count — it does not admit the token
    // (pitfall 3), so the bare form must land beside it.
    let has_bare_root = levels_array.iter().any(|existing| {
        existing.get("name").and_then(Value::as_str) == Some(incoming_root)
            && existing
                .get("children")
                .and_then(Value::as_array)
                .is_some_and(|children| children.is_empty())
    });
    if has_bare_root {
        return false;
    }
    levels_array.push(json!({ "name": incoming_root, "children": [] }));
    true
}

/// Structural equality of two level trees by `name` and `children`,
/// recursively. Every other key (`description`, …) is ignored and a
/// missing `children` reads as empty.
fn level_matches(a: &Value, b: &Value) -> bool {
    let name = |v: &Value| v.get("name").and_then(Value::as_str).map(str::to_string);
    let children = |v: &Value| -> Vec<Value> {
        v.get("children")
            .and_then(Value::as_array)
            .cloned()
            .unwrap_or_default()
    };
    if name(a).is_none() || name(a) != name(b) {
        return false;
    }
    let (ca, cb) = (children(a), children(b));
    ca.len() == cb.len() && ca.iter().zip(cb.iter()).all(|(x, y)| level_matches(x, y))
}

/// `true` for a BARE entry (no children) named `Authenticated` or
/// `Public`, any case — the two forms every API key holds.
fn is_open_entry(entry: &Value, only_authenticated: bool) -> bool {
    let bare = entry
        .get("children")
        .and_then(Value::as_array)
        .is_none_or(Vec::is_empty);
    let name = entry.get("name").and_then(Value::as_str).unwrap_or("");
    bare && (name.eq_ignore_ascii_case("authenticated")
        || (!only_authenticated && name.eq_ignore_ascii_case("public")))
}

/// The WRITE-side merge: add `level` VERBATIM to
/// `writePermissions.securityLevels` unless an entry equal to it by
/// name and children already exists (recursive; descriptions and any
/// other key are ignored). Returns true when the config changed. A
/// missing permissions object is CREATED as AnyOf holding only
/// `level`. It never derives a root from `level`, so it can never
/// add a bare `Authenticated` unless the caller passes exactly that
/// (adopt refuses it before getting here).
pub fn merge_write_level_into(config: &mut Value, level: &Value) -> bool {
    let Some(config_object) = config.as_object_mut() else {
        return false;
    };
    let permissions = config_object
        .entry("writePermissions")
        .or_insert_with(|| json!({ "type": "AnyOf", "securityLevels": [] }));
    let Some(permissions_object) = permissions.as_object_mut() else {
        return false;
    };
    let levels = permissions_object
        .entry("securityLevels")
        .or_insert_with(|| Value::Array(Vec::new()));
    let Some(levels_array) = levels.as_array_mut() else {
        return false;
    };
    if levels_array.iter().any(|entry| level_matches(entry, level)) {
        return false;
    }
    levels_array.push(level.clone());
    true
}

/// `Some(reason)` when `writePermissions` admits EVERY API key: it is
/// not set, it is an empty list (Ignition reads `[]` as Public), or
/// it holds a bare `Authenticated` / bare `Public` entry (any case).
/// `None` for a list of exact levels, including a nested entry that
/// happens to be named `Authenticated` but has children.
pub fn write_admits_every_key(config: &Value) -> Option<String> {
    let levels = config
        .get("writePermissions")
        .and_then(|permissions| permissions.get("securityLevels"))
        .and_then(Value::as_array);
    let Some(levels) = levels else {
        return Some("writePermissions is not set".to_string());
    };
    if levels.is_empty() {
        return Some("writePermissions is empty, which Ignition reads as Public".to_string());
    }
    levels
        .iter()
        .find(|entry| is_open_entry(entry, false))
        .map(|entry| {
            let name = entry.get("name").and_then(Value::as_str).unwrap_or("");
            format!("writePermissions holds a bare {name} entry, which every API key holds")
        })
}

/// Remove every bare `Authenticated` entry (any case, no children)
/// from `writePermissions.securityLevels`. `Ok(true)` when something
/// was removed, `Ok(false)` when there was nothing to remove. Refuses
/// with `Err` — leaving `config` unchanged — when the removal would
/// leave the list empty, because Ignition reads `[]` as Public.
/// Never touches `readPermissions` or any other entry.
pub fn remove_bare_authenticated_from_write(config: &mut Value) -> Result<bool, String> {
    let Some(levels) = config
        .get_mut("writePermissions")
        .and_then(|permissions| permissions.get_mut("securityLevels"))
        .and_then(Value::as_array_mut)
    else {
        return Ok(false);
    };
    let kept: Vec<Value> = levels
        .iter()
        .filter(|entry| !is_open_entry(entry, true))
        .cloned()
        .collect();
    if kept.len() == levels.len() {
        return Ok(false);
    }
    if kept.is_empty() {
        return Err(
            "removing the bare Authenticated entry would leave writePermissions \
                    empty, which Ignition reads as Public"
                .to_string(),
        );
    }
    *levels = kept;
    Ok(true)
}

/// `GET …/resources/list/ignition/api-token` on the session tier —
/// the pre-token idempotent find. One page at `limit=100`; a gateway
/// holding MORE tokens than that REFUSES rather than guessing (the
/// review round's truncation trap: a key beyond the page would read
/// as absent and the mint would collide — an honest error beats an
/// ambiguous duplicate).
pub async fn api_tokens_via_session(
    flow: &IdpLoginFlow,
    session: &GatewaySession,
) -> Result<Vec<ApiTokenRecord>, CoreError> {
    let value = flow
        .session_get_json(session, API_TOKEN_LIST_PATH, &[("limit", "100")])
        .await?;
    let total = value
        .get("metadata")
        .and_then(|metadata| metadata.get("total"))
        .and_then(Value::as_i64)
        .unwrap_or(0);
    let items = value
        .get("items")
        .cloned()
        .ok_or_else(|| CoreError::Internal("api-token list carried no items array".into()))?;
    let count = items.as_array().map_or(0, Vec::len) as i64;
    if total > count {
        return Err(CoreError::Internal(format!(
            "this gateway holds {total} API keys — more than adopt's one-page \
             lookup ({count} returned); delete unused keys and re-run"
        )));
    }
    let records: Vec<ApiTokenRecord> = serde_json::from_value(items).map_err(|err| {
        CoreError::Internal(format!(
            "api-token list item did not match the record shape: {err}"
        ))
    })?;
    Ok(records)
}

/// `POST /data/api/v1/api-token/generate` on the session tier —
/// the mint (see [`GeneratedKeyWire`] for the plaintext discipline).
pub async fn generate_api_key_via_session(
    flow: &IdpLoginFlow,
    session: &GatewaySession,
) -> Result<GeneratedKeyWire, CoreError> {
    let value = flow
        .session_post_json(session, GENERATE_PATH, &json!({}))
        .await?;
    serde_json::from_value(value)
        .map_err(|err| CoreError::Internal(format!("api-token generate answer shape: {err}")))
}

/// `POST …/resources/ignition/api-token` on the session tier — the
/// create (array-of-one body from [`build_token_create_body`]).
pub async fn create_api_token_via_session(
    flow: &IdpLoginFlow,
    session: &GatewaySession,
    body: &Value,
) -> Result<ResourceMutationWire, CoreError> {
    let value = flow
        .session_post_json(session, API_TOKEN_CREATE_PATH, body)
        .await?;
    serde_json::from_value(value)
        .map_err(|err| CoreError::Internal(format!("api-token create answer shape: {err}")))
}

/// `GET …/resources/singleton/ignition/security-properties` on the
/// session tier — the pre-token read for the merge.
pub async fn security_properties_via_session(
    flow: &IdpLoginFlow,
    session: &GatewaySession,
) -> Result<SecuritySingletonWire, CoreError> {
    let value = flow
        .session_get_json(
            session,
            SECURITY_SINGLETON_PATH,
            &[("defaultIfUndefined", "true")],
        )
        .await?;
    serde_json::from_value(value)
        .map_err(|err| CoreError::Internal(format!("security-properties singleton shape: {err}")))
}

/// `PUT …/resources/ignition/security-properties` on the session
/// tier — the whole-config replacement (body from
/// [`build_security_put_body`]; the signature is the concurrency
/// gate).
pub async fn put_security_properties_via_session(
    flow: &IdpLoginFlow,
    session: &GatewaySession,
    body: &Value,
) -> Result<ResourceMutationWire, CoreError> {
    let value = flow
        .session_put_json(session, SECURITY_PUT_PATH, body)
        .await?;
    serde_json::from_value(value)
        .map_err(|err| CoreError::Internal(format!("security-properties put answer shape: {err}")))
}

#[cfg(test)]
mod tests {
    use serde_json::Value;
    use serde_json::json;

    use super::{
        ApiTokenRecord, GeneratedKeyWire, ResourceMutationWire, SecuritySingletonWire,
        build_security_put_body, build_token_create_body, level_tree, merge_level_into,
        merge_write_level_into, remove_bare_authenticated_from_write, write_admits_every_key,
    };

    /// THE live-capture regression — the generate answer's SHAPE,
    /// from the 8.3.6 rig capture (ADOPT-RESEARCH §1a). The VALUES
    /// are redacted same-shape synthetics: real key material never
    /// lands in source, even disposable-rig keys (review round).
    #[test]
    fn generate_parses_the_live_capture() {
        let wire: GeneratedKeyWire = serde_json::from_value(json!({
            "key": "AAAAexample-redacted-key-43-chars-urlsafe-0",
            "hash": "BBBBexample_redacted_hash_43_chars_urlsafe0"
        }))
        .expect("the live generate shape must parse");
        assert_eq!(wire.key.len(), 43, "urlsafe plaintext, 43 chars");
        assert_eq!(wire.hash.len(), 43, "stored hash, 43 chars");
    }

    /// The live-captured list item (trimmed to the typed fields +
    /// one passthrough key) must parse with the level + secure flag
    /// + hash visible (ADOPT-RESEARCH §1c).
    #[test]
    fn list_item_parses_the_live_capture() {
        let record: ApiTokenRecord = serde_json::from_value(json!({
            "type": "ignition/api-token",
            "name": "ign-adopt-capture",
            "description": "",
            "enabled": true,
            "version": 1,
            "collection": "core",
            "signature": "87717b87",
            "config": {
                "profile": {
                    "type": "basic-token",
                    "secureChannelRequired": false,
                    "securityLevels": [
                        { "name": "Authenticated", "children": [] }
                    ],
                    "timestamp": 1789760514446i64
                },
                "settings": { "tokenHash": "BBBBexample_redacted_hash_43_chars_urlsafe0" }
            },
            "attributes": { "uuid": "…", "enabled": true }
        }))
        .expect("the live list item shape must parse");
        assert_eq!(record.name, "ign-adopt-capture");
        assert!(record.enabled);
        assert!(!record.config.profile.secure_channel_required);
        assert_eq!(record.config.profile.kind, "basic-token");
        assert_eq!(
            record.config.settings.token_hash,
            "BBBBexample_redacted_hash_43_chars_urlsafe0"
        );
        assert!(record.extra.contains_key("signature"), "passthrough rides");
    }

    /// The create body builder must reproduce the live-captured
    /// request VERBATIM (modulo the varying timestamp) —
    /// ADOPT-RESEARCH §1b.
    #[test]
    fn create_body_matches_the_live_capture() {
        let level = level_tree(&["Authenticated"]);
        let body = build_token_create_body(
            "ign-adopt-capture",
            std::slice::from_ref(&level),
            "BBBBexample_redacted_hash_43_chars_urlsafe0",
            1789760514446,
        );
        let captured: Value = json!([{
            "name": "ign-adopt-capture",
            "collection": "core",
            "enabled": true,
            "description": "",
            "config": {
                "profile": {
                    "securityLevels": [
                        { "name": "Authenticated",
                          "description": "Represents a user who has been authenticated by the system.",
                          "children": [] }
                    ],
                    "secureChannelRequired": false,
                    "type": "basic-token",
                    "timestamp": 1789760514446i64
                },
                "settings": { "tokenHash": "BBBBexample_redacted_hash_43_chars_urlsafe0" }
            }
        }]);
        // descriptions are optional-in (the gateway echoes them out);
        // the builder omits them by design — compare descriptionless.
        let mut expected = captured;
        for record in expected.as_array_mut().expect("array") {
            record["config"]["profile"]["securityLevels"][0]
                .as_object_mut()
                .expect("level object")
                .remove("description");
        }
        assert_eq!(body, expected, "byte-faithful modulo descriptions");
    }

    /// The create answer — `{success, changes[], problem}` — must
    /// parse with the new signature visible (ADOPT-RESEARCH §1b).
    #[test]
    fn mutation_parses_the_live_create_answer() {
        let wire: ResourceMutationWire = serde_json::from_value(json!({
            "success": true,
            "changes": [{
                "name": "ign-adopt-capture",
                "type": "ignition/api-token",
                "collection": "core",
                "newSignature": "87717b874ec57a83e676c7e757e5264efc20e4cdb571525470ef6c93d5736f45"
            }],
            "problem": null
        }))
        .expect("the live create answer must parse");
        assert!(wire.success);
        assert_eq!(wire.changes.len(), 1);
        assert_eq!(wire.changes[0].kind, "ignition/api-token");
        assert!(wire.problem.is_none());
    }

    /// The singleton GET shape — signature + config-nested
    /// permissions + attributes passthrough (ADOPT-RESEARCH §2).
    #[test]
    fn singleton_parses_the_live_capture() {
        let wire: SecuritySingletonWire = serde_json::from_value(json!({
            "type": "ignition/security-properties",
            "signature": "dee8c94600032841",
            "collection": "core",
            "enabled": true,
            "config": {
                "readPermissions": {
                    "type": "AnyOf",
                    "securityLevels": [ { "name": "Authenticated", "children": [] } ]
                },
                "writePermissions": {
                    "type": "AnyOf",
                    "securityLevels": [ { "name": "Authenticated", "children": [] } ]
                }
            },
            "attributes": { "lastModification": { "actor": "admin" } }
        }))
        .expect("the live singleton shape must parse");
        assert_eq!(wire.signature, "dee8c94600032841");
        assert!(wire.config.get("writePermissions").is_some());
        assert!(wire.extra.contains_key("attributes"));
    }

    /// The Administrator leaf-path tree — the defaultConfig encoding
    /// (ADOPT-RESEARCH §1b/§2).
    #[test]
    fn level_tree_nests_the_administrator_path() {
        assert_eq!(
            level_tree(&["Authenticated", "Roles", "Administrator"]),
            json!({
                "name": "Authenticated",
                "children": [{
                    "name": "Roles",
                    "children": [{
                        "name": "Administrator",
                        "children": []
                    }]
                }]
            })
        );
        assert_eq!(
            level_tree(&["Authenticated"]),
            json!({ "name": "Authenticated", "children": [] })
        );
    }

    /// The slash-path render — report rows print the full leaf path.
    #[test]
    fn level_path_string_walks_the_chain() {
        use super::level_path_string;
        assert_eq!(
            level_path_string(&level_tree(&["Authenticated", "Roles", "Administrator"])),
            "Authenticated/Roles/Administrator"
        );
        assert_eq!(
            level_path_string(&level_tree(&["Authenticated"])),
            "Authenticated"
        );
    }

    /// merge: ensures a BARE-ROOT entry for the granted level's top
    /// segment — add-if-missing, idempotent; a NESTED same-root entry
    /// does NOT count (pitfall 3: nested entries do not admit
    /// equal-path tokens — the bare root lands BESIDE it, the
    /// fresh-gateway-default fix); `[]` (the PUBLIC encoding —
    /// pitfall 2) gets the root ADDED; a missing field is created.
    #[test]
    fn merge_adds_missing_and_is_idempotent() {
        let authenticated = level_tree(&["Authenticated"]);
        let administrator = level_tree(&["Authenticated", "Roles", "Administrator"]);
        let bare = |root: &str| json!({ "name": root, "children": [] });

        // Different root → the bare root added; re-run changes nothing.
        let mut config = json!({
            "writePermissions": {
                "type": "AnyOf",
                "securityLevels": [ bare("SecurityZones") ]
            }
        });
        assert!(merge_level_into(
            &mut config,
            "writePermissions",
            &administrator
        ));
        assert!(
            !merge_level_into(&mut config, "writePermissions", &administrator),
            "idempotent re-run changes nothing"
        );
        assert_eq!(
            config["writePermissions"]["securityLevels"][1],
            bare("Authenticated"),
            "the BARE root lands (pitfall 3), not the nested tree"
        );

        // Bare-root entry already present → skip.
        let mut config = json!({
            "writePermissions": { "type": "AnyOf", "securityLevels": [authenticated.clone()] }
        });
        assert!(!merge_level_into(
            &mut config,
            "writePermissions",
            &administrator
        ));

        // NESTED same-root entry (the fresh-gateway default) does not
        // admit the token — the bare root lands BESIDE it.
        let mut config = json!({
            "writePermissions": { "type": "AnyOf", "securityLevels": [administrator.clone()] }
        });
        assert!(merge_level_into(
            &mut config,
            "writePermissions",
            &administrator
        ));
        let levels = config["writePermissions"]["securityLevels"]
            .as_array()
            .expect("levels");
        assert_eq!(levels.len(), 2, "bare root added beside the nested entry");
        assert_eq!(levels[1], bare("Authenticated"));

        // Empty list (Public) → the bare root lands, tightening it.
        let mut config = json!({
            "writePermissions": { "type": "AnyOf", "securityLevels": [] }
        });
        assert!(merge_level_into(
            &mut config,
            "writePermissions",
            &authenticated
        ));
        let levels = config["writePermissions"]["securityLevels"]
            .as_array()
            .expect("levels");
        assert_eq!(levels.len(), 1);
        assert_eq!(levels[0], bare("Authenticated"));

        // Missing field entirely → created as AnyOf.
        let mut config = json!({});
        assert!(merge_level_into(
            &mut config,
            "readPermissions",
            &authenticated
        ));
        assert_eq!(config["readPermissions"]["type"], "AnyOf");
    }

    /// The PUT body — array-of-one, whole config, the GET's
    /// signature riding verbatim (ADOPT-RESEARCH §2).
    #[test]
    fn put_body_carries_the_signature() {
        let singleton: SecuritySingletonWire = serde_json::from_value(json!({
            "signature": "dee8c94600032841",
            "collection": "core",
            "config": { "forceIdpAuth": true }
        }))
        .expect("parses");
        let mut config = singleton.config.clone();
        merge_level_into(
            &mut config,
            "writePermissions",
            &level_tree(&["Authenticated"]),
        );
        let body = build_security_put_body(&singleton, &config);
        assert_eq!(body[0]["signature"], "dee8c94600032841");
        assert_eq!(body[0]["collection"], "core");
        assert_eq!(body[0]["config"]["forceIdpAuth"], true);
        assert!(
            body[0]["config"]["writePermissions"]["securityLevels"]
                .as_array()
                .expect("levels")
                .len()
                == 1
        );
    }

    /// The commissioned write list: one nested Administrator tree.
    fn commissioned() -> Value {
        json!({
            "writePermissions": {
                "type": "AnyOf",
                "securityLevels": [level_tree(&["Authenticated", "Roles", "Administrator"])]
            }
        })
    }

    #[test]
    fn merge_write_level_adds_the_exact_tree_and_is_idempotent() {
        let mut config = commissioned();
        // Already present (a description on the stored entry is ignored).
        config["writePermissions"]["securityLevels"][0]["description"] = json!("x");
        let admin = level_tree(&["Authenticated", "Roles", "Administrator"]);
        assert!(!merge_write_level_into(&mut config, &admin));

        let dedicated = level_tree(&["Authenticated", "IgnCliWrite"]);
        assert!(merge_write_level_into(&mut config, &dedicated));
        assert_eq!(config["writePermissions"]["securityLevels"][1], dedicated);
        assert!(!merge_write_level_into(&mut config, &dedicated));

        let bare_dedicated = level_tree(&["IgnCliWrite"]);
        assert!(merge_write_level_into(&mut config, &bare_dedicated));
        assert_eq!(
            config["writePermissions"]["securityLevels"][2],
            json!({ "name": "IgnCliWrite", "children": [] })
        );

        // A missing writePermissions is created as AnyOf holding only the level.
        let mut empty = json!({});
        assert!(merge_write_level_into(&mut empty, &dedicated));
        assert_eq!(empty["writePermissions"]["type"], "AnyOf");
        assert_eq!(
            empty["writePermissions"]["securityLevels"],
            json!([dedicated])
        );

        // No call ever appended a bare Authenticated entry.
        for config in [&config, &empty] {
            let levels = config["writePermissions"]["securityLevels"]
                .as_array()
                .expect("levels");
            assert!(!levels.iter().any(|entry| {
                entry["name"] == "Authenticated"
                    && entry["children"].as_array().is_some_and(Vec::is_empty)
            }));
        }
    }

    #[test]
    fn write_admits_every_key_flags_the_three_open_forms() {
        // Absent, empty, bare Authenticated, bare Public (any case).
        assert!(write_admits_every_key(&json!({})).is_some());
        assert!(
            write_admits_every_key(&json!({
                "writePermissions": { "type": "AnyOf", "securityLevels": [] }
            }))
            .is_some()
        );
        for name in ["Authenticated", "authenticated", "Public", "PUBLIC"] {
            let config = json!({
                "writePermissions": {
                    "type": "AnyOf",
                    "securityLevels": [
                        level_tree(&["Authenticated", "Roles", "Administrator"]),
                        { "name": name, "children": [] }
                    ]
                }
            });
            assert!(write_admits_every_key(&config).is_some(), "{name}");
        }
        // Exact forms are not open.
        assert_eq!(write_admits_every_key(&commissioned()), None);
        let mut with_dedicated = commissioned();
        merge_write_level_into(&mut with_dedicated, &level_tree(&["IgnCliWrite"]));
        assert_eq!(write_admits_every_key(&with_dedicated), None);
        // A nested entry named Authenticated that has children is not open.
        let nested = json!({
            "writePermissions": {
                "type": "AnyOf",
                "securityLevels": [level_tree(&["Authenticated", "IgnCliWrite"])]
            }
        });
        assert_eq!(write_admits_every_key(&nested), None);
    }

    #[test]
    fn remove_bare_authenticated_keeps_the_rest_and_refuses_empty() {
        let admin = level_tree(&["Authenticated", "Roles", "Administrator"]);
        let bare = json!({ "name": "Authenticated", "children": [] });

        let mut config = json!({
            "readPermissions": { "type": "AnyOf", "securityLevels": [bare.clone()] },
            "writePermissions": { "type": "AnyOf", "securityLevels": [admin.clone(), bare.clone()] }
        });
        assert_eq!(remove_bare_authenticated_from_write(&mut config), Ok(true));
        assert_eq!(
            config["writePermissions"]["securityLevels"],
            json!([admin.clone()])
        );
        assert_eq!(
            config["readPermissions"]["securityLevels"],
            json!([bare.clone()]),
            "readPermissions is never touched"
        );

        // Nothing to remove.
        let mut clean = commissioned();
        let before = clean.clone();
        assert_eq!(remove_bare_authenticated_from_write(&mut clean), Ok(false));
        assert_eq!(clean, before);

        // The only entry: refused, unchanged.
        let mut only = json!({
            "writePermissions": { "type": "AnyOf", "securityLevels": [bare] }
        });
        let before = only.clone();
        let err = remove_bare_authenticated_from_write(&mut only).expect_err("would empty");
        assert!(err.contains("Public"), "{err}");
        assert_eq!(only, before);
    }

    #[test]
    fn create_body_carries_every_level() {
        let levels = [
            level_tree(&["Authenticated", "Roles", "IgnCheckRead"]),
            level_tree(&["Authenticated", "IgnCliWrite"]),
        ];
        let body = build_token_create_body("k", &levels, "hash", 1);
        let granted = body[0]["config"]["profile"]["securityLevels"]
            .as_array()
            .expect("levels");
        assert_eq!(granted.len(), 2);
        assert_eq!(granted[0], levels[0]);
        assert_eq!(granted[1], levels[1]);
    }
}