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;
const PATH: &str = "/runners";
pub const ROLE_CI_RUNNER: &str = "ci_runner";
pub const MAX_LABELS: usize = 16;
const SECRET_KEYS: [&str; 2] = ["registration_token", "token"];
const TOKEN_MARK: &str = "[token]";
const MIN_TOKEN_TAIL: usize = 8;
const BODY_CAPACITY: usize = 16 * 1024;
const TOKEN_LEN: std::ops::RangeInclusive<usize> = 20..=255;
const GITLAB_TOKEN_PREFIX: &str = "glrt-";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Target {
GitLab { origin: String },
GitHub { repo: String },
}
impl Target {
#[must_use]
pub fn forge(&self) -> &'static str {
match self {
Self::GitLab { .. } => "gitlab",
Self::GitHub { .. } => "github",
}
}
#[must_use]
pub fn target(&self) -> &str {
match self {
Self::GitLab { origin } => origin,
Self::GitHub { repo } => repo,
}
}
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()),
})
}
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()
}
}
#[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
}
}
#[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'-'))
}
#[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,
}
}
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 {
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
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddRequest {
pub request_id: String,
pub name: String,
pub team: Option<String>,
pub target: Target,
pub labels: Vec<String>,
}
#[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 {
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)
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize)]
pub struct RunnerList {
pub runners: Vec<Map<String, Value>>,
}
pub type RawExchange<'a> = &'a dyn Fn(&str, &str, &[u8]) -> Result<(u16, Value), CloudError>;
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))
})
}
}
pub fn list(send: Exchange<'_>) -> Result<Answer<RunnerList>, CloudError> {
let (status, body) = send("GET", PATH, None)?;
computers::classify(status, &body, list_of)
}
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)
}
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))
}
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(),
})
}
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()))
}
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
}
fn scrub(text: &str, token: &RegistrationToken) -> String {
let secret = token.expose();
let mut out = text.replace(secret, TOKEN_MARK);
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)),
_ => {}
}
}
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
}
}
}
}
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.")
);
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)));
}
}