1use std::net::{Ipv4Addr, Ipv6Addr};
9use std::path::{Path, PathBuf};
10
11use serde::Deserialize;
12use zeroize::Zeroizing;
13
14use super::ConfigError;
15
16pub const COMPUTER_ROUTABLE_PACKS: [&str; 7] = [
18 "computer",
19 "exec",
20 "git",
21 "code",
22 "workspace",
23 "blob",
24 "tool",
25];
26
27pub const COMMAND_RUNNING_PACKS: [&str; 5] = ["exec", "git", "code", "workspace", "tool"];
31
32pub const DEFAULT_COMPUTER_CALL_TIMEOUT_S: u64 = 3700;
34
35pub const MAX_COMPUTER_CALL_TIMEOUT_S: u64 = 7200;
37
38pub const MAX_COMPUTER_KEY_BYTES: usize = 4096;
40
41const MAX_COMPUTER_NAME_BYTES: usize = 64;
42
43#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
57#[serde(deny_unknown_fields)]
58pub struct ComputerSectionConfig {
59 pub name: String,
61 pub url: String,
63 pub key_file: PathBuf,
65 pub packs: Vec<String>,
67 #[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#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct ComputerEndpoint {
79 pub https: bool,
81 pub host: String,
83 pub port: u16,
85 pub loopback: bool,
87}
88
89impl ComputerSectionConfig {
90 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 pub fn endpoint(&self) -> Result<ComputerEndpoint, ConfigError> {
112 parse_computer_url(&self.url)
113 }
114}
115
116pub(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
186fn 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
296pub struct ComputerKey(Zeroizing<String>);
301
302impl ComputerKey {
303 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
318pub enum ComputerKeyRefusal {
319 Unreadable(std::io::ErrorKind),
321 NotRegularFile,
323 NotOwnedByProcessUser,
325 GroupOrOtherPermissionBits { mode: u32 },
327 TooLarge,
329 Empty,
331 NotOneToken,
333 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#[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 pub const KIND: &'static str = "computer_key_unavailable";
377}
378
379pub 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 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 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;