mod config;
mod diag;
mod grants;
mod host;
mod meter;
mod secret_file;
mod users;
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use lean_ctx_cloud::CloudStore;
const CONFIG_ENV: &str = "LEANCTX_COMPUTER_CONFIG";
const CONFIG_DEFAULT: &str = "/etc/leanctx/computer.json";
const ENROL_CREDENTIAL: &str = "enrol.token";
const METER_CREDENTIAL: &str = "meter.token";
const SERVICE_USER: &str = "leanctx";
const STATE_DIR: &str = "/var/lib/leanctx";
const GRANTS_FILE: &str = "/var/lib/leanctx/grants.json";
const STATUS_FILE: &str = "/var/lib/leanctx/computer-status.json";
const USERS_FILE: &str = "/var/lib/leanctx-users/computer-users.json";
const SSH_DIR: &str = "/etc/ssh";
const UNIT: &str = "lean-ctx-computer.service";
const KEYS_PATH: &str = "/me/computer/authorized-keys";
const PERIOD: Duration = Duration::from_secs(60);
const FAILED_START_PAUSE: Duration = Duration::from_secs(60);
const UNIT_FILE: &str = include_str!("lean-ctx-computer.service");
const USERS_UNIT_FILE: &str = include_str!("lean-ctx-computer-users.service");
const USERS_PATH_FILE: &str = include_str!("lean-ctx-computer-users.path");
const HELP: &str = "The cloud computer agent (runs on the computer itself)\n\n\
Usage: lean-ctx computer run Enrol once, then meter and fetch SSH grants every minute (lean-ctx-computer.service)\n\
\x20 lean-ctx computer sync-users Turn the fetched grants into Unix users (root; lean-ctx-computer-users.service)\n\
\x20 lean-ctx computer diag Diagnostic menu for SSH logins: status, help\n\
\x20 lean-ctx computer unit [users|path] Print a systemd unit\n\n\
Reads the identity file of LEANCTX_COMPUTER_CONFIG (default /etc/leanctx/computer.json) and the tokens systemd passes as credentials.\n";
pub(crate) fn cmd_computer(args: &[String]) {
let code = match args.first().map(String::as_str) {
Some("run") => run_service(),
Some("sync-users") => sync_users(),
Some("diag") => diag::run(&args[1..]),
Some("unit") => match args.get(1).map(String::as_str) {
None => print_unit(UNIT_FILE),
Some("users") => print_unit(USERS_UNIT_FILE),
Some("path") => print_unit(USERS_PATH_FILE),
Some(_) => {
eprint!("{HELP}");
2
}
},
None | Some("help" | "--help" | "-h") => {
print!("{HELP}");
0
}
Some(_) => {
eprint!("{HELP}");
2
}
};
if code != 0 {
std::process::exit(code);
}
}
fn print_unit(text: &str) -> i32 {
print!("{text}");
0
}
fn log(line: &str) {
eprintln!("lean-ctx computer: {line}");
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct Status {
role: String,
enrolled: bool,
meter: String,
last_tick: Option<u64>,
users: usize,
key_sync: String,
}
impl Status {
fn lines(&self) -> String {
let clean =
|s: &str| -> String { s.chars().filter(|c| !c.is_control()).take(160).collect() };
let ago = self.last_tick.map_or_else(
|| "never".to_string(),
|t| format!("{} s ago", now_secs().saturating_sub(t)),
);
format!(
" role {}\n enrolled {}\n meter {} (last tick {ago})\n granted {} user(s)\n grants {}\n",
clean(&self.role),
if self.enrolled { "yes" } else { "no" },
clean(&self.meter),
self.users,
clean(&self.key_sync),
)
}
}
fn now_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_secs())
}
fn write_status(status: &Status) {
let Ok(body) = serde_json::to_vec(status) else {
return;
};
let path = Path::new(STATUS_FILE);
let tmp = path.with_extension("json.tmp");
let written = std::fs::write(&tmp, body)
.and_then(|()| set_mode(&tmp, 0o644))
.and_then(|()| std::fs::rename(&tmp, path));
if let Err(e) = written {
log(&format!("{STATUS_FILE}: {}", e.kind()));
}
}
#[cfg(unix)]
fn set_mode(path: &Path, mode: u32) -> std::io::Result<()> {
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode))
}
#[cfg(not(unix))]
fn set_mode(_path: &Path, _mode: u32) -> std::io::Result<()> {
Ok(())
}
fn store() -> CloudStore {
let dir = Path::new(STATE_DIR);
CloudStore::at(dir.join("config/cloud"), dir.join("data/cloud"))
}
fn uid_in_passwd(passwd: &str, name: &str) -> Option<u32> {
passwd.lines().find_map(|line| {
let mut fields = line.split(':');
(fields.next()? == name).then_some(())?;
fields.nth(1)?.parse().ok()
})
}
fn service_uid() -> Option<u32> {
let passwd = std::fs::read_to_string("/etc/passwd").ok()?;
uid_in_passwd(&passwd, SERVICE_USER).filter(|&uid| uid != 0)
}
fn config_path() -> PathBuf {
std::env::var_os(CONFIG_ENV).map_or_else(|| PathBuf::from(CONFIG_DEFAULT), PathBuf::from)
}
fn load_config() -> Result<config::ComputerConfig, String> {
secret_file::read_checked(&config_path(), 0, secret_file::Exposure::Readable, 4096)
.and_then(|bytes| config::parse(&bytes))
}
fn credential(name: &str, prefix: &str) -> Result<zeroize::Zeroizing<String>, String> {
let dir = std::env::var_os("CREDENTIALS_DIRECTORY")
.filter(|d| Path::new(d).is_absolute())
.ok_or("no systemd credentials (start the agent as lean-ctx-computer.service)")?;
secret_file::read_token(
&Path::new(&dir).join(name),
secret_file::effective_uid(),
prefix,
)
}
fn failed_start(why: &str) -> i32 {
log(why);
std::thread::sleep(FAILED_START_PAUSE);
1
}
fn run_service() -> i32 {
if secret_file::effective_uid() == 0 {
return failed_start("the agent never runs as root; start it as lean-ctx-computer.service");
}
let config = match load_config() {
Ok(config) => config,
Err(why) => return failed_start(&why),
};
let cloud = lean_ctx::core::config::Config::load().cloud.clone();
let mut status = Status {
role: config.role.as_str().into(),
..Status::default()
};
if let Err(why) = ensure_enrolled(&config, &cloud) {
status.meter = "not started".into();
status.key_sync = "not enrolled".into();
write_status(&status);
return failed_start(&format!("enrolment: {why}"));
}
status.enrolled = true;
let meter = match credential(METER_CREDENTIAL, "lcm_")
.and_then(|token| meter::Meter::new(&config.origin, &config.computer_id, &token))
{
Ok(meter) => meter,
Err(why) => return failed_start(&why),
};
log(&format!(
"enrolled; metering and fetching SSH grants every {} s",
PERIOD.as_secs()
));
let mut host_keys_sent = false;
let mut last_meter = String::new();
let mut last_sync = String::new();
let mut last_grants: Option<Vec<u8>> = None;
loop {
let started = std::time::Instant::now();
let seen = match meter.tick(host::grantee_active()) {
Ok(tick) => {
status.last_tick = Some(now_secs());
status.meter.clone_from(&tick.state);
match tick.action {
meter::Action::Run => format!("run ({})", tick.state),
meter::Action::Stop => format!("stop requested ({})", tick.state),
}
}
Err(e) => {
status.meter = e.to_string();
e.to_string()
}
};
if seen != last_meter {
log(&format!("meter: {seen}"));
last_meter = seen;
}
if !host_keys_sent {
host_keys_sent = report_host_keys(&meter);
}
let synced = match fetch_grants(&config, &mut last_grants) {
Ok((granted, summary)) => {
status.users = granted;
status.key_sync = "ok".into();
summary
}
Err(why) => {
status.key_sync.clone_from(&why);
why
}
};
if synced != last_sync {
log(&format!("grants: {synced}"));
last_sync = synced;
}
write_status(&status);
std::thread::sleep(PERIOD.saturating_sub(started.elapsed()));
}
}
fn report_host_keys(meter: &meter::Meter) -> bool {
let fingerprints = host::host_key_fingerprints(Path::new(SSH_DIR));
if fingerprints.is_empty() {
log("no SSH host keys found to report");
return true;
}
match meter.host_keys(&fingerprints) {
Ok(()) => {
log(&format!("reported {} SSH host key(s)", fingerprints.len()));
true
}
Err(e) => {
log(&format!("host keys: {e}"));
false
}
}
}
fn ensure_enrolled(
config: &config::ComputerConfig,
cloud: &lean_ctx_cloud::CloudConfig,
) -> Result<(), String> {
let store = store();
if let Some(existing) = store.instance().map_err(|e| e.to_string())? {
if existing.url != config.origin {
return Err("this computer is enrolled with another cloud".into());
}
return Ok(());
}
let raw = credential(ENROL_CREDENTIAL, "het_")?;
let token = lean_ctx_cloud::auth::EnrollmentToken::parse(&raw).map_err(|e| e.to_string())?;
drop(raw);
let client =
lean_ctx_cloud::transport::CloudClient::new(&config.origin).map_err(|e| e.to_string())?;
let trust = lean_ctx_cloud::root_cert::for_connect(&client, cloud, &config.origin)
.map_err(|e| e.to_string())?;
let label = format!("Cloud computer {}", &config.computer_id[..8]);
lean_ctx_cloud::auth::enroll_with_token(&store, &client, &token, &label, &trust.root)
.map_err(|e| e.to_string())?;
if let Some(certificate) = &trust.certificate {
lean_ctx_cloud::root_cert::store_certificate(&store, certificate)
.map_err(|e| e.to_string())?;
}
lean_ctx_cloud::revoked::clear(&store).map_err(|e| e.to_string())?;
lean_ctx_cloud::throttle::clear_connect(&store);
lean_ctx_cloud::auth::Session::load(store, trust.root)
.and_then(|session| session.client())
.map_err(|e| e.to_string())?;
log("enrolled with the cloud");
Ok(())
}
fn fetch_grants(
config: &config::ComputerConfig,
last: &mut Option<Vec<u8>>,
) -> Result<(usize, String), String> {
let store = store();
let cloud = lean_ctx::core::config::Config::load().cloud.clone();
let root = lean_ctx_cloud::root_cert::trust_root(&store, &cloud, &config.origin)
.map_err(|e| format!("trust root: {e}"))?;
let session =
lean_ctx_cloud::auth::Session::load(store, root).map_err(|e| format!("session: {e}"))?;
let answer = session
.client()
.and_then(|client| client.get(KEYS_PATH))
.map_err(|e| format!("authorized keys unavailable: {e}"))?;
let body = serde_json::to_vec(&answer).map_err(|e| e.to_string())?;
let desired = grants::desired(&body)?;
let handoff = grants::handoff(&desired);
if last.as_deref() != Some(handoff.as_slice()) {
write_private(Path::new(GRANTS_FILE), &handoff)
.map_err(|e| format!("{GRANTS_FILE}: {}", e.kind()))?;
*last = Some(handoff);
}
let granted = desired.users.len();
let mut summary = format!("{granted} user(s) granted");
if desired.dropped > 0 {
summary.push_str(&format!(", {} malformed grant(s) ignored", desired.dropped));
}
Ok((granted, summary))
}
#[cfg(unix)]
fn write_private(path: &Path, body: &[u8]) -> std::io::Result<()> {
use std::io::Write as _;
use std::os::unix::fs::OpenOptionsExt;
let tmp = path.with_extension("json.tmp");
if let Err(e) = std::fs::remove_file(&tmp)
&& e.kind() != std::io::ErrorKind::NotFound
{
return Err(e);
}
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
.open(&tmp)?;
file.write_all(body)?;
file.sync_all()?;
std::fs::rename(&tmp, path)
}
#[cfg(not(unix))]
fn write_private(_path: &Path, _body: &[u8]) -> std::io::Result<()> {
Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
}
fn sync_users() -> i32 {
match sync_users_once() {
Ok(summary) => {
log(&format!("users: {summary}"));
0
}
Err(why) => {
log(&format!("users: {why}"));
1
}
}
}
fn sync_users_once() -> Result<String, String> {
if secret_file::effective_uid() != 0 {
return Err("runs as root only, as lean-ctx-computer-users.service".into());
}
let config = load_config()?;
let agent = service_uid().ok_or("the service user leanctx does not exist")?;
let path = Path::new(GRANTS_FILE);
let bytes =
match secret_file::read_checked(path, agent, secret_file::Exposure::Private, 1024 * 1024) {
Ok(bytes) => bytes,
Err(_) if !path.exists() => return Ok("no grants fetched yet".into()),
Err(why) => return Err(why),
};
let desired = grants::desired(&bytes)?;
let mut managed = users::load_state(Path::new(USERS_FILE), 0)?;
let steps = grants::diff(config.role, &desired, &managed);
let failures = users::apply(config.role, &steps, &mut managed, Path::new(USERS_FILE))?;
let active = managed.users.values().filter(|m| m.active).count();
let mut summary = format!("{active} user(s) with access, {} change(s)", steps.len());
for failure in &failures {
summary.push_str("; ");
summary.push_str(failure);
}
if failures.is_empty() {
Ok(summary)
} else {
Err(summary)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_status_shows_no_control_characters() {
let status = Status {
role: "weave_host".into(),
enrolled: true,
meter: "running\u{1b}[2J".into(),
last_tick: None,
users: 2,
key_sync: "ok".into(),
};
let text = status.lines();
assert!(!text.contains('\u{1b}'));
assert!(text.contains("meter running[2J (last tick never)"));
assert!(text.contains("granted 2 user(s)"));
}
#[test]
fn the_units_split_the_agent_from_the_root_user_sync() {
assert!(UNIT_FILE.contains("\nExecStart=/usr/local/bin/lean-ctx computer run\n"));
assert!(UNIT_FILE.contains("\nUser=leanctx\n"));
assert!(UNIT_FILE.contains("\nLoadCredential=enrol.token:/etc/leanctx/enrol.token\n"));
assert!(UNIT_FILE.contains("\nLoadCredential=meter.token:/etc/leanctx/meter.token\n"));
assert!(
UNIT_FILE
.contains("\nEnvironment=LEANCTX_COMPUTER_CONFIG=/etc/leanctx/computer.json\n")
);
assert!(UNIT_FILE.contains("\nCapabilityBoundingSet=\n"));
assert!(UNIT_FILE.contains("\nProtectSystem=strict\n"));
for file in [GRANTS_FILE, STATUS_FILE] {
assert!(file.starts_with(&format!("{STATE_DIR}/")));
}
assert!(!USERS_FILE.starts_with(&format!("{STATE_DIR}/")));
assert!(
USERS_UNIT_FILE.contains("\nExecStart=/usr/local/bin/lean-ctx computer sync-users\n")
);
assert!(USERS_UNIT_FILE.contains("\nType=oneshot\n"));
assert!(USERS_UNIT_FILE.contains("\nStateDirectory=leanctx-users\n"));
assert!(USERS_UNIT_FILE.contains("\nProtectSystem=strict\n"));
assert!(USERS_UNIT_FILE.contains("\nRestart=on-failure\n"));
assert!(USERS_PATH_FILE.contains(&format!("\nPathChanged={GRANTS_FILE}\n")));
assert!(USERS_PATH_FILE.contains("\nUnit=lean-ctx-computer-users.service\n"));
assert_eq!(UNIT, "lean-ctx-computer.service");
}
#[test]
fn the_service_user_is_found_by_its_exact_name() {
let passwd = "root:x:0:0:root:/root:/bin/bash\n\
leanctxx:x:997:997::/:/usr/sbin/nologin\n\
leanctx:x:998:998::/var/lib/leanctx:/usr/sbin/nologin\n";
assert_eq!(uid_in_passwd(passwd, "leanctx"), Some(998));
assert_eq!(uid_in_passwd(passwd, "nobody"), None);
}
#[cfg(unix)]
#[test]
fn the_grants_handoff_is_private_and_reads_back() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("grants.json");
let body = grants::handoff(&grants::Desired::default());
write_private(&path, &body).unwrap();
write_private(&path, &body).unwrap();
let mode = std::fs::metadata(&path).unwrap().permissions().mode();
assert_eq!(mode & 0o777, 0o600);
let read = secret_file::read_checked(
&path,
secret_file::effective_uid(),
secret_file::Exposure::Private,
1024,
)
.unwrap();
assert_eq!(grants::desired(&read).unwrap(), grants::Desired::default());
}
}