mino 1.6.0

Secure AI agent sandbox using rootless containers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
//! Configuration management for Mino

pub mod schema;
pub mod trust;

pub use schema::Config;

use crate::error::{MinoError, MinoResult};
use std::path::{Path, PathBuf};
use tokio::fs;
use toml::Value;
use tracing::debug;

/// Local config filename
const LOCAL_CONFIG_FILENAME: &str = ".mino.toml";

/// Configuration manager
pub struct ConfigManager {
    config_path: PathBuf,
}

impl ConfigManager {
    /// Create a new config manager with default path
    pub fn new() -> Self {
        Self {
            config_path: Self::default_config_path(),
        }
    }

    /// Create a config manager with a custom path
    pub fn with_path(path: PathBuf) -> Self {
        Self { config_path: path }
    }

    /// Get the default config file path
    pub fn default_config_path() -> PathBuf {
        dirs::config_dir()
            .unwrap_or_else(|| PathBuf::from("."))
            .join("mino")
            .join("config.toml")
    }

    /// Get the state directory path
    pub fn state_dir() -> PathBuf {
        dirs::state_dir()
            .or_else(dirs::data_local_dir)
            .unwrap_or_else(|| PathBuf::from("."))
            .join("mino")
    }

    /// Get the sessions directory path
    pub fn sessions_dir() -> PathBuf {
        Self::state_dir().join("sessions")
    }

    /// Get the credentials cache directory path
    pub fn credentials_dir() -> PathBuf {
        Self::state_dir().join("credentials")
    }

    /// Get the cache state directory path (sidecar JSON files)
    pub fn cache_state_dir() -> PathBuf {
        Self::state_dir().join("cache")
    }

    /// Get the audit log file path
    pub fn audit_log_path() -> PathBuf {
        Self::state_dir().join("audit.log")
    }

    /// Search from `start_dir` upward for `.mino.toml`.
    /// Stops at filesystem root. Returns the path if found.
    pub fn find_local_config(start_dir: &Path) -> Option<PathBuf> {
        let mut current = start_dir.to_path_buf();
        loop {
            let candidate = current.join(LOCAL_CONFIG_FILENAME);
            if candidate.is_file() {
                return Some(candidate);
            }
            if !current.pop() {
                return None;
            }
        }
    }

    /// Deep-merge two TOML value trees. Keys in `overlay` override `base`.
    /// Tables are merged recursively; all other value types (including arrays)
    /// replace outright — arrays are **not** appended.
    pub fn merge_toml(base: Value, overlay: Value) -> Value {
        match (base, overlay) {
            (Value::Table(mut base_table), Value::Table(overlay_table)) => {
                for (key, overlay_val) in overlay_table {
                    let merged = match base_table.remove(&key) {
                        Some(base_val) => Self::merge_toml(base_val, overlay_val),
                        None => overlay_val,
                    };
                    base_table.insert(key, merged);
                }
                Value::Table(base_table)
            }
            // Non-table overlay replaces base entirely
            (_base, overlay) => overlay,
        }
    }

    /// Load merged configuration: global config merged with optional local config.
    ///
    /// Precedence: local `.mino.toml` > global `~/.config/mino/config.toml` > defaults.
    /// (CLI flags override the result separately at the call site.)
    pub async fn load_merged(&self, local_path: Option<&Path>) -> MinoResult<Config> {
        // Load global as raw TOML value (empty table if file missing)
        let global_value = if self.config_path.exists() {
            let content = fs::read_to_string(&self.config_path).await.map_err(|e| {
                MinoError::io(
                    format!("reading config from {}", self.config_path.display()),
                    e,
                )
            })?;
            content
                .parse::<Value>()
                .map_err(|e| MinoError::ConfigInvalid {
                    path: self.config_path.clone(),
                    reason: e.to_string(),
                })?
        } else {
            debug!("Global config not found, using defaults");
            Value::Table(toml::map::Map::new())
        };

        // Merge local on top if present
        let merged_value = match local_path {
            Some(path) => {
                let content = fs::read_to_string(path).await.map_err(|e| {
                    MinoError::io(format!("reading local config from {}", path.display()), e)
                })?;
                let local_value =
                    content
                        .parse::<Value>()
                        .map_err(|e| MinoError::ConfigInvalid {
                            path: path.to_path_buf(),
                            reason: e.to_string(),
                        })?;
                debug!("Merging local config from {} over global", path.display());
                Self::merge_toml(global_value, local_value)
            }
            None => global_value,
        };

        // Deserialize merged tree into Config (serde defaults fill gaps)
        let config_source = match local_path {
            Some(lp) => format!(
                "merged config [global: {}, local: {}]",
                self.config_path.display(),
                lp.display()
            ),
            None => self.config_path.display().to_string(),
        };

        merged_value
            .try_into()
            .map_err(|e: toml::de::Error| MinoError::ConfigInvalid {
                path: local_path.unwrap_or(&self.config_path).to_path_buf(),
                reason: format!("{} (source: {})", e, config_source),
            })
    }

    /// Load configuration, creating default if not exists
    pub async fn load(&self) -> MinoResult<Config> {
        if !self.config_path.exists() {
            debug!("Config file not found, using defaults");
            return Ok(Config::default());
        }

        self.load_from_file(&self.config_path).await
    }

    /// Load configuration from a specific file
    pub async fn load_from_file(&self, path: &Path) -> MinoResult<Config> {
        let content = fs::read_to_string(path)
            .await
            .map_err(|e| MinoError::io(format!("reading config from {}", path.display()), e))?;

        toml::from_str(&content).map_err(|e| MinoError::ConfigInvalid {
            path: path.to_path_buf(),
            reason: e.to_string(),
        })
    }

    /// Save configuration to file
    pub async fn save(&self, config: &Config) -> MinoResult<()> {
        self.ensure_config_dir().await?;

        let content = toml::to_string_pretty(config)?;
        fs::write(&self.config_path, content).await.map_err(|e| {
            MinoError::io(
                format!("writing config to {}", self.config_path.display()),
                e,
            )
        })?;

        debug!("Configuration saved to {}", self.config_path.display());
        Ok(())
    }

    /// Ensure the config directory exists
    async fn ensure_config_dir(&self) -> MinoResult<()> {
        if let Some(parent) = self.config_path.parent() {
            fs::create_dir_all(parent)
                .await
                .map_err(|e| MinoError::ConfigDirCreate {
                    path: parent.to_path_buf(),
                    source: e,
                })?;
        }
        Ok(())
    }

    /// Ensure all state directories exist
    pub async fn ensure_state_dirs() -> MinoResult<()> {
        let dirs = [
            Self::state_dir(),
            Self::sessions_dir(),
            Self::credentials_dir(),
            Self::cache_state_dir(),
        ];

        for dir in &dirs {
            fs::create_dir_all(dir)
                .await
                .map_err(|e| MinoError::io(format!("creating directory {}", dir.display()), e))?;
        }

        // Set restrictive permissions on credentials directory
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let perms = std::fs::Permissions::from_mode(0o700);
            std::fs::set_permissions(Self::credentials_dir(), perms)
                .map_err(|e| MinoError::io("setting credentials dir permissions", e))?;
        }

        Ok(())
    }

    /// Get the config file path
    pub fn path(&self) -> &Path {
        &self.config_path
    }
}

impl Default for ConfigManager {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[tokio::test]
    async fn load_default_when_missing() {
        let temp = TempDir::new().unwrap();
        let path = temp.path().join("nonexistent.toml");
        let manager = ConfigManager::with_path(path);

        let config = manager.load().await.unwrap();
        assert_eq!(config.vm.name, "mino");
    }

    #[tokio::test]
    async fn save_and_load_roundtrip() {
        let temp = TempDir::new().unwrap();
        let path = temp.path().join("config.toml");
        let manager = ConfigManager::with_path(path);

        let mut config = Config::default();
        config.vm.name = "test-vm".to_string();

        manager.save(&config).await.unwrap();
        let loaded = manager.load().await.unwrap();

        assert_eq!(loaded.vm.name, "test-vm");
    }

    #[test]
    fn merge_toml_leaf_override() {
        let base: Value = toml::from_str(
            r#"
            [container]
            image = "fedora:43"
            network = "host"
            "#,
        )
        .unwrap();
        let overlay: Value = toml::from_str(
            r#"
            [container]
            image = "typescript"
            "#,
        )
        .unwrap();
        let merged = ConfigManager::merge_toml(base, overlay);
        let table = merged.as_table().unwrap();
        let container = table["container"].as_table().unwrap();
        assert_eq!(container["image"].as_str().unwrap(), "typescript");
        assert_eq!(container["network"].as_str().unwrap(), "host");
    }

    #[test]
    fn merge_toml_additive_tables() {
        let base: Value = toml::from_str(
            r#"
            [container]
            image = "fedora:43"
            "#,
        )
        .unwrap();
        let overlay: Value = toml::from_str(
            r#"
            [credentials.aws]
            enabled = true
            region = "us-west-2"
            "#,
        )
        .unwrap();
        let merged = ConfigManager::merge_toml(base, overlay);
        let table = merged.as_table().unwrap();
        // Base container preserved
        assert_eq!(
            table["container"].as_table().unwrap()["image"]
                .as_str()
                .unwrap(),
            "fedora:43"
        );
        // Overlay credentials added
        let aws = table["credentials"].as_table().unwrap()["aws"]
            .as_table()
            .unwrap();
        assert!(aws["enabled"].as_bool().unwrap());
        assert_eq!(aws["region"].as_str().unwrap(), "us-west-2");
    }

    #[test]
    fn merge_toml_nested_tables() {
        let base: Value = toml::from_str(
            r#"
            [credentials.aws]
            region = "us-east-1"
            session_duration_secs = 3600

            [credentials.gcp]
            project = "my-proj"
            "#,
        )
        .unwrap();
        let overlay: Value = toml::from_str(
            r#"
            [credentials.aws]
            region = "eu-west-1"
            "#,
        )
        .unwrap();
        let merged = ConfigManager::merge_toml(base, overlay);
        let creds = merged.as_table().unwrap()["credentials"]
            .as_table()
            .unwrap();
        let aws = creds["aws"].as_table().unwrap();
        // Overridden
        assert_eq!(aws["region"].as_str().unwrap(), "eu-west-1");
        // Preserved from base
        assert_eq!(aws["session_duration_secs"].as_integer().unwrap(), 3600);
        // Sibling table preserved
        let gcp = creds["gcp"].as_table().unwrap();
        assert_eq!(gcp["project"].as_str().unwrap(), "my-proj");
    }

    #[test]
    fn merge_toml_empty_overlay() {
        let base: Value = toml::from_str(
            r#"
            [container]
            image = "fedora:43"
            "#,
        )
        .unwrap();
        let overlay: Value = toml::from_str("").unwrap();
        let merged = ConfigManager::merge_toml(base.clone(), overlay);
        assert_eq!(merged, base);
    }

    #[test]
    fn merge_toml_array_replaces() {
        let base: Value = toml::from_str(
            r#"
            [container]
            volumes = ["/shared:/shared"]
            "#,
        )
        .unwrap();
        let overlay: Value = toml::from_str(
            r#"
            [container]
            volumes = ["/project:/project"]
            "#,
        )
        .unwrap();
        let merged = ConfigManager::merge_toml(base, overlay);
        let volumes = merged["container"]["volumes"].as_array().unwrap();
        assert_eq!(volumes.len(), 1);
        assert_eq!(volumes[0].as_str().unwrap(), "/project:/project");
    }

    #[test]
    fn find_local_config_in_cwd() {
        let temp = TempDir::new().unwrap();
        std::fs::write(temp.path().join(".mino.toml"), "# local config").unwrap();
        let found = ConfigManager::find_local_config(temp.path());
        assert_eq!(found.unwrap(), temp.path().join(".mino.toml"));
    }

    #[test]
    fn find_local_config_in_parent() {
        let temp = TempDir::new().unwrap();
        let child = temp.path().join("sub").join("deep");
        std::fs::create_dir_all(&child).unwrap();
        std::fs::write(temp.path().join(".mino.toml"), "# parent config").unwrap();
        let found = ConfigManager::find_local_config(&child);
        assert_eq!(found.unwrap(), temp.path().join(".mino.toml"));
    }

    #[test]
    fn find_local_config_missing() {
        let temp = TempDir::new().unwrap();
        let found = ConfigManager::find_local_config(temp.path());
        assert!(found.is_none());
    }

    #[tokio::test]
    async fn load_merged_combines_global_and_local() {
        let temp = TempDir::new().unwrap();

        // Write global config
        let global_path = temp.path().join("global.toml");
        std::fs::write(
            &global_path,
            r#"
            [container]
            image = "fedora:43"
            network = "host"

            [session]
            shell = "/bin/bash"
            "#,
        )
        .unwrap();

        // Write local config
        let local_path = temp.path().join(".mino.toml");
        std::fs::write(
            &local_path,
            r#"
            [container]
            image = "typescript"

            [credentials.aws]
            enabled = true
            region = "us-west-2"
            "#,
        )
        .unwrap();

        let manager = ConfigManager::with_path(global_path);
        let config = manager.load_merged(Some(&local_path)).await.unwrap();

        // Local overrides global
        assert_eq!(config.container.image, "typescript");
        // Global preserved where local is silent
        assert_eq!(config.container.network, "host");
        assert_eq!(config.session.shell, "/bin/bash");
        // Local adds new section
        assert!(config.credentials.aws.enabled);
        assert_eq!(config.credentials.aws.region.as_deref(), Some("us-west-2"));
    }

    #[tokio::test]
    async fn load_merged_no_local() {
        let temp = TempDir::new().unwrap();
        let global_path = temp.path().join("global.toml");
        std::fs::write(
            &global_path,
            r#"
            [container]
            image = "custom:latest"
            "#,
        )
        .unwrap();

        let manager = ConfigManager::with_path(global_path);
        let config = manager.load_merged(None).await.unwrap();
        assert_eq!(config.container.image, "custom:latest");
    }

    #[tokio::test]
    async fn load_merged_no_global() {
        let temp = TempDir::new().unwrap();
        let global_path = temp.path().join("nonexistent.toml");
        let local_path = temp.path().join(".mino.toml");
        std::fs::write(
            &local_path,
            r#"
            [container]
            image = "typescript"
            "#,
        )
        .unwrap();

        let manager = ConfigManager::with_path(global_path);
        let config = manager.load_merged(Some(&local_path)).await.unwrap();
        assert_eq!(config.container.image, "typescript");
        // Defaults fill in the rest
        assert_eq!(config.vm.name, "mino");
    }
}