Skip to main content

khive_runtime/
engine_config_computer.rs

1//! The `[computer]` table (ADR-220): the one computer a caller's command
2//! verbs run on, and the key that reaches it.
3//!
4//! The table is parsed and validated with the rest of the configuration file.
5//! The key is never part of the parsed configuration: it is read from
6//! `key_file` by [`read_computer_key`] only when a routed operation needs it.
7
8use std::net::{Ipv4Addr, Ipv6Addr};
9use std::path::{Path, PathBuf};
10
11use serde::Deserialize;
12use zeroize::Zeroizing;
13
14use super::ConfigError;
15
16/// Every pack a `[computer]` table may route.
17pub const COMPUTER_ROUTABLE_PACKS: [&str; 7] = [
18    "computer",
19    "exec",
20    "git",
21    "code",
22    "workspace",
23    "blob",
24    "tool",
25];
26
27/// The packs that run commands. With a `[computer]` table none of these
28/// dispatches on the store's machine: a listed one is routed, an unlisted one
29/// is refused with `runs_on_computer`.
30pub const COMMAND_RUNNING_PACKS: [&str; 5] = ["exec", "git", "code", "workspace", "tool"];
31
32/// `call_timeout_s` when the table does not set it.
33pub const DEFAULT_COMPUTER_CALL_TIMEOUT_S: u64 = 3700;
34
35/// The largest accepted `call_timeout_s`.
36pub const MAX_COMPUTER_CALL_TIMEOUT_S: u64 = 7200;
37
38/// The largest accepted key, in bytes, not counting a trailing newline.
39pub const MAX_COMPUTER_KEY_BYTES: usize = 4096;
40
41const MAX_COMPUTER_NAME_BYTES: usize = 64;
42
43/// `[computer]`: which computer this caller's routed packs go to.
44///
45/// ```toml
46/// [computer]
47/// name = "build-1"
48/// url = "http://127.0.0.1:8700/mcp"
49/// key_file = "/home/example/.secrets/computer-build-1.key"
50/// packs = ["computer", "exec", "git", "blob", "tool"]
51/// call_timeout_s = 3700
52/// ```
53///
54/// The table is closed. No value in it is a secret: `key_file` is a path, and
55/// `Debug` prints it as one without reading the file.
56#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
57#[serde(deny_unknown_fields)]
58pub struct ComputerSectionConfig {
59    /// Labels the computer in the catalog and in refusals.
60    pub name: String,
61    /// Where the computer serves MCP over streamable HTTP.
62    pub url: String,
63    /// Absolute path of the file holding this caller's computer key.
64    pub key_file: PathBuf,
65    /// The packs served by the computer for this caller.
66    pub packs: Vec<String>,
67    /// How long a routed request may take, in seconds.
68    #[serde(default = "default_call_timeout_s")]
69    pub call_timeout_s: u64,
70}
71
72fn default_call_timeout_s() -> u64 {
73    DEFAULT_COMPUTER_CALL_TIMEOUT_S
74}
75
76/// Where a validated `[computer].url` connects.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct ComputerEndpoint {
79    /// `true` for `https`, `false` for plain `http` (loopback only).
80    pub https: bool,
81    /// The host as written, without the brackets of an IPv6 literal.
82    pub host: String,
83    /// The explicit port, or the scheme's default.
84    pub port: u16,
85    /// Whether the host is `localhost`, in `127.0.0.0/8`, or `::1`.
86    pub loopback: bool,
87}
88
89impl ComputerSectionConfig {
90    /// Check every rule of the table. Reads nothing from disk.
91    pub fn validate(&self) -> Result<(), ConfigError> {
92        validate_name(&self.name)?;
93        self.endpoint()?;
94        if !self.key_file.is_absolute() {
95            return Err(invalid("key_file", "is not an absolute path"));
96        }
97        validate_packs(&self.packs)?;
98        if self.call_timeout_s == 0 || self.call_timeout_s > MAX_COMPUTER_CALL_TIMEOUT_S {
99            return Err(invalid(
100                "call_timeout_s",
101                format!(
102                    "must be between 1 and {MAX_COMPUTER_CALL_TIMEOUT_S} seconds; got {}",
103                    self.call_timeout_s
104                ),
105            ));
106        }
107        Ok(())
108    }
109
110    /// Parse `url` into the endpoint the client connects to.
111    pub fn endpoint(&self) -> Result<ComputerEndpoint, ConfigError> {
112        parse_computer_url(&self.url)
113    }
114}
115
116/// ADR-220 section 2: `[actor].computer` names the computer of the
117/// `[computer]` table. Each is refused without the other, and the two names
118/// must be equal.
119pub(super) fn validate_actor_computer(
120    table: Option<&ComputerSectionConfig>,
121    named: Option<&str>,
122) -> Result<(), ConfigError> {
123    let refusal = |reason: String| ConfigError::InvalidActorComputer { reason };
124    match (table, named) {
125        (None, None) => Ok(()),
126        (Some(table), Some(named)) if table.name == named => Ok(()),
127        (Some(table), Some(named)) => Err(refusal(format!(
128            "is {named:?} but [computer].name is {:?}; the two must be equal",
129            table.name
130        ))),
131        (Some(table), None) => Err(refusal(format!(
132            "is required with a [computer] table; set it to {:?}",
133            table.name
134        ))),
135        (None, Some(named)) => Err(refusal(format!(
136            "is {named:?} but there is no [computer] table; remove the field or add the table"
137        ))),
138    }
139}
140
141fn invalid(key: &str, reason: impl Into<String>) -> ConfigError {
142    ConfigError::InvalidComputerConfig {
143        key: key.to_owned(),
144        reason: reason.into(),
145    }
146}
147
148fn validate_name(name: &str) -> Result<(), ConfigError> {
149    let well_formed = (1..=MAX_COMPUTER_NAME_BYTES).contains(&name.len())
150        && name
151            .bytes()
152            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-');
153    if well_formed {
154        Ok(())
155    } else {
156        Err(invalid(
157            "name",
158            format!(
159                "must be 1 to {MAX_COMPUTER_NAME_BYTES} bytes of lowercase ASCII letters, digits and '-'"
160            ),
161        ))
162    }
163}
164
165fn validate_packs(packs: &[String]) -> Result<(), ConfigError> {
166    if packs.is_empty() {
167        return Err(invalid("packs", "must name at least one pack"));
168    }
169    for (index, pack) in packs.iter().enumerate() {
170        if !COMPUTER_ROUTABLE_PACKS.contains(&pack.as_str()) {
171            return Err(invalid(
172                "packs",
173                format!(
174                    "{pack:?} is not a routable pack; each entry is one of {}",
175                    COMPUTER_ROUTABLE_PACKS.join(", ")
176                ),
177            ));
178        }
179        if packs[..index].contains(pack) {
180            return Err(invalid("packs", format!("{pack:?} is listed twice")));
181        }
182    }
183    Ok(())
184}
185
186/// Parse a `[computer].url`. A refusal never repeats the URL: it may hold a
187/// user name or password, and a refusal names only the host when it must.
188fn parse_computer_url(url: &str) -> Result<ComputerEndpoint, ConfigError> {
189    if !url.bytes().all(|byte| byte.is_ascii_graphic()) {
190        return Err(invalid(
191            "url",
192            "must be ASCII with no spaces or control characters",
193        ));
194    }
195    let Some((scheme, rest)) = url.split_once("://") else {
196        return Err(invalid("url", "is not an absolute http or https URL"));
197    };
198    let https = if scheme.eq_ignore_ascii_case("https") {
199        true
200    } else if scheme.eq_ignore_ascii_case("http") {
201        false
202    } else {
203        return Err(invalid("url", "must use the http or https scheme"));
204    };
205    let (authority, path) = rest.split_at(rest.find(['/', '?', '#']).unwrap_or(rest.len()));
206    if authority.contains('@') {
207        return Err(invalid(
208            "url",
209            "carries a user name or password; the key is read only from key_file",
210        ));
211    }
212    if !path.starts_with('/') {
213        return Err(invalid("url", "must have a path, such as /mcp"));
214    }
215    if path.contains(['?', '#']) {
216        return Err(invalid("url", "must not carry a query or a fragment"));
217    }
218
219    let (host, port_text) = if let Some(bracketed) = authority.strip_prefix('[') {
220        let Some((host, tail)) = bracketed.split_once(']') else {
221            return Err(invalid(
222                "url",
223                "has an IPv6 address with no closing bracket",
224            ));
225        };
226        if host.parse::<Ipv6Addr>().is_err() {
227            return Err(invalid(
228                "url",
229                "brackets a host that is not an IPv6 address",
230            ));
231        }
232        let port_text = match tail {
233            "" => None,
234            tail => match tail.strip_prefix(':') {
235                Some(port) => Some(port),
236                None => return Err(invalid("url", "has text after its IPv6 address")),
237            },
238        };
239        (host, port_text)
240    } else {
241        let (host, port_text) = match authority.rsplit_once(':') {
242            Some((host, port)) => (host, Some(port)),
243            None => (authority, None),
244        };
245        if !host
246            .bytes()
247            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'.')
248        {
249            return Err(invalid(
250                "url",
251                "has a host that is not a DNS name, an IPv4 address or a bracketed IPv6 address",
252            ));
253        }
254        (host, port_text)
255    };
256    if host.is_empty() {
257        return Err(invalid("url", "names no host"));
258    }
259    let port = match port_text {
260        None if https => 443,
261        None => 80,
262        Some(text) => match text.parse::<u16>() {
263            Ok(port) if port != 0 && text.bytes().all(|byte| byte.is_ascii_digit()) => port,
264            _ => {
265                return Err(invalid(
266                    "url",
267                    "has a port that is not a number from 1 to 65535",
268                ))
269            }
270        },
271    };
272    let loopback = host.eq_ignore_ascii_case("localhost")
273        || host
274            .parse::<Ipv4Addr>()
275            .is_ok_and(|address| address.is_loopback())
276        || host
277            .parse::<Ipv6Addr>()
278            .is_ok_and(|address| address.is_loopback());
279    if !https && !loopback {
280        return Err(invalid(
281            "url",
282            format!(
283                "plain http is accepted only for a loopback host (localhost, 127.0.0.0/8, ::1), \
284                 because the key travels in a request header; host {host:?} requires https"
285            ),
286        ));
287    }
288    Ok(ComputerEndpoint {
289        https,
290        host: host.to_owned(),
291        port,
292        loopback,
293    })
294}
295
296/// A computer key read from `[computer].key_file`.
297///
298/// The buffer is cleared on drop and `Debug` never prints it. The token is
299/// visible ASCII, so it is always a valid `Authorization` header value.
300pub struct ComputerKey(Zeroizing<String>);
301
302impl ComputerKey {
303    /// The token, for the `Authorization` header of requests to `url` only.
304    pub fn token(&self) -> &str {
305        &self.0
306    }
307}
308
309impl std::fmt::Debug for ComputerKey {
310    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
311        formatter.write_str("ComputerKey(<redacted>)")
312    }
313}
314
315/// Why `[computer].key_file` could not supply a key. No variant carries the
316/// path or any byte of the file.
317#[derive(Debug, Clone, Copy, PartialEq, Eq)]
318pub enum ComputerKeyRefusal {
319    /// The file could not be opened or read.
320    Unreadable(std::io::ErrorKind),
321    /// A symbolic link, a directory, a device or anything but a regular file.
322    NotRegularFile,
323    /// The file is owned by another user.
324    NotOwnedByProcessUser,
325    /// The file's mode grants the group or others any permission.
326    GroupOrOtherPermissionBits { mode: u32 },
327    /// More than [`MAX_COMPUTER_KEY_BYTES`] bytes before a trailing newline.
328    TooLarge,
329    /// Nothing but an optional trailing newline.
330    Empty,
331    /// Whitespace, control bytes or non-ASCII bytes in the token.
332    NotOneToken,
333    /// The platform offers no owner-only permission check.
334    UnsupportedPlatform,
335}
336
337impl std::fmt::Display for ComputerKeyRefusal {
338    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
339        match self {
340            Self::Unreadable(kind) => write!(formatter, "cannot be read ({kind})"),
341            Self::NotRegularFile => formatter.write_str(
342                "is not a regular file; a symbolic link, a directory or a device is refused",
343            ),
344            Self::NotOwnedByProcessUser => {
345                formatter.write_str("is not owned by the user running this process")
346            }
347            Self::GroupOrOtherPermissionBits { mode } => write!(
348                formatter,
349                "has group or other permission bits (mode {mode:04o}); it must be owner-only"
350            ),
351            Self::TooLarge => write!(
352                formatter,
353                "holds more than {MAX_COMPUTER_KEY_BYTES} bytes before a trailing newline"
354            ),
355            Self::Empty => formatter.write_str("holds no key"),
356            Self::NotOneToken => formatter.write_str(
357                "must hold one token of visible ASCII characters with no inner whitespace",
358            ),
359            Self::UnsupportedPlatform => {
360                formatter.write_str("cannot be checked for owner-only permissions on this platform")
361            }
362        }
363    }
364}
365
366/// The refusal behind `computer_key_unavailable`. Its message names the table
367/// key, never the path and never the contents.
368#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
369#[error("computer_key_unavailable: [computer].key_file {refusal}")]
370pub struct ComputerKeyError {
371    pub refusal: ComputerKeyRefusal,
372}
373
374impl ComputerKeyError {
375    /// The refusal kind a routed operation reports.
376    pub const KIND: &'static str = "computer_key_unavailable";
377}
378
379/// Read the key from `key_file`.
380///
381/// The file must be a regular file, reached without following a symbolic
382/// link, owned by this process's user, with no group or other permission bits,
383/// holding one nonempty token of at most [`MAX_COMPUTER_KEY_BYTES`] visible
384/// ASCII bytes. One trailing newline (`\n` or `\r\n`) is ignored.
385pub fn read_computer_key(key_file: &Path) -> Result<ComputerKey, ComputerKeyError> {
386    read_key(key_file).map_err(|refusal| ComputerKeyError { refusal })
387}
388
389#[cfg(unix)]
390fn read_key(key_file: &Path) -> Result<ComputerKey, ComputerKeyRefusal> {
391    use std::io::Read;
392    use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
393
394    let mut file = std::fs::OpenOptions::new()
395        .read(true)
396        .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK)
397        .open(key_file)
398        .map_err(|error| {
399            if error.raw_os_error() == Some(libc::ELOOP) {
400                ComputerKeyRefusal::NotRegularFile
401            } else {
402                ComputerKeyRefusal::Unreadable(error.kind())
403            }
404        })?;
405    let metadata = file
406        .metadata()
407        .map_err(|error| ComputerKeyRefusal::Unreadable(error.kind()))?;
408    if !metadata.file_type().is_file() {
409        return Err(ComputerKeyRefusal::NotRegularFile);
410    }
411    // SAFETY: geteuid takes no arguments, has no preconditions and cannot fail.
412    let process_user = unsafe { libc::geteuid() };
413    if metadata.uid() != process_user {
414        return Err(ComputerKeyRefusal::NotOwnedByProcessUser);
415    }
416    let mode = metadata.mode() & 0o7777;
417    if mode & 0o077 != 0 {
418        return Err(ComputerKeyRefusal::GroupOrOtherPermissionBits { mode });
419    }
420
421    // Room for the largest token, `\r\n` and one byte more: a file that fills it
422    // is too large. The buffer never grows, so no copy of the key is left
423    // behind unzeroed.
424    let mut buffer = Zeroizing::new(vec![0u8; MAX_COMPUTER_KEY_BYTES + 3]);
425    let mut filled = 0;
426    loop {
427        if filled == buffer.len() {
428            return Err(ComputerKeyRefusal::TooLarge);
429        }
430        match file.read(&mut buffer[filled..]) {
431            Ok(0) => break,
432            Ok(read) => filled += read,
433            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
434            Err(error) => return Err(ComputerKeyRefusal::Unreadable(error.kind())),
435        }
436    }
437    token_from(&buffer[..filled])
438}
439
440#[cfg(not(unix))]
441fn read_key(_key_file: &Path) -> Result<ComputerKey, ComputerKeyRefusal> {
442    Err(ComputerKeyRefusal::UnsupportedPlatform)
443}
444
445fn token_from(content: &[u8]) -> Result<ComputerKey, ComputerKeyRefusal> {
446    let token = match content.strip_suffix(b"\n") {
447        Some(line) => line.strip_suffix(b"\r").unwrap_or(line),
448        None => content,
449    };
450    if token.is_empty() {
451        return Err(ComputerKeyRefusal::Empty);
452    }
453    if token.len() > MAX_COMPUTER_KEY_BYTES {
454        return Err(ComputerKeyRefusal::TooLarge);
455    }
456    if !token.iter().all(u8::is_ascii_graphic) {
457        return Err(ComputerKeyRefusal::NotOneToken);
458    }
459    let text = std::str::from_utf8(token).map_err(|_| ComputerKeyRefusal::NotOneToken)?;
460    let mut owned = Zeroizing::new(String::with_capacity(text.len()));
461    owned.push_str(text);
462    Ok(ComputerKey(owned))
463}
464
465#[cfg(test)]
466#[path = "engine_config_computer_tests.rs"]
467mod tests;