Skip to main content

everruns_capabilities/
memory.rs

1//! Runtime mount configuration for the hosted memory capability.
2use everruns_contracts::typed_id::MemoryId;
3use serde::{Deserialize, Serialize};
4#[cfg(feature = "openapi")]
5use utoipa::ToSchema;
6
7/// Mount access mode. Defaults to `ReadOnly` when omitted from config.
8#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
9#[cfg_attr(feature = "openapi", derive(ToSchema))]
10#[serde(rename_all = "lowercase")]
11pub enum MemoryMountAccess {
12    #[default]
13    ReadOnly,
14    ReadWrite,
15}
16
17impl std::fmt::Display for MemoryMountAccess {
18    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19        match self {
20            MemoryMountAccess::ReadOnly => write!(f, "readonly"),
21            MemoryMountAccess::ReadWrite => write!(f, "readwrite"),
22        }
23    }
24}
25
26impl From<&str> for MemoryMountAccess {
27    fn from(s: &str) -> Self {
28        match s {
29            "readwrite" => MemoryMountAccess::ReadWrite,
30            _ => MemoryMountAccess::ReadOnly,
31        }
32    }
33}
34
35/// Capability config entry for `memory`. One entry per mount.
36///
37/// Wire shape:
38///
39/// ```json
40/// { "memory": "mem_abc...", "path": "/workspace/research", "mode": "readonly" }
41/// ```
42#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
43#[cfg_attr(feature = "openapi", derive(ToSchema))]
44pub struct MemoryMountConfig {
45    /// Public Memory ID (`mem_<32-hex>`).
46    pub memory: String,
47    /// Mount path under `/workspace`.
48    pub path: String,
49    /// Access mode. Defaults to `readonly` when omitted.
50    #[serde(default)]
51    pub mode: MemoryMountAccess,
52}
53
54/// Top-level config for the `memory` capability.
55#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
56#[cfg_attr(feature = "openapi", derive(ToSchema))]
57pub struct MemoryConfig {
58    #[serde(default, skip_serializing_if = "Vec::is_empty")]
59    pub mounts: Vec<MemoryMountConfig>,
60}
61
62/// Validation outcome for a single mount config entry.
63///
64/// Domain-level cross-validation (cross-org references, archived/deleted
65/// memories, capability-mount overlaps) happens at the server layer. This
66/// helper covers the structural checks we can perform without DB access so
67/// that capability `validate_config` and any clientside form validation
68/// share semantics.
69pub fn validate_mount_config_shape(mount: &MemoryMountConfig) -> Result<(), String> {
70    // Memory reference must be a syntactically valid MemoryId
71    // (mem_<32-lowercase-hex>) — match the DB CHECK constraint exactly so
72    // structurally invalid IDs cannot pass capability validation and reach
73    // domain code or the database.
74    if MemoryId::parse(&mount.memory).is_err() {
75        return Err(format!(
76            "mount.memory must be a valid Memory ID of the form mem_<32-lowercase-hex>, got '{}'",
77            mount.memory
78        ));
79    }
80
81    // Mount path must be either exactly `/workspace` or descend from it via a
82    // `/workspace/` boundary (rejects lookalikes such as `/workspacefoo`).
83    // It must not contain `..`, null bytes, empty segments, or a trailing slash.
84    let path = &mount.path;
85    if path != "/workspace" && !path.starts_with("/workspace/") {
86        return Err(format!(
87            "mount.path must be /workspace or start with /workspace/, got '{path}'"
88        ));
89    }
90    if path.contains("//") {
91        return Err(format!("mount.path must not contain '//', got '{path}'"));
92    }
93    if path.contains('\0') {
94        return Err(format!(
95            "mount.path must not contain null bytes, got '{path}'"
96        ));
97    }
98    if path.split('/').any(|seg| seg == "..") {
99        return Err(format!("mount.path must not contain '..', got '{path}'"));
100    }
101    if path.len() > 1 && path.ends_with('/') {
102        return Err(format!(
103            "mount.path must not end with a trailing slash, got '{path}'"
104        ));
105    }
106    Ok(())
107}
108
109/// Validate a full `memory` capability config: per-entry shape + duplicate /
110/// overlapping path detection.
111pub fn validate_memory_config(config: &MemoryConfig) -> Result<(), String> {
112    for mount in &config.mounts {
113        validate_mount_config_shape(mount)?;
114    }
115    // Reject duplicate mount paths.
116    let mut seen: Vec<&str> = Vec::with_capacity(config.mounts.len());
117    for mount in &config.mounts {
118        if seen.iter().any(|p| *p == mount.path) {
119            return Err(format!(
120                "duplicate mount path '{}' in memory config",
121                mount.path
122            ));
123        }
124        seen.push(&mount.path);
125    }
126    // Reject overlapping mount paths (one being a prefix of another).
127    for (i, a) in config.mounts.iter().enumerate() {
128        for b in &config.mounts[i + 1..] {
129            if mount_paths_overlap(&a.path, &b.path) {
130                return Err(format!(
131                    "overlapping mount paths '{}' and '{}'",
132                    a.path, b.path
133                ));
134            }
135        }
136    }
137    Ok(())
138}
139
140fn mount_paths_overlap(a: &str, b: &str) -> bool {
141    if a == b {
142        return true;
143    }
144    let (shorter, longer) = if a.len() < b.len() { (a, b) } else { (b, a) };
145    longer.starts_with(shorter) && longer.as_bytes().get(shorter.len()) == Some(&b'/')
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151    #[test]
152    fn access_default_is_readonly() {
153        let cfg: MemoryMountConfig = serde_json::from_str(
154            r#"{ "memory": "mem_00000000000000000000000000000001", "path": "/workspace/r" }"#,
155        )
156        .unwrap();
157        assert_eq!(cfg.mode, MemoryMountAccess::ReadOnly);
158    }
159
160    #[test]
161    fn validate_rejects_non_mem_prefix() {
162        let cfg = MemoryMountConfig {
163            memory: "agent_x".into(),
164            path: "/workspace/r".into(),
165            mode: MemoryMountAccess::ReadOnly,
166        };
167        assert!(validate_mount_config_shape(&cfg).is_err());
168    }
169
170    #[test]
171    fn validate_rejects_path_outside_workspace() {
172        let cfg = MemoryMountConfig {
173            memory: "mem_00000000000000000000000000000001".into(),
174            path: "/etc/passwd".into(),
175            mode: MemoryMountAccess::ReadOnly,
176        };
177        assert!(validate_mount_config_shape(&cfg).is_err());
178    }
179
180    #[test]
181    fn validate_rejects_workspace_prefix_lookalike() {
182        // /workspacefoo must NOT pass the /workspace boundary check.
183        let cfg = MemoryMountConfig {
184            memory: "mem_00000000000000000000000000000001".into(),
185            path: "/workspacefoo".into(),
186            mode: MemoryMountAccess::ReadOnly,
187        };
188        assert!(validate_mount_config_shape(&cfg).is_err());
189    }
190
191    #[test]
192    fn validate_accepts_workspace_root() {
193        let cfg = MemoryMountConfig {
194            memory: "mem_00000000000000000000000000000001".into(),
195            path: "/workspace".into(),
196            mode: MemoryMountAccess::ReadOnly,
197        };
198        assert!(validate_mount_config_shape(&cfg).is_ok());
199    }
200
201    #[test]
202    fn validate_rejects_invalid_hex_in_memory_id() {
203        // mem_-prefixed but not 32 lowercase hex chars must be rejected so
204        // structurally invalid IDs cannot reach the database.
205        let cfg = MemoryMountConfig {
206            memory: "mem_not-hex".into(),
207            path: "/workspace/r".into(),
208            mode: MemoryMountAccess::ReadOnly,
209        };
210        assert!(validate_mount_config_shape(&cfg).is_err());
211    }
212
213    #[test]
214    fn validate_rejects_dotdot() {
215        let cfg = MemoryMountConfig {
216            memory: "mem_00000000000000000000000000000001".into(),
217            path: "/workspace/../etc".into(),
218            mode: MemoryMountAccess::ReadOnly,
219        };
220        assert!(validate_mount_config_shape(&cfg).is_err());
221    }
222
223    #[test]
224    fn validate_rejects_double_slash() {
225        let cfg = MemoryMountConfig {
226            memory: "mem_00000000000000000000000000000001".into(),
227            path: "/workspace//data".into(),
228            mode: MemoryMountAccess::ReadOnly,
229        };
230        assert!(validate_mount_config_shape(&cfg).is_err());
231    }
232
233    #[test]
234    fn validate_rejects_trailing_slash() {
235        let cfg = MemoryMountConfig {
236            memory: "mem_00000000000000000000000000000001".into(),
237            path: "/workspace/data/".into(),
238            mode: MemoryMountAccess::ReadOnly,
239        };
240        assert!(validate_mount_config_shape(&cfg).is_err());
241    }
242
243    #[test]
244    fn validate_accepts_valid_mount() {
245        let cfg = MemoryMountConfig {
246            memory: "mem_00000000000000000000000000000001".into(),
247            path: "/workspace/research".into(),
248            mode: MemoryMountAccess::ReadOnly,
249        };
250        assert!(validate_mount_config_shape(&cfg).is_ok());
251    }
252
253    #[test]
254    fn config_validate_rejects_duplicate_paths() {
255        let cfg = MemoryConfig {
256            mounts: vec![
257                MemoryMountConfig {
258                    memory: "mem_00000000000000000000000000000001".into(),
259                    path: "/workspace/data".into(),
260                    mode: MemoryMountAccess::ReadOnly,
261                },
262                MemoryMountConfig {
263                    memory: "mem_00000000000000000000000000000002".into(),
264                    path: "/workspace/data".into(),
265                    mode: MemoryMountAccess::ReadWrite,
266                },
267            ],
268        };
269        let err = validate_memory_config(&cfg).unwrap_err();
270        assert!(err.contains("duplicate"));
271    }
272
273    #[test]
274    fn config_validate_rejects_overlapping_paths() {
275        let cfg = MemoryConfig {
276            mounts: vec![
277                MemoryMountConfig {
278                    memory: "mem_00000000000000000000000000000001".into(),
279                    path: "/workspace/data".into(),
280                    mode: MemoryMountAccess::ReadOnly,
281                },
282                MemoryMountConfig {
283                    memory: "mem_00000000000000000000000000000002".into(),
284                    path: "/workspace/data/sub".into(),
285                    mode: MemoryMountAccess::ReadWrite,
286                },
287            ],
288        };
289        let err = validate_memory_config(&cfg).unwrap_err();
290        assert!(err.contains("overlapping"));
291    }
292
293    #[test]
294    fn config_validate_accepts_distinct_paths() {
295        let cfg = MemoryConfig {
296            mounts: vec![
297                MemoryMountConfig {
298                    memory: "mem_00000000000000000000000000000001".into(),
299                    path: "/workspace/data".into(),
300                    mode: MemoryMountAccess::ReadOnly,
301                },
302                MemoryMountConfig {
303                    memory: "mem_00000000000000000000000000000002".into(),
304                    path: "/workspace/notes".into(),
305                    mode: MemoryMountAccess::ReadWrite,
306                },
307            ],
308        };
309        assert!(validate_memory_config(&cfg).is_ok());
310    }
311
312    #[test]
313    fn overlap_helper_does_not_match_unrelated_prefix() {
314        // /workspace/data and /workspace/datasets must NOT overlap.
315        assert!(!mount_paths_overlap(
316            "/workspace/data",
317            "/workspace/datasets"
318        ));
319    }
320}