act-runtime 0.13.2

Embeddable wasmtime host for ACT (Agent Component Tools) components
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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
//! Layer 1 phase C1, part 2/2: custom `wasi:filesystem` host impl that gates
//! `open_at` (and path-taking siblings) on the `FsMatcher`.
//!
//! The host-facing surface:
//! - `PolicyFilesystem` is a `HasData` marker used in place of the default
//!   `wasmtime_wasi::WasiFilesystem` when adding the `wasi:filesystem/types`
//!   and `wasi:filesystem/preopens` interfaces to the linker.
//! - `PolicyFilesystemCtxView<'a>` bundles the default `WasiFilesystemCtx`,
//!   the `ResourceTable`, the compiled `FsMatcher`, and a running map of
//!   `fd → absolute host path`. It implements `preopens::Host`, `types::Host`,
//!   `HostDescriptor`, and `HostDirectoryEntryStream`, mostly by delegating
//!   to a temp `WasiFilesystemCtxView` constructed from the same fields.
//! - Path-taking methods (`open_at`, `stat_at`, `readlink_at`,
//!   `create_directory_at`, `remove_directory_at`, `unlink_file_at`,
//!   `rename_at`, `link_at`, `symlink_at`, `metadata_hash_at`,
//!   `set_times_at`) resolve the parent fd's host path, join the
//!   guest-supplied relative path, canonicalise, and consult the matcher.
//!   Deny → `ErrorCode::NotPermitted`; allow → delegate and (for `open_at`)
//!   record the resulting fd's host path.
//!
//! fd→path tracking:
//! - Preopens are recorded at construction (we know their host paths from
//!   `derive_preopens` before calling `WasiCtxBuilder::preopened_dir`).
//!   Their Resource reps aren't known at that point; we match reps to host
//!   paths lazily the first time `get_directories()` is called.
//! - New descriptors produced by `open_at` are recorded with the
//!   canonicalised child path.

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

use path_clean::PathClean;
use wasmtime::component::{HasData, Resource, ResourceTable};
use wasmtime_wasi::filesystem::{WasiFilesystemCtx, WasiFilesystemCtxView};
use wasmtime_wasi::p2::bindings::filesystem::preopens;
use wasmtime_wasi::p2::bindings::filesystem::types::{
    self, ErrorCode, HostDescriptor, HostDirectoryEntryStream,
};
use wasmtime_wasi::p2::{DynInputStream, DynOutputStream, FsError, FsResult};

use act_types::{Capabilities, MountType};

use act_policy::Decision;
use act_policy::consent::{ConsentAsk, ConsentPrompter, DecisionCache};
use act_policy::fs_matcher::FsAccess;
use act_policy::grant::PolicyMode;
use act_policy::provider::{CompiledCeiling, ResourceOp};

use crate::audit::{CapDecisionRecord, Decision4, emit_cap_decision};

// ── Mounts → preopens ─────────────────────────────────────────────────────

/// A (guest path → host path) pair handed to wasmtime-wasi's `preopened_dir`.
///
/// Preopens are derived from the component's resolved mounts (see
/// `resolve_mounts`): a `bind` mount preopens one host dir at its guest path,
/// a `root` mount preopens the platform root(s). A component that declares
/// only `bind` mounts sees ONLY those dirs (sandbox); the `FsMatcher` still
/// gates per-op access on the host paths within them.
#[derive(Debug, Clone, PartialEq)]
pub struct Preopen {
    pub guest: String,
    pub host: PathBuf,
}

/// A resolved mount: concrete guest path + (for binds) an expanded host dir.
#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedMount {
    pub kind: MountType,
    pub guest: String,
    /// Expanded host directory for `bind`; `None` for `root`.
    pub host: Option<PathBuf>,
}

/// Resolve a component's declared mounts into concrete topology.
///
/// Order: explicit `params.mounts`, then `mount-root` sugar (a `root` mount,
/// skipped if an explicit `root` mount already exists), then a default `root`
/// mount when nothing else is declared. Returns empty under `Deny` (the guest
/// can name nothing).
pub fn resolve_mounts(caps: &Capabilities, mode: PolicyMode) -> Vec<ResolvedMount> {
    if mode == PolicyMode::Deny {
        return Vec::new();
    }
    let declared = caps.fs_mounts().unwrap_or_else(|e| {
        tracing::warn!(error = %e, "ignoring malformed wasi:filesystem mounts");
        Vec::new()
    });
    let has_explicit_root = declared.iter().any(|m| m.kind == MountType::Root);

    let mut out = Vec::new();
    for m in &declared {
        match m.kind {
            MountType::Bind => {
                if let (Some(g), Some(h)) = (m.guest.as_deref(), m.host.as_deref()) {
                    out.push(ResolvedMount {
                        kind: MountType::Bind,
                        guest: g.to_string(),
                        host: Some(expand_host_dir(h)),
                    });
                }
            }
            MountType::Root => out.push(ResolvedMount {
                kind: MountType::Root,
                guest: m.guest.as_deref().unwrap_or("/").to_string(),
                host: None,
            }),
        }
    }

    // mount-root sugar → a root mount. "/" and "" are treated as no-ops (NOT a
    // whole-fs root): a degenerate mount-root must never silently expose the
    // entire host filesystem next to declared binds. Use an explicit
    // `{type = "root"}` mount to combine whole-fs with binds.
    if !has_explicit_root
        && let Some(mr) = caps.fs_mount_root()
        && mr != "/"
        && !mr.is_empty()
    {
        out.push(ResolvedMount {
            kind: MountType::Root,
            guest: mr.to_string(),
            host: None,
        });
    }

    if out.is_empty() {
        out.push(ResolvedMount {
            kind: MountType::Root,
            guest: "/".to_string(),
            host: None,
        });
    }
    out
}

/// Expand `~` and make a host directory path absolute (no glob handling — this
/// is a directory, not a matcher pattern).
fn expand_host_dir(s: &str) -> PathBuf {
    let expanded = shellexpand::tilde(s).into_owned();
    let p = PathBuf::from(&expanded);
    if p.is_absolute() {
        p
    } else {
        std::env::current_dir().map(|c| c.join(&p)).unwrap_or(p)
    }
}

/// Build the preopen list from resolved mounts.
pub fn derive_preopens(mounts: &[ResolvedMount]) -> Vec<Preopen> {
    let mut out = Vec::new();
    for m in mounts {
        match m.kind {
            MountType::Bind => {
                if let Some(host) = &m.host {
                    out.push(Preopen {
                        guest: m.guest.clone(),
                        host: host.clone(),
                    });
                }
            }
            MountType::Root => out.extend(root_preopens_under(&m.guest)),
        }
    }
    out
}

/// Create missing `bind` host directories so they can be preopened. `root`
/// mounts point at the platform root and create nothing.
pub fn create_mount_dirs(mounts: &[ResolvedMount]) -> std::io::Result<()> {
    for m in mounts {
        if m.kind == MountType::Bind
            && let Some(host) = &m.host
        {
            std::fs::create_dir_all(host)?;
        }
    }
    Ok(())
}

#[cfg(unix)]
fn root_preopens_under(guest: &str) -> Vec<Preopen> {
    vec![Preopen {
        guest: guest.to_string(),
        host: PathBuf::from("/"),
    }]
}

#[cfg(windows)]
fn root_preopens_under(guest: &str) -> Vec<Preopen> {
    let base = guest.trim_end_matches('/');
    let mut out = Vec::new();
    for letter in b'A'..=b'Z' {
        let c = letter as char;
        let host = PathBuf::from(format!("{}:\\", c));
        // metadata trips DriveNotReady / access errors for absent drives;
        // treat any failure as "skip this letter".
        if std::fs::metadata(&host).is_ok() {
            let g = if base.is_empty() {
                format!("/{}", c.to_ascii_lowercase())
            } else {
                format!("{}/{}", base, c.to_ascii_lowercase())
            };
            out.push(Preopen { guest: g, host });
        }
    }
    out
}

#[cfg(not(any(unix, windows)))]
fn root_preopens_under(guest: &str) -> Vec<Preopen> {
    vec![Preopen {
        guest: guest.to_string(),
        host: PathBuf::from("/"),
    }]
}

// ── Wasmtime host impl ────────────────────────────────────────────────────

/// `HasData` marker for our policy-aware filesystem view.
pub struct PolicyFilesystem;

impl HasData for PolicyFilesystem {
    type Data<'a> = PolicyFilesystemCtxView<'a>;
}

/// Per-call view bundling all state the policy wrapper needs.
pub struct PolicyFilesystemCtxView<'a> {
    pub ctx: &'a mut WasiFilesystemCtx,
    pub table: &'a mut ResourceTable,
    pub ceiling: &'a Arc<dyn CompiledCeiling>,
    pub fd_paths: &'a mut FdPathMap,
    /// Configured mode; drives the p3 preopens kill-switch. p3 path-taking
    /// ops can't be gated (upstream `Dir::open_at` is `pub(crate)`), so when
    /// mode is anything but `Open` we return zero preopens from p3 and p3
    /// guests can't acquire a `Descriptor::Dir` handle at all.
    pub mode: PolicyMode,
    /// Interactive-consent prompter, consulted when the ceiling returns
    /// `Decision::Ask`. Shared across the store.
    pub prompter: Arc<dyn ConsentPrompter>,
    /// Per-session memory of ask decisions, keyed by `(cap-id, path)`.
    pub cache: Arc<DecisionCache>,
}

/// Tracks the host path associated with each open filesystem descriptor,
/// plus the configured preopen list (guest path → host path) used to fill
/// in the map lazily the first time the guest calls `get-directories`.
#[derive(Default, Debug)]
pub struct FdPathMap {
    pub preopens: Vec<(String, PathBuf)>,
    pub by_rep: HashMap<u32, PathBuf>,
}

/// Sync matcher outcome for one path op. `Deny` is folded into the `Err` arm
/// of `check_path_sync`; `Ask` carries owned `Arc` clones so the async prompt
/// resolution never borrows the (`!Sync`) view.
enum PathDecision {
    Allow(PathBuf),
    Ask {
        canonical: PathBuf,
        cache: Arc<DecisionCache>,
        prompter: Arc<dyn ConsentPrompter>,
    },
}

/// Resolve an `Ask`-mode filesystem decision via the interactive prompter
/// (cached per canonical path). Free function over owned data so the returned
/// future is `Send` (it captures only `Arc`s + a `PathBuf`, never the view).
async fn resolve_ask(
    cache: Arc<DecisionCache>,
    prompter: Arc<dyn ConsentPrompter>,
    canonical: PathBuf,
) -> FsResult<PathBuf> {
    let path = canonical.display().to_string();
    let has_channel = prompter.has_channel();
    let allowed = cache
        .decide_cached(
            &*prompter,
            ConsentAsk {
                cap_id: act_types::constants::CAP_FILESYSTEM.to_string(),
                key: path.clone(),
                summary: format!("filesystem access: {path}"),
            },
        )
        .await;
    emit_cap_decision(&CapDecisionRecord::answered(
        act_types::constants::CAP_FILESYSTEM,
        &path,
        allowed,
        has_channel,
    ));
    if allowed {
        Ok(canonical)
    } else {
        Err(ErrorCode::NotPermitted.into())
    }
}

impl PolicyFilesystemCtxView<'_> {
    fn inner(&mut self) -> WasiFilesystemCtxView<'_> {
        WasiFilesystemCtxView {
            ctx: self.ctx,
            table: self.table,
        }
    }

    fn parent_path(&self, fd: &Resource<types::Descriptor>) -> Option<PathBuf> {
        self.fd_paths.by_rep.get(&fd.rep()).cloned()
    }

    /// Resolve `(parent_fd, rel_path)` to an absolute canonical host path and
    /// run it through the matcher. Returns `Ok(canonical)` on allow,
    /// `Err(NotPermitted)` on deny. In `Ask` mode the matcher defers and we
    /// resolve the verdict through the interactive consent prompter (cached
    /// per path). Records the resolved path for the caller to associate with a
    /// newly-opened fd if desired.
    ///
    /// This is the async entry point used by every path-taking method. It must
    /// NOT hold a borrow of `self` across the `.await` (the host descriptor
    /// futures must be `Send`, and `&PolicyFilesystemCtxView` is not `Sync`),
    /// so it is a *sync* fn that performs the matcher decision (borrowing
    /// `self`) and then returns a `Send` future that captures only owned data
    /// (`Arc` clones + the path) — never `self`.
    fn check_path(
        &self,
        parent_fd: &Resource<types::Descriptor>,
        rel: &str,
        access: FsAccess,
    ) -> impl Future<Output = FsResult<PathBuf>> + Send + 'static {
        let decision = self.check_path_sync(parent_fd, rel, access);
        async move {
            match decision? {
                PathDecision::Allow(canonical) => Ok(canonical),
                PathDecision::Ask {
                    canonical,
                    cache,
                    prompter,
                } => resolve_ask(cache, prompter, canonical).await,
            }
        }
    }

    /// Synchronous part of `check_path`: resolve + matcher decision. Borrows
    /// `self` but never awaits, so the borrow ends before `check_path`'s await.
    fn check_path_sync(
        &self,
        parent_fd: &Resource<types::Descriptor>,
        rel: &str,
        access: FsAccess,
    ) -> FsResult<PathDecision> {
        let Some(parent) = self.parent_path(parent_fd) else {
            // Parent fd has no tracked path — belongs to an unknown preopen
            // or was never witnessed. Deny conservatively.
            tracing::warn!(fd = parent_fd.rep(), "fs policy: untracked parent fd");
            return Err(ErrorCode::NotPermitted.into());
        };
        let canonical = parent.join(rel).clean();
        let op = ResourceOp {
            cap_id: act_types::constants::CAP_FILESYSTEM.to_string(),
            key: canonical.display().to_string(),
            action: if access == FsAccess::Write {
                "write".to_string()
            } else {
                "read".to_string()
            },
            attrs: serde_json::Value::Null,
        };
        let explained = self.ceiling.classify_explained(&op);
        let mode = self.ceiling.effective_mode().to_string();
        match explained.decision {
            Decision::Allow => {
                emit_cap_decision(&CapDecisionRecord::statik(
                    act_types::constants::CAP_FILESYSTEM,
                    &op.key,
                    &op.action,
                    Decision4::Allow,
                    &mode,
                    explained.rule,
                ));
                Ok(PathDecision::Allow(canonical))
            }
            Decision::Deny => {
                emit_cap_decision(&CapDecisionRecord::statik(
                    act_types::constants::CAP_FILESYSTEM,
                    &op.key,
                    &op.action,
                    Decision4::Deny,
                    &mode,
                    explained.rule,
                ));
                Err(ErrorCode::NotPermitted.into())
            }
            // Deliberately silent: `ask` has not resolved yet. The record is
            // emitted in `resolve_ask` once the verdict exists.
            Decision::Ask => Ok(PathDecision::Ask {
                canonical,
                cache: self.cache.clone(),
                prompter: self.prompter.clone(),
            }),
        }
    }

    /// Called from `get_directories` on first use to align Resource reps with
    /// the host paths we configured at preopen time.
    fn populate_preopens(&mut self, entries: &[(Resource<types::Descriptor>, String)]) {
        for (res, guest_path) in entries {
            if self.fd_paths.by_rep.contains_key(&res.rep()) {
                continue;
            }
            let Some(host) = self
                .fd_paths
                .preopens
                .iter()
                .find(|(g, _)| g == guest_path)
                .map(|(_, h)| h.clone())
            else {
                continue;
            };
            self.fd_paths.by_rep.insert(res.rep(), host);
        }
    }
}

// ── preopens::Host ────────────────────────────────────────────────────────

impl preopens::Host for PolicyFilesystemCtxView<'_> {
    fn get_directories(&mut self) -> wasmtime::Result<Vec<(Resource<types::Descriptor>, String)>> {
        let entries = self.inner().get_directories()?;
        self.populate_preopens(&entries);
        Ok(entries)
    }
}

// ── types::Host ───────────────────────────────────────────────────────────

impl types::Host for PolicyFilesystemCtxView<'_> {
    fn convert_error_code(&mut self, err: FsError) -> wasmtime::Result<ErrorCode> {
        self.inner().convert_error_code(err)
    }
    fn filesystem_error_code(
        &mut self,
        err: Resource<wasmtime::Error>,
    ) -> wasmtime::Result<Option<ErrorCode>> {
        self.inner().filesystem_error_code(err)
    }
}

// ── HostDescriptor ────────────────────────────────────────────────────────
//
// Every method delegates to `self.inner()` after a policy check on
// path-taking methods. Non-path-taking methods operate on an already-opened
// Resource<Descriptor>; access was granted at open_at time so no further
// check is needed.

impl HostDescriptor for PolicyFilesystemCtxView<'_> {
    async fn advise(
        &mut self,
        fd: Resource<types::Descriptor>,
        offset: types::Filesize,
        len: types::Filesize,
        advice: types::Advice,
    ) -> FsResult<()> {
        self.inner().advise(fd, offset, len, advice).await
    }

    async fn sync_data(&mut self, fd: Resource<types::Descriptor>) -> FsResult<()> {
        self.inner().sync_data(fd).await
    }

    async fn get_flags(
        &mut self,
        fd: Resource<types::Descriptor>,
    ) -> FsResult<types::DescriptorFlags> {
        self.inner().get_flags(fd).await
    }

    async fn get_type(
        &mut self,
        fd: Resource<types::Descriptor>,
    ) -> FsResult<types::DescriptorType> {
        self.inner().get_type(fd).await
    }

    async fn set_size(
        &mut self,
        fd: Resource<types::Descriptor>,
        size: types::Filesize,
    ) -> FsResult<()> {
        self.inner().set_size(fd, size).await
    }

    async fn set_times(
        &mut self,
        fd: Resource<types::Descriptor>,
        atim: types::NewTimestamp,
        mtim: types::NewTimestamp,
    ) -> FsResult<()> {
        self.inner().set_times(fd, atim, mtim).await
    }

    async fn read(
        &mut self,
        fd: Resource<types::Descriptor>,
        len: types::Filesize,
        offset: types::Filesize,
    ) -> FsResult<(Vec<u8>, bool)> {
        self.inner().read(fd, len, offset).await
    }

    async fn write(
        &mut self,
        fd: Resource<types::Descriptor>,
        buf: Vec<u8>,
        offset: types::Filesize,
    ) -> FsResult<types::Filesize> {
        self.inner().write(fd, buf, offset).await
    }

    async fn read_directory(
        &mut self,
        fd: Resource<types::Descriptor>,
    ) -> FsResult<Resource<types::DirectoryEntryStream>> {
        self.inner().read_directory(fd).await
    }

    async fn sync(&mut self, fd: Resource<types::Descriptor>) -> FsResult<()> {
        self.inner().sync(fd).await
    }

    async fn create_directory_at(
        &mut self,
        fd: Resource<types::Descriptor>,
        path: String,
    ) -> FsResult<()> {
        let _checked = self.check_path(&fd, &path, FsAccess::Write).await?;
        self.inner().create_directory_at(fd, path).await
    }

    async fn stat(&mut self, fd: Resource<types::Descriptor>) -> FsResult<types::DescriptorStat> {
        self.inner().stat(fd).await
    }

    async fn stat_at(
        &mut self,
        fd: Resource<types::Descriptor>,
        path_flags: types::PathFlags,
        path: String,
    ) -> FsResult<types::DescriptorStat> {
        let _checked = self.check_path(&fd, &path, FsAccess::Read).await?;
        self.inner().stat_at(fd, path_flags, path).await
    }

    async fn set_times_at(
        &mut self,
        fd: Resource<types::Descriptor>,
        path_flags: types::PathFlags,
        path: String,
        atim: types::NewTimestamp,
        mtim: types::NewTimestamp,
    ) -> FsResult<()> {
        let _checked = self.check_path(&fd, &path, FsAccess::Write).await?;
        self.inner()
            .set_times_at(fd, path_flags, path, atim, mtim)
            .await
    }

    async fn link_at(
        &mut self,
        fd: Resource<types::Descriptor>,
        old_path_flags: types::PathFlags,
        old_path: String,
        new_descriptor: Resource<types::Descriptor>,
        new_path: String,
    ) -> FsResult<()> {
        let _old = self.check_path(&fd, &old_path, FsAccess::Read).await?;
        let _new = self
            .check_path(&new_descriptor, &new_path, FsAccess::Write)
            .await?;
        self.inner()
            .link_at(fd, old_path_flags, old_path, new_descriptor, new_path)
            .await
    }

    async fn open_at(
        &mut self,
        fd: Resource<types::Descriptor>,
        path_flags: types::PathFlags,
        path: String,
        oflags: types::OpenFlags,
        flags: types::DescriptorFlags,
    ) -> FsResult<Resource<types::Descriptor>> {
        let access = if flags.contains(types::DescriptorFlags::WRITE)
            || flags.contains(types::DescriptorFlags::MUTATE_DIRECTORY)
            || oflags.contains(types::OpenFlags::CREATE)
            || oflags.contains(types::OpenFlags::TRUNCATE)
            || oflags.contains(types::OpenFlags::EXCLUSIVE)
        {
            FsAccess::Write
        } else {
            FsAccess::Read
        };
        let canonical = self.check_path(&fd, &path, access).await?;
        let new_fd = self
            .inner()
            .open_at(fd, path_flags, path, oflags, flags)
            .await?;
        self.fd_paths.by_rep.insert(new_fd.rep(), canonical);
        Ok(new_fd)
    }

    fn drop(&mut self, fd: Resource<types::Descriptor>) -> wasmtime::Result<()> {
        self.fd_paths.by_rep.remove(&fd.rep());
        HostDescriptor::drop(&mut self.inner(), fd)
    }

    async fn readlink_at(
        &mut self,
        fd: Resource<types::Descriptor>,
        path: String,
    ) -> FsResult<String> {
        let _checked = self.check_path(&fd, &path, FsAccess::Read).await?;
        self.inner().readlink_at(fd, path).await
    }

    async fn remove_directory_at(
        &mut self,
        fd: Resource<types::Descriptor>,
        path: String,
    ) -> FsResult<()> {
        let _checked = self.check_path(&fd, &path, FsAccess::Write).await?;
        self.inner().remove_directory_at(fd, path).await
    }

    async fn rename_at(
        &mut self,
        fd: Resource<types::Descriptor>,
        old_path: String,
        new_fd: Resource<types::Descriptor>,
        new_path: String,
    ) -> FsResult<()> {
        let _old = self.check_path(&fd, &old_path, FsAccess::Write).await?;
        let _new = self.check_path(&new_fd, &new_path, FsAccess::Write).await?;
        self.inner().rename_at(fd, old_path, new_fd, new_path).await
    }

    async fn symlink_at(
        &mut self,
        fd: Resource<types::Descriptor>,
        src_path: String,
        dest_path: String,
    ) -> FsResult<()> {
        let _checked = self.check_path(&fd, &dest_path, FsAccess::Write).await?;
        self.inner().symlink_at(fd, src_path, dest_path).await
    }

    async fn unlink_file_at(
        &mut self,
        fd: Resource<types::Descriptor>,
        path: String,
    ) -> FsResult<()> {
        let _checked = self.check_path(&fd, &path, FsAccess::Write).await?;
        self.inner().unlink_file_at(fd, path).await
    }

    fn read_via_stream(
        &mut self,
        fd: Resource<types::Descriptor>,
        offset: types::Filesize,
    ) -> FsResult<Resource<DynInputStream>> {
        self.inner().read_via_stream(fd, offset)
    }

    fn write_via_stream(
        &mut self,
        fd: Resource<types::Descriptor>,
        offset: types::Filesize,
    ) -> FsResult<Resource<DynOutputStream>> {
        self.inner().write_via_stream(fd, offset)
    }

    fn append_via_stream(
        &mut self,
        fd: Resource<types::Descriptor>,
    ) -> FsResult<Resource<DynOutputStream>> {
        self.inner().append_via_stream(fd)
    }

    async fn is_same_object(
        &mut self,
        a: Resource<types::Descriptor>,
        b: Resource<types::Descriptor>,
    ) -> wasmtime::Result<bool> {
        self.inner().is_same_object(a, b).await
    }

    async fn metadata_hash(
        &mut self,
        fd: Resource<types::Descriptor>,
    ) -> FsResult<types::MetadataHashValue> {
        self.inner().metadata_hash(fd).await
    }

    async fn metadata_hash_at(
        &mut self,
        fd: Resource<types::Descriptor>,
        path_flags: types::PathFlags,
        path: String,
    ) -> FsResult<types::MetadataHashValue> {
        let _checked = self.check_path(&fd, &path, FsAccess::Read).await?;
        self.inner().metadata_hash_at(fd, path_flags, path).await
    }
}

// ── p3 preopens kill-switch ───────────────────────────────────────────────
//
// We can't mirror the full p2 matcher on p3 because `Dir::open_at` and
// friends are `pub(crate)` in wasmtime-wasi — shadowing `HostDescriptorWithStore`
// would need to reproject the Accessor via a `U: WasiFilesystemView` bound
// that the trait doesn't permit, and the sibling methods we'd need to call
// directly (`dir.open_at`, `dir.as_dir`) are gated.
//
// Instead we gate at preopens: if fs mode is anything other than `Open`,
// p3 `get_directories` returns an empty vec. A p3 guest with an empty
// preopen list can't construct a `Descriptor::Dir` resource, so every
// p3 path op fails before it reaches cap-std. Components that genuinely
// need p3 filesystem access must run under `policy.filesystem = "open"`.

impl wasmtime_wasi::p3::bindings::filesystem::preopens::Host for PolicyFilesystemCtxView<'_> {
    fn get_directories(
        &mut self,
    ) -> wasmtime::Result<
        Vec<(
            Resource<wasmtime_wasi::p3::bindings::filesystem::types::Descriptor>,
            String,
        )>,
    > {
        if self.mode != PolicyMode::Open {
            tracing::warn!(
                mode = ?self.mode,
                "p3 wasi:filesystem/preopens: returning empty; p3 path ops can't be matcher-gated",
            );
            return Ok(vec![]);
        }
        let mut inner = WasiFilesystemCtxView {
            ctx: self.ctx,
            table: self.table,
        };
        <WasiFilesystemCtxView as wasmtime_wasi::p3::bindings::filesystem::preopens::Host>::get_directories(&mut inner)
    }
}

// ── HostDirectoryEntryStream ──────────────────────────────────────────────

impl HostDirectoryEntryStream for PolicyFilesystemCtxView<'_> {
    async fn read_directory_entry(
        &mut self,
        stream: Resource<types::DirectoryEntryStream>,
    ) -> FsResult<Option<types::DirectoryEntry>> {
        self.inner().read_directory_entry(stream).await
    }

    fn drop(&mut self, stream: Resource<types::DirectoryEntryStream>) -> wasmtime::Result<()> {
        HostDirectoryEntryStream::drop(&mut self.inner(), stream)
    }
}

#[cfg(test)]
mod mount_tests {
    use super::*;
    use act_policy::grant::PolicyMode;
    use act_types::{Capabilities, CapabilityRequest, MountType};
    use std::collections::BTreeMap;

    fn caps_with_mounts(mounts: serde_json::Value) -> Capabilities {
        let mut caps = Capabilities::default();
        let mut params = BTreeMap::new();
        params.insert("mounts".to_string(), mounts);
        caps.0.insert(
            "wasi:filesystem".into(),
            CapabilityRequest {
                params,
                ..Default::default()
            },
        );
        caps
    }

    #[test]
    fn deny_mode_yields_no_mounts() {
        let caps = caps_with_mounts(serde_json::json!([{ "guest": "/ows", "host": "/tmp/x" }]));
        assert!(resolve_mounts(&caps, PolicyMode::Deny).is_empty());
    }

    #[test]
    fn bind_only_component_gets_just_the_bind_preopen() {
        let caps = caps_with_mounts(serde_json::json!([{ "guest": "/ows", "host": "/tmp/x" }]));
        let mounts = resolve_mounts(&caps, PolicyMode::Ask);
        let pre = derive_preopens(&mounts);
        assert_eq!(pre.len(), 1);
        assert_eq!(pre[0].guest, "/ows");
        assert_eq!(pre[0].host, std::path::PathBuf::from("/tmp/x"));
    }

    #[test]
    fn no_mounts_declared_defaults_to_root() {
        let caps = Capabilities::default();
        let mounts = resolve_mounts(&caps, PolicyMode::Allowlist);
        assert_eq!(mounts.len(), 1);
        assert_eq!(mounts[0].kind, MountType::Root);
        assert_eq!(mounts[0].guest, "/");
    }

    #[cfg(unix)]
    #[test]
    fn root_mount_preopens_the_filesystem_root() {
        let caps = caps_with_mounts(serde_json::json!([{ "type": "root", "guest": "/" }]));
        let pre = derive_preopens(&resolve_mounts(&caps, PolicyMode::Open));
        assert_eq!(pre.len(), 1);
        assert_eq!(pre[0].guest, "/");
        assert_eq!(pre[0].host, std::path::PathBuf::from("/"));
    }

    #[test]
    fn mount_root_sugar_becomes_a_root_mount() {
        let mut caps = Capabilities::default();
        let mut params = BTreeMap::new();
        params.insert("mount-root".to_string(), serde_json::json!("/data"));
        caps.0.insert(
            "wasi:filesystem".into(),
            CapabilityRequest {
                params,
                ..Default::default()
            },
        );
        let mounts = resolve_mounts(&caps, PolicyMode::Allowlist);
        assert_eq!(mounts.len(), 1);
        assert_eq!(mounts[0].kind, MountType::Root);
        assert_eq!(mounts[0].guest, "/data");
    }

    #[test]
    fn mount_root_slash_is_noop_with_binds() {
        // A degenerate `mount-root = "/"` alongside binds must NOT silently add a
        // whole-fs root mount — the guest gets only the declared bind.
        let mut caps = Capabilities::default();
        let mut params = BTreeMap::new();
        params.insert(
            "mounts".to_string(),
            serde_json::json!([{ "guest": "/ows", "host": "/tmp/x" }]),
        );
        params.insert("mount-root".to_string(), serde_json::json!("/"));
        caps.0.insert(
            "wasi:filesystem".into(),
            CapabilityRequest {
                params,
                ..Default::default()
            },
        );
        let mounts = resolve_mounts(&caps, PolicyMode::Ask);
        assert_eq!(mounts.len(), 1);
        assert_eq!(mounts[0].kind, MountType::Bind);
        assert_eq!(mounts[0].guest, "/ows");
    }

    #[test]
    fn explicit_root_suppresses_mount_root_sugar() {
        // An explicit `{type = "root"}` mount suppresses the mount-root sugar
        // entirely — `/data` is NOT added.
        let mut caps = Capabilities::default();
        let mut params = BTreeMap::new();
        params.insert(
            "mounts".to_string(),
            serde_json::json!([{ "type": "root", "guest": "/x" }]),
        );
        params.insert("mount-root".to_string(), serde_json::json!("/data"));
        caps.0.insert(
            "wasi:filesystem".into(),
            CapabilityRequest {
                params,
                ..Default::default()
            },
        );
        let mounts = resolve_mounts(&caps, PolicyMode::Allowlist);
        assert_eq!(mounts.len(), 1);
        assert_eq!(mounts[0].kind, MountType::Root);
        assert_eq!(mounts[0].guest, "/x");
    }

    #[test]
    fn tilde_in_bind_host_is_expanded() {
        let caps = caps_with_mounts(serde_json::json!([{ "guest": "/ows", "host": "~/.ows" }]));
        let mounts = resolve_mounts(&caps, PolicyMode::Ask);
        let host = mounts[0].host.clone().unwrap();
        assert!(host.is_absolute());
        assert!(!host.to_string_lossy().starts_with('~'));
    }

    #[test]
    fn create_mount_dirs_makes_bind_targets() {
        let tmp = std::env::temp_dir().join(format!("act-mount-test-{}", std::process::id()));
        let target = tmp.join("nested");
        let mounts = vec![ResolvedMount {
            kind: MountType::Bind,
            guest: "/d".into(),
            host: Some(target.clone()),
        }];
        create_mount_dirs(&mounts).unwrap();
        assert!(target.is_dir());
        std::fs::remove_dir_all(&tmp).ok();
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn fs_records_carry_the_matched_rule_and_a_reason_on_deny() {
        // Pure record construction — no wasmtime store needed.
        let allow = crate::audit::CapDecisionRecord::statik(
            act_types::constants::CAP_FILESYSTEM,
            "/data/app.db",
            "read",
            crate::audit::Decision4::Allow,
            "allowlist",
            Some("/data/**".into()),
        );
        assert_eq!(allow.cap_id, act_types::constants::CAP_FILESYSTEM);
        assert_eq!(allow.rule.as_deref(), Some("/data/**"));
        assert!(allow.reason.is_none());

        let deny = crate::audit::CapDecisionRecord::statik(
            act_types::constants::CAP_FILESYSTEM,
            "/etc/passwd",
            "read",
            crate::audit::Decision4::Deny,
            "allowlist",
            None,
        );
        assert_eq!(deny.reason.as_deref(), Some("outside ceiling"));
        assert_eq!(deny.actor, crate::audit::record::Actor::Static);
    }

    #[test]
    fn ask_resolution_attributes_the_decision_to_the_user() {
        let r = crate::audit::CapDecisionRecord::answered(
            act_types::constants::CAP_FILESYSTEM,
            "/home/u/.ssh/id_ed25519",
            false,
            true,
        );
        assert_eq!(r.decision, crate::audit::Decision4::AskDeny);
        assert_eq!(r.actor, crate::audit::record::Actor::User);
        assert_eq!(r.reason.as_deref(), Some("denied by user"));

        let r = crate::audit::CapDecisionRecord::answered(
            act_types::constants::CAP_FILESYSTEM,
            "/home/u/notes.txt",
            true,
            true,
        );
        assert_eq!(r.decision, crate::audit::Decision4::AskAllow);
        assert_eq!(r.actor, crate::audit::record::Actor::User);
    }

    #[test]
    fn ask_resolution_with_no_channel_is_not_attributed_to_the_user() {
        // M1: `resolve_ask` is called with a `DenyPrompter` in exactly this
        // shape whenever a headless run has no interactive channel — see
        // `fs_ask_resolution_reaches_the_audit_trail` in `audit_cli.rs` for
        // the end-to-end version. Pinned here too, at the constructor, since
        // this is the record `resolve_ask` actually builds.
        let r = crate::audit::CapDecisionRecord::answered(
            act_types::constants::CAP_FILESYSTEM,
            "/home/u/.ssh/id_ed25519",
            false,
            false,
        );
        assert_eq!(r.decision, crate::audit::Decision4::AskDeny);
        assert_ne!(r.actor, crate::audit::record::Actor::User);
        assert_eq!(r.reason.as_deref(), Some("no prompt channel"));
    }
}

#[cfg(test)]
mod policy_tests {
    use act_policy::Decision;
    use act_policy::fs_matcher::{FsAccess, FsMatcher};
    use act_policy::grant::{FsAllow, FsConfig, PolicyMode};
    use act_types::FsMode;
    use std::path::Path;

    #[test]
    fn ro_matcher_blocks_write_allows_read() {
        let cfg = FsConfig {
            mode: PolicyMode::Allowlist,
            allow: vec![FsAllow {
                glob: "/data/**".into(),
                mode: FsMode::Ro,
            }],
            deny: vec![],
        };
        let matcher = FsMatcher::compile(&cfg).unwrap();
        assert_eq!(
            matcher.decide(Path::new("/data/x.db"), FsAccess::Read),
            Decision::Allow
        );
        assert_eq!(
            matcher.decide(Path::new("/data/x.db"), FsAccess::Write),
            Decision::Deny
        );
    }
}