astrid-capsule 0.3.0

Core runtime management for User-Space Capsules in Astrid OS
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
use extism::{CurrentPlugin, Error, UserData, Val};
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;

use crate::engine::wasm::host::util;
use crate::engine::wasm::host_state::HostState;

/// URI scheme prefix for the global shared directory (`~/.astrid/shared/`).
const GLOBAL_SCHEME: &str = "global://";

/// Strip any leading absolute slashes or prefixes (e.g. C:\) from the requested path
fn make_relative(requested: &str) -> &Path {
    let path = Path::new(requested);
    let mut components = path.components();
    while let Some(c) = components.clone().next() {
        if matches!(c, Component::RootDir | Component::Prefix(_)) {
            components.next(); // consume it
        } else {
            break;
        }
    }
    components.as_path()
}

/// Result of resolving a path to a physical absolute location on disk.
struct ResolvedPhysical {
    /// The fully resolved physical path (symlinks canonicalized where possible).
    physical: PathBuf,
    /// The canonical root this path was resolved against.
    canonical_root: PathBuf,
}

/// Compute the true physical absolute path for the security gate by canonicalizing on the host filesystem.
/// This prevents symlink bypass attacks where a lexical path passes the gate but cap-std follows a symlink.
fn resolve_physical_absolute(root: &Path, requested: &str) -> Result<ResolvedPhysical, Error> {
    let canonical_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());

    let relative_requested = make_relative(requested);
    let joined = canonical_root.join(relative_requested);

    let mut current_check = joined.clone();
    let mut unexisting_components = Vec::new();

    loop {
        if std::fs::symlink_metadata(&current_check).is_ok() {
            let canonical =
                std::fs::canonicalize(&current_check).unwrap_or_else(|_| current_check.clone());
            let mut final_path = canonical;
            for comp in unexisting_components.into_iter().rev() {
                final_path.push(comp);
            }
            if !final_path.starts_with(&canonical_root) {
                return Err(Error::msg(format!(
                    "path escapes root boundary: {requested} resolves to {}",
                    final_path.display()
                )));
            }
            return Ok(ResolvedPhysical {
                physical: final_path,
                canonical_root,
            });
        }
        if let Some(parent) = current_check.parent() {
            if let Some(file_name) = current_check.file_name() {
                unexisting_components.push(file_name.to_os_string());
            }
            current_check = parent.to_path_buf();
        } else {
            break;
        }
    }

    if !joined.starts_with(&canonical_root) {
        return Err(Error::msg(format!(
            "path escapes root boundary: {requested} resolves to {}",
            joined.display()
        )));
    }

    Ok(ResolvedPhysical {
        physical: joined,
        canonical_root,
    })
}

/// First-phase resolution result: physical path for the security gate,
/// the VFS-relative path, and whether this is a global:// path.
struct ResolvedPath {
    /// Absolute physical path (for security gate check).
    physical: PathBuf,
    /// Path relative to the root (for VFS operations).
    relative: PathBuf,
    /// Whether this path targets the global shared VFS.
    is_global: bool,
}

/// Second-phase resolution result: the VFS instance and capability handle
/// to use for the actual filesystem operation.
struct ResolvedVfsPath {
    /// Path relative to the VFS root.
    relative: PathBuf,
    /// The VFS instance to use.
    vfs: Arc<dyn astrid_vfs::Vfs>,
    /// The capability handle for the VFS root.
    handle: astrid_capabilities::DirHandle,
}

/// Phase 1: Resolve a raw guest path to a physical path and determine
/// whether it targets the workspace or global VFS.
fn resolve_path(state: &HostState, raw_path: &str) -> Result<ResolvedPath, Error> {
    if let Some(stripped) = raw_path.strip_prefix(GLOBAL_SCHEME) {
        let global_root = state.global_root.as_ref().ok_or_else(|| {
            Error::msg(
                "global:// scheme is not available: no ~/.astrid/shared/ directory is configured. \
                 Create the directory and restart the kernel.",
            )
        })?;
        let resolved = resolve_physical_absolute(global_root, stripped)?;
        let relative = resolved
            .physical
            .strip_prefix(&resolved.canonical_root)
            .map_err(|_| Error::msg("resolved global path escaped canonical root"))?
            .to_path_buf();
        Ok(ResolvedPath {
            physical: resolved.physical,
            relative,
            is_global: true,
        })
    } else {
        let resolved = resolve_physical_absolute(&state.workspace_root, raw_path)?;
        let relative = resolved
            .physical
            .strip_prefix(&resolved.canonical_root)
            .map_err(|_| Error::msg("resolved path escaped canonical root"))?
            .to_path_buf();
        Ok(ResolvedPath {
            physical: resolved.physical,
            relative,
            is_global: false,
        })
    }
}

/// Phase 2: Given a first-phase result, select the correct VFS instance
/// and capability handle.
fn resolve_vfs(state: &HostState, resolved: &ResolvedPath) -> Result<ResolvedVfsPath, Error> {
    if resolved.is_global {
        let vfs = state.global_vfs.clone().ok_or_else(|| {
            Error::msg(
                "global:// VFS is not mounted: ~/.astrid/shared/ directory may not exist. \
                 Create the directory and restart the kernel.",
            )
        })?;
        let handle = state
            .global_vfs_root_handle
            .clone()
            .ok_or_else(|| Error::msg("global:// VFS root handle is not available"))?;
        Ok(ResolvedVfsPath {
            relative: resolved.relative.clone(),
            vfs,
            handle,
        })
    } else {
        Ok(ResolvedVfsPath {
            relative: resolved.relative.clone(),
            vfs: state.vfs.clone(),
            handle: state.vfs_root_handle.clone(),
        })
    }
}

#[expect(clippy::needless_pass_by_value)]
pub(crate) fn astrid_fs_exists_impl(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostState>,
) -> Result<(), Error> {
    let path_bytes: Vec<u8> = util::get_safe_bytes(plugin, &inputs[0], util::MAX_PATH_LEN)?;
    let path = String::from_utf8(path_bytes).unwrap_or_default();

    let ud = user_data.get()?;
    // Safety: HostState lock is held across bounded_block_on. This is safe because
    // WASM is single-threaded per plugin - the plugin mutex in invoke_interceptor /
    // run loop serializes all host function calls, so no concurrent lock contention
    // is possible on the same UserData. The lock is needed for resolve_path/resolve_vfs
    // which reference multiple HostState fields.
    let state = ud
        .lock()
        .map_err(|e| Error::msg(format!("host state lock poisoned: {e}")))?;

    let capsule_id = state.capsule_id.as_str().to_owned();

    // Phase 1: resolve to physical path
    let resolved = resolve_path(&state, &path)?;

    // Security gate check
    let security = state.security.clone();
    if let Some(gate) = security {
        let p = resolved.physical.to_string_lossy().to_string();
        let pid = capsule_id.clone();
        let check =
            util::bounded_block_on(&state.runtime_handle, &state.host_semaphore, async move {
                gate.check_file_read(&pid, &p).await
            });
        if let Err(reason) = check {
            return Err(Error::msg(format!(
                "security denied exists check: {reason}"
            )));
        }
    }

    // Phase 2: resolve to VFS
    let vfs_path = resolve_vfs(&state, &resolved)?;

    let exists = util::bounded_block_on(&state.runtime_handle, &state.host_semaphore, async {
        vfs_path
            .vfs
            .exists(
                &vfs_path.handle,
                vfs_path.relative.to_string_lossy().as_ref(),
            )
            .await
    })
    .unwrap_or(false);

    let result = if exists {
        b"true".to_vec()
    } else {
        b"".to_vec()
    };
    let mem = plugin.memory_new(result)?;
    outputs[0] = plugin.memory_to_val(mem);
    Ok(())
}

#[expect(clippy::needless_pass_by_value)]
pub(crate) fn astrid_fs_mkdir_impl(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    _outputs: &mut [Val],
    user_data: UserData<HostState>,
) -> Result<(), Error> {
    let path_bytes: Vec<u8> = util::get_safe_bytes(plugin, &inputs[0], util::MAX_PATH_LEN)?;
    let path = String::from_utf8(path_bytes).unwrap_or_default();

    let ud = user_data.get()?;
    let state = ud
        .lock()
        .map_err(|e| Error::msg(format!("host state lock poisoned: {e}")))?;
    let capsule_id = state.capsule_id.as_str().to_owned();

    let resolved = resolve_path(&state, &path)?;

    let security = state.security.clone();
    if let Some(gate) = security {
        let p = resolved.physical.to_string_lossy().to_string();
        let pid = capsule_id.clone();
        let check =
            util::bounded_block_on(&state.runtime_handle, &state.host_semaphore, async move {
                gate.check_file_write(&pid, &p).await
            });
        if let Err(reason) = check {
            return Err(Error::msg(format!("security denied mkdir: {reason}")));
        }
    }

    let vfs_path = resolve_vfs(&state, &resolved)?;

    util::bounded_block_on(&state.runtime_handle, &state.host_semaphore, async {
        vfs_path
            .vfs
            .mkdir(
                &vfs_path.handle,
                vfs_path.relative.to_string_lossy().as_ref(),
            )
            .await
    })
    .map_err(|e| Error::msg(format!("mkdir failed: {e}")))?;

    Ok(())
}

#[expect(clippy::needless_pass_by_value)]
pub(crate) fn astrid_fs_readdir_impl(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostState>,
) -> Result<(), Error> {
    let path_bytes: Vec<u8> = util::get_safe_bytes(plugin, &inputs[0], util::MAX_PATH_LEN)?;
    let path = String::from_utf8(path_bytes).unwrap_or_default();

    let ud = user_data.get()?;
    let state = ud
        .lock()
        .map_err(|e| Error::msg(format!("host state lock poisoned: {e}")))?;
    let capsule_id = state.capsule_id.as_str().to_owned();

    let resolved = resolve_path(&state, &path)?;

    let security = state.security.clone();
    if let Some(gate) = security {
        let p = resolved.physical.to_string_lossy().to_string();
        let pid = capsule_id.clone();
        let check =
            util::bounded_block_on(&state.runtime_handle, &state.host_semaphore, async move {
                gate.check_file_read(&pid, &p).await
            });
        if let Err(reason) = check {
            return Err(Error::msg(format!("security denied readdir: {reason}")));
        }
    }

    let vfs_path = resolve_vfs(&state, &resolved)?;

    let entries = util::bounded_block_on(&state.runtime_handle, &state.host_semaphore, async {
        vfs_path
            .vfs
            .readdir(
                &vfs_path.handle,
                vfs_path.relative.to_string_lossy().as_ref(),
            )
            .await
    })
    .map_err(|e| Error::msg(format!("readdir failed: {e}")))?;

    // We historically map this to an array of strings in extism
    let string_entries: Vec<String> = entries.into_iter().map(|e| e.name).collect();

    let json = serde_json::to_string(&string_entries)
        .map_err(|e| Error::msg(format!("failed to serialize directory entries: {e}")))?;

    let mem = plugin.memory_new(&json)?;
    outputs[0] = plugin.memory_to_val(mem);
    Ok(())
}

#[expect(clippy::needless_pass_by_value)]
pub(crate) fn astrid_fs_stat_impl(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostState>,
) -> Result<(), Error> {
    let path_bytes: Vec<u8> = util::get_safe_bytes(plugin, &inputs[0], util::MAX_PATH_LEN)?;
    let path = String::from_utf8(path_bytes).unwrap_or_default();

    let ud = user_data.get()?;
    let state = ud
        .lock()
        .map_err(|e| Error::msg(format!("host state lock poisoned: {e}")))?;

    let capsule_id = state.capsule_id.as_str().to_owned();

    let resolved = resolve_path(&state, &path)?;

    let security = state.security.clone();
    if let Some(gate) = security {
        let p = resolved.physical.to_string_lossy().to_string();
        let pid = capsule_id.clone();
        let check =
            util::bounded_block_on(&state.runtime_handle, &state.host_semaphore, async move {
                gate.check_file_read(&pid, &p).await
            });
        if let Err(reason) = check {
            return Err(Error::msg(format!("security denied stat: {reason}")));
        }
    }

    let vfs_path = resolve_vfs(&state, &resolved)?;

    let metadata = util::bounded_block_on(&state.runtime_handle, &state.host_semaphore, async {
        vfs_path
            .vfs
            .stat(
                &vfs_path.handle,
                vfs_path.relative.to_string_lossy().as_ref(),
            )
            .await
    })
    .map_err(|e| Error::msg(format!("stat failed: {e}")))?;

    let stat = serde_json::json!({
        "size": metadata.size,
        "isDir": metadata.is_dir,
        "mtime": metadata.mtime
    });

    let json = stat.to_string();
    let mem = plugin.memory_new(&json)?;
    outputs[0] = plugin.memory_to_val(mem);
    Ok(())
}

#[expect(clippy::needless_pass_by_value)]
pub(crate) fn astrid_fs_unlink_impl(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    _outputs: &mut [Val],
    user_data: UserData<HostState>,
) -> Result<(), Error> {
    let path_bytes: Vec<u8> = util::get_safe_bytes(plugin, &inputs[0], util::MAX_PATH_LEN)?;
    let path = String::from_utf8(path_bytes).unwrap_or_default();

    let ud = user_data.get()?;
    let state = ud
        .lock()
        .map_err(|e| Error::msg(format!("host state lock poisoned: {e}")))?;

    let capsule_id = state.capsule_id.as_str().to_owned();

    let resolved = resolve_path(&state, &path)?;

    let security = state.security.clone();
    if let Some(gate) = security {
        let p = resolved.physical.to_string_lossy().to_string();
        let pid = capsule_id.clone();
        let check =
            util::bounded_block_on(&state.runtime_handle, &state.host_semaphore, async move {
                gate.check_file_write(&pid, &p).await
            });
        if let Err(reason) = check {
            return Err(Error::msg(format!("security denied unlink: {reason}")));
        }
    }

    let vfs_path = resolve_vfs(&state, &resolved)?;

    util::bounded_block_on(&state.runtime_handle, &state.host_semaphore, async {
        vfs_path
            .vfs
            .unlink(
                &vfs_path.handle,
                vfs_path.relative.to_string_lossy().as_ref(),
            )
            .await
    })
    .map_err(|e| Error::msg(format!("unlink failed: {e}")))?;

    Ok(())
}

#[expect(clippy::needless_pass_by_value)]
pub(crate) fn astrid_read_file_impl(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    outputs: &mut [Val],
    user_data: UserData<HostState>,
) -> Result<(), Error> {
    let path_bytes: Vec<u8> = util::get_safe_bytes(plugin, &inputs[0], util::MAX_PATH_LEN)?;
    let path = String::from_utf8(path_bytes).unwrap_or_default();

    let ud = user_data.get()?;
    let state = ud
        .lock()
        .map_err(|e| Error::msg(format!("host state lock poisoned: {e}")))?;

    let capsule_id = state.capsule_id.as_str().to_owned();

    let resolved = resolve_path(&state, &path)?;

    let security = state.security.clone();
    if let Some(gate) = security {
        let p = resolved.physical.to_string_lossy().to_string();
        let pid = capsule_id.clone();
        let check =
            util::bounded_block_on(&state.runtime_handle, &state.host_semaphore, async move {
                gate.check_file_read(&pid, &p).await
            });
        if let Err(reason) = check {
            return Err(Error::msg(format!("security denied read_file: {reason}")));
        }
    }

    let vfs_path = resolve_vfs(&state, &resolved)?;

    let content_bytes =
        util::bounded_block_on(&state.runtime_handle, &state.host_semaphore, async {
            let metadata = vfs_path
                .vfs
                .stat(
                    &vfs_path.handle,
                    vfs_path.relative.to_string_lossy().as_ref(),
                )
                .await?;
            if metadata.size > util::MAX_GUEST_PAYLOAD_LEN {
                return Err(astrid_vfs::VfsError::PermissionDenied(format!(
                    "File too large to read into memory ({} bytes > {} bytes)",
                    metadata.size,
                    util::MAX_GUEST_PAYLOAD_LEN
                )));
            }

            let handle = vfs_path
                .vfs
                .open(
                    &vfs_path.handle,
                    vfs_path.relative.to_string_lossy().as_ref(),
                    false,
                    false,
                )
                .await?;
            let data = vfs_path.vfs.read(&handle).await;
            let _ = vfs_path.vfs.close(&handle).await;
            data
        })
        .map_err(|e| Error::msg(format!("read_file failed: {e}")))?;

    let mem = plugin.memory_new(&content_bytes)?;
    outputs[0] = plugin.memory_to_val(mem);
    Ok(())
}

#[expect(clippy::needless_pass_by_value)]
pub(crate) fn astrid_write_file_impl(
    plugin: &mut CurrentPlugin,
    inputs: &[Val],
    _outputs: &mut [Val],
    user_data: UserData<HostState>,
) -> Result<(), Error> {
    let path_bytes: Vec<u8> = util::get_safe_bytes(plugin, &inputs[0], util::MAX_PATH_LEN)?;
    let content_bytes: Vec<u8> =
        util::get_safe_bytes(plugin, &inputs[1], util::MAX_GUEST_PAYLOAD_LEN)?;
    let path = String::from_utf8(path_bytes).unwrap_or_default();

    let ud = user_data.get()?;
    let state = ud
        .lock()
        .map_err(|e| Error::msg(format!("host state lock poisoned: {e}")))?;

    let capsule_id = state.capsule_id.as_str().to_owned();

    let resolved = resolve_path(&state, &path)?;

    let security = state.security.clone();
    if let Some(gate) = security {
        let p = resolved.physical.to_string_lossy().to_string();
        let pid = capsule_id.clone();
        let check =
            util::bounded_block_on(&state.runtime_handle, &state.host_semaphore, async move {
                gate.check_file_write(&pid, &p).await
            });
        if let Err(reason) = check {
            return Err(Error::msg(format!("security denied write_file: {reason}")));
        }
    }

    let vfs_path = resolve_vfs(&state, &resolved)?;

    util::bounded_block_on(&state.runtime_handle, &state.host_semaphore, async {
        // Note: pass truncate=true to emulate standard write behavior
        let handle = vfs_path
            .vfs
            .open(
                &vfs_path.handle,
                vfs_path.relative.to_string_lossy().as_ref(),
                true,
                true,
            )
            .await?;
        let res = vfs_path.vfs.write(&handle, &content_bytes).await;
        let _ = vfs_path.vfs.close(&handle).await;
        res
    })
    .map_err(|e| Error::msg(format!("write_file failed: {e}")))?;

    Ok(())
}