loupe-cli 0.1.0

loupectl — admin CLI for loupe-server.
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
//! `loupectl` — operator CLI for loupe-server.
//!
//! Authenticates with the admin client cert minted by `loupe-server
//! init`. Every command is one round-trip; the CLI does no caching.

mod render;

use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use clap::{Args, Parser, Subcommand};
use loupe_proto::{
	FindingDetail, JobInfo, ListFindingsResponse, ListReposResponse, RegisterRepoRequest,
	RegisterRepoResponse, RegisterWorkerRequest, RegisterWorkerResponse, ReportingSetup,
	RetryVerifyRequest, RetryVerifyResponse, RotateRepoPatRequest, ScanRequest, ScanResponse,
	SetRepoGithubReportingRequest, UpdateRepoRequest, PROTOCOL_VERSION,
};

#[derive(Debug, Parser)]
#[command(version, about = "loupe operator CLI")]
struct Cli {
	#[command(flatten)]
	conn: ConnArgs,
	#[command(subcommand)]
	cmd: Cmd,
}

#[derive(Debug, Args)]
struct ConnArgs {
	#[arg(long, env = "LOUPE_SERVER_URL")]
	server_url: Option<reqwest::Url>,
	#[arg(long, env = "LOUPE_CA_CERT")]
	ca_cert: Option<PathBuf>,
	#[arg(long, env = "LOUPE_CA_CERT_PEM", hide_env_values = true)]
	ca_cert_pem: Option<String>,
	#[arg(long, env = "LOUPE_CA_CERT_PEM_B64", hide_env_values = true)]
	ca_cert_pem_b64: Option<String>,
	#[arg(long, env = "LOUPE_ADMIN_CERT")]
	admin_cert: Option<PathBuf>,
	#[arg(long, env = "LOUPE_ADMIN_CERT_PEM", hide_env_values = true)]
	admin_cert_pem: Option<String>,
	#[arg(long, env = "LOUPE_ADMIN_CERT_PEM_B64", hide_env_values = true)]
	admin_cert_pem_b64: Option<String>,
	#[arg(long, env = "LOUPE_ADMIN_KEY")]
	admin_key: Option<PathBuf>,
	#[arg(long, env = "LOUPE_ADMIN_KEY_PEM", hide_env_values = true)]
	admin_key_pem: Option<String>,
	#[arg(long, env = "LOUPE_ADMIN_KEY_PEM_B64", hide_env_values = true)]
	admin_key_pem_b64: Option<String>,
}

#[derive(Debug, Subcommand)]
enum Cmd {
	#[command(subcommand)]
	Repo(RepoCmd),
	#[command(subcommand)]
	Worker(WorkerCmd),
	#[command(subcommand)]
	Job(JobCmd),
	#[command(subcommand)]
	Finding(FindingCmd),
	#[command(subcommand)]
	Cert(CertCmd),
}

#[derive(Debug, Subcommand)]
enum RepoCmd {
	/// Register a new repo for scanning.
	Add(RepoAddArgs),
	/// List registered repos.
	List(ListArgs),
	/// Deregister a repo (cascades to its jobs and findings).
	Rm { id: i64 },
	/// Patch a repo's scheduling / verification settings. Each flag is
	/// optional and only present fields are applied.
	Update(RepoUpdateArgs),
	/// Replace the GitHub PAT used by this repo's issue reporter.
	RotatePat(RepoRotatePatArgs),
	/// Configure or replace this repo's GitHub issue reporter.
	SetGithubReporting(RepoSetGithubReportingArgs),
	/// Trigger a scan now.
	Scan {
		id: i64,
		#[arg(long, default_value_t = false)]
		incremental: bool,
	},
}

#[derive(Debug, Args)]
struct RepoRotatePatArgs {
	id: i64,
	/// Replacement PAT for this repo's GitHub issue reporter. Read
	/// from LOUPE_TRACKER_PAT if omitted.
	#[arg(long, env = "LOUPE_TRACKER_PAT", hide_env_values = true)]
	pat: String,
}

#[derive(Debug, Args)]
struct RepoSetGithubReportingArgs {
	id: i64,
	#[arg(long)]
	target_owner: String,
	#[arg(long)]
	target_repo: String,
	/// PAT for the target tracker repo. Read from LOUPE_TRACKER_PAT if
	/// omitted.
	#[arg(long, env = "LOUPE_TRACKER_PAT", hide_env_values = true)]
	pat: String,
}

#[derive(Debug, Args)]
struct RepoUpdateArgs {
	id: i64,
	/// Stop the scheduler from picking this repo. Triggered scans
	/// (`loupectl repo scan`) still go through.
	#[arg(long, conflicts_with = "enable")]
	disable: bool,
	/// Re-enable a previously disabled repo.
	#[arg(long, conflicts_with = "disable")]
	enable: bool,
	/// Set the scan interval (seconds). Pass 0 to leave it as-is — use
	/// `--disable` if you want to stop scheduled scans.
	#[arg(long)]
	interval: Option<u64>,
	/// Route findings through the verify flow before dispatching.
	#[arg(long, conflicts_with = "no_verification")]
	verification_enabled: bool,
	/// Dispatch findings immediately on insert; skip the verify flow.
	#[arg(long, conflicts_with = "verification_enabled")]
	no_verification: bool,
	/// Pin require_approval = true for this repo. Confirmed findings
	/// park in `awaiting_approval` until a human runs `loupectl
	/// finding approve`.
	#[arg(long, conflicts_with_all = ["no_require_approval", "inherit_approval"])]
	require_approval: bool,
	/// Pin require_approval = false for this repo (immediate dispatch
	/// even if the server default is on).
	#[arg(long, conflicts_with_all = ["require_approval", "inherit_approval"])]
	no_require_approval: bool,
	/// Clear any per-repo override and fall back to the server-level
	/// `require_approval_default`.
	#[arg(long, conflicts_with_all = ["require_approval", "no_require_approval"])]
	inherit_approval: bool,
}

#[derive(Debug, Args)]
struct RepoAddArgs {
	#[arg(long)]
	clone_url: String,
	#[arg(long)]
	branch: Option<String>,
	#[arg(long)]
	scan_interval_seconds: Option<u64>,
	/// Owner of the tracker repo where findings get filed. Required
	/// unless `--no-reporting` is set.
	#[arg(long, required_unless_present = "no_reporting")]
	target_owner: Option<String>,
	/// Tracker repo name where findings get filed. Required unless
	/// `--no-reporting` is set.
	#[arg(long, required_unless_present = "no_reporting")]
	target_repo: Option<String>,
	/// PAT with `repo` scope on the target tracker. Read from the env
	/// var `LOUPE_TRACKER_PAT` if not supplied — never echo it on the
	/// command line in shared shells. Required unless `--no-reporting`
	/// is set.
	#[arg(
		long,
		env = "LOUPE_TRACKER_PAT",
		hide_env_values = true,
		required_unless_present = "no_reporting"
	)]
	pat: Option<String>,
	/// Skip configuring an automatic reporter. Findings still go
	/// through the full scan + verification + approval pipeline.
	/// Confirmed findings remain `confirmed` so operators can configure
	/// reporting later and run `loupectl finding retry-report`, or
	/// triage manually with `loupectl finding show / approve / reject`.
	#[arg(
		long,
		default_value_t = false,
		conflicts_with_all = ["target_owner", "target_repo", "pat"],
	)]
	no_reporting: bool,
	/// Route findings through the verify flow before dispatching.
	#[arg(long, conflicts_with = "no_verification")]
	verification_enabled: bool,
	/// Pin verification off for this repo, even if the server default
	/// is on. If neither flag is set, repo registration inherits the
	/// server-level verification default.
	#[arg(long, conflicts_with = "verification_enabled")]
	no_verification: bool,
	/// Pin per-repo require_approval = true at registration time.
	#[arg(long, conflicts_with = "no_require_approval")]
	require_approval: bool,
	/// Pin per-repo require_approval = false at registration time.
	/// If neither flag is set, the repo inherits the server-level
	/// `require_approval_default`.
	#[arg(long, conflicts_with = "require_approval")]
	no_require_approval: bool,
}

#[derive(Debug, Subcommand)]
enum WorkerCmd {
	/// Mint a new worker cert. Saves the bundle to `--out` (or stdout).
	Register(WorkerRegisterArgs),
	/// Revoke a worker (next mTLS handshake from that cert will 401).
	Rm { id: i64 },
}

#[derive(Debug, Args)]
struct WorkerRegisterArgs {
	#[arg(long)]
	name: String,
	#[arg(long, conflicts_with = "emit_env")]
	out: Option<PathBuf>,
	/// Print sourceable LOUPE_WORKER_* env assignments instead of JSON.
	#[arg(long, default_value_t = false)]
	emit_env: bool,
}

#[derive(Debug, Subcommand)]
enum JobCmd {
	/// List jobs with the newest row printed last.
	List(ListArgs),
	Get {
		id: i64,
	},
	/// Requeue a failed job.
	Retry {
		id: i64,
	},
	/// Cancel queued or leased work.
	Cancel {
		id: i64,
	},
}

#[derive(Debug, Subcommand)]
enum FindingCmd {
	/// List recent findings for a repo (recent page, newest row printed last).
	List(FindingListArgs),
	/// FTS5 keyword search over a repo's findings (title, description,
	/// file path). Free-form keywords are sanitized server-side; the
	/// match is "every term must appear" with BM25 ranking. Useful for
	/// "have we seen something like this before?" lookups.
	Search {
		repo_id: i64,
		/// One or more space-separated keywords. Quote the whole
		/// thing if your shell would split on spaces.
		query: String,
		#[arg(long, default_value_t = 20)]
		limit: i64,
	},
	/// Pretty-print a single finding for human review: title + severity,
	/// location, description, PoC diff, and audit trail. Pass `--json`
	/// to dump the raw FindingDetail DTO instead (for scripting).
	Show {
		id: i64,
		/// Output the raw JSON DTO instead of the pretty rendering.
		#[arg(long, default_value_t = false)]
		json: bool,
	},
	/// Approve a finding parked in `awaiting_approval`. Transitions
	/// it to `confirmed` and immediately runs the dispatcher.
	Approve { id: i64 },
	/// Retry external reporting for a confirmed finding.
	RetryReport { id: i64 },
	/// Recover findings that still need verifier work and requeue or
	/// create their verify jobs.
	RetryVerify(RetryVerifyArgs),
	/// Reject a finding parked in `awaiting_approval`. Transitions
	/// it to terminal `dismissed` with the rejection audit trail
	/// stamped (distinct from a verifier-issued dismiss).
	Reject { id: i64 },
}

#[derive(Debug, Args)]
struct ListArgs {
	/// Number of rows to return.
	#[arg(short = 'n', long = "limit", value_parser = parse_positive_i64)]
	limit: Option<i64>,
}

#[derive(Debug, Args)]
struct FindingListArgs {
	repo_id: i64,
	/// Number of rows to return.
	#[arg(short = 'n', long = "limit", value_parser = parse_positive_i64)]
	limit: Option<i64>,
}

fn parse_positive_i64(raw: &str) -> Result<i64, String> {
	let value = raw.parse::<i64>().map_err(|_| "limit must be an integer".to_owned())?;
	if value <= 0 {
		return Err("limit must be positive".to_owned());
	}
	Ok(value)
}

#[derive(Debug, Args)]
struct RetryVerifyArgs {
	/// Return counts without changing findings or jobs.
	#[arg(long, default_value_t = false)]
	dry_run: bool,
	/// Also retry findings whose verifier-produced history contains an
	/// inconclusive verdict. Deadline-reaper inconclusive rows remain
	/// recoverable without this flag.
	#[arg(long, default_value_t = false)]
	include_inconclusive: bool,
	/// Restrict recovery to one repo.
	#[arg(long)]
	repo_id: Option<i64>,
	/// Optional cap on findings processed in one request.
	#[arg(long)]
	limit: Option<i64>,
}

#[derive(Debug, Subcommand)]
enum CertCmd {
	/// Mint a replacement server certificate signed by the existing CA.
	MintServer(CertMintServerArgs),
}

#[derive(Debug, Args)]
struct CertMintServerArgs {
	/// DNS name to include in the server certificate SAN. Repeat for
	/// every hostname clients will use.
	#[arg(long = "hostname", required = true)]
	hostnames: Vec<String>,
	#[arg(long, default_value = "loupe-server")]
	common_name: String,
	#[arg(long, default_value_t = false)]
	emit_env: bool,
	#[arg(long, env = "LOUPE_CA_CERT")]
	ca_cert: Option<PathBuf>,
	#[arg(long, env = "LOUPE_CA_CERT_PEM", hide_env_values = true)]
	ca_cert_pem: Option<String>,
	#[arg(long, env = "LOUPE_CA_CERT_PEM_B64", hide_env_values = true)]
	ca_cert_pem_b64: Option<String>,
	#[arg(long, env = "LOUPE_CA_KEY")]
	ca_key: Option<PathBuf>,
	#[arg(long, env = "LOUPE_CA_KEY_PEM", hide_env_values = true)]
	ca_key_pem: Option<String>,
	#[arg(long, env = "LOUPE_CA_KEY_PEM_B64", hide_env_values = true)]
	ca_key_pem_b64: Option<String>,
}

#[tokio::main]
async fn main() -> Result<()> {
	let Cli { conn, cmd } = Cli::parse();
	match cmd {
		Cmd::Repo(c) => match c {
			RepoCmd::Add(a) => {
				let (client, base) = client_and_url(&conn)?;
				repo_add(&client, base, a).await
			},
			RepoCmd::List(args) => {
				let (client, base) = client_and_url(&conn)?;
				repo_list(&client, base, args.limit).await
			},
			RepoCmd::Rm { id } => {
				let (client, base) = client_and_url(&conn)?;
				repo_rm(&client, base, id).await
			},
			RepoCmd::Update(a) => {
				let (client, base) = client_and_url(&conn)?;
				repo_update(&client, base, a).await
			},
			RepoCmd::RotatePat(a) => {
				let (client, base) = client_and_url(&conn)?;
				repo_rotate_pat(&client, base, a).await
			},
			RepoCmd::SetGithubReporting(a) => {
				let (client, base) = client_and_url(&conn)?;
				repo_set_github_reporting(&client, base, a).await
			},
			RepoCmd::Scan { id, incremental } => {
				let (client, base) = client_and_url(&conn)?;
				repo_scan(&client, base, id, incremental).await
			},
		},
		Cmd::Worker(c) => match c {
			WorkerCmd::Register(a) => {
				let (client, base) = client_and_url(&conn)?;
				worker_register(&client, base, a).await
			},
			WorkerCmd::Rm { id } => {
				let (client, base) = client_and_url(&conn)?;
				worker_rm(&client, base, id).await
			},
		},
		Cmd::Job(c) => match c {
			JobCmd::List(args) => {
				let (client, base) = client_and_url(&conn)?;
				job_list(&client, base, args.limit).await
			},
			JobCmd::Get { id } => {
				let (client, base) = client_and_url(&conn)?;
				job_get(&client, base, id).await
			},
			JobCmd::Retry { id } => {
				let (client, base) = client_and_url(&conn)?;
				job_retry(&client, base, id).await
			},
			JobCmd::Cancel { id } => {
				let (client, base) = client_and_url(&conn)?;
				job_cancel(&client, base, id).await
			},
		},
		Cmd::Finding(c) => match c {
			FindingCmd::List(args) => {
				let (client, base) = client_and_url(&conn)?;
				finding_list(&client, base, args.repo_id, args.limit).await
			},
			FindingCmd::Search { repo_id, query, limit } => {
				let (client, base) = client_and_url(&conn)?;
				finding_search(&client, base, repo_id, &query, limit).await
			},
			FindingCmd::Show { id, json } => {
				let (client, base) = client_and_url(&conn)?;
				finding_show(&client, base, id, json).await
			},
			FindingCmd::Approve { id } => {
				let (client, base) = client_and_url(&conn)?;
				finding_approve(&client, base, id).await
			},
			FindingCmd::RetryReport { id } => {
				let (client, base) = client_and_url(&conn)?;
				finding_retry_report(&client, base, id).await
			},
			FindingCmd::RetryVerify(a) => {
				let (client, base) = client_and_url(&conn)?;
				finding_retry_verify(&client, base, a).await
			},
			FindingCmd::Reject { id } => {
				let (client, base) = client_and_url(&conn)?;
				finding_reject(&client, base, id).await
			},
		},
		Cmd::Cert(c) => match c {
			CertCmd::MintServer(a) => cert_mint_server(a),
		},
	}
}

fn client_and_url(c: &ConnArgs) -> Result<(reqwest::Client, &reqwest::Url)> {
	let base = server_url(c)?;
	let client = build_client(c)?;
	Ok((client, base))
}

fn server_url(c: &ConnArgs) -> Result<&reqwest::Url> {
	c.server_url.as_ref().context("server URL missing — set LOUPE_SERVER_URL or pass --server-url")
}

fn build_client(c: &ConnArgs) -> Result<reqwest::Client> {
	let ca = pem_from_env_or_file(
		"CA cert",
		&c.ca_cert_pem,
		&c.ca_cert_pem_b64,
		c.ca_cert.as_ref(),
		"CA cert missing — set LOUPE_CA_CERT_PEM, LOUPE_CA_CERT_PEM_B64, or LOUPE_CA_CERT",
	)?;
	let cert = pem_from_env_or_file(
		"admin cert",
		&c.admin_cert_pem,
		&c.admin_cert_pem_b64,
		c.admin_cert.as_ref(),
		"admin cert missing — set LOUPE_ADMIN_CERT_PEM, LOUPE_ADMIN_CERT_PEM_B64, or LOUPE_ADMIN_CERT",
	)?;
	let key = pem_from_env_or_file(
		"admin key",
		&c.admin_key_pem,
		&c.admin_key_pem_b64,
		c.admin_key.as_ref(),
		"admin key missing — set LOUPE_ADMIN_KEY_PEM, LOUPE_ADMIN_KEY_PEM_B64, or LOUPE_ADMIN_KEY",
	)?;
	let mut combined = String::with_capacity(cert.len() + key.len() + 1);
	combined.push_str(&cert);
	if !cert.ends_with('\n') {
		combined.push('\n');
	}
	combined.push_str(&key);

	let identity =
		reqwest::Identity::from_pem(combined.as_bytes()).context("parsing admin identity")?;
	let root = reqwest::Certificate::from_pem(ca.as_bytes()).context("parsing CA cert")?;
	reqwest::Client::builder()
		.add_root_certificate(root)
		.identity(identity)
		.use_rustls_tls()
		.build()
		.context("building reqwest client")
}

fn pem_from_env_or_file(
	label: &str, pem: &Option<String>, pem_b64: &Option<String>, path: Option<&PathBuf>,
	missing: &'static str,
) -> Result<String> {
	if let Some(pem) = pem.as_deref().filter(|s| !s.is_empty()) {
		return Ok(pem.to_owned());
	}
	if let Some(pem_b64) = pem_b64.as_deref().filter(|s| !s.is_empty()) {
		use base64::Engine as _;
		let bytes = base64::engine::general_purpose::STANDARD
			.decode(pem_b64.trim())
			.with_context(|| format!("decoding base64 {label} PEM"))?;
		return String::from_utf8(bytes).with_context(|| format!("{label} PEM is not valid UTF-8"));
	}
	let path = path.context(missing)?;
	std::fs::read_to_string(path).with_context(|| format!("reading {label} at {}", path.display()))
}

fn url(base: &reqwest::Url, path: &str) -> reqwest::Url {
	base.join(path).expect("path is always valid")
}

async fn repo_add(client: &reqwest::Client, base: &reqwest::Url, a: RepoAddArgs) -> Result<()> {
	let require_approval = match (a.require_approval, a.no_require_approval) {
		(true, false) => Some(true),
		(false, true) => Some(false),
		_ => None,
	};
	let verification_enabled = match (a.verification_enabled, a.no_verification) {
		(true, false) => Some(true),
		(false, true) => Some(false),
		_ => None,
	};
	let reporting = if a.no_reporting {
		ReportingSetup::Manual
	} else {
		ReportingSetup::GithubIssue {
			// `clap` enforces these are present unless --no-reporting is set,
			// so the unwrap is structurally safe.
			target_owner: a.target_owner.expect("clap enforces target_owner"),
			target_repo: a.target_repo.expect("clap enforces target_repo"),
			github_pat: a.pat.expect("clap enforces pat"),
		}
	};
	let req = RegisterRepoRequest {
		protocol_version: PROTOCOL_VERSION,
		clone_url: a.clone_url,
		branch: a.branch,
		scan_interval_seconds: a.scan_interval_seconds,
		reporting,
		scanner_config: serde_json::Value::Null,
		verification_enabled,
		require_approval,
	};
	let resp = client.post(url(base, "/v1/repos")).json(&req).send().await?;
	let status = resp.status();
	if !status.is_success() {
		anyhow::bail!("register repo: {} — {}", status, resp.text().await.unwrap_or_default());
	}
	let body: RegisterRepoResponse = resp.json().await?;
	println!("repo_id={}", body.repo_id);
	Ok(())
}

async fn repo_list(
	client: &reqwest::Client, base: &reqwest::Url, limit: Option<i64>,
) -> Result<()> {
	let req = client.get(url(base, "/v1/repos"));
	let req = if let Some(limit) = limit { req.query(&[("limit", limit)]) } else { req };
	let resp = req.send().await?;
	let body: ListReposResponse = resp.error_for_status()?.json().await?;
	for r in body.repos {
		let approval = r.require_approval.map_or("inherit".to_owned(), |v| v.to_string());
		let disabled = r.disabled_at.map_or("active".to_owned(), |ts| format!("disabled@{ts}"));
		println!(
			"{:>4}\t{}\t{}/{}\tinterval={:?}\tverify={}\tapproval={}\t{}\tlast_sha={:?}",
			r.id,
			r.host,
			r.owner,
			r.repo,
			r.scan_interval_seconds,
			r.verification_enabled,
			approval,
			disabled,
			r.last_scanned_sha,
		);
	}
	Ok(())
}

async fn repo_rm(client: &reqwest::Client, base: &reqwest::Url, id: i64) -> Result<()> {
	let resp = client.delete(url(base, &format!("/v1/repos/{id}"))).send().await?;
	resp.error_for_status()?;
	Ok(())
}

async fn repo_update(
	client: &reqwest::Client, base: &reqwest::Url, a: RepoUpdateArgs,
) -> Result<()> {
	let disabled = match (a.disable, a.enable) {
		(true, false) => Some(true),
		(false, true) => Some(false),
		_ => None,
	};
	let verification_enabled = match (a.verification_enabled, a.no_verification) {
		(true, false) => Some(true),
		(false, true) => Some(false),
		_ => None,
	};
	let require_approval = match (a.require_approval, a.no_require_approval) {
		(true, false) => Some(true),
		(false, true) => Some(false),
		_ => None,
	};
	let req = UpdateRepoRequest {
		protocol_version: PROTOCOL_VERSION,
		disabled,
		scan_interval_seconds: a.interval,
		verification_enabled,
		require_approval,
		inherit_require_approval: a.inherit_approval,
	};
	let resp = client.patch(url(base, &format!("/v1/repos/{}", a.id))).json(&req).send().await?;
	let status = resp.status();
	if !status.is_success() {
		anyhow::bail!("update repo: {} — {}", status, resp.text().await.unwrap_or_default());
	}
	Ok(())
}

async fn repo_rotate_pat(
	client: &reqwest::Client, base: &reqwest::Url, a: RepoRotatePatArgs,
) -> Result<()> {
	let req = RotateRepoPatRequest { protocol_version: PROTOCOL_VERSION, github_pat: a.pat };
	let resp = client
		.post(url(base, &format!("/v1/repos/{}/reporting/github-pat", a.id)))
		.json(&req)
		.send()
		.await?;
	let status = resp.status();
	if !status.is_success() {
		anyhow::bail!("rotate repo PAT: {} — {}", status, resp.text().await.unwrap_or_default());
	}
	Ok(())
}

async fn repo_set_github_reporting(
	client: &reqwest::Client, base: &reqwest::Url, a: RepoSetGithubReportingArgs,
) -> Result<()> {
	let req = SetRepoGithubReportingRequest {
		protocol_version: PROTOCOL_VERSION,
		target_owner: a.target_owner,
		target_repo: a.target_repo,
		github_pat: a.pat,
	};
	let resp = client
		.put(url(base, &format!("/v1/repos/{}/reporting/github", a.id)))
		.json(&req)
		.send()
		.await?;
	let status = resp.status();
	if !status.is_success() {
		anyhow::bail!(
			"set GitHub reporting: {} — {}",
			status,
			resp.text().await.unwrap_or_default()
		);
	}
	Ok(())
}

async fn repo_scan(
	client: &reqwest::Client, base: &reqwest::Url, id: i64, incremental: bool,
) -> Result<()> {
	let resp = client
		.post(url(base, &format!("/v1/repos/{id}/scan")))
		.json(&ScanRequest { protocol_version: PROTOCOL_VERSION, incremental })
		.send()
		.await?;
	let status = resp.status();
	if !status.is_success() {
		anyhow::bail!("scan: {} — {}", status, resp.text().await.unwrap_or_default());
	}
	let body: ScanResponse = resp.json().await?;
	println!("job_id={}", body.job_id);
	Ok(())
}

async fn worker_register(
	client: &reqwest::Client, base: &reqwest::Url, a: WorkerRegisterArgs,
) -> Result<()> {
	let resp = client
		.post(url(base, "/v1/workers"))
		.json(&RegisterWorkerRequest { protocol_version: PROTOCOL_VERSION, name: a.name })
		.send()
		.await?;
	let status = resp.status();
	if !status.is_success() {
		anyhow::bail!("register worker: {} — {}", status, resp.text().await.unwrap_or_default());
	}
	let bundle: RegisterWorkerResponse = resp.json().await?;
	if a.emit_env {
		for (name, value) in worker_env_assignments(base, &bundle) {
			println!("{name}={value}");
		}
		return Ok(());
	}
	let serialised = serde_json::to_string_pretty(&bundle)?;
	if let Some(path) = a.out {
		write_secret_file(&path, serialised.as_bytes())?;
		println!("worker_id={} bundle written to {}", bundle.worker_id, path.display());
	} else {
		println!("{serialised}");
	}
	Ok(())
}

/// Persist secret material without exposing it to group/other users.
///
/// The worker registration bundle includes an mTLS private key, so we
/// create it atomically with owner-only permissions and refuse to
/// overwrite an existing path that may already have weaker permissions.
fn write_secret_file(path: &Path, contents: &[u8]) -> Result<()> {
	use std::io::Write;

	let mut options = std::fs::OpenOptions::new();
	options.write(true).create_new(true);
	#[cfg(unix)]
	{
		use std::os::unix::fs::OpenOptionsExt;
		options.mode(0o600);
	}

	let mut file =
		options.open(path).with_context(|| format!("creating secret file {}", path.display()))?;
	#[cfg(unix)]
	{
		use std::os::unix::fs::PermissionsExt;
		file.set_permissions(std::fs::Permissions::from_mode(0o600))
			.with_context(|| format!("setting permissions on {}", path.display()))?;
	}
	file.write_all(contents).with_context(|| format!("writing secret file {}", path.display()))?;
	Ok(())
}

fn worker_env_assignments(
	base: &reqwest::Url, bundle: &RegisterWorkerResponse,
) -> Vec<(&'static str, String)> {
	vec![
		("LOUPE_SERVER_URL", base.as_str().to_owned()),
		("LOUPE_WORKER_CA_CERT_PEM_B64", b64(&bundle.ca_cert_pem)),
		("LOUPE_WORKER_CERT_PEM_B64", b64(&bundle.client_cert_pem)),
		("LOUPE_WORKER_KEY_PEM_B64", b64(&bundle.client_key_pem)),
	]
}

fn b64(value: &str) -> String {
	use base64::Engine as _;
	base64::engine::general_purpose::STANDARD.encode(value.as_bytes())
}

fn cert_mint_server(a: CertMintServerArgs) -> Result<()> {
	let bundle = mint_server_cert(&a)?;
	if a.emit_env {
		for (name, value) in server_cert_env_assignments(&bundle) {
			println!("{name}={value}");
		}
		return Ok(());
	}

	println!(
		"{}",
		serde_json::to_string_pretty(&serde_json::json!({
			"server_cert_pem": bundle.cert_pem,
			"server_key_pem": bundle.key_pem,
		}))?
	);
	Ok(())
}

fn mint_server_cert(a: &CertMintServerArgs) -> Result<loupe_tls::CertBundle> {
	let ca_cert = pem_from_env_or_file(
		"CA cert",
		&a.ca_cert_pem,
		&a.ca_cert_pem_b64,
		a.ca_cert.as_ref(),
		"CA cert missing — set LOUPE_CA_CERT_PEM, LOUPE_CA_CERT_PEM_B64, or LOUPE_CA_CERT",
	)?;
	let ca_key = pem_from_env_or_file(
		"CA key",
		&a.ca_key_pem,
		&a.ca_key_pem_b64,
		a.ca_key.as_ref(),
		"CA key missing — set LOUPE_CA_KEY_PEM, LOUPE_CA_KEY_PEM_B64, or LOUPE_CA_KEY",
	)?;
	let ca = loupe_tls::Ca::from_pem(&ca_cert, &ca_key)?;
	ca.mint_server(&a.common_name, &a.hostnames)
}

fn server_cert_env_assignments(bundle: &loupe_tls::CertBundle) -> Vec<(&'static str, String)> {
	vec![
		("LOUPE_SERVER_CERT_PEM_B64", b64(&bundle.cert_pem)),
		("LOUPE_SERVER_KEY_PEM_B64", b64(&bundle.key_pem)),
	]
}

async fn worker_rm(client: &reqwest::Client, base: &reqwest::Url, id: i64) -> Result<()> {
	let resp = client.delete(url(base, &format!("/v1/workers/{id}"))).send().await?;
	resp.error_for_status()?;
	Ok(())
}

async fn job_list(client: &reqwest::Client, base: &reqwest::Url, limit: Option<i64>) -> Result<()> {
	let req = client.get(url(base, "/v1/jobs"));
	let req = if let Some(limit) = limit { req.query(&[("limit", limit)]) } else { req };
	let resp = req.send().await?;
	let jobs: Vec<JobInfo> = resp.error_for_status()?.json().await?;
	for j in jobs.into_iter().rev() {
		println!(
			"{:>4}\trepo={}\tkind={:?}\tstate={:?}\tattempts={}\thead={:?}",
			j.job_id, j.repo_id, j.kind, j.state, j.attempts, j.head_sha,
		);
	}
	Ok(())
}

async fn job_get(client: &reqwest::Client, base: &reqwest::Url, id: i64) -> Result<()> {
	let resp = client.get(url(base, &format!("/v1/jobs/{id}"))).send().await?;
	let job: JobInfo = resp.error_for_status()?.json().await?;
	println!("{}", serde_json::to_string_pretty(&job)?);
	Ok(())
}

async fn job_retry(client: &reqwest::Client, base: &reqwest::Url, id: i64) -> Result<()> {
	let resp = client.post(url(base, &format!("/v1/jobs/{id}/retry"))).send().await?;
	let status = resp.status();
	if !status.is_success() {
		anyhow::bail!("retry job: {} — {}", status, resp.text().await.unwrap_or_default());
	}
	let job: JobInfo = resp.json().await?;
	println!("job_id={} state={:?} attempts={}", job.job_id, job.state, job.attempts);
	Ok(())
}

async fn job_cancel(client: &reqwest::Client, base: &reqwest::Url, id: i64) -> Result<()> {
	let resp = client.post(url(base, &format!("/v1/jobs/{id}/cancel"))).send().await?;
	let status = resp.status();
	if !status.is_success() {
		anyhow::bail!("cancel job: {} — {}", status, resp.text().await.unwrap_or_default());
	}
	let job: JobInfo = resp.json().await?;
	println!("job_id={} state={:?} attempts={}", job.job_id, job.state, job.attempts);
	Ok(())
}

async fn finding_list(
	client: &reqwest::Client, base: &reqwest::Url, repo_id: i64, limit: Option<i64>,
) -> Result<()> {
	let req = client.get(url(base, &format!("/v1/repos/{repo_id}/findings")));
	let req = if let Some(limit) = limit { req.query(&[("limit", limit)]) } else { req };
	let resp = req.send().await?;
	let body: ListFindingsResponse = resp.error_for_status()?.json().await?;
	for f in body.findings.into_iter().rev() {
		let loc = match (f.file_path.as_deref(), f.line_start) {
			(Some(p), Some(l)) => format!("{p}:{l}"),
			(Some(p), None) => p.to_string(),
			_ => "-".into(),
		};
		println!(
			"{:>5}\tjob={}\t{:?}\t{}\tstate={}\tverify={}\t{}\t{}",
			f.id,
			f.job_id,
			f.severity,
			f.scanner_id,
			f.state,
			f.verification_required,
			loc,
			f.title,
		);
	}
	Ok(())
}

async fn finding_search(
	client: &reqwest::Client, base: &reqwest::Url, repo_id: i64, query: &str, limit: i64,
) -> Result<()> {
	let url = url(base, &format!("/v1/repos/{repo_id}/findings/search"));
	let resp = client.get(url).query(&[("q", query), ("limit", &limit.to_string())]).send().await?;
	let body: ListFindingsResponse = resp.error_for_status()?.json().await?;
	if body.findings.is_empty() {
		println!("(no matches)");
		return Ok(());
	}
	for f in body.findings {
		let loc = match (f.file_path.as_deref(), f.line_start) {
			(Some(p), Some(l)) => format!("{p}:{l}"),
			(Some(p), None) => p.to_string(),
			_ => "-".into(),
		};
		println!(
			"{:>5}\t{:?}\t{}\tstate={}\t{}\t{}",
			f.id, f.severity, f.scanner_id, f.state, loc, f.title,
		);
	}
	Ok(())
}

async fn finding_show(
	client: &reqwest::Client, base: &reqwest::Url, id: i64, as_json: bool,
) -> Result<()> {
	let resp = client.get(url(base, &format!("/v1/findings/{id}"))).send().await?;
	let detail: FindingDetail = resp.error_for_status()?.json().await?;
	if as_json {
		println!("{}", serde_json::to_string_pretty(&detail)?);
	} else {
		print!("{}", render::finding(&detail, render::Style::detect()));
	}
	Ok(())
}

async fn finding_approve(client: &reqwest::Client, base: &reqwest::Url, id: i64) -> Result<()> {
	let resp = client.post(url(base, &format!("/v1/findings/{id}/approve"))).send().await?;
	let status = resp.status();
	if !status.is_success() {
		anyhow::bail!("approve finding: {} — {}", status, resp.text().await.unwrap_or_default());
	}
	Ok(())
}

async fn finding_retry_report(
	client: &reqwest::Client, base: &reqwest::Url, id: i64,
) -> Result<()> {
	let resp = client.post(url(base, &format!("/v1/findings/{id}/retry-report"))).send().await?;
	let status = resp.status();
	if !status.is_success() {
		anyhow::bail!("retry report: {} — {}", status, resp.text().await.unwrap_or_default());
	}
	Ok(())
}

async fn finding_retry_verify(
	client: &reqwest::Client, base: &reqwest::Url, args: RetryVerifyArgs,
) -> Result<()> {
	let req = RetryVerifyRequest {
		protocol_version: PROTOCOL_VERSION,
		dry_run: args.dry_run,
		include_inconclusive: args.include_inconclusive,
		repo_id: args.repo_id,
		limit: args.limit,
	};
	let resp = client.post(url(base, "/v1/findings/retry-verify")).json(&req).send().await?;
	let status = resp.status();
	if !status.is_success() {
		anyhow::bail!("retry verify: {} — {}", status, resp.text().await.unwrap_or_default());
	}
	let body: RetryVerifyResponse = resp.json().await?;
	let label = if body.dry_run { "would_revive" } else { "revived" };
	println!(
		"dry_run={} matched={} {}={} requeued_jobs={} created_jobs={} left_queued_or_leased={}",
		body.dry_run,
		body.matched,
		label,
		body.revived,
		body.requeued_jobs,
		body.created_jobs,
		body.left_queued_or_leased,
	);
	Ok(())
}

async fn finding_reject(client: &reqwest::Client, base: &reqwest::Url, id: i64) -> Result<()> {
	let resp = client.post(url(base, &format!("/v1/findings/{id}/reject"))).send().await?;
	let status = resp.status();
	if !status.is_success() {
		anyhow::bail!("reject finding: {} — {}", status, resp.text().await.unwrap_or_default());
	}
	Ok(())
}

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

	#[test]
	fn pem_b64_env_wins_over_file_path() {
		let file = std::env::temp_dir().join("loupectl-test-path-that-should-not-be-read.pem");
		let pem = "-----BEGIN CERTIFICATE-----\nfrom-env\n-----END CERTIFICATE-----\n";
		let pem_b64 = b64(pem);

		let got =
			pem_from_env_or_file("CA cert", &None, &Some(pem_b64), Some(&file), "missing").unwrap();
		assert_eq!(got, pem);
	}

	#[test]
	fn worker_register_out_conflicts_with_emit_env() {
		let err = Cli::try_parse_from([
			"loupectl",
			"--server-url",
			"https://loupe.example:8443",
			"worker",
			"register",
			"--name",
			"worker-1",
			"--out",
			"worker.json",
			"--emit-env",
		])
		.expect_err("clap should reject --out with --emit-env");
		assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
	}

	#[cfg(unix)]
	fn unique_temp_dir(prefix: &str) -> PathBuf {
		let suffix =
			std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
		let dir = std::env::temp_dir().join(format!("{prefix}-{}-{suffix}", std::process::id()));
		std::fs::create_dir(&dir).unwrap();
		dir
	}

	#[cfg(unix)]
	#[test]
	fn worker_bundle_file_is_owner_only() {
		use std::os::unix::fs::PermissionsExt;

		let dir = unique_temp_dir("loupectl-worker-bundle-perms");
		let path = dir.join("worker.json");

		write_secret_file(&path, b"{\"client_key_pem\":\"PRIVATE KEY\"}").unwrap();

		let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
		std::fs::remove_dir_all(&dir).unwrap();

		assert_eq!(
			mode, 0o600,
			"worker bundle persisted by --out must be owner-only, got mode {mode:o}",
		);
	}

	#[test]
	fn secret_file_refuses_to_overwrite_existing_path() {
		let suffix =
			std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
		let dir = std::env::temp_dir()
			.join(format!("loupectl-worker-bundle-overwrite-{}-{suffix}", std::process::id()));
		std::fs::create_dir(&dir).unwrap();
		let path = dir.join("worker.json");
		std::fs::write(&path, b"existing").unwrap();

		let err = write_secret_file(&path, b"replacement").expect_err("existing path is refused");
		let contents = std::fs::read(&path).unwrap();
		std::fs::remove_dir_all(&dir).unwrap();

		assert!(err.to_string().contains("creating secret file"), "unexpected error: {err}");
		assert_eq!(contents, b"existing");
	}

	#[test]
	fn repo_rotate_pat_parses_explicit_pat() {
		let cli = Cli::try_parse_from([
			"loupectl",
			"--server-url",
			"https://loupe.example:8443",
			"repo",
			"rotate-pat",
			"7",
			"--pat",
			"ghp_replacement",
		])
		.unwrap();
		let Cmd::Repo(RepoCmd::RotatePat(args)) = cli.cmd else {
			panic!("expected repo rotate-pat command");
		};
		assert_eq!(args.id, 7);
		assert_eq!(args.pat, "ghp_replacement");
	}

	#[test]
	fn repo_add_inherits_verification_default_unless_pinned() {
		let base = [
			"loupectl",
			"--server-url",
			"https://loupe.example:8443",
			"repo",
			"add",
			"--clone-url",
			"https://github.com/acme/widget.git",
			"--no-reporting",
		];

		let cli = Cli::try_parse_from(base).unwrap();
		let Cmd::Repo(RepoCmd::Add(args)) = cli.cmd else {
			panic!("expected repo add command");
		};
		assert!(!args.verification_enabled);
		assert!(!args.no_verification);

		let mut with_verify = base.to_vec();
		with_verify.push("--verification-enabled");
		let cli = Cli::try_parse_from(with_verify).unwrap();
		let Cmd::Repo(RepoCmd::Add(args)) = cli.cmd else {
			panic!("expected repo add command");
		};
		assert!(args.verification_enabled);
		assert!(!args.no_verification);

		let mut without_verify = base.to_vec();
		without_verify.push("--no-verification");
		let cli = Cli::try_parse_from(without_verify).unwrap();
		let Cmd::Repo(RepoCmd::Add(args)) = cli.cmd else {
			panic!("expected repo add command");
		};
		assert!(!args.verification_enabled);
		assert!(args.no_verification);
	}

	#[test]
	fn repo_set_github_reporting_parses_explicit_pat() {
		let cli = Cli::try_parse_from([
			"loupectl",
			"--server-url",
			"https://loupe.example:8443",
			"repo",
			"set-github-reporting",
			"7",
			"--target-owner",
			"acme",
			"--target-repo",
			"tracker",
			"--pat",
			"ghp_replacement",
		])
		.unwrap();
		let Cmd::Repo(RepoCmd::SetGithubReporting(args)) = cli.cmd else {
			panic!("expected repo set-github-reporting command");
		};
		assert_eq!(args.id, 7);
		assert_eq!(args.target_owner, "acme");
		assert_eq!(args.target_repo, "tracker");
		assert_eq!(args.pat, "ghp_replacement");
	}

	#[test]
	fn finding_retry_report_parses() {
		let cli = Cli::try_parse_from([
			"loupectl",
			"--server-url",
			"https://loupe.example:8443",
			"finding",
			"retry-report",
			"11",
		])
		.unwrap();
		let Cmd::Finding(FindingCmd::RetryReport { id }) = cli.cmd else {
			panic!("expected finding retry-report command");
		};
		assert_eq!(id, 11);
	}

	#[test]
	fn list_limits_parse() {
		let cli = Cli::try_parse_from([
			"loupectl",
			"--server-url",
			"https://loupe.example:8443",
			"repo",
			"list",
			"-n",
			"25",
		])
		.unwrap();
		let Cmd::Repo(RepoCmd::List(args)) = cli.cmd else {
			panic!("expected repo list command");
		};
		assert_eq!(args.limit, Some(25));

		let cli = Cli::try_parse_from([
			"loupectl",
			"--server-url",
			"https://loupe.example:8443",
			"job",
			"list",
			"-n",
			"25",
		])
		.unwrap();
		let Cmd::Job(JobCmd::List(args)) = cli.cmd else {
			panic!("expected job list command");
		};
		assert_eq!(args.limit, Some(25));

		let cli = Cli::try_parse_from([
			"loupectl",
			"--server-url",
			"https://loupe.example:8443",
			"finding",
			"list",
			"7",
			"-n",
			"250",
		])
		.unwrap();
		let Cmd::Finding(FindingCmd::List(args)) = cli.cmd else {
			panic!("expected finding list command");
		};
		assert_eq!(args.repo_id, 7);
		assert_eq!(args.limit, Some(250));
	}

	#[test]
	fn list_limits_must_be_positive() {
		let err = Cli::try_parse_from([
			"loupectl",
			"--server-url",
			"https://loupe.example:8443",
			"finding",
			"list",
			"7",
			"-n",
			"0",
		])
		.expect_err("zero limit must be rejected");
		assert!(err.to_string().contains("limit must be positive"));
	}

	#[test]
	fn finding_retry_verify_parses() {
		let cli = Cli::try_parse_from([
			"loupectl",
			"--server-url",
			"https://loupe.example:8443",
			"finding",
			"retry-verify",
			"--dry-run",
			"--include-inconclusive",
			"--repo-id",
			"7",
			"--limit",
			"50",
		])
		.unwrap();
		let Cmd::Finding(FindingCmd::RetryVerify(args)) = cli.cmd else {
			panic!("expected finding retry-verify command");
		};
		assert!(args.dry_run);
		assert!(args.include_inconclusive);
		assert_eq!(args.repo_id, Some(7));
		assert_eq!(args.limit, Some(50));
	}

	#[test]
	fn job_retry_parses() {
		let cli = Cli::try_parse_from([
			"loupectl",
			"--server-url",
			"https://loupe.example:8443",
			"job",
			"retry",
			"33",
		])
		.unwrap();
		let Cmd::Job(JobCmd::Retry { id }) = cli.cmd else {
			panic!("expected job retry command");
		};
		assert_eq!(id, 33);
	}

	#[test]
	fn job_cancel_parses() {
		let cli = Cli::try_parse_from([
			"loupectl",
			"--server-url",
			"https://loupe.example:8443",
			"job",
			"cancel",
			"34",
		])
		.unwrap();
		let Cmd::Job(JobCmd::Cancel { id }) = cli.cmd else {
			panic!("expected job cancel command");
		};
		assert_eq!(id, 34);
	}

	#[test]
	fn cert_mint_server_parses_without_server_url() {
		let cli = Cli::try_parse_from([
			"loupectl",
			"cert",
			"mint-server",
			"--hostname",
			"loupe.example.com",
			"--ca-cert-pem",
			"ca-cert",
			"--ca-key-pem",
			"ca-key",
		])
		.unwrap();
		let Cmd::Cert(CertCmd::MintServer(args)) = cli.cmd else {
			panic!("expected cert mint-server command");
		};
		assert_eq!(args.hostnames, vec!["loupe.example.com"]);
		assert!(cli.conn.server_url.is_none());
	}

	#[test]
	fn cert_mint_server_uses_existing_ca() {
		let ca = loupe_tls::Ca::new("loupe-test-ca").unwrap();
		let args = CertMintServerArgs {
			hostnames: vec!["loupe.example.com".into(), "loupe.internal".into()],
			common_name: "loupe-server".into(),
			emit_env: true,
			ca_cert: None,
			ca_cert_pem: Some(ca.cert_pem().to_owned()),
			ca_cert_pem_b64: None,
			ca_key: None,
			ca_key_pem: Some(ca.key_pem().to_owned()),
			ca_key_pem_b64: None,
		};

		let bundle = mint_server_cert(&args).unwrap();
		assert!(bundle.cert_pem.contains("BEGIN CERTIFICATE"));
		assert!(bundle.key_pem.contains("PRIVATE KEY"));
	}

	#[test]
	fn server_cert_env_assignments_are_single_line_and_decode_to_bundle() {
		let bundle = loupe_tls::CertBundle {
			cert_pem: "server\ncert\n".into(),
			key_pem: "server\nkey\n".into(),
		};

		let assignments = server_cert_env_assignments(&bundle);
		let names: Vec<_> = assignments.iter().map(|(name, _)| *name).collect();
		assert_eq!(names, vec!["LOUPE_SERVER_CERT_PEM_B64", "LOUPE_SERVER_KEY_PEM_B64"]);
		for (name, value) in &assignments {
			assert!(!value.is_empty(), "{name} value must be present");
			assert!(!value.contains('\n'), "{name} value must fit dotenv/env-file syntax");
		}

		use base64::Engine as _;
		let decoded_cert =
			base64::engine::general_purpose::STANDARD.decode(&assignments[0].1).unwrap();
		assert_eq!(String::from_utf8(decoded_cert).unwrap(), bundle.cert_pem);
		let decoded_key =
			base64::engine::general_purpose::STANDARD.decode(&assignments[1].1).unwrap();
		assert_eq!(String::from_utf8(decoded_key).unwrap(), bundle.key_pem);
	}

	#[test]
	fn worker_env_assignments_are_single_line_and_decode_to_bundle() {
		let base = reqwest::Url::parse("https://loupe.example:8443/").unwrap();
		let bundle = RegisterWorkerResponse {
			protocol_version: PROTOCOL_VERSION,
			worker_id: 42,
			ca_cert_pem: "ca\ncert\n".into(),
			client_cert_pem: "worker\ncert\n".into(),
			client_key_pem: "worker\nkey\n".into(),
		};

		let assignments = worker_env_assignments(&base, &bundle);
		let names: Vec<_> = assignments.iter().map(|(name, _)| *name).collect();
		assert_eq!(
			names,
			vec![
				"LOUPE_SERVER_URL",
				"LOUPE_WORKER_CA_CERT_PEM_B64",
				"LOUPE_WORKER_CERT_PEM_B64",
				"LOUPE_WORKER_KEY_PEM_B64",
			]
		);
		for (name, value) in &assignments {
			assert!(!value.is_empty(), "{name} value must be present");
			assert!(!value.contains('\n'), "{name} value must fit dotenv/env-file syntax");
		}

		use base64::Engine as _;
		let decoded_ca =
			base64::engine::general_purpose::STANDARD.decode(&assignments[1].1).unwrap();
		assert_eq!(String::from_utf8(decoded_ca).unwrap(), bundle.ca_cert_pem);
	}
}