a3s-box-runtime 2.5.2

MicroVM runtime engine — VM lifecycle, OCI images, attestation, networking
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
//! Persistent storage for network configurations.
//!
//! Networks are stored as JSON in `~/.a3s/networks.json` with atomic writes
//! (write to tmp file, then rename) to prevent corruption.

use a3s_box_core::error::{BoxError, Result};
use a3s_box_core::network::NetworkConfig;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// Persistent store for network configurations.
#[derive(Debug)]
pub struct NetworkStore {
    /// Path to the JSON file.
    path: PathBuf,
}

/// Serializable wrapper for the networks file.
#[derive(Debug, serde::Serialize, serde::Deserialize, Default)]
struct NetworksFile {
    networks: HashMap<String, NetworkConfig>,
}

impl NetworkStore {
    /// Create a new store at the given path.
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self { path: path.into() }
    }

    /// Create a store at the default location (`~/.a3s/networks.json`).
    pub fn default_path() -> Result<Self> {
        let home = a3s_box_core::dirs_home();
        Ok(Self::new(home.join("networks.json")))
    }

    /// Load all networks from disk.
    pub fn load(&self) -> Result<HashMap<String, NetworkConfig>> {
        if !self.path.exists() {
            return Ok(HashMap::new());
        }

        let data = std::fs::read_to_string(&self.path).map_err(|e| {
            BoxError::NetworkError(format!(
                "failed to read networks file {}: {}",
                self.path.display(),
                e
            ))
        })?;

        // A corrupt/old-schema networks file must not brick the runtime: quarantine
        // it and start from an empty set (create repopulates) rather than failing
        // every network operation. Mirrors the boxes.json hardening.
        let file: NetworksFile = match serde_json::from_str(&data) {
            Ok(f) => f,
            Err(e) => {
                let preserved = crate::store_io::quarantine_label(&self.path);
                tracing::warn!(
                    "networks file {} is corrupt ({e}); preserved a copy at {preserved} \
                     and started from an empty network set",
                    self.path.display(),
                );
                return Ok(HashMap::new());
            }
        };

        Ok(file.networks)
    }

    /// Save all networks to disk (atomic write).
    pub fn save(&self, networks: &HashMap<String, NetworkConfig>) -> Result<()> {
        // Ensure parent directory exists
        if let Some(parent) = self.path.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                BoxError::NetworkError(format!(
                    "failed to create directory {}: {}",
                    parent.display(),
                    e
                ))
            })?;
        }

        let file = NetworksFile {
            networks: networks.clone(),
        };

        let json = serde_json::to_string_pretty(&file)
            .map_err(|e| BoxError::NetworkError(format!("failed to serialize networks: {}", e)))?;

        // Atomic write: write to tmp, then rename
        let tmp_path = self.path.with_extension("json.tmp");
        std::fs::write(&tmp_path, &json).map_err(|e| {
            BoxError::NetworkError(format!(
                "failed to write tmp file {}: {}",
                tmp_path.display(),
                e
            ))
        })?;

        std::fs::rename(&tmp_path, &self.path).map_err(|e| {
            BoxError::NetworkError(format!(
                "failed to rename {}{}: {}",
                tmp_path.display(),
                self.path.display(),
                e
            ))
        })?;

        Ok(())
    }

    /// Get a single network by name.
    pub fn get(&self, name: &str) -> Result<Option<NetworkConfig>> {
        let networks = self.load()?;
        Ok(networks.get(name).cloned())
    }

    /// Run `f` against the full networks map under the **cross-process write
    /// lock** (load-fresh → mutate → save). Use this to make a
    /// get-modify-update sequence atomic — e.g. allocate-an-IP-then-connect —
    /// so concurrent boots cannot assign duplicate IPs/MACs or silently lose
    /// each other's endpoints. The map is saved only if `f` returns `Ok`.
    ///
    /// The lock is held across the whole load/mutate/save; `save` is itself
    /// lock-free, so there is no re-entrant `flock` (which would self-deadlock).
    pub fn with_write_lock<F, R, E>(&self, f: F) -> std::result::Result<R, E>
    where
        F: FnOnce(&mut HashMap<String, NetworkConfig>) -> std::result::Result<R, E>,
        E: From<BoxError>,
    {
        let _lock = crate::file_lock::FileLock::acquire(&self.path).map_err(|e| {
            E::from(BoxError::NetworkError(format!(
                "failed to lock networks file {}: {e}",
                self.path.display()
            )))
        })?;
        let mut networks = self.load().map_err(E::from)?;
        let r = f(&mut networks)?;
        self.save(&networks).map_err(E::from)?;
        Ok(r)
    }

    /// Create a new network. Returns error if name already exists.
    pub fn create(&self, config: NetworkConfig) -> Result<()> {
        self.with_write_lock(|networks| {
            if networks.contains_key(&config.name) {
                return Err(BoxError::NetworkError(format!(
                    "network '{}' already exists",
                    config.name
                )));
            }
            networks.insert(config.name.clone(), config);
            Ok(())
        })
    }

    /// Remove a network by name. Returns the removed config or error if not found.
    pub fn remove(&self, name: &str) -> Result<NetworkConfig> {
        self.with_write_lock(|networks| {
            let config = networks
                .remove(name)
                .ok_or_else(|| BoxError::NetworkError(format!("network '{}' not found", name)))?;

            if !config.endpoints.is_empty() {
                // Returning Err skips the save, so the in-memory removal is not
                // persisted — the network stays intact.
                return Err(BoxError::NetworkError(format!(
                    "network '{}' has {} connected endpoint(s); disconnect them first or use --force",
                    name,
                    config.endpoints.len()
                )));
            }
            Ok(config)
        })
    }

    /// List all network names.
    pub fn list(&self) -> Result<Vec<NetworkConfig>> {
        let networks = self.load()?;
        Ok(networks.into_values().collect())
    }

    /// Update a network in-place (used for connect/disconnect).
    ///
    /// Prefer [`with_write_lock`](Self::with_write_lock) for a
    /// get-modify-update sequence: `update` re-loads under the lock, but a
    /// caller that read the network *before* calling `update` decided its
    /// mutation on a possibly-stale snapshot.
    pub fn update(&self, config: &NetworkConfig) -> Result<()> {
        self.with_write_lock(|networks| {
            if !networks.contains_key(&config.name) {
                return Err(BoxError::NetworkError(format!(
                    "network '{}' not found",
                    config.name
                )));
            }
            networks.insert(config.name.clone(), config.clone());
            Ok(())
        })
    }

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

impl a3s_box_core::traits::NetworkStoreBackend for NetworkStore {
    fn get(&self, name: &str) -> Result<Option<NetworkConfig>> {
        self.get(name)
    }

    fn create(&self, config: NetworkConfig) -> Result<()> {
        self.create(config)
    }

    fn remove(&self, name: &str) -> Result<NetworkConfig> {
        self.remove(name)
    }

    fn list(&self) -> Result<Vec<NetworkConfig>> {
        self.list()
    }

    fn update(&self, config: &NetworkConfig) -> Result<()> {
        self.update(config)
    }
}

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

    fn temp_store() -> (tempfile::TempDir, NetworkStore) {
        let dir = tempfile::tempdir().unwrap();
        let store = NetworkStore::new(dir.path().join("networks.json"));
        (dir, store)
    }

    #[test]
    fn test_load_empty() {
        let (_dir, store) = temp_store();
        let networks = store.load().unwrap();
        assert!(networks.is_empty());
    }

    #[test]
    fn test_create_and_load() {
        let (_dir, store) = temp_store();
        let net = NetworkConfig::new("mynet", "10.88.0.0/24").unwrap();
        store.create(net).unwrap();

        let networks = store.load().unwrap();
        assert_eq!(networks.len(), 1);
        assert!(networks.contains_key("mynet"));
    }

    #[test]
    fn test_create_duplicate() {
        let (_dir, store) = temp_store();
        let net1 = NetworkConfig::new("mynet", "10.88.0.0/24").unwrap();
        let net2 = NetworkConfig::new("mynet", "10.89.0.0/24").unwrap();

        store.create(net1).unwrap();
        assert!(store.create(net2).is_err());
    }

    #[test]
    fn test_get_existing() {
        let (_dir, store) = temp_store();
        let net = NetworkConfig::new("mynet", "10.88.0.0/24").unwrap();
        store.create(net).unwrap();

        let found = store.get("mynet").unwrap();
        assert!(found.is_some());
        assert_eq!(found.unwrap().name, "mynet");
    }

    #[test]
    fn test_get_nonexistent() {
        let (_dir, store) = temp_store();
        let found = store.get("nope").unwrap();
        assert!(found.is_none());
    }

    #[test]
    fn test_remove() {
        let (_dir, store) = temp_store();
        let net = NetworkConfig::new("mynet", "10.88.0.0/24").unwrap();
        store.create(net).unwrap();

        let removed = store.remove("mynet").unwrap();
        assert_eq!(removed.name, "mynet");

        let networks = store.load().unwrap();
        assert!(networks.is_empty());
    }

    #[test]
    fn test_remove_nonexistent() {
        let (_dir, store) = temp_store();
        assert!(store.remove("nope").is_err());
    }

    #[test]
    fn test_remove_with_endpoints() {
        let (_dir, store) = temp_store();
        let mut net = NetworkConfig::new("mynet", "10.88.0.0/24").unwrap();
        net.connect("box-1", "web").unwrap();
        store.create(net).unwrap();

        // Should fail because endpoints are connected
        assert!(store.remove("mynet").is_err());
    }

    #[test]
    fn test_list() {
        let (_dir, store) = temp_store();
        store
            .create(NetworkConfig::new("net1", "10.88.0.0/24").unwrap())
            .unwrap();
        store
            .create(NetworkConfig::new("net2", "10.89.0.0/24").unwrap())
            .unwrap();

        let list = store.list().unwrap();
        assert_eq!(list.len(), 2);
    }

    #[test]
    fn test_update() {
        let (_dir, store) = temp_store();
        let net = NetworkConfig::new("mynet", "10.88.0.0/24").unwrap();
        store.create(net).unwrap();

        // Connect a box
        let mut net = store.get("mynet").unwrap().unwrap();
        net.connect("box-1", "web").unwrap();
        store.update(&net).unwrap();

        // Verify persistence
        let loaded = store.get("mynet").unwrap().unwrap();
        assert_eq!(loaded.endpoints.len(), 1);
    }

    #[test]
    fn test_update_nonexistent() {
        let (_dir, store) = temp_store();
        let net = NetworkConfig::new("nope", "10.88.0.0/24").unwrap();
        assert!(store.update(&net).is_err());
    }

    #[test]
    fn test_atomic_write() {
        let (_dir, store) = temp_store();
        let net = NetworkConfig::new("mynet", "10.88.0.0/24").unwrap();
        store.create(net).unwrap();

        // Verify the file exists and is valid JSON
        let data = std::fs::read_to_string(store.path()).unwrap();
        let _: serde_json::Value = serde_json::from_str(&data).unwrap();

        // Verify no tmp file left behind
        let tmp = store.path().with_extension("json.tmp");
        assert!(!tmp.exists());
    }

    #[test]
    fn test_creates_parent_directory() {
        let dir = tempfile::tempdir().unwrap();
        let store = NetworkStore::new(dir.path().join("subdir").join("networks.json"));

        let net = NetworkConfig::new("mynet", "10.88.0.0/24").unwrap();
        store.create(net).unwrap();

        assert!(store.path().exists());
    }

    #[test]
    fn concurrent_connects_allocate_distinct_ips() {
        use std::collections::HashSet;
        use std::sync::Arc;

        let dir = tempfile::tempdir().unwrap();
        let store = Arc::new(NetworkStore::new(dir.path().join("networks.json")));
        store
            .create(NetworkConfig::new("dev", "10.88.0.0/24").unwrap())
            .unwrap();

        // Many threads connect concurrently. with_write_lock must serialize the
        // load → allocate → save so every box gets a distinct IP and no endpoint
        // is lost — the bug allocated duplicate IPs and dropped endpoints.
        let handles: Vec<_> = (0..16)
            .map(|i| {
                let store = Arc::clone(&store);
                std::thread::spawn(move || {
                    store
                        .with_write_lock(|nets| {
                            nets.get_mut("dev")
                                .unwrap()
                                .connect(&format!("box-{i}"), &format!("name-{i}"))
                                .map_err(BoxError::NetworkError)
                        })
                        .unwrap()
                        .ip_address
                })
            })
            .collect();

        let ips: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();
        let unique: HashSet<_> = ips.iter().collect();
        assert_eq!(
            unique.len(),
            ips.len(),
            "concurrent connects must allocate distinct IPs (got {ips:?})"
        );
        assert_eq!(
            store.get("dev").unwrap().unwrap().endpoints.len(),
            16,
            "every concurrent endpoint must be persisted (no lost writes)"
        );
    }

    #[test]
    fn corrupt_networks_file_is_quarantined_not_fatal() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("networks.json");
        std::fs::write(&path, "{ not valid json").unwrap();
        let store = NetworkStore::new(path.clone());

        // load() must succeed (empty) instead of erroring every network op.
        assert!(store.load().unwrap().is_empty());
        // The corrupt file is preserved as a timestamped sibling, not lost.
        let quarantined = std::fs::read_dir(dir.path())
            .unwrap()
            .filter_map(|e| e.ok())
            .any(|e| {
                e.file_name()
                    .to_string_lossy()
                    .contains("networks.json.corrupt-")
            });
        assert!(quarantined, "corrupt networks.json must be quarantined");
    }
}