Skip to main content

lean_ctx_cloud/
team_stop.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The team stop (kill switch) as the Cloud reports it to an engine
3//! (`GET /v1/stop`, acting as the person the instance is linked to).
4//!
5//! A stopped team's engines get `423 team_stopped` from the Cloud on its
6//! writes, landings and Code sessions. Nothing here gates anything on this
7//! machine: local agent tools keep working (owner decision 19.11.). This
8//! module only reads the state for `cloud status` and the `cloud stop`
9//! commands, and keeps the last answer of the enrolled server in
10//! `<data>/team-stop.json` with the time it was read. `cloud status` reads
11//! only that file (never the Cloud): the scheduler tick and the `cloud stop`
12//! commands refresh it, and status names its age (`age_s`) and whether it is
13//! older than two pull intervals (`stale`).
14//!
15//! The Cloud answers `200 {team, stopped, since, by: {id, name}, reason,
16//! generation, role, may_stop, may_release, company?: {admin}, step_up_url?}`;
17//! the instance credential names the team (no org in the route). Before any
18//! call of `/v1/stop` the engine reads `GET /v1/capabilities`: a Cloud that
19//! does not announce `team_stop` is "not offered" and hears nothing of it;
20//! a `404` from the route reads the same (`Ok(None)`).
21
22use serde::{Deserialize, Serialize};
23use serde_json::Value;
24
25use crate::CloudError;
26use crate::config::CloudConfig;
27use crate::state::{CloudStore, write_private};
28use crate::transport::CloudClient;
29
30/// The Cloud route (under `/v1`): `GET` the state, `POST {reason}` stops,
31/// `DELETE {confirm, note?}` releases.
32pub const PATH: &str = "/stop";
33/// The `features` entry of a Cloud that offers the team stop.
34pub const FEATURE: &str = "team_stop";
35/// Largest answer read.
36pub const MAX_ANSWER_BYTES: usize = 64 * 1024;
37/// Longest reason the Cloud keeps (and this engine sends).
38pub const MAX_REASON_CHARS: usize = 500;
39/// The last answer.
40const FILE: &str = "team-stop.json";
41
42/// The team stop as one answer of the Cloud, checked.
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub struct TeamStop {
45    /// The team's slug (what `--confirm` must name).
46    pub team: String,
47    pub stopped: bool,
48    /// When the stop began, as the Cloud wrote it (RFC 3339).
49    pub since: Option<String>,
50    /// Who stopped it (display name).
51    pub by: Option<String>,
52    pub reason: Option<String>,
53    /// Counts stops and releases (the Cloud's; `0` when absent).
54    pub generation: u64,
55    /// The linked person's acting role in the team.
56    pub role: Option<String>,
57    pub may_stop: bool,
58    pub may_release: bool,
59    /// Whether the person administers the team's company; `None` when the
60    /// Cloud does not say (or the team has no company).
61    pub company_admin: Option<bool>,
62    /// The browser page that confirms a release (two-factor), when the
63    /// Cloud named one.
64    pub step_up_url: Option<String>,
65}
66
67impl TeamStop {
68    /// The page that confirms a release: the Cloud's when it lies below the
69    /// web app's origin, else the web app's stop page of the team when this
70    /// person may release an active stop.
71    #[must_use]
72    pub fn release_link(&self, web_origin: &str) -> Option<String> {
73        if let Some(url) = self
74            .step_up_url
75            .as_ref()
76            .filter(|u| below_origin(u, web_origin))
77        {
78            return Some(url.clone());
79        }
80        (self.stopped && self.may_release)
81            .then(|| format!("{}/o/{}/stop/", web_origin.trim_end_matches('/'), self.team))
82    }
83}
84
85/// Whether `slug` has the Cloud's slug shape (`[a-z0-9-]`, 1–64).
86#[must_use]
87pub fn is_slug(slug: &str) -> bool {
88    !slug.is_empty()
89        && slug.len() <= 64
90        && slug
91            .bytes()
92            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
93}
94
95/// The Cloud's words, safe for a terminal: control characters become
96/// spaces, at most `max` characters; `None` when nothing is left.
97#[must_use]
98pub fn safe_text(text: &str, max: usize) -> Option<String> {
99    let text: String = text
100        .chars()
101        .map(|c| if c.is_control() { ' ' } else { c })
102        .take(max)
103        .collect();
104    let text = text.trim();
105    (!text.is_empty()).then(|| text.to_owned())
106}
107
108/// Whether `url` is a plain link below `origin` (same scheme, host and
109/// port; no whitespace or control characters).
110#[must_use]
111pub fn below_origin(url: &str, origin: &str) -> bool {
112    let origin = origin.trim_end_matches('/');
113    url.len() <= 2048
114        && !origin.is_empty()
115        && !url.chars().any(|c| c.is_control() || c.is_whitespace())
116        && url
117            .strip_prefix(origin)
118            .is_some_and(|rest| rest.starts_with('/'))
119}
120
121/// The checked state of a `200` answer. `team` and `stopped` are required;
122/// other members that are malformed are left out, never repaired.
123pub fn decode(body: &Value) -> Result<TeamStop, CloudError> {
124    let bad = |why: &str| CloudError::Protocol(format!("team stop: {why}"));
125    let team = body["team"]
126        .as_str()
127        .filter(|t| is_slug(t))
128        .ok_or_else(|| bad("team is not a slug"))?;
129    let stopped = body["stopped"]
130        .as_bool()
131        .ok_or_else(|| bad("stopped is not a boolean"))?;
132    let since = body["since"]
133        .as_str()
134        .filter(|t| t.len() <= 64 && t.chars().all(|c| c.is_ascii_graphic()))
135        .map(str::to_owned);
136    let role = body["role"]
137        .as_str()
138        .filter(|r| {
139            !r.is_empty() && r.len() <= 32 && r.bytes().all(|b| b.is_ascii_lowercase() || b == b'_')
140        })
141        .map(str::to_owned);
142    Ok(TeamStop {
143        team: team.to_owned(),
144        stopped,
145        since: since.filter(|_| stopped),
146        // The display name, else the email when the person set no name.
147        by: ["name", "email"]
148            .iter()
149            .find_map(|key| body["by"][*key].as_str().and_then(|n| safe_text(n, 200)))
150            .filter(|_| stopped),
151        reason: body["reason"]
152            .as_str()
153            .and_then(|r| safe_text(r, MAX_REASON_CHARS))
154            .filter(|_| stopped),
155        generation: body["generation"].as_u64().unwrap_or(0),
156        role,
157        may_stop: body["may_stop"].as_bool() == Some(true),
158        may_release: body["may_release"].as_bool() == Some(true),
159        company_admin: body["company"]["admin"].as_bool(),
160        step_up_url: body["step_up_url"]
161            .as_str()
162            .filter(|u| {
163                let host = u
164                    .strip_prefix("https://")
165                    .or_else(|| u.strip_prefix("http://"));
166                host.is_some_and(|rest| !rest.starts_with('/'))
167                    && u.len() <= 2048
168                    && !u.chars().any(|c| c.is_control() || c.is_whitespace())
169            })
170            .map(str::to_owned),
171    })
172}
173
174/// `GET /v1/stop` with `client`. A `401` is an error, so the session mints a
175/// new token once and then reports it.
176pub fn fetch(client: &CloudClient) -> Result<(u16, Value), CloudError> {
177    let (status, body) = client.send_answer("GET", PATH, None, MAX_ANSWER_BYTES)?;
178    if status == 401 {
179        return Err(CloudError::Unauthorized);
180    }
181    Ok((status, body))
182}
183
184/// Whether the Cloud `client` talks to offers the team stop: asks
185/// `GET /v1/capabilities` and records the answer for `server` (the enrolled
186/// origin), as every feature check does.
187pub fn offered(store: &CloudStore, server: &str, client: &CloudClient) -> Result<bool, CloudError> {
188    crate::session_ref::refresh(store, server, client)?;
189    Ok(crate::session_ref::announced(store, FEATURE))
190}
191
192/// A refusal of `/v1/stop` the team stop does not name itself, in the
193/// shared mapping of every cloud call.
194#[must_use]
195pub fn refused(status: u16, body: &Value) -> CloudError {
196    CloudError::from_response(status, body)
197}
198
199/// The state of a `GET /v1/stop` answer; `None` from a Cloud without the
200/// route.
201pub fn classify(status: u16, body: &Value) -> Result<Option<TeamStop>, CloudError> {
202    let code = body["error"]["code"].as_str().unwrap_or_default();
203    match status {
204        200 => decode(body).map(Some),
205        404 if code.is_empty() || code == "not_found" => Ok(None),
206        403 => Err(CloudError::Forbidden),
207        _ => Err(CloudError::from_response(status, body)),
208    }
209}
210
211#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
212#[serde(default)]
213struct Cache {
214    /// The origin that answered; another enrolled server reads none of it.
215    server: String,
216    /// The team and the enrolment it was read for: after a new `cloud
217    /// connect` (another team on the same server, `--keep-local`) none of
218    /// it is read.
219    org_id: String,
220    instance_id: String,
221    /// `None`: this Cloud does not offer the team stop (it answered `404`).
222    stop: Option<TeamStop>,
223    /// When it answered (seconds since the Unix epoch, this machine's clock).
224    read_at: Option<u64>,
225}
226
227/// A kept answer of the Cloud and how old it is.
228#[derive(Debug, Clone, PartialEq, Eq)]
229pub struct TeamStopRead {
230    pub stop: TeamStop,
231    /// Seconds since the Cloud answered it; `None` when unknown (an older
232    /// file, or a clock that went back).
233    pub age_s: Option<u64>,
234    /// Older than two pull intervals, or of unknown age: the tick did not
235    /// refresh it as it should.
236    pub stale: bool,
237}
238
239/// What `cloud status` knows of the team stop, from the kept answer only.
240#[derive(Debug, Clone, PartialEq, Eq)]
241pub enum Cached {
242    /// Connected, but no answer kept yet (no tick or `cloud stop` ran).
243    Missing,
244    /// This Cloud does not offer the team stop.
245    NotOffered,
246    Kept(TeamStopRead),
247}
248
249fn now_unix() -> u64 {
250    std::time::SystemTime::now()
251        .duration_since(std::time::UNIX_EPOCH)
252        .map_or(0, |d| d.as_secs())
253}
254
255/// The team stop for `cloud status`: the kept answer of the enrolled
256/// server, never a call of the Cloud. `None` when not enrolled.
257pub fn read(store: &CloudStore, config: &CloudConfig) -> Option<Cached> {
258    let instance = store.instance().ok()??;
259    let Some(cache) = load(store).filter(|c| c.is_for(&instance)) else {
260        return Some(Cached::Missing);
261    };
262    let Some(stop) = cache.stop else {
263        return Some(Cached::NotOffered);
264    };
265    let age_s = cache.read_at.and_then(|at| now_unix().checked_sub(at));
266    let fresh_for = u64::from(config.pull_interval()) * 60 * 2;
267    Some(Cached::Kept(TeamStopRead {
268        stop,
269        age_s,
270        stale: age_s.is_none_or(|age| age > fresh_for),
271    }))
272}
273
274/// Ask the Cloud with `session` and keep its answer (the tick, and the
275/// `cloud stop` commands through [`keep`]). A failure keeps the last answer;
276/// a Cloud that does not announce [`FEATURE`] is asked nothing else.
277pub fn refresh_with(
278    store: &CloudStore,
279    session: &crate::auth::Session,
280) -> Result<Option<TeamStop>, CloudError> {
281    let server = session.instance.url.clone();
282    if !session.with_client(|client| offered(store, &server, client))? {
283        keep(store, None);
284        return Ok(None);
285    }
286    let (status, body) = session.with_client(fetch)?;
287    let stop = classify(status, &body)?;
288    keep(store, stop.as_ref());
289    Ok(stop)
290}
291
292/// The Cloud session of this machine for the team stop: none when
293/// `[cloud] enabled = false`, not connected, or the lease lapsed (as every
294/// other cloud call off the tick).
295pub fn session(
296    store: &CloudStore,
297    config: &CloudConfig,
298) -> Result<crate::auth::Session, CloudError> {
299    crate::scheduler::connected_session(store, config)
300}
301
302/// Fill the team-stop members of `cloud status --json` from `cached`
303/// (`web_origin`: the web app's origin, for the release link). Nothing for
304/// a Cloud that does not offer the stop.
305pub fn apply(
306    status: &mut lean_ctx_protocol::cloud::status::CloudCliStatusV1,
307    cached: &Cached,
308    web_origin: &str,
309) {
310    use lean_ctx_protocol::cloud::status::{CloudStatusCompanyV1, CloudStatusTeamStopV1};
311    let read = match cached {
312        Cached::NotOffered => return,
313        // No answer kept yet: `team_stop: null`, never defaults that read
314        // as a running team nobody may stop.
315        Cached::Missing => {
316            status.team_stop = Some(None);
317            return;
318        }
319        Cached::Kept(read) => read,
320    };
321    let stop = &read.stop;
322    status.team_stop = Some(Some(CloudStatusTeamStopV1 {
323        active: stop.stopped,
324        reason: stop.reason.clone(),
325        since: stop.since.clone(),
326        by: stop.by.clone(),
327        generation: stop.generation,
328        may_stop: stop.may_stop,
329        may_release: stop.may_release,
330        cache: if read.stale { "stale" } else { "fresh" }.into(),
331        age_s: read.age_s,
332    }));
333    status.role.clone_from(&stop.role);
334    status.org_slug = Some(stop.team.clone());
335    status.company = stop
336        .company_admin
337        .map(|admin| CloudStatusCompanyV1 { admin });
338    status.step_up_url = stop.release_link(web_origin).filter(|_| stop.stopped);
339}
340
341/// Keep `stop` as the answer of the enrolled server just read (`None`: it
342/// does not offer the team stop). Fail-safe: a Cloud that stops offering it
343/// does not clear a kept stop of the team; that stop stays, of unknown age
344/// (so `stale`), until the Cloud answers the state again.
345pub fn keep(store: &CloudStore, stop: Option<&TeamStop>) {
346    let Ok(Some(instance)) = store.instance() else {
347        return;
348    };
349    let (stop, read_at) = match stop {
350        Some(stop) => (Some(stop.clone()), Some(now_unix())),
351        None => match load(store).filter(|c| c.is_for(&instance)) {
352            Some(Cache {
353                stop: Some(kept), ..
354            }) if kept.stopped => (Some(kept), None),
355            _ => (None, Some(now_unix())),
356        },
357    };
358    let cache = Cache {
359        server: instance.url,
360        org_id: instance.org_id,
361        instance_id: instance.instance_id,
362        stop,
363        read_at,
364    };
365    if let Ok(bytes) = serde_json::to_vec_pretty(&cache) {
366        let _ = write_private(store.data_dir(), FILE, &bytes);
367    }
368}
369
370impl Cache {
371    /// Read for this enrolment: its server, its team and its instance.
372    fn is_for(&self, instance: &crate::state::InstanceRecord) -> bool {
373        self.server == instance.url
374            && self.org_id == instance.org_id
375            && self.instance_id == instance.instance_id
376    }
377}
378
379fn load(store: &CloudStore) -> Option<Cache> {
380    std::fs::read(store.data_dir().join(FILE))
381        .ok()
382        .and_then(|b| serde_json::from_slice(&b).ok())
383}
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388    use serde_json::json;
389
390    fn stopped() -> Value {
391        json!({
392            "team": "acme-platform",
393            "stopped": true,
394            "since": "2026-11-19T10:00:00Z",
395            "by": {"id": "8d0c", "name": "Ada\u{1b}[2J Lovelace"},
396            "reason": "runaway agent\nspending",
397            "generation": 3,
398            "team_stop": {"since": "2026-11-19T10:00:00Z", "generation": 3},
399            "role": "admin",
400            "may_stop": true,
401            "may_release": true,
402            "signed": {"v": 1, "signature": "sig"}
403        })
404    }
405
406    #[test]
407    fn a_stop_is_checked_and_its_words_made_safe() {
408        let stop = decode(&stopped()).unwrap();
409        assert_eq!(
410            stop,
411            TeamStop {
412                team: "acme-platform".into(),
413                stopped: true,
414                since: Some("2026-11-19T10:00:00Z".into()),
415                by: Some("Ada [2J Lovelace".into()),
416                reason: Some("runaway agent spending".into()),
417                generation: 3,
418                role: Some("admin".into()),
419                may_stop: true,
420                may_release: true,
421                company_admin: None,
422                step_up_url: None,
423            }
424        );
425        assert_eq!(
426            stop.release_link("https://cloud.leanctx.com/").as_deref(),
427            Some("https://cloud.leanctx.com/o/acme-platform/stop/")
428        );
429    }
430
431    #[test]
432    fn a_running_team_names_no_stopper_and_no_release_link() {
433        let body = json!({"team": "acme", "stopped": false, "since": null, "by": null,
434            "reason": null, "generation": 4, "role": "contributor", "may_stop": true,
435            "may_release": false, "company": {"admin": true}});
436        let stop = decode(&body).unwrap();
437        assert!(!stop.stopped && stop.by.is_none() && stop.reason.is_none());
438        assert_eq!(stop.company_admin, Some(true));
439        assert_eq!(stop.release_link("https://cloud.leanctx.com"), None);
440    }
441
442    #[test]
443    fn a_stopper_without_a_name_is_named_by_email() {
444        let mut body = stopped();
445        body["by"] = json!({"id": "8d0c", "name": null, "email": "ada@acme.test"});
446        assert_eq!(decode(&body).unwrap().by.as_deref(), Some("ada@acme.test"));
447        body["by"] = json!({"id": "8d0c", "name": "  ", "email": "ada@acme.test"});
448        assert_eq!(decode(&body).unwrap().by.as_deref(), Some("ada@acme.test"));
449    }
450
451    #[test]
452    fn a_broken_answer_is_refused_and_odd_members_left_out() {
453        for bad in [
454            json!({"stopped": true}),
455            json!({"team": "Acme Co", "stopped": true}),
456            json!({"team": "acme", "stopped": "yes"}),
457        ] {
458            assert!(
459                matches!(decode(&bad), Err(CloudError::Protocol(_))),
460                "{bad}"
461            );
462        }
463        let mut body = stopped();
464        body["role"] = json!("Admin<b>");
465        body["since"] = json!("2026-11-19 10:00");
466        body["may_release"] = json!("true");
467        body["step_up_url"] = json!("javascript:alert(1)");
468        let stop = decode(&body).unwrap();
469        assert_eq!(
470            (stop.role, stop.since, stop.may_release, stop.step_up_url),
471            (None, None, false, None)
472        );
473        body["step_up_url"] = json!("https://cloud.leanctx.com/o/acme-platform/stop/");
474        assert!(decode(&body).unwrap().step_up_url.is_some());
475    }
476
477    #[test]
478    fn links_stay_below_their_origin() {
479        let origin = "https://cloud.leanctx.com";
480        assert!(below_origin("https://cloud.leanctx.com/o/a/stop/", origin));
481        for bad in [
482            "https://cloud.leanctx.com.evil.example/o/a/stop/",
483            "https://evil.example/o/a/stop/",
484            "https://cloud.leanctx.com/o/a b/",
485            "https://cloud.leanctx.com",
486        ] {
487            assert!(!below_origin(bad, origin), "{bad}");
488        }
489    }
490
491    #[test]
492    fn an_older_cloud_offers_no_stop_and_a_refusal_is_an_error() {
493        assert_eq!(classify(404, &json!({})).unwrap(), None);
494        assert_eq!(
495            classify(403, &json!({"error": {"code": "forbidden"}})).unwrap_err(),
496            CloudError::Forbidden
497        );
498        assert!(classify(200, &stopped()).unwrap().unwrap().stopped);
499    }
500}