silicon-iam-cli 1.0.0

Command-line client for Silicon IAM, built on the silicon-iam-client crate.
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
//! The command grammar.
//!
//! Nouns then verbs -- `iam tag create`, `iam member remove` -- because that
//! is what a person guesses, and because it keeps related commands together in
//! `--help`. Global flags come before the command and are accepted anywhere.

use std::path::PathBuf;

use clap::{Args, Parser, Subcommand, ValueEnum};
use uuid::Uuid;

use crate::output::Format;

/// The Silicon IAM command-line client.
#[derive(Debug, Parser)]
#[command(
    name = "iam",
    version,
    about = "Silicon IAM from the command line",
    long_about = "Silicon IAM from the command line.\n\n\
        Sign in once with `iam login`; the session is stored under \
        ~/.silicon-iam/ and renewed automatically. Most commands act on an \
        organization: pass --org, or set a default with \
        `iam config set org <handle>`.",
    propagate_version = true,
    disable_help_subcommand = false
)]
pub struct Cli {
    /// Global options.
    #[command(flatten)]
    pub global: Global,

    /// The command to run.
    #[command(subcommand)]
    pub command: Command,
}

/// Options accepted by every command.
#[derive(Debug, Args)]
pub struct Global {
    /// Service base URL.
    #[arg(long, global = true, env = "SILICON_IAM_URL")]
    pub url: Option<String>,

    /// Stored profile to use.
    #[arg(long, global = true, env = "SILICON_IAM_PROFILE")]
    pub profile: Option<String>,

    /// Organization handle to act on.
    #[arg(long, global = true, env = "SILICON_IAM_ORG")]
    pub org: Option<String>,

    /// Run inside a testing environment, by its UUID.
    #[arg(
        long,
        global = true,
        env = "SILICON_IAM_TEST",
        value_name = "ENVIRONMENT_ID",
        value_parser = parse_testing_environment_id
    )]
    pub test: Option<Uuid>,

    /// Step-up assertion for commands that require one.
    #[arg(long, global = true)]
    pub step_up: Option<String>,

    /// Output format.
    #[arg(long, short = 'o', global = true, value_enum, default_value_t = Format::Text)]
    pub output: Format,
}

/// Everything the CLI can do.
#[derive(Debug, Subcommand)]
pub enum Command {
    /// Sign in as a Carbon.
    Login(LoginArgs),
    /// Sign in as a Silicon with its credential.
    SiliconLogin(SiliconLoginArgs),
    /// Sign out, forgetting the stored session.
    Logout,
    /// Show who is signed in.
    Whoami,
    /// Create a Carbon account.
    Signup(SignupArgs),
    /// Print every command this CLI accepts.
    Commands,

    /// Organizations.
    #[command(subcommand)]
    Org(OrgCommand),
    /// Members of an organization.
    #[command(subcommand)]
    Member(MemberCommand),
    /// Invitations, from both ends.
    #[command(subcommand)]
    Invite(InviteCommand),
    /// Organization tags.
    #[command(subcommand)]
    Tag(TagCommand),
    /// Advisory trust.
    #[command(subcommand)]
    Trust(TrustCommand),
    /// Approvals, direct changes, and history.
    #[command(subcommand)]
    Approval(ApprovalCommand),
    /// Silicons.
    #[command(subcommand)]
    Silicon(SiliconCommand),
    /// Applications.
    #[command(subcommand)]
    App(AppCommand),
    /// Testing environments.
    #[command(subcommand)]
    Env(EnvCommand),
    /// Your own sessions and login history.
    #[command(subcommand)]
    Session(SessionCommand),
    /// Stored settings.
    #[command(subcommand)]
    Config(ConfigCommand),
    /// The service itself.
    #[command(subcommand)]
    System(SystemCommand),
}

/// Arguments for signing in.
#[derive(Debug, Args)]
pub struct LoginArgs {
    /// Email address to sign in with.
    #[arg(long, group = "identity")]
    pub email: Option<String>,
    /// Phone number, in E.164 form.
    #[arg(long, group = "identity")]
    pub phone: Option<String>,
    /// Carbon ID.
    #[arg(long, group = "identity")]
    pub carbon_id: Option<String>,
    /// Verification code, if you already have it. Prompted for otherwise.
    #[arg(long)]
    pub code: Option<String>,
    /// Application to sign in to. Prints a short-lived token for it.
    #[arg(long = "app-id", value_name = "APP_ID")]
    pub app_id: Option<String>,
}

/// Arguments for signing a Silicon in.
#[derive(Debug, Args)]
pub struct SiliconLoginArgs {
    /// Silicon ID, in `handle:org` form. Prompted for when omitted.
    #[arg(long = "sid")]
    pub sid: Option<String>,
    /// Silicon token. Prompted for when omitted, so it stays out of shell history.
    #[arg(long = "stk")]
    pub stk: Option<String>,
    /// Application to sign in to. Prints a short-lived token for it.
    #[arg(long = "app-id", value_name = "APP_ID")]
    pub app_id: Option<String>,
}

/// Arguments for creating an account.
#[derive(Debug, Args)]
pub struct SignupArgs {
    /// Email address to verify.
    #[arg(long)]
    pub email: String,
    /// Phone number to verify, in E.164 form.
    #[arg(long)]
    pub phone: String,
    /// The Carbon ID to claim.
    #[arg(long)]
    pub carbon_id: String,
    /// Display name. Defaults to the Carbon ID.
    #[arg(long)]
    pub display_name: Option<String>,
    /// IANA time zone, such as `Asia/Kolkata`.
    #[arg(long)]
    pub timezone: Option<String>,
}

/// Organization commands.
#[derive(Debug, Subcommand)]
pub enum OrgCommand {
    /// List organizations you belong to.
    List(PageArgs),
    /// Create an organization.
    Create {
        /// Handle to claim.
        handle: String,
        /// Display name.
        #[arg(long)]
        name: String,
        /// Description.
        #[arg(long)]
        description: Option<String>,
    },
    /// Show one organization.
    Show {
        /// Handle. Defaults to --org.
        handle: Option<String>,
    },
    /// Rename or re-describe an organization.
    Update {
        /// Handle. Defaults to --org.
        handle: Option<String>,
        /// New display name.
        #[arg(long)]
        name: Option<String>,
        /// New description.
        #[arg(long)]
        description: Option<String>,
        /// Join method: `email` or `sso`.
        #[arg(long)]
        join_method: Option<String>,
    },
    /// Check whether a handle can be claimed.
    Available {
        /// Handle to check.
        handle: String,
    },
    /// Hand ownership to another member. Needs --step-up.
    Transfer {
        /// Membership that becomes the owner.
        membership_id: Uuid,
        /// Handle. Defaults to --org.
        #[arg(long)]
        org: Option<String>,
    },
}

/// Member commands.
#[derive(Debug, Subcommand)]
pub enum MemberCommand {
    /// List members.
    List {
        /// Only Carbons, or only Silicons.
        #[arg(long, value_name = "carbon|silicon")]
        principal_type: Option<String>,
        /// Only members carrying this tag.
        #[arg(long)]
        tag: Option<Uuid>,
        /// Only members in this state.
        #[arg(long)]
        status: Option<String>,
        /// Paging.
        #[command(flatten)]
        page: PageArgs,
    },
    /// Show one member.
    Show {
        /// Membership identifier.
        membership_id: Uuid,
    },
    /// Show a member's role and capabilities.
    Authorization {
        /// Membership identifier.
        membership_id: Uuid,
    },
    /// Update a member's directory metadata.
    Update {
        /// Membership identifier.
        membership_id: Uuid,
        /// New reporting line.
        #[arg(long)]
        reports_to: Option<Uuid>,
        /// New profile photo URL.
        #[arg(long)]
        profile_photo: Option<String>,
    },
    /// Remove a member.
    Remove {
        /// Membership identifier.
        membership_id: Uuid,
        /// Membership to inherit anyone reporting to them.
        #[arg(long)]
        reassign_reports_to: Option<Uuid>,
    },
    /// Promote a member to administrator. Needs --step-up.
    Promote {
        /// Membership identifier.
        membership_id: Uuid,
    },
    /// Demote an administrator. Needs --step-up.
    Demote {
        /// Membership identifier.
        membership_id: Uuid,
    },
    /// Replace an administrator's capabilities. Needs --step-up.
    Capabilities {
        /// Membership identifier.
        membership_id: Uuid,
        /// The complete set to grant; anything omitted is revoked.
        #[arg(long = "capability", value_name = "CAPABILITY")]
        capabilities: Vec<String>,
    },
    /// Show the organization directory.
    Directory {
        /// Field selector the service understands.
        #[arg(long)]
        fields: Option<String>,
        /// Paging.
        #[command(flatten)]
        page: PageArgs,
    },
    /// Show your own directory entry.
    Self_ {
        /// Field selector the service understands.
        #[arg(long)]
        fields: Option<String>,
    },
}

/// Invitation commands.
#[derive(Debug, Subcommand)]
pub enum InviteCommand {
    /// List invitations this organization issued.
    List {
        /// Only invitations in this state.
        #[arg(long)]
        status: Option<String>,
        /// Paging.
        #[command(flatten)]
        page: PageArgs,
    },
    /// Invite a Carbon by handle or email.
    Create {
        /// Carbon ID to invite.
        #[arg(long, group = "identity")]
        carbon_id: Option<String>,
        /// Email address to invite.
        #[arg(long, group = "identity")]
        email: Option<String>,
        /// Job role granted on acceptance.
        #[arg(long)]
        job_role: String,
        /// Trust boundary the new member starts with.
        #[arg(long, default_value = "internal")]
        boundary: String,
        /// Trust level the new member starts with.
        #[arg(long, default_value = "not_trusted")]
        level: String,
    },
    /// Show one invitation.
    Show {
        /// Invitation identifier.
        invite_id: Uuid,
    },
    /// Revoke a pending invitation.
    Revoke {
        /// Invitation identifier.
        invite_id: Uuid,
    },
    /// Send yourself the verification code for an email invitation.
    Code {
        /// The invited email address.
        email: String,
    },
    /// Accept an invitation and join.
    Accept {
        /// The invitation being accepted.
        invite_id: Uuid,
        /// Verification code from the invitation email.
        #[arg(long)]
        code: String,
    },
}

/// Tag commands.
#[derive(Debug, Subcommand)]
pub enum TagCommand {
    /// List tags.
    List(PageArgs),
    /// Create a tag.
    Create {
        /// Tag name.
        name: String,
    },
    /// Show one tag.
    Show {
        /// Tag identifier.
        tag_id: Uuid,
    },
    /// Rename a tag.
    Rename {
        /// Tag identifier.
        tag_id: Uuid,
        /// New name.
        name: String,
    },
    /// Delete a tag, and everything it conferred.
    Delete {
        /// Tag identifier.
        tag_id: Uuid,
    },
    /// List members carrying a tag.
    Members {
        /// Tag identifier.
        tag_id: Uuid,
        /// Paging.
        #[command(flatten)]
        page: PageArgs,
    },
}

/// Trust commands.
#[derive(Debug, Subcommand)]
pub enum TrustCommand {
    /// Show the organization-wide default.
    Default,
    /// Replace the organization-wide default.
    SetDefault {
        /// `internal` or `external`.
        #[arg(long)]
        boundary: String,
        /// `not_trusted`, `needs_approval`, or `trusted`.
        #[arg(long)]
        level: String,
    },
    /// List trust rules.
    List(PageArgs),
    /// Create a trust rule.
    Create {
        /// Subject tag.
        #[arg(long, group = "subject")]
        subject_tag: Option<Uuid>,
        /// Subject membership.
        #[arg(long, group = "subject")]
        subject_membership: Option<Uuid>,
        /// Target tag.
        #[arg(long, group = "target")]
        target_tag: Option<Uuid>,
        /// Target Silicon membership.
        #[arg(long, group = "target")]
        target_membership: Option<Uuid>,
        /// `internal` or `external`.
        #[arg(long)]
        boundary: String,
        /// `not_trusted`, `needs_approval`, or `trusted`.
        #[arg(long)]
        level: String,
    },
    /// Show one trust rule.
    Show {
        /// Rule identifier.
        rule_id: Uuid,
    },
    /// Change a rule's trust value.
    Update {
        /// Rule identifier.
        rule_id: Uuid,
        /// `internal` or `external`.
        #[arg(long)]
        boundary: String,
        /// `not_trusted`, `needs_approval`, or `trusted`.
        #[arg(long)]
        level: String,
    },
    /// Archive a trust rule.
    Delete {
        /// Rule identifier.
        rule_id: Uuid,
    },
    /// Explain the trust between a subject and a target Silicon.
    Evaluate {
        /// Subject membership.
        #[arg(long)]
        subject: Uuid,
        /// Target Silicon membership.
        #[arg(long)]
        target: Uuid,
    },
}

/// Governance commands.
#[derive(Debug, Subcommand)]
pub enum ApprovalCommand {
    /// List approval requests.
    List {
        /// Only requests in this state.
        #[arg(long)]
        status: Option<String>,
        /// Only requests of this kind.
        #[arg(long)]
        kind: Option<String>,
        /// Only requests you can decide now.
        #[arg(long)]
        mine: bool,
        /// Paging.
        #[command(flatten)]
        page: PageArgs,
    },
    /// Show one approval request.
    Show {
        /// Request identifier.
        request_id: Uuid,
    },
    /// Approve or reject a request.
    Decide {
        /// Request identifier.
        request_id: Uuid,
        /// `approve` or `reject`.
        #[arg(long)]
        decision: String,
        /// Reason recorded with the decision.
        #[arg(long)]
        reason: Option<String>,
    },
    /// Request a job-role change.
    RequestRole {
        /// Membership whose role should change.
        #[arg(long)]
        membership_id: Uuid,
        /// The role being asked for.
        #[arg(long)]
        job_role: String,
    },
    /// Request a tag change for a member.
    RequestTags {
        /// Membership whose tags should change.
        #[arg(long)]
        membership_id: Uuid,
        /// Tags to add.
        #[arg(long = "add", value_name = "TAG_ID")]
        add: Vec<Uuid>,
        /// Tags to remove.
        #[arg(long = "remove", value_name = "TAG_ID")]
        remove: Vec<Uuid>,
    },
    /// Set a member's job role directly.
    SetRole {
        /// Membership identifier.
        membership_id: Uuid,
        /// The role to set.
        job_role: String,
    },
    /// Replace a member's tags directly.
    SetTags {
        /// Membership identifier.
        membership_id: Uuid,
        /// The complete tag set; anything omitted is removed.
        #[arg(long = "tag", value_name = "TAG_ID")]
        tags: Vec<Uuid>,
    },
    /// Show a member's job-role history.
    RoleHistory {
        /// Membership identifier.
        membership_id: Uuid,
        /// Paging.
        #[command(flatten)]
        page: PageArgs,
    },
    /// Show a member's tag history.
    TagHistory {
        /// Membership identifier.
        membership_id: Uuid,
        /// Paging.
        #[command(flatten)]
        page: PageArgs,
    },
}

/// Silicon commands.
#[derive(Debug, Subcommand)]
pub enum SiliconCommand {
    /// List Silicons.
    List {
        /// Only Silicons carrying this tag.
        #[arg(long)]
        tag: Option<Uuid>,
        /// Paging.
        #[command(flatten)]
        page: PageArgs,
    },
    /// Create a Silicon, returning its credential once.
    Create {
        /// Handle component; the global ID becomes `handle:org`.
        handle: String,
        /// Job role this Silicon holds.
        #[arg(long)]
        job_role: String,
        /// Display name.
        #[arg(long)]
        display_name: Option<String>,
        /// Membership this Silicon reports to.
        #[arg(long)]
        reports_to: Option<Uuid>,
        /// Tags to assign at creation.
        #[arg(long = "tag", value_name = "TAG_ID")]
        tags: Vec<Uuid>,
    },
    /// Show one Silicon.
    Show {
        /// Global Silicon ID.
        silicon_id: String,
    },
    /// Update a Silicon's directory configuration.
    Update {
        /// Global Silicon ID.
        silicon_id: String,
        /// New display name.
        #[arg(long)]
        display_name: Option<String>,
        /// New reporting line.
        #[arg(long)]
        reports_to: Option<Uuid>,
    },
    /// Remove a Silicon.
    Remove {
        /// Global Silicon ID.
        silicon_id: String,
        /// Membership to inherit anyone reporting to it.
        #[arg(long)]
        reassign_reports_to: Option<Uuid>,
    },
    /// Request credential rotation. Needs --step-up.
    RotateRequest {
        /// Global Silicon ID.
        silicon_id: String,
    },
    /// Complete an approved rotation. Needs --step-up.
    RotateComplete {
        /// Global Silicon ID.
        silicon_id: String,
        /// The approved request.
        request_id: Uuid,
    },
    /// Show the webhook endpoint.
    Webhook {
        /// Global Silicon ID.
        silicon_id: String,
    },
    /// Configure or replace the webhook endpoint.
    SetWebhook {
        /// Global Silicon ID.
        silicon_id: String,
        /// HTTPS endpoint to deliver to.
        #[arg(long)]
        url: String,
    },
    /// Remove the webhook endpoint.
    DeleteWebhook {
        /// Global Silicon ID.
        silicon_id: String,
    },
    /// Show the webhook subscription.
    Subscription {
        /// Global Silicon ID.
        silicon_id: String,
    },
    /// Replace the webhook subscription.
    SetSubscription {
        /// Global Silicon ID.
        silicon_id: String,
        /// `all` for every event, or `selected` with --topic.
        #[arg(long, default_value = "all")]
        mode: String,
        /// Topics to receive when mode is `selected`.
        #[arg(long = "topic", value_name = "TOPIC")]
        topics: Vec<String>,
        /// Additional tags whose events should also be delivered.
        #[arg(long = "tag", value_name = "TAG_ID")]
        tags: Vec<Uuid>,
    },
    /// Remove the webhook subscription.
    DeleteSubscription {
        /// Global Silicon ID.
        silicon_id: String,
    },
    /// List deliveries that exhausted their retries.
    DeadLetters {
        /// Global Silicon ID.
        silicon_id: String,
        /// Paging.
        #[command(flatten)]
        page: PageArgs,
    },
    /// Re-queue dead-lettered deliveries.
    Replay {
        /// Global Silicon ID.
        silicon_id: String,
        /// Deliveries to replay.
        #[arg(long = "delivery", value_name = "DELIVERY_ID")]
        deliveries: Vec<Uuid>,
    },
}

/// Application commands.
#[derive(Debug, Subcommand)]
pub enum AppCommand {
    /// List applications you can administer.
    List {
        /// Only applications in this state.
        #[arg(long)]
        status: Option<String>,
        /// Paging.
        #[command(flatten)]
        page: PageArgs,
    },
    /// Register an application, returning its secrets once.
    Create {
        /// Local Application handle to claim; IAM prefixes the organization.
        app_id: String,
        /// Display name.
        #[arg(long)]
        name: String,
        /// Owning organization. Defaults to --org.
        #[arg(long)]
        org: Option<String>,
        /// HTTPS endpoint the service delivers webhooks to.
        #[arg(long)]
        webhook_url: String,
        /// Public base URL other applications discover for this application.
        #[arg(long)]
        base_url: String,
        /// JSON array of OBO endpoint definitions.
        #[arg(long, value_name = "JSON")]
        obo_endpoints: Option<String>,
    },
    /// Show one application.
    Show {
        /// Canonical Application identifier (`org>handle`).
        app_id: String,
    },
    /// Update an application.
    Update {
        /// Canonical Application identifier (`org>handle`).
        app_id: String,
        /// New display name.
        #[arg(long)]
        name: Option<String>,
        /// New public base URL.
        #[arg(long)]
        base_url: Option<String>,
        /// Complete replacement OBO endpoint array as JSON.
        #[arg(long, value_name = "JSON")]
        obo_endpoints: Option<String>,
    },
    /// Rotate the client secret. Needs --step-up.
    RotateSecret {
        /// Canonical Application identifier (`org>handle`).
        app_id: String,
    },
    /// Rotate the webhook signing secret. Needs --step-up.
    RotateWebhookSecret {
        /// Canonical Application identifier (`org>handle`).
        app_id: String,
    },
    /// Discover an application's base URL as another application.
    Discover {
        /// Canonical Application whose base URL to discover.
        app_id: String,
        /// Canonical Application making the request.
        #[arg(long = "as-app-id", value_name = "APP_ID")]
        requester_app_id: String,
        /// Requester's application secret. Prompted for when omitted.
        #[arg(long)]
        app_secret: Option<String>,
    },
    /// Application token exchange, refresh, and introspection.
    #[command(subcommand)]
    Token(AppTokenCommand),
    /// Same-organization on-behalf-of access.
    #[command(subcommand)]
    Obo(AppOboCommand),
    /// Verify a captured webhook locally, before parsing or acting on it.
    VerifyWebhook {
        /// File containing the exact delivered body bytes; use `-` for stdin.
        #[arg(value_name = "BODY_FILE")]
        body_file: PathBuf,
        /// Value of `X-Silicon-IAM-Event-ID`.
        #[arg(long)]
        event_id: String,
        /// Value of `X-Silicon-IAM-Timestamp`.
        #[arg(long)]
        timestamp: String,
        /// Value of `X-Silicon-IAM-Key-Version`.
        #[arg(long)]
        key_version: String,
        /// Value of `X-Silicon-IAM-Signature`.
        #[arg(long)]
        signature: String,
        /// Signing secret for this key version. Prompted for when omitted.
        #[arg(long)]
        webhook_secret: Option<String>,
        /// Maximum accepted clock distance in seconds.
        #[arg(long, default_value_t = 300)]
        tolerance_seconds: u64,
    },
    /// Import a production application into the selected testing environment.
    Import {
        /// Canonical production application identifier, such as `google>drive`.
        app_id: String,
    },
    /// Show the webhook endpoint.
    Webhook {
        /// Canonical Application identifier (`org>handle`).
        app_id: String,
    },
    /// Propose a webhook endpoint.
    SetWebhook {
        /// Canonical Application identifier (`org>handle`).
        app_id: String,
        /// HTTPS endpoint to deliver to.
        #[arg(long)]
        url: String,
    },
    /// List deliveries that exhausted their retries.
    DeadLetters {
        /// Canonical Application identifier (`org>handle`).
        app_id: String,
        /// Paging.
        #[command(flatten)]
        page: PageArgs,
    },
    /// Re-queue dead-lettered deliveries.
    Replay {
        /// Canonical Application identifier (`org>handle`).
        app_id: String,
        /// Deliveries to replay.
        #[arg(long = "delivery", value_name = "DELIVERY_ID")]
        deliveries: Vec<Uuid>,
    },
    /// Show logins performed through an application.
    History {
        /// Canonical Application identifier (`org>handle`).
        app_id: String,
        /// Paging.
        #[command(flatten)]
        page: PageArgs,
    },
}

/// Application token commands.
#[derive(Debug, Subcommand)]
pub enum AppTokenCommand {
    /// Exchange a single-use short-lived token for an Application session.
    Exchange {
        /// Canonical Application identifier (`org>handle`).
        app_id: String,
        /// Short-lived token. Prompted for when omitted.
        #[arg(long)]
        slt: Option<String>,
        /// Application secret. Prompted for when omitted.
        #[arg(long)]
        app_secret: Option<String>,
        /// Reuse this after an uncertain exchange of the same short-lived token.
        #[arg(long)]
        idempotency_key: Option<String>,
    },
    /// Rotate an Application refresh token and its access token.
    Refresh {
        /// Canonical Application identifier (`org>handle`).
        app_id: String,
        /// Refresh token. Prompted for when omitted.
        #[arg(long)]
        refresh_token: Option<String>,
        /// Application secret. Prompted for when omitted.
        #[arg(long)]
        app_secret: Option<String>,
        /// Reuse this after an uncertain refresh; never retry with a new key.
        #[arg(long)]
        idempotency_key: Option<String>,
    },
    /// Ask IAM for a token's current, authoritative state.
    Introspect {
        /// Canonical Application identifier (`org>handle`).
        app_id: String,
        /// Access or refresh token. Prompted for when omitted.
        #[arg(long)]
        token: Option<String>,
        /// Hint which kind of token is being checked.
        #[arg(long, value_enum)]
        token_type: Option<AppTokenType>,
        /// Optional organization context sent as `X-Org-ID`.
        #[arg(long)]
        org_context: Option<String>,
        /// Application secret. Prompted for when omitted.
        #[arg(long)]
        app_secret: Option<String>,
    },
}

/// Token type hints accepted by Application introspection.
#[derive(Clone, Copy, Debug, ValueEnum)]
pub enum AppTokenType {
    /// An Application access token.
    AccessToken,
    /// An Application refresh token.
    RefreshToken,
}

/// OBO commands called by Applications as themselves.
#[derive(Debug, Subcommand)]
pub enum AppOboCommand {
    /// Discover an Application's callable OBO endpoint catalog.
    Endpoints {
        /// Canonical audience Application identifier (`org>handle`).
        audience_app_id: String,
        /// Canonical Application making the request.
        #[arg(long = "as-app-id", value_name = "APP_ID")]
        requester_app_id: String,
        /// Requester's Application secret. Prompted for when omitted.
        #[arg(long)]
        app_secret: Option<String>,
    },
    /// Bind a single-use proof to one exact downstream request.
    Exchange {
        /// Canonical audience Application identifier (`org>handle`).
        audience_app_id: String,
        /// Registered endpoint identifier from `app obo endpoints`.
        endpoint_id: String,
        /// Canonical Application making the request.
        #[arg(long = "as-app-id", value_name = "APP_ID")]
        requester_app_id: String,
        /// Requester's Application secret. Prompted for when omitted.
        #[arg(long)]
        app_secret: Option<String>,
        /// Actor-bound Application access token. Prompted for when omitted.
        #[arg(long)]
        subject_token: Option<String>,
        /// Downstream HTTP method; normalized to uppercase.
        #[arg(long)]
        method: String,
        /// JSON object required by the registered endpoint.
        #[arg(long, default_value = "{}")]
        metadata: String,
        /// Reuse this with the same timestamp and request after an uncertain exchange.
        #[arg(long)]
        idempotency_key: Option<String>,
        /// Unix timestamp used in the OBO signature. Defaults to now.
        #[arg(long)]
        timestamp: Option<i64>,
        /// Exact downstream body bytes.
        #[command(flatten)]
        body: RequestBodyArgs,
    },
    /// Consume and verify an OBO proof as its audience Application.
    Verify {
        /// Canonical audience Application identifier (`org>handle`).
        audience_app_id: String,
        /// Audience Application secret. Prompted for when omitted.
        #[arg(long)]
        app_secret: Option<String>,
        /// Single-use OBO proof. Prompted for when omitted.
        #[arg(long)]
        access_proof: Option<String>,
        /// Actual downstream HTTP method; normalized to uppercase.
        #[arg(long)]
        method: String,
        /// Exact registered path of the actual downstream request.
        #[arg(long)]
        path: String,
        /// Exact downstream body bytes.
        #[command(flatten)]
        body: RequestBodyArgs,
    },
}

/// A downstream request body supplied losslessly from a file or conveniently inline.
#[derive(Debug, Args)]
pub struct RequestBodyArgs {
    /// UTF-8 request body given directly; defaults to an empty body.
    #[arg(long, conflicts_with = "body_file")]
    pub body: Option<String>,
    /// File containing exact request bytes; use `-` for stdin.
    #[arg(long, value_name = "PATH", conflicts_with = "body")]
    pub body_file: Option<PathBuf>,
}

/// Testing environment commands.
#[derive(Debug, Subcommand)]
pub enum EnvCommand {
    /// List environments.
    List {
        /// `active`, `deleted`, or `all`.
        #[arg(long)]
        status: Option<String>,
        /// Paging.
        #[command(flatten)]
        page: PageArgs,
    },
    /// Create an environment, returning its key.
    Create {
        /// Environment name.
        name: String,
        /// Description.
        #[arg(long)]
        description: Option<String>,
    },
    /// Show one environment.
    Show {
        /// Environment identifier.
        environment_id: Uuid,
    },
    /// Rename or re-describe an environment.
    Update {
        /// Environment identifier.
        environment_id: Uuid,
        /// New name.
        #[arg(long)]
        name: Option<String>,
        /// New description.
        #[arg(long)]
        description: Option<String>,
    },
    /// Retire an environment, keeping it recoverable.
    Delete {
        /// Environment identifier.
        environment_id: Uuid,
    },
    /// Bring a retired environment back.
    Restore {
        /// Environment identifier.
        environment_id: Uuid,
    },
    /// Show an environment's key.
    Key {
        /// Environment identifier.
        environment_id: Uuid,
    },
    /// Issue a new key, invalidating the old one.
    RotateKey {
        /// Environment identifier.
        environment_id: Uuid,
    },
    /// Erase everything inside an environment.
    Clean {
        /// Environment identifier. Omit to clean the one selected by --test.
        environment_id: Option<Uuid>,
    },
    /// Describe the environment selected by --test.
    Current,
}

/// Session commands.
#[derive(Debug, Subcommand)]
pub enum SessionCommand {
    /// List your active sessions.
    List(PageArgs),
    /// Revoke one of your sessions. Needs --step-up.
    Revoke {
        /// Session identifier.
        session_id: Uuid,
    },
    /// Show your login history.
    History(PageArgs),
}

/// Settings commands.
#[derive(Debug, Subcommand)]
pub enum ConfigCommand {
    /// Show the current settings.
    Show,
    /// List configured profiles.
    Profiles,
    /// Set a value on the current profile.
    Set {
        /// One of `url`, `org`.
        key: String,
        /// The value to store.
        value: String,
    },
    /// Clear a value on the current profile.
    Unset {
        /// `org`.
        key: String,
    },
    /// Switch the default profile.
    Use {
        /// Profile name.
        profile: String,
    },
}

/// Service commands.
#[derive(Debug, Subcommand)]
pub enum SystemCommand {
    /// Show the service's version, and agree an API version.
    Version,
    /// Check that the service is alive and ready.
    Health,
}

/// Where a listing starts, and how much of it to take.
#[derive(Debug, Args, Default)]
pub struct PageArgs {
    /// Continue from a cursor a previous page returned.
    #[arg(long)]
    pub cursor: Option<String>,
    /// Maximum entries to return.
    #[arg(long)]
    pub limit: Option<u16>,
}

/// Accepts only the familiar hyphenated UUID form.
///
/// `uuid` deliberately also parses a 32-hex-digit simple UUID. Testing root
/// keys are 32 alphanumeric characters, so accepting that alternate form here
/// would let some secrets be mistaken for public environment ids.
fn parse_testing_environment_id(value: &str) -> Result<Uuid, String> {
    let bytes = value.as_bytes();
    let hyphenated = bytes.len() == 36
        && [8, 13, 18, 23]
            .into_iter()
            .all(|index| bytes.get(index) == Some(&b'-'));
    if !hyphenated {
        return Err(
            "expected a hyphenated testing-environment UUID, never its root key".to_owned(),
        );
    }
    Uuid::parse_str(value).map_err(|_| "expected a valid testing-environment UUID".to_owned())
}

impl PageArgs {
    /// The client's paging value for these arguments.
    #[must_use]
    pub fn paging(&self) -> silicon_iam_client::Paging {
        let mut paging = silicon_iam_client::Paging::new();
        if let Some(cursor) = &self.cursor {
            paging = paging.after(cursor.clone());
        }
        if let Some(limit) = self.limit {
            paging = paging.limit(limit);
        }
        paging
    }
}

#[cfg(test)]
mod tests {
    use clap::CommandFactory as _;

    use super::Cli;

    #[test]
    fn the_grammar_is_internally_consistent() {
        Cli::command().debug_assert();
        assert_eq!(Cli::command().get_name(), "iam");
    }

    #[test]
    fn global_flags_are_accepted_after_the_command_too() {
        use clap::Parser as _;

        let parsed = Cli::try_parse_from(["iam", "tag", "list", "--org", "acme"]);
        assert!(parsed.is_ok(), "{parsed:?}");
        let Ok(cli) = parsed else { return };
        assert_eq!(cli.global.org.as_deref(), Some("acme"));
    }

    #[test]
    fn login_admits_exactly_one_identity() {
        use clap::Parser as _;

        assert!(Cli::try_parse_from(["iam", "login", "--email", "a@b.test"]).is_ok());
        // Two identities is ambiguous, and the grammar says so rather than
        // silently preferring one.
        assert!(
            Cli::try_parse_from([
                "iam",
                "login",
                "--email",
                "a@b.test",
                "--carbon-id",
                "someone"
            ])
            .is_err()
        );
    }

    #[test]
    fn test_context_accepts_an_environment_id_and_never_a_raw_key() {
        use clap::Parser as _;

        let id = "0198aa41-52e7-7f32-8ab3-bd42110a6e2c";
        let parsed = Cli::try_parse_from(["iam", "--test", id, "whoami"]);
        assert!(parsed.is_ok(), "{parsed:?}");
        let Ok(cli) = parsed else { return };
        assert_eq!(
            cli.global.test.map(|value| value.to_string()).as_deref(),
            Some(id)
        );

        assert!(
            Cli::try_parse_from(["iam", "--test", &"a".repeat(32), "whoami"]).is_err(),
            "a root key must never be accepted where the public test id belongs"
        );
    }

    #[test]
    fn application_creation_requires_the_discoverable_base_url() {
        use clap::Parser as _;

        assert!(
            Cli::try_parse_from([
                "iam",
                "app",
                "create",
                "billing",
                "--name",
                "Billing",
                "--webhook-url",
                "https://billing.example/hooks",
            ])
            .is_err()
        );
        assert!(
            Cli::try_parse_from([
                "iam",
                "app",
                "create",
                "billing",
                "--name",
                "Billing",
                "--webhook-url",
                "https://billing.example/hooks",
                "--base-url",
                "https://billing.example",
            ])
            .is_ok()
        );
    }

    #[test]
    fn application_token_protocol_is_reachable_without_putting_secrets_in_argv() {
        use clap::Parser as _;

        assert!(Cli::try_parse_from(["iam", "app", "token", "exchange", "acme>checkout"]).is_ok());
        assert!(Cli::try_parse_from(["iam", "app", "token", "refresh", "acme>checkout"]).is_ok());
        assert!(
            Cli::try_parse_from([
                "iam",
                "app",
                "token",
                "introspect",
                "acme>checkout",
                "--token-type",
                "access-token",
            ])
            .is_ok()
        );
    }

    #[test]
    fn application_obo_protocol_has_all_three_steps_and_lossless_body_input() {
        use clap::Parser as _;

        assert!(
            Cli::try_parse_from([
                "iam",
                "app",
                "obo",
                "endpoints",
                "acme>billing",
                "--as-app-id",
                "acme>checkout",
            ])
            .is_ok()
        );
        assert!(
            Cli::try_parse_from([
                "iam",
                "app",
                "obo",
                "exchange",
                "acme>billing",
                "invoices.create",
                "--as-app-id",
                "acme>checkout",
                "--method",
                "post",
                "--body-file",
                "invoice.json",
            ])
            .is_ok()
        );
        assert!(
            Cli::try_parse_from([
                "iam",
                "app",
                "obo",
                "verify",
                "acme>billing",
                "--method",
                "POST",
                "--path",
                "/v1/invoices",
            ])
            .is_ok()
        );
        assert!(
            Cli::try_parse_from([
                "iam",
                "app",
                "obo",
                "exchange",
                "acme>billing",
                "invoices.create",
                "--as-app-id",
                "acme>checkout",
                "--method",
                "POST",
                "--body",
                "{}",
                "--body-file",
                "invoice.json",
            ])
            .is_err(),
            "inline and file bodies are mutually exclusive"
        );
    }

    #[test]
    fn offline_webhook_verification_requires_every_signed_header() {
        use clap::Parser as _;

        let complete = [
            "iam",
            "app",
            "verify-webhook",
            "delivery.json",
            "--event-id",
            "0198aa41-52e7-7f32-8ab3-bd42110a6e2c",
            "--timestamp",
            "1700000000",
            "--key-version",
            "1",
            "--signature",
            "v1=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
        ];
        assert!(Cli::try_parse_from(complete).is_ok());
        assert!(
            Cli::try_parse_from([
                "iam",
                "app",
                "verify-webhook",
                "delivery.json",
                "--event-id",
                "0198aa41-52e7-7f32-8ab3-bd42110a6e2c",
                "--timestamp",
                "1700000000",
                "--key-version",
                "1",
            ])
            .is_err()
        );
    }
}