Skip to main content

lean_ctx_cloud/
runners.rs

1// SPDX-License-Identifier: Apache-2.0
2//! CI runners on LeanCTX computers (`/v1/runners`, local-read-v1 §45): list,
3//! add and remove the GitHub Actions and GitLab runners LeanCTX Cloud runs
4//! for the person and their teams.
5//!
6//! A runner binds an existing computer of the account or team: the cloud
7//! registers the runner on the live computer of that scope and keeps the
8//! computer's own role, state and price. Removing a runner unbinds it; the
9//! computer stays. The cloud checks role, plan and scope; this module passes
10//! the request on and hands back what the cloud answered (see
11//! [`crate::computers`] for the answer classes).
12//!
13//! The forge's registration token goes only into the body of one
14//! `POST /v1/runners`, to the connected cloud over its pinned TLS session. It
15//! is held in zeroizing buffers (also the encoded body), has no `Debug` or
16//! `Display` text, and is cut out of anything the cloud answers before that
17//! is bounded or passed on.
18
19use std::fmt;
20
21use serde::Serialize;
22use serde_json::{Map, Value, json};
23use zeroize::Zeroizing;
24
25use crate::CloudError;
26use crate::computers::{self, Answer, Exchange};
27use crate::config::CloudConfig;
28use crate::state::CloudStore;
29
30/// The cloud route (under `/v1`).
31const PATH: &str = "/runners";
32/// The role the request names (contract); the cloud binds the scope's
33/// computer and keeps that computer's own role.
34pub const ROLE_CI_RUNNER: &str = "ci_runner";
35/// Most labels (GitHub) or tags (GitLab) sent.
36pub const MAX_LABELS: usize = 16;
37/// Keys never passed on from a cloud answer, at any depth.
38const SECRET_KEYS: [&str; 2] = ["registration_token", "token"];
39/// What a token found in a cloud message is replaced with.
40const TOKEN_MARK: &str = "[token]";
41/// The shortest cut-off start of the token that is still masked at the end
42/// of a text (a message bounded elsewhere may end inside the token).
43const MIN_TOKEN_TAIL: usize = 8;
44/// Room for the encoded `add` body: far above its largest size (16 labels of
45/// 64, a 255-character token, a GitLab origin), so the buffer never grows
46/// and leaves no copy of the token behind.
47const BODY_CAPACITY: usize = 16 * 1024;
48/// The token's length bounds (LeanCTX Cloud's rule).
49const TOKEN_LEN: std::ops::RangeInclusive<usize> = 20..=255;
50/// The prefix of a GitLab runner authentication token.
51const GITLAB_TOKEN_PREFIX: &str = "glrt-";
52
53/// The forge a runner registers with.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum Target {
56    /// A GitLab server, by its `https://` origin.
57    GitLab { origin: String },
58    /// A GitHub repository, `owner/repo`.
59    GitHub { repo: String },
60}
61
62impl Target {
63    /// `gitlab` or `github`.
64    #[must_use]
65    pub fn forge(&self) -> &'static str {
66        match self {
67            Self::GitLab { .. } => "gitlab",
68            Self::GitHub { .. } => "github",
69        }
70    }
71
72    /// The origin or `owner/repo`, as sent.
73    #[must_use]
74    pub fn target(&self) -> &str {
75        match self {
76            Self::GitLab { origin } => origin,
77            Self::GitHub { repo } => repo,
78        }
79    }
80
81    /// A GitLab server origin: `https://host[:port]`, no credentials, no
82    /// path, no query. The runner token decides the project or group.
83    pub fn gitlab(url: &str) -> Result<Self, String> {
84        let bad = |why: &str| {
85            Err(format!(
86                "--gitlab '{}': {why}; give the GitLab server as https://host",
87                printable(url)
88            ))
89        };
90        let Some(rest) = url.strip_prefix("https://") else {
91            return bad("only https:// is accepted");
92        };
93        let rest = rest.strip_suffix('/').unwrap_or(rest);
94        if rest.contains(['/', '?', '#']) {
95            return bad("no path, query or fragment");
96        }
97        if rest.contains('@') {
98            return bad("no credentials in the URL");
99        }
100        let (host, port) = match rest.rsplit_once(':') {
101            Some((host, port)) => (host, Some(port)),
102            None => (rest, None),
103        };
104        let host_ok = (1..=253).contains(&host.len())
105            && host.split('.').all(|label| {
106                (1..=63).contains(&label.len())
107                    && label
108                        .bytes()
109                        .all(|b| b.is_ascii_alphanumeric() || b == b'-')
110                    && !label.starts_with('-')
111                    && !label.ends_with('-')
112            });
113        if !host_ok {
114            return bad("not a host name");
115        }
116        if let Some(port) = port
117            && !port.parse::<u16>().is_ok_and(|p| p > 0)
118        {
119            return bad("not a port");
120        }
121        Ok(Self::GitLab {
122            origin: format!("https://{}", rest.to_ascii_lowercase()),
123        })
124    }
125
126    /// A GitHub repository as GitHub names them: owner 1-39 of `A-Za-z0-9-`
127    /// (not starting or ending with `-`), repo 1-100 of `A-Za-z0-9._-`, not
128    /// `.` or `..`.
129    pub fn github(repo: &str) -> Result<Self, String> {
130        let bad = || {
131            Err(format!(
132                "--github '{}': give the repository as owner/repo",
133                printable(repo)
134            ))
135        };
136        let Some((owner, name)) = repo.split_once('/') else {
137            return bad();
138        };
139        let owner_ok = (1..=39).contains(&owner.len())
140            && owner
141                .bytes()
142                .all(|b| b.is_ascii_alphanumeric() || b == b'-')
143            && !owner.starts_with('-')
144            && !owner.ends_with('-');
145        let name_ok = (1..=100).contains(&name.len())
146            && name
147                .bytes()
148                .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
149            && name != "."
150            && name != "..";
151        if owner_ok && name_ok {
152            Ok(Self::GitHub {
153                repo: repo.to_owned(),
154            })
155        } else {
156            bad()
157        }
158    }
159
160    /// The default runner name: `gl-<first host label>` or `gh-<repo>`,
161    /// lowercased, other characters as `-`, at most 32 characters, without a
162    /// trailing `-`.
163    #[must_use]
164    pub fn default_name(&self) -> String {
165        let (prefix, base) = match self {
166            Self::GitLab { origin } => (
167                "gl-",
168                origin
169                    .trim_start_matches("https://")
170                    .split(['.', ':'])
171                    .next()
172                    .unwrap_or_default(),
173            ),
174            Self::GitHub { repo } => ("gh-", repo.split('/').nth(1).unwrap_or_default()),
175        };
176        let mut name: String = prefix
177            .chars()
178            .chain(base.chars().map(|c| {
179                if c.is_ascii_alphanumeric() {
180                    c.to_ascii_lowercase()
181                } else {
182                    '-'
183                }
184            }))
185            .take(32)
186            .collect();
187        while name.ends_with('-') {
188            name.pop();
189        }
190        name
191    }
192}
193
194/// A label (GitHub) or tag (GitLab): 1-64 of `A-Za-z0-9_.-`.
195#[must_use]
196pub fn valid_label(label: &str) -> bool {
197    (1..=64).contains(&label.len())
198        && label
199            .bytes()
200            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-'))
201}
202
203/// A runner id as the cloud sends it: `cmp_<id>`, or a bare UUID.
204#[must_use]
205pub fn valid_id(id: &str) -> bool {
206    computers::valid_id(id) || is_uuid(id)
207}
208
209fn is_uuid(id: &str) -> bool {
210    let hex = |s: &str| s.bytes().all(|b| b.is_ascii_hexdigit());
211    match id.len() {
212        32 => hex(id),
213        36 => id.split('-').map(str::len).eq([8, 4, 4, 4, 12]) && hex(&id.replace('-', "")),
214        _ => false,
215    }
216}
217
218/// The forge's registration token. No `Debug`/`Display` text, no
219/// `Serialize`: it leaves this process only inside [`add`]'s request body.
220pub struct RegistrationToken(Zeroizing<String>);
221
222impl fmt::Debug for RegistrationToken {
223    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224        f.write_str("RegistrationToken([redacted])")
225    }
226}
227
228impl RegistrationToken {
229    /// The token for `target`'s forge, trimmed, when it has that forge's
230    /// shape (LeanCTX Cloud's rule): 20-255 characters, GitLab `glrt-` then
231    /// `A-Za-z0-9_-`, GitHub `A-Za-z0-9` only. The message never contains it.
232    pub fn new(raw: &str, target: &Target) -> Result<Self, String> {
233        let trimmed = raw.trim();
234        if !TOKEN_LEN.contains(&trimmed.len()) {
235            return Err(format!(
236                "the registration token must be {}-{} characters",
237                TOKEN_LEN.start(),
238                TOKEN_LEN.end()
239            ));
240        }
241        let shaped = match target {
242            Target::GitLab { .. } => {
243                trimmed
244                    .strip_prefix(GITLAB_TOKEN_PREFIX)
245                    .is_some_and(|rest| {
246                        rest.bytes()
247                            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-'))
248                    })
249            }
250            Target::GitHub { .. } => trimmed.bytes().all(|b| b.is_ascii_alphanumeric()),
251        };
252        if !shaped {
253            return Err(match target {
254                Target::GitLab { .. } => "the registration token is not a GitLab runner token (glrt- followed by A-Z, a-z, 0-9, _ and -)".into(),
255                Target::GitHub { .. } => "the registration token is not a GitHub runner token (only A-Z, a-z and 0-9)".into(),
256            });
257        }
258        Ok(Self(Zeroizing::new(trimmed.to_owned())))
259    }
260
261    fn expose(&self) -> &str {
262        &self.0
263    }
264}
265
266/// `POST /v1/runners`, without the token (that is added only when sent).
267#[derive(Debug, Clone, PartialEq, Eq)]
268pub struct AddRequest {
269    pub request_id: String,
270    pub name: String,
271    /// The team's org id; absent for a personal runner.
272    pub team: Option<String>,
273    pub target: Target,
274    pub labels: Vec<String>,
275}
276
277/// The wire body: borrows every field, so the token is copied only once,
278/// into the zeroizing buffer [`AddRequest::encoded`] writes.
279#[derive(Serialize)]
280struct Body<'a> {
281    request_id: &'a str,
282    name: &'a str,
283    role: &'static str,
284    forge: &'static str,
285    target: &'a str,
286    labels: &'a [String],
287    #[serde(skip_serializing_if = "Option::is_none")]
288    team: Option<&'a str>,
289    registration_token: &'a str,
290}
291
292impl AddRequest {
293    /// The JSON body with the token, in a buffer wiped when dropped. Its
294    /// room is reserved up front, so it never reallocates (a reallocation
295    /// would leave an unwiped copy behind).
296    fn encoded(&self, token: &RegistrationToken) -> Result<Zeroizing<Vec<u8>>, CloudError> {
297        let mut buffer = Zeroizing::new(Vec::with_capacity(BODY_CAPACITY));
298        let body = Body {
299            request_id: &self.request_id,
300            name: &self.name,
301            role: ROLE_CI_RUNNER,
302            forge: self.target.forge(),
303            target: self.target.target(),
304            labels: &self.labels,
305            team: self.team.as_deref(),
306            registration_token: token.expose(),
307        };
308        serde_json::to_writer(&mut *buffer, &body)
309            .map_err(|e| CloudError::Protocol(format!("encode request: {e}")))?;
310        Ok(buffer)
311    }
312}
313
314/// `GET /v1/runners`, checked. The cloud's `balance` is not read: a runner
315/// costs nothing beyond its computer.
316#[derive(Debug, Clone, PartialEq, Default, Serialize)]
317pub struct RunnerList {
318    /// The rows (computer rows with a `runner` member), secrets cut out.
319    pub runners: Vec<Map<String, Value>>,
320}
321
322/// One exchange with an already encoded JSON body: method, path (under
323/// `/v1`) and body bytes → the HTTP status and the JSON answer.
324pub type RawExchange<'a> = &'a dyn Fn(&str, &str, &[u8]) -> Result<(u16, Value), CloudError>;
325
326/// The raw exchanges of the connected instance (as
327/// [`computers::connected`]): each one through its session, which
328/// refreshes a refused token.
329pub fn connected_raw<'a>(
330    store: &'a CloudStore,
331    config: &'a CloudConfig,
332) -> impl Fn(&str, &str, &[u8]) -> Result<(u16, Value), CloudError> + 'a {
333    move |method, path, body| {
334        let session = crate::scheduler::connected_session(store, config)?;
335        session.with_client(|client| {
336            let (status, answer) =
337                client.send_json_bytes_answer(method, path, body, computers::MAX_ANSWER_BYTES)?;
338            if status == 401 {
339                return Err(CloudError::from_response(status, &answer));
340            }
341            Ok((status, answer))
342        })
343    }
344}
345
346/// `GET /v1/runners`.
347pub fn list(send: Exchange<'_>) -> Result<Answer<RunnerList>, CloudError> {
348    let (status, body) = send("GET", PATH, None)?;
349    computers::classify(status, &body, list_of)
350}
351
352/// `POST /v1/runners`: the bound row (`runner.status` `pending`). The token
353/// is sent in this one body and nowhere else; an answer or error that
354/// repeats it has it cut before anything bounds its text.
355pub fn add(
356    send: RawExchange<'_>,
357    request: &AddRequest,
358    token: &RegistrationToken,
359) -> Result<Answer<Map<String, Value>>, CloudError> {
360    let body = request.encoded(token)?;
361    let result = send("POST", PATH, &body);
362    drop(body);
363    let (status, answer) = result.map_err(|e| scrub_error(e, token))?;
364    answer_of(status, answer, token)
365}
366
367/// The answer of `add`: the token cut from the whole body first, then
368/// classified (which bounds the cloud's texts).
369fn answer_of(
370    status: u16,
371    mut answer: Value,
372    token: &RegistrationToken,
373) -> Result<Answer<Map<String, Value>>, CloudError> {
374    scrub_value(&mut answer, token);
375    computers::classify(status, &answer, row_of).map_err(|e| scrub_error(e, token))
376}
377
378/// `POST /v1/runners/{id}/remove`: the row (`runner.status` `removed`). It
379/// unbinds the runner; the computer stays.
380pub fn remove(
381    send: Exchange<'_>,
382    id: &str,
383    request_id: &str,
384) -> Result<Answer<Map<String, Value>>, CloudError> {
385    if !valid_id(id) {
386        return Err(CloudError::Protocol(format!(
387            "runners: bad id '{}'",
388            printable(id)
389        )));
390    }
391    let path = format!("{PATH}/{id}/remove");
392    let body = json!({ "request_id": request_id });
393    let (status, answer) = send("POST", &path, Some(&body))?;
394    computers::classify(status, &answer, row_of)
395}
396
397fn list_of(body: &Value) -> Result<RunnerList, CloudError> {
398    let rows = body
399        .get("runners")
400        .and_then(Value::as_array)
401        .ok_or_else(|| CloudError::Protocol("runners: no `runners` list".into()))?;
402    Ok(RunnerList {
403        runners: rows
404            .iter()
405            .filter_map(computers::checked_row)
406            .map(without_secrets)
407            .take(computers::MAX_ROWS)
408            .collect(),
409    })
410}
411
412/// A write's answer: the row itself, or `{runner: row}` / `{computer: row}`.
413fn row_of(body: &Value) -> Result<Map<String, Value>, CloudError> {
414    let row = body
415        .get("runner")
416        .filter(|r| r.get("id").is_some())
417        .or_else(|| body.get("computer"))
418        .unwrap_or(body);
419    computers::checked_row(row)
420        .map(without_secrets)
421        .ok_or_else(|| CloudError::Protocol("runners: the answer is not a runner row".into()))
422}
423
424/// `row` without any [`SECRET_KEYS`] member, at any depth.
425fn without_secrets(mut row: Map<String, Value>) -> Map<String, Value> {
426    fn cut(value: &mut Value) {
427        match value {
428            Value::Object(map) => {
429                for key in SECRET_KEYS {
430                    map.remove(key);
431                }
432                map.values_mut().for_each(cut);
433            }
434            Value::Array(items) => items.iter_mut().for_each(cut),
435            _ => {}
436        }
437    }
438    for key in SECRET_KEYS {
439        row.remove(key);
440    }
441    row.values_mut().for_each(cut);
442    row
443}
444
445/// `text` with every occurrence of the token replaced by [`TOKEN_MARK`], and
446/// a cut-off start of the token at its end (at least [`MIN_TOKEN_TAIL`]
447/// characters) as well.
448fn scrub(text: &str, token: &RegistrationToken) -> String {
449    let secret = token.expose();
450    let mut out = text.replace(secret, TOKEN_MARK);
451    // The token is ASCII (checked in `new`), so every prefix is a char boundary.
452    let longest = secret.len().saturating_sub(1).min(out.len());
453    if let Some(cut) = (MIN_TOKEN_TAIL..=longest)
454        .rev()
455        .find(|&n| out.ends_with(&secret[..n]))
456    {
457        out.truncate(out.len() - cut);
458        out.push_str(TOKEN_MARK);
459    }
460    out
461}
462
463fn mentions(text: &str, token: &RegistrationToken) -> bool {
464    scrub(text, token) != text
465}
466
467fn scrub_value(value: &mut Value, token: &RegistrationToken) {
468    match value {
469        Value::String(text) if mentions(text, token) => *text = scrub(text, token),
470        Value::Object(map) => map.values_mut().for_each(|v| scrub_value(v, token)),
471        Value::Array(items) => items.iter_mut().for_each(|v| scrub_value(v, token)),
472        _ => {}
473    }
474}
475
476/// `error` with the token cut from its texts. The variant stays (it decides
477/// the exit and the error code); only a structured variant whose rendered
478/// text still names the token becomes [`CloudError::Protocol`].
479fn scrub_error(error: CloudError, token: &RegistrationToken) -> CloudError {
480    let s = |text: String| scrub(&text, token);
481    match error {
482        CloudError::Offline(text) => CloudError::Offline(s(text)),
483        CloudError::Protocol(text) => CloudError::Protocol(s(text)),
484        CloudError::Config(text) => CloudError::Config(s(text)),
485        CloudError::Local(text) => CloudError::Local(s(text)),
486        CloudError::Refused(text) => CloudError::Refused(s(text)),
487        CloudError::DeviceFlow(text) => CloudError::DeviceFlow(s(text)),
488        CloudError::Server { status, code } => CloudError::Server {
489            status,
490            code: s(code),
491        },
492        CloudError::Task {
493            refusal,
494            number,
495            detail,
496        } => CloudError::Task {
497            refusal,
498            number,
499            detail: detail.map(s),
500        },
501        other => {
502            let text = other.to_string();
503            if mentions(&text, token) {
504                CloudError::Protocol(scrub(&text, token))
505            } else {
506                other
507            }
508        }
509    }
510}
511
512/// `text` with control characters dropped and cut to 200 characters, for
513/// echoing a bad argument.
514fn printable(text: &str) -> String {
515    text.chars().filter(|c| !c.is_control()).take(200).collect()
516}
517
518#[cfg(test)]
519mod tests {
520    use super::*;
521
522    fn gl_token(text: &str) -> RegistrationToken {
523        let target = Target::gitlab("https://gitlab.example.com").expect("gl");
524        RegistrationToken::new(text, &target).expect("token")
525    }
526
527    fn gh_token(text: &str) -> RegistrationToken {
528        let target = Target::github("o/r").expect("gh");
529        RegistrationToken::new(text, &target).expect("token")
530    }
531
532    #[test]
533    fn gitlab_targets_are_https_origins_only() {
534        assert_eq!(
535            Target::gitlab("https://GitLab.Example.com/").expect("origin"),
536            Target::GitLab {
537                origin: "https://gitlab.example.com".into()
538            }
539        );
540        assert!(Target::gitlab("https://gitlab.example.com:8443").is_ok());
541        for bad in [
542            "http://gitlab.example.com",
543            "https://gitlab.example.com/group/project",
544            "https://user:pw@gitlab.example.com",
545            "https://gitlab.example.com?x=1",
546            "https://gitlab.example.com:0",
547            "https://-bad.example.com",
548            "gitlab.example.com",
549        ] {
550            assert!(Target::gitlab(bad).is_err(), "{bad}");
551        }
552        let message = Target::gitlab("https://user:secret@x.example").expect_err("refused");
553        assert!(message.contains("no credentials"));
554    }
555
556    #[test]
557    fn github_targets_are_owner_and_repo() {
558        assert!(Target::github("leanctx/lean-ctx").is_ok());
559        assert!(Target::github("a/b.c_d-e").is_ok());
560        for bad in [
561            "leanctx", "-x/y", "x-/y", "x/..", "x/.", "x/y/z", "x/", "/y",
562        ] {
563            assert!(Target::github(bad).is_err(), "{bad}");
564        }
565    }
566
567    #[test]
568    fn default_names_follow_the_computer_name_rule() {
569        let gl = Target::gitlab("https://gitlab.pounce.ch").expect("gl");
570        assert_eq!(gl.default_name(), "gl-gitlab");
571        let gh = Target::github("LeanCTX/Lean.Ctx_Repo").expect("gh");
572        assert_eq!(gh.default_name(), "gh-lean-ctx-repo");
573        let long = Target::github(&format!("o/{}", "a".repeat(80))).expect("gh");
574        assert_eq!(long.default_name().len(), 32);
575        let trailing = Target::github("o/abcdefghijklmnopqrstuvwxyzabc-").expect("gh");
576        assert!(!trailing.default_name().ends_with('-'));
577    }
578
579    #[test]
580    fn tokens_have_no_text_and_the_forges_shape() {
581        let t = gl_token("  glrt-AbCdEfGh12345678_x-y\n");
582        assert_eq!(t.expose(), "glrt-AbCdEfGh12345678_x-y");
583        assert_eq!(format!("{t:?}"), "RegistrationToken([redacted])");
584        let gh = gh_token("AABBCCDDEEFF0011223344");
585        assert_eq!(gh.expose(), "AABBCCDDEEFF0011223344");
586        let gitlab = Target::gitlab("https://gitlab.example.com").expect("gl");
587        let github = Target::github("o/r").expect("gh");
588        let long = format!("glrt-{}", "x".repeat(251));
589        for (bad, target) in [
590            ("glrt-short", &gitlab),
591            ("glrt-has space inside-12345", &gitlab),
592            ("AABBCCDDEEFF0011223344", &gitlab),
593            (long.as_str(), &gitlab),
594            ("glrt-AbCdEfGh12345678", &github),
595            ("AABBCCDD-EEFF0011223344", &github),
596            ("AABBCCDDEEFF00112", &github),
597        ] {
598            let err = RegistrationToken::new(bad, target).expect_err("bad");
599            assert!(!err.contains(bad.trim()), "the message repeats the input");
600        }
601        let edge = format!("glrt-{}", "x".repeat(250));
602        assert!(RegistrationToken::new(&edge, &gitlab).is_ok());
603    }
604
605    #[test]
606    fn the_add_body_carries_the_token_and_the_target() {
607        let request = AddRequest {
608            request_id: "req_12345678".into(),
609            name: "gh-lean-ctx".into(),
610            team: Some("org_acme".into()),
611            target: Target::github("leanctx/lean-ctx").expect("gh"),
612            labels: vec!["linux".into()],
613        };
614        let t = gh_token("AABBCCDDEEFF0011223344");
615        let encoded = request.encoded(&t).expect("encoded");
616        assert!(encoded.capacity() >= BODY_CAPACITY, "the buffer never grew");
617        let body: Value = serde_json::from_slice(&encoded).expect("json");
618        assert_eq!(body["role"], ROLE_CI_RUNNER);
619        assert_eq!(body["forge"], "github");
620        assert_eq!(body["target"], "leanctx/lean-ctx");
621        assert_eq!(body["registration_token"], "AABBCCDDEEFF0011223344");
622        assert_eq!(body["team"], "org_acme");
623        assert_eq!(body["labels"], json!(["linux"]));
624        let personal = AddRequest {
625            team: None,
626            ..request
627        };
628        let body: Value =
629            serde_json::from_slice(&personal.encoded(&t).expect("encoded")).expect("json");
630        assert!(body.get("team").is_none());
631        assert!(!format!("{personal:?}").contains("AABBCCDD"));
632    }
633
634    #[test]
635    fn add_sends_the_encoded_body_once_and_scrubs_the_answer() {
636        let t = gl_token("glrt-SECRET-1234567890");
637        let request = AddRequest {
638            request_id: "req_12345678".into(),
639            name: "gl-x".into(),
640            team: None,
641            target: Target::gitlab("https://gitlab.example.com").expect("gl"),
642            labels: vec![],
643        };
644        let calls = std::cell::Cell::new(0);
645        let send = |method: &str, path: &str, body: &[u8]| {
646            calls.set(calls.get() + 1);
647            assert_eq!((method, path), ("POST", "/runners"));
648            let sent: Value = serde_json::from_slice(body).expect("json");
649            assert_eq!(sent["registration_token"], "glrt-SECRET-1234567890");
650            Ok((
651                201,
652                json!({ "runner": { "id": "cmp_9", "name": "gl-x", "state": "running",
653                    "runner": { "status": "pending" },
654                    "note": "registered glrt-SECRET-1234567890" } }),
655            ))
656        };
657        let Answer::Done(row) = add(&send, &request, &t).expect("ok") else {
658            panic!("not done");
659        };
660        assert_eq!(calls.get(), 1);
661        assert_eq!(row["note"], "registered [token]");
662        assert_eq!(row["runner"]["status"], "pending");
663    }
664
665    #[test]
666    fn rows_lose_secret_members_at_any_depth() {
667        let body = json!({
668            "runners": [{
669                "id": "cmp_1", "name": "gh-x", "state": "running", "role": "general",
670                "token": "t1",
671                "runner": { "status": "registered", "registration_token": "t2",
672                            "steps": [{ "token": "t3", "ok": true }] }
673            }, { "name": "no id" }],
674            "balance": { "usd": 3.0 }
675        });
676        let Answer::Done(list) = computers::classify(200, &body, list_of).expect("ok") else {
677            panic!("not done");
678        };
679        assert_eq!(list.runners.len(), 1);
680        let text = serde_json::to_string(&list).expect("json");
681        for secret in ["t1", "t2", "t3"] {
682            assert!(!text.contains(&format!("\"{secret}\"")), "{text}");
683        }
684        assert!(
685            !text.contains("balance"),
686            "a runner list carries no balance"
687        );
688        assert_eq!(list.runners[0]["runner"]["steps"][0]["ok"], true);
689    }
690
691    #[test]
692    fn a_write_answer_is_the_row_or_a_wrapped_row() {
693        let row = json!({ "id": "cmp_2", "name": "gl-x", "state": "running",
694                          "runner": { "status": "pending" } });
695        assert_eq!(row_of(&row).expect("row")["id"], "cmp_2");
696        assert_eq!(
697            row_of(&json!({ "runner": row.clone() })).expect("row")["id"],
698            "cmp_2"
699        );
700        assert_eq!(
701            row_of(&json!({ "computer": row })).expect("row")["id"],
702            "cmp_2"
703        );
704        assert!(row_of(&json!({ "ok": true })).is_err());
705    }
706
707    #[test]
708    fn refusals_are_scrubbed_before_they_are_bounded() {
709        let t = gl_token("glrt-SECRET-1234567890");
710        let body = json!({ "error": { "code": "runner_token_rejected",
711            "message": "GitLab refused glrt-SECRET-1234567890 for this project." } });
712        let Answer::Refused(refusal) = answer_of(422, body, &t).expect("refusal") else {
713            panic!("not refused");
714        };
715        assert_eq!(refusal.code, "runner_token_rejected");
716        assert_eq!(
717            refusal.message.as_deref(),
718            Some("GitLab refused [token] for this project.")
719        );
720        // The token straddles the 500-character bound: scrubbed first, no
721        // start of it survives the cut.
722        let long = format!("{} glrt-SECRET-1234567890 tail", "x".repeat(490));
723        let body = json!({ "error": { "code": "runner_token_rejected", "message": long } });
724        let Answer::Refused(refusal) = answer_of(422, body, &t).expect("refusal") else {
725            panic!("not refused");
726        };
727        let message = refusal.message.expect("message");
728        assert!(!message.contains("glrt-SECRE"), "{message}");
729    }
730
731    #[test]
732    fn a_cut_off_token_at_the_end_of_a_text_is_masked() {
733        let t = gl_token("glrt-SECRET-1234567890");
734        assert_eq!(scrub("sent glrt-SECRET-12", &t), "sent [token]");
735        assert_eq!(
736            scrub("sent glrt-SE", &t),
737            "sent glrt-SE",
738            "too short to mask"
739        );
740        assert_eq!(scrub("no token here", &t), "no token here");
741    }
742
743    #[test]
744    fn scrubbed_errors_keep_their_class() {
745        let t = gl_token("glrt-SECRET-1234567890");
746        let offline = scrub_error(
747            CloudError::Offline("connect glrt-SECRET-1234567890".into()),
748            &t,
749        );
750        assert!(matches!(&offline, CloudError::Offline(text) if text == "connect [token]"));
751        let server = scrub_error(
752            CloudError::Server {
753                status: 502,
754                code: "bad glrt-SECRET-1234567890".into(),
755            },
756            &t,
757        );
758        assert!(matches!(server, CloudError::Server { status: 502, .. }));
759        assert!(!server.to_string().contains("SECRET"));
760        assert!(matches!(
761            scrub_error(CloudError::NotConnected, &t),
762            CloudError::NotConnected
763        ));
764    }
765
766    #[test]
767    fn labels_are_checked() {
768        assert!(valid_label("linux-x64"));
769        assert!(valid_label("self_hosted.1"));
770        assert!(!valid_label(""));
771        assert!(!valid_label("has space"));
772        assert!(!valid_label(&"a".repeat(65)));
773    }
774}