runner-manager-github 0.4.7

Device flow and typed GitHub REST adapters (inventory, demand, JIT) for runner-manager.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
// owner: c4-demand-and-jit-gateway

//! Just-in-time runner registration: the one call in this product that returns
//! a secret.
//!
//! ```text
//! POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig
//! POST /orgs/{org}/actions/runners/generate-jitconfig
//! body { name, runner_group_id, labels, work_folder }
//!   -> 201 { runner { … }, encoded_jit_config }
//! ```
//!
//! Two scopes, one request shape, one response shape, and — after D4 — one
//! credential. The Actions-service credential chain and message protocol this
//! replaces were disproved by `d17-user-to-server-scale-set-chain.md`; what is
//! here instead is documented, stable REST against a host and a token that
//! already exist.
//!
//! # What the live spikes settled, and what each one costs to get wrong
//!
//! `v1` (`docs/spikes/d18-org-jit-verification.md`) drove both scopes against
//! live GitHub. Four of its findings are load-bearing here rather than
//! interesting:
//!
//! 1. **`runner_group_id` is mandatory.** Omitting it answers `422 Invalid
//!    input: object is missing required key: runner_group_id`. There is no
//!    server-side default, so [`JitRunnerRequest`] takes it as a required `u64`
//!    rather than an `Option` — a field that cannot be omitted cannot be
//!    forgotten.
//! 2. **An unusable group answers `403` *or* `404`, depending on why.** Group
//!    `2` — the GitHub-hosted group — answered `403`; group `99999` answered
//!    `404`. Error handling keyed on `404` alone misreports the first case as "no
//!    such group" when the truth is "not yours to administer", so
//!    [`JitError::Forbidden`] and [`JitError::NotFound`] are separate outcomes
//!    and **both** name the runner group.
//! 3. **`1` is not special.** A non-default group id (`3`) also returned `201`.
//!    Nothing here may hard-code `1`.
//! 4. **No labels are added implicitly, and labels are stored lower-cased.** The
//!    `201` carries exactly the labels requested — no `self-hosted`, no OS, no
//!    architecture — so `runs-on: self-hosted` does **not** match a runner
//!    registered without that label. `b1`'s
//!    [`runner_manager_domain::policy::RoutingLabels::as_registration_labels`]
//!    is the array this module sends, and [`runner_manager_domain::model::Label`]
//!    lower-cases on construction, which is what keeps the labels this product
//!    asks for and the labels GitHub stores the same strings.
//!
//! # The encoded configuration is the one short-lived secret in the product
//!
//! `07-security.md`'s credential inventory lists exactly two sensitive values
//! after D4: the persisted user access token, and this. It is returned in
//! [`EncodedJitConfig`], whose `Debug` and `Display` redact, which does not
//! implement [`serde::Serialize`], and which zeroises its buffer on drop.
//!
//! **This crate never writes it to disk and never puts it in an error message.**
//! Every [`JitError`] is built from the *request* — target, runner group, name —
//! and from GitHub's own `message`, never from a response body. The restrictive
//! handoff to the runner process is `d1`'s primitive and `e3`'s job; the rule
//! here is only that nothing leaves this module carrying the blob except
//! [`JitRegistration`].
//!
//! ## What the wrapper does not cover, stated rather than implied
//!
//! [`crate::ApiResponse`] buffers the whole response body, so the encoded
//! configuration also exists as bytes in that buffer until the response is
//! dropped at the end of [`RestJit::generate_jit_config`]. That buffer is `c2`'s
//! and is not zeroised. The intermediate `String` serde produces **is**
//! zeroised here explicitly, immediately after the value is copied into the
//! wrapper, because that one is this module's to scrub.
//!
//! The residual exposure is therefore one heap buffer, for the duration of one
//! call, in a process that already holds the user access token. It is recorded
//! rather than papered over: claiming the blob exists in exactly one place would
//! be false, and a false claim is worse than a bounded one.
//!
//! # There is no job reservation, and this call is not one
//!
//! A JIT configuration registers a runner; it does **not** claim a job. The
//! scale-set model's `AcquireJobs` has no REST equivalent, so another host may
//! take the job this runner was started for
//! (`01-current-architecture.md`, edge case 6). The runner then receives nothing
//! and exits on its idle timeout — the surplus-runner path, which is an
//! accepted, bounded cost with a test of its own (`h1` scenario 8).
//!
//! **Do not add a claim, a lease, or a local reservation table here to
//! compensate**, and do not read this call as one.
//! `demand::tests::nothing_in_this_crate_reserves_or_claims_a_job` makes that
//! executable across the whole crate.

use std::{
    fmt,
    sync::{
        Arc,
        atomic::{AtomicU64, Ordering},
    },
};

use runner_manager_domain::{model::ScaleTarget, policy::RoutingLabels};
use secrecy::{ExposeSecret, ExposeSecretMut, SecretString, zeroize::Zeroize};
use serde::{Deserialize, Serialize};

use crate::{
    ApiRequest, AuthenticatedClient, GithubError,
    rest::{CancelToken, InventoryError, RateLimited},
};

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// The runner's working directory, relative to its installation root.
///
/// `_work` is the GitHub runner's own default and the value `v1` registered
/// with. It is a constant rather than an inline literal because `e3` creates the
/// directory this names and `e2` lays the runner package out around it: three
/// tasks agreeing on a path is a shared fact, not a repeated string.
pub const DEFAULT_WORK_FOLDER: &str = "_work";

/// The endpoint suffix both scopes share.
pub const JITCONFIG_PATH: &str = "/actions/runners/generate-jitconfig";

/// What GitHub answers a successful registration with.
///
/// Named because `201` rather than `200` is a fact about this endpoint that a
/// reader should not have to re-derive, and because
/// [`RestJit::generate_jit_config`] says so in a log line when the answer is
/// anything else. It is **not** a gate: a different success status is reported
/// and then decoded anyway, because the body is what this module needs and a
/// `200` would carry the same one.
pub const CREATED: u16 = 201;

// ---------------------------------------------------------------------------
// The request
// ---------------------------------------------------------------------------

/// One `generate-jitconfig` request, before a scope is chosen.
///
/// The same value registers at repository scope or organization scope: `v1`
/// established that the two forms take the identical body and answer with the
/// identical shape, so the scope is a [`ScaleTarget`] passed to
/// [`JitGateway::generate_jit_config`] rather than a property of the request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JitRunnerRequest {
    name: String,
    runner_group_id: u64,
    labels: Vec<String>,
    work_folder: String,
}

impl JitRunnerRequest {
    /// A registration for `name` in `runner_group_id`, carrying `labels`.
    ///
    /// `runner_group_id` is a required argument and not an `Option` on purpose:
    /// `v1` proved there is no server-side default and that omitting the field
    /// is a `422`, so the only way to send a request without one is not to be
    /// able to build it.
    ///
    /// # An empty label set is not rejected here
    ///
    /// GitHub answers `labels: []` with `422 Invalid property /labels: 1 item
    /// required; only 0 were supplied`, and that message is more useful to an
    /// operator than anything this constructor could say — it names the property
    /// and the requirement. The ordinary path cannot produce one anyway:
    /// [`Self::for_policy`] takes a [`RoutingLabels`], which is non-empty by
    /// construction because its host label has no removal path.
    #[must_use]
    pub fn new(
        name: impl Into<String>,
        runner_group_id: u64,
        labels: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        Self {
            name: name.into(),
            runner_group_id,
            labels: labels.into_iter().map(Into::into).collect(),
            work_folder: DEFAULT_WORK_FOLDER.to_string(),
        }
    }

    /// A registration carrying exactly the policy's routing labels.
    ///
    /// This is the constructor the product uses.
    /// [`RoutingLabels::as_registration_labels`] is documented as "`c4` sends
    /// exactly this", and exactly is the operative word: `v1` established that
    /// **no labels are added implicitly**, so a label the operator expects to be
    /// matchable has to be in this array or it does not exist on the runner.
    #[must_use]
    pub fn for_policy(
        name: impl Into<String>,
        runner_group_id: u64,
        labels: &RoutingLabels,
    ) -> Self {
        Self::new(name, runner_group_id, labels.as_registration_labels())
    }

    /// Override the runner's working directory.
    #[must_use]
    pub fn with_work_folder(mut self, work_folder: impl Into<String>) -> Self {
        self.work_folder = work_folder.into();
        self
    }

    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    #[must_use]
    pub const fn runner_group_id(&self) -> u64 {
        self.runner_group_id
    }

    #[must_use]
    pub fn labels(&self) -> &[String] {
        &self.labels
    }

    #[must_use]
    pub fn work_folder(&self) -> &str {
        &self.work_folder
    }

    fn body(&self) -> JitRequestBody<'_> {
        JitRequestBody {
            name: &self.name,
            runner_group_id: self.runner_group_id,
            labels: &self.labels,
            work_folder: &self.work_folder,
        }
    }
}

/// The wire body, and nothing else.
///
/// A separate type from [`JitRunnerRequest`] so that the four documented keys
/// are the whole of what is serialised. Adding an accessor, a builder field or a
/// derived trait to the public type cannot change what goes on the wire, which
/// is the property `the_request_body_is_exactly_the_four_documented_keys` pins.
///
/// No `skip_serializing_if` anywhere: `runner_group_id` is required, and an
/// attribute that could ever omit it would reintroduce the one `422` `v1` went
/// and measured.
#[derive(Debug, Serialize)]
struct JitRequestBody<'a> {
    name: &'a str,
    runner_group_id: u64,
    labels: &'a [String],
    work_folder: &'a str,
}

// ---------------------------------------------------------------------------
// The secret
// ---------------------------------------------------------------------------

/// The encoded just-in-time configuration: a short-lived credential.
///
/// `07-security.md`, credential inventory: "Restrictive temporary handoff only.
/// Delete immediately after launch; never persist." This type is what makes the
/// first half enforceable at the type level rather than by everyone remembering:
///
/// * **`Debug` and `Display` redact.** Both are hand-written. A `#[derive(Debug)]`
///   added later to a struct with a plain `String` field is precisely how this
///   control is lost, which is why `lib.rs`'s crate documentation states the rule
///   and why `tests/no_jit_config_reaches_the_logs.rs` plants that exact mistake
///   as a positive control.
/// * **It does not serialise.** There is no [`serde::Serialize`] impl, so it
///   cannot be written into a config file, a SQLite row, a `status --json`
///   payload or a structured log field by any code that compiles. The doctest
///   below is the executable form of that claim.
/// * **It zeroises on drop.** [`Drop`] calls `Self::scrub`, which zeroes the
///   buffer through `zeroize`. `secrecy`'s [`SecretString`] also zeroises on its
///   own drop; the explicit scrub is what makes the property *testable* rather
///   than a statement about a dependency.
/// * **It is not [`Clone`].** A clone of a secret is a second copy with its own
///   lifetime, and this value's whole security property is a short one.
///
/// The error code is pinned, and that is the whole value of the doctest. A bare
/// `compile_fail` passes when the snippet fails to compile for *any* reason — a
/// typo, a renamed type, a missing import — so it would keep passing after
/// someone added a `Serialize` derive and broke something else in the same
/// edit. `E0277` is "the trait bound is not satisfied", which is the one reason
/// this claim is about.
///
/// ```compile_fail,E0277
/// # use runner_manager_github::jit::EncodedJitConfig;
/// fn is_serialisable<T: serde::Serialize>(_: &T) {}
/// let config = EncodedJitConfig::new("not-a-real-jit-configuration");
/// // The JIT configuration must never reach a config file, a database row, a
/// // `--json` payload or a structured log field. This must not compile.
/// is_serialisable(&config);
/// ```
pub struct EncodedJitConfig(SecretString);

impl EncodedJitConfig {
    #[must_use]
    pub fn new(raw: impl Into<String>) -> Self {
        Self(SecretString::from(raw.into()))
    }

    /// The configuration itself, for the one caller that hands it to a runner
    /// process.
    ///
    /// Named `expose` rather than `as_str` so that every use site says out loud
    /// what it is doing, and so that `grep expose_jit` finds all of them.
    #[must_use]
    pub fn expose(&self) -> &str {
        self.0.expose_secret()
    }

    /// Length in bytes, which is safe to log and useful for diagnosing a
    /// truncated handoff. `v1` observed 4,088 characters at organization scope.
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.expose_secret().len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Overwrite the buffer with zeroes.
    ///
    /// Exactly what [`Drop`] calls, and `pub(crate)` rather than private so that
    /// a test can invoke the *same* call and observe the result. Observing the
    /// buffer after the drop itself is not possible without reading freed
    /// memory, which is undefined behaviour; this is the strongest sound
    /// alternative, and the gap it leaves — that `drop` calls `scrub` — is one
    /// line directly below.
    pub(crate) fn scrub(&mut self) {
        self.0.expose_secret_mut().zeroize();
    }
}

impl Drop for EncodedJitConfig {
    fn drop(&mut self) {
        self.scrub();
    }
}

/// What `Debug` and `Display` render instead of the configuration.
const REDACTED: &str = "[REDACTED JIT CONFIGURATION]";

impl fmt::Debug for EncodedJitConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // The length is rendered and the value is not: a diagnostic that says
        // "0 bytes" is what distinguishes a truncated handoff from a redacted
        // one, and neither is the secret.
        f.debug_tuple("EncodedJitConfig")
            .field(&REDACTED)
            .field(&format_args!("{} bytes", self.len()))
            .finish()
    }
}

impl fmt::Display for EncodedJitConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(REDACTED)
    }
}

// ---------------------------------------------------------------------------
// The response
// ---------------------------------------------------------------------------

/// The runner GitHub registered, as it described it in the `201`.
///
/// Distinct from [`crate::rest::Runner`], which is what the *inventory* endpoint
/// reports, and deliberately so: this one carries `runner_group_id`, which the
/// inventory shape has no field for and which is the value an operator needs
/// when a later registration is refused for the group.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JitRunner {
    pub id: u64,
    pub name: String,
    pub os: String,
    pub status: String,
    pub busy: bool,
    /// Optional in the wire schema. `v1` observed it present at both scopes; it
    /// stays optional because a missing field is not a reason to fail a
    /// registration that GitHub already accepted.
    pub runner_group_id: Option<u64>,
    /// The labels GitHub actually stored, **lower-cased** — see the module
    /// documentation. Comparing these against what was requested is how a caller
    /// learns that no labels were added implicitly.
    pub labels: Vec<String>,
}

/// A registered runner and the configuration that starts it.
///
/// `Debug` is hand-written. The configuration's own `Debug` already redacts, so
/// a derive would be safe *today*; it is written out because the field it is
/// protecting is a secret and the crate's stated rule is that such types do not
/// rely on a derive staying correct across an edit nobody reviews.
pub struct JitRegistration {
    config: EncodedJitConfig,
    runner: JitRunner,
}

impl JitRegistration {
    #[must_use]
    pub fn new(config: EncodedJitConfig, runner: JitRunner) -> Self {
        Self { config, runner }
    }

    #[must_use]
    pub fn config(&self) -> &EncodedJitConfig {
        &self.config
    }

    /// Take the configuration, leaving the runner reference behind.
    ///
    /// The handoff in `e3` wants the secret and the diagnostics separately, and
    /// moving it out rather than cloning is what keeps there being one copy.
    #[must_use]
    pub fn into_config(self) -> EncodedJitConfig {
        self.config
    }

    #[must_use]
    pub fn runner(&self) -> &JitRunner {
        &self.runner
    }
}

impl fmt::Debug for JitRegistration {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("JitRegistration")
            .field("runner", &self.runner)
            .field("config", &REDACTED)
            .finish()
    }
}

// ---------------------------------------------------------------------------
// Failures
// ---------------------------------------------------------------------------

/// Everything a just-in-time registration can fail with.
///
/// The three GitHub answers `c4`'s specification names are **distinct outcomes,
/// not one error**, because an operator's next action differs for each and a
/// caller's does too: `403` is terminal and needs a permissions or runner-group
/// change, `404` means the target or the group is not there, and `422` means the
/// request itself was rejected.
///
/// # None of these carries the encoded configuration
///
/// Every variant is built from the request — target, runner group, name — and
/// from GitHub's own `message` field. A failing response has no
/// `encoded_jit_config` to leak, and a `201` that fails to *decode* is reported
/// through [`GithubError::Decode`], which carries a `serde_json::Error` and not
/// the body. `an_error_never_carries_the_encoded_configuration` pins it.
#[derive(Debug, thiserror::Error)]
pub enum JitError {
    /// GitHub refused: the permission or the runner group does not allow it.
    ///
    /// **Terminal.** Nothing retries this, and nothing may: `d17` is the record
    /// of what a `403` on this family of endpoints means and what it does not.
    #[error(
        "GitHub refused just-in-time runner registration for {target} in runner group \
         {runner_group_id}{}. This is terminal — retrying will not change it. Check that the \
         App installation grants `Administration: Read and write` for a repository target or \
         `Self-hosted runners: Read and write` for an organization target, and that runner \
         group {runner_group_id} is one this installation may administer; a GitHub-hosted \
         runner group answers 403 and cannot be used",
        message.as_deref().map(|m| format!(" ({m})")).unwrap_or_default()
    )]
    Forbidden {
        target: String,
        runner_group_id: u64,
        message: Option<String>,
    },

    /// GitHub found neither the target nor the runner group.
    ///
    /// Separate from [`JitError::Forbidden`] because `v1` measured both answers
    /// from the same mistake: a group that does not exist is `404`, a group that
    /// exists but is not administrable is `403`. Collapsing them tells an
    /// operator to create a group that is already there.
    #[error(
        "GitHub could not find the just-in-time registration target {target} or runner group \
         {runner_group_id}{}. Check the target name, and that runner group \
         {runner_group_id} exists — a group id that does not exist answers 404, while one \
         that exists but cannot be administered answers 403",
        message.as_deref().map(|m| format!(" ({m})")).unwrap_or_default()
    )]
    NotFound {
        target: String,
        runner_group_id: u64,
        message: Option<String>,
    },

    /// GitHub rejected the request body: the name or the label set.
    #[error(
        "GitHub rejected the just-in-time runner registration for {target}{}. The runner name \
         or the label set is not acceptable: `labels` must hold at least one item and \
         `runner_group_id` is required",
        message.as_deref().map(|m| format!(" ({m})")).unwrap_or_default()
    )]
    Rejected {
        target: String,
        message: Option<String>,
    },

    /// GitHub is rate limiting this credential. Resolves by waiting, and is the
    /// one failure here that is not about the request.
    #[error("{0}")]
    RateLimited(RateLimited),

    /// The caller withdrew the registration before it completed.
    #[error("the just-in-time runner registration was cancelled before it completed")]
    Cancelled,

    #[error(transparent)]
    Github(#[from] GithubError),
}

impl JitError {
    /// Whether retrying this exact request could ever produce a different
    /// answer.
    ///
    /// `403`, `404` and `422` are all `true` here, and a `403` **must** be:
    /// `c4`'s specification says "a `403` must never become a retry loop", and
    /// `d17` is the record of a design that spent a spike discovering what a
    /// `403` on this family of endpoints means. A rejected credential is
    /// terminal too — it resolves by an interactive `auth login`, not by
    /// retrying.
    ///
    /// # Why an undecodable answer is terminal, and why it is the expensive one
    ///
    /// A body this client cannot parse will not parse on the next attempt, so
    /// the answer to the question in the first line is plainly no. What makes
    /// it worth spelling out is the cost of getting it wrong here rather than
    /// anywhere else: `generate-jitconfig` answers `201` by **completing a
    /// registration**, and the decode happens after that. A caller that read
    /// this as retryable would issue a second registration, and a third, each
    /// one a real runner created at GitHub whose one-shot configuration this
    /// process then discards — a target silently accumulating registered
    /// runners that never come online. So [`GithubError::Decode`] and
    /// [`GithubError::Malformed`] are terminal, and
    /// [`JitError::operator_action`] answers for both rather than leaving the
    /// failure silent.
    ///
    /// # Why [`GithubError::Forbidden`] and a `404` under `Github` are not
    ///
    /// Both are reachable through the transparent `#[from]` without passing
    /// `RestJit::classify`, and both would be terminal if they had. They stay
    /// as they are because answering them here means keeping a second
    /// status-code table beside `classify`'s, and the two would drift. For the
    /// `403` it is worse than untidy: GitHub answers a secondary rate limit
    /// with a `403`, `classify` runs [`RateLimited::detect`] *first* for
    /// exactly that reason, and a predicate that called the raw variant
    /// terminal without repeating that detection would turn the one 403 that
    /// resolves by waiting into a permanent failure. An unclassified failure
    /// reported as retryable costs a wasted request; an unclassified rate limit
    /// reported as terminal costs the registration. The fix for those two is to
    /// route them through `classify`, which every path inside this crate
    /// already does.
    #[must_use]
    pub fn is_terminal(&self) -> bool {
        match self {
            Self::Forbidden { .. } | Self::NotFound { .. } | Self::Rejected { .. } => true,
            // The rejected credential, and an answer this client cannot read.
            // An authentication *lockout* is not terminal — it is the one 403
            // that resolves by waiting — and a transport failure resolves when
            // the network does.
            Self::Github(error) => matches!(
                error,
                GithubError::AuthenticationFailed
                    | GithubError::Decode { .. }
                    | GithubError::Malformed { .. }
            ),
            Self::RateLimited(_) | Self::Cancelled => false,
        }
    }

    /// The rate limit behind this failure, when there is one.
    #[must_use]
    pub fn rate_limited(&self) -> Option<&RateLimited> {
        match self {
            Self::RateLimited(limit) => Some(limit),
            _ => None,
        }
    }

    #[must_use]
    pub fn is_cancelled(&self) -> bool {
        matches!(self, Self::Cancelled)
    }

    /// What an operator can actually do about this, or `None` when there is
    /// nothing for them to do.
    ///
    /// Every terminal outcome has one, which is what "terminal and
    /// operator-actionable" means: a failure a human cannot act on and a
    /// program will not retry is a dead end. `None` is correct for a rate limit
    /// and a cancellation — both resolve without anyone doing anything.
    #[must_use]
    pub fn operator_action(&self) -> Option<String> {
        match self {
            Self::Forbidden {
                target,
                runner_group_id,
                ..
            } => Some(format!(
                "Grant the App installation `Administration: Read and write` on {target} (or \
                 `Self-hosted runners: Read and write` for an organization), and use a runner \
                 group this installation may administer — runner group {runner_group_id} \
                 answered 403, which a GitHub-hosted group always does."
            )),
            Self::NotFound {
                target,
                runner_group_id,
                ..
            } => Some(format!(
                "Check that {target} is spelled correctly and still exists, and that runner \
                 group {runner_group_id} exists in it."
            )),
            Self::Rejected { target, .. } => Some(format!(
                "Correct the runner name or the routing labels for {target}: the label set \
                 must hold at least one label."
            )),
            Self::Github(GithubError::AuthenticationFailed) => {
                Some("Run `runner-manager auth login` to sign in again.".to_string())
            }
            // Deliberately says nothing about the body it could not read. The
            // undecodable answer is a `201`, so the body it is holding is a real
            // encoded configuration, and this string is rendered wherever the
            // error is; the module's redaction rule binds the remedy as tightly
            // as the failure.
            Self::Github(GithubError::Decode { .. } | GithubError::Malformed { .. }) => Some(
                "Do not retry this registration: GitHub's answer could not be read, and \
                 `generate-jitconfig` answers 201 by creating the runner — so each further \
                 attempt can leave another registered runner that never comes online. \
                 Check the target's self-hosted runner list for offline runners matching \
                 this name and remove them, then report the response shape: this means \
                 GitHub's payload changed or the request body could not be built."
                    .to_string(),
            ),
            _ => None,
        }
    }
}

// ---------------------------------------------------------------------------
// The gateway
// ---------------------------------------------------------------------------

/// Just-in-time runner registration.
///
/// A trait for [`crate::rest::InventoryGateway`]'s reason: `e3`'s launch path is
/// tested against `runner_manager_testkit::github::FakeGithub`, with no network
/// and no `wiremock` in its dependency graph. [`RestJit`] is the one
/// implementation that talks to GitHub.
#[async_trait::async_trait]
pub trait JitGateway: fmt::Debug + Send + Sync {
    /// Register one ephemeral runner and return its configuration.
    ///
    /// # Errors
    /// Every variant of [`JitError`].
    async fn generate_jit_config(
        &self,
        target: &ScaleTarget,
        request: &JitRunnerRequest,
        cancel: &CancelToken,
    ) -> Result<JitRegistration, JitError>;
}

/// [`JitGateway`] over `api.github.com`.
///
/// Holds no credential of its own: authentication is entirely
/// [`AuthenticatedClient`]'s, and this type only ever hands it an
/// [`ApiRequest`] — whose `Debug` renders the body as `[REDACTED JSON]`, which
/// matters here because this is the one place in the crate that posts one.
pub struct RestJit {
    client: Arc<AuthenticatedClient>,
    requests_issued: AtomicU64,
}

impl fmt::Debug for RestJit {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RestJit")
            .field(
                "requests_issued",
                &self.requests_issued.load(Ordering::Relaxed),
            )
            .finish_non_exhaustive()
    }
}

impl RestJit {
    #[must_use]
    pub fn new(client: Arc<AuthenticatedClient>) -> Self {
        Self {
            client,
            requests_issued: AtomicU64::new(0),
        }
    }

    /// How many HTTP requests this gateway has issued.
    ///
    /// This is how "no code path retries a `403`" is asserted rather than
    /// asserted about: one refused registration must leave this at one.
    #[must_use]
    pub fn requests_issued(&self) -> u64 {
        self.requests_issued.load(Ordering::SeqCst)
    }

    /// The `generate-jitconfig` path for either scope.
    ///
    /// One function rather than a branch at each call site, because `v1`'s whole
    /// organization finding is that the two differ in nothing but this string.
    #[must_use]
    pub fn path(target: &ScaleTarget) -> String {
        match target {
            ScaleTarget::Repository(repo) => {
                format!("/repos/{}/{}{JITCONFIG_PATH}", repo.owner(), repo.repo())
            }
            ScaleTarget::Organization(org) => {
                format!("/orgs/{}{JITCONFIG_PATH}", org.as_str())
            }
        }
    }

    /// Map a failure onto the outcome a caller branches on.
    ///
    /// Order matters. [`RateLimited::detect`] runs first because GitHub answers
    /// a secondary rate limit with a `403`, and reporting that as a permissions
    /// refusal would tell an operator to change a permission that is already
    /// correct. `c3` owns that decision procedure and this consumes it rather
    /// than writing a second one.
    fn classify(error: GithubError, target: &ScaleTarget, runner_group_id: u64) -> JitError {
        if let Some(limit) = RateLimited::detect(&error) {
            return JitError::RateLimited(limit);
        }
        let target = target.slug();
        match &error {
            GithubError::Forbidden { message, .. } => JitError::Forbidden {
                target,
                runner_group_id,
                message: message.clone(),
            },
            GithubError::Status {
                status: 404,
                message,
                ..
            } => JitError::NotFound {
                target,
                runner_group_id,
                message: message.clone(),
            },
            GithubError::Status {
                status: 422,
                message,
                ..
            } => JitError::Rejected {
                target,
                message: message.clone(),
            },
            _ => JitError::Github(error),
        }
    }

    fn from_inventory(
        error: InventoryError,
        target: &ScaleTarget,
        runner_group_id: u64,
    ) -> JitError {
        match error {
            InventoryError::Cancelled => JitError::Cancelled,
            InventoryError::RateLimited(limit) => JitError::RateLimited(limit),
            InventoryError::Github(error) => Self::classify(error, target, runner_group_id),
        }
    }
}

#[async_trait::async_trait]
impl JitGateway for RestJit {
    async fn generate_jit_config(
        &self,
        target: &ScaleTarget,
        request: &JitRunnerRequest,
        cancel: &CancelToken,
    ) -> Result<JitRegistration, JitError> {
        let group = request.runner_group_id();
        let api_request = ApiRequest::post_json(Self::path(target), &request.body())
            .map_err(|error| Self::classify(error, target, group))?;

        // `CancelToken` is `c3`'s, and reusing it rather than inventing a second
        // cancellation type is what lets `e1` hold one token across a refresh
        // and the registration it decides on.
        let response = cancel
            .run(async {
                // Counted inside the future for `c3`'s reason: `run`'s biased
                // `select!` answers `Cancelled` without polling this block when
                // the token is already flipped, so no socket is opened and the
                // count stays a count of requests actually attempted.
                self.requests_issued.fetch_add(1, Ordering::SeqCst);
                self.client
                    .send(&api_request)
                    .await
                    .map_err(InventoryError::from)
            })
            .await
            .map_err(|error| Self::from_inventory(error, target, group))?;

        // A `warn!` and not a `debug_assert!`, and the difference is deliberate.
        // `c3`'s `total_count` tripwire asserts because the number it guards is
        // read *off* the field it doubts; this status is guarding nothing — the
        // body is what matters, and a `200` would decode identically. An assert
        // here would panic a debug build, and so kill a developer's agent, over
        // a status code that changed nothing. The unexpected status is still
        // worth saying out loud, because it would mean GitHub or
        // `AuthenticatedClient::send` changed underneath this module.
        if response.status().as_u16() != CREATED {
            tracing::warn!(
                status = response.status().as_u16(),
                expected = CREATED,
                "`generate-jitconfig` answered a success status other than 201; the \
                 registration is still decoded, but this endpoint has always answered 201"
            );
        }

        let decoded: JitResponse = response.json().map_err(JitError::Github)?;
        // Copied into the wrapper, then the intermediate scrubbed. serde owns
        // this `String`, so it is the one copy of the secret this module can
        // actually reach; the response buffer behind it is `c2`'s and is
        // documented as the residual exposure at the top of this file.
        let mut raw = decoded.encoded_jit_config;
        let config = EncodedJitConfig::new(raw.as_str());
        raw.zeroize();

        tracing::debug!(
            target = %target,
            runner_id = decoded.runner.id,
            runner_name = %decoded.runner.name,
            runner_group_id = decoded.runner.runner_group_id,
            config_bytes = config.len(),
            "registered a just-in-time runner"
        );

        Ok(JitRegistration::new(
            config,
            JitRunner {
                id: decoded.runner.id,
                name: decoded.runner.name,
                os: decoded.runner.os,
                status: decoded.runner.status,
                busy: decoded.runner.busy,
                runner_group_id: decoded.runner.runner_group_id,
                labels: decoded
                    .runner
                    .labels
                    .into_iter()
                    .map(|label| label.name)
                    .collect(),
            },
        ))
    }
}

// ---------------------------------------------------------------------------
// Wire shapes
// ---------------------------------------------------------------------------

/// The `201` body. `v1`: "top-level keys: `runner`, `encoded_jit_config` —
/// exactly two", and "the response shape is **identical to the repository
/// form**", which is why one type serves both scopes.
#[derive(Debug, Deserialize)]
struct JitResponse {
    encoded_jit_config: String,
    runner: RawJitRunner,
}

#[derive(Debug, Deserialize)]
struct RawJitRunner {
    id: u64,
    #[serde(default)]
    name: String,
    #[serde(default)]
    os: String,
    #[serde(default)]
    status: String,
    #[serde(default)]
    busy: bool,
    runner_group_id: Option<u64>,
    #[serde(default)]
    labels: Vec<RawJitLabel>,
}

#[derive(Debug, Deserialize)]
struct RawJitLabel {
    name: String,
}

// Inline for the reason `rest.rs` records: `lib.rs`'s
// `the_confidential_credential_scan_covers_every_source_file` requires every
// `.rs` file under `src/` to appear in a list `c2` owns, so a second file here
// could only be added by editing another task's file.
#[cfg(test)]
mod tests {
    use super::*;
    use crate::testing::{FIXTURE_TOKEN, TestClock};
    use crate::{Endpoints, UserAccessToken};
    use runner_manager_domain::model::{Arch, HostLabel, Os};
    use serde_json::{Value, json};
    use wiremock::{
        Mock, MockServer, ResponseTemplate,
        matchers::{body_json, method, path},
    };

    /// Shaped like a real encoded configuration — base64url of a JSON envelope —
    /// and unmistakably not one. Long enough that a truncating leak still
    /// contains a recognisable prefix.
    const FIXTURE_JIT_CONFIG: &str = concat!(
        "eyJmaXh0dXJlIjoibm90LWEtcmVhbC1qaXQtY29uZmlndXJhdGlvbiIsIm5vdGUiOiJpZi",
        "B0aGlzIHN0cmluZyBhcHBlYXJzIGluIGEgbG9nIHRoZSByZWRhY3Rpb24gZmFpbGVkIn0"
    );

    fn repo_target() -> ScaleTarget {
        ScaleTarget::repository("octo/dashboard").expect("a valid owner/repo")
    }

    fn org_target() -> ScaleTarget {
        ScaleTarget::organization("octo-org").expect("a valid organization login")
    }

    /// Both scopes, so that every test written over this list runs against each
    /// one. `v1`'s finding is that the two differ in nothing but the path, and
    /// a list is how that stops being a claim.
    fn both_scopes() -> Vec<ScaleTarget> {
        vec![repo_target(), org_target()]
    }

    fn gateway(server: &MockServer) -> RestJit {
        let client = AuthenticatedClient::new(
            Endpoints::for_test_server(&server.uri()).expect("a valid test base"),
            UserAccessToken::new(SecretString::from(FIXTURE_TOKEN)),
            Arc::new(TestClock::default()),
        )
        .expect("the HTTP client builds");
        RestJit::new(Arc::new(client))
    }

    fn request() -> JitRunnerRequest {
        JitRunnerRequest::new(
            "rm-home-win-x64-0001",
            3,
            ["rm-home-win-x64", "self-hosted"],
        )
    }

    /// The `201` body, in the shape `v1` read back from live GitHub.
    fn created_body(labels: &[&str]) -> Value {
        json!({
            "runner": {
                "id": 73,
                "name": "rm-home-win-x64-0001",
                "os": "windows",
                "status": "offline",
                "busy": false,
                "runner_group_id": 3,
                "labels": labels
                    .iter()
                    .map(|name| json!({ "id": 1, "name": name, "type": "read-only" }))
                    .collect::<Vec<_>>()
            },
            "encoded_jit_config": FIXTURE_JIT_CONFIG
        })
    }

    async fn mount_created(server: &MockServer, target: &ScaleTarget, body: Value) {
        Mock::given(method("POST"))
            .and(path(RestJit::path(target)))
            .respond_with(ResponseTemplate::new(201).set_body_json(body))
            .mount(server)
            .await;
    }

    async fn mount_failure(server: &MockServer, target: &ScaleTarget, status: u16, message: &str) {
        Mock::given(method("POST"))
            .and(path(RestJit::path(target)))
            .respond_with(
                ResponseTemplate::new(status).set_body_json(json!({ "message": message })),
            )
            .mount(server)
            .await;
    }

    // -- the happy path, at both scopes under one body ----------------------

    /// The documented body shape goes out and the `201` comes back decoded — at
    /// repository scope and at organization scope, under one shared test body.
    #[tokio::test]
    async fn a_201_decodes_into_the_configuration_and_the_runner_at_either_scope() {
        for target in both_scopes() {
            let server = MockServer::start().await;
            // `body_json` is an *exact* match on the whole object, so an extra
            // key, a missing key or a renamed key fails here rather than
            // silently reaching GitHub. This is the pin for "sends exactly the
            // documented body shape".
            Mock::given(method("POST"))
                .and(path(RestJit::path(&target)))
                .and(body_json(json!({
                    "name": "rm-home-win-x64-0001",
                    "runner_group_id": 3,
                    "labels": ["rm-home-win-x64", "self-hosted"],
                    "work_folder": "_work"
                })))
                .respond_with(
                    ResponseTemplate::new(201)
                        .set_body_json(created_body(&["rm-home-win-x64", "self-hosted"])),
                )
                .mount(&server)
                .await;

            let gateway = gateway(&server);
            let registration = gateway
                .generate_jit_config(&target, &request(), &CancelToken::new())
                .await
                .unwrap_or_else(|error| panic!("a 201 at {target}: {error}"));

            assert_eq!(
                registration.config().expose(),
                FIXTURE_JIT_CONFIG,
                "the encoded configuration must survive the round trip at {target}"
            );
            assert_eq!(registration.runner().id, 73);
            assert_eq!(registration.runner().name, "rm-home-win-x64-0001");
            assert_eq!(
                registration.runner().runner_group_id,
                Some(3),
                "the runner reference carries the group it was registered in, which \
                 `c3`'s inventory shape has no field for"
            );
            assert_eq!(
                registration.runner().labels,
                vec!["rm-home-win-x64".to_string(), "self-hosted".to_string()],
                "no labels are added implicitly, so the 201 carries exactly what was sent"
            );
            assert_eq!(gateway.requests_issued(), 1);
        }
    }

    /// An unexpected success status is reported, not fatal.
    ///
    /// The status guards nothing here — the body is what this module needs, and
    /// a `200` carries the same one. An assertion would panic a debug build, and
    /// so kill a developer's agent, over a code that changed nothing; this pins
    /// that the registration still succeeds.
    #[tokio::test]
    async fn a_success_status_other_than_201_is_still_decoded() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path(RestJit::path(&repo_target())))
            .respond_with(ResponseTemplate::new(200).set_body_json(created_body(&["a"])))
            .mount(&server)
            .await;

        let registration = gateway(&server)
            .generate_jit_config(&repo_target(), &request(), &CancelToken::new())
            .await
            .expect("a 200 carries the same body a 201 does and must not be fatal");
        assert_eq!(registration.config().expose(), FIXTURE_JIT_CONFIG);
        assert_ne!(
            200, CREATED,
            "the fixture has to be a status the code notices, or this proves nothing"
        );
    }

    /// The path differs between scopes and nothing else does.
    #[test]
    fn the_two_scopes_differ_only_in_the_path() {
        assert_eq!(
            RestJit::path(&repo_target()),
            "/repos/octo/dashboard/actions/runners/generate-jitconfig"
        );
        assert_eq!(
            RestJit::path(&org_target()),
            "/orgs/octo-org/actions/runners/generate-jitconfig"
        );
        assert!(
            RestJit::path(&repo_target()).ends_with(JITCONFIG_PATH)
                && RestJit::path(&org_target()).ends_with(JITCONFIG_PATH),
            "one suffix, two prefixes -- that is the whole of `v1`'s organization finding"
        );
    }

    /// `runner_group_id` is always on the wire, because it cannot be omitted.
    ///
    /// `v1` measured the alternative: omitting the key answers `422 Invalid
    /// input: object is missing required key: runner_group_id`. There is no
    /// server-side default, so the field is a required constructor argument and
    /// the serialised body carries no attribute that could ever drop it.
    #[test]
    fn the_request_body_is_exactly_the_four_documented_keys() {
        let body = serde_json::to_value(request().body()).expect("the body serialises");
        let object = body.as_object().expect("a JSON object");

        let mut keys: Vec<&str> = object.keys().map(String::as_str).collect();
        keys.sort_unstable();
        assert_eq!(
            keys,
            vec!["labels", "name", "runner_group_id", "work_folder"],
            "`04-subsystem-contracts.md` types this body as {{name, runner_group_id, \
             labels, work_folder}}; an extra key is an untested request and a missing \
             `runner_group_id` is a 422"
        );
        assert_eq!(object["runner_group_id"], json!(3));
        assert_eq!(object["work_folder"], json!("_work"));

        // `1` is not special: `v1` registered successfully in group 3.
        let other = JitRunnerRequest::new("n", 99, ["a"]);
        assert_eq!(
            serde_json::to_value(other.body()).expect("serialises")["runner_group_id"],
            json!(99),
            "any administrable group id works, so nothing here may assume 1"
        );
    }

    /// The labels sent are the policy's, verbatim and lower-cased, with nothing
    /// added.
    #[test]
    fn a_policy_registers_exactly_its_own_routing_labels() {
        let labels = RoutingLabels::derive(
            &HostLabel::new("home").expect("a valid host label"),
            Os::Windows,
            Arch::X64,
        );
        let request = JitRunnerRequest::for_policy("runner-1", 1, &labels);

        assert_eq!(request.labels(), &["rm-home-win-x64".to_string()]);
        assert!(
            !request.labels().iter().any(|label| label == "self-hosted"),
            "`v1` established that no labels are added implicitly; adding one here would \
             make a runner answer a `runs-on` the operator never asked it to"
        );
        assert!(
            request
                .labels()
                .iter()
                .all(|l| l == &l.to_ascii_lowercase()),
            "GitHub stores labels lower-cased, so what is sent and what is stored must be \
             the same string"
        );
    }

    // -- the three failure modes -------------------------------------------

    /// `403`, `404` and `422` are three outcomes, not one — and none of them is
    /// retried.
    #[tokio::test]
    async fn each_failure_status_is_a_distinct_outcome_and_none_is_retried() {
        for target in both_scopes() {
            // 403: the permission or the group does not allow it.
            let server = MockServer::start().await;
            mount_failure(
                &server,
                &target,
                403,
                "GitHub hosted runner groups cannot be modified",
            )
            .await;
            let refused = gateway(&server);
            let error = refused
                .generate_jit_config(&target, &request(), &CancelToken::new())
                .await
                .expect_err("a 403 is a failure");
            assert!(
                matches!(
                    error,
                    JitError::Forbidden {
                        runner_group_id: 3,
                        ..
                    }
                ),
                "a 403 must be its own outcome and must name the group: {error:?}"
            );
            assert!(error.is_terminal(), "a 403 is terminal");
            assert!(
                error.operator_action().is_some(),
                "terminal and operator-actionable: a failure nobody can act on and nothing \
                 retries is a dead end"
            );
            assert_eq!(
                refused.requests_issued(),
                1,
                "no code path may retry a 403; `d17` is the record of what it means"
            );

            // 404: the target or the group is not there.
            let server = MockServer::start().await;
            mount_failure(&server, &target, 404, "Not Found").await;
            let missing = gateway(&server);
            let error = missing
                .generate_jit_config(&target, &request(), &CancelToken::new())
                .await
                .expect_err("a 404 is a failure");
            assert!(
                matches!(
                    error,
                    JitError::NotFound {
                        runner_group_id: 3,
                        ..
                    }
                ),
                "a 404 must be its own outcome: {error:?}"
            );
            assert!(error.is_terminal());
            assert_eq!(missing.requests_issued(), 1);

            // 422: the body was rejected.
            let server = MockServer::start().await;
            mount_failure(
                &server,
                &target,
                422,
                "Invalid property /labels: 1 item required; only 0 were supplied",
            )
            .await;
            let rejected = gateway(&server);
            let error = rejected
                .generate_jit_config(&target, &request(), &CancelToken::new())
                .await
                .expect_err("a 422 is a failure");
            assert!(
                matches!(error, JitError::Rejected { .. }),
                "a 422 must be its own outcome: {error:?}"
            );
            assert!(error.is_terminal());
            assert_eq!(rejected.requests_issued(), 1);
        }
    }

    /// An unusable runner group answers `403` **or** `404`, and the two must not
    /// be collapsed.
    ///
    /// `v1` measured both from the same operator mistake — a wrong
    /// `runner_group_id`. Group `2`, the GitHub-hosted group, answered `403`;
    /// group `99999` answered `404`. Error handling keyed on `404` alone tells
    /// an operator to create a group that already exists.
    #[tokio::test]
    async fn an_unusable_runner_group_is_reported_differently_for_403_and_404() {
        let target = org_target();

        let server = MockServer::start().await;
        mount_failure(
            &server,
            &target,
            403,
            "GitHub hosted runner groups cannot be modified",
        )
        .await;
        let hosted_group = gateway(&server)
            .generate_jit_config(
                &target,
                &JitRunnerRequest::new("n", 2, ["a"]),
                &CancelToken::new(),
            )
            .await
            .expect_err("group 2 is not administrable");

        let server = MockServer::start().await;
        mount_failure(&server, &target, 404, "Not Found").await;
        let missing_group = gateway(&server)
            .generate_jit_config(
                &target,
                &JitRunnerRequest::new("n", 99_999, ["a"]),
                &CancelToken::new(),
            )
            .await
            .expect_err("group 99999 does not exist");

        assert!(matches!(
            hosted_group,
            JitError::Forbidden {
                runner_group_id: 2,
                ..
            }
        ));
        assert!(matches!(
            missing_group,
            JitError::NotFound {
                runner_group_id: 99_999,
                ..
            }
        ));
        assert_ne!(
            hosted_group.operator_action(),
            missing_group.operator_action(),
            "the two answers need different remedies: one is a permission on an existing \
             group, the other is a group that is not there"
        );
        assert!(
            hosted_group.to_string().contains("403"),
            "the 403 message must explain that a GitHub-hosted group always answers this"
        );
        assert!(
            missing_group.to_string().contains("404"),
            "and the 404 message must explain the difference in the other direction"
        );
    }

    /// A secondary rate limit arrives as a `403`, and must not be reported as a
    /// permissions refusal.
    ///
    /// A rate limit resolves by waiting; a permissions refusal does not resolve
    /// at all. Reporting the first as the second tells an operator to change a
    /// permission that is already correct, and — worse here — marks a transient
    /// failure terminal, so the runner is never registered.
    #[tokio::test]
    async fn a_rate_limit_wearing_a_403_is_not_a_permissions_refusal() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path(RestJit::path(&repo_target())))
            .respond_with(
                ResponseTemplate::new(403)
                    .insert_header("retry-after", "60")
                    .set_body_json(json!({
                        "message": "You have exceeded a secondary rate limit"
                    })),
            )
            .mount(&server)
            .await;

        let error = gateway(&server)
            .generate_jit_config(&repo_target(), &request(), &CancelToken::new())
            .await
            .expect_err("a rate limit is a failure");

        assert!(
            error.rate_limited().is_some(),
            "`c3`'s detector owns this decision and it said rate limit: {error:?}"
        );
        assert!(
            !error.is_terminal(),
            "a rate limit resolves by waiting; marking it terminal never registers the runner"
        );
        assert!(error.operator_action().is_none());
    }

    /// A cancelled registration opens no socket at all.
    #[tokio::test]
    async fn a_cancelled_registration_issues_no_request() {
        let server = MockServer::start().await;
        mount_created(&server, &repo_target(), created_body(&["a"])).await;
        let gateway = gateway(&server);
        let cancel = CancelToken::new();
        cancel.cancel();

        let error = gateway
            .generate_jit_config(&repo_target(), &request(), &cancel)
            .await
            .expect_err("a cancelled token withdraws the registration");
        assert!(error.is_cancelled());
        assert_eq!(
            gateway.requests_issued(),
            0,
            "the count is of requests actually attempted, and a withdrawn one is not"
        );
    }

    // -- the secret ---------------------------------------------------------

    /// The configuration is absent from `Debug` and from `Display`.
    #[test]
    fn the_configuration_is_absent_from_debug_and_display() {
        let config = EncodedJitConfig::new(FIXTURE_JIT_CONFIG);

        let debug = format!("{config:?}");
        let display = format!("{config}");
        assert!(
            !debug.contains(FIXTURE_JIT_CONFIG),
            "Debug leaked it: {debug}"
        );
        assert!(
            !display.contains(FIXTURE_JIT_CONFIG),
            "Display leaked it: {display}"
        );
        assert!(debug.contains(REDACTED) && display.contains(REDACTED));
        assert!(
            debug.contains(&format!("{} bytes", FIXTURE_JIT_CONFIG.len())),
            "the length is useful and is not the secret: {debug}"
        );

        // And through the registration that carries it, which is what a caller
        // actually holds.
        let registration = JitRegistration::new(
            EncodedJitConfig::new(FIXTURE_JIT_CONFIG),
            JitRunner {
                id: 73,
                name: "runner".into(),
                os: "windows".into(),
                status: "offline".into(),
                busy: false,
                runner_group_id: Some(1),
                labels: vec!["rm-home-win-x64".into()],
            },
        );
        let rendered = format!("{registration:?}");
        assert!(
            !rendered.contains(FIXTURE_JIT_CONFIG),
            "the registration's Debug leaked it: {rendered}"
        );
        assert!(
            rendered.contains("runner"),
            "and still says something useful"
        );
    }

    /// The scan above can actually see a leak.
    ///
    /// A redaction test that never had the secret in reach passes for the wrong
    /// reason. This plants the exact mistake `lib.rs`'s crate documentation
    /// names — a plain `String` field with a derived `Debug` — and requires the
    /// same assertions to catch it.
    #[test]
    fn the_redaction_assertions_would_catch_a_derived_debug_over_a_plain_string() {
        #[derive(Debug)]
        struct ConfigWithADerivedDebug {
            #[allow(dead_code)]
            encoded_jit_config: String,
        }

        let leaky = ConfigWithADerivedDebug {
            encoded_jit_config: FIXTURE_JIT_CONFIG.to_string(),
        };
        assert!(
            format!("{leaky:?}").contains(FIXTURE_JIT_CONFIG),
            "the assertions above cannot see a plain-String secret rendered through a \
             derived Debug, so every one of them is worthless"
        );
    }

    /// The wrapper's buffer is zeroised.
    ///
    /// `scrub` is exactly the call [`Drop::drop`] makes. Observing the buffer
    /// *after* the drop would mean reading freed memory, which is undefined
    /// behaviour and would be a test that proves nothing while appearing to
    /// prove everything; this invokes the same code on a live value instead.
    #[test]
    fn the_wrapper_scrubs_its_buffer() {
        let mut config = EncodedJitConfig::new(FIXTURE_JIT_CONFIG);
        assert_eq!(
            config.expose(),
            FIXTURE_JIT_CONFIG,
            "the fixture has to be really in there, or the assertion below is vacuous"
        );

        config.scrub();

        assert!(
            config.expose().bytes().all(|byte| byte == 0),
            "every byte of the buffer must be zero after a scrub, not merely unreachable"
        );
        assert!(!config.expose().contains("eyJ"));
        assert_eq!(
            config.len(),
            FIXTURE_JIT_CONFIG.len(),
            "`str::zeroize` overwrites in place rather than shortening, so the length is \
             unchanged and every byte of it is zero"
        );
    }

    /// No error value carries the encoded configuration, on any path.
    #[tokio::test]
    async fn an_error_never_carries_the_encoded_configuration() {
        // A `201` whose body cannot be decoded is the one failure that has the
        // secret in reach: the response really does carry it.
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path(RestJit::path(&repo_target())))
            .respond_with(ResponseTemplate::new(201).set_body_json(json!({
                "encoded_jit_config": FIXTURE_JIT_CONFIG,
                "runner": { "name": "no id field, so this cannot decode" }
            })))
            .mount(&server)
            .await;

        let error = gateway(&server)
            .generate_jit_config(&repo_target(), &request(), &CancelToken::new())
            .await
            .expect_err("a 201 missing `runner.id` cannot decode");

        let rendered = format!("{error} {error:?}");
        assert!(
            !rendered.contains(FIXTURE_JIT_CONFIG),
            "a decode failure must not carry the body it failed to decode: {rendered}"
        );
        assert!(
            !rendered.contains("eyJ"),
            "not even a prefix of it: {rendered}"
        );

        // And the three failure statuses, each answered with a body that carries
        // an `encoded_jit_config` key it has no business carrying. GitHub does
        // not send one on a failure; the point is that a variant which ever
        // rendered a response *body* rather than its `message` would be caught
        // here rather than in production.
        for status in [403_u16, 404, 422] {
            let server = MockServer::start().await;
            Mock::given(method("POST"))
                .and(path(RestJit::path(&repo_target())))
                .respond_with(ResponseTemplate::new(status).set_body_json(json!({
                    "message": "Resource not accessible by integration",
                    "encoded_jit_config": FIXTURE_JIT_CONFIG
                })))
                .mount(&server)
                .await;
            let error = gateway(&server)
                .generate_jit_config(&repo_target(), &request(), &CancelToken::new())
                .await
                .expect_err("a failure status");

            let rendered = format!("{error} {error:?}");
            assert!(
                !rendered.contains(FIXTURE_JIT_CONFIG),
                "a {status} rendered a response body verbatim: {rendered}"
            );
            // GitHub's own `message` is the opposite requirement, and both have
            // to hold at once: an error that redacted the message along with the
            // body would be safe and useless. `Resource not accessible by
            // integration` is the sentence that tells an operator which
            // permission is missing.
            assert!(
                rendered.contains("Resource not accessible by integration"),
                "GitHub's message is what makes a {status} operator-actionable and must \
                 survive: {rendered}"
            );
        }
    }

    /// A `201` this client cannot decode is terminal, and tells an operator what
    /// to do about it.
    ///
    /// This is the one failure on this path where retrying is not merely
    /// useless but actively destructive, and the two facts compound. A `201`
    /// **is a completed registration**: GitHub has already created the runner
    /// and spent the one-shot configuration on it. So a caller that reads
    /// [`JitError::is_terminal`] as "safe to try again" issues a second
    /// registration, and a third, each one a fresh runner that this process
    /// then throws away undecoded — a target quietly accumulating registered
    /// runners that never come online, none of which is visible from the
    /// failure itself.
    ///
    /// It was reported non-terminal, and with no
    /// [`JitError::operator_action`], so the loop was silent as well as
    /// unbounded. Both halves are pinned here: the answer to "could retrying
    /// this exact request ever produce a different answer" is no — a body this
    /// client cannot parse will not parse on the next attempt — and a terminal
    /// outcome without an operator action is the dead end that
    /// `operator_action`'s own documentation forbids.
    #[tokio::test]
    async fn an_undecodable_registration_is_terminal_and_operator_actionable() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path(RestJit::path(&repo_target())))
            .respond_with(ResponseTemplate::new(201).set_body_json(json!({
                "encoded_jit_config": FIXTURE_JIT_CONFIG,
                "runner": { "name": "no id field, so this cannot decode" }
            })))
            .mount(&server)
            .await;

        let error = gateway(&server)
            .generate_jit_config(&repo_target(), &request(), &CancelToken::new())
            .await
            .expect_err("a 201 missing `runner.id` cannot decode");

        assert!(
            matches!(error, JitError::Github(GithubError::Decode { .. })),
            "the undecodable 201 arrives through the transparent `#[from]`, which is \
             what makes its terminality a question about `GithubError` rather than \
             about a `JitError` variant: {error:?}"
        );
        assert!(
            error.is_terminal(),
            "a response body this client cannot parse will not parse on a retry, and \
             every retry registers another runner that is then discarded"
        );
        let action = error
            .operator_action()
            .expect("a terminal outcome with no operator action is a dead end");
        assert!(
            action.contains("Do not retry"),
            "the action has to say the one thing a caller must not do: {action}"
        );
        assert!(
            !action.contains(FIXTURE_JIT_CONFIG) && !action.contains("eyJ"),
            "the operator action is rendered wherever the error is, so it is bound by \
             the same redaction rule as the error itself: {action}"
        );

        // The sibling variant, which reaches the same conclusion by the same
        // route: `Malformed` is a value this client cannot use, and it will be
        // the same value next time. Constructed directly because there is no
        // response shape that produces it on the registration path today --
        // which is exactly why it needs pinning rather than leaving to chance.
        let malformed = JitError::Github(GithubError::Malformed {
            what: "runner.id",
            value: "not a number".to_string(),
        });
        assert!(malformed.is_terminal());
        assert!(malformed.operator_action().is_some());

        // And the two failures that stay non-terminal, so the widening above is
        // read as deliberate rather than as "everything under `Github` is
        // terminal now". A lockout resolves by waiting and a transport failure
        // resolves when the network does; retrying either is the correct
        // behaviour, and neither has registered anything.
        for still_retryable in [
            JitError::Github(GithubError::AuthenticationLockout {
                retry_after: std::time::Duration::from_secs(60),
            }),
            JitError::Cancelled,
        ] {
            assert!(
                !still_retryable.is_terminal(),
                "{still_retryable:?} resolves on its own and must not be reported as \
                 terminal"
            );
        }
    }

    /// A registration whose response reports different labels than were
    /// requested is still returned, and says so.
    ///
    /// `v1` observed that label *order* is not preserved and that labels come
    /// back lower-cased, so an equality check on the array would fail on a
    /// correct registration. The runner reference carries what GitHub stored, and
    /// comparing is the caller's business.
    #[tokio::test]
    async fn the_runner_reference_reports_the_labels_github_actually_stored() {
        let server = MockServer::start().await;
        mount_created(
            &server,
            &repo_target(),
            created_body(&["self-hosted", "rm-home-win-x64"]),
        )
        .await;

        let registration = gateway(&server)
            .generate_jit_config(&repo_target(), &request(), &CancelToken::new())
            .await
            .expect("a 201");

        assert_eq!(
            registration.runner().labels,
            vec!["self-hosted".to_string(), "rm-home-win-x64".to_string()],
            "what GitHub stored, in the order GitHub returned it -- `v1` established that \
             the order is not the order requested"
        );
    }
}