-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
3839 lines (3684 loc) · 137 KB
/
Copy pathmain.rs
File metadata and controls
3839 lines (3684 loc) · 137 KB
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
//! `proxilion-cli` — operator CLI for log queries, chain verification,
//! end-to-end selftest, killswitch.
//!
//! Talks to the proxy's HTTP API (`/healthz`, `/api/v1/pca/...`) and, for
//! `selftest`, directly to the Trust Plane (`/v1/federation/info`,
//! `/v1/pca/issue`). For deeper SQL audit (action stream, blocked actions,
//! quarantine), connect to postgres — see `docs/specs/spec.md` §5.4.
use std::io::IsTerminal;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use anyhow::{Context, Result, anyhow};
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD as B64URL};
use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use clap_complete::Shell;
use serde::Deserialize;
use serde_json::{Value, json};
/// Proxilion CLI.
#[derive(Parser, Debug)]
#[command(version, about = "operator CLI for Proxilion", long_about = None)]
struct Cli {
/// Proxy base URL (overrides PROXILION_URL env var).
#[arg(long, env = "PROXILION_URL", default_value = "https://localhost:8443")]
url: String,
/// Trust Plane base URL (only used by `selftest`).
#[arg(long, env = "TRUST_PLANE_URL", default_value = "http://localhost:8080")]
trust_plane: String,
/// Accept self-signed certs (development only).
#[arg(long)]
insecure: bool,
/// Operator token (sent as `Authorization: Bearer <token>` on
/// `/api/v1/*` requests). When the proxy runs with
/// `PROXILION_DISABLE_OPERATOR_AUTH=1` this can be empty.
#[arg(long, env = "PROXILION_OPERATOR_TOKEN", default_value = "")]
token: String,
/// When to colorize output: auto (color iff stdout is a TTY and
/// `NO_COLOR` is unset), always, or never.
/// surface-delight-and-correctness.md §3.2.
#[arg(long, value_enum, default_value_t = ColorChoice::Auto)]
color: ColorChoice,
#[command(subcommand)]
cmd: Cmd,
}
/// `--color` policy. `auto` honors `NO_COLOR` and the TTY-ness of stdout.
#[derive(Copy, Clone, Debug, PartialEq, Eq, ValueEnum)]
enum ColorChoice {
Auto,
Always,
Never,
}
#[derive(Subcommand, Debug)]
enum Cmd {
/// Emit a shell completion script for `proxilion-cli`.
///
/// surface-delight-and-correctness.md §3.4. Offline — talks to no proxy.
/// Install (bash): `proxilion-cli completion bash > /etc/bash_completion.d/proxilion-cli`.
/// zsh: write to a dir on `$fpath`; fish: `~/.config/fish/completions/`.
Completion {
/// Target shell: bash | zsh | fish | powershell | elvish.
shell: Shell,
},
/// Probe the proxy's /healthz.
Health,
/// Fetch a single PCA by id.
Pca {
/// PCA UUID.
id: String,
},
/// Walk a PCA chain from this leaf to PCA_0 and report verification.
Verify {
/// Leaf PCA UUID.
id: String,
},
/// Run a synthetic end-to-end transaction (no real OAuth, no real SaaS).
///
/// Steps:
/// 1. /healthz must report ready
/// 2. /v1/federation/info reachable on the Trust Plane
/// 3. Mock IdP JWT → Trust Plane POST /v1/pca/issue → PCA_0
///
/// Reports ✓/✗ per step with timings. Non-zero exit on any failure.
Selftest,
/// Live tail / list / show / export of the action log.
#[command(subcommand)]
Actions(ActionsCmd),
/// Operator-token management (ui-less-surfaces.md §4.4). Writes
/// directly to postgres via `DATABASE_URL` — no token required (this
/// is how the bootstrap token is minted).
#[command(subcommand)]
Tokens(TokensCmd),
/// Policy hot-reload + mode flips (ui-less-surfaces.md §2 + §4).
#[command(subcommand)]
Policy(PolicyCmd),
/// Blocked-action queue: list / show / approve / reject.
#[command(subcommand)]
Blocked(BlockedCmd),
/// Notifier diagnostics (ui-less-surfaces.md §4.1).
#[command(subcommand)]
Notifier(NotifierCmd),
/// System + setup snapshot. Combines /healthz reachability + the
/// /api/v1/setup/status checklist into a single one-screen report.
/// Exits non-zero when /healthz is `ready:false` so a CI runner /
/// shell pipeline can gate on `proxilion-cli status` without parsing
/// JSON. ui-less-surfaces.md §4.1.
Status {
/// Output: pretty (default) | json.
#[arg(long, default_value = "pretty")]
format: String,
},
/// PCA inspection (ui-less-surfaces.md §4.1 — `pic` command tree).
/// Subset of the upstream §4.1 sketch: `show` and `verify` (the live
/// invariants-mode flip is wired through `policy set-mode` per
/// ui-less-surfaces.md §2 deviation 1; this subcommand is purely
/// the chain inspector).
#[command(subcommand)]
Pic(PicCmd),
/// Killswitch — revoke an agent's right to take further actions.
/// Spec.md §3.2. All three forms write to `kill_records`, mark
/// matching `agent_bearers.revoked_at`, and the auth middleware
/// rejects on the next request.
#[command(subcommand)]
Killswitch(KillswitchCmd),
/// Prometheus `/metrics` helpers (ui-less-surfaces.md §4.1).
#[command(subcommand)]
Metrics(MetricsCmd),
/// Trust Plane diagnostics (ui-less-surfaces.md §4.1).
#[command(subcommand)]
TrustPlane(TrustPlaneCmd),
/// OAuth client registry (ui-less-surfaces.md §4.1). Writes directly
/// to postgres via `DATABASE_URL` — no token required (same bootstrap
/// pattern as `tokens`). Replaces hand-editing `oauth_clients` via
/// psql / a migration.
#[command(subcommand)]
Clients(ClientsCmd),
}
#[derive(Subcommand, Debug)]
enum ClientsCmd {
/// List every OAuth client. By default skips revoked rows; `--all`
/// shows them.
List {
#[arg(long)]
all: bool,
/// Output: pretty (default) | json.
#[arg(long, default_value = "pretty")]
format: String,
},
/// Register a new OAuth client.
Add {
/// Stable client id the agent will send in `?client_id=...`.
id: String,
#[arg(long)]
name: String,
/// One or more allowed redirect URIs. Pass `--redirect-uri` once
/// per URI; the agent's redirect_uri must match one exactly.
#[arg(long = "redirect-uri", required = true)]
redirect_uri: Vec<String>,
},
/// Soft-revoke a client. The row stays in the table (historical
/// sessions still resolve) but the authorize handler refuses new
/// flows. ui-less-surfaces.md §4.1.
Revoke {
id: String,
#[arg(long, default_value = "operator-initiated")]
reason: String,
/// Preview whether the client would be revoked (and that it exists and
/// is not already revoked) without writing. §3.3.
#[arg(long)]
dry_run: bool,
},
}
#[derive(Subcommand, Debug)]
enum MetricsCmd {
/// Curl /metrics and pretty-print the top N series by sample count.
/// Mounted outside operator-auth — same trust boundary as the
/// Prometheus scrape target (assume operator network is private).
Sample {
/// Show only series whose name contains this substring.
#[arg(long)]
filter: Option<String>,
/// Print every metric line in raw exposition format instead of
/// the grouped summary.
#[arg(long)]
raw: bool,
},
}
#[derive(Subcommand, Debug)]
enum TrustPlaneCmd {
/// Fetch the Trust Plane's federation/info endpoint — confirms the
/// upstream is reachable and surfaces the CAT key id the proxy will
/// verify chain signatures against.
Info,
}
#[derive(Subcommand, Debug)]
enum PicCmd {
/// Fetch a PCA by id (same payload as `proxilion-cli pca`, kept here
/// so `pic show <id>` reads naturally alongside `pic verify <id>`).
Show {
/// PCA UUID.
id: String,
},
/// Walk a chain from this leaf to PCA_0 and report the result.
/// Non-zero exit when `intact:false`.
Verify {
/// Leaf PCA UUID.
id: String,
},
}
#[derive(Subcommand, Debug)]
enum KillswitchCmd {
/// Revoke a single session (`pxl_live_*` bearer chain rooted in this
/// OAuth session). All bearers under the session and all PCA-issuance
/// rights tied to it are revoked atomically.
Session {
/// Session UUID (the `id` column on `oauth_sessions`).
id: String,
/// Operator-visible reason; stored on `kill_records.reason`.
#[arg(long, default_value = "operator-initiated")]
reason: String,
/// Preview the blast radius (count of bearers that WOULD be revoked)
/// without revoking anything. surface-delight-and-correctness.md §3.3.
#[arg(long)]
dry_run: bool,
},
/// Revoke every active session for a user (`p_0`). Use for full-user
/// kill — e.g., suspended account, compromised credentials.
User {
/// `p_0` value (typically `user:alice@org.com`, but accepts any
/// PrincipalIdentifier-shaped string).
p_0: String,
#[arg(long, default_value = "operator-initiated")]
reason: String,
/// Preview without revoking. §3.3.
#[arg(long)]
dry_run: bool,
},
/// Revoke EVERY active session globally. Requires explicit confirmation
/// to guard against fat-fingered fleet-wide kills.
All {
/// Must be `yes` (case-sensitive) for the kill to fire. Not required
/// with `--dry-run` (a preview revokes nothing).
#[arg(long, default_value = "")]
confirm: String,
#[arg(long, default_value = "operator-initiated")]
reason: String,
/// Preview the fleet-wide blast radius without revoking. §3.3.
#[arg(long)]
dry_run: bool,
},
}
#[derive(Subcommand, Debug)]
enum NotifierCmd {
/// Display the current webhook + burst-suppressor config.
Show {
#[arg(long, default_value = "pretty")]
format: String,
},
/// Send a synthetic test notification. Default fans out to every
/// configured driver; `--driver <name>` targets one and 412s if
/// that driver isn't configured. ui-less-surfaces.md §4.1.
Test {
/// One of `all` (default) | `webhook` | `slack` | `email`.
#[arg(long, default_value = "all")]
driver: String,
},
/// Read the persisted notifier_config row.
Config,
/// Set / update the webhook driver config (DB-stored, hot-swapped on
/// the proxy without restart). ui-less-surfaces.md §8.4.
SetWebhook {
/// Webhook URL the proxy POSTs to.
#[arg(long)]
url: String,
/// HMAC secret (hex, ≥32 chars).
#[arg(long)]
hmac_hex: String,
/// Disable the webhook without removing the row.
#[arg(long)]
disabled: bool,
},
/// Set / update the Slack driver config (ui-less-surfaces.md §5.3).
/// Outbound: posts Block Kit message to the incoming-webhook URL.
/// Inbound: verifies button-click POSTs via the signing-secret.
SetSlack {
/// Slack incoming-webhook URL (Slack workspace admin > Apps > your app).
#[arg(long)]
incoming_webhook_url: String,
/// Slack signing secret (32-char hex from "Basic Information").
#[arg(long)]
signing_secret: String,
/// Disable without removing the row.
#[arg(long)]
disabled: bool,
},
/// Set / update the Email driver config (ui-less-surfaces.md §5.4).
/// Sends plain-text + HTML email with single-use signed approve/reject
/// URLs on every blocked action.
SetEmail {
/// SMTP relay URL: smtps://user:pass@host:465 or smtp://host:25.
#[arg(long)]
smtp_url: String,
/// RFC 5322 from address (e.g. "Proxilion <secops@org.com>").
#[arg(long)]
from: String,
/// Recipient(s). Repeat for multiple addresses.
#[arg(long = "to", required = true)]
to: Vec<String>,
/// Disable without removing the row.
#[arg(long)]
disabled: bool,
},
}
#[derive(Subcommand, Debug)]
enum PolicyCmd {
/// List current policies + modes.
List {
/// Optional mode filter: enforce | observe | disabled.
#[arg(long)]
mode: Option<String>,
/// Output: pretty | json.
#[arg(long, default_value = "pretty")]
format: String,
},
/// Show a single policy by id. Pulls the current loaded policy set
/// from the proxy (`GET /api/v1/policy`) and filters locally — no
/// new endpoint needed.
Show {
/// Policy id.
id: String,
#[arg(long, default_value = "pretty")]
format: String,
},
/// Parse a candidate YAML file and report whether it's loadable.
/// Exit 0 on success, 1 on parse failure. ui-less-surfaces.md §4.1.
/// Local-only — does not touch the proxy or DB; safe to run in CI.
Validate {
/// YAML file to validate.
file: String,
},
/// Diff two policy YAML files. Reports added / removed / modified
/// policy ids and per-policy field deltas (mode, decision shape,
/// match-expression text, required_ops). Local-only, no proxy hit.
Diff {
/// Baseline YAML file.
before: String,
/// Candidate YAML file.
after: String,
#[arg(long, default_value = "pretty")]
format: String,
},
/// Force a re-read from disk.
Reload,
/// Flip a single policy between observe / enforce / disabled.
SetMode {
/// Policy id.
id: String,
/// Target mode: `enforce`, `observe`, or `disabled`.
mode: String,
},
/// Open the live policy YAML in `$EDITOR`, validate on save, and
/// hot-reload the proxy. ui-less-surfaces.md §4.1 `policy edit`.
///
/// File-path resolution: `--file <path>` wins; otherwise the path
/// is pulled from `GET /api/v1/policy` (`source` field). When the
/// proxy's source path isn't reachable from this machine (remote
/// deployment), pass `--file` explicitly to edit a local copy.
///
/// Pre-flight: a backup copy is dropped at `<path>.bak` before the
/// editor opens. On a validation failure the new file is reverted
/// from the backup; the backup is removed on a successful reload.
Edit {
/// Path to the policy YAML. If unset, queried from the proxy.
#[arg(long)]
file: Option<String>,
/// Editor command. Defaults to `$EDITOR`, then `$VISUAL`, then
/// `vi`. Passed verbatim to the shell, so you can use e.g.
/// `--editor "code --wait"`.
#[arg(long)]
editor: Option<String>,
/// Skip the `POST /api/v1/policy/reload` after the save.
/// Local-only validation; the operator can hot-reload manually
/// later via `proxilion-cli policy reload`.
#[arg(long)]
no_reload: bool,
},
/// Replay historical action_events against a candidate YAML and
/// report would-have-block deltas per policy. ui-less-surfaces.md §2.4.
Simulate {
/// Candidate YAML file.
file: String,
/// Window: `last-7d`, `last-24h`, `last-1h`, or an explicit
/// `--since` / `--until` pair via the standard CLI flags above.
#[arg(long, default_value = "last-7d")]
against: String,
/// Customer domain for `${customer_domain}` substitution. If
/// unset, falls back to `PROXILION_CUSTOMER_DOMAIN` then a
/// reasonable default.
#[arg(long)]
customer_domain: Option<String>,
/// Per-page fetch limit. Default 500 (the proxy max).
#[arg(long, default_value_t = 500)]
page_limit: u32,
/// Output format. `pretty` (default) | `json`.
#[arg(long, default_value = "pretty")]
format: String,
/// Exit non-zero (code 1) when any policy's delta exceeds this
/// percentage of replayed events. Useful in CI gates.
#[arg(long)]
fail_if_delta_exceeds: Option<f64>,
},
}
#[derive(Subcommand, Debug)]
enum BlockedCmd {
/// List blocked actions, default filter pending.
List {
/// `pending` (default) | `approved` | `overridden` | `rejected` | `expired` | `all`.
#[arg(long, default_value = "pending")]
status: String,
/// Filter by p_0.
#[arg(long)]
p_0: Option<String>,
/// Filter by policy_id.
#[arg(long)]
policy_id: Option<String>,
/// Per-page limit (1..=500, default 50).
#[arg(long, default_value_t = 50)]
limit: u32,
/// Output: pretty | json.
#[arg(long, default_value = "pretty")]
format: String,
},
/// Show one blocked-action record (full envelope).
Show {
id: String,
/// Output: pretty | json.
#[arg(long, default_value = "pretty")]
format: String,
},
/// Approve a blocked action with a justification.
Approve {
id: String,
#[arg(long)]
justification: String,
/// Approver subject (defaults to $USER@cli).
#[arg(long)]
approver: Option<String>,
/// TTL in minutes for the override (1..=1440).
#[arg(long)]
ttl: Option<u32>,
},
/// Reject a blocked action.
Reject {
id: String,
#[arg(long)]
reason: Option<String>,
},
}
#[derive(Subcommand, Debug)]
enum TokensCmd {
/// Mint a new operator token. Prints once to stdout; only the SHA-256
/// hash is persisted.
Issue {
/// Human-readable name (e.g. "alice (on-call)" or "ci-bot").
#[arg(long)]
name: String,
/// Comma-separated scopes. Use `*` for an admin/bootstrap token.
/// See `--help-scopes` for the full catalogue.
#[arg(long, value_delimiter = ',')]
scope: Vec<String>,
},
/// List active (non-revoked) tokens.
List {
/// Include revoked tokens.
#[arg(long)]
all: bool,
},
/// Revoke a token by id.
Revoke {
/// Token id (UUID).
id: String,
/// Reason (optional, recorded for audit).
#[arg(long)]
reason: Option<String>,
},
/// Print the operator-token scope catalogue (what each scope grants,
/// which endpoints require it). ui-less-surfaces.md §4.4.
Scopes {
/// Output format. `pretty` (default) | `json`.
#[arg(long, default_value = "pretty")]
format: String,
},
}
#[derive(Subcommand, Debug)]
enum ActionsCmd {
/// Stream live action events (SSE) until interrupted.
Tail {
/// Filter: decision (allow|block|require_confirmation|rate_limit).
#[arg(long)]
decision: Option<String>,
/// Filter: vendor.
#[arg(long)]
vendor: Option<String>,
/// Filter: action verb (e.g. drive.files.get).
#[arg(long)]
action: Option<String>,
/// Output format. Defaults to ndjson.
#[arg(long, default_value = "ndjson")]
format: String,
},
/// List paginated history.
List {
#[arg(long)]
decision: Option<String>,
#[arg(long)]
vendor: Option<String>,
#[arg(long)]
action: Option<String>,
#[arg(long, value_name = "EMAIL_OR_ID")]
p_0: Option<String>,
#[arg(long)]
session_id: Option<String>,
/// Window like "24h", "5m", "7d".
#[arg(long)]
since: Option<String>,
/// Per-page limit (1..=500). Default 50.
#[arg(long, default_value_t = 50)]
limit: u32,
/// Follow `next_before` cursors until exhausted.
#[arg(long)]
all: bool,
/// Output: pretty | json | ndjson.
#[arg(long, default_value = "pretty")]
format: String,
},
/// Show a full action record with its PCA chain (ASCII inspector).
Show {
id: String,
/// Output: pretty | json.
#[arg(long, default_value = "pretty")]
format: String,
},
/// Bulk audit export. Streams from the proxy to stdout or a file.
Export {
/// `ndjson` (default) | `csv`.
#[arg(long, default_value = "ndjson")]
format: String,
/// Window like "30d", "7d", "24h", or an RFC3339 date.
#[arg(long)]
since: Option<String>,
/// Upper bound, RFC3339. Defaults to now.
#[arg(long)]
until: Option<String>,
#[arg(long)]
decision: Option<String>,
#[arg(long)]
vendor: Option<String>,
#[arg(long)]
action: Option<String>,
#[arg(long)]
p_0: Option<String>,
/// Write to file (default: stdout).
#[arg(long, short = 'o')]
output: Option<String>,
},
/// Show the ordered PCA chain for a given session (every leaf the
/// agent's bearers minted, walked back to PCA_0). Wraps
/// `GET /api/v1/sessions/{id}/chain` (ui-less-surfaces.md §4.1).
Chain {
/// Session UUID (`oauth_sessions.id`).
session_id: String,
/// Output: pretty (default) | json.
#[arg(long, default_value = "pretty")]
format: String,
},
/// Delete audit rows older than a window. Cron-friendly retention.
Purge {
/// Window like "90d", "30d", "7d", "24h", or an RFC3339 date. Rows
/// with `at < (now - window)` are deleted.
#[arg(long)]
older_than: String,
/// Count what would be deleted without deleting. Defaults to false.
#[arg(long)]
dry_run: bool,
/// Output: pretty (default) | json.
#[arg(long, default_value = "pretty")]
format: String,
},
}
#[tokio::main]
async fn main() -> Result<()> {
let cli = Cli::parse();
set_color_mode(cli.color);
// Offline, network-free commands handled before the HTTP client is built.
if let Cmd::Completion { shell } = &cli.cmd {
let shell = *shell;
let mut cmd = Cli::command();
let bin = cmd.get_name().to_string();
clap_complete::generate(shell, &mut cmd, bin, &mut std::io::stdout());
return Ok(());
}
let http = reqwest::Client::builder()
.timeout(Duration::from_secs(15))
.danger_accept_invalid_certs(cli.insecure)
.build()
.context("building reqwest client")?;
match cli.cmd {
Cmd::Completion { .. } => unreachable!("handled before the HTTP client is built"),
Cmd::Health => cmd_health(&http, &cli.url).await,
Cmd::Pca { id } => cmd_pca(&http, &cli.url, &cli.token, &id).await,
Cmd::Verify { id } => cmd_verify(&http, &cli.url, &cli.token, &id).await,
Cmd::Selftest => cmd_selftest(&http, &cli.url, &cli.trust_plane).await,
Cmd::Actions(sub) => cmd_actions(&http, &cli.url, &cli.token, sub).await,
Cmd::Tokens(sub) => cmd_tokens(sub).await,
Cmd::Policy(sub) => cmd_policy(&http, &cli.url, &cli.token, sub).await,
Cmd::Blocked(sub) => cmd_blocked(&http, &cli.url, &cli.token, sub).await,
Cmd::Notifier(sub) => cmd_notifier(&http, &cli.url, &cli.token, sub).await,
Cmd::Status { format } => cmd_status(&http, &cli.url, &cli.token, &format).await,
Cmd::Pic(sub) => cmd_pic(&http, &cli.url, &cli.token, sub).await,
Cmd::Killswitch(sub) => cmd_killswitch(&http, &cli.url, &cli.token, sub).await,
Cmd::Metrics(sub) => cmd_metrics(&http, &cli.url, sub).await,
Cmd::TrustPlane(sub) => cmd_trust_plane(&http, &cli.trust_plane, sub).await,
Cmd::Clients(sub) => cmd_clients(sub).await,
}
}
async fn cmd_clients(sub: ClientsCmd) -> Result<()> {
let db_url = std::env::var("DATABASE_URL")
.context("DATABASE_URL must be set (proxilion-cli clients writes directly to postgres)")?;
let pool = sqlx::PgPool::connect(&db_url)
.await
.context("connecting to postgres")?;
match sub {
ClientsCmd::List { all, format } => {
let rows: Vec<(
String,
String,
Vec<String>,
chrono::DateTime<chrono::Utc>,
Option<chrono::DateTime<chrono::Utc>>,
Option<String>,
)> = sqlx::query_as(
"SELECT id, name, redirect_uris, created_at, revoked_at, revoked_reason
FROM oauth_clients
WHERE ($1 OR revoked_at IS NULL)
ORDER BY created_at",
)
.bind(all)
.fetch_all(&pool)
.await
.context("selecting oauth_clients")?;
let arr: Vec<_> = rows
.iter()
.map(|(id, name, redirects, created, revoked, reason)| {
json!({
"id": id,
"name": name,
"redirect_uris": redirects,
"created_at": created.to_rfc3339(),
"revoked_at": revoked.map(|t| t.to_rfc3339()),
"revoked_reason": reason,
})
})
.collect();
if format == "json" {
println!("{}", serde_json::to_string_pretty(&arr)?);
} else {
// §3.1 — aligned table: client_id · name · created_at · revoked.
println!(
"{:<28} {:<24} {:<22} revoked",
"client_id", "name", "created_at"
);
println!("{}", "─".repeat(86));
for (id, name, _redirects, created, revoked, reason) in &rows {
let revoked_cell = match (revoked, reason) {
(Some(t), Some(r)) => format!("yes ({}) — {}", t.format("%Y-%m-%d"), r),
(Some(t), None) => format!("yes ({})", t.format("%Y-%m-%d")),
(None, _) => "no".to_string(),
};
println!(
"{:<28} {:<24} {:<22} {}",
truncate(id, 28),
truncate(name, 24),
created.format("%Y-%m-%d %H:%M UTC"),
revoked_cell,
);
}
println!("\n{} client(s)", rows.len());
}
Ok(())
}
ClientsCmd::Add {
id,
name,
redirect_uri,
} => {
// Defensive URL validation — every redirect_uri must parse as
// a real URL so we don't accept obvious typos that would
// 404 the OAuth handshake at exchange-time.
for u in &redirect_uri {
let parsed = reqwest::Url::parse(u)
.map_err(|e| anyhow!("redirect_uri `{u}` is not a valid URL: {e}"))?;
if parsed.scheme() != "https" && parsed.scheme() != "http" {
return Err(anyhow!(
"redirect_uri `{u}` must use http(s); got scheme `{}`",
parsed.scheme()
));
}
}
let res = sqlx::query(
"INSERT INTO oauth_clients (id, name, redirect_uris)
VALUES ($1, $2, $3)
ON CONFLICT (id) DO NOTHING",
)
.bind(&id)
.bind(&name)
.bind(&redirect_uri)
.execute(&pool)
.await
.context("inserting oauth_clients")?;
if res.rows_affected() == 0 {
return Err(anyhow!("client id `{id}` already exists"));
}
println!(
"{}",
serde_json::to_string_pretty(&json!({
"ok": true,
"id": id,
"name": name,
"redirect_uris": redirect_uri,
}))?
);
Ok(())
}
ClientsCmd::Revoke {
id,
reason,
dry_run,
} => {
if dry_run {
// §3.3 — resolve the target (would it be revoked?) without
// writing. Counts the rows the real UPDATE's WHERE matches.
let active: i64 = sqlx::query_scalar(
"SELECT count(*) FROM oauth_clients WHERE id = $1 AND revoked_at IS NULL",
)
.bind(&id)
.fetch_one(&pool)
.await
.context("previewing oauth_clients revoke")?;
if active == 0 {
return Err(anyhow!(
"no active client with id `{id}` (already revoked, or never existed)"
));
}
#[allow(non_snake_case)]
let (GREEN, _, DIM, RESET, _) = colors();
println!(
"{GREEN}dry-run{RESET}: would revoke client {DIM}{id}{RESET} (reason: {reason}) — nothing was changed."
);
return Ok(());
}
let res = sqlx::query(
"UPDATE oauth_clients
SET revoked_at = now(), revoked_reason = $2
WHERE id = $1 AND revoked_at IS NULL",
)
.bind(&id)
.bind(&reason)
.execute(&pool)
.await
.context("revoking oauth_clients row")?;
if res.rows_affected() == 0 {
return Err(anyhow!(
"no active client with id `{id}` (already revoked, or never existed)"
));
}
println!(
"{}",
serde_json::to_string_pretty(&json!({
"ok": true,
"id": id,
"revoked_reason": reason,
}))?
);
Ok(())
}
}
}
async fn cmd_metrics(http: &reqwest::Client, url: &str, sub: MetricsCmd) -> Result<()> {
match sub {
MetricsCmd::Sample { filter, raw } => {
let body = http
.get(format!("{url}/metrics"))
.send()
.await?
.error_for_status()?
.text()
.await?;
if raw {
if let Some(f) = filter.as_deref() {
for line in body.lines() {
if line.contains(f) {
println!("{line}");
}
}
} else {
print!("{body}");
}
return Ok(());
}
// Group by metric family (the name before `{`). One row per
// family with: sample count, smallest value, largest value.
// HELP / TYPE lines are dropped — the operator wants the data,
// not the schema, in this view.
use std::collections::BTreeMap;
let mut by_family: BTreeMap<String, (usize, f64, f64)> = BTreeMap::new();
for line in body.lines() {
let line = line.trim_start();
if line.is_empty() || line.starts_with('#') {
continue;
}
// `name{labels…} value` OR `name value`.
let (name_part, value_part) = match line.rsplit_once(' ') {
Some(t) => t,
None => continue,
};
let family = match name_part.find('{') {
Some(b) => &name_part[..b],
None => name_part,
};
if let Some(f) = filter.as_deref() {
if !family.contains(f) {
continue;
}
}
let v: f64 = value_part.parse().unwrap_or(f64::NAN);
let entry = by_family.entry(family.to_string()).or_insert((
0usize,
f64::INFINITY,
f64::NEG_INFINITY,
));
entry.0 += 1;
if !v.is_nan() {
if v < entry.1 {
entry.1 = v;
}
if v > entry.2 {
entry.2 = v;
}
}
}
if by_family.is_empty() {
println!("(no metric families matched)");
return Ok(());
}
println!(
"{:<60} {:>8} {:>14} {:>14}",
"FAMILY", "SERIES", "MIN", "MAX"
);
for (fam, (count, min, max)) in by_family {
let min_s = if min.is_infinite() {
"—".to_string()
} else {
format_metric_value(min)
};
let max_s = if max.is_infinite() {
"—".to_string()
} else {
format_metric_value(max)
};
println!("{fam:<60} {count:>8} {min_s:>14} {max_s:>14}");
}
Ok(())
}
}
}
/// Render a metric value compactly. Integers (no fractional part within
/// 1e-9 tolerance) drop the decimal; floats keep up to 6 significant digits.
fn format_metric_value(v: f64) -> String {
if (v.fract().abs() < 1e-9) && v.abs() < 1e15 {
format!("{}", v as i64)
} else {
format!("{v:.6}")
}
}
async fn cmd_trust_plane(
http: &reqwest::Client,
trust_plane_url: &str,
sub: TrustPlaneCmd,
) -> Result<()> {
match sub {
TrustPlaneCmd::Info => {
let v: Value = http
.get(format!("{trust_plane_url}/v1/federation/info"))
.send()
.await?
.error_for_status()?
.json()
.await?;
println!("{}", serde_json::to_string_pretty(&v)?);
Ok(())
}
}
}
async fn cmd_status(http: &reqwest::Client, url: &str, token: &str, format: &str) -> Result<()> {
#[allow(non_snake_case)]
let (GREEN, RED, _, RESET, _) = colors();
let healthz: Value = http
.get(format!("{url}/healthz"))
.send()
.await?
.json()
.await
.unwrap_or_else(|_| serde_json::json!({}));
let setup: Value = match auth_header(http.get(format!("{url}/api/v1/setup/status")), token)
.send()
.await
{
Ok(r) if r.status().is_success() => r.json().await.unwrap_or(Value::Null),
_ => Value::Null,
};
let ready = healthz
.get("ready")
.and_then(|v| v.as_bool())
.unwrap_or(false);
let combined = serde_json::json!({
"ready": ready,
"healthz": healthz,
"setup": setup,
});
if format == "json" {
println!("{}", serde_json::to_string_pretty(&combined)?);
} else {
let symbol = if ready { GREEN } else { RED };
let label = if ready { "ready" } else { "NOT ready" };
println!("proxilion status — {symbol}{label}{RESET}");
println!(" endpoint: {url}");
if let Some(version) = healthz.get("version").and_then(|v| v.as_str()) {
println!(" version: {version}");
}
if let Some(checks) = healthz.get("checks") {
println!(
" checks: {}",
serde_json::to_string(checks).unwrap_or_default()
);
}
if !setup.is_null() {
println!("\nsetup checklist:");
println!(
"{}",
serde_json::to_string_pretty(&setup).unwrap_or_default()
);
} else {
println!("\nsetup checklist: (unavailable — token missing or insufficient scope)");
}
}
if !ready {
std::process::exit(1);
}
Ok(())
}
async fn cmd_pic(http: &reqwest::Client, url: &str, token: &str, sub: PicCmd) -> Result<()> {
match sub {
PicCmd::Show { id } => {
let v: Value = auth_header(
http.get(format!("{url}/api/v1/pca/{}", urlencode(&id))),
token,
)
.send()
.await?
.error_for_status()?
.json()
.await?;
println!("{}", serde_json::to_string_pretty(&v)?);