Skip to main content

khive_runtime/
engine_config_share.rs

1//! The `[share]` table (ADR-220 Amendment 1): the directory a caller may share
2//! files from, the bounds of one share, and the computers a share can go to.
3//!
4//! Like `[computer]`, the table is parsed and validated with the rest of the
5//! configuration file and nothing here reads from disk: a target's key is read
6//! from its `key_file` only when a share to that target runs, and `root` is
7//! canonicalized and checked as a directory at the same moment.
8
9use std::path::PathBuf;
10
11use serde::Deserialize;
12
13use super::computer::{parse_computer_url, validate_name};
14use super::{
15    ComputerEndpoint, ConfigError, DEFAULT_COMPUTER_CALL_TIMEOUT_S, MAX_COMPUTER_CALL_TIMEOUT_S,
16};
17
18/// The default and the largest `max_file_bytes`: a computer's limit for one
19/// blob, 64 MiB.
20pub const MAX_SHARE_FILE_BYTES: u64 = 64 * 1024 * 1024;
21
22/// `max_total_bytes` when the table does not set it.
23pub const DEFAULT_SHARE_TOTAL_BYTES: u64 = 256 * 1024 * 1024;
24
25/// The largest accepted `max_total_bytes`.
26pub const MAX_SHARE_TOTAL_BYTES: u64 = 1024 * 1024 * 1024;
27
28/// `max_files` when the table does not set it.
29pub const DEFAULT_SHARE_FILES: usize = 256;
30
31/// The largest accepted `max_files`: the most files a computer accepts in one
32/// share.
33pub const MAX_SHARE_FILES: usize = 1000;
34
35/// `[share]`: what a caller may share and where it may send it.
36///
37/// ```toml
38/// [share]
39/// root = "/home/example/share"
40/// max_file_bytes = 67108864
41/// max_total_bytes = 268435456
42/// max_files = 256
43///
44/// [[share.targets]]
45/// name = "build-1"
46/// url = "https://build-1.example/mcp"
47/// key_file = "/home/example/.secrets/share-build-1.key"
48/// call_timeout_s = 600
49/// ```
50///
51/// The table and each target are closed. No value in them is a secret.
52#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
53#[serde(deny_unknown_fields)]
54pub struct ShareSectionConfig {
55    /// Absolute path of the directory whose files may be shared. Everything
56    /// under it can be shared, and nothing else.
57    pub root: PathBuf,
58    /// The largest file a share sends, in bytes.
59    #[serde(default = "default_max_file_bytes")]
60    pub max_file_bytes: u64,
61    /// The most bytes one share sends, over all its files.
62    #[serde(default = "default_max_total_bytes")]
63    pub max_total_bytes: u64,
64    /// The most files one share names.
65    #[serde(default = "default_max_files")]
66    pub max_files: usize,
67    /// The computers a share can go to.
68    #[serde(default)]
69    pub targets: Vec<ShareTargetConfig>,
70}
71
72/// One `[[share.targets]]` entry: a computer a share can go to, reached as
73/// the `[computer]` table reaches its computer.
74#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
75#[serde(deny_unknown_fields)]
76pub struct ShareTargetConfig {
77    /// Names the target in a share's `target` argument and in refusals.
78    pub name: String,
79    /// Where the target serves MCP over streamable HTTP.
80    pub url: String,
81    /// Absolute path of the file holding the key the target's owner issued to
82    /// this caller.
83    pub key_file: PathBuf,
84    /// How long one call to the target may take, in seconds.
85    #[serde(default = "default_call_timeout_s")]
86    pub call_timeout_s: u64,
87}
88
89fn default_max_file_bytes() -> u64 {
90    MAX_SHARE_FILE_BYTES
91}
92
93fn default_max_total_bytes() -> u64 {
94    DEFAULT_SHARE_TOTAL_BYTES
95}
96
97fn default_max_files() -> usize {
98    DEFAULT_SHARE_FILES
99}
100
101fn default_call_timeout_s() -> u64 {
102    DEFAULT_COMPUTER_CALL_TIMEOUT_S
103}
104
105fn invalid(key: &str, reason: impl Into<String>) -> ConfigError {
106    ConfigError::InvalidShareConfig {
107        key: key.to_owned(),
108        reason: reason.into(),
109    }
110}
111
112fn within(key: &str, value: u64, max: u64) -> Result<(), ConfigError> {
113    if value == 0 || value > max {
114        return Err(invalid(
115            key,
116            format!("must be between 1 and {max}; got {value}"),
117        ));
118    }
119    Ok(())
120}
121
122impl ShareSectionConfig {
123    /// Check every rule of the table. Reads nothing from disk.
124    pub fn validate(&self) -> Result<(), ConfigError> {
125        if !self.root.is_absolute() {
126            return Err(invalid("root", "is not an absolute path"));
127        }
128        within("max_file_bytes", self.max_file_bytes, MAX_SHARE_FILE_BYTES)?;
129        within(
130            "max_total_bytes",
131            self.max_total_bytes,
132            MAX_SHARE_TOTAL_BYTES,
133        )?;
134        within("max_files", self.max_files as u64, MAX_SHARE_FILES as u64)?;
135        if self.targets.is_empty() {
136            return Err(invalid(
137                "targets",
138                "names no target; a [share] table needs at least one [[share.targets]] entry",
139            ));
140        }
141        for (index, target) in self.targets.iter().enumerate() {
142            target.validate(index)?;
143            if self.targets[..index]
144                .iter()
145                .any(|earlier| earlier.name == target.name)
146            {
147                return Err(invalid(
148                    &format!("targets[{index}].name"),
149                    format!(
150                        "{:?} names an earlier target too; target names are distinct",
151                        target.name
152                    ),
153                ));
154            }
155        }
156        Ok(())
157    }
158
159    /// The target named `name`.
160    pub fn target(&self, name: &str) -> Option<&ShareTargetConfig> {
161        self.targets.iter().find(|target| target.name == name)
162    }
163}
164
165impl ShareTargetConfig {
166    /// The rules section 2 and section 3 of ADR-220 give the `[computer]` keys
167    /// of the same names. A refusal names the target by its index.
168    fn validate(&self, index: usize) -> Result<(), ConfigError> {
169        let relabel = |error: ConfigError| match error {
170            ConfigError::InvalidComputerConfig { key, reason } => {
171                invalid(&format!("targets[{index}].{key}"), reason)
172            }
173            other => other,
174        };
175        validate_name(&self.name).map_err(relabel)?;
176        self.endpoint().map_err(relabel)?;
177        if !self.key_file.is_absolute() {
178            return Err(invalid(
179                &format!("targets[{index}].key_file"),
180                "is not an absolute path",
181            ));
182        }
183        if self.call_timeout_s == 0 || self.call_timeout_s > MAX_COMPUTER_CALL_TIMEOUT_S {
184            return Err(invalid(
185                &format!("targets[{index}].call_timeout_s"),
186                format!(
187                    "must be between 1 and {MAX_COMPUTER_CALL_TIMEOUT_S} seconds; got {}",
188                    self.call_timeout_s
189                ),
190            ));
191        }
192        Ok(())
193    }
194
195    /// Parse `url` into the endpoint the client connects to, by the rules of
196    /// `[computer].url`.
197    pub fn endpoint(&self) -> Result<ComputerEndpoint, ConfigError> {
198        parse_computer_url(&self.url)
199    }
200}
201
202#[cfg(test)]
203#[path = "engine_config_share_tests.rs"]
204mod tests;