diff --git a/pkgs/fleet/Cargo.lock b/pkgs/fleet/Cargo.lock index fba3886b5d..1714192d85 100644 --- a/pkgs/fleet/Cargo.lock +++ b/pkgs/fleet/Cargo.lock @@ -729,6 +729,7 @@ dependencies = [ "proptest", "rusqlite", "serde_json", + "sha2", "ureq", ] @@ -853,6 +854,7 @@ dependencies = [ "fleet-secrets", "libc", "proptest", + "ring", "rusqlite", "serde", "serde_json", diff --git a/pkgs/fleet/README.md b/pkgs/fleet/README.md index 6ffdae71ea..ee93818128 100644 --- a/pkgs/fleet/README.md +++ b/pkgs/fleet/README.md @@ -304,7 +304,8 @@ and every build compiles it, so no build can know a domain another build forgot. The registered domains are `fleet queue`, `fleet serve`, `fleet proxy`, `fleet dispatch`, `fleet dispatch-test`, `fleet secrets`, `fleet gh`, `fleet bridge`, `fleet agent`, -`fleet shell`, `fleet search`, `fleet laptop-agent` and `fleet cert`, and the +`fleet shell`, `fleet search`, `fleet laptop-agent`, `fleet cert` and +`fleet actions`, and the laptop route forms (#13717): `fleet laptop` (tier T0, the generic tiered command), `fleet commander` (T1), `fleet http` (T2) and `fleet ssh` (T3), plus the diff --git a/pkgs/fleet/book/SUMMARY.md b/pkgs/fleet/book/SUMMARY.md index 5b61eb9298..3987220da3 100644 --- a/pkgs/fleet/book/SUMMARY.md +++ b/pkgs/fleet/book/SUMMARY.md @@ -37,6 +37,7 @@ - [fleet search](reference/search.md) - [fleet laptop-agent](reference/laptop-agent.md) - [fleet laptop route forms](reference/laptop-route-forms.md) +- [fleet actions](reference/actions.md) - [Tutorial: enrol a new seat](tutorials/enrol-a-seat.md) - [Tutorial: claim and complete a queue task](tutorials/claim-and-complete.md) diff --git a/pkgs/fleet/book/reference/actions.md b/pkgs/fleet/book/reference/actions.md new file mode 100644 index 0000000000..9d4d97fd4a --- /dev/null +++ b/pkgs/fleet/book/reference/actions.md @@ -0,0 +1,92 @@ +# fleet actions + +Live short-lived exec sessions inside GitHub Actions runners +(#13774), coordinator-handed-off. A seat opens a session at the +queue broker (the coordinator), dispatches the `fleet-exec.yml` +workflow in `dezren39/fleet`, and binds the resulting run — the +**handoff** is the session handle plus the portable +`OWNER/REPO#RUN_ID` form and the run attempt. Commands then run +on the runner with their IO streamed back through the broker; +files leave through the workflow artifact and, when configured, +R2. Nothing connection-shaped is ever printed: the workflow +inputs carry only the handle and non-secret parameters, and the +runner proves its run membership to the broker with the job's +GitHub OIDC token, verified against GitHub's JWKS with its +`repository`, `job_workflow_ref`, `run_id` and `run_attempt` +claims bound to the session row. + +## The lease + +Every session carries two clocks, both enforced by the broker +and by the runner-side agent (which exits at expiry even if +partitioned from the broker): + +- the **lease** — set by `start --timeout`, required, no default; + renewable through the coordinator, clamped at the max; +- the **max lifespan** — `--max-lifespan`, default 30 min, + ceiling 2 h (the fleet leg cap). Past it, only an **emergency + extension** helps: `exec extend` records the request and the + broker raises a needs-drew alert (source `fleet-actions-exec`); + Drew's approve/deny returns through `exec decide`, and approval + adds up to +30 min to the max and the lease. While a decision + is pending the session holds a 300 s grace past its lease. + +## Commands + +- `fleet actions exec start --repo OWNER/REPO --timeout S + [--max-lifespan S] [--ref R] [--target-repo OWNER/REPO] + [--hide-logs] [--detach] [--broker-url URL]` — open, claim + (the #13765 coordinator claim is attempted first; while those + verbs are not live the session proceeds on the singular path + and the output names it via `placement_path`), dispatch, bind, + print the handoff, then attach unless `--detach`. `--repo` is + the workflow host repo (default `dezren39/fleet`); sessions are + recorded in the local store under the state dir so the + portable form resolves later. +- `fleet actions exec run [--timeout S] -- ` — + enqueue one command, stream its output, exit with its code. +- `fleet actions exec attach ` / `watch ` — stream the + session's IO after handoff; `watch` also reports the run and + session status. +- `fleet actions exec renew --timeout S` — extend the + lease within the max. +- `fleet actions exec extend [--minutes M] [--reason T]` — + request the emergency extension (raises the alert). +- `fleet actions exec decide --approve|--deny` — record + Drew's answer. +- `fleet actions exec close ` — close the session. +- `fleet actions agent …` — the runner half, invoked by the + `fleet-exec-session` composite action in `dezren39/fleet`: it + registers with the OIDC token, long-polls the broker, executes + commands in the workdir, streams IO back, installs + `fleet-exec-put` on the session PATH, and enforces the lease + locally. +- `fleet actions put ` — the egress helper: copy the file + into the session outbox (uploaded as the run's + `fleet-exec-out` artifact) and, when the workflow populated the + `FLEET_EXEC_R2_*` environment from masked repo secrets, PUT it + to R2 under `fleet-exec//` with a SigV4 signature. + +## Log visibility + +The agent echoes command IO to its own stdout by default, so it +lands in the public Actions run log; `start --hide-logs` turns +the echo off. Either way the broker is the transport — its IO +chunk store is the cache of record — and the seat's `run`, +`attach` and `watch` read from it. The OIDC token and the R2 +credentials are never written to any log; the log audit is part +of the mode's acceptance bar. + +## The broker surface + +The verbs live in `crates/fleet-queue/src/turso_queue/ +actions_exec.rs` beside placement's: `/actions-exec-open`, +`-bind`, `-command`, `-stream`, `-renew`, `-extend-request`, +`-extend-decide`, `-close` (seat side, broker token) and +`/actions-exec-register`, `-poll`, `-io`, `-result` (agent side, +OIDC through the public door at `exec.security.cab`, which is +path-scoped to these verbs). Session state lives in the +`actions_exec_sessions` / `actions_exec_commands` / +`actions_exec_io` tables; every transition is a conditional +UPDATE, so two actors racing a session resolve to exactly one +winner. diff --git a/pkgs/fleet/crates/fleet-queue/Cargo.toml b/pkgs/fleet/crates/fleet-queue/Cargo.toml index 6c030ff53c..275324bc0b 100644 --- a/pkgs/fleet/crates/fleet-queue/Cargo.toml +++ b/pkgs/fleet/crates/fleet-queue/Cargo.toml @@ -15,6 +15,7 @@ description = "The fleet queue domain: the repo-queue client surface plus the qu client = ["dep:fleet-config", "dep:ureq"] queue-broker = [ "client", + "dep:ring", "dep:tiny_http", "dep:ureq", "dep:fleet-config", @@ -40,6 +41,9 @@ ureq = { version = "3", features = ["rustls", "json", "platform-verifier"], opti # the broker surfaces need no system SQLite (atlas-core pins the same # stack). Only the queue-broker surface carries the replica. rusqlite = { version = "0.42", features = ["bundled"], optional = true } +# #13774: RS256 verification of the Actions OIDC token in the +# actions-exec broker verbs (JWKS modulus/exponent -> ring RSA). +ring = { version = "0.17", optional = true } # Standalone artifacts — the migration's rollback inventory (design # note §7): the same code as the fleet binary's queue domain, shipped diff --git a/pkgs/fleet/crates/fleet-queue/src/client.rs b/pkgs/fleet/crates/fleet-queue/src/client.rs index 859b24af82..562cb384a8 100644 --- a/pkgs/fleet/crates/fleet-queue/src/client.rs +++ b/pkgs/fleet/crates/fleet-queue/src/client.rs @@ -27,6 +27,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; use serde_json::{Map, Value, json}; +pub mod actions_exec; mod commands_lifecycle; mod commands_query; mod fallback_stack; @@ -1482,14 +1483,13 @@ mod tests { // the same outcome class, distinct from unavailable — // and a denial is never retried under another identity. let at_transport = Err((3, "session proxy: unauthorized token".to_string())); - let (rec, code) = - exact_task_status("repo-health", 7, at_transport, "2026-11-23T12:05:00Z"); + let (rec, code) = exact_task_status("repo-health", 7, at_transport, "2026-11-23T12:05:00Z"); assert_eq!(code, 3); assert_eq!(rec["result"], json!("unknown")); assert_eq!(rec["detail"], json!("denied")); - let by_envelope = Ok(json!({"ok": false, "error": "permission denied for this queue", "exit": 4})); - let (rec, code) = - exact_task_status("repo-health", 7, by_envelope, "2026-11-23T12:05:00Z"); + let by_envelope = + Ok(json!({"ok": false, "error": "permission denied for this queue", "exit": 4})); + let (rec, code) = exact_task_status("repo-health", 7, by_envelope, "2026-11-23T12:05:00Z"); assert_eq!(code, 4); assert_eq!(rec["result"], json!("unknown")); assert_eq!(rec["detail"], json!("denied")); diff --git a/pkgs/fleet/crates/fleet-queue/src/client/actions_exec.rs b/pkgs/fleet/crates/fleet-queue/src/client/actions_exec.rs new file mode 100644 index 0000000000..4c065d3b19 --- /dev/null +++ b/pkgs/fleet/crates/fleet-queue/src/client/actions_exec.rs @@ -0,0 +1,126 @@ +//! Seat-side typed helpers for the actions-exec broker verbs +//! (#13774): live short-lived exec sessions inside GitHub Actions +//! runners. The runner-side agent does NOT use this client — it +//! speaks to the broker's public door with the job's OIDC token; +//! these helpers are the seat's half, over the standard queue +//! client transport (broker token, laptop broker endpoint). + +use serde_json::{Value, json}; + +use super::transport::call_result; + +/// POST one actions-exec verb through the shared client transport. +/// The envelope is returned as-is ({ok:true, ...} or the broker's +/// {ok:false, exit, error}); transport failure is exit 3. +fn ae_call(path: &str, body: Value) -> Result { + call_result(path, &body) +} + +/// Open a session row. `lease_s` is the caller's --timeout (required +/// by the verb; there is no default), `max_s` the hard lifespan cap. +pub fn ae_open( + host_repo: &str, + workflow: &str, + seat: &str, + lease_s: i64, + max_s: i64, + hide_logs: bool, +) -> Result { + ae_call( + "/actions-exec-open", + json!({ + "host_repo": host_repo, + "workflow": workflow, + "seat": seat, + "lease_s": lease_s, + "max_s": max_s, + "hide_logs": hide_logs, + }), + ) +} + +/// Bind the dispatched workflow run to the session (the handoff). +pub fn ae_bind(handle: &str, run_id: i64, run_attempt: i64) -> Result { + ae_call( + "/actions-exec-bind", + json!({"handle": handle, "run_id": run_id, "run_attempt": run_attempt}), + ) +} + +/// Enqueue one command on a bound/live session. +pub fn ae_command(handle: &str, text: &str, timeout_s: i64) -> Result { + ae_call( + "/actions-exec-command", + json!({"handle": handle, "text": text, "timeout_s": timeout_s}), + ) +} + +/// Read session state + command states + IO chunks after `after_id`. +pub fn ae_stream( + handle: &str, + after_id: i64, + cmd_id: Option<&str>, +) -> Result { + let mut body = json!({"handle": handle, "after_id": after_id}); + if let Some(cmd) = cmd_id { + body["cmd_id"] = json!(cmd); + } + ae_call("/actions-exec-stream", body) +} + +/// Renew the lease (clamped at the max lifespan by the broker; +/// `extension_required` in the reply says the ask passed the max). +pub fn ae_renew(handle: &str, lease_s: i64) -> Result { + ae_call( + "/actions-exec-renew", + json!({"handle": handle, "lease_s": lease_s}), + ) +} + +/// Request an emergency extension past the max lifespan. The +/// broker records the request and raises the needs-drew alert. +pub fn ae_extend_request( + handle: &str, + extend_s: i64, + reason: &str, +) -> Result { + ae_call( + "/actions-exec-extend-request", + json!({"handle": handle, "extend_s": extend_s, "reason": reason}), + ) +} + +/// Record the decision on a pending extension request. +pub fn ae_extend_decide(handle: &str, approve: bool) -> Result { + ae_call( + "/actions-exec-extend-decide", + json!({"handle": handle, "approve": approve}), + ) +} + +/// Close a session (seat side; the agent side closes through the +/// OIDC door instead). +pub fn ae_close(handle: &str) -> Result { + ae_call("/actions-exec-close", json!({"handle": handle})) +} + +/// The #13765 placement-coordinator claim attempt. The verbs are +/// not live yet: an unknown-command answer (or any error) comes +/// back as Err/ok:false and the caller proceeds on the singular +/// path, naming it. Returns Ok(true) only when a coordinator +/// actually granted the claim. +pub fn ae_placement_claim(host_repo: &str, seat: &str, handle: &str) -> bool { + let body = json!({ + "repo": host_repo, + "seat": seat, + "session": handle, + "kind": "actions-exec", + }); + match call_result("/placement-claim", &body) { + Ok(v) => { + v.get("ok").and_then(|o| o.as_bool()) == Some(true) + && v.get("granted").and_then(|g| g.as_bool()) != Some(false) + } + Err(_) => false, + } +} diff --git a/pkgs/fleet/crates/fleet-queue/src/needs_drew.rs b/pkgs/fleet/crates/fleet-queue/src/needs_drew.rs index 3815e00e13..0ac8ad3322 100644 --- a/pkgs/fleet/crates/fleet-queue/src/needs_drew.rs +++ b/pkgs/fleet/crates/fleet-queue/src/needs_drew.rs @@ -210,6 +210,55 @@ pub fn post_plain_alert_to(url: &str, token: &str, body: &Value) -> Result<(), S post_json(url, token, body).map(|_| ()) } +/// Build the alerts-intake body for a fleet actions exec +/// emergency-extension request (#13774). The PM stack renders the +/// needsDrew block as Drew's approve/deny choice; the answer comes +/// back as a seat-run `/actions-exec-extend-decide` (the phone -> +/// broker write-back is the PM stack's next phase). Deduped by the +/// throat on (source, key), one live request per session handle. +pub fn build_extension_alert_body( + handle: &str, + host_repo: &str, + run_id: Option, + extend_s: i64, + grace_until: &str, + reason: &str, +) -> Value { + let minutes = (extend_s + 59) / 60; + let question = + format!("Extend actions exec session {handle} past its max lifespan by {minutes} min?"); + let mut context = format!( + "Session {handle} on {host_repo} reached its max lifespan cap. Approving adds {extend_s}s to the max and the lease; denying lets the session expire (decision grace runs to {grace_until})." + ); + if !reason.is_empty() { + context.push_str(&format!(" Reason given: {reason}")); + } + let mut links = vec!["https://github.com/developing-today/code/issues/13774".to_string()]; + if let Some(id) = run_id { + links.insert( + 0, + format!("https://github.com/{host_repo}/actions/runs/{id}"), + ); + } + json!({ + "source": "fleet-actions-exec", + "key": format!("actions-exec-ext:{handle}"), + "severity": "warning", + "title": question, + "body": context, + "needsDrew": { + "ledgerId": format!("actions-exec-ext:{handle}"), + "question": question, + "context": context, + "options": [ + {"id": "approve", "label": format!("Approve +{minutes} min")}, + {"id": "deny", "label": "Deny — let it expire"}, + ], + "links": links, + }, + }) +} + /// Parse the snake_case `needs_drew` object the /block body /// carries (the shape cmd_block sends and the broker receives): /// {ledger_id, question, context?, options?, links?}, with diff --git a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs index 36c8bfa0c7..9f744766d5 100644 --- a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs +++ b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs @@ -544,6 +544,99 @@ fn maybe_raise_needs_drew(st: &State, req: &Value, resp: &Value) { }); } +/// #13774: the actions-exec agent verbs authenticate with the +/// job's GitHub OIDC JWT instead of the broker token — the agent +/// runs on a public runner and never holds the broker token. A +/// JWT-shaped X-Agent-Token (three base64url segments) on one of +/// these paths passes the token gate; the verb then verifies the +/// JWT against GitHub's JWKS and binds its claims to the session +/// row before acting. Any other call on these paths still needs +/// the broker token. +const ACTIONS_EXEC_AGENT_PATHS: [&str; 5] = [ + "/actions-exec-register", + "/actions-exec-poll", + "/actions-exec-io", + "/actions-exec-result", + "/actions-exec-close", +]; + +fn actions_exec_agent_call(path: &str, provided_token: Option<&str>) -> bool { + if !ACTIONS_EXEC_AGENT_PATHS.contains(&path) { + return false; + } + let Some(token) = provided_token else { + return false; + }; + let mut parts = token.split('.'); + match (parts.next(), parts.next(), parts.next(), parts.next()) { + (Some(h), Some(p), Some(s), None) => { + !h.is_empty() + && !p.is_empty() + && !s.is_empty() + && token + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_')) + } + _ => false, + } +} + +/// #13774: an approved-by-nobody-yet extension request raises the +/// needs-drew alert on the PM push surface (fire-and-forget, the +/// /block pattern): the verb has already recorded the pending +/// request and its decision grace; this post is what puts the +/// approve/deny choice in front of Drew. +fn maybe_raise_actions_exec_extension(st: &State, resp: &Value) { + if resp.get("requested").and_then(|v| v.as_bool()) != Some(true) { + return; + } + let (Some(handle), Some(host_repo)) = ( + resp.get("handle").and_then(|v| v.as_str()), + resp.get("host_repo").and_then(|v| v.as_str()), + ) else { + return; + }; + let body = crate::needs_drew::build_extension_alert_body( + handle, + host_repo, + resp.get("run_id").and_then(|v| v.as_i64()), + resp.get("extend_s") + .and_then(|v| v.as_i64()) + .unwrap_or(1800), + resp.get("grace_until") + .and_then(|v| v.as_str()) + .unwrap_or(""), + resp.get("reason").and_then(|v| v.as_str()).unwrap_or(""), + ); + let secrets_url = st.secrets_url.clone(); + let secrets_token = st.secrets_token.clone(); + let agent = st.agent.clone(); + std::thread::spawn(move || { + let resolver = Resolver::new(vec![Box::new(DirectSecrets { + url: secrets_url, + token: secrets_token, + agent: agent.clone(), + })]); + let raised = resolver + .resolve(crate::needs_drew::ALERTS_INTAKE_TOKEN_SECRET) + .map_err(|e| e.to_string()) + .and_then(|token| { + crate::needs_drew::post_plain_alert_to( + &crate::needs_drew::alerts_url(), + token.expose(), + &body, + ) + }); + match raised { + Ok(_) => crate::log::info("queue-broker", "actions-exec extension alert raised"), + Err(e) => crate::log::info( + "queue-broker", + &format!("actions-exec extension alert failed: {e}"), + ), + } + }); +} + fn dispatch(st: &State, path: &str, req: &Value) -> Value { if let Err(e) = validate_durations(path, req) { return fail(2, e); @@ -573,6 +666,10 @@ fn dispatch(st: &State, path: &str, req: &Value) -> Value { if path == "/block" { maybe_raise_needs_drew(st, req, &resp); } + // #13774: the emergency-extension needs-drew raise. + if path == "/actions-exec-extend-request" { + maybe_raise_actions_exec_extension(st, &resp); + } resp } } @@ -613,7 +710,7 @@ fn pre_body_refusal( if method == "GET" && path == "/healthz" { return None; } - if !token_matches(provided_token, token) { + if !actions_exec_agent_call(path, provided_token) && !token_matches(provided_token, token) { return Some((401, json!({"error": "unauthorized"}))); } if let Some(n) = content_length { @@ -639,14 +736,28 @@ fn handle_request( let path = target.split('?').next().unwrap_or(""); if method == "GET" && path == "/healthz" { (200, ok(json!({"service": "queue-broker"}))) - } else if !token_matches(provided_token, token) { + } else if !actions_exec_agent_call(path, provided_token) + && !token_matches(provided_token, token) + { (401, json!({"error": "unauthorized"})) } else if method != "POST" { (405, json!({"error": "POST only"})) } else { match std::str::from_utf8(body) { Ok(buf) => { - let parsed: Value = serde_json::from_str(buf).unwrap_or(Value::Null); + let mut parsed: Value = serde_json::from_str(buf).unwrap_or(Value::Null); + // #13774: _oidc_jwt is broker-injected, never + // client-supplied — strip any spoofed copy from + // every body, then inject the header token on + // agent-path calls for the verbs to verify. + if let Some(obj) = parsed.as_object_mut() { + obj.remove("_oidc_jwt"); + if actions_exec_agent_call(path, provided_token) { + if let Some(tok) = provided_token { + obj.insert("_oidc_jwt".to_string(), Value::String(tok.to_string())); + } + } + } (200, dispatch(st, path, &parsed)) } Err(e) => ( diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs index d8f077f626..141e868d92 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs @@ -43,6 +43,7 @@ use serde_json::{Map, Value, json}; use crate::validate::{task_from_packet, validate_packet}; +mod actions_exec; mod admin; mod claim; mod closed_bound; @@ -55,6 +56,7 @@ mod stacks_outbox; mod staleness; mod work_identity; +pub use actions_exec::*; pub use admin::*; pub use claim::*; pub use closed_bound::*; diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue/actions_exec.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue/actions_exec.rs new file mode 100644 index 0000000000..c48e54bbbe --- /dev/null +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue/actions_exec.rs @@ -0,0 +1,1615 @@ +//! turso_queue::actions_exec — live, short-lived exec sessions +//! inside GitHub Actions runners (developing-today/code#13774). +//! +//! The broker half of `fleet actions exec`. A seat opens a session, +//! dispatches the fleet-exec workflow with the session handle, and +//! binds the resulting run; the runner-side agent then proves it is +//! inside that run with the job's GitHub OIDC token and registers. +//! Commands flow seat -> broker -> agent over these verbs; IO flows +//! back the same way. Nothing connection-shaped exists outside the +//! two endpoints: the handle is a public identifier, and the OIDC +//! token is presented only to the broker, in the X-Agent-Token +//! header (queue_broker's gate passes JWT-shaped tokens on the +//! agent paths through to these verbs, which verify them). +//! +//! Agent auth: the register/poll/io/result/close verbs carry the +//! job's OIDC JWT in the request's `_oidc_jwt` field (injected by +//! queue_broker from the X-Agent-Token header — never accepted from +//! the request body itself). Verification is RS256 against GitHub's +//! JWKS (cached), then claims against the session row the seat +//! created: issuer, expiry, `repository`, `job_workflow_ref`, and +//! the run binding (`run_id` / `run_attempt` — taken from the +//! verified claims at register time, then required to match). +//! The `aud` claim is deliberately not pinned in v1: GitHub's +//! default audience varies by instance, and the repository + +//! workflow + run binding is the substantive check. +//! +//! Lease discipline (the design's contract): the lease is set at +//! open; renewals may move it up to `max_until` and no further; +//! past the max only an approved emergency extension moves it +//! (+30 min per approval, requested via /actions-exec-extend-request +//! — queue_broker raises the needs-drew PM alert on that verb's +//! success). While an extension request is pending the session sits +//! in `extension-pending` with a short decision grace past its +//! lease, so a live agent is not killed mid-question; past the +//! grace (or the max, unextended) the session is expired and the +//! agent dies — the agent also enforces its own local deadline. +//! +//! Atomicity follows the house shape: state transitions are single +//! conditional UPDATEs whose WHERE clause re-checks the expected +//! prior state, so racing verbs resolve to exactly one winner. + +use super::*; + +use std::sync::Mutex; + +// --------------------------------------------------------------------------- +// DDL (referenced from core::SCHEMA, beside placement_sessions) +// --------------------------------------------------------------------------- + +pub(crate) const ACTIONS_EXEC_DDL_SESSIONS: &str = "CREATE TABLE IF NOT EXISTS actions_exec_sessions (\ + handle TEXT PRIMARY KEY, host_repo TEXT NOT NULL, workflow TEXT NOT NULL, \ + seat TEXT NOT NULL, state TEXT NOT NULL DEFAULT 'open', \ + hide_logs INTEGER NOT NULL DEFAULT 0, \ + run_id INTEGER, run_attempt INTEGER, \ + lease_until TEXT NOT NULL, max_until TEXT NOT NULL, \ + ext_state TEXT, ext_seconds INTEGER, \ + created_at TEXT NOT NULL, updated_at TEXT NOT NULL, closed_at TEXT)"; + +pub(crate) const ACTIONS_EXEC_DDL_COMMANDS: &str = "CREATE TABLE IF NOT EXISTS actions_exec_commands (\ + cmd_id TEXT PRIMARY KEY, handle TEXT NOT NULL, seq INTEGER NOT NULL, \ + text TEXT NOT NULL, timeout_s INTEGER NOT NULL DEFAULT 60, \ + state TEXT NOT NULL DEFAULT 'queued', exit_code INTEGER, \ + created_at TEXT NOT NULL, updated_at TEXT NOT NULL)"; + +pub(crate) const ACTIONS_EXEC_DDL_COMMANDS_IDX: &str = "CREATE INDEX IF NOT EXISTS actions_exec_commands_handle \ + ON actions_exec_commands(handle, seq)"; + +pub(crate) const ACTIONS_EXEC_DDL_IO: &str = "CREATE TABLE IF NOT EXISTS actions_exec_io (\ + id INTEGER PRIMARY KEY AUTOINCREMENT, handle TEXT NOT NULL, \ + cmd_id TEXT NOT NULL, seq INTEGER NOT NULL, stream TEXT NOT NULL, \ + data TEXT NOT NULL, created_at TEXT NOT NULL)"; + +pub(crate) const ACTIONS_EXEC_DDL_IO_IDX: &str = "CREATE INDEX IF NOT EXISTS actions_exec_io_cmd \ + ON actions_exec_io(cmd_id, id)"; + +// --------------------------------------------------------------------------- +// Constants and small helpers +// --------------------------------------------------------------------------- + +/// The workflow file the session agent runs under. The register +/// verb checks the OIDC `job_workflow_ref` against +/// `{host_repo}/.github/workflows/{workflow}@...`. +pub(crate) const DEFAULT_WORKFLOW: &str = "fleet-exec.yml"; + +/// Minimum lease the open verb accepts (the Action validates the +/// same floor runner-side). +const MIN_LEASE_S: i64 = 30; +/// Hard cap on max lifespan: the fleet-run leg cap (2 h). +const MAX_LIFESPAN_S: i64 = 7_200; +/// Default max lifespan when the seat does not name one (30 min). +const DEFAULT_MAX_S: i64 = 1_800; +/// One approved emergency extension adds at most this much. +const MAX_EXTENSION_S: i64 = 1_800; +/// While an extension request awaits Drew's answer, the session +/// may outlive its lease by this much before it expires. +const EXTENSION_GRACE_S: i64 = 300; +/// Long-poll ceiling for /actions-exec-poll. +const MAX_POLL_WAIT_S: i64 = 25; +/// IO chunk cap per append (the broker caps bodies anyway; a chunk +/// larger than this is a client bug, not data). +const MAX_IO_CHUNK: usize = 64 * 1024; + +static RAND_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// Random-enough identifier material for handles and command ids: +/// SHA-256 over the clock, the process id, a process counter and a +/// caller-supplied distinguisher. Handles are public identifiers, +/// not credentials — uniqueness, not secrecy, is the requirement. +fn rand_hex(distinguisher: &str, bytes: usize) -> String { + use sha2::{Digest, Sha256}; + let n = RAND_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let mut h = Sha256::new(); + h.update(now.to_le_bytes()); + h.update(std::process::id().to_le_bytes()); + h.update(n.to_le_bytes()); + h.update(distinguisher.as_bytes()); + let digest = h.finalize(); + let hex: String = digest.iter().map(|b| format!("{b:02x}")).collect(); + hex.chars().take(bytes * 2).collect() +} + +/// Parse the house ISO stamp (`YYYY-MM-DDTHH:MM:SSZ`, as produced by +/// core::iso) back to unix seconds. Returns None on any other shape. +fn parse_iso(s: &str) -> Option { + let b = s.as_bytes(); + if b.len() != 20 || b[4] != b'-' || b[7] != b'-' || b[10] != b'T' || b[19] != b'Z' { + return None; + } + let num = |from: usize, len: usize| -> Option { s[from..from + len].parse::().ok() }; + let (y, mo, d) = (num(0, 4)?, num(5, 2)?, num(8, 2)?); + let (hh, mi, ss) = (num(11, 2)?, num(14, 2)?, num(17, 2)?); + // days_from_civil (Howard Hinnant's algorithm, the inverse of + // core::civil_from_days). + let y_adj = if mo <= 2 { y - 1 } else { y }; + let era = if y_adj >= 0 { y_adj } else { y_adj - 399 } / 400; + let yoe = y_adj - era * 400; + let mp = if mo > 2 { mo - 3 } else { mo + 9 }; + let doy = (153 * mp + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + let days = era * 146_097 + doe - 719_468; + Some(days * 86_400 + hh * 3_600 + mi * 60 + ss) +} + +// --------------------------------------------------------------------------- +// Session rows +// --------------------------------------------------------------------------- + +fn session_row(t: &TursoBackend, handle: &str) -> Result, TErr> { + // query_objs' third argument is the JSON-parse column list; + // this schema carries no JSON columns, so it stays empty. + let rows = t.query_objs( + "SELECT handle, host_repo, workflow, seat, state, hide_logs, \ + run_id, run_attempt, lease_until, max_until, \ + ext_state, ext_seconds, created_at, updated_at \ + FROM actions_exec_sessions WHERE handle = ?", + &[Arg::Text(handle.to_string())], + &[], + )?; + Ok(rows.into_iter().next()) +} + +fn session_json(row: &Value) -> Value { + let lease_unix = row + .get("lease_until") + .and_then(|v| v.as_str()) + .and_then(parse_iso) + .unwrap_or(0); + let max_unix = row + .get("max_until") + .and_then(|v| v.as_str()) + .and_then(parse_iso) + .unwrap_or(0); + json!({ + "handle": row.get("handle").cloned().unwrap_or(Value::Null), + "host_repo": row.get("host_repo").cloned().unwrap_or(Value::Null), + "workflow": row.get("workflow").cloned().unwrap_or(Value::Null), + "seat": row.get("seat").cloned().unwrap_or(Value::Null), + "state": row.get("state").cloned().unwrap_or(Value::Null), + "hide_logs": row.get("hide_logs").and_then(|v| v.as_i64()).unwrap_or(0) != 0, + "run_id": row.get("run_id").cloned().unwrap_or(Value::Null), + "run_attempt": row.get("run_attempt").cloned().unwrap_or(Value::Null), + "lease_until": row.get("lease_until").cloned().unwrap_or(Value::Null), + "lease_unix": lease_unix, + "max_until": row.get("max_until").cloned().unwrap_or(Value::Null), + "max_unix": max_unix, + "ext_state": row.get("ext_state").cloned().unwrap_or(Value::Null), + }) +} + +/// The last moment the agent may live, in unix seconds: the lease, +/// or — while an extension decision is pending — the lease plus +/// the decision grace. Never past max_until unless an approved +/// extension already moved max_until (approvals update both). +fn hard_deadline_unix(row: &Value) -> i64 { + let lease = row + .get("lease_until") + .and_then(|v| v.as_str()) + .and_then(parse_iso) + .unwrap_or(0); + if row.get("ext_state").and_then(|v| v.as_str()) == Some("pending") { + lease + EXTENSION_GRACE_S + } else { + lease + } +} + +/// The state the rest of the world should treat the session as +/// being in: a live-shaped row past its hard deadline reads as +/// expired (the transition is also written back lazily by poll). +fn effective_state(row: &Value, now: i64) -> String { + let state = row + .get("state") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + if matches!( + state.as_str(), + "open" | "bound" | "live" | "extension-pending" + ) && now > hard_deadline_unix(row) + { + return "expired".to_string(); + } + state +} + +fn require_session(t: &TursoBackend, req: &Value) -> Result { + let Some(handle) = req_str(req, "handle").filter(|h| !h.is_empty()) else { + return Err(fail(2, "handle is required".to_string())); + }; + match session_row(t, handle) { + Ok(Some(row)) => Ok(row), + Ok(None) => Err(fail(5, format!("unknown session handle {handle}"))), + Err(e) => Err(terr(e)), + } +} + +// --------------------------------------------------------------------------- +// GitHub OIDC verification (agent auth) +// --------------------------------------------------------------------------- + +fn b64url_decode(s: &str) -> Option> { + fn val(c: u8) -> Option { + match c { + b'A'..=b'Z' => Some((c - b'A') as u32), + b'a'..=b'z' => Some((c - b'a') as u32 + 26), + b'0'..=b'9' => Some((c - b'0') as u32 + 52), + b'-' => Some(62), + b'_' => Some(63), + _ => None, + } + } + let mut out = Vec::with_capacity(s.len() * 3 / 4 + 3); + let mut acc: u32 = 0; + let mut nbits: u32 = 0; + for &c in s.as_bytes() { + if c == b'=' { + break; + } + acc = (acc << 6) | val(c)?; + nbits += 6; + if nbits >= 8 { + nbits -= 8; + out.push((acc >> nbits) as u8); + } + } + Some(out) +} + +struct JwksKey { + kid: String, + /// DER-encoded RSAPublicKey (SEQUENCE of modulus, exponent) — + /// the shape ring's RSA verification takes. + der: Vec, +} + +struct JwksCache { + fetched_unix: i64, + keys: Vec, +} + +static JWKS: Mutex> = Mutex::new(None); +const JWKS_TTL_S: i64 = 600; + +fn jwks_url() -> String { + std::env::var("FLEET_ACTIONS_EXEC_JWKS_URL").unwrap_or_else(|_| { + "https://token.actions.githubusercontent.com/.well-known/jwks".to_string() + }) +} + +fn der_len(out: &mut Vec, len: usize) { + if len < 0x80 { + out.push(len as u8); + } else if len < 0x100 { + out.push(0x81); + out.push(len as u8); + } else { + out.push(0x82); + out.push((len >> 8) as u8); + out.push(len as u8); + } +} + +fn der_integer(out: &mut Vec, raw: &[u8]) { + // Strip leading zero bytes, then re-add one if the high bit is + // set (DER integers are signed). + let mut body: &[u8] = raw; + while body.len() > 1 && body[0] == 0 { + body = &body[1..]; + } + let pad = body.first().map(|b| b & 0x80 != 0).unwrap_or(false); + out.push(0x02); + der_len(out, body.len() + usize::from(pad)); + if pad { + out.push(0); + } + out.extend_from_slice(body); +} + +fn rsa_public_key_der(n_b64: &str, e_b64: &str) -> Option> { + let n = b64url_decode(n_b64)?; + let e = b64url_decode(e_b64)?; + let mut content = Vec::new(); + der_integer(&mut content, &n); + der_integer(&mut content, &e); + let mut out = vec![0x30]; + der_len(&mut out, content.len()); + out.extend_from_slice(&content); + Some(out) +} + +fn jwks_keys(force: bool) -> Result)>, String> { + let now = now_unix(); + if !force { + if let Ok(guard) = JWKS.lock() { + if let Some(cache) = guard.as_ref() { + if now - cache.fetched_unix < JWKS_TTL_S { + return Ok(cache + .keys + .iter() + .map(|k| (k.kid.clone(), k.der.clone())) + .collect()); + } + } + } + } + let url = jwks_url(); + let mut resp = ureq::agent() + .get(&url) + .call() + .map_err(|e| format!("jwks fetch {url}: {e}"))?; + let doc: Value = resp + .body_mut() + .read_json() + .map_err(|e| format!("jwks parse: {e}"))?; + let mut keys = Vec::new(); + if let Some(arr) = doc.get("keys").and_then(|k| k.as_array()) { + for k in arr { + if k.get("kty").and_then(|v| v.as_str()) != Some("RSA") { + continue; + } + let (Some(kid), Some(n), Some(e)) = ( + k.get("kid").and_then(|v| v.as_str()), + k.get("n").and_then(|v| v.as_str()), + k.get("e").and_then(|v| v.as_str()), + ) else { + continue; + }; + if let Some(der) = rsa_public_key_der(n, e) { + keys.push(JwksKey { + kid: kid.to_string(), + der, + }); + } + } + } + if keys.is_empty() { + return Err(format!("jwks at {url} carried no usable RSA keys")); + } + if let Ok(mut guard) = JWKS.lock() { + *guard = Some(JwksCache { + fetched_unix: now, + keys: keys + .iter() + .map(|k| JwksKey { + kid: k.kid.clone(), + der: k.der.clone(), + }) + .collect(), + }); + } + Ok(keys.into_iter().map(|k| (k.kid, k.der)).collect()) +} + +/// Verified OIDC claims, reduced to what the session binding needs. +struct OidcClaims { + repository: String, + job_workflow_ref: String, + run_id: i64, + run_attempt: i64, +} + +fn verify_oidc(jwt: &str) -> Result { + let parts: Vec<&str> = jwt.split('.').collect(); + if parts.len() != 3 { + return Err("token is not a three-segment JWT".to_string()); + } + let header: Value = + serde_json::from_slice(&b64url_decode(parts[0]).ok_or("JWT header is not base64url")?) + .map_err(|e| format!("JWT header parse: {e}"))?; + if header.get("alg").and_then(|v| v.as_str()) != Some("RS256") { + return Err("JWT alg is not RS256".to_string()); + } + let kid = header + .get("kid") + .and_then(|v| v.as_str()) + .ok_or("JWT header carries no kid")?; + let signing_input = format!("{}.{}", parts[0], parts[1]); + let signature = b64url_decode(parts[2]).ok_or("JWT signature is not base64url")?; + let verify_with = |keys: &[(String, Vec)]| -> Result<(), String> { + let der = keys + .iter() + .find(|(k, _)| k == kid) + .map(|(_, d)| d.clone()) + .ok_or_else(|| format!("no JWKS key for kid {kid}"))?; + let public_key = ring::signature::UnparsedPublicKey::new( + &ring::signature::RSA_PKCS1_2048_8192_SHA256, + der, + ); + public_key + .verify(signing_input.as_bytes(), &signature) + .map_err(|_| "JWT signature does not verify".to_string()) + }; + if let Err(e) = verify_with(&jwks_keys(false)?) { + // One refetch on failure: the kid may belong to a key GitHub + // rotated in since the cache filled. + verify_with(&jwks_keys(true)?).map_err(|_| e)?; + } + let claims: Value = + serde_json::from_slice(&b64url_decode(parts[1]).ok_or("JWT payload is not base64url")?) + .map_err(|e| format!("JWT payload parse: {e}"))?; + if claims.get("iss").and_then(|v| v.as_str()) + != Some("https://token.actions.githubusercontent.com") + { + return Err("JWT issuer is not GitHub Actions".to_string()); + } + let exp = claims.get("exp").and_then(|v| v.as_i64()).unwrap_or(0); + if exp <= now_unix() { + return Err("JWT is expired".to_string()); + } + let repository = claims + .get("repository") + .and_then(|v| v.as_str()) + .ok_or("JWT carries no repository claim")? + .to_string(); + let job_workflow_ref = claims + .get("job_workflow_ref") + .and_then(|v| v.as_str()) + .ok_or("JWT carries no job_workflow_ref claim")? + .to_string(); + let run_id = claims + .get("run_id") + .and_then(|v| v.as_str()) + .and_then(|s| s.parse::().ok()) + .ok_or("JWT run_id claim is not an integer string")?; + let run_attempt = claims + .get("run_attempt") + .and_then(|v| v.as_str()) + .and_then(|s| s.parse::().ok()) + .ok_or("JWT run_attempt claim is not an integer string")?; + Ok(OidcClaims { + repository, + job_workflow_ref, + run_id, + run_attempt, + }) +} + +/// The agent-side gate shared by register/poll/io/result/close: +/// verify the JWT, then bind its claims to the session row — the +/// repository and workflow must be the ones the seat opened the +/// session for, and once a run is bound the claims must name it. +fn verify_agent(req: &Value, row: &Value) -> Result { + let Some(jwt) = req_str(req, "_oidc_jwt").filter(|s| !s.is_empty()) else { + return Err(fail(4, "agent auth required (OIDC JWT)".to_string())); + }; + let claims = verify_oidc(jwt).map_err(|e| fail(4, format!("oidc: {e}")))?; + let host_repo = row.get("host_repo").and_then(|v| v.as_str()).unwrap_or(""); + let workflow = row.get("workflow").and_then(|v| v.as_str()).unwrap_or(""); + if claims.repository != host_repo { + return Err(fail( + 4, + format!( + "oidc repository {} does not match session host {}", + claims.repository, host_repo + ), + )); + } + let expect_prefix = format!("{host_repo}/.github/workflows/{workflow}@"); + if !claims.job_workflow_ref.starts_with(&expect_prefix) { + return Err(fail( + 4, + format!( + "oidc workflow {} is not the session workflow", + claims.job_workflow_ref + ), + )); + } + if let Some(bound) = row.get("run_id").and_then(|v| v.as_i64()) { + if bound != claims.run_id { + return Err(fail(4, "oidc run does not match the bound run".to_string())); + } + if let Some(bound_attempt) = row.get("run_attempt").and_then(|v| v.as_i64()) { + if bound_attempt != claims.run_attempt { + return Err(fail( + 4, + "oidc run attempt does not match the bound attempt".to_string(), + )); + } + } + } + Ok(claims) +} + +// --------------------------------------------------------------------------- +// Seat verbs +// --------------------------------------------------------------------------- + +pub(crate) fn verb_actions_exec_open(t: &TursoBackend, req: &Value) -> Value { + let Some(host_repo) = req_str(req, "host_repo").filter(|s| s.contains('/')) else { + return fail(2, "host_repo (owner/repository) is required".to_string()); + }; + let workflow = req_str(req, "workflow") + .filter(|s| !s.is_empty()) + .unwrap_or(DEFAULT_WORKFLOW) + .to_string(); + let seat = req_str(req, "seat") + .filter(|s| !s.is_empty()) + .unwrap_or("unknown-seat") + .to_string(); + let lease_s = req_i64(req, "lease_s").unwrap_or(0); + let max_s = req_i64(req, "max_s").unwrap_or(DEFAULT_MAX_S); + if lease_s < MIN_LEASE_S { + return fail( + 2, + format!( + "lease_s must be at least {MIN_LEASE_S} (the lease is the start --timeout; there is no default)" + ), + ); + } + if max_s > MAX_LIFESPAN_S { + return fail( + 2, + format!("max_s must not exceed {MAX_LIFESPAN_S} (the fleet leg cap)"), + ); + } + if lease_s > max_s { + return fail(2, "lease_s must not exceed max_s".to_string()); + } + let handle = req_str(req, "handle") + .filter(|h| { + h.len() >= 8 + && h.len() <= 64 + && h.chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') + }) + .map(str::to_string) + .unwrap_or_else(|| format!("fx-{}", rand_hex("handle", 10))); + let hide_logs = if req.get("hide_logs").and_then(|v| v.as_bool()) == Some(true) { + 1 + } else { + 0 + }; + let now = now_unix(); + let lease_until = iso(now + lease_s); + let max_until = iso(now + max_s); + let stamp = iso(now); + let work = (|| -> Result { + t.exec( + "INSERT INTO actions_exec_sessions \ + (handle, host_repo, workflow, seat, state, hide_logs, \ + lease_until, max_until, created_at, updated_at) \ + VALUES (?, ?, ?, ?, 'open', ?, ?, ?, ?, ?)", + &[ + Arg::Text(handle.clone()), + Arg::Text(host_repo.to_string()), + Arg::Text(workflow), + Arg::Text(seat), + Arg::Int(hide_logs), + Arg::Text(lease_until.clone()), + Arg::Text(max_until.clone()), + Arg::Text(stamp.clone()), + Arg::Text(stamp), + ], + )?; + Ok(json!({ + "handle": handle, + "state": "open", + "lease_until": lease_until, + "max_until": max_until, + })) + })(); + match work { + Ok(v) => ok(v), + Err(e) => terr(e), + } +} + +pub(crate) fn verb_actions_exec_bind(t: &TursoBackend, req: &Value) -> Value { + let row = match require_session(t, req) { + Ok(r) => r, + Err(v) => return v, + }; + let handle = row.get("handle").and_then(|v| v.as_str()).unwrap_or(""); + let (Some(run_id), Some(run_attempt)) = (req_i64(req, "run_id"), req_i64(req, "run_attempt")) + else { + return fail(2, "run_id and run_attempt are required".to_string()); + }; + let work = (|| -> Result { + let res = t.exec( + "UPDATE actions_exec_sessions \ + SET run_id = ?, run_attempt = ?, state = 'bound', updated_at = ? \ + WHERE handle = ? AND state IN ('open', 'bound')", + &[ + Arg::Int(run_id), + Arg::Int(run_attempt), + Arg::Text(now_iso()), + Arg::Text(handle.to_string()), + ], + )?; + if res.affected == 0 { + return Ok(json!({"bound": false})); + } + Ok(json!({"bound": true, "run_id": run_id, "run_attempt": run_attempt})) + })(); + match work { + Ok(v) => ok(v), + Err(e) => terr(e), + } +} + +pub(crate) fn verb_actions_exec_command(t: &TursoBackend, req: &Value) -> Value { + let row = match require_session(t, req) { + Ok(r) => r, + Err(v) => return v, + }; + let now = now_unix(); + let state = effective_state(&row, now); + if !matches!(state.as_str(), "bound" | "live" | "extension-pending") { + return fail( + 5, + format!("session is {state}; commands need a bound or live session"), + ); + } + let Some(text) = req_str(req, "text").filter(|s| !s.is_empty()) else { + return fail(2, "text (the command) is required".to_string()); + }; + let timeout_s = req_i64(req, "timeout_s").unwrap_or(600).clamp(1, 3_600); + let handle = row.get("handle").and_then(|v| v.as_str()).unwrap_or(""); + let cmd_id = format!("cmd-{}", rand_hex(handle, 8)); + let stamp = now_iso(); + let work = (|| -> Result { + let seq_rows = t.query_objs( + "SELECT COALESCE(MAX(seq), 0) + 1 AS next_seq \ + FROM actions_exec_commands WHERE handle = ?", + &[Arg::Text(handle.to_string())], + &[], + )?; + let seq = seq_rows + .first() + .and_then(|r| r.get("next_seq")) + .and_then(|v| v.as_i64()) + .unwrap_or(1); + t.exec( + "INSERT INTO actions_exec_commands \ + (cmd_id, handle, seq, text, timeout_s, state, created_at, updated_at) \ + VALUES (?, ?, ?, ?, ?, 'queued', ?, ?)", + &[ + Arg::Text(cmd_id.clone()), + Arg::Text(handle.to_string()), + Arg::Int(seq), + Arg::Text(text.to_string()), + Arg::Int(timeout_s), + Arg::Text(stamp.clone()), + Arg::Text(stamp), + ], + )?; + Ok(json!({"cmd_id": cmd_id, "seq": seq, "state": "queued"})) + })(); + match work { + Ok(v) => ok(v), + Err(e) => terr(e), + } +} + +pub(crate) fn verb_actions_exec_stream(t: &TursoBackend, req: &Value) -> Value { + let row = match require_session(t, req) { + Ok(r) => r, + Err(v) => return v, + }; + let handle = row.get("handle").and_then(|v| v.as_str()).unwrap_or(""); + let after_id = req_i64(req, "after_id").unwrap_or(0); + let cmd_filter = req_str(req, "cmd_id").map(str::to_string); + let limit = req_i64(req, "limit").unwrap_or(500).clamp(1, 2_000); + let now = now_unix(); + let work = (|| -> Result { + let (sql, args): (&str, Vec) = match &cmd_filter { + Some(cmd) => ( + "SELECT id, cmd_id, seq, stream, data FROM actions_exec_io \ + WHERE handle = ? AND cmd_id = ? AND id > ? ORDER BY id LIMIT ?", + vec![ + Arg::Text(handle.to_string()), + Arg::Text(cmd.clone()), + Arg::Int(after_id), + Arg::Int(limit), + ], + ), + None => ( + "SELECT id, cmd_id, seq, stream, data FROM actions_exec_io \ + WHERE handle = ? AND id > ? ORDER BY id LIMIT ?", + vec![ + Arg::Text(handle.to_string()), + Arg::Int(after_id), + Arg::Int(limit), + ], + ), + }; + let chunks = t.query_objs(sql, &args, &[])?; + let cmds = t.query_objs( + "SELECT cmd_id, seq, text, timeout_s, state, exit_code \ + FROM actions_exec_commands WHERE handle = ? ORDER BY seq", + &[Arg::Text(handle.to_string())], + &[], + )?; + let mut session = session_json(&row); + session["state"] = json!(effective_state(&row, now)); + session["server_now"] = json!(now); + Ok(json!({ + "session": session, + "chunks": chunks, + "commands": cmds, + })) + })(); + match work { + Ok(v) => ok(v), + Err(e) => terr(e), + } +} + +pub(crate) fn verb_actions_exec_renew(t: &TursoBackend, req: &Value) -> Value { + let row = match require_session(t, req) { + Ok(r) => r, + Err(v) => return v, + }; + let now = now_unix(); + let state = effective_state(&row, now); + if !matches!( + state.as_str(), + "open" | "bound" | "live" | "extension-pending" + ) { + return fail(5, format!("session is {state}; it cannot be renewed")); + } + let Some(lease_s) = req_i64(req, "lease_s") else { + return fail( + 2, + "lease_s is required (renewal names its timeout)".to_string(), + ); + }; + if lease_s < 1 { + return fail(2, "lease_s must be positive".to_string()); + } + let max_unix = row + .get("max_until") + .and_then(|v| v.as_str()) + .and_then(parse_iso) + .unwrap_or(0); + let target = now + lease_s; + let extension_required = target > max_unix; + let new_lease_unix = target.min(max_unix); + if new_lease_unix <= now { + return fail( + 5, + "session is at its max lifespan; an approved emergency extension is the only way past it" + .to_string(), + ); + } + let handle = row.get("handle").and_then(|v| v.as_str()).unwrap_or(""); + let new_lease = iso(new_lease_unix); + let work = (|| -> Result { + t.exec( + "UPDATE actions_exec_sessions SET lease_until = ?, updated_at = ? \ + WHERE handle = ? AND state IN ('open', 'bound', 'live', 'extension-pending')", + &[ + Arg::Text(new_lease.clone()), + Arg::Text(now_iso()), + Arg::Text(handle.to_string()), + ], + )?; + Ok(json!({ + "lease_until": new_lease, + "max_until": row.get("max_until").cloned().unwrap_or(Value::Null), + "extension_required": extension_required, + })) + })(); + match work { + Ok(v) => ok(v), + Err(e) => terr(e), + } +} + +pub(crate) fn verb_actions_exec_extend_request(t: &TursoBackend, req: &Value) -> Value { + let row = match require_session(t, req) { + Ok(r) => r, + Err(v) => return v, + }; + let now = now_unix(); + let state = effective_state(&row, now); + if !matches!( + state.as_str(), + "open" | "bound" | "live" | "extension-pending" + ) { + return fail( + 5, + format!("session is {state}; extensions need a live session"), + ); + } + if row.get("ext_state").and_then(|v| v.as_str()) == Some("pending") { + return fail(5, "an extension request is already pending".to_string()); + } + let extend_s = req_i64(req, "extend_s") + .unwrap_or(MAX_EXTENSION_S) + .clamp(60, MAX_EXTENSION_S); + let handle = row.get("handle").and_then(|v| v.as_str()).unwrap_or(""); + let work = (|| -> Result { + let res = t.exec( + "UPDATE actions_exec_sessions \ + SET state = 'extension-pending', ext_state = 'pending', \ + ext_seconds = ?, updated_at = ? \ + WHERE handle = ? AND state IN ('open', 'bound', 'live', 'extension-pending') \ + AND COALESCE(ext_state, '') <> 'pending'", + &[ + Arg::Int(extend_s), + Arg::Text(now_iso()), + Arg::Text(handle.to_string()), + ], + )?; + if res.affected == 0 { + return Ok(json!({"requested": false})); + } + Ok(json!({ + "requested": true, + "handle": handle, + "host_repo": row.get("host_repo").cloned().unwrap_or(Value::Null), + "run_id": row.get("run_id").cloned().unwrap_or(Value::Null), + "extend_s": extend_s, + "grace_until": iso(hard_deadline_unix(&row)), + "reason": req_str(req, "reason").unwrap_or(""), + })) + })(); + match work { + Ok(v) => ok(v), + Err(e) => terr(e), + } +} + +pub(crate) fn verb_actions_exec_extend_decide(t: &TursoBackend, req: &Value) -> Value { + let row = match require_session(t, req) { + Ok(r) => r, + Err(v) => return v, + }; + if row.get("ext_state").and_then(|v| v.as_str()) != Some("pending") { + return fail( + 5, + "no extension request is pending on this session".to_string(), + ); + } + let approve = req.get("approve").and_then(|v| v.as_bool()) == Some(true); + let handle = row.get("handle").and_then(|v| v.as_str()).unwrap_or(""); + let now = now_unix(); + let work = (|| -> Result { + if approve { + let extend_s = row + .get("ext_seconds") + .and_then(|v| v.as_i64()) + .unwrap_or(MAX_EXTENSION_S) + .clamp(60, MAX_EXTENSION_S); + let max_unix = row + .get("max_until") + .and_then(|v| v.as_str()) + .and_then(parse_iso) + .unwrap_or(0); + let lease_unix = row + .get("lease_until") + .and_then(|v| v.as_str()) + .and_then(parse_iso) + .unwrap_or(0); + let new_max = iso(max_unix + extend_s); + let new_lease = iso(lease_unix.max(now + extend_s).min(max_unix + extend_s)); + let res = t.exec( + "UPDATE actions_exec_sessions \ + SET state = 'live', ext_state = 'approved', max_until = ?, \ + lease_until = ?, updated_at = ? \ + WHERE handle = ? AND ext_state = 'pending'", + &[ + Arg::Text(new_max.clone()), + Arg::Text(new_lease.clone()), + Arg::Text(now_iso()), + Arg::Text(handle.to_string()), + ], + )?; + Ok(json!({ + "decided": res.affected > 0, + "approved": true, + "max_until": new_max, + "lease_until": new_lease, + })) + } else { + let res = t.exec( + "UPDATE actions_exec_sessions \ + SET state = 'live', ext_state = 'denied', updated_at = ? \ + WHERE handle = ? AND ext_state = 'pending'", + &[Arg::Text(now_iso()), Arg::Text(handle.to_string())], + )?; + Ok(json!({"decided": res.affected > 0, "approved": false})) + } + })(); + match work { + Ok(v) => ok(v), + Err(e) => terr(e), + } +} + +pub(crate) fn verb_actions_exec_close(t: &TursoBackend, req: &Value) -> Value { + let row = match require_session(t, req) { + Ok(r) => r, + Err(v) => return v, + }; + // Dual-sided: a seat close arrives behind the broker token (no + // _oidc_jwt); an agent close must prove itself like any agent + // verb. + if req_str(req, "_oidc_jwt").is_some() { + if let Err(v) = verify_agent(req, &row) { + return v; + } + } + let handle = row.get("handle").and_then(|v| v.as_str()).unwrap_or(""); + let work = (|| -> Result { + let res = t.exec( + "UPDATE actions_exec_sessions \ + SET state = 'closed', closed_at = ?, updated_at = ? \ + WHERE handle = ? AND state <> 'closed'", + &[ + Arg::Text(now_iso()), + Arg::Text(now_iso()), + Arg::Text(handle.to_string()), + ], + )?; + t.exec( + "UPDATE actions_exec_commands SET state = 'error', updated_at = ? \ + WHERE handle = ? AND state = 'queued'", + &[Arg::Text(now_iso()), Arg::Text(handle.to_string())], + )?; + Ok(json!({"closed": res.affected > 0})) + })(); + match work { + Ok(v) => ok(v), + Err(e) => terr(e), + } +} + +// --------------------------------------------------------------------------- +// Agent verbs +// --------------------------------------------------------------------------- + +pub(crate) fn verb_actions_exec_register(t: &TursoBackend, req: &Value) -> Value { + let row = match require_session(t, req) { + Ok(r) => r, + Err(v) => return v, + }; + let claims = match verify_agent(req, &row) { + Ok(c) => c, + Err(v) => return v, + }; + let handle = row.get("handle").and_then(|v| v.as_str()).unwrap_or(""); + let work = (|| -> Result { + // The verified claims bind the run when the seat has not + // bound it yet; a bound run was already required to match + // by verify_agent. + let res = t.exec( + "UPDATE actions_exec_sessions \ + SET state = 'live', \ + run_id = COALESCE(run_id, ?), run_attempt = COALESCE(run_attempt, ?), \ + updated_at = ? \ + WHERE handle = ? AND state IN ('open', 'bound', 'live')", + &[ + Arg::Int(claims.run_id), + Arg::Int(claims.run_attempt), + Arg::Text(now_iso()), + Arg::Text(handle.to_string()), + ], + )?; + if res.affected == 0 { + return Ok(json!({"registered": false})); + } + Ok(json!({ + "registered": true, + "state": "live", + "lease_until": row.get("lease_until").cloned().unwrap_or(Value::Null), + "max_until": row.get("max_until").cloned().unwrap_or(Value::Null), + "hide_logs": row.get("hide_logs").and_then(|v| v.as_i64()).unwrap_or(0) != 0, + })) + })(); + match work { + Ok(v) => ok(v), + Err(e) => terr(e), + } +} + +pub(crate) fn verb_actions_exec_poll(t: &TursoBackend, req: &Value) -> Value { + let row = match require_session(t, req) { + Ok(r) => r, + Err(v) => return v, + }; + if let Err(v) = verify_agent(req, &row) { + return v; + } + let handle = row.get("handle").and_then(|v| v.as_str()).unwrap_or(""); + let wait_s = req_i64(req, "wait_s") + .unwrap_or(0) + .clamp(0, MAX_POLL_WAIT_S); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(wait_s as u64); + // Long-poll: re-read the session + queued commands until a + // command appears, the session leaves a live shape, or the + // wait budget runs out. + loop { + let current = match session_row(t, handle) { + Ok(Some(r)) => r, + Ok(None) => return fail(5, format!("unknown session handle {handle}")), + Err(e) => return terr(e), + }; + let now = now_unix(); + let state = effective_state(¤t, now); + if state == "expired" && current.get("state").and_then(|v| v.as_str()) != Some("expired") { + // Write the lazy transition back so every reader agrees. + let _ = t.exec( + "UPDATE actions_exec_sessions SET state = 'expired', updated_at = ? \ + WHERE handle = ? AND state IN ('open', 'bound', 'live', 'extension-pending')", + &[Arg::Text(now_iso()), Arg::Text(handle.to_string())], + ); + } + let queued = match t.query_objs( + "SELECT cmd_id, seq, text, timeout_s FROM actions_exec_commands \ + WHERE handle = ? AND state = 'queued' ORDER BY seq LIMIT 16", + &[Arg::Text(handle.to_string())], + &[], + ) { + Ok(q) => q, + Err(e) => return terr(e), + }; + if !queued.is_empty() || state != "live" && state != "extension-pending" || wait_s == 0 { + let mut session = session_json(¤t); + session["state"] = json!(state); + session["server_now"] = json!(now); + session["deadline_unix"] = json!(hard_deadline_unix(¤t)); + return ok(json!({"session": session, "commands": queued})); + } + if std::time::Instant::now() >= deadline { + let mut session = session_json(¤t); + session["state"] = json!(state); + session["server_now"] = json!(now); + session["deadline_unix"] = json!(hard_deadline_unix(¤t)); + return ok(json!({"session": session, "commands": queued})); + } + std::thread::sleep(std::time::Duration::from_millis(500)); + } +} + +pub(crate) fn verb_actions_exec_io(t: &TursoBackend, req: &Value) -> Value { + let row = match require_session(t, req) { + Ok(r) => r, + Err(v) => return v, + }; + if let Err(v) = verify_agent(req, &row) { + return v; + } + let (Some(cmd_id), Some(seq), Some(stream), Some(data)) = ( + req_str(req, "cmd_id"), + req_i64(req, "seq"), + req_str(req, "stream"), + req_str(req, "data"), + ) else { + return fail(2, "cmd_id, seq, stream and data are required".to_string()); + }; + if data.len() > MAX_IO_CHUNK { + return fail(2, "io chunk exceeds the 64 KiB cap".to_string()); + } + if stream != "stdout" && stream != "stderr" { + return fail(2, "stream must be stdout or stderr".to_string()); + } + let handle = row.get("handle").and_then(|v| v.as_str()).unwrap_or(""); + let work = (|| -> Result { + t.exec( + "INSERT INTO actions_exec_io (handle, cmd_id, seq, stream, data, created_at) \ + VALUES (?, ?, ?, ?, ?, ?)", + &[ + Arg::Text(handle.to_string()), + Arg::Text(cmd_id.to_string()), + Arg::Int(seq), + Arg::Text(stream.to_string()), + Arg::Text(data.to_string()), + Arg::Text(now_iso()), + ], + )?; + // First IO on a queued command marks it running. + t.exec( + "UPDATE actions_exec_commands SET state = 'running', updated_at = ? \ + WHERE cmd_id = ? AND state = 'queued'", + &[Arg::Text(now_iso()), Arg::Text(cmd_id.to_string())], + )?; + Ok(json!({"appended": true})) + })(); + match work { + Ok(v) => ok(v), + Err(e) => terr(e), + } +} + +pub(crate) fn verb_actions_exec_result(t: &TursoBackend, req: &Value) -> Value { + let row = match require_session(t, req) { + Ok(r) => r, + Err(v) => return v, + }; + if let Err(v) = verify_agent(req, &row) { + return v; + } + let (Some(cmd_id), Some(exit_code)) = (req_str(req, "cmd_id"), req_i64(req, "exit_code")) + else { + return fail(2, "cmd_id and exit_code are required".to_string()); + }; + let work = (|| -> Result { + let res = t.exec( + "UPDATE actions_exec_commands \ + SET state = 'done', exit_code = ?, updated_at = ? \ + WHERE cmd_id = ? AND state IN ('queued', 'running')", + &[ + Arg::Int(exit_code), + Arg::Text(now_iso()), + Arg::Text(cmd_id.to_string()), + ], + )?; + Ok(json!({"recorded": res.affected > 0})) + })(); + match work { + Ok(v) => ok(v), + Err(e) => terr(e), + } +} + +// --------------------------------------------------------------------------- +// Tests: a rusqlite-backed fake of the Turso pipeline endpoint (the +// #13765 proof-bar pattern — real SQL semantics, so the conditional +// UPDATEs and lease transitions are exercised, not mimicked), plus +// a throwaway RSA keypair's signed JWT for the OIDC verbs. The +// private key never left the generating machine and the fixture +// verifies only against the test JWKS below — GitHub's real JWKS +// has no such kid. +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use std::io::{BufRead, BufReader, Read, Write}; + use std::sync::Arc; + + const TEST_JWT: &str = "eyJhbGciOiJSUzI1NiIsImtpZCI6InRlc3Qta2lkLTEiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL3Rva2VuLmFjdGlvbnMuZ2l0aHVidXNlcmNvbnRlbnQuY29tIiwic3ViIjoicmVwbzpkZXpyZW4zOS9mbGVldDpyZWY6cmVmcy9oZWFkcy9tYWluIiwiYXVkIjoiaHR0cHM6Ly9naXRodWIuY29tL2RlenJlbjM5IiwiaWF0IjoxNzAwMDAwMDAwLCJleHAiOjQxMDI0NDQ4MDAsInJlcG9zaXRvcnkiOiJkZXpyZW4zOS9mbGVldCIsInJlcG9zaXRvcnlfb3duZXIiOiJkZXpyZW4zOSIsIndvcmtmbG93IjoiZmxlZXQtZXhlYyIsIndvcmtmbG93X3JlZiI6ImRlenJlbjM5L2ZsZWV0Ly5naXRodWIvd29ya2Zsb3dzL2ZsZWV0LWV4ZWMueW1sQHJlZnMvaGVhZHMvbWFpbiIsImpvYl93b3JrZmxvd19yZWYiOiJkZXpyZW4zOS9mbGVldC8uZ2l0aHViL3dvcmtmbG93cy9mbGVldC1leGVjLnltbEByZWZzL2hlYWRzL21haW4iLCJydW5faWQiOiIxMjM0NTY3ODkiLCJydW5fYXR0ZW1wdCI6IjEiLCJldmVudF9uYW1lIjoid29ya2Zsb3dfZGlzcGF0Y2giLCJyZWYiOiJyZWZzL2hlYWRzL21haW4iLCJzaGEiOiI1ZDI4ZjAzZGY0MiJ9.dGPmPh4__6ksSCFlT0I7IClcTiGwKoeLexHGEkCkOjjrmSQzkDPQqLT_Sn2dZbZ_5TIt97FhJszmO7B2J9u707iGs8ts1D6H1ZTtpt17IkD68580MlA37IeRM5svsHTCOD56xvnPggJSJ7NkUTLpYQFPDePBjyUI-GG7N_o12OSMuNj7DBP1Uw7fUwi7ZytRLeNANxNN31T-bKsoXNKZ2Y36pr7hk9p3zo9C18iosVNwAARdrK5CPyG0_x499X7x1_qiXJwuMkfIXys9PfeHrH5GgjnPUVo9IZSC_AvdPdC0aWMpwLwr5gZNTisRRWqAfzgNbB3skeync8brxTCalg"; + const TEST_JWK_N: &str = "v-HGaXBUMPAM-kNMOETfcHvPUX-Rx0-mXHqK_KV6-1HuhDeCc2Tg2iD0z136S19t1-CIGvMvQyiKGIV5vUlrs1b7SIgh-YEbLNtESJr6soNpONOtIL_eH1ZI4WrL8RKmkK0OZpa4BRKyBooA2qIMDmcwa4Gl9Ae0wIgrRyHk0DnxLf2uTC3t8UtHvFPiM82pOv9DC3RpvMCtOay4-97P3T1Ir5mCMwRKex5KNApSGXmvTCfx6ALM7A7EAzi9-nRW_AlUPdiNDIh1qXLX8FG0Mw6OGOAyBFsbQ5tEc159dP74NB15AJeCTCW9gObJCc4jgXTWO5z9uQ3b81fnYLHX9Q"; + const TEST_JWK_E: &str = "AQAB"; + + /// One shared fake store for the whole module (tests use unique + /// handles, so they cannot collide), serving both the pipeline + /// endpoint and the test JWKS. + fn fake_store() -> &'static (String, Arc>) { + static STORE: std::sync::OnceLock<(String, Arc>)> = + std::sync::OnceLock::new(); + STORE.get_or_init(|| { + let conn = rusqlite::Connection::open_in_memory().unwrap(); + for ddl in [ + ACTIONS_EXEC_DDL_SESSIONS, + ACTIONS_EXEC_DDL_COMMANDS, + ACTIONS_EXEC_DDL_COMMANDS_IDX, + ACTIONS_EXEC_DDL_IO, + ACTIONS_EXEC_DDL_IO_IDX, + ] { + conn.execute_batch(ddl).unwrap(); + } + let db = Arc::new(Mutex::new(conn)); + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let base = format!("http://{addr}"); + // SAFETY: this OnceLock initializer runs once, before + // any test can read the variable, and the only reader + // is this module's OIDC path. + unsafe { + std::env::set_var("FLEET_ACTIONS_EXEC_JWKS_URL", format!("{base}/jwks")); + } + let db_thread = db.clone(); + std::thread::spawn(move || { + for sock in listener.incoming() { + let Ok(sock) = sock else { return }; + let db_conn = db_thread.clone(); + std::thread::spawn(move || handle_conn(sock, db_conn)); + } + }); + (base, db) + }) + } + + fn cell_json(v: rusqlite::types::ValueRef) -> Value { + use rusqlite::types::ValueRef::*; + match v { + Null => json!({"type": "null"}), + Integer(i) => json!({"type": "integer", "value": i.to_string()}), + Real(f) => json!({"type": "float", "value": f}), + Text(s) => json!({"type": "text", "value": String::from_utf8_lossy(s)}), + Blob(b) => json!({"type": "blob", "value": b64_encode(b)}), + } + } + + fn b64_encode(data: &[u8]) -> String { + const TBL: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::new(); + for chunk in data.chunks(3) { + let b = [ + chunk[0], + *chunk.get(1).unwrap_or(&0), + *chunk.get(2).unwrap_or(&0), + ]; + let n = ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | b[2] as u32; + out.push(TBL[(n >> 18) as usize & 63] as char); + out.push(TBL[(n >> 12) as usize & 63] as char); + out.push(if chunk.len() > 1 { + TBL[(n >> 6) as usize & 63] as char + } else { + '=' + }); + out.push(if chunk.len() > 2 { + TBL[n as usize & 63] as char + } else { + '=' + }); + } + out + } + + fn handle_conn(mut sock: std::net::TcpStream, db: Arc>) { + let mut reader = BufReader::new(sock.try_clone().unwrap()); + loop { + let mut request_line = String::new(); + if reader.read_line(&mut request_line).unwrap_or(0) == 0 { + return; + } + let mut content_length = 0usize; + loop { + let mut line = String::new(); + if reader.read_line(&mut line).unwrap_or(0) == 0 { + return; + } + let trimmed = line.trim(); + if trimmed.is_empty() { + break; + } + if let Some((name, value)) = trimmed.split_once(':') { + if name.trim().eq_ignore_ascii_case("content-length") { + content_length = value.trim().parse().unwrap_or(0); + } + } + } + let mut body = vec![0u8; content_length]; + if reader.read_exact(&mut body).is_err() { + return; + } + let (status, payload) = if request_line.contains("/jwks") { + ( + 200, + json!({"keys": [{"kty": "RSA", "kid": "test-kid-1", "use": "sig", + "alg": "RS256", "n": TEST_JWK_N, "e": TEST_JWK_E}]}), + ) + } else { + (200, run_pipeline(&db, &body)) + }; + let text = payload.to_string(); + let resp = format!( + "HTTP/1.1 {status} OK\r\nContent-Type: application/json\r\n\ + Content-Length: {}\r\n\r\n{}", + text.len(), + text + ); + if sock.write_all(resp.as_bytes()).is_err() { + return; + } + } + } + + fn run_pipeline(db: &Arc>, body: &[u8]) -> Value { + let req: Value = serde_json::from_slice(body).unwrap_or(Value::Null); + let conn = db.lock().unwrap(); + let mut results = Vec::new(); + for r in req + .get("requests") + .and_then(|v| v.as_array()) + .cloned() + .unwrap_or_default() + { + match r.get("type").and_then(|v| v.as_str()) { + Some("close") => { + results.push(json!({"type": "ok", "response": {"type": "close"}})); + } + Some("execute") => { + let stmt = r.get("stmt").cloned().unwrap_or(Value::Null); + let sql = stmt.get("sql").and_then(|v| v.as_str()).unwrap_or(""); + let mut params: Vec = Vec::new(); + if let Some(args) = stmt.get("args").and_then(|v| v.as_array()) { + for a in args { + params.push(match a.get("type").and_then(|v| v.as_str()) { + Some("text") => rusqlite::types::Value::Text( + a.get("value") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(), + ), + Some("integer") => rusqlite::types::Value::Integer( + a.get("value") + .and_then(|v| v.as_str()) + .and_then(|s| s.parse().ok()) + .unwrap_or(0), + ), + _ => rusqlite::types::Value::Null, + }); + } + } + results.push(execute_sql(&conn, sql, ¶ms)); + } + _ => {} + } + } + json!({"results": results, "baton": null}) + } + + fn execute_sql( + conn: &rusqlite::Connection, + sql: &str, + params: &[rusqlite::types::Value], + ) -> Value { + let is_query = sql.trim_start().to_ascii_uppercase().starts_with("SELECT"); + let mut stmt = match conn.prepare(sql) { + Ok(s) => s, + Err(e) => { + return json!({"type": "error", "error": {"message": e.to_string(), "code": "SQLITE"}}); + } + }; + if is_query { + let cols: Vec = stmt.column_names().map(|s| s.to_string()).collect(); + let mut rows_out = Vec::new(); + match stmt.query(rusqlite::params_from_iter(params.iter())) { + Ok(mut rows) => loop { + match rows.next() { + Ok(Some(row)) => { + let mut cells = Vec::new(); + for i in 0..cols.len() { + cells.push(cell_json(row.get_ref(i).unwrap())); + } + rows_out.push(Value::Array(cells)); + } + Ok(None) => break, + Err(e) => { + return json!({"type": "error", "error": {"message": e.to_string(), "code": "SQLITE"}}); + } + } + }, + Err(e) => { + return json!({"type": "error", "error": {"message": e.to_string(), "code": "SQLITE"}}); + } + } + json!({"type": "ok", "response": {"type": "execute", "result": { + "cols": cols.iter().map(|c| json!({"name": c, "decltype": null})).collect::>(), + "rows": rows_out, "affected_row_count": 0, "last_insert_rowid": null}}}) + } else { + match stmt.execute(rusqlite::params_from_iter(params.iter())) { + Ok(changed) => json!({"type": "ok", "response": {"type": "execute", "result": { + "cols": [], "rows": [], "affected_row_count": changed, + "last_insert_rowid": conn.last_insert_rowid().to_string()}}}), + Err(e) => { + json!({"type": "error", "error": {"message": e.to_string(), "code": "SQLITE"}}) + } + } + } + } + + fn backend() -> TursoBackend { + let (base, _) = fake_store(); + TursoBackend::new(base.clone(), "test".to_string(), ureq::agent()) + } + + fn open_session(t: &TursoBackend, handle: &str, lease_s: i64, max_s: i64) -> Value { + verb_actions_exec_open( + t, + &json!({ + "handle": handle, "host_repo": "dezren39/fleet", + "seat": "test-seat", "lease_s": lease_s, "max_s": max_s, + }), + ) + } + + #[test] + fn iso_parse_round_trips() { + for unix in [0, 1_700_000_000, 1_799_999_999, 4_102_444_800] { + assert_eq!(parse_iso(&iso(unix)), Some(unix), "unix {unix}"); + } + assert_eq!(parse_iso("not a date"), None); + assert_eq!(parse_iso("2026-11-23 15:00:00"), None); + } + + #[test] + fn open_validates_the_lease_contract() { + let t = backend(); + // No lease at all: the lease is required, there is no default. + let out = verb_actions_exec_open( + &t, + &json!({"host_repo": "dezren39/fleet", "seat": "s", "max_s": 1800}), + ); + assert_eq!(out["ok"], false, "{out}"); + // Lease past the max, and a max past the 2 h leg cap. + let out = open_session(&t, "fx-test-open1", 900, 600); + assert_eq!(out["ok"], false, "{out}"); + let out = open_session(&t, "fx-test-open2", 900, 7_201); + assert_eq!(out["ok"], false, "{out}"); + // A valid open names its lease and max. + let out = open_session(&t, "fx-test-open3", 900, 1_800); + assert_eq!(out["ok"], true, "{out}"); + assert_eq!(out["handle"], "fx-test-open3"); + assert_eq!(out["state"], "open"); + } + + #[test] + fn seat_flow_bind_command_stream_close() { + let t = backend(); + let h = "fx-test-flow1"; + assert_eq!(open_session(&t, h, 900, 1_800)["ok"], true); + let out = verb_actions_exec_bind(&t, &json!({"handle": h, "run_id": 42, "run_attempt": 2})); + assert_eq!(out["bound"], true, "{out}"); + let cmd = verb_actions_exec_command( + &t, + &json!({"handle": h, "text": "echo hello", "timeout_s": 30}), + ); + assert_eq!(cmd["ok"], true, "{cmd}"); + assert_eq!(cmd["seq"], 1); + let stream = verb_actions_exec_stream(&t, &json!({"handle": h})); + assert_eq!(stream["session"]["state"], "bound", "{stream}"); + assert_eq!(stream["commands"][0]["text"], "echo hello"); + assert_eq!(stream["commands"][0]["state"], "queued"); + // Close: queued commands are errored, the session is closed, + // and new commands are refused. + let out = verb_actions_exec_close(&t, &json!({"handle": h})); + assert_eq!(out["closed"], true, "{out}"); + let stream = verb_actions_exec_stream(&t, &json!({"handle": h})); + assert_eq!(stream["session"]["state"], "closed"); + assert_eq!(stream["commands"][0]["state"], "error"); + let out = verb_actions_exec_command(&t, &json!({"handle": h, "text": "echo nope"})); + assert_eq!(out["ok"], false, "{out}"); + } + + #[test] + fn renew_clamps_at_max_and_names_the_extension() { + let t = backend(); + let h = "fx-test-renew"; + assert_eq!(open_session(&t, h, 60, 120)["ok"], true); + // Ask for far more than the max: clamped, extension flagged. + let out = verb_actions_exec_renew(&t, &json!({"handle": h, "lease_s": 3600})); + assert_eq!(out["ok"], true, "{out}"); + assert_eq!(out["extension_required"], true, "{out}"); + let lease_unix = parse_iso(out["lease_until"].as_str().unwrap()).unwrap(); + let max_unix = parse_iso(out["max_until"].as_str().unwrap()).unwrap(); + assert_eq!( + lease_unix, max_unix, + "the clamped lease lands exactly on the max" + ); + // Once the max is in the past, renewal is refused outright. + t.exec( + "UPDATE actions_exec_sessions SET max_until = ?, lease_until = ? WHERE handle = ?", + &[ + Arg::Text(iso(now_unix() - 10)), + Arg::Text(iso(now_unix() - 10)), + Arg::Text(h.to_string()), + ], + ) + .unwrap(); + let out = verb_actions_exec_renew(&t, &json!({"handle": h, "lease_s": 600})); + assert_eq!(out["ok"], false, "{out}"); + } + + #[test] + fn extension_request_and_decision_move_the_max() { + let t = backend(); + let h = "fx-test-extend"; + assert_eq!(open_session(&t, h, 60, 120)["ok"], true); + verb_actions_exec_bind(&t, &json!({"handle": h, "run_id": 7, "run_attempt": 1})); + let out = verb_actions_exec_extend_request(&t, &json!({"handle": h, "extend_s": 1800})); + assert_eq!(out["requested"], true, "{out}"); + assert_eq!(out["run_id"], 7); + // A second request while one is pending is refused. + let out = verb_actions_exec_extend_request(&t, &json!({"handle": h})); + assert_eq!(out["ok"], false, "{out}"); + // Deny: state returns to live-shaped, max unmoved. + let out = verb_actions_exec_extend_decide(&t, &json!({"handle": h, "approve": false})); + assert_eq!(out["approved"], false, "{out}"); + let stream = verb_actions_exec_stream(&t, &json!({"handle": h})); + assert_eq!(stream["session"]["ext_state"], "denied"); + // Approve on a fresh request: max and lease both move +1800. + let before = stream["session"]["max_unix"].as_i64().unwrap(); + verb_actions_exec_extend_request(&t, &json!({"handle": h, "extend_s": 1800})); + let out = verb_actions_exec_extend_decide(&t, &json!({"handle": h, "approve": true})); + assert_eq!(out["approved"], true, "{out}"); + let stream = verb_actions_exec_stream(&t, &json!({"handle": h})); + assert_eq!( + stream["session"]["max_unix"].as_i64().unwrap(), + before + 1800 + ); + assert_eq!(stream["session"]["ext_state"], "approved"); + } + + #[test] + fn oidc_agent_flow_register_poll_io_result() { + let t = backend(); + let h = "fx-test-oidc1"; + assert_eq!(open_session(&t, h, 900, 1_800)["ok"], true); + // No token: refused before any state change. + let out = verb_actions_exec_register(&t, &json!({"handle": h})); + assert_eq!(out["ok"], false, "{out}"); + // A tampered token (signature edited): refused. + let mut tampered = TEST_JWT.to_string(); + let last = tampered.pop().unwrap(); + tampered.push(if last == 'A' { 'B' } else { 'A' }); + let out = verb_actions_exec_register(&t, &json!({"handle": h, "_oidc_jwt": tampered})); + assert_eq!(out["ok"], false, "{out}"); + // The real fixture: registers live and binds the run from + // the verified claims. + let out = verb_actions_exec_register(&t, &json!({"handle": h, "_oidc_jwt": TEST_JWT})); + assert_eq!(out["registered"], true, "{out}"); + let stream = verb_actions_exec_stream(&t, &json!({"handle": h})); + assert_eq!(stream["session"]["state"], "live"); + assert_eq!(stream["session"]["run_id"], 123_456_789); + assert_eq!(stream["session"]["run_attempt"], 1); + // Seat enqueues; agent polls it back, streams IO, records + // the exit code; the seat's stream shows all of it. + let cmd = verb_actions_exec_command(&t, &json!({"handle": h, "text": "echo hi"})); + let cmd_id = cmd["cmd_id"].as_str().unwrap().to_string(); + let poll = verb_actions_exec_poll( + &t, + &json!({"handle": h, "_oidc_jwt": TEST_JWT, "wait_s": 0}), + ); + assert_eq!(poll["commands"][0]["cmd_id"], cmd_id, "{poll}"); + let out = verb_actions_exec_io( + &t, + &json!({"handle": h, "_oidc_jwt": TEST_JWT, "cmd_id": cmd_id, + "seq": 1, "stream": "stdout", "data": "hi\n"}), + ); + assert_eq!(out["ok"], true, "{out}"); + let out = verb_actions_exec_result( + &t, + &json!({"handle": h, "_oidc_jwt": TEST_JWT, "cmd_id": cmd_id, "exit_code": 3}), + ); + assert_eq!(out["recorded"], true, "{out}"); + let stream = verb_actions_exec_stream(&t, &json!({"handle": h})); + assert_eq!(stream["chunks"][0]["data"], "hi\n"); + assert_eq!(stream["commands"][0]["state"], "done"); + assert_eq!(stream["commands"][0]["exit_code"], 3); + // A session opened for a different host rejects the token: + // the claims bind to dezren39/fleet, not to the other repo. + let h2 = "fx-test-oidc2"; + let out = verb_actions_exec_open( + &t, + &json!({"handle": h2, "host_repo": "developing-today/code", + "seat": "test-seat", "lease_s": 900, "max_s": 1800}), + ); + assert_eq!(out["ok"], true, "{out}"); + let out = verb_actions_exec_register(&t, &json!({"handle": h2, "_oidc_jwt": TEST_JWT})); + assert_eq!(out["ok"], false, "{out}"); + } + + #[test] + fn expired_lease_ends_the_session_on_poll() { + let t = backend(); + let h = "fx-test-expire"; + assert_eq!(open_session(&t, h, 900, 1_800)["ok"], true); + let out = verb_actions_exec_register(&t, &json!({"handle": h, "_oidc_jwt": TEST_JWT})); + assert_eq!(out["registered"], true, "{out}"); + // Drag the lease into the past: the next poll reports the + // session expired (and writes the transition back). + t.exec( + "UPDATE actions_exec_sessions SET lease_until = ? WHERE handle = ?", + &[Arg::Text(iso(now_unix() - 5)), Arg::Text(h.to_string())], + ) + .unwrap(); + let poll = verb_actions_exec_poll( + &t, + &json!({"handle": h, "_oidc_jwt": TEST_JWT, "wait_s": 0}), + ); + assert_eq!(poll["session"]["state"], "expired", "{poll}"); + let stream = verb_actions_exec_stream(&t, &json!({"handle": h})); + assert_eq!(stream["session"]["state"], "expired"); + } +} diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs index b84ffd38fe..c1cb922129 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue/core.rs @@ -822,10 +822,7 @@ impl TursoBackend { /// #13146: several statements in one pipeline request (the /// placement-sync batch insert). Same per-statement results as /// repeated `exec` calls, one round trip. - pub(crate) fn exec_batch( - &self, - stmts: &[(&str, Vec)], - ) -> Result, TErr> { + pub(crate) fn exec_batch(&self, stmts: &[(&str, Vec)]) -> Result, TErr> { self.pipeline(stmts) } @@ -986,7 +983,7 @@ impl Clone for Arg { } } -pub(crate) const SCHEMA: [&str; 19] = [ +pub(crate) const SCHEMA: [&str; 24] = [ "CREATE TABLE IF NOT EXISTS tasks (\ id INTEGER PRIMARY KEY AUTOINCREMENT, \ queue TEXT NOT NULL, title TEXT, body TEXT, \ @@ -1072,6 +1069,13 @@ pub(crate) const SCHEMA: [&str; 19] = [ created_at TEXT NOT NULL, updated_at TEXT NOT NULL)", "CREATE INDEX IF NOT EXISTS placement_sessions_created \ ON placement_sessions(created_at)", + // #13774: actions exec sessions — DDL of record in the + // actions_exec module. + crate::turso_queue::ACTIONS_EXEC_DDL_SESSIONS, + crate::turso_queue::ACTIONS_EXEC_DDL_COMMANDS, + crate::turso_queue::ACTIONS_EXEC_DDL_COMMANDS_IDX, + crate::turso_queue::ACTIONS_EXEC_DDL_IO, + crate::turso_queue::ACTIONS_EXEC_DDL_IO_IDX, ]; // --------------------------------------------------------------------------- diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue/stacks_outbox.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue/stacks_outbox.rs index dbacfcad95..e1202aae91 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue/stacks_outbox.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue/stacks_outbox.rs @@ -1055,6 +1055,18 @@ pub fn dispatch(t: &TursoBackend, path: &str, req: &Value) -> Value { "/outbox-metrics" => verb_outbox_metrics(t, req), "/sweep" => verb_sweep(t, req), "/coverage" => verb_coverage(t, req), + "/actions-exec-open" => verb_actions_exec_open(t, req), + "/actions-exec-bind" => verb_actions_exec_bind(t, req), + "/actions-exec-register" => verb_actions_exec_register(t, req), + "/actions-exec-poll" => verb_actions_exec_poll(t, req), + "/actions-exec-command" => verb_actions_exec_command(t, req), + "/actions-exec-io" => verb_actions_exec_io(t, req), + "/actions-exec-result" => verb_actions_exec_result(t, req), + "/actions-exec-stream" => verb_actions_exec_stream(t, req), + "/actions-exec-renew" => verb_actions_exec_renew(t, req), + "/actions-exec-extend-request" => verb_actions_exec_extend_request(t, req), + "/actions-exec-extend-decide" => verb_actions_exec_extend_decide(t, req), + "/actions-exec-close" => verb_actions_exec_close(t, req), _ => fail(2, format!("unknown command {path}")), } } diff --git a/pkgs/fleet/crates/fleet-registry/src/lib.rs b/pkgs/fleet/crates/fleet-registry/src/lib.rs index 130935bb38..47758a10c2 100644 --- a/pkgs/fleet/crates/fleet-registry/src/lib.rs +++ b/pkgs/fleet/crates/fleet-registry/src/lib.rs @@ -82,6 +82,11 @@ pub enum Capability { /// roots, issuers, leaves, chains and bundles (code#9157, fleet CA /// program #9155). A working-seat client surface, so full only. Cert, + /// `fleet actions …` — live short-lived exec sessions inside + /// GitHub Actions runners (#13774): the seat verbs, the + /// runner-side agent, and the egress helper. A working-seat + /// client surface, so full only. + Actions, } impl Capability { @@ -109,6 +114,7 @@ impl Capability { Capability::LaptopSsh => "laptop-ssh", Capability::Laptop => "laptop", Capability::Cert => "cert", + Capability::Actions => "actions", } } @@ -135,6 +141,7 @@ impl Capability { Capability::LaptopSsh, Capability::Laptop, Capability::Cert, + Capability::Actions, ]; } @@ -392,7 +399,14 @@ pub const DOMAINS: &[Domain] = &[ primary: Capability::Cert, aliases: &["pki"], subcommands: &[ - "root", "issuer", "leaf", "chain", "bundle", "profile", "algorithms", "explain", + "root", + "issuer", + "leaf", + "chain", + "bundle", + "profile", + "algorithms", + "explain", "doctor", ], }, @@ -436,6 +450,14 @@ pub const DOMAINS: &[Domain] = &[ aliases: &[], subcommands: &["tiers", "exec"], }, + Domain { + name: "actions", + summary: "Live short-lived exec sessions inside GitHub Actions runners (#13774), coordinator-handed-off: start a session in a runner, run commands in it, stream its IO, renew or extend its lease, close it.", + capabilities: &[Capability::Actions], + primary: Capability::Actions, + aliases: &[], + subcommands: &["exec", "agent", "put"], + }, ]; /// Look a domain up by canonical name. diff --git a/pkgs/fleet/crates/fleet/Cargo.toml b/pkgs/fleet/crates/fleet/Cargo.toml index 90c6daa1d2..5b198439f6 100644 --- a/pkgs/fleet/crates/fleet/Cargo.toml +++ b/pkgs/fleet/crates/fleet/Cargo.toml @@ -43,6 +43,9 @@ serde_json = { workspace = true } # The OpenCode session liveness probe (session_state.rs) only; # optional so the connect variant stays under the D7 size gate. base64 = { version = "0.23", optional = true } +# The actions domain's R2 egress helper (#13774): SigV4 signing +# over the workspace SHA-256. +sha2 = { workspace = true, optional = true } # The gh domain (code#8887) mints App installation tokens over the # GitHub API; same ureq pin as fleet-queue/fleet-search (rustls, no # native-tls). Only the JSON-free surface is needed: bodies are read @@ -92,6 +95,7 @@ full = [ "bridge", "agent", "cert", + "actions", "opencode-probe", ] # The serve variant's set, as one feature for the nix build. @@ -146,6 +150,10 @@ commander = ["dep:fleet-secrets", "dep:ureq"] http = ["dep:fleet-laptop-agent"] ssh = [] laptop = ["commander", "http", "ssh"] +# The actions domain (#13774): live exec sessions inside Actions +# runners — seat verbs over the queue client, the runner-side +# agent, and the R2 egress helper (SigV4 over sha2). Full only. +actions = ["dep:fleet-secrets", "dep:fleet-queue", "fleet-queue/client", "dep:ureq", "dep:sha2"] # Ask the local OpenCode server whether a worktree's recorded session # is live before reusing it (session_state.rs). In full and serve; # never in connect, where ureq+rustls would break the D7 2 MiB gate diff --git a/pkgs/fleet/crates/fleet/src/actions.rs b/pkgs/fleet/crates/fleet/src/actions.rs new file mode 100644 index 0000000000..5532c480de --- /dev/null +++ b/pkgs/fleet/crates/fleet/src/actions.rs @@ -0,0 +1,1498 @@ +//! `fleet actions` — developing-today/code#13774: live short-lived +//! exec sessions inside GitHub Actions runners, coordinator- +//! handed-off. +//! +//! The family has three leaves: +//! +//! - `fleet actions exec …` — the seat half. `start` opens a +//! session row at the queue broker (the coordinator), attempts +//! the #13765 placement claim (falling back to the singular path, +//! named in the output via `placement_path`, while those verbs +//! are not live), dispatches the `fleet-exec.yml` workflow with +//! only the session handle and non-secret parameters, and binds +//! the resulting run — the handoff is the handle plus the +//! portable `OWNER/REPO#RUN_ID` + attempt form. `run` sends one +//! command and streams its IO back; `attach` / `watch` stream a +//! session after handoff; `renew` extends the lease within the +//! max lifespan; `extend` asks past the max (the broker raises +//! the needs-drew alert; Drew's answer returns via `decide`); +//! `close` ends the session. +//! - `fleet actions agent …` — the runner half, run by the +//! fleet-exec-session composite action. It proves run membership +//! with the job's GitHub OIDC token (fetched from the Actions +//! runtime, never logged), registers with the broker's public +//! door, long-polls for commands, executes them in the workdir, +//! and streams IO back through the broker. The lease is enforced +//! locally too: the agent exits at expiry even if partitioned +//! from the broker. +//! - `fleet actions put ` — the egress helper (the agent +//! installs it on the session PATH as `fleet-exec-put`): copies +//! the file into the session outbox (uploaded as the run's +//! artifact) and, when the session carries R2 credentials, PUTs +//! it to the bucket with a SigV4 signature. No credential value +//! is ever printed. +//! +//! Lease discipline: `start` requires `--timeout` — the lease — +//! by construction (there is no default); `--max-lifespan` caps +//! the session (default 30 min, ceiling 2 h, the fleet leg cap). + +use std::io::{BufRead, BufReader, Read, Write}; +use std::process::{Command, Stdio}; +use std::sync::mpsc; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use fleet_config::Config; +use serde_json::{Value, json}; + +pub const ACTIONS_USAGE: &str = "\ +Usage: fleet actions [args...] + +Live short-lived exec sessions inside GitHub Actions runners +(#13774). Commands: + + exec start --repo OWNER/REPO --timeout S [--max-lifespan S] + [--ref R] [--target-repo OWNER/REPO] [--hide-logs] + [--detach] [--broker-url URL] + Open a session, dispatch fleet-exec.yml, print the + handoff (handle + OWNER/REPO#RUN_ID + attempt), then + attach unless --detach. --timeout is the lease and is + REQUIRED — there is no default. --repo is the workflow + host repo (default dezren39/fleet, where fleet-exec.yml + lives); its OIDC identity is what the broker binds. + exec run [--timeout S] -- + Run one command on the session's runner; streams its + output and exits with the command's exit code. + is a handle or the portable OWNER/REPO#RUN_ID form. + exec attach + Stream the session's IO (full replay) until it ends. + exec watch + Stream IO and report run/session status as it changes. + exec renew --timeout S + Extend the lease, clamped at the max lifespan. + exec extend [--minutes M] [--reason TEXT] + Request an emergency extension past the max lifespan; + the broker raises a needs-drew alert for Drew's + approve/deny. + exec decide --approve|--deny + Record Drew's answer to a pending extension request. + exec close + Close the session. + agent --handle H --broker-url URL --lease-seconds S + --max-seconds S --workdir D --outbox D [--hide-logs] + The runner-side agent (invoked by the Action). + put Copy a file to the session outbox (+ R2 when the + session carries credentials). Installed on the + session PATH as fleet-exec-put."; + +const EXIT_OK: i32 = 0; +const EXIT_ERROR: i32 = 1; +const EXIT_USAGE: i32 = 2; +const EXIT_TRANSPORT: i32 = 3; + +const DEFAULT_BROKER_URL: &str = "https://exec.security.cab"; +const DEFAULT_HOST_REPO: &str = "dezren39/fleet"; +const DEFAULT_WORKFLOW: &str = "fleet-exec.yml"; +const GH_TOKEN_SECRET: &str = "github.ghcr-classic-pat"; + +fn now_unix() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0) +} + +fn seat_name() -> String { + if let Ok(s) = std::env::var("FLEET_SEAT") { + if !s.is_empty() { + return s; + } + } + let user = std::env::var("USER").unwrap_or_else(|_| "seat".to_string()); + let host = std::env::var("HOSTNAME") + .ok() + .filter(|h| !h.is_empty()) + .or_else(|| { + std::fs::read_to_string("/etc/hostname") + .ok() + .map(|s| s.trim().to_string()) + }) + .unwrap_or_else(|| "unknown-host".to_string()); + format!("{user}@{host}") +} + +// --------------------------------------------------------------------------- +// Local session store: handle -> handoff record, so the portable +// OWNER/REPO#RUN_ID form resolves on the seat that started it. +// --------------------------------------------------------------------------- + +fn store_path() -> std::path::PathBuf { + fleet_config::Config::state_dir().join("actions-exec-sessions.json") +} + +fn store_load() -> Value { + std::fs::read_to_string(store_path()) + .ok() + .and_then(|s| serde_json::from_str(&s).ok()) + .unwrap_or_else(|| json!({})) +} + +fn store_save(store: &Value) { + let path = store_path(); + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + if let Ok(text) = serde_json::to_string_pretty(store) { + let _ = std::fs::write(&path, text); + } +} + +fn store_put(record: Value) { + let mut store = store_load(); + if let (Some(obj), Some(handle)) = ( + store.as_object_mut(), + record + .get("handle") + .and_then(|v| v.as_str()) + .map(str::to_string), + ) { + obj.insert(handle, record); + store_save(&store); + } +} + +/// Resolve a user reference — a bare handle or the portable +/// OWNER/REPO#RUN_ID form — to a session handle. +fn resolve_ref(reference: &str) -> Result { + if let Some((repo, run)) = reference.rsplit_once('#') { + if repo.contains('/') && run.chars().all(|c| c.is_ascii_digit()) && !run.is_empty() { + let store = store_load(); + if let Some(obj) = store.as_object() { + for (handle, rec) in obj { + if rec.get("host_repo").and_then(|v| v.as_str()) == Some(repo) + && rec.get("run_id").and_then(|v| v.as_i64()) == run.parse::().ok() + { + return Ok(handle.clone()); + } + } + } + return Err(format!( + "no local session record for {reference} (the portable form resolves on the seat that started the session; use the handle there)" + )); + } + } + Ok(reference.to_string()) +} + +// --------------------------------------------------------------------------- +// Broker envelope + GitHub helpers +// --------------------------------------------------------------------------- + +fn verb_err(v: &Value) -> String { + v.get("error") + .and_then(|e| e.as_str()) + .unwrap_or("broker returned an error envelope") + .to_string() +} + +fn check_envelope(v: Value) -> Result { + if v.get("ok").and_then(|o| o.as_bool()) == Some(true) { + Ok(v) + } else { + let code = v.get("exit").and_then(|e| e.as_i64()).unwrap_or(1) as i32; + Err((code, verb_err(&v))) + } +} + +fn gh_token(config: &Config) -> Result { + for var in ["GH_TOKEN", "GITHUB_TOKEN"] { + if let Ok(t) = std::env::var(var) { + if !t.is_empty() { + return Ok(t); + } + } + } + if let Ok(out) = Command::new("gh").args(["auth", "token"]).output() { + if out.status.success() { + let t = String::from_utf8_lossy(&out.stdout).trim().to_string(); + if !t.is_empty() { + return Ok(t); + } + } + } + fleet_secrets::Resolver::default_chain(config) + .resolve(GH_TOKEN_SECRET) + .map(|s| s.expose().to_string()) + .map_err(|e| format!("no GitHub token available (env, gh auth, or secret by name): {e}")) +} + +fn gh_api( + config: &Config, + method: &str, + path: &str, + body: Option<&Value>, +) -> Result { + let token = gh_token(config)?; + let url = format!("https://api.github.com{path}"); + let agent = ureq::agent(); + let mut resp = if method == "POST" { + agent + .post(&url) + .header("Accept", "application/vnd.github+json") + .header("X-GitHub-Api-Version", "2022-11-28") + .header("Authorization", &format!("Bearer {token}")) + .header("User-Agent", "fleet-actions") + .header("Content-Type", "application/json") + .send( + serde_json::to_string(&body.unwrap_or(&Value::Null)) + .unwrap_or_default() + .as_str(), + ) + .map_err(|e| format!("github api {method} {path}: transport: {e}"))? + } else { + agent + .get(&url) + .header("Accept", "application/vnd.github+json") + .header("X-GitHub-Api-Version", "2022-11-28") + .header("Authorization", &format!("Bearer {token}")) + .header("User-Agent", "fleet-actions") + .call() + .map_err(|e| format!("github api {method} {path}: transport: {e}"))? + }; + let status = resp.status().as_u16(); + let text = resp + .body_mut() + .read_to_string() + .map_err(|e| format!("github api {method} {path}: unreadable body: {e}"))?; + if !(200..300).contains(&status) { + let snippet: String = text.chars().take(200).collect(); + return Err(format!( + "github api {method} {path}: HTTP {status}: {snippet}" + )); + } + if text.trim().is_empty() { + return Ok(json!({})); + } + serde_json::from_str(&text).map_err(|e| format!("github api {method} {path}: bad JSON: {e}")) +} + +// --------------------------------------------------------------------------- +// `fleet actions exec …` — the seat half +// --------------------------------------------------------------------------- + +struct Flags { + map: std::collections::HashMap, + switches: std::collections::HashSet, + positional: Vec, +} + +fn parse_flags(args: &[String], value_flags: &[&str], switches: &[&str]) -> Result { + let mut out = Flags { + map: std::collections::HashMap::new(), + switches: std::collections::HashSet::new(), + positional: Vec::new(), + }; + let mut i = 0; + while i < args.len() { + let a = &args[i]; + if a == "--" { + out.positional.extend_from_slice(&args[i + 1..]); + break; + } else if let Some(name) = a.strip_prefix("--") { + if value_flags.contains(&name) { + let Some(v) = args.get(i + 1) else { + return Err(format!("--{name} needs a value")); + }; + out.map.insert(name.to_string(), v.clone()); + i += 2; + } else if switches.contains(&name) { + out.switches.insert(name.to_string()); + i += 1; + } else { + return Err(format!("unknown flag --{name}")); + } + } else { + out.positional.push(a.clone()); + i += 1; + } + } + Ok(out) +} + +impl Flags { + fn get(&self, name: &str) -> Option<&str> { + self.map.get(name).map(|s| s.as_str()) + } + fn has(&self, name: &str) -> bool { + self.switches.contains(name) + } + fn seconds(&self, name: &str) -> Result, String> { + match self.get(name) { + None => Ok(None), + Some(v) => v + .parse::() + .map(Some) + .map_err(|_| format!("--{name} must be whole seconds, got {v:?}")), + } + } +} + +pub fn run(config: &Config, args: &[String]) -> i32 { + match args.first().map(|s| s.as_str()) { + Some("exec") => exec_run(config, &args[1..]), + Some("agent") => agent_run(&args[1..]), + Some("put") => put_run(&args[1..]), + Some("--help") | Some("-h") | Some("help") | None => { + println!("{ACTIONS_USAGE}"); + EXIT_OK + } + Some(other) => { + eprintln!("fleet actions: unknown command {other:?}\n\n{ACTIONS_USAGE}"); + EXIT_USAGE + } + } +} + +fn exec_run(config: &Config, args: &[String]) -> i32 { + match args.first().map(|s| s.as_str()) { + Some("start") => exec_start(config, &args[1..]), + Some("run") => exec_command(config, &args[1..]), + Some("attach") => exec_attach(config, &args[1..], false), + Some("watch") => exec_attach(config, &args[1..], true), + Some("renew") => exec_renew(config, &args[1..]), + Some("extend") => exec_extend(config, &args[1..]), + Some("decide") => exec_decide(config, &args[1..]), + Some("close") => exec_close(config, &args[1..]), + Some("--help") | Some("-h") | None => { + println!("{ACTIONS_USAGE}"); + EXIT_OK + } + Some(other) => { + eprintln!("fleet actions exec: unknown command {other:?}\n\n{ACTIONS_USAGE}"); + EXIT_USAGE + } + } +} + +fn fail_out(code: i32, msg: &str) -> i32 { + eprintln!("fleet actions: {msg}"); + code +} + +fn exec_start(config: &Config, args: &[String]) -> i32 { + let flags = match parse_flags( + args, + &[ + "repo", + "workflow", + "ref", + "target-repo", + "target-ref", + "timeout", + "max-lifespan", + "broker-url", + ], + &["hide-logs", "detach"], + ) { + Ok(f) => f, + Err(e) => return fail_out(EXIT_USAGE, &e), + }; + // The lease is required by construction: no --timeout, no start. + let lease_s = match flags.seconds("timeout") { + Ok(Some(v)) => v, + Ok(None) => { + return fail_out( + EXIT_USAGE, + "exec start requires --timeout S (the session lease; there is no default)", + ); + } + Err(e) => return fail_out(EXIT_USAGE, &e), + }; + let max_s = match flags.seconds("max-lifespan") { + Ok(v) => v.unwrap_or(1800), + Err(e) => return fail_out(EXIT_USAGE, &e), + }; + let host_repo = flags.get("repo").unwrap_or(DEFAULT_HOST_REPO).to_string(); + let workflow = flags + .get("workflow") + .unwrap_or(DEFAULT_WORKFLOW) + .to_string(); + let broker_url = flags + .get("broker-url") + .map(str::to_string) + .or_else(|| std::env::var("FLEET_ACTIONS_EXEC_BROKER_URL").ok()) + .unwrap_or_else(|| DEFAULT_BROKER_URL.to_string()); + let seat = seat_name(); + + // 1. Open the session row at the coordinator. + let opened = match fleet_queue::client::actions_exec::ae_open( + &host_repo, + &workflow, + &seat, + lease_s, + max_s, + flags.has("hide-logs"), + ) + .and_then(check_envelope) + { + Ok(v) => v, + Err((c, m)) => return fail_out(c, &format!("open session: {m}")), + }; + let handle = opened + .get("handle") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + if handle.is_empty() { + return fail_out(EXIT_ERROR, "broker opened a session without a handle"); + } + + // 2. The #13765 coordinator claim: attempted first; while the + // verbs are not live the session proceeds on the singular path + // and says so (placement_path), per the design. + let coordinator = + fleet_queue::client::actions_exec::ae_placement_claim(&host_repo, &seat, &handle); + let placement_path = if coordinator { + "coordinator (#13765 claim granted)".to_string() + } else { + "singular (coordinator claim unavailable — #13765 verbs not live; session proceeds on the broker row alone)" + .to_string() + }; + + // 3. Dispatch the workflow with the handle + non-secret inputs. + let dispatch_ref = match flags.get("ref") { + Some(r) => r.to_string(), + None => gh_api(config, "GET", &format!("/repos/{host_repo}"), None) + .ok() + .and_then(|v| { + v.get("default_branch") + .and_then(|b| b.as_str()) + .map(str::to_string) + }) + .unwrap_or_else(|| "main".to_string()), + }; + let dispatch_body = json!({ + "ref": dispatch_ref, + "inputs": { + "handle": handle, + "broker_url": broker_url, + "repo": flags.get("target-repo").unwrap_or(""), + "ref": flags.get("target-ref").unwrap_or(""), + "lease_seconds": lease_s.to_string(), + "max_seconds": max_s.to_string(), + "hide_logs": if flags.has("hide-logs") { "true" } else { "false" }, + "agent_ref": "", + }, + }); + if let Err(e) = gh_api( + config, + "POST", + &format!("/repos/{host_repo}/actions/workflows/{workflow}/dispatches"), + Some(&dispatch_body), + ) { + let _ = fleet_queue::client::actions_exec::ae_close(&handle); + return fail_out(EXIT_ERROR, &format!("workflow dispatch: {e}")); + } + + // 4. Find the run (the workflow's run-name carries the handle) + // and bind it — that bind is the handoff. + let want_title = format!("Fleet exec session {handle}"); + let mut found: Option<(i64, i64)> = None; + let deadline = Instant::now() + Duration::from_secs(120); + while Instant::now() < deadline { + if let Ok(runs) = gh_api( + config, + "GET", + &format!( + "/repos/{host_repo}/actions/workflows/{workflow}/runs?event=workflow_dispatch&per_page=30" + ), + None, + ) { + if let Some(list) = runs.get("workflow_runs").and_then(|v| v.as_array()) { + for run in list { + if run.get("display_title").and_then(|v| v.as_str()) + == Some(want_title.as_str()) + { + if let (Some(id), Some(att)) = ( + run.get("id").and_then(|v| v.as_i64()), + run.get("run_attempt").and_then(|v| v.as_i64()), + ) { + found = Some((id, att)); + break; + } + } + } + } + } + if found.is_some() { + break; + } + std::thread::sleep(Duration::from_secs(5)); + } + let Some((run_id, run_attempt)) = found else { + return fail_out( + EXIT_ERROR, + "dispatched but the run did not appear within 120s; the session row stays open at the broker — check the workflow runs and bind by hand", + ); + }; + match fleet_queue::client::actions_exec::ae_bind(&handle, run_id, run_attempt) + .and_then(check_envelope) + { + Ok(_) => {} + Err((c, m)) => return fail_out(c, &format!("bind run: {m}")), + } + + let record = json!({ + "handle": handle, + "host_repo": host_repo, + "workflow": workflow, + "run_id": run_id, + "run_attempt": run_attempt, + "lease_until": opened.get("lease_until").cloned().unwrap_or(Value::Null), + "max_until": opened.get("max_until").cloned().unwrap_or(Value::Null), + "placement_path": placement_path, + "broker_url": broker_url, + "hide_logs": flags.has("hide-logs"), + }); + store_put(record); + + println!("session {handle} open on {host_repo}"); + println!("handoff: {handle} · {host_repo}#{run_id} attempt {run_attempt}"); + println!("run: https://github.com/{host_repo}/actions/runs/{run_id}"); + println!("placement_path: {placement_path}"); + println!( + "lease_until: {} · max_until: {}", + opened + .get("lease_until") + .and_then(|v| v.as_str()) + .unwrap_or("?"), + opened + .get("max_until") + .and_then(|v| v.as_str()) + .unwrap_or("?"), + ); + println!("form: actions/fleet (fleet actions exec start)"); + if flags.has("detach") { + println!( + "detached. drive it with: fleet actions exec run {handle} -- · watch: fleet actions exec watch {handle}" + ); + return EXIT_OK; + } + println!( + "attached — streaming session IO (commands go through `fleet actions exec run` from another shell; Ctrl-C detaches, the session lives on)" + ); + stream_session(&handle, true, None) +} + +/// Stream a session's IO from the broker, printing new chunks as +/// they land. With `only_cmd`, restricts to one command and returns +/// its exit code when it finishes. Otherwise streams until the +/// session reaches a terminal state. +fn stream_session(handle: &str, _replay: bool, only_cmd: Option<&str>) -> i32 { + let mut after_id: i64 = 0; + let mut last_state = String::new(); + loop { + let stream = match fleet_queue::client::actions_exec::ae_stream(handle, after_id, only_cmd) + .and_then(check_envelope) + { + Ok(v) => v, + Err((c, m)) => return fail_out(c, &format!("stream: {m}")), + }; + if let Some(chunks) = stream.get("chunks").and_then(|v| v.as_array()) { + for chunk in chunks { + if let Some(id) = chunk.get("id").and_then(|v| v.as_i64()) { + after_id = after_id.max(id); + } + let data = chunk.get("data").and_then(|v| v.as_str()).unwrap_or(""); + match chunk.get("stream").and_then(|v| v.as_str()) { + Some("stderr") => { + eprint!("{data}"); + let _ = std::io::stderr().flush(); + } + _ => { + print!("{data}"); + let _ = std::io::stdout().flush(); + } + } + } + } + let state = stream + .get("session") + .and_then(|s| s.get("state")) + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + if state != last_state { + if !last_state.is_empty() || only_cmd.is_some() { + eprintln!("[session {handle}: {state}]"); + } + last_state = state.clone(); + } + if let Some(cmd_id) = only_cmd { + if let Some(cmds) = stream.get("commands").and_then(|v| v.as_array()) { + for cmd in cmds { + if cmd.get("cmd_id").and_then(|v| v.as_str()) == Some(cmd_id) { + match cmd.get("state").and_then(|v| v.as_str()) { + Some("done") => { + return cmd.get("exit_code").and_then(|v| v.as_i64()).unwrap_or(0) + as i32; + } + Some("error") => { + return fail_out( + EXIT_ERROR, + "the command ended in error (session closed or expired)", + ); + } + _ => {} + } + } + } + } + } + if matches!(state.as_str(), "closed" | "expired") { + if only_cmd.is_some() { + return fail_out(EXIT_ERROR, "the session ended before the command finished"); + } + return EXIT_OK; + } + std::thread::sleep(Duration::from_secs(1)); + } +} + +fn exec_command(_config: &Config, args: &[String]) -> i32 { + // Split: flags before the reference; the command is everything + // after `--`, or the positional words after the reference. + let flags = match parse_flags(args, &["timeout"], &[]) { + Ok(f) => f, + Err(e) => return fail_out(EXIT_USAGE, &e), + }; + let Some(reference) = flags.positional.first() else { + return fail_out( + EXIT_USAGE, + "usage: fleet actions exec run [--timeout S] -- ", + ); + }; + let command_text = flags.positional[1..].join(" "); + if command_text.trim().is_empty() { + return fail_out(EXIT_USAGE, "exec run needs a command (after --)"); + } + let timeout_s = match flags.seconds("timeout") { + Ok(v) => v.unwrap_or(600), + Err(e) => return fail_out(EXIT_USAGE, &e), + }; + let handle = match resolve_ref(reference) { + Ok(h) => h, + Err(e) => return fail_out(EXIT_USAGE, &e), + }; + let cmd = match fleet_queue::client::actions_exec::ae_command(&handle, &command_text, timeout_s) + .and_then(check_envelope) + { + Ok(v) => v, + Err((c, m)) => return fail_out(c, &format!("enqueue command: {m}")), + }; + let cmd_id = cmd + .get("cmd_id") + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + if cmd_id.is_empty() { + return fail_out(EXIT_ERROR, "broker accepted the command without an id"); + } + stream_session(&handle, false, Some(&cmd_id)) +} + +fn exec_attach(_config: &Config, args: &[String], watch: bool) -> i32 { + let flags = match parse_flags(args, &[], &[]) { + Ok(f) => f, + Err(e) => return fail_out(EXIT_USAGE, &e), + }; + let Some(reference) = flags.positional.first() else { + return fail_out(EXIT_USAGE, "usage: fleet actions exec attach|watch "); + }; + let handle = match resolve_ref(reference) { + Ok(h) => h, + Err(e) => return fail_out(EXIT_USAGE, &e), + }; + if watch { + // One status snapshot up front (run + session), then the + // stream itself reports state changes as they happen. + if let Ok(stream) = + fleet_queue::client::actions_exec::ae_stream(&handle, 0, None).and_then(check_envelope) + { + let s = &stream["session"]; + println!( + "watching {handle}: state={} run={} attempt={} lease_until={} max_until={}", + s.get("state").and_then(|v| v.as_str()).unwrap_or("?"), + s.get("run_id").and_then(|v| v.as_i64()).unwrap_or(0), + s.get("run_attempt").and_then(|v| v.as_i64()).unwrap_or(0), + s.get("lease_until").and_then(|v| v.as_str()).unwrap_or("?"), + s.get("max_until").and_then(|v| v.as_str()).unwrap_or("?"), + ); + } + } + stream_session(&handle, true, None) +} + +fn ref_arg( + args: &[String], + value_flags: &[&str], + switches: &[&str], +) -> Result<(Flags, String), i32> { + let flags = match parse_flags(args, value_flags, switches) { + Ok(f) => f, + Err(e) => return Err(fail_out(EXIT_USAGE, &e)), + }; + let Some(reference) = flags.positional.first().cloned() else { + return Err(fail_out(EXIT_USAGE, "a session reference is required")); + }; + match resolve_ref(&reference) { + Ok(h) => Ok((flags, h)), + Err(e) => Err(fail_out(EXIT_USAGE, &e)), + } +} + +fn exec_renew(_config: &Config, args: &[String]) -> i32 { + let (flags, handle) = match ref_arg(args, &["timeout"], &[]) { + Ok(v) => v, + Err(c) => return c, + }; + let lease_s = match flags.seconds("timeout") { + Ok(Some(v)) => v, + Ok(None) => { + return fail_out( + EXIT_USAGE, + "renew requires --timeout S (the renewal names its lease)", + ); + } + Err(e) => return fail_out(EXIT_USAGE, &e), + }; + match fleet_queue::client::actions_exec::ae_renew(&handle, lease_s).and_then(check_envelope) { + Ok(v) => { + println!( + "renewed {handle}: lease_until={} max_until={} extension_required={}", + v.get("lease_until").and_then(|x| x.as_str()).unwrap_or("?"), + v.get("max_until").and_then(|x| x.as_str()).unwrap_or("?"), + v.get("extension_required") + .and_then(|x| x.as_bool()) + .unwrap_or(false), + ); + if v.get("extension_required").and_then(|x| x.as_bool()) == Some(true) { + println!( + "the ask passed the max lifespan and was clamped; past the max only an approved `fleet actions exec extend` helps" + ); + } + EXIT_OK + } + Err((c, m)) => fail_out(c, &format!("renew: {m}")), + } +} + +fn exec_extend(_config: &Config, args: &[String]) -> i32 { + let (flags, handle) = match ref_arg(args, &["minutes", "reason"], &[]) { + Ok(v) => v, + Err(c) => return c, + }; + let minutes: i64 = match flags.get("minutes") { + None => 30, + Some(v) => match v.parse() { + Ok(n) => n, + Err(_) => return fail_out(EXIT_USAGE, "--minutes must be a whole number"), + }, + }; + let reason = flags.get("reason").unwrap_or("").to_string(); + match fleet_queue::client::actions_exec::ae_extend_request(&handle, minutes * 60, &reason) + .and_then(check_envelope) + { + Ok(v) => { + if v.get("requested").and_then(|x| x.as_bool()) == Some(true) { + println!( + "extension requested for {handle}: +{}s past the max; the needs-drew alert is raised (source fleet-actions-exec, key actions-exec-ext:{handle}); decision grace runs to {}", + minutes * 60, + v.get("grace_until").and_then(|x| x.as_str()).unwrap_or("?"), + ); + println!( + "Drew's answer returns via: fleet actions exec decide {handle} --approve|--deny" + ); + EXIT_OK + } else { + fail_out(EXIT_ERROR, "the broker did not record the request") + } + } + Err((c, m)) => fail_out(c, &format!("extend: {m}")), + } +} + +fn exec_decide(_config: &Config, args: &[String]) -> i32 { + let (flags, handle) = match ref_arg(args, &[], &["approve", "deny"]) { + Ok(v) => v, + Err(c) => return c, + }; + let approve = match (flags.has("approve"), flags.has("deny")) { + (true, false) => true, + (false, true) => false, + _ => return fail_out(EXIT_USAGE, "decide needs exactly one of --approve / --deny"), + }; + match fleet_queue::client::actions_exec::ae_extend_decide(&handle, approve) + .and_then(check_envelope) + { + Ok(v) => { + if approve { + println!( + "extension approved for {handle}: max_until={} lease_until={}", + v.get("max_until").and_then(|x| x.as_str()).unwrap_or("?"), + v.get("lease_until").and_then(|x| x.as_str()).unwrap_or("?"), + ); + } else { + println!("extension denied for {handle}; the session expires on its lease"); + } + EXIT_OK + } + Err((c, m)) => fail_out(c, &format!("decide: {m}")), + } +} + +fn exec_close(_config: &Config, args: &[String]) -> i32 { + let (_flags, handle) = match ref_arg(args, &[], &[]) { + Ok(v) => v, + Err(c) => return c, + }; + match fleet_queue::client::actions_exec::ae_close(&handle).and_then(check_envelope) { + Ok(v) => { + println!( + "closed {handle}: {}", + if v.get("closed").and_then(|x| x.as_bool()) == Some(true) { + "session closed" + } else { + "already closed" + } + ); + EXIT_OK + } + Err((c, m)) => fail_out(c, &format!("close: {m}")), + } +} + +// --------------------------------------------------------------------------- +// `fleet actions agent` — the runner half +// --------------------------------------------------------------------------- + +/// Parse the broker's ISO-8601 UTC stamps (inverse of its civil +/// conversion; same algorithm as the broker's own). +fn parse_iso(s: &str) -> Option { + let b = s.as_bytes(); + if b.len() != 20 || b[4] != b'-' || b[7] != b'-' || b[10] != b'T' || b[19] != b'Z' { + return None; + } + let num = |i: usize, n: usize| -> Option { + let mut v: i64 = 0; + for k in 0..n { + let c = b[i + k]; + if !c.is_ascii_digit() { + return None; + } + v = v * 10 + (c - b'0') as i64; + } + Some(v) + }; + let (y, mo, d) = (num(0, 4)?, num(5, 2)?, num(8, 2)?); + let (h, mi, sec) = (num(11, 2)?, num(14, 2)?, num(17, 2)?); + // Days from civil (Howard Hinnant's algorithm). + let y_adj = if mo <= 2 { y - 1 } else { y }; + let era = if y_adj >= 0 { y_adj } else { y_adj - 399 } / 400; + let yoe = y_adj - era * 400; + let mp = (mo + 9) % 12; + let doy = (153 * mp + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + let days = era * 146097 + doe - 719468; + Some(days * 86400 + h * 3600 + mi * 60 + sec) +} + +/// Fetch a fresh OIDC token from the Actions runtime. The token is +/// a credential: it is only ever placed in the X-Agent-Token +/// header of broker calls, never printed. +fn fetch_oidc_token() -> Result { + let base = std::env::var("ACTIONS_ID_TOKEN_REQUEST_URL") + .map_err(|_| "ACTIONS_ID_TOKEN_REQUEST_URL is not set (not running in Actions?)")?; + let bearer = std::env::var("ACTIONS_ID_TOKEN_REQUEST_TOKEN") + .map_err(|_| "ACTIONS_ID_TOKEN_REQUEST_TOKEN is not set")?; + let sep = if base.contains('?') { '&' } else { '?' }; + let url = format!("{base}{sep}audience=fleet-actions-exec"); + let mut resp = ureq::get(&url) + .header("Authorization", &format!("Bearer {bearer}")) + .header("User-Agent", "fleet-actions-agent") + .call() + .map_err(|e| format!("oidc token fetch: transport: {e}"))?; + let text = resp + .body_mut() + .read_to_string() + .map_err(|e| format!("oidc token fetch: unreadable body: {e}"))?; + let v: Value = + serde_json::from_str(&text).map_err(|e| format!("oidc token fetch: bad JSON: {e}"))?; + v.get("value") + .and_then(|t| t.as_str()) + .filter(|t| !t.is_empty()) + .map(str::to_string) + .ok_or_else(|| "oidc token fetch: response carried no token".to_string()) +} + +/// One agent→broker call through the public door. Errors name the +/// path and status only — never headers, never the token. +fn agent_call(broker_url: &str, path: &str, jwt: &str, body: &Value) -> Result { + let url = format!("{}{path}", broker_url.trim_end_matches('/')); + let mut resp = ureq::post(&url) + .header("X-Agent-Token", jwt) + .header("User-Agent", "fleet-actions-agent") + .send(serde_json::to_string(body).unwrap_or_default().as_str()) + .map_err(|e| format!("{path}: transport: {e}"))?; + let status = resp.status().as_u16(); + let text = resp + .body_mut() + .read_to_string() + .map_err(|e| format!("{path}: unreadable body: {e}"))?; + if !(200..300).contains(&status) { + return Err(format!("{path}: HTTP {status}")); + } + let v: Value = serde_json::from_str(&text).map_err(|e| format!("{path}: bad JSON: {e}"))?; + if v.get("ok").and_then(|o| o.as_bool()) != Some(true) { + return Err(format!( + "{path}: {}", + v.get("error") + .and_then(|e| e.as_str()) + .unwrap_or("error envelope") + )); + } + Ok(v) +} + +struct AgentCtx { + broker_url: String, + handle: String, + workdir: String, + outbox: String, + hide_logs: bool, +} + +fn agent_run(args: &[String]) -> i32 { + let flags = match parse_flags( + args, + &[ + "handle", + "broker-url", + "lease-seconds", + "max-seconds", + "workdir", + "outbox", + ], + &["hide-logs"], + ) { + Ok(f) => f, + Err(e) => return fail_out(EXIT_USAGE, &e), + }; + let (Some(handle), Some(broker_url), Some(workdir), Some(outbox)) = ( + flags.get("handle"), + flags.get("broker-url"), + flags.get("workdir"), + flags.get("outbox"), + ) else { + return fail_out( + EXIT_USAGE, + "agent requires --handle, --broker-url, --workdir and --outbox", + ); + }; + let max_s: i64 = flags + .get("max-seconds") + .and_then(|v| v.parse().ok()) + .unwrap_or(1800); + let started = now_unix(); + let local_max_deadline = started + max_s; + let ctx = AgentCtx { + broker_url: broker_url.to_string(), + handle: handle.to_string(), + workdir: workdir.to_string(), + outbox: outbox.to_string(), + hide_logs: flags.has("hide-logs"), + }; + let _ = std::fs::create_dir_all(&ctx.outbox); + install_put_helper(&ctx); + + // Register with a fresh OIDC token; the verified claims bind + // this run to the session row. + let jwt = match fetch_oidc_token() { + Ok(t) => t, + Err(e) => return fail_out(EXIT_ERROR, &e), + }; + let registered = match agent_call( + &ctx.broker_url, + "/actions-exec-register", + &jwt, + &json!({"handle": ctx.handle}), + ) { + Ok(v) => v, + Err(e) => return fail_out(EXIT_ERROR, &format!("register: {e}")), + }; + let lease_deadline = registered + .get("lease_until") + .and_then(|v| v.as_str()) + .and_then(parse_iso) + .unwrap_or(local_max_deadline); + let mut deadline = lease_deadline.min(local_max_deadline); + eprintln!( + "fleet actions agent: session {} live; lease deadline {deadline}", + ctx.handle + ); + + loop { + if now_unix() >= deadline { + eprintln!("fleet actions agent: lease expired; exiting"); + return EXIT_OK; + } + let jwt = match fetch_oidc_token() { + Ok(t) => t, + Err(e) => { + eprintln!("fleet actions agent: {e} (retrying)"); + std::thread::sleep(Duration::from_secs(5)); + continue; + } + }; + let poll = match agent_call( + &ctx.broker_url, + "/actions-exec-poll", + &jwt, + &json!({"handle": ctx.handle, "wait_s": 20}), + ) { + Ok(v) => v, + Err(e) => { + // Partition tolerance: the broker holds the + // session; keep retrying until the LOCAL deadline + // (the lease is enforced here too). + eprintln!("fleet actions agent: poll: {e} (retrying until the local deadline)"); + std::thread::sleep(Duration::from_secs(5)); + continue; + } + }; + if let Some(d) = poll + .get("session") + .and_then(|s| s.get("deadline_unix")) + .and_then(|v| v.as_i64()) + { + deadline = d.min(local_max_deadline); + } + let state = poll + .get("session") + .and_then(|s| s.get("state")) + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_string(); + if matches!(state.as_str(), "closed" | "expired") { + eprintln!("fleet actions agent: session {state}; exiting"); + // Best-effort close so the seat sees a terminal row + // even when the lease, not the seat, ended it. + if state == "expired" { + if let Ok(jwt) = fetch_oidc_token() { + let _ = agent_call( + &ctx.broker_url, + "/actions-exec-close", + &jwt, + &json!({"handle": ctx.handle}), + ); + } + } + return EXIT_OK; + } + if let Some(cmds) = poll.get("commands").and_then(|v| v.as_array()) { + for cmd in cmds { + run_one_command(&ctx, cmd); + } + } + } +} + +/// Write the fleet-exec-put helper into a session bin dir beside +/// the outbox and prepend it to this process's PATH (inherited by +/// every command shell the agent spawns). +fn install_put_helper(ctx: &AgentCtx) { + let parent = std::path::Path::new(&ctx.outbox) + .parent() + .map(|p| p.to_path_buf()) + .unwrap_or_else(|| std::path::PathBuf::from(".")); + let bin_dir = parent.join("fleet-exec-bin"); + if std::fs::create_dir_all(&bin_dir).is_err() { + return; + } + let exe = std::env::current_exe() + .map(|p| p.to_string_lossy().into_owned()) + .unwrap_or_else(|_| "fleet".to_string()); + let script = format!( + "#!/bin/sh\n# fleet-exec-put: session egress helper (#13774).\nexec \"{exe}\" actions put \"$@\"\n" + ); + let path = bin_dir.join("fleet-exec-put"); + if std::fs::write(&path, script).is_ok() { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)); + } + let old = std::env::var("PATH").unwrap_or_default(); + unsafe { + std::env::set_var("PATH", format!("{}:{old}", bin_dir.to_string_lossy())); + } + } +} + +/// Execute one queued command: stream its IO to the broker (and to +/// this process's own stdout unless the session hides logs), then +/// record the exit code. +fn run_one_command(ctx: &AgentCtx, cmd: &Value) { + let cmd_id = cmd.get("cmd_id").and_then(|v| v.as_str()).unwrap_or(""); + let text = cmd.get("text").and_then(|v| v.as_str()).unwrap_or(""); + let timeout_s = cmd.get("timeout_s").and_then(|v| v.as_i64()).unwrap_or(600); + if cmd_id.is_empty() || text.is_empty() { + return; + } + eprintln!("fleet actions agent: running {cmd_id}: {text}"); + let mut child = match Command::new("bash") + .args(["-c", text]) + .current_dir(&ctx.workdir) + .env("FLEET_EXEC_OUTBOX", &ctx.outbox) + .env("FLEET_EXEC_HANDLE", &ctx.handle) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + { + Ok(c) => c, + Err(e) => { + post_result(ctx, cmd_id, 127); + eprintln!("fleet actions agent: spawn failed for {cmd_id}: {e}"); + return; + } + }; + let (tx, rx) = mpsc::channel::<(&'static str, String)>(); + fn spawn_reader( + name: &'static str, + stream: R, + tx: mpsc::Sender<(&'static str, String)>, + ) { + std::thread::spawn(move || { + let mut reader = BufReader::new(stream); + let mut line = String::new(); + loop { + line.clear(); + match reader.read_line(&mut line) { + Ok(0) | Err(_) => break, + Ok(_) => { + if tx.send((name, line.clone())).is_err() { + break; + } + } + } + } + }); + } + if let Some(out) = child.stdout.take() { + spawn_reader("stdout", out, tx.clone()); + } + if let Some(err) = child.stderr.take() { + spawn_reader("stderr", err, tx.clone()); + } + drop(tx); + let mut seq = 0i64; + let mut bufs: std::collections::HashMap<&'static str, String> = + std::collections::HashMap::new(); + let started = Instant::now(); + let mut exit_code: Option = None; + let mut timed_out = false; + loop { + match rx.recv_timeout(Duration::from_millis(200)) { + Ok((stream, data)) => { + if !ctx.hide_logs { + match stream { + "stderr" => { + eprint!("{data}"); + let _ = std::io::stderr().flush(); + } + _ => { + print!("{data}"); + let _ = std::io::stdout().flush(); + } + } + } + let buf = bufs.entry(stream).or_default(); + buf.push_str(&data); + if buf.len() >= 16384 { + seq += 1; + let chunk = std::mem::take(buf); + post_io(ctx, cmd_id, seq, stream, &chunk); + } + } + Err(mpsc::RecvTimeoutError::Timeout) => {} + Err(mpsc::RecvTimeoutError::Disconnected) => { + // Both pipes closed; reap below. + if let Ok(status) = child.wait() { + exit_code = status.code(); + break; + } + } + } + if started.elapsed() > Duration::from_secs(timeout_s.max(1) as u64) { + let _ = child.kill(); + timed_out = true; + let _ = child.wait(); + exit_code = Some(124); + break; + } + if exit_code.is_none() { + if let Ok(Some(status)) = child.try_wait() { + exit_code = status.code(); + // Drain whatever the reader threads still hold. + while let Ok((stream, data)) = rx.try_recv() { + if !ctx.hide_logs { + match stream { + "stderr" => eprint!("{data}"), + _ => print!("{data}"), + } + } + bufs.entry(stream).or_default().push_str(&data); + } + break; + } + } + } + for (stream, buf) in &bufs { + if !buf.is_empty() { + seq += 1; + post_io(ctx, cmd_id, seq, stream, buf); + } + } + if timed_out { + seq += 1; + post_io( + ctx, + cmd_id, + seq, + "stderr", + &format!("fleet actions agent: command timed out after {timeout_s}s\n"), + ); + } + post_result(ctx, cmd_id, exit_code.unwrap_or(1)); +} + +fn post_io(ctx: &AgentCtx, cmd_id: &str, seq: i64, stream: &str, data: &str) { + // IO chunks are capped at 64 KiB by the broker; flush in + // slices cut on char boundaries. + let mut rest = data; + while !rest.is_empty() { + let mut cut = rest.len().min(32768); + while cut > 0 && !rest.is_char_boundary(cut) { + cut -= 1; + } + if cut == 0 { + break; + } + let (text, tail) = rest.split_at(cut); + rest = tail; + match fetch_oidc_token() { + Ok(jwt) => { + let _ = agent_call( + &ctx.broker_url, + "/actions-exec-io", + &jwt, + &json!({ + "handle": ctx.handle, "cmd_id": cmd_id, "seq": seq, + "stream": stream, "data": text, + }), + ); + } + Err(e) => eprintln!("fleet actions agent: io post skipped: {e}"), + } + } +} + +fn post_result(ctx: &AgentCtx, cmd_id: &str, exit_code: i32) { + if let Ok(jwt) = fetch_oidc_token() { + let _ = agent_call( + &ctx.broker_url, + "/actions-exec-result", + &jwt, + &json!({"handle": ctx.handle, "cmd_id": cmd_id, "exit_code": exit_code}), + ); + } +} + +// --------------------------------------------------------------------------- +// `fleet actions put` — the egress helper +// --------------------------------------------------------------------------- + +fn put_run(args: &[String]) -> i32 { + let flags = match parse_flags(args, &[], &[]) { + Ok(f) => f, + Err(e) => return fail_out(EXIT_USAGE, &e), + }; + let Some(file) = flags.positional.first() else { + return fail_out(EXIT_USAGE, "usage: fleet actions put "); + }; + let outbox = match std::env::var("FLEET_EXEC_OUTBOX") { + Ok(d) if !d.is_empty() => d, + _ => { + return fail_out( + EXIT_USAGE, + "FLEET_EXEC_OUTBOX is not set — put runs inside a session (as fleet-exec-put)", + ); + } + }; + let src = std::path::Path::new(file); + let Some(name) = src.file_name().map(|n| n.to_string_lossy().into_owned()) else { + return fail_out(EXIT_USAGE, "the file has no name"); + }; + let bytes = match std::fs::read(src) { + Ok(b) => b, + Err(e) => return fail_out(EXIT_ERROR, &format!("read {file}: {e}")), + }; + if std::fs::create_dir_all(&outbox).is_err() { + return fail_out(EXIT_ERROR, "cannot create the outbox directory"); + } + let dst = std::path::Path::new(&outbox).join(&name); + if let Err(e) = std::fs::write(&dst, &bytes) { + return fail_out(EXIT_ERROR, &format!("write outbox copy: {e}")); + } + println!( + "put: {name} ({} bytes) -> session outbox (workflow artifact)", + bytes.len() + ); + // The R2 leg: only when the session carries credentials, and + // quietly skipped otherwise. Values come from the environment + // the workflow populated from masked secrets; never printed. + let (Ok(key_id), Ok(secret), Ok(endpoint), Ok(bucket)) = ( + std::env::var("FLEET_EXEC_R2_ACCESS_KEY_ID"), + std::env::var("FLEET_EXEC_R2_SECRET_ACCESS_KEY"), + std::env::var("FLEET_EXEC_R2_ENDPOINT"), + std::env::var("FLEET_EXEC_R2_BUCKET"), + ) else { + return EXIT_OK; + }; + if key_id.is_empty() || secret.is_empty() || endpoint.is_empty() || bucket.is_empty() { + return EXIT_OK; + } + let handle = std::env::var("FLEET_EXEC_HANDLE").unwrap_or_else(|_| "session".to_string()); + let key = format!("fleet-exec/{handle}/{name}"); + match r2_put(&endpoint, &bucket, &key, &key_id, &secret, &bytes) { + Ok(()) => { + println!("put: {name} -> R2 {bucket}/{key}"); + EXIT_OK + } + Err(e) => fail_out(EXIT_ERROR, &format!("R2 put: {e}")), + } +} + +// --- SigV4 (S3-compatible, R2) ---------------------------------------------- + +fn sha256(data: &[u8]) -> [u8; 32] { + use sha2::Digest; + let mut h = sha2::Sha256::new(); + h.update(data); + h.finalize().into() +} + +fn sha256_hex(data: &[u8]) -> String { + sha256(data).iter().map(|b| format!("{b:02x}")).collect() +} + +fn hmac_sha256(key: &[u8], data: &[u8]) -> Vec { + let mut block = if key.len() > 64 { + sha256(key).to_vec() + } else { + key.to_vec() + }; + block.resize(64, 0); + let ipad: Vec = block.iter().map(|b| b ^ 0x36).collect(); + let opad: Vec = block.iter().map(|b| b ^ 0x5c).collect(); + let mut inner = ipad; + inner.extend_from_slice(data); + let inner_hash = sha256(&inner); + let mut outer = opad; + outer.extend_from_slice(&inner_hash); + sha256(&outer).to_vec() +} + +fn amz_dates(unix: i64) -> (String, String) { + // Civil from days (Hinnant), the inverse of parse_iso. + let days = unix.div_euclid(86400); + let secs = unix.rem_euclid(86400); + let z = days + 719468; + let era = if z >= 0 { z } else { z - 146096 } / 146097; + let doe = z - era * 146097; + let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = if m <= 2 { y + 1 } else { y }; + let (hh, mm, ss) = (secs / 3600, (secs % 3600) / 60, secs % 60); + ( + format!("{year:04}{m:02}{d:02}"), + format!("{year:04}{m:02}{d:02}T{hh:02}{mm:02}{ss:02}Z"), + ) +} + +fn r2_put( + endpoint: &str, + bucket: &str, + key: &str, + access_key: &str, + secret_key: &str, + bytes: &[u8], +) -> Result<(), String> { + let endpoint = endpoint.trim_end_matches('/'); + let host = endpoint + .strip_prefix("https://") + .or_else(|| endpoint.strip_prefix("http://")) + .unwrap_or(endpoint) + .split('/') + .next() + .unwrap_or("") + .to_string(); + if host.is_empty() { + return Err("the R2 endpoint has no host".to_string()); + } + let path = format!("/{bucket}/{key}"); + let url = format!("{endpoint}{path}"); + let payload_hash = sha256_hex(bytes); + let (datestamp, amzdate) = amz_dates(now_unix()); + let region = "auto"; + let service = "s3"; + let canonical_headers = + format!("host:{host}\nx-amz-content-sha256:{payload_hash}\nx-amz-date:{amzdate}\n"); + let signed_headers = "host;x-amz-content-sha256;x-amz-date"; + let canonical_request = + format!("PUT\n{path}\n\n{canonical_headers}\n{signed_headers}\n{payload_hash}"); + let scope = format!("{datestamp}/{region}/{service}/aws4_request"); + let string_to_sign = format!( + "AWS4-HMAC-SHA256\n{amzdate}\n{scope}\n{}", + sha256_hex(canonical_request.as_bytes()) + ); + let k_date = hmac_sha256(format!("AWS4{secret_key}").as_bytes(), datestamp.as_bytes()); + let k_region = hmac_sha256(&k_date, region.as_bytes()); + let k_service = hmac_sha256(&k_region, service.as_bytes()); + let k_signing = hmac_sha256(&k_service, b"aws4_request"); + let signature = hmac_sha256(&k_signing, string_to_sign.as_bytes()) + .iter() + .map(|b| format!("{b:02x}")) + .collect::(); + let authorization = format!( + "AWS4-HMAC-SHA256 Credential={access_key}/{scope}, SignedHeaders={signed_headers}, Signature={signature}" + ); + let mut resp = ureq::put(&url) + .header("Authorization", &authorization) + .header("x-amz-date", &amzdate) + .header("x-amz-content-sha256", &payload_hash) + .header("User-Agent", "fleet-actions-put") + .send(bytes) + .map_err(|e| format!("transport: {e}"))?; + let status = resp.status().as_u16(); + if (200..300).contains(&status) { + Ok(()) + } else { + let _ = resp.body_mut().read_to_string(); + Err(format!("HTTP {status}")) + } +} diff --git a/pkgs/fleet/crates/fleet/src/main.rs b/pkgs/fleet/crates/fleet/src/main.rs index 2bf65c08e5..12451e16fa 100644 --- a/pkgs/fleet/crates/fleet/src/main.rs +++ b/pkgs/fleet/crates/fleet/src/main.rs @@ -51,6 +51,17 @@ mod secrets; #[cfg(feature = "gh")] mod gh; +#[cfg(feature = "actions")] +mod actions; +#[cfg(feature = "commander")] +mod commander; +#[cfg(any( + feature = "commander", + feature = "http", + feature = "ssh", + feature = "laptop" +))] +mod forms; #[cfg(feature = "gh")] mod gh_cache; #[cfg(feature = "gh")] @@ -59,23 +70,14 @@ mod gh_closure; mod gh_guard; #[cfg(feature = "gh")] mod gh_metadata; -#[cfg(feature = "commander")] -mod commander; #[cfg(feature = "http")] mod http; -#[cfg(feature = "ssh")] -mod ssh; +mod invocation_ledger; #[cfg(feature = "laptop")] mod laptop; -#[cfg(any( - feature = "commander", - feature = "http", - feature = "ssh", - feature = "laptop" -))] -mod forms; -mod invocation_ledger; mod session_state; +#[cfg(feature = "ssh")] +mod ssh; #[allow(dead_code)] // the derivation runs in build.rs (which includes this module by path); the binary itself consumes only the baked FLEET_DERIVED_VERSION value, plus these unit tests @@ -153,6 +155,9 @@ fn compiled_capabilities() -> CapabilitySet { if cfg!(feature = "cert") { caps.insert(Capability::Cert); } + if cfg!(feature = "actions") { + caps.insert(Capability::Actions); + } caps } @@ -834,6 +839,18 @@ fn run_domain_with_initializer( println!("{}", fleet_cert::cli::CERT_USAGE); return EXIT_OK; } + // The actions domain's own usage answers `fleet actions + // --help` (#13774): the registry help names the leaves but not + // the lease contract — the same carve-out the cert domain + // gets above. + #[cfg(feature = "actions")] + if d.name == "actions" + && args.first().is_some_and(|a| is_help_flag(a)) + && surface.cap_state(Capability::Actions, d.name) == CapState::Available + { + println!("{}", actions::ACTIONS_USAGE); + return EXIT_OK; + } // The proxy role under its serve spelling has its own usage // (SERVE_PROXY_USAGE, #6770): `fleet serve proxy --help` asks for // the role's help, not the serve domain's — answer it before the @@ -1035,6 +1052,12 @@ fn run_domain_with_initializer( if d.name == "laptop" { return laptop::run(&surface.config, args); } + // #13774: the actions domain runs for real — live exec + // sessions inside Actions runners (seat + agent + put). + #[cfg(feature = "actions")] + if d.name == "actions" { + return actions::run(&surface.config, args); + } // code#8887: the gh domain runs for real — the real // `gh` binary as a passthrough under the token // rotation (App installations, then personal last). diff --git a/pkgs/fleet/docs/verbs.md b/pkgs/fleet/docs/verbs.md index 1296452435..56bd2598d5 100644 --- a/pkgs/fleet/docs/verbs.md +++ b/pkgs/fleet/docs/verbs.md @@ -362,6 +362,57 @@ daemon's general client. | `health` | Run `hostname` over ssh; exit 0 iff the host answers. | | `exec [--cwd DIR] [--timeout SECS] -- CMD...` | Run a command line over ssh under the binary-owned client contract (pinned host key, proxy CONNECT, fleet-owned multiplex master); the remote exit code propagates; the binary deadline exits 124. ssh's own failure exit is 255. | | `close` | Tear down the fleet-owned multiplex master, if any. | +## `actions` — live exec sessions in Actions runners + +`fleet actions exec start --repo OWNER/REPO --timeout S +[--max-lifespan S] [--ref R] [--target-repo OWNER/REPO] +[--hide-logs] [--detach] [--broker-url URL]` + +Open a session at the queue broker, attempt the #13765 +coordinator claim (the singular fallback names itself in the +output as `placement_path` while those verbs are not live), +dispatch `fleet-exec.yml` with only the handle and non-secret +inputs, bind the run, and print the handoff: the handle plus the +portable `OWNER/REPO#RUN_ID` form and the run attempt. `--timeout` +is the session lease and is required — there is no default; +`--max-lifespan` defaults to 1800 s and caps at 7200 s. Without +`--detach`, start attaches and streams session IO. + +`fleet actions exec run [--timeout S] -- ` — +enqueue one command on the session's runner, stream its output, +exit with the command's exit code (default command timeout +600 s). `` is a handle or the portable `OWNER/REPO#RUN_ID` +form. + +`fleet actions exec attach ` / `fleet actions exec watch +` — stream the session's IO after handoff (watch also +reports run/session status). `fleet actions exec renew +--timeout S` extends the lease, clamped at the max lifespan; +the reply names `extension_required` when the ask passed the +max. `fleet actions exec extend [--minutes M] [--reason +TEXT]` requests an emergency extension past the max: the broker +records it and raises the needs-drew alert (source +`fleet-actions-exec`, key `actions-exec-ext:`); `fleet +actions exec decide --approve|--deny` records the answer +(approval adds the minutes to the max and the lease). `fleet +actions exec close ` closes the session. + +`fleet actions agent --handle H --broker-url URL +--lease-seconds S --max-seconds S --workdir D --outbox D +[--hide-logs]` — the runner half, invoked by the +fleet-exec-session composite action: registers with the job's +GitHub OIDC token (never logged), long-polls for commands, runs +them in the workdir, streams IO through the broker (echoed to +the run log unless `--hide-logs`), installs `fleet-exec-put` on +the session PATH, and exits at lease expiry even if partitioned. + +`fleet actions put ` — the egress helper (session PATH +name `fleet-exec-put`): copies the file into the session outbox +(the run's `fleet-exec-out` artifact) and, when the session +carries `FLEET_EXEC_R2_*` credentials, PUTs it to R2 under +`fleet-exec//` with a SigV4 signature. Credential values +are never printed. + ## Exit and availability Usage errors generally exit 2. Capability stubs exit 69. Some domains define additional statuses, such as queue transport unavailable or `agent next` having no work. A successful command's exit code and output belong to its handler; preserve both when wrapping Fleet in scripts.