lean-ctx-cloud 3.12.13

The LeanCTX connector: enrollment, bus, knowledge sync, tasks and policy on top of LeanCTX | OSS.
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
// SPDX-License-Identifier: Apache-2.0
//! CI runners on LeanCTX computers (`/v1/runners`, local-read-v1 ยง45): list,
//! add and remove the GitHub Actions and GitLab runners LeanCTX Cloud runs
//! for the person and their teams.
//!
//! A runner binds an existing computer of the account or team: the cloud
//! registers the runner on the live computer of that scope and keeps the
//! computer's own role, state and price. Removing a runner unbinds it; the
//! computer stays. The cloud checks role, plan and scope; this module passes
//! the request on and hands back what the cloud answered (see
//! [`crate::computers`] for the answer classes).
//!
//! The forge's registration token goes only into the body of one
//! `POST /v1/runners`, to the connected cloud over its pinned TLS session. It
//! is held in zeroizing buffers (also the encoded body), has no `Debug` or
//! `Display` text, and is cut out of anything the cloud answers before that
//! is bounded or passed on.

use std::fmt;

use serde::Serialize;
use serde_json::{Map, Value, json};
use zeroize::Zeroizing;

use crate::CloudError;
use crate::computers::{self, Answer, Exchange};
use crate::config::CloudConfig;
use crate::state::CloudStore;

/// The cloud route (under `/v1`).
const PATH: &str = "/runners";
/// The role the request names (contract); the cloud binds the scope's
/// computer and keeps that computer's own role.
pub const ROLE_CI_RUNNER: &str = "ci_runner";
/// Most labels (GitHub) or tags (GitLab) sent.
pub const MAX_LABELS: usize = 16;
/// Keys never passed on from a cloud answer, at any depth.
const SECRET_KEYS: [&str; 2] = ["registration_token", "token"];
/// What a token found in a cloud message is replaced with.
const TOKEN_MARK: &str = "[token]";
/// The shortest cut-off start of the token that is still masked at the end
/// of a text (a message bounded elsewhere may end inside the token).
const MIN_TOKEN_TAIL: usize = 8;
/// Room for the encoded `add` body: far above its largest size (16 labels of
/// 64, a 255-character token, a GitLab origin), so the buffer never grows
/// and leaves no copy of the token behind.
const BODY_CAPACITY: usize = 16 * 1024;
/// The token's length bounds (LeanCTX Cloud's rule).
const TOKEN_LEN: std::ops::RangeInclusive<usize> = 20..=255;
/// The prefix of a GitLab runner authentication token.
const GITLAB_TOKEN_PREFIX: &str = "glrt-";

/// The forge a runner registers with.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Target {
    /// A GitLab server, by its `https://` origin.
    GitLab { origin: String },
    /// A GitHub repository, `owner/repo`.
    GitHub { repo: String },
}

impl Target {
    /// `gitlab` or `github`.
    #[must_use]
    pub fn forge(&self) -> &'static str {
        match self {
            Self::GitLab { .. } => "gitlab",
            Self::GitHub { .. } => "github",
        }
    }

    /// The origin or `owner/repo`, as sent.
    #[must_use]
    pub fn target(&self) -> &str {
        match self {
            Self::GitLab { origin } => origin,
            Self::GitHub { repo } => repo,
        }
    }

    /// A GitLab server origin: `https://host[:port]`, no credentials, no
    /// path, no query. The runner token decides the project or group.
    pub fn gitlab(url: &str) -> Result<Self, String> {
        let bad = |why: &str| {
            Err(format!(
                "--gitlab '{}': {why}; give the GitLab server as https://host",
                printable(url)
            ))
        };
        let Some(rest) = url.strip_prefix("https://") else {
            return bad("only https:// is accepted");
        };
        let rest = rest.strip_suffix('/').unwrap_or(rest);
        if rest.contains(['/', '?', '#']) {
            return bad("no path, query or fragment");
        }
        if rest.contains('@') {
            return bad("no credentials in the URL");
        }
        let (host, port) = match rest.rsplit_once(':') {
            Some((host, port)) => (host, Some(port)),
            None => (rest, None),
        };
        let host_ok = (1..=253).contains(&host.len())
            && host.split('.').all(|label| {
                (1..=63).contains(&label.len())
                    && label
                        .bytes()
                        .all(|b| b.is_ascii_alphanumeric() || b == b'-')
                    && !label.starts_with('-')
                    && !label.ends_with('-')
            });
        if !host_ok {
            return bad("not a host name");
        }
        if let Some(port) = port
            && !port.parse::<u16>().is_ok_and(|p| p > 0)
        {
            return bad("not a port");
        }
        Ok(Self::GitLab {
            origin: format!("https://{}", rest.to_ascii_lowercase()),
        })
    }

    /// A GitHub repository as GitHub names them: owner 1-39 of `A-Za-z0-9-`
    /// (not starting or ending with `-`), repo 1-100 of `A-Za-z0-9._-`, not
    /// `.` or `..`.
    pub fn github(repo: &str) -> Result<Self, String> {
        let bad = || {
            Err(format!(
                "--github '{}': give the repository as owner/repo",
                printable(repo)
            ))
        };
        let Some((owner, name)) = repo.split_once('/') else {
            return bad();
        };
        let owner_ok = (1..=39).contains(&owner.len())
            && owner
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b == b'-')
            && !owner.starts_with('-')
            && !owner.ends_with('-');
        let name_ok = (1..=100).contains(&name.len())
            && name
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
            && name != "."
            && name != "..";
        if owner_ok && name_ok {
            Ok(Self::GitHub {
                repo: repo.to_owned(),
            })
        } else {
            bad()
        }
    }

    /// The default runner name: `gl-<first host label>` or `gh-<repo>`,
    /// lowercased, other characters as `-`, at most 32 characters, without a
    /// trailing `-`.
    #[must_use]
    pub fn default_name(&self) -> String {
        let (prefix, base) = match self {
            Self::GitLab { origin } => (
                "gl-",
                origin
                    .trim_start_matches("https://")
                    .split(['.', ':'])
                    .next()
                    .unwrap_or_default(),
            ),
            Self::GitHub { repo } => ("gh-", repo.split('/').nth(1).unwrap_or_default()),
        };
        let mut name: String = prefix
            .chars()
            .chain(base.chars().map(|c| {
                if c.is_ascii_alphanumeric() {
                    c.to_ascii_lowercase()
                } else {
                    '-'
                }
            }))
            .take(32)
            .collect();
        while name.ends_with('-') {
            name.pop();
        }
        name
    }
}

/// A label (GitHub) or tag (GitLab): 1-64 of `A-Za-z0-9_.-`.
#[must_use]
pub fn valid_label(label: &str) -> bool {
    (1..=64).contains(&label.len())
        && label
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-'))
}

/// A runner id as the cloud sends it: `cmp_<id>`, or a bare UUID.
#[must_use]
pub fn valid_id(id: &str) -> bool {
    computers::valid_id(id) || is_uuid(id)
}

fn is_uuid(id: &str) -> bool {
    let hex = |s: &str| s.bytes().all(|b| b.is_ascii_hexdigit());
    match id.len() {
        32 => hex(id),
        36 => id.split('-').map(str::len).eq([8, 4, 4, 4, 12]) && hex(&id.replace('-', "")),
        _ => false,
    }
}

/// The forge's registration token. No `Debug`/`Display` text, no
/// `Serialize`: it leaves this process only inside [`add`]'s request body.
pub struct RegistrationToken(Zeroizing<String>);

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

impl RegistrationToken {
    /// The token for `target`'s forge, trimmed, when it has that forge's
    /// shape (LeanCTX Cloud's rule): 20-255 characters, GitLab `glrt-` then
    /// `A-Za-z0-9_-`, GitHub `A-Za-z0-9` only. The message never contains it.
    pub fn new(raw: &str, target: &Target) -> Result<Self, String> {
        let trimmed = raw.trim();
        if !TOKEN_LEN.contains(&trimmed.len()) {
            return Err(format!(
                "the registration token must be {}-{} characters",
                TOKEN_LEN.start(),
                TOKEN_LEN.end()
            ));
        }
        let shaped = match target {
            Target::GitLab { .. } => {
                trimmed
                    .strip_prefix(GITLAB_TOKEN_PREFIX)
                    .is_some_and(|rest| {
                        rest.bytes()
                            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-'))
                    })
            }
            Target::GitHub { .. } => trimmed.bytes().all(|b| b.is_ascii_alphanumeric()),
        };
        if !shaped {
            return Err(match target {
                Target::GitLab { .. } => "the registration token is not a GitLab runner token (glrt- followed by A-Z, a-z, 0-9, _ and -)".into(),
                Target::GitHub { .. } => "the registration token is not a GitHub runner token (only A-Z, a-z and 0-9)".into(),
            });
        }
        Ok(Self(Zeroizing::new(trimmed.to_owned())))
    }

    fn expose(&self) -> &str {
        &self.0
    }
}

/// `POST /v1/runners`, without the token (that is added only when sent).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddRequest {
    pub request_id: String,
    pub name: String,
    /// The team's org id; absent for a personal runner.
    pub team: Option<String>,
    pub target: Target,
    pub labels: Vec<String>,
}

/// The wire body: borrows every field, so the token is copied only once,
/// into the zeroizing buffer [`AddRequest::encoded`] writes.
#[derive(Serialize)]
struct Body<'a> {
    request_id: &'a str,
    name: &'a str,
    role: &'static str,
    forge: &'static str,
    target: &'a str,
    labels: &'a [String],
    #[serde(skip_serializing_if = "Option::is_none")]
    team: Option<&'a str>,
    registration_token: &'a str,
}

impl AddRequest {
    /// The JSON body with the token, in a buffer wiped when dropped. Its
    /// room is reserved up front, so it never reallocates (a reallocation
    /// would leave an unwiped copy behind).
    fn encoded(&self, token: &RegistrationToken) -> Result<Zeroizing<Vec<u8>>, CloudError> {
        let mut buffer = Zeroizing::new(Vec::with_capacity(BODY_CAPACITY));
        let body = Body {
            request_id: &self.request_id,
            name: &self.name,
            role: ROLE_CI_RUNNER,
            forge: self.target.forge(),
            target: self.target.target(),
            labels: &self.labels,
            team: self.team.as_deref(),
            registration_token: token.expose(),
        };
        serde_json::to_writer(&mut *buffer, &body)
            .map_err(|e| CloudError::Protocol(format!("encode request: {e}")))?;
        Ok(buffer)
    }
}

/// `GET /v1/runners`, checked. The cloud's `balance` is not read: a runner
/// costs nothing beyond its computer.
#[derive(Debug, Clone, PartialEq, Default, Serialize)]
pub struct RunnerList {
    /// The rows (computer rows with a `runner` member), secrets cut out.
    pub runners: Vec<Map<String, Value>>,
}

/// One exchange with an already encoded JSON body: method, path (under
/// `/v1`) and body bytes โ†’ the HTTP status and the JSON answer.
pub type RawExchange<'a> = &'a dyn Fn(&str, &str, &[u8]) -> Result<(u16, Value), CloudError>;

/// The raw exchanges of the connected instance (as
/// [`computers::connected`]): each one through its session, which
/// refreshes a refused token.
pub fn connected_raw<'a>(
    store: &'a CloudStore,
    config: &'a CloudConfig,
) -> impl Fn(&str, &str, &[u8]) -> Result<(u16, Value), CloudError> + 'a {
    move |method, path, body| {
        let session = crate::scheduler::connected_session(store, config)?;
        session.with_client(|client| {
            let (status, answer) =
                client.send_json_bytes_answer(method, path, body, computers::MAX_ANSWER_BYTES)?;
            if status == 401 {
                return Err(CloudError::from_response(status, &answer));
            }
            Ok((status, answer))
        })
    }
}

/// `GET /v1/runners`.
pub fn list(send: Exchange<'_>) -> Result<Answer<RunnerList>, CloudError> {
    let (status, body) = send("GET", PATH, None)?;
    computers::classify(status, &body, list_of)
}

/// `POST /v1/runners`: the bound row (`runner.status` `pending`). The token
/// is sent in this one body and nowhere else; an answer or error that
/// repeats it has it cut before anything bounds its text.
pub fn add(
    send: RawExchange<'_>,
    request: &AddRequest,
    token: &RegistrationToken,
) -> Result<Answer<Map<String, Value>>, CloudError> {
    let body = request.encoded(token)?;
    let result = send("POST", PATH, &body);
    drop(body);
    let (status, answer) = result.map_err(|e| scrub_error(e, token))?;
    answer_of(status, answer, token)
}

/// The answer of `add`: the token cut from the whole body first, then
/// classified (which bounds the cloud's texts).
fn answer_of(
    status: u16,
    mut answer: Value,
    token: &RegistrationToken,
) -> Result<Answer<Map<String, Value>>, CloudError> {
    scrub_value(&mut answer, token);
    computers::classify(status, &answer, row_of).map_err(|e| scrub_error(e, token))
}

/// `POST /v1/runners/{id}/remove`: the row (`runner.status` `removed`). It
/// unbinds the runner; the computer stays.
pub fn remove(
    send: Exchange<'_>,
    id: &str,
    request_id: &str,
) -> Result<Answer<Map<String, Value>>, CloudError> {
    if !valid_id(id) {
        return Err(CloudError::Protocol(format!(
            "runners: bad id '{}'",
            printable(id)
        )));
    }
    let path = format!("{PATH}/{id}/remove");
    let body = json!({ "request_id": request_id });
    let (status, answer) = send("POST", &path, Some(&body))?;
    computers::classify(status, &answer, row_of)
}

fn list_of(body: &Value) -> Result<RunnerList, CloudError> {
    let rows = body
        .get("runners")
        .and_then(Value::as_array)
        .ok_or_else(|| CloudError::Protocol("runners: no `runners` list".into()))?;
    Ok(RunnerList {
        runners: rows
            .iter()
            .filter_map(computers::checked_row)
            .map(without_secrets)
            .take(computers::MAX_ROWS)
            .collect(),
    })
}

/// A write's answer: the row itself, or `{runner: row}` / `{computer: row}`.
fn row_of(body: &Value) -> Result<Map<String, Value>, CloudError> {
    let row = body
        .get("runner")
        .filter(|r| r.get("id").is_some())
        .or_else(|| body.get("computer"))
        .unwrap_or(body);
    computers::checked_row(row)
        .map(without_secrets)
        .ok_or_else(|| CloudError::Protocol("runners: the answer is not a runner row".into()))
}

/// `row` without any [`SECRET_KEYS`] member, at any depth.
fn without_secrets(mut row: Map<String, Value>) -> Map<String, Value> {
    fn cut(value: &mut Value) {
        match value {
            Value::Object(map) => {
                for key in SECRET_KEYS {
                    map.remove(key);
                }
                map.values_mut().for_each(cut);
            }
            Value::Array(items) => items.iter_mut().for_each(cut),
            _ => {}
        }
    }
    for key in SECRET_KEYS {
        row.remove(key);
    }
    row.values_mut().for_each(cut);
    row
}

/// `text` with every occurrence of the token replaced by [`TOKEN_MARK`], and
/// a cut-off start of the token at its end (at least [`MIN_TOKEN_TAIL`]
/// characters) as well.
fn scrub(text: &str, token: &RegistrationToken) -> String {
    let secret = token.expose();
    let mut out = text.replace(secret, TOKEN_MARK);
    // The token is ASCII (checked in `new`), so every prefix is a char boundary.
    let longest = secret.len().saturating_sub(1).min(out.len());
    if let Some(cut) = (MIN_TOKEN_TAIL..=longest)
        .rev()
        .find(|&n| out.ends_with(&secret[..n]))
    {
        out.truncate(out.len() - cut);
        out.push_str(TOKEN_MARK);
    }
    out
}

fn mentions(text: &str, token: &RegistrationToken) -> bool {
    scrub(text, token) != text
}

fn scrub_value(value: &mut Value, token: &RegistrationToken) {
    match value {
        Value::String(text) if mentions(text, token) => *text = scrub(text, token),
        Value::Object(map) => map.values_mut().for_each(|v| scrub_value(v, token)),
        Value::Array(items) => items.iter_mut().for_each(|v| scrub_value(v, token)),
        _ => {}
    }
}

/// `error` with the token cut from its texts. The variant stays (it decides
/// the exit and the error code); only a structured variant whose rendered
/// text still names the token becomes [`CloudError::Protocol`].
fn scrub_error(error: CloudError, token: &RegistrationToken) -> CloudError {
    let s = |text: String| scrub(&text, token);
    match error {
        CloudError::Offline(text) => CloudError::Offline(s(text)),
        CloudError::Protocol(text) => CloudError::Protocol(s(text)),
        CloudError::Config(text) => CloudError::Config(s(text)),
        CloudError::Local(text) => CloudError::Local(s(text)),
        CloudError::Refused(text) => CloudError::Refused(s(text)),
        CloudError::DeviceFlow(text) => CloudError::DeviceFlow(s(text)),
        CloudError::Server { status, code } => CloudError::Server {
            status,
            code: s(code),
        },
        CloudError::Task {
            refusal,
            number,
            detail,
        } => CloudError::Task {
            refusal,
            number,
            detail: detail.map(s),
        },
        other => {
            let text = other.to_string();
            if mentions(&text, token) {
                CloudError::Protocol(scrub(&text, token))
            } else {
                other
            }
        }
    }
}

/// `text` with control characters dropped and cut to 200 characters, for
/// echoing a bad argument.
fn printable(text: &str) -> String {
    text.chars().filter(|c| !c.is_control()).take(200).collect()
}

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

    fn gl_token(text: &str) -> RegistrationToken {
        let target = Target::gitlab("https://gitlab.example.com").expect("gl");
        RegistrationToken::new(text, &target).expect("token")
    }

    fn gh_token(text: &str) -> RegistrationToken {
        let target = Target::github("o/r").expect("gh");
        RegistrationToken::new(text, &target).expect("token")
    }

    #[test]
    fn gitlab_targets_are_https_origins_only() {
        assert_eq!(
            Target::gitlab("https://GitLab.Example.com/").expect("origin"),
            Target::GitLab {
                origin: "https://gitlab.example.com".into()
            }
        );
        assert!(Target::gitlab("https://gitlab.example.com:8443").is_ok());
        for bad in [
            "http://gitlab.example.com",
            "https://gitlab.example.com/group/project",
            "https://user:pw@gitlab.example.com",
            "https://gitlab.example.com?x=1",
            "https://gitlab.example.com:0",
            "https://-bad.example.com",
            "gitlab.example.com",
        ] {
            assert!(Target::gitlab(bad).is_err(), "{bad}");
        }
        let message = Target::gitlab("https://user:secret@x.example").expect_err("refused");
        assert!(message.contains("no credentials"));
    }

    #[test]
    fn github_targets_are_owner_and_repo() {
        assert!(Target::github("leanctx/lean-ctx").is_ok());
        assert!(Target::github("a/b.c_d-e").is_ok());
        for bad in [
            "leanctx", "-x/y", "x-/y", "x/..", "x/.", "x/y/z", "x/", "/y",
        ] {
            assert!(Target::github(bad).is_err(), "{bad}");
        }
    }

    #[test]
    fn default_names_follow_the_computer_name_rule() {
        let gl = Target::gitlab("https://gitlab.pounce.ch").expect("gl");
        assert_eq!(gl.default_name(), "gl-gitlab");
        let gh = Target::github("LeanCTX/Lean.Ctx_Repo").expect("gh");
        assert_eq!(gh.default_name(), "gh-lean-ctx-repo");
        let long = Target::github(&format!("o/{}", "a".repeat(80))).expect("gh");
        assert_eq!(long.default_name().len(), 32);
        let trailing = Target::github("o/abcdefghijklmnopqrstuvwxyzabc-").expect("gh");
        assert!(!trailing.default_name().ends_with('-'));
    }

    #[test]
    fn tokens_have_no_text_and_the_forges_shape() {
        let t = gl_token("  glrt-AbCdEfGh12345678_x-y\n");
        assert_eq!(t.expose(), "glrt-AbCdEfGh12345678_x-y");
        assert_eq!(format!("{t:?}"), "RegistrationToken([redacted])");
        let gh = gh_token("AABBCCDDEEFF0011223344");
        assert_eq!(gh.expose(), "AABBCCDDEEFF0011223344");
        let gitlab = Target::gitlab("https://gitlab.example.com").expect("gl");
        let github = Target::github("o/r").expect("gh");
        let long = format!("glrt-{}", "x".repeat(251));
        for (bad, target) in [
            ("glrt-short", &gitlab),
            ("glrt-has space inside-12345", &gitlab),
            ("AABBCCDDEEFF0011223344", &gitlab),
            (long.as_str(), &gitlab),
            ("glrt-AbCdEfGh12345678", &github),
            ("AABBCCDD-EEFF0011223344", &github),
            ("AABBCCDDEEFF00112", &github),
        ] {
            let err = RegistrationToken::new(bad, target).expect_err("bad");
            assert!(!err.contains(bad.trim()), "the message repeats the input");
        }
        let edge = format!("glrt-{}", "x".repeat(250));
        assert!(RegistrationToken::new(&edge, &gitlab).is_ok());
    }

    #[test]
    fn the_add_body_carries_the_token_and_the_target() {
        let request = AddRequest {
            request_id: "req_12345678".into(),
            name: "gh-lean-ctx".into(),
            team: Some("org_acme".into()),
            target: Target::github("leanctx/lean-ctx").expect("gh"),
            labels: vec!["linux".into()],
        };
        let t = gh_token("AABBCCDDEEFF0011223344");
        let encoded = request.encoded(&t).expect("encoded");
        assert!(encoded.capacity() >= BODY_CAPACITY, "the buffer never grew");
        let body: Value = serde_json::from_slice(&encoded).expect("json");
        assert_eq!(body["role"], ROLE_CI_RUNNER);
        assert_eq!(body["forge"], "github");
        assert_eq!(body["target"], "leanctx/lean-ctx");
        assert_eq!(body["registration_token"], "AABBCCDDEEFF0011223344");
        assert_eq!(body["team"], "org_acme");
        assert_eq!(body["labels"], json!(["linux"]));
        let personal = AddRequest {
            team: None,
            ..request
        };
        let body: Value =
            serde_json::from_slice(&personal.encoded(&t).expect("encoded")).expect("json");
        assert!(body.get("team").is_none());
        assert!(!format!("{personal:?}").contains("AABBCCDD"));
    }

    #[test]
    fn add_sends_the_encoded_body_once_and_scrubs_the_answer() {
        let t = gl_token("glrt-SECRET-1234567890");
        let request = AddRequest {
            request_id: "req_12345678".into(),
            name: "gl-x".into(),
            team: None,
            target: Target::gitlab("https://gitlab.example.com").expect("gl"),
            labels: vec![],
        };
        let calls = std::cell::Cell::new(0);
        let send = |method: &str, path: &str, body: &[u8]| {
            calls.set(calls.get() + 1);
            assert_eq!((method, path), ("POST", "/runners"));
            let sent: Value = serde_json::from_slice(body).expect("json");
            assert_eq!(sent["registration_token"], "glrt-SECRET-1234567890");
            Ok((
                201,
                json!({ "runner": { "id": "cmp_9", "name": "gl-x", "state": "running",
                    "runner": { "status": "pending" },
                    "note": "registered glrt-SECRET-1234567890" } }),
            ))
        };
        let Answer::Done(row) = add(&send, &request, &t).expect("ok") else {
            panic!("not done");
        };
        assert_eq!(calls.get(), 1);
        assert_eq!(row["note"], "registered [token]");
        assert_eq!(row["runner"]["status"], "pending");
    }

    #[test]
    fn rows_lose_secret_members_at_any_depth() {
        let body = json!({
            "runners": [{
                "id": "cmp_1", "name": "gh-x", "state": "running", "role": "general",
                "token": "t1",
                "runner": { "status": "registered", "registration_token": "t2",
                            "steps": [{ "token": "t3", "ok": true }] }
            }, { "name": "no id" }],
            "balance": { "usd": 3.0 }
        });
        let Answer::Done(list) = computers::classify(200, &body, list_of).expect("ok") else {
            panic!("not done");
        };
        assert_eq!(list.runners.len(), 1);
        let text = serde_json::to_string(&list).expect("json");
        for secret in ["t1", "t2", "t3"] {
            assert!(!text.contains(&format!("\"{secret}\"")), "{text}");
        }
        assert!(
            !text.contains("balance"),
            "a runner list carries no balance"
        );
        assert_eq!(list.runners[0]["runner"]["steps"][0]["ok"], true);
    }

    #[test]
    fn a_write_answer_is_the_row_or_a_wrapped_row() {
        let row = json!({ "id": "cmp_2", "name": "gl-x", "state": "running",
                          "runner": { "status": "pending" } });
        assert_eq!(row_of(&row).expect("row")["id"], "cmp_2");
        assert_eq!(
            row_of(&json!({ "runner": row.clone() })).expect("row")["id"],
            "cmp_2"
        );
        assert_eq!(
            row_of(&json!({ "computer": row })).expect("row")["id"],
            "cmp_2"
        );
        assert!(row_of(&json!({ "ok": true })).is_err());
    }

    #[test]
    fn refusals_are_scrubbed_before_they_are_bounded() {
        let t = gl_token("glrt-SECRET-1234567890");
        let body = json!({ "error": { "code": "runner_token_rejected",
            "message": "GitLab refused glrt-SECRET-1234567890 for this project." } });
        let Answer::Refused(refusal) = answer_of(422, body, &t).expect("refusal") else {
            panic!("not refused");
        };
        assert_eq!(refusal.code, "runner_token_rejected");
        assert_eq!(
            refusal.message.as_deref(),
            Some("GitLab refused [token] for this project.")
        );
        // The token straddles the 500-character bound: scrubbed first, no
        // start of it survives the cut.
        let long = format!("{} glrt-SECRET-1234567890 tail", "x".repeat(490));
        let body = json!({ "error": { "code": "runner_token_rejected", "message": long } });
        let Answer::Refused(refusal) = answer_of(422, body, &t).expect("refusal") else {
            panic!("not refused");
        };
        let message = refusal.message.expect("message");
        assert!(!message.contains("glrt-SECRE"), "{message}");
    }

    #[test]
    fn a_cut_off_token_at_the_end_of_a_text_is_masked() {
        let t = gl_token("glrt-SECRET-1234567890");
        assert_eq!(scrub("sent glrt-SECRET-12", &t), "sent [token]");
        assert_eq!(
            scrub("sent glrt-SE", &t),
            "sent glrt-SE",
            "too short to mask"
        );
        assert_eq!(scrub("no token here", &t), "no token here");
    }

    #[test]
    fn scrubbed_errors_keep_their_class() {
        let t = gl_token("glrt-SECRET-1234567890");
        let offline = scrub_error(
            CloudError::Offline("connect glrt-SECRET-1234567890".into()),
            &t,
        );
        assert!(matches!(&offline, CloudError::Offline(text) if text == "connect [token]"));
        let server = scrub_error(
            CloudError::Server {
                status: 502,
                code: "bad glrt-SECRET-1234567890".into(),
            },
            &t,
        );
        assert!(matches!(server, CloudError::Server { status: 502, .. }));
        assert!(!server.to_string().contains("SECRET"));
        assert!(matches!(
            scrub_error(CloudError::NotConnected, &t),
            CloudError::NotConnected
        ));
    }

    #[test]
    fn labels_are_checked() {
        assert!(valid_label("linux-x64"));
        assert!(valid_label("self_hosted.1"));
        assert!(!valid_label(""));
        assert!(!valid_label("has space"));
        assert!(!valid_label(&"a".repeat(65)));
    }
}