use serde::{Deserialize, Serialize};
use super::error::Revocation;
use super::state::{CloudStore, InstanceRecord};
use super::{CloudError, workers::canonical_instance_id};
pub(crate) const REVOKED_FILE: &str = "revoked.json";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct RevokedRecord {
instance_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
reason: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
revoked_at: Option<u64>,
}
fn named(instance: &InstanceRecord, mut r: Revocation) -> CloudError {
r.workspace = Some(instance.org_name.clone()).filter(|n| !n.trim().is_empty());
CloudError::Revoked(r)
}
pub(crate) fn note(store: &CloudStore, instance: &InstanceRecord, error: CloudError) -> CloudError {
let CloudError::Revoked(r) = error else {
return error;
};
let own = canonical_instance_id(&instance.instance_id);
let ours = r
.instance_id
.as_deref()
.is_none_or(|id| canonical_instance_id(id) == own);
if ours {
let record = RevokedRecord {
instance_id: own,
reason: r.reason.clone(),
revoked_at: r.revoked_at,
};
if let Err(e) = store.write_config(REVOKED_FILE, &record) {
tracing::warn!("cloud: could not record the revocation: {e}");
}
super::receipts::stop_local_recording(store.data_dir());
}
named(instance, r)
}
pub(crate) fn recorded(store: &CloudStore, instance: &InstanceRecord) -> Option<CloudError> {
let record = store
.read_config::<RevokedRecord>(REVOKED_FILE)
.ok()
.flatten()?;
(record.instance_id == canonical_instance_id(&instance.instance_id)).then(|| {
named(
instance,
Revocation {
workspace: None,
reason: record.reason,
revoked_at: record.revoked_at,
instance_id: Some(record.instance_id),
},
)
})
}
pub fn clear(store: &CloudStore) -> Result<(), CloudError> {
store.remove_config(REVOKED_FILE)
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
use crate::config::CloudConfig;
const FIXTURE: &str = include_str!(
"../../../crates/lean-ctx-protocol/tests/fixtures/cloud-v2/routes/instance_revoked.error.json"
);
fn instance(id: &str) -> InstanceRecord {
InstanceRecord {
instance_id: id.into(),
org_id: "4b6d8f0a-2c4e-4f6a-8b0c-2e4f6a8c0e1a".into(),
org_name: "acme".into(),
label: "laptop".into(),
url: "https://cloud.example".into(),
org_salt_id: "s".into(),
enrolled_at: "2026-10-25T10:00:00Z".into(),
web_url: None,
org_kind: None,
company_name: None,
}
}
#[test]
fn the_c0_revocation_body_is_one_clear_refusal() {
let body: serde_json::Value = serde_json::from_str(FIXTURE).unwrap();
let error = CloudError::from_response(401, &body);
let CloudError::Revoked(r) = &error else {
panic!("{error:?}");
};
assert_eq!(r.reason.as_deref(), Some("key_compromise"));
assert_eq!(r.revoked_at, Some(1_792_800_500_000));
assert!(!error.is_transient(), "never retried");
assert_eq!(
error.to_string(),
"this instance was revoked by its workspace (key compromise); reconnect with \
`lean-ctx cloud connect` after an admin allows it"
);
let newer = CloudError::from_response(
401,
&json!({"error": {"code": "brand_new", "message": "x"}}),
);
assert!(matches!(newer, CloudError::Server { status: 401, .. }));
}
#[test]
fn a_noted_revocation_closes_the_session_until_a_new_connect() {
let dir = tempfile::tempdir().unwrap();
let store = CloudStore::at(dir.path().join("c"), dir.path().join("d"));
let own = instance("inst_8e3c0d5f2b4e4f609b8c1d2e3f4a5b6c");
store
.write_config(crate::state::INSTANCE_FILE, &own)
.unwrap();
assert!(recorded(&store, &own).is_none());
let other = CloudError::Revoked(Revocation {
instance_id: Some("11111111-2222-4333-8444-555555555555".into()),
..Revocation::default()
});
let _ = note(&store, &own, other);
assert!(recorded(&store, &own).is_none());
let body: serde_json::Value = serde_json::from_str(FIXTURE).unwrap();
let shown = note(&store, &own, CloudError::from_response(401, &body));
assert!(
shown
.to_string()
.starts_with("this instance was revoked by acme")
);
let again = recorded(&store, &own).expect("recorded");
assert_eq!(again, shown);
let error = crate::auth::Session::load(store.clone(), [7; 32])
.err()
.expect("closed");
assert_eq!(error, shown);
let status = crate::status::report(
&store,
&CloudConfig::default(),
lean_ctx_time::UtcDateTime::now(),
);
assert!(!status.connected());
assert!(status.lease.is_none(), "no valid lease shown");
assert_eq!(status.problem.as_deref(), Some(shown.to_string().as_str()));
assert!(recorded(&store, &instance("inst_00000000000040008000000000000001")).is_none());
clear(&store).unwrap();
assert!(recorded(&store, &own).is_none());
}
#[test]
fn a_revocation_stops_metrics_and_receipts_recording() {
let dir = tempfile::tempdir().unwrap();
let data = dir.path().join("d");
let store = CloudStore::at(dir.path().join("c"), data.clone());
let own = instance("inst_8e3c0d5f2b4e4f609b8c1d2e3f4a5b6c");
store
.write_config(crate::state::INSTANCE_FILE, &own)
.unwrap();
crate::metrics_v2::secrets::enable(&data).unwrap();
crate::state::write_private(&data, "receipts.enabled", b"1").unwrap();
assert!(store.may_record());
let body: serde_json::Value = serde_json::from_str(FIXTURE).unwrap();
let _ = note(&store, &own, CloudError::from_response(401, &body));
assert!(!crate::metrics_v2::secrets::enabled(&data));
assert!(!data.join("receipts.enabled").is_file());
assert!(!store.may_record(), "revoked: nothing records");
}
}