use std::io::{BufRead, Read};
use serde::Serialize;
use serde_json::{Map, Value};
use zeroize::Zeroizing;
use lean_ctx_cloud::CloudStore;
use lean_ctx_cloud::computers::{self, Answer, Refusal};
use lean_ctx_cloud::config::CloudConfig;
use lean_ctx_cloud::runners::{
self, AddRequest, MAX_LABELS, RegistrationToken, RunnerList, Target,
};
use lean_ctx_cloud::state::InstanceRecord;
use super::Args;
use super::cloud;
use super::ssh;
use crate::cli::local_read::{self, Code, Failure};
pub(super) const KIND_LIST: &str = "cloud.runners";
pub(super) const KIND_ACK: &str = "cloud.runner.ack";
const MAX_TOKEN_LINE: u64 = 1024;
pub(super) const HELP: &str = "\
lean-ctx cloud computer runner — CI runners for GitHub and GitLab on LeanCTX computers
USAGE:
lean-ctx cloud computer runner add (--gitlab https://<host> | --github <owner/repo>)
[--name <name>] [--label <label>]… [--team <team id> | --personal]
[--token-stdin] [--request-id <id>] [--yes] [--json]
lean-ctx cloud computer runner list [--json]
lean-ctx cloud computer runner remove <name|id> [--request-id <id>] [--yes] [--json]
add Bind a runner to an existing LeanCTX computer of your team (--team, or
the team this machine is connected to) or of your account (--personal).
It registers with your GitLab server (the runner token decides the
project or group) or your GitHub repository. --label sets runner labels
(GitHub) or tags (GitLab). The default name is gl-<host> or gh-<repo>.
The computer keeps its role and its price; the runner adds no cost of
its own. add runs only with --yes; without it the command says what it
would do and exits 1 (confirmation_required).
The registration token is read after --yes: from standard input with
--token-stdin, else at a hidden prompt. It goes only to the cloud over
TLS, is never printed, logged or stored, and is never a command-line flag.
Pass it from a file or a secret store (--token-stdin < file), not with
`echo <token> |`, which can leave it in your shell history.
list Your runners; --json prints cloud.runners.
remove Unbind the runner and deregister it from the forge; the computer stays
(needs --yes). --json prints cloud.runner.ack.
The cloud decides who may do this and on which computer.
";
pub(super) fn run(args: &Args) {
let json = args.json();
let verb = args.positionals.get(1).map_or("help", String::as_str);
if verb == "help" {
print!("{HELP}");
return;
}
let result = match verb {
"add" | "list" | "remove" => cloud::connected().and_then(|(store, config, instance)| {
let ctx = Ctx {
store: &store,
config: &config,
instance: &instance,
args,
};
match verb {
"add" => add(&ctx),
"list" => list(&ctx),
_ => remove(&ctx),
}
}),
other => Err(Failure::invalid(format!(
"unknown runner subcommand '{other}' (add, list, remove)"
))),
};
if let Err(failure) = result {
if json {
local_read::fail(&failure);
}
eprintln!("cloud computer runner: {}", failure.message);
std::process::exit(failure.code.exit_status());
}
}
struct Ctx<'a> {
store: &'a CloudStore,
config: &'a CloudConfig,
instance: &'a InstanceRecord,
args: &'a Args,
}
#[derive(Debug, Serialize, PartialEq)]
struct ListDoc {
available: bool,
runners: Vec<Map<String, Value>>,
}
fn list_doc(answer: Answer<RunnerList>) -> Result<ListDoc, Failure> {
match answer {
Answer::Done(list) => Ok(ListDoc {
available: true,
runners: list.runners,
}),
Answer::NotOffered => Ok(ListDoc {
available: false,
runners: Vec::new(),
}),
Answer::Refused(refusal) => Err(refused(&refusal)),
}
}
fn fetch_list(ctx: &Ctx<'_>) -> Result<RunnerList, Failure> {
let send = computers::connected(ctx.store, ctx.config);
match runners::list(&send).map_err(Failure::from)? {
Answer::Done(list) => Ok(list),
Answer::NotOffered => Err(not_offered()),
Answer::Refused(refusal) => Err(refused(&refusal)),
}
}
fn list(ctx: &Ctx<'_>) -> Result<(), Failure> {
let send = computers::connected(ctx.store, ctx.config);
let doc = list_doc(runners::list(&send).map_err(Failure::from)?)?;
if ctx.args.json() {
local_read::emit(KIND_LIST, || Ok(doc));
return Ok(());
}
if !doc.available {
println!("The Cloud does not offer CI runners yet.");
return Ok(());
}
if doc.runners.is_empty() {
println!(
"no CI runner yet (lean-ctx cloud computer runner add --github <owner/repo> | --gitlab https://<host>)"
);
}
for row in &doc.runners {
let text = |k: &str| row.get(k).and_then(Value::as_str).unwrap_or("-");
let runner = |k: &str| {
row.get("runner")
.and_then(|r| r.get(k))
.and_then(Value::as_str)
.unwrap_or("-")
};
println!(
"{:<20} {:<7} {:<32} {:<12} {:<14} {}",
text("name"),
runner("forge"),
runner("target"),
runner("status"),
text("state"),
text("id")
);
}
Ok(())
}
#[derive(Debug, Serialize, PartialEq)]
struct AckDoc {
action: &'static str,
id: Value,
name: Value,
state: Value,
role: Value,
forge: Value,
target: Value,
status: Value,
registered: Value,
request_id: String,
}
fn ack(
action: &'static str,
row: &Map<String, Value>,
request_id: String,
target: Option<&Target>,
) -> AckDoc {
let pick = |k: &str| row.get(k).cloned().unwrap_or(Value::Null);
let runner = |k: &str| {
row.get("runner")
.and_then(|r| r.get(k))
.cloned()
.unwrap_or(Value::Null)
};
let or_sent = |value: Value, sent: Option<&str>| match (value, sent) {
(Value::Null, Some(sent)) => Value::String(sent.to_owned()),
(value, _) => value,
};
AckDoc {
action,
id: pick("id"),
name: pick("name"),
state: pick("state"),
role: pick("role"),
forge: or_sent(runner("forge"), target.map(Target::forge)),
target: or_sent(runner("target"), target.map(Target::target)),
status: runner("status"),
registered: runner("registered"),
request_id,
}
}
fn target_of(args: &Args) -> Result<Target, Failure> {
match (args.value("--gitlab"), args.value("--github")) {
(Some(_), Some(_)) => Err(Failure::invalid("give --gitlab or --github, not both")),
(Some(url), None) => Target::gitlab(url).map_err(Failure::invalid),
(None, Some(repo)) => Target::github(repo).map_err(Failure::invalid),
(None, None) => Err(Failure::invalid(
"name the forge: --gitlab https://<host> or --github <owner/repo>",
)),
}
}
fn labels_of(args: &Args) -> Result<Vec<String>, Failure> {
let mut labels: Vec<String> = Vec::new();
for label in args.all("--label") {
if !runners::valid_label(label) {
return Err(Failure::invalid(format!(
"--label '{}': use 1-64 of A-Z, a-z, 0-9, _, . and -",
label
.chars()
.filter(|c| !c.is_control())
.take(80)
.collect::<String>()
)));
}
if !labels.iter().any(|l| l == label) {
labels.push(label.to_owned());
}
}
if labels.len() > MAX_LABELS {
return Err(Failure::invalid(format!(
"at most {MAX_LABELS} labels per runner"
)));
}
Ok(labels)
}
fn scope_of(args: &Args, instance: &InstanceRecord) -> Result<Option<String>, Failure> {
match (args.has("--personal"), args.value("--team")) {
(true, Some(_)) => Err(Failure::invalid("give --team or --personal, not both")),
(true, None) => Ok(None),
(false, Some(team)) => {
let ok = (1..=64).contains(&team.len())
&& team
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-'));
if ok {
Ok(Some(team.to_owned()))
} else {
Err(Failure::invalid(
"--team: give the team's id (or its slug), 1-64 of A-Z, a-z, 0-9, _ and -",
))
}
}
(false, None) if instance.org_kind.as_deref() == Some("personal") => Ok(None),
(false, None) => Ok(Some(instance.org_id.clone())),
}
}
fn request_id(args: &Args) -> Result<String, Failure> {
match args.value("--request-id") {
Some(id) if computers::valid_request_id(id) => Ok(id.to_owned()),
Some(_) => Err(Failure::invalid(
"--request-id: use 8-64 of A-Z, a-z, 0-9, _ and -",
)),
None => Ok(computers::new_request_id()),
}
}
fn confirmation(what: String) -> Failure {
Failure::new(Code::ConfirmationRequired, what)
}
fn scope_text(team: Option<&str>, instance: &InstanceRecord) -> String {
match team {
None => "your account".to_owned(),
Some(team) if team == instance.org_id => format!("team {}", instance.org_name),
Some(team) => format!("team {team}"),
}
}
fn add(ctx: &Ctx<'_>) -> Result<(), Failure> {
let target = target_of(ctx.args)?;
let labels = labels_of(ctx.args)?;
let name = match ctx.args.value("--name") {
Some(name) => name.to_owned(),
None => target.default_name(),
};
ssh::check_name(&name).map_err(Failure::invalid)?;
let team = scope_of(ctx.args, ctx.instance)?;
let request_id = request_id(ctx.args)?;
if !ctx.args.yes() {
return Err(confirmation(format!(
"add runner '{name}' for {} {}: binds it to the existing LeanCTX computer of {}; the computer keeps its role and price. Nothing was done; repeat with --yes to add it.",
target.forge(),
target.target(),
scope_text(team.as_deref(), ctx.instance)
)));
}
let token = read_token(ctx.args.has("--token-stdin"), &target)?;
let request = AddRequest {
request_id: request_id.clone(),
name,
team,
target,
labels,
};
let send = runners::connected_raw(ctx.store, ctx.config);
let answer = runners::add(&send, &request, &token).map_err(Failure::from)?;
drop(token);
match answer {
Answer::Done(row) => finish(ctx, &ack("add", &row, request_id, Some(&request.target))),
Answer::NotOffered => Err(not_offered()),
Answer::Refused(refusal) => Err(refused(&refusal)),
}
}
fn remove(ctx: &Ctx<'_>) -> Result<(), Failure> {
let wanted = ctx
.args
.positionals
.get(2)
.map(String::as_str)
.ok_or_else(|| Failure::invalid("name the runner (or give its id)"))?;
let by_id = runners::valid_id(wanted);
if !by_id {
ssh::check_name(wanted).map_err(Failure::invalid)?;
}
let request_id = request_id(ctx.args)?;
if !ctx.args.yes() {
return Err(confirmation(format!(
"remove runner '{wanted}': deregisters it from the forge and unbinds it; the computer stays. Nothing was done; repeat with --yes to remove it."
)));
}
let id = if by_id {
wanted.to_owned()
} else {
let list = fetch_list(ctx)?;
let row = cloud::pick(&list.runners, wanted, ctx.instance)?;
row.get("id")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned()
};
let send = computers::connected(ctx.store, ctx.config);
match runners::remove(&send, &id, &request_id).map_err(Failure::from)? {
Answer::Done(answer) => finish(ctx, &ack("remove", &answer, request_id, None)),
Answer::NotOffered => Err(not_offered()),
Answer::Refused(refusal) => Err(refused(&refusal)),
}
}
fn read_token(from_stdin: bool, target: &Target) -> Result<RegistrationToken, Failure> {
let raw = if from_stdin {
let mut line = Zeroizing::new(String::new());
std::io::stdin()
.lock()
.take(MAX_TOKEN_LINE)
.read_line(&mut line)
.map_err(|e| Failure::invalid(format!("cannot read the token from stdin: {e}")))?;
line
} else if lean_ctx::core::host_env::stdin_is_terminal() {
Zeroizing::new(
rpassword::prompt_password("Runner registration token (input hidden): ").map_err(
|e| Failure::invalid(format!("cannot read the token at the prompt: {e}")),
)?,
)
} else {
return Err(Failure::invalid(
"give the registration token on standard input with --token-stdin (no terminal for a hidden prompt)",
));
};
token_of(&raw, target)
}
fn token_of(raw: &str, target: &Target) -> Result<RegistrationToken, Failure> {
RegistrationToken::new(raw, target).map_err(Failure::invalid)
}
fn finish(ctx: &Ctx<'_>, doc: &AckDoc) -> Result<(), Failure> {
if ctx.args.json() {
local_read::emit(KIND_ACK, || Ok(doc));
return Ok(());
}
let text = |v: &Value| v.as_str().unwrap_or("-").to_owned();
println!(
"{}: runner '{}' ({}) for {} {} is {}",
doc.action,
text(&doc.name),
text(&doc.id),
text(&doc.forge),
text(&doc.target),
text(&doc.status)
);
Ok(())
}
fn refused(refusal: &Refusal) -> Failure {
let code = match refusal.code.as_str() {
"step_up_required" => Some(Code::StepUpRequired),
"runner_exists" => Some(Code::ComputerExists),
"runner_token_rejected" => Some(Code::InvalidField),
_ => None,
};
let mut failure = cloud::refused(refusal);
if let Some(code) = code {
failure.code = code;
}
failure
}
fn not_offered() -> Failure {
Failure::new(Code::NotOffered, "The Cloud does not offer CI runners yet.")
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn args(raw: &[&str]) -> Args {
Args::parse(&raw.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>()).expect("args")
}
fn object(value: Value) -> Map<String, Value> {
let Value::Object(map) = value else {
panic!("not an object: {value}");
};
map
}
fn instance(kind: &str) -> InstanceRecord {
serde_json::from_value(json!({
"instance_id": "inst_1", "org_id": "8f0c1a52-1111-4222-8333-944455556666",
"org_name": "Acme", "label": "mac", "url": "https://cloud.example",
"org_salt_id": "salt", "enrolled_at": "2026-11-01T00:00:00Z",
"org_kind": kind
}))
.expect("instance")
}
fn refusal(status: u16, code: &str, reason: Option<&str>) -> Refusal {
Refusal {
status,
code: code.to_owned(),
message: Some("no".to_owned()),
next_step: None,
retry_after_s: None,
details: None,
reason: reason.map(str::to_owned),
}
}
#[test]
fn the_target_is_exactly_one_forge() {
let gl = target_of(&args(&[
"runner",
"add",
"--gitlab",
"https://gitlab.example.com",
]))
.expect("gitlab");
assert_eq!(gl.forge(), "gitlab");
let gh = target_of(&args(&["runner", "add", "--github", "leanctx/lean-ctx"])).expect("gh");
assert_eq!(gh.target(), "leanctx/lean-ctx");
let both = target_of(&args(&[
"runner",
"add",
"--gitlab",
"https://g.example",
"--github",
"o/r",
]))
.expect_err("both");
assert_eq!(both.code, Code::InvalidArgument);
assert!(target_of(&args(&["runner", "add"])).is_err());
assert!(target_of(&args(&["runner", "add", "--gitlab", "http://g.example"])).is_err());
}
#[test]
fn a_token_is_never_a_flag() {
for raw in [
vec!["runner", "add", "--token", "glrt-SECRET-123456"],
vec!["runner", "add", "--token=glrt-SECRET-123456"],
] {
let raw: Vec<String> = raw.iter().map(|s| (*s).to_owned()).collect();
let err = Args::parse(&raw).expect_err("refused");
assert!(!err.contains("SECRET"), "{err}");
}
}
#[test]
fn a_bad_token_message_never_repeats_it() {
let gitlab = Target::gitlab("https://gitlab.example.com").expect("gl");
let failure = token_of("glrt SECRET with spaces", &gitlab).expect_err("bad");
assert_eq!(failure.code, Code::InvalidArgument);
assert!(!failure.message.contains("SECRET"));
assert!(token_of("glrt-SECRET-1234567890\n", &gitlab).is_ok());
let github = Target::github("o/r").expect("gh");
assert!(token_of("glrt-SECRET-1234567890", &github).is_err());
}
#[test]
fn labels_are_checked_and_deduplicated() {
let labels = labels_of(&args(&[
"runner", "add", "--label", "linux", "--label", "x64", "--label", "linux",
]))
.expect("labels");
assert_eq!(labels, ["linux", "x64"]);
assert!(labels_of(&args(&["runner", "add", "--label", "a b"])).is_err());
let many: Vec<String> = (0..=MAX_LABELS)
.flat_map(|i| ["--label".to_owned(), format!("l{i}")])
.collect();
let mut raw = vec!["runner".to_owned(), "add".to_owned()];
raw.extend(many);
assert!(labels_of(&Args::parse(&raw).expect("args")).is_err());
}
#[test]
fn the_scope_is_personal_a_team_or_the_connected_one() {
let team = instance("team");
let personal = instance("personal");
assert_eq!(
scope_of(&args(&["runner", "add", "--personal"]), &team).expect("personal"),
None
);
assert_eq!(
scope_of(&args(&["runner", "add", "--team", "acme-dev"]), &personal).expect("slug"),
Some("acme-dev".to_owned())
);
assert_eq!(
scope_of(&args(&["runner", "add"]), &team).expect("connected"),
Some(team.org_id.clone())
);
assert_eq!(
scope_of(&args(&["runner", "add"]), &personal).expect("mine"),
None
);
assert!(
scope_of(
&args(&["runner", "add", "--personal", "--team", "x"]),
&team
)
.is_err()
);
assert!(scope_of(&args(&["runner", "add", "--team", "a/b"]), &team).is_err());
assert_eq!(scope_text(Some(&team.org_id), &team), "team Acme");
assert_eq!(scope_text(None, &team), "your account");
}
#[test]
fn the_ack_names_the_runner_status_and_carries_no_billing() {
let row = object(json!({
"id": "cmp_9", "name": "gh-lean-ctx", "state": "running", "role": "general",
"runner": { "status": "pending", "registered": false }
}));
let target = Target::github("leanctx/lean-ctx").expect("gh");
let doc = ack("add", &row, "req_12345678".into(), Some(&target));
let value = serde_json::to_value(&doc).expect("json");
assert_eq!(value["forge"], "github");
assert_eq!(value["target"], "leanctx/lean-ctx");
assert_eq!(value["status"], "pending");
assert_eq!(value["registered"], false);
assert!(value.get("billing").is_none());
let gone = object(
json!({ "id": "cmp_9", "name": "gh-lean-ctx", "state": "running",
"runner": { "status": "removed" } }),
);
let value =
serde_json::to_value(ack("remove", &gone, "req_12345678".into(), None)).expect("json");
assert_eq!(value["status"], "removed");
assert_eq!(value["state"], "running", "the computer stays");
assert_eq!(value["forge"], Value::Null);
}
#[test]
fn runner_refusals_have_their_codes() {
assert_eq!(
refused(&refusal(403, "step_up_required", None)).code,
Code::StepUpRequired
);
assert_eq!(
refused(&refusal(409, "runner_exists", None)).code,
Code::ComputerExists
);
assert_eq!(
refused(&refusal(422, "runner_token_rejected", None)).code,
Code::InvalidField
);
assert_eq!(
refused(&refusal(409, "invalid_state", Some("runner_limit"))).code,
Code::InvalidState
);
assert_eq!(
refused(&refusal(404, "no_computer", None)).code,
Code::NoComputer
);
let failure = refused(&refusal(403, "step_up_required", None));
assert!(
failure.message.contains("step_up_required"),
"{}",
failure.message
);
assert_eq!(Code::StepUpRequired.as_str(), "step_up_required");
assert_eq!(not_offered().code, Code::NotOffered);
}
#[test]
fn a_cloud_without_runners_lists_none_and_no_balance() {
let doc = list_doc(Answer::NotOffered).expect("doc");
assert!(!doc.available);
assert!(doc.runners.is_empty());
let done = list_doc(Answer::Done(RunnerList {
runners: vec![object(
json!({ "id": "cmp_1", "name": "gl-x", "state": "running" }),
)],
}))
.expect("doc");
assert!(done.available);
assert_eq!(done.runners.len(), 1);
let value = serde_json::to_value(&done).expect("json");
assert!(value.get("balance").is_none());
assert!(value.get("as_of").is_none());
}
}