axiam-sdk 1.2.2

Official Rust client SDK for AXIAM IAM
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
//! Declarative management — CONTRACT.md §27.6.
//!
//! The 147 operations of §27 are the floor, not the ceiling. What an
//! application actually does at start-up, in a migration, or in a test fixture
//! is **assert a shape**: this tenant has these resources, with these scopes,
//! these permissions, these roles, and these bindings. Written imperatively
//! that is forty calls wrapped in exists-checks, and it is wrong the second
//! time it runs.
//!
//! ```no_run
//! # use axiam_sdk::client::AxiamClient;
//! use axiam_sdk::management::manifest::{
//!     GrantSpec, ManagementManifest, PermissionSpec, ResourceSpec, RoleSpec, ScopeSpec,
//! };
//!
//! # async fn demo(client: &AxiamClient) -> Result<(), axiam_sdk::AxiamError> {
//! let manifest = ManagementManifest::new()
//!     .with_resource(
//!         ResourceSpec::new("docs", "documents", "collection")
//!             .with_scope(ScopeSpec::new("docs.draft", "draft", "Unpublished documents")),
//!     )
//!     .with_permission(PermissionSpec::new("read", "document:read", "Read a document"))
//!     .with_role(
//!         RoleSpec::new("editor", "Editor", "Edits documents")
//!             .granting(GrantSpec::allow("read").scoped_to(["docs.draft"])),
//!     );
//!
//! // Read-only: shows what would change, touches nothing.
//! let plan = client.manifest().plan(&manifest).await?;
//! println!("{} change(s)", plan.change_count());
//!
//! let report = client.manifest().apply(&manifest).await?;
//! assert!(report.is_complete());
//! # Ok(())
//! # }
//! ```
//!
//! # The rules that matter
//!
//! **[`plan`](Manifest::plan) writes nothing.** Not "nothing important" —
//! nothing. It issues `GET`s only, which is what makes it safe to point at
//! production, and which has its own test asserting the mock transport saw no
//! other verb.
//!
//! **Reconciliation is by natural key.** A manifest is written before the
//! things in it exist, so it cannot name them by id. Each spec carries the key
//! its namespace is unique on — a user's `username`, a role's `name`, a
//! scope's `name` within its resource — and cross-references use a
//! manifest-local `key` resolved during planning.
//!
//! **A field the manifest does not state is never a difference.** That is what
//! makes [`apply`](Manifest::apply) safe against a tenant that also holds
//! hand-made state.
//!
//! **Nothing is ever deleted.** §27.6 rule 4 forbids deleting without an
//! explicit per-namespace opt-in; this SDK offers no such opt-in at all, so a
//! manifest that omits an existing role leaves it alone. A manifest is usually
//! a *subset* of a tenant's truth, and a prune would turn "make sure these
//! three roles exist" into "delete the other forty".
//!
//! **There is no transaction.** See [`ApplyReport`].
//!
//! # Contract 1.51: metadata, scoped bindings, service accounts
//!
//! §27.6.1 made three things explicit that no SDK had:
//!
//! * [`ResourceSpec::with_metadata`] — compared as the **whole** JSON object;
//!   a changed key is an `Update` that sends the whole object.
//! * [`RoleBinding`] — a role bound at a resource, optionally stopping there
//!   (`inherit: false`). A subject holds a role at most once, so binding one
//!   role twice to one subject is refused before any request. A changed
//!   binding is unassign-then-assign, restored on failure, with the server
//!   binding's `tenant_scope` carried across.
//! * [`ServiceAccountSpec`] — reconciled by name, which the server does not
//!   keep unique, so an ambiguous name fails `plan`. A `Create` returns the
//!   one-time `client_secret` on its outcome,
//!   [`Outcome::CreatedServiceAccount`], and [`ApplyReport::created_service_accounts`]
//!   lists them — **the only time the secret is ever returned**. `apply`
//!   never rotates a secret.
//!
//! `webhooks` is named by §27.6 and deliberately not implemented: no consumer
//! has asked for it, and contract 1.51 does not require it.
//!
//! # Contract 1.62: `network`
//!
//! §27.6.2 makes the network namespace — segments, their reply profiles and the
//! tenant's `Session-Timeout` cap — a manifest namespace, planned last: the
//! policy, then the segments, then the profiles. See [`NetworkSpec`] for the
//! natural keys, the version-conditional `replace_*` bodies, how a clamped
//! profile and `filter_ids` are judged, and what a `409` and its `reason_code`
//! mean to an `apply`.

mod builder;
#[macro_use]
mod macros;
mod network;
mod plan;
mod spec;

pub use builder::ManifestBuilder;
pub use network::{NetworkPolicySpec, NetworkProfileSpec, NetworkSegmentSpec, NetworkSpec};
pub use plan::{
    ApplyReport, Change, CreatedServiceAccount, ManagementPlan, Outcome, PlannedAction, Target,
};
pub use spec::{
    GrantSpec, GroupSpec, ManagementManifest, PermissionSpec, ResourceSpec, RoleBinding, RoleSpec,
    ScopeSpec, ServiceAccountSpec, UserSpec,
};

use std::collections::HashMap;

use uuid::Uuid;

use crate::AxiamError;
use crate::client::AxiamClient;
use crate::management::models;
use crate::management::page::PageRequest;
use plan::{Resolved, topological_order, validate};

/// How many items a planning read asks for per page.
///
/// Planning walks each collection to exhaustion; this is only the page size.
const PLAN_PAGE: u64 = 200;

/// The declarative-management handle, reached from [`AxiamClient::manifest`].
#[derive(Clone, Copy)]
pub struct Manifest<'c> {
    client: &'c AxiamClient,
}

impl std::fmt::Debug for Manifest<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("Manifest")
    }
}

impl AxiamClient {
    /// Declarative management (CONTRACT.md §27.6) — [`plan`](Manifest::plan)
    /// and [`apply`](Manifest::apply) a [`ManagementManifest`].
    #[must_use]
    pub fn manifest(&self) -> Manifest<'_> {
        Manifest { client: self }
    }
}

/// The current state a plan is computed against.
struct Snapshot {
    resources: Vec<models::Resource>,
    scopes: HashMap<Uuid, Vec<models::Scope>>,
    permissions: Vec<models::Permission>,
    roles: Vec<models::Role>,
    groups: Vec<models::Group>,
    users: Vec<models::UserResponse>,
    /// Read only when the manifest names a service account, so a manifest
    /// without that section costs no request it did not cost before 1.51.
    service_accounts: Vec<models::ServiceAccountResponse>,
    role_grants: HashMap<Uuid, Vec<Uuid>>,
    role_users: HashMap<Uuid, Vec<Held>>,
    role_groups: HashMap<Uuid, Vec<Held>>,
    role_service_accounts: HashMap<Uuid, Vec<Held>>,
    group_members: HashMap<Uuid, Vec<Uuid>>,
    /// Read only when the manifest has a `network` section (§27.6.2), so a
    /// manifest without one costs no request it did not cost before 1.62.
    network: network::NetworkSnapshot,
}

/// One assignment of a role, as the server holds it — everything a binding
/// `Update` needs to put back if its re-assignment fails (§27.6.1 item 2).
#[derive(Debug, Clone)]
struct Held {
    subject: Uuid,
    resource_id: Option<Uuid>,
    inherit: bool,
    /// Not a manifest field in 1.51, and so never compared — but carried
    /// across an `Update` unchanged, because dropping it would silently widen
    /// an organization-level account's reach (§5.2.3).
    tenant_scope: Option<Vec<Uuid>>,
}

/// Which kind of subject a binding binds a role to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Subject {
    Group,
    User,
    ServiceAccount,
}

impl Subject {
    fn target(self) -> Target {
        match self {
            Subject::Group => Target::GroupRole,
            Subject::User => Target::UserRole,
            Subject::ServiceAccount => Target::ServiceAccountRole,
        }
    }

    fn noun(self) -> &'static str {
        match self {
            Subject::Group => "group",
            Subject::User => "user",
            Subject::ServiceAccount => "service account",
        }
    }

    fn resolved(self, resolved: &Resolved) -> &HashMap<String, Uuid> {
        match self {
            Subject::Group => &resolved.groups,
            Subject::User => &resolved.users,
            Subject::ServiceAccount => &resolved.service_accounts,
        }
    }
}

impl<'c> Manifest<'c> {
    /// What reconciling `manifest` would do. **Issues no writes.**
    pub async fn plan(&self, manifest: &ManagementManifest) -> Result<ManagementPlan, AxiamError> {
        validate(manifest)?;
        let snapshot = self.read(manifest).await?;
        let (plan, _, _) = self.compute(manifest, &snapshot)?;
        Ok(plan)
    }

    /// Reconcile `manifest`, stopping at the first failure.
    ///
    /// Re-running after fixing the cause is the recovery path, and is safe:
    /// applying twice converges (§27.6 rule 6).
    pub async fn apply(&self, manifest: &ManagementManifest) -> Result<ApplyReport, AxiamError> {
        validate(manifest)?;
        let snapshot = self.read(manifest).await?;
        let (plan, mut resolved, steps) = self.compute(manifest, &snapshot)?;
        self.execute(plan, steps, &mut resolved).await
    }

    // -----------------------------------------------------------------
    // Read
    // -----------------------------------------------------------------

    async fn read(&self, manifest: &ManagementManifest) -> Result<Snapshot, AxiamError> {
        let c = self.client;
        // A fresh request per read rather than one reused value: `PageRequest`
        // carries an owned search term since §27.4 rule 4 grew one, so it is
        // `Clone` and no longer `Copy`. The plan is a snapshot of everything,
        // so none of these five is filtered.
        let start = || PageRequest::first(PLAN_PAGE);
        let resources = c.resources().list_all(start()).await?;
        let permissions = c.permissions().list_all(start()).await?;
        let roles = c.roles().list_all(start()).await?;
        let groups = c.groups().list_all(start()).await?;
        let users = c.users().list_all(start()).await?;

        let mut scopes = HashMap::new();
        // Only resources the manifest could match: a tenant with a thousand
        // resources should not cost a thousand scope reads to plan five.
        let wanted: Vec<&models::Resource> = resources
            .iter()
            .filter(|r| manifest.resources.iter().any(|s| s.name == r.name))
            .collect();
        for resource in wanted {
            scopes.insert(resource.id, c.scopes().list(resource.id).await?);
        }

        let with_accounts = !manifest.service_accounts.is_empty();
        let service_accounts = if with_accounts {
            c.service_accounts().list_all(start()).await?
        } else {
            Vec::new()
        };

        let mut role_grants = HashMap::new();
        let mut role_users = HashMap::new();
        let mut role_groups = HashMap::new();
        let mut role_service_accounts = HashMap::new();
        for role in roles
            .iter()
            .filter(|r| manifest.roles.iter().any(|s| s.name == r.name))
        {
            role_grants.insert(
                role.id,
                c.roles()
                    .list_permissions(role.id)
                    .await?
                    .into_iter()
                    .map(|g| g.permission.id)
                    .collect::<Vec<_>>(),
            );
            role_users.insert(
                role.id,
                c.roles()
                    .list_users(role.id)
                    .await?
                    .into_iter()
                    .map(|a| Held {
                        subject: a.user.id,
                        resource_id: a.resource_id,
                        inherit: a.inherit,
                        tenant_scope: a.tenant_scope,
                    })
                    .collect::<Vec<_>>(),
            );
            role_groups.insert(
                role.id,
                c.roles()
                    .list_groups(role.id)
                    .await?
                    .into_iter()
                    .map(|a| Held {
                        subject: a.group.id,
                        resource_id: a.resource_id,
                        inherit: a.inherit,
                        tenant_scope: a.tenant_scope,
                    })
                    .collect::<Vec<_>>(),
            );
            if with_accounts {
                role_service_accounts.insert(
                    role.id,
                    c.roles()
                        .list_service_accounts(role.id)
                        .await?
                        .into_iter()
                        .map(|a| Held {
                            subject: a.service_account.id,
                            resource_id: a.resource_id,
                            inherit: a.inherit,
                            tenant_scope: a.tenant_scope,
                        })
                        .collect::<Vec<_>>(),
                );
            }
        }

        let mut group_members = HashMap::new();
        for group in groups
            .iter()
            .filter(|g| manifest.groups.iter().any(|s| s.name == g.name))
        {
            group_members.insert(
                group.id,
                c.groups()
                    .list_members_all(group.id, start())
                    .await?
                    .into_iter()
                    .map(|u| u.id)
                    .collect::<Vec<_>>(),
            );
        }

        let network = if manifest.network.is_empty() {
            network::NetworkSnapshot::default()
        } else {
            self.read_network(&manifest.network).await?
        };

        Ok(Snapshot {
            resources,
            scopes,
            permissions,
            roles,
            groups,
            users,
            service_accounts,
            role_grants,
            role_users,
            role_groups,
            role_service_accounts,
            group_members,
            network,
        })
    }
}

/// One executable step, carrying manifest keys rather than ids.
///
/// Keys, not ids, because a child resource's parent may not exist until the
/// step before it runs — the plan is computed once, up front, and resolution
/// has to happen as execution goes.
#[derive(Debug, Clone)]
enum Step {
    Noop,
    CreateResource {
        key: String,
        name: String,
        resource_type: String,
        parent: Option<String>,
        metadata: Option<serde_json::Value>,
    },
    UpdateResource {
        key: String,
        /// Only when it drifted — the body is sparse.
        resource_type: Option<String>,
        /// Only when stated and drifted, and then the **whole** object.
        metadata: Option<serde_json::Value>,
    },
    CreateScope {
        resource: String,
        key: String,
        name: String,
        description: String,
    },
    CreatePermission {
        key: String,
        action: String,
        description: String,
    },
    UpdatePermission {
        key: String,
        description: String,
    },
    CreateRole {
        key: String,
        name: String,
        description: String,
        is_global: bool,
    },
    UpdateRole {
        key: String,
        description: String,
        is_global: bool,
    },
    GrantPermission {
        role: String,
        permission: String,
        effect: Option<crate::management::models::PermissionEffect>,
        scopes: Vec<String>,
    },
    CreateGroup {
        key: String,
        name: String,
        description: String,
    },
    UpdateGroup {
        key: String,
        description: String,
    },
    /// A binding that does not exist yet (§27.6.1 item 2).
    AssignRole {
        subject_kind: Subject,
        subject: String,
        role: String,
        resource: Option<String>,
        inherit: bool,
    },
    /// A binding whose resource or `inherit` differs: unassign, then assign,
    /// and on a failed assign put `previous` back.
    RebindRole {
        subject_kind: Subject,
        subject: String,
        role: String,
        resource: Option<String>,
        inherit: bool,
        previous: Held,
    },
    CreateServiceAccount {
        key: String,
        name: String,
        description: Option<String>,
    },
    UpdateServiceAccount {
        key: String,
        description: String,
    },
    CreateUser {
        key: String,
        username: String,
        email: String,
        password: crate::Sensitive<String>,
    },
    UpdateUser {
        key: String,
        email: String,
    },
    AddGroupMember {
        group: String,
        user: String,
    },
    /// A `network` action (contract 1.62, §27.6.2).
    Network(network::NetStep),
}

impl<'c> Manifest<'c> {
    // -----------------------------------------------------------------
    // Plan
    // -----------------------------------------------------------------

    #[allow(clippy::too_many_lines)]
    fn compute(
        &self,
        manifest: &ManagementManifest,
        snapshot: &Snapshot,
    ) -> Result<(ManagementPlan, Resolved, Vec<Step>), AxiamError> {
        let mut resolved = Resolved::default();
        let mut steps: Vec<(PlannedAction, Step)> = Vec::new();

        let specs: HashMap<&str, &ResourceSpec> = manifest
            .resources
            .iter()
            .map(|r| (r.key.as_str(), r))
            .collect();

        // Resources, parents first — `topological_order` already rejected a
        // cycle during validation, so this cannot loop.
        let order = topological_order(manifest).map_err(AxiamError::network)?;
        for key in &order {
            let spec = specs[key.as_str()];
            let parent_id = spec
                .parent
                .as_ref()
                .map(|p| resolved.resources.get(p).copied());
            // A child whose parent is itself pending cannot already exist, so
            // matching it against a root of the same name would be wrong.
            let parent_pending = matches!(parent_id, Some(None));
            let parent_id = parent_id.flatten();
            let existing = if parent_pending {
                None
            } else {
                snapshot
                    .resources
                    .iter()
                    .find(|r| r.name == spec.name && r.parent_id == parent_id)
            };
            match existing {
                Some(found) => {
                    resolved.resources.insert(spec.key.clone(), found.id);
                    let type_drifted = found.resource_type != spec.resource_type;
                    // §27.6.1 item 1: whole-object JSON equality, and only when
                    // the manifest states it. The server returns `{}` for none,
                    // so a stated `{}` matches that.
                    let metadata_drifted = spec
                        .metadata
                        .as_ref()
                        .is_some_and(|stated| *stated != found.metadata);
                    let drifted = type_drifted || metadata_drifted;
                    steps.push((
                        action(
                            if drifted {
                                Change::Update
                            } else {
                                Change::NoChange
                            },
                            Target::Resource,
                            &spec.key,
                            format!("resource {:?} ({})", spec.name, spec.resource_type),
                        ),
                        if drifted {
                            Step::UpdateResource {
                                key: spec.key.clone(),
                                resource_type: type_drifted.then(|| spec.resource_type.clone()),
                                metadata: if metadata_drifted {
                                    spec.metadata.clone()
                                } else {
                                    None
                                },
                            }
                        } else {
                            Step::Noop
                        },
                    ));
                }
                None => steps.push((
                    action(
                        Change::Create,
                        Target::Resource,
                        &spec.key,
                        format!("resource {:?} ({})", spec.name, spec.resource_type),
                    ),
                    Step::CreateResource {
                        key: spec.key.clone(),
                        name: spec.name.clone(),
                        resource_type: spec.resource_type.clone(),
                        parent: spec.parent.clone(),
                        metadata: spec.metadata.clone(),
                    },
                )),
            }
        }

        // Scopes, under whichever resource declares them.
        for key in &order {
            let spec = specs[key.as_str()];
            let resource_id = resolved.resources.get(&spec.key).copied();
            let empty = Vec::new();
            let existing_scopes = resource_id
                .and_then(|id| snapshot.scopes.get(&id))
                .unwrap_or(&empty);
            for scope in &spec.scopes {
                match existing_scopes.iter().find(|s| s.name == scope.name) {
                    Some(found) => {
                        resolved.scopes.insert(scope.key.clone(), found.id);
                        steps.push((
                            action(
                                Change::NoChange,
                                Target::Scope,
                                &scope.key,
                                format!("scope {:?} on {:?}", scope.name, spec.name),
                            ),
                            Step::Noop,
                        ));
                    }
                    None => steps.push((
                        action(
                            Change::Create,
                            Target::Scope,
                            &scope.key,
                            format!("scope {:?} on {:?}", scope.name, spec.name),
                        ),
                        Step::CreateScope {
                            resource: spec.key.clone(),
                            key: scope.key.clone(),
                            name: scope.name.clone(),
                            description: scope.description.clone(),
                        },
                    )),
                }
            }
        }

        for spec in &manifest.permissions {
            match snapshot
                .permissions
                .iter()
                .find(|p| p.action == spec.action)
            {
                Some(found) => {
                    resolved.permissions.insert(spec.key.clone(), found.id);
                    let drifted = found.description != spec.description;
                    steps.push((
                        action(
                            if drifted {
                                Change::Update
                            } else {
                                Change::NoChange
                            },
                            Target::Permission,
                            &spec.key,
                            format!("permission {:?}", spec.action),
                        ),
                        if drifted {
                            Step::UpdatePermission {
                                key: spec.key.clone(),
                                description: spec.description.clone(),
                            }
                        } else {
                            Step::Noop
                        },
                    ));
                }
                None => steps.push((
                    action(
                        Change::Create,
                        Target::Permission,
                        &spec.key,
                        format!("permission {:?}", spec.action),
                    ),
                    Step::CreatePermission {
                        key: spec.key.clone(),
                        action: spec.action.clone(),
                        description: spec.description.clone(),
                    },
                )),
            }
        }

        for spec in &manifest.roles {
            match snapshot.roles.iter().find(|r| r.name == spec.name) {
                Some(found) => {
                    resolved.roles.insert(spec.key.clone(), found.id);
                    let drifted =
                        found.description != spec.description || found.is_global != spec.is_global;
                    steps.push((
                        action(
                            if drifted {
                                Change::Update
                            } else {
                                Change::NoChange
                            },
                            Target::Role,
                            &spec.key,
                            format!("role {:?}", spec.name),
                        ),
                        if drifted {
                            Step::UpdateRole {
                                key: spec.key.clone(),
                                description: spec.description.clone(),
                                is_global: spec.is_global,
                            }
                        } else {
                            Step::Noop
                        },
                    ));
                }
                None => steps.push((
                    action(
                        Change::Create,
                        Target::Role,
                        &spec.key,
                        format!("role {:?}", spec.name),
                    ),
                    Step::CreateRole {
                        key: spec.key.clone(),
                        name: spec.name.clone(),
                        description: spec.description.clone(),
                        is_global: spec.is_global,
                    },
                )),
            }
        }

        // Role grants. Present-or-absent only: a grant this manifest does not
        // mention is left alone (§27.6 rule 3), which is also why there is no
        // "revoke" step.
        for spec in &manifest.roles {
            let held = resolved
                .roles
                .get(&spec.key)
                .and_then(|id| snapshot.role_grants.get(id));
            for grant in &spec.grants {
                let permission_id = resolved.permissions.get(&grant.permission).copied();
                let present =
                    matches!((held, permission_id), (Some(list), Some(pid)) if list.contains(&pid));
                steps.push((
                    action(
                        if present {
                            Change::NoChange
                        } else {
                            Change::Create
                        },
                        Target::RoleGrant,
                        &spec.key,
                        format!("role {:?} grants {:?}", spec.name, grant.permission),
                    ),
                    if present {
                        Step::Noop
                    } else {
                        Step::GrantPermission {
                            role: spec.key.clone(),
                            permission: grant.permission.clone(),
                            effect: grant.effect.clone(),
                            scopes: grant.scopes.clone(),
                        }
                    },
                ));
            }
        }

        for spec in &manifest.groups {
            match snapshot.groups.iter().find(|g| g.name == spec.name) {
                Some(found) => {
                    resolved.groups.insert(spec.key.clone(), found.id);
                    let drifted = found.description != spec.description;
                    steps.push((
                        action(
                            if drifted {
                                Change::Update
                            } else {
                                Change::NoChange
                            },
                            Target::Group,
                            &spec.key,
                            format!("group {:?}", spec.name),
                        ),
                        if drifted {
                            Step::UpdateGroup {
                                key: spec.key.clone(),
                                description: spec.description.clone(),
                            }
                        } else {
                            Step::Noop
                        },
                    ));
                }
                None => steps.push((
                    action(
                        Change::Create,
                        Target::Group,
                        &spec.key,
                        format!("group {:?}", spec.name),
                    ),
                    Step::CreateGroup {
                        key: spec.key.clone(),
                        name: spec.name.clone(),
                        description: spec.description.clone(),
                    },
                )),
            }
        }

        for spec in &manifest.groups {
            for binding in &spec.roles {
                steps.push(plan_binding(
                    Subject::Group,
                    &spec.key,
                    &spec.name,
                    binding,
                    &snapshot.role_groups,
                    &resolved,
                ));
            }
        }

        for spec in &manifest.users {
            match snapshot.users.iter().find(|u| u.username == spec.username) {
                Some(found) => {
                    resolved.users.insert(spec.key.clone(), found.id);
                    let drifted = found.email != spec.email;
                    steps.push((
                        action(
                            if drifted {
                                Change::Update
                            } else {
                                Change::NoChange
                            },
                            Target::User,
                            &spec.key,
                            format!("user {:?}", spec.username),
                        ),
                        if drifted {
                            Step::UpdateUser {
                                key: spec.key.clone(),
                                email: spec.email.clone(),
                            }
                        } else {
                            Step::Noop
                        },
                    ));
                }
                None => {
                    // §27.6 rule 1: catch this here, before anything has been
                    // written, rather than halfway through an apply.
                    let password = spec.initial_password.clone().ok_or_else(|| {
                        AxiamError::network(format!(
                            "user {:?} does not exist and would be created, but the spec carries \
                             no initial_password",
                            spec.username
                        ))
                    })?;
                    steps.push((
                        action(
                            Change::Create,
                            Target::User,
                            &spec.key,
                            format!("user {:?}", spec.username),
                        ),
                        Step::CreateUser {
                            key: spec.key.clone(),
                            username: spec.username.clone(),
                            email: spec.email.clone(),
                            password,
                        },
                    ));
                }
            }
        }

        for spec in &manifest.users {
            let user_id = resolved.users.get(&spec.key).copied();
            for binding in &spec.roles {
                steps.push(plan_binding(
                    Subject::User,
                    &spec.key,
                    &spec.username,
                    binding,
                    &snapshot.role_users,
                    &resolved,
                ));
            }
            for group_key in &spec.groups {
                let group_id = resolved.groups.get(group_key).copied();
                let present = matches!(
                    (group_id, user_id),
                    (Some(gid), Some(uid))
                        if snapshot.group_members.get(&gid).is_some_and(|l| l.contains(&uid))
                );
                steps.push((
                    action(
                        if present {
                            Change::NoChange
                        } else {
                            Change::Create
                        },
                        Target::GroupMember,
                        &spec.key,
                        format!("user {:?} is in group {group_key:?}", spec.username),
                    ),
                    if present {
                        Step::Noop
                    } else {
                        Step::AddGroupMember {
                            group: group_key.clone(),
                            user: spec.key.clone(),
                        }
                    },
                ));
            }
        }

        // Service accounts, then their bindings (§27.6 rule 5, as 1.51 names it).
        for spec in &manifest.service_accounts {
            let mut matching = snapshot
                .service_accounts
                .iter()
                .filter(|a| a.name == spec.name);
            let found = matching.next();
            // §27.6.1 item 3: the name is the natural key and the server does
            // not enforce it. Two matches means `plan` cannot know which one the
            // manifest describes, and reconciling either would be a guess.
            if found.is_some() && matching.next().is_some() {
                return Err(AxiamError::network(format!(
                    "service account {:?} is ambiguous: more than one existing account is named \
                     {:?}, and a service account's name is not unique on the server — rename one, \
                     or remove it from the manifest",
                    spec.key, spec.name
                )));
            }
            let summary = format!("service account {:?}", spec.name);
            match found {
                Some(found) => {
                    resolved.service_accounts.insert(spec.key.clone(), found.id);
                    let drifted = spec
                        .description
                        .as_ref()
                        .is_some_and(|d| found.description.as_ref() != Some(d));
                    steps.push((
                        action(
                            if drifted {
                                Change::Update
                            } else {
                                Change::NoChange
                            },
                            Target::ServiceAccount,
                            &spec.key,
                            summary,
                        ),
                        match (&spec.description, drifted) {
                            (Some(description), true) => Step::UpdateServiceAccount {
                                key: spec.key.clone(),
                                description: description.clone(),
                            },
                            _ => Step::Noop,
                        },
                    ));
                }
                None => steps.push((
                    action(Change::Create, Target::ServiceAccount, &spec.key, summary),
                    Step::CreateServiceAccount {
                        key: spec.key.clone(),
                        name: spec.name.clone(),
                        description: spec.description.clone(),
                    },
                )),
            }
        }
        for spec in &manifest.service_accounts {
            for binding in &spec.roles {
                steps.push(plan_binding(
                    Subject::ServiceAccount,
                    &spec.key,
                    &spec.name,
                    binding,
                    &snapshot.role_service_accounts,
                    &resolved,
                ));
            }
        }

        // §27.6.2 item 2: the `network` namespace, appended last — policy,
        // segments, profiles — so that a manifest without a `network` section
        // plans exactly as it did before 1.62.
        network::plan(
            &manifest.network,
            &snapshot.network,
            &mut resolved,
            &mut steps,
        )?;

        let (actions, pending): (Vec<_>, Vec<_>) = steps.into_iter().unzip();
        Ok((ManagementPlan { actions }, resolved, pending))
    }
}

/// Plan one role binding (§27.6.1 item 2).
///
/// The natural key is `(subject, role)`: the server holds at most one
/// assignment of a role to a subject. `NoChange` when that assignment names the
/// same resource (none for a plain role) and the same `inherit`; `Update` when
/// either differs; `Create` when there is none — or when the subject or the
/// role does not exist yet, so there cannot be one.
fn plan_binding(
    kind: Subject,
    subject_key: &str,
    subject_label: &str,
    binding: &RoleBinding,
    held: &HashMap<Uuid, Vec<Held>>,
    resolved: &Resolved,
) -> (PlannedAction, Step) {
    let role_key = binding.role();
    let subject_id = kind.resolved(resolved).get(subject_key).copied();
    let role_id = resolved.roles.get(role_key).copied();
    let existing = match (role_id, subject_id) {
        (Some(role), Some(subject)) => held
            .get(&role)
            .and_then(|list| list.iter().find(|h| h.subject == subject)),
        _ => None,
    };
    // `None` means the resource is still to be created, and so cannot be the
    // one an existing assignment names.
    let wanted_resource: Option<Option<Uuid>> = match binding.resource() {
        None => Some(None),
        Some(key) => resolved.resources.get(key).map(|id| Some(*id)),
    };

    let mut summary = format!("{} {subject_label:?} holds role {role_key:?}", kind.noun());
    if let Some(resource) = binding.resource() {
        summary.push_str(&format!(" at {resource:?}"));
        if !binding.inherit() {
            summary.push_str(" (here only)");
        }
    }

    let change = match existing {
        None => Change::Create,
        Some(h) if wanted_resource == Some(h.resource_id) && h.inherit == binding.inherit() => {
            Change::NoChange
        }
        Some(_) => Change::Update,
    };
    let step = match (change, existing) {
        (Change::NoChange, _) => Step::Noop,
        (Change::Update, Some(previous)) => Step::RebindRole {
            subject_kind: kind,
            subject: subject_key.to_string(),
            role: role_key.to_string(),
            resource: binding.resource().map(str::to_string),
            inherit: binding.inherit(),
            previous: previous.clone(),
        },
        _ => Step::AssignRole {
            subject_kind: kind,
            subject: subject_key.to_string(),
            role: role_key.to_string(),
            resource: binding.resource().map(str::to_string),
            inherit: binding.inherit(),
        },
    };
    (action(change, kind.target(), subject_key, summary), step)
}

fn action(change: Change, target: Target, key: &str, summary: String) -> PlannedAction {
    PlannedAction {
        change,
        target,
        key: key.to_string(),
        summary,
    }
}

impl<'c> Manifest<'c> {
    // -----------------------------------------------------------------
    // Apply
    // -----------------------------------------------------------------

    /// Run the plan, stopping at the first failure.
    ///
    /// §27.6 rule 7: there is no transaction across 147 independent HTTP
    /// endpoints, so this reports what each step did, stops rather than
    /// continuing blindly past a failure, and offers no rollback.
    async fn execute(
        &self,
        plan: ManagementPlan,
        steps: Vec<Step>,
        resolved: &mut Resolved,
    ) -> Result<ApplyReport, AxiamError> {
        let mut out: Vec<(PlannedAction, Outcome)> = Vec::with_capacity(plan.actions.len());
        let mut stopped = false;
        for (action, step) in plan.actions.into_iter().zip(steps) {
            if stopped {
                out.push((action, Outcome::NotAttempted));
                continue;
            }
            if matches!(step, Step::Noop) {
                out.push((action, Outcome::Unchanged));
                continue;
            }
            let created = matches!(action.change, Change::Create);
            match self.run(step, resolved).await {
                Ok(Done::Plain) => out.push((
                    action,
                    if created {
                        Outcome::Created
                    } else {
                        Outcome::Updated
                    },
                )),
                // §27.5 rule 5: the body, secret and all, on this action's
                // outcome — never summarised as a bare "created".
                Ok(Done::ServiceAccount(response)) => out.push((
                    action,
                    Outcome::CreatedServiceAccount(CreatedServiceAccount(response)),
                )),
                // §27.6.2 item 5: a `409` on a network write is that action's
                // failure, and its `reason_code` is data on the outcome — the
                // caller branches on it, never on the message.
                Err(StepError::Plain(e)) if action.target.is_network() && e.is_conflict() => {
                    stopped = true;
                    out.push((
                        action,
                        Outcome::Conflict {
                            message: e.to_string(),
                            reason_code: e.reason_code().map(str::to_string),
                        },
                    ));
                }
                Err(StepError::Plain(e)) => {
                    stopped = true;
                    out.push((action, Outcome::Failed(e.to_string())));
                }
                Err(StepError::Rebind(failure)) => {
                    let RebindFailure { error, restore } = *failure;
                    stopped = true;
                    out.push((
                        action,
                        Outcome::BindingUpdateFailed {
                            error: error.to_string(),
                            restore: restore.map_err(|e| e.to_string()),
                        },
                    ));
                }
            }
        }
        Ok(ApplyReport { steps: out })
    }

    #[allow(clippy::too_many_lines)]
    async fn run(&self, step: Step, resolved: &mut Resolved) -> Result<Done, StepError> {
        let c = self.client;
        match step {
            Step::Noop => {}
            Step::CreateResource {
                key,
                name,
                resource_type,
                parent,
                metadata,
            } => {
                let parent_id = match parent {
                    Some(p) => Some(lookup(&resolved.resources, &p, "resource")?),
                    None => None,
                };
                let created = c
                    .resources()
                    .create(&models::CreateResourceRequest {
                        name,
                        resource_type,
                        parent_id,
                        metadata,
                    })
                    .await?;
                resolved.resources.insert(key, created.id);
            }
            Step::UpdateResource {
                key,
                resource_type,
                metadata,
            } => {
                let id = lookup(&resolved.resources, &key, "resource")?;
                c.resources()
                    .update(
                        id,
                        &models::UpdateResourceRequest {
                            resource_type,
                            metadata,
                            ..Default::default()
                        },
                    )
                    .await?;
            }
            Step::CreateScope {
                resource,
                key,
                name,
                description,
            } => {
                let resource_id = lookup(&resolved.resources, &resource, "resource")?;
                let created = c
                    .scopes()
                    .create(
                        resource_id,
                        &models::CreateScopeRequest { name, description },
                    )
                    .await?;
                resolved.scopes.insert(key, created.id);
            }
            Step::CreatePermission {
                key,
                action,
                description,
            } => {
                let created = c
                    .permissions()
                    .create(&models::CreatePermissionRequest {
                        action,
                        description,
                    })
                    .await?;
                resolved.permissions.insert(key, created.id);
            }
            Step::UpdatePermission { key, description } => {
                let id = lookup(&resolved.permissions, &key, "permission")?;
                c.permissions()
                    .update(
                        id,
                        &models::UpdatePermissionRequest {
                            description: Some(description),
                            ..Default::default()
                        },
                    )
                    .await?;
            }
            Step::CreateRole {
                key,
                name,
                description,
                is_global,
            } => {
                let created = c
                    .roles()
                    .create(&models::CreateRoleRequest {
                        name,
                        description,
                        is_global,
                    })
                    .await?;
                resolved.roles.insert(key, created.id);
            }
            Step::UpdateRole {
                key,
                description,
                is_global,
            } => {
                let id = lookup(&resolved.roles, &key, "role")?;
                c.roles()
                    .update(
                        id,
                        &models::UpdateRole {
                            description: Some(description),
                            is_global: Some(is_global),
                            ..Default::default()
                        },
                    )
                    .await?;
            }
            Step::GrantPermission {
                role,
                permission,
                effect,
                scopes,
            } => {
                let role_id = lookup(&resolved.roles, &role, "role")?;
                let permission_id = lookup(&resolved.permissions, &permission, "permission")?;
                let scope_ids = scopes
                    .iter()
                    .map(|s| lookup(&resolved.scopes, s, "scope"))
                    .collect::<Result<Vec<_>, _>>()?;
                c.roles()
                    .grant_permission(
                        role_id,
                        &models::GrantPermissionRequest {
                            permission_id,
                            effect,
                            scope_ids: if scope_ids.is_empty() {
                                None
                            } else {
                                Some(scope_ids)
                            },
                        },
                    )
                    .await?;
            }
            Step::CreateGroup {
                key,
                name,
                description,
            } => {
                let created = c
                    .groups()
                    .create(&models::CreateGroupRequest {
                        name,
                        description,
                        metadata: None,
                    })
                    .await?;
                resolved.groups.insert(key, created.id);
            }
            Step::UpdateGroup { key, description } => {
                let id = lookup(&resolved.groups, &key, "group")?;
                c.groups()
                    .update(
                        id,
                        &models::UpdateGroup {
                            description: Some(description),
                            ..Default::default()
                        },
                    )
                    .await?;
            }
            Step::CreateUser {
                key,
                username,
                email,
                password,
            } => {
                let created = c
                    .users()
                    .create(&models::CreateUserRequest {
                        username,
                        email,
                        password,
                        metadata: None,
                        opaque: None,
                    })
                    .await?;
                resolved.users.insert(key, created.id);
            }
            Step::UpdateUser { key, email } => {
                let id = lookup(&resolved.users, &key, "user")?;
                c.users()
                    .update(
                        id,
                        &models::UpdateUserRequest {
                            email: Some(email),
                            ..Default::default()
                        },
                    )
                    .await?;
            }
            Step::AssignRole {
                subject_kind,
                subject,
                role,
                resource,
                inherit,
            } => {
                let role_id = lookup(&resolved.roles, &role, "role")?;
                let subject_id = lookup(
                    subject_kind.resolved(resolved),
                    &subject,
                    subject_kind.noun(),
                )?;
                let resource_id = resource
                    .as_deref()
                    .map(|r| lookup(&resolved.resources, r, "resource"))
                    .transpose()?;
                // A new binding: the manifest states no tenant scope, and so
                // sends none (§5.2.3 — every assignment the manifest wrote
                // before the field existed meant exactly this).
                self.assign(
                    subject_kind,
                    role_id,
                    subject_id,
                    resource_id,
                    inherit,
                    None,
                )
                .await?;
            }
            Step::RebindRole {
                subject_kind,
                subject,
                role,
                resource,
                inherit,
                previous,
            } => {
                // Every lookup before the first write: once the old assignment
                // is gone, nothing but the server may stop the new one.
                let role_id = lookup(&resolved.roles, &role, "role")?;
                let subject_id = lookup(
                    subject_kind.resolved(resolved),
                    &subject,
                    subject_kind.noun(),
                )?;
                let resource_id = resource
                    .as_deref()
                    .map(|r| lookup(&resolved.resources, r, "resource"))
                    .transpose()?;

                // There is no update endpoint: unassign, then assign. A failed
                // unassign changes nothing and is an ordinary failure.
                self.unassign(subject_kind, role_id, subject_id, previous.resource_id)
                    .await?;
                if let Err(error) = self
                    .assign(
                        subject_kind,
                        role_id,
                        subject_id,
                        resource_id,
                        inherit,
                        // Carried across unchanged: the manifest is silent on
                        // it, and dropping it would widen the subject's reach.
                        previous.tenant_scope.clone(),
                    )
                    .await
                {
                    // §27.6.1 item 2: the subject now holds no such role. Put
                    // the previous binding back, and report both results.
                    let restore = self
                        .assign(
                            subject_kind,
                            role_id,
                            subject_id,
                            previous.resource_id,
                            previous.inherit,
                            previous.tenant_scope,
                        )
                        .await;
                    return Err(StepError::Rebind(Box::new(RebindFailure {
                        error,
                        restore,
                    })));
                }
            }
            Step::CreateServiceAccount {
                key,
                name,
                description,
            } => {
                let created = c
                    .service_accounts()
                    .create(&models::CreateServiceAccountRequest { name, description })
                    .await?;
                resolved.service_accounts.insert(key, created.id);
                return Ok(Done::ServiceAccount(Box::new(created)));
            }
            Step::UpdateServiceAccount { key, description } => {
                let id = lookup(&resolved.service_accounts, &key, "service account")?;
                c.service_accounts()
                    .update(
                        id,
                        &models::UpdateServiceAccount {
                            description: Some(description),
                            ..Default::default()
                        },
                    )
                    .await?;
            }
            Step::AddGroupMember { group, user } => {
                let group_id = lookup(&resolved.groups, &group, "group")?;
                let user_id = lookup(&resolved.users, &user, "user")?;
                c.groups()
                    .add_member(group_id, &models::AddMemberRequest { user_id })
                    .await?;
            }
            Step::Network(step) => return self.run_network(step, resolved).await,
        }
        Ok(Done::Plain)
    }

    /// `roles.assign_to_*`, for whichever kind of subject.
    ///
    /// `inherit` reaches the wire only as `false` (§27.13 S-10 rule 1), so an
    /// inheritable assignment's body stays byte-for-byte a pre-1.51 body.
    async fn assign(
        &self,
        kind: Subject,
        role_id: Uuid,
        subject_id: Uuid,
        resource_id: Option<Uuid>,
        inherit: bool,
        tenant_scope: Option<Vec<Uuid>>,
    ) -> Result<(), AxiamError> {
        let roles = self.client.roles();
        let inherit = if inherit { None } else { Some(false) };
        match kind {
            Subject::Group => {
                roles
                    .assign_to_group(
                        role_id,
                        &models::AssignRoleToGroupRequest {
                            group_id: subject_id,
                            inherit,
                            resource_id,
                            tenant_scope,
                        },
                    )
                    .await
            }
            Subject::User => {
                roles
                    .assign_to_user(
                        role_id,
                        &models::AssignRoleToUserRequest {
                            user_id: subject_id,
                            inherit,
                            resource_id,
                            tenant_scope,
                        },
                    )
                    .await
            }
            Subject::ServiceAccount => {
                roles
                    .assign_to_service_account(
                        role_id,
                        &models::AssignRoleToServiceAccountRequest {
                            service_account_id: subject_id,
                            inherit,
                            resource_id,
                            tenant_scope,
                        },
                    )
                    .await
            }
        }
    }

    /// `roles.unassign_from_*`. The resource names *which* assignment: none
    /// removes the tenant-wide one specifically.
    async fn unassign(
        &self,
        kind: Subject,
        role_id: Uuid,
        subject_id: Uuid,
        resource_id: Option<Uuid>,
    ) -> Result<(), AxiamError> {
        let roles = self.client.roles();
        let resource = resource_id.map(|r| r.to_string());
        let resource = resource.as_deref();
        match kind {
            Subject::Group => {
                roles
                    .unassign_from_group(role_id, subject_id, resource)
                    .await
            }
            Subject::User => {
                roles
                    .unassign_from_user(role_id, subject_id, resource)
                    .await
            }
            Subject::ServiceAccount => {
                roles
                    .unassign_from_service_account(role_id, subject_id, resource)
                    .await
            }
        }
    }
}

/// What a step produced, when it produced more than "done".
enum Done {
    Plain,
    /// §27.5 rule 5: the one-time secret travels on the outcome.
    ServiceAccount(Box<models::ServiceAccountCreatedResponse>),
}

/// How a step failed.
enum StepError {
    Plain(AxiamError),
    /// A binding `Update` whose re-assignment failed, and what restoring the
    /// previous binding did. Boxed: two errors side by side would make every
    /// step's `Result` carry them inline (clippy `result_large_err`).
    Rebind(Box<RebindFailure>),
}

/// The two results a failed binding `Update` reports (§27.6.1 item 2).
struct RebindFailure {
    error: AxiamError,
    restore: Result<(), AxiamError>,
}

impl From<AxiamError> for StepError {
    fn from(error: AxiamError) -> Self {
        StepError::Plain(error)
    }
}

/// Resolve a manifest key to the id an earlier step recorded.
///
/// A miss here is an SDK bug, not a user error — validation already rejected
/// dangling references, and the plan orders producers before consumers — so it
/// says so rather than blaming the manifest.
fn lookup(map: &HashMap<String, Uuid>, key: &str, kind: &str) -> Result<Uuid, AxiamError> {
    map.get(key).copied().ok_or_else(|| {
        AxiamError::network(format!(
            "internal: {kind} key {key:?} was consumed before the step that creates it ran"
        ))
    })
}