Skip to main content

merry_runtime/
live_policy.rs

1//! Atomic single-lock live policy baseline and per-session evaluation handle.
2//!
3//! `LivePolicyHandle` replaces the previously separate `RwLock`s for workspace
4//! filesystem access, network/domain admission, sandbox mode, and protected
5//! product paths with a single atomic `Arc<LivePolicyBaseline>` swap.
6//!
7//! Child subagent sessions derive from their parent handle via
8//! [`LivePolicyHandle::for_child`]: they share the parent's live baseline lock
9//! (tracking sandbox/config/workspace-permission reloads automatically) while
10//! evaluating session-scoped grants strictly against their own
11//! [`ProcessSessionPermissionView`] and pre-resolved child overrides.
12
13use crate::{
14    NetworkAccessDecision, NetworkAccessPolicy, PathAccess, PathAccessDecision, PathAccessRule,
15    PathDenialReason, PathEvaluation, ProcessSessionPermissionSnapshot,
16    ProcessSessionPermissionView, WorkspaceAccessPolicy,
17    access_policy::{ResolvedPathRule, resolve_rule_path},
18    is_protected_in_unrestricted_mode,
19};
20use std::{
21    path::{Path, PathBuf},
22    sync::{Arc, RwLock},
23};
24
25/// Immutable point-in-time policy baseline shared atomically across file tools,
26/// web/browser tools, host-process backends, and child sessions.
27#[derive(Debug, Clone)]
28pub struct LivePolicyBaseline {
29    restricted: bool,
30    workspace_access: Option<WorkspaceAccessPolicy>,
31    product_private_paths: Vec<PathBuf>,
32    network_access: NetworkAccessPolicy,
33}
34
35impl LivePolicyBaseline {
36    /// Constructs a new immutable policy baseline.
37    #[must_use]
38    pub fn new(
39        restricted: bool,
40        workspace_access: Option<WorkspaceAccessPolicy>,
41        product_private_paths: Vec<PathBuf>,
42        network_access: NetworkAccessPolicy,
43    ) -> Self {
44        Self {
45            restricted,
46            workspace_access,
47            product_private_paths,
48            network_access,
49        }
50    }
51
52    /// Returns whether workspace sandbox restrictions are active (`--sandbox workspace`).
53    #[must_use]
54    pub const fn is_restricted(&self) -> bool {
55        self.restricted
56    }
57
58    /// Returns the workspace access policy active under `--sandbox workspace`,
59    /// or `None` under `--sandbox off`.
60    #[must_use]
61    pub fn workspace_access(&self) -> Option<&WorkspaceAccessPolicy> {
62        self.workspace_access.as_ref()
63    }
64
65    /// Returns built-in Merry protected credential paths (`providers/`,
66    /// `MERRY_API_KEY_FILE`) guarded by approval even in `--sandbox off`.
67    #[must_use]
68    pub fn product_private_paths(&self) -> &[PathBuf] {
69        &self.product_private_paths
70    }
71
72    /// Returns the outbound network and domain policy baseline.
73    #[must_use]
74    pub fn network_access(&self) -> &NetworkAccessPolicy {
75        &self.network_access
76    }
77}
78
79/// Child-session workspace overrides layered purely on top of the parent's
80/// live baseline without disconnecting live reload propagation.
81#[derive(Debug, Clone)]
82pub struct ChildWorkspacePolicyOverride {
83    workspace_root_canonical: Option<PathBuf>,
84    workspace_writable: bool,
85    extra_resolved_rules: Vec<ResolvedPathRule>,
86}
87
88impl ChildWorkspacePolicyOverride {
89    /// Creates a child override intersecting `workspace_writable`.
90    #[must_use]
91    pub fn new(workspace_writable: bool) -> Self {
92        Self {
93            workspace_root_canonical: None,
94            workspace_writable,
95            extra_resolved_rules: Vec::new(),
96        }
97    }
98
99    /// Overrides the effective workspace root (used by worktree-isolated subagents),
100    /// canonicalizing the root path once up front.
101    #[must_use]
102    pub fn with_workspace_root(mut self, root: impl Into<PathBuf>) -> Self {
103        self.workspace_root_canonical = Some(resolve_rule_path(&root.into()));
104        self
105    }
106
107    /// Appends child-specific static path rules (such as worktree `.git` baseline
108    /// rules), canonicalizing each path once up front.
109    #[must_use]
110    pub fn with_extra_path_rules(
111        mut self,
112        rules: impl IntoIterator<Item = PathAccessRule>,
113    ) -> Self {
114        self.extra_resolved_rules = rules
115            .into_iter()
116            .map(|rule| ResolvedPathRule::from_rule(&rule))
117            .collect();
118        self
119    }
120
121    #[must_use]
122    pub(crate) fn workspace_root_canonical(&self) -> Option<&Path> {
123        self.workspace_root_canonical.as_deref()
124    }
125
126    /// Returns whether the child session is permitted to write to its workspace.
127    #[must_use]
128    pub const fn workspace_writable(&self) -> bool {
129        self.workspace_writable
130    }
131
132    #[must_use]
133    pub(crate) fn extra_resolved_rules(&self) -> &[ResolvedPathRule] {
134        &self.extra_resolved_rules
135    }
136}
137
138/// Single-lock live policy handle coordinating filesystem, network, sandbox
139/// mode, and protected-path evaluation across parent and child sessions.
140#[derive(Debug, Clone)]
141pub struct LivePolicyHandle {
142    baseline: Arc<RwLock<Arc<LivePolicyBaseline>>>,
143    session_permissions: Option<ProcessSessionPermissionView>,
144    child_override: Option<Arc<ChildWorkspacePolicyOverride>>,
145}
146
147impl LivePolicyHandle {
148    /// Creates a live handle initialized with `baseline`.
149    #[must_use]
150    pub fn new(baseline: LivePolicyBaseline) -> Self {
151        Self {
152            baseline: Arc::new(RwLock::new(Arc::new(baseline))),
153            session_permissions: None,
154            child_override: None,
155        }
156    }
157
158    /// Creates a standalone handle initialized from an optional
159    /// [`WorkspaceAccessPolicy`] (primarily for standalone tools and tests).
160    #[must_use]
161    pub fn for_workspace(policy: Option<WorkspaceAccessPolicy>) -> Self {
162        let product_private_paths = policy
163            .as_ref()
164            .map(WorkspaceAccessPolicy::product_private_paths)
165            .unwrap_or_default();
166        Self::new(LivePolicyBaseline::new(
167            policy.is_some(),
168            policy,
169            product_private_paths,
170            NetworkAccessPolicy::default(),
171        ))
172    }
173
174    /// Creates a standalone handle initialized from a [`NetworkAccessPolicy`]
175    /// (preserving any attached session permission view).
176    #[must_use]
177    pub fn for_network(policy: NetworkAccessPolicy) -> Self {
178        let session_view = policy.session_permissions_view();
179        let mut handle = Self::new(LivePolicyBaseline::new(false, None, Vec::new(), policy));
180        if let Some(view) = session_view {
181            handle = handle.with_session_permissions(view);
182        }
183        handle
184    }
185
186    /// Attaches a live read-only view of session-scoped permission grants.
187    #[must_use]
188    pub fn with_session_permissions(mut self, view: ProcessSessionPermissionView) -> Self {
189        self.session_permissions = Some(view);
190        self
191    }
192
193    /// Derives a child handle sharing the same atomic baseline lock while
194    /// binding session grant evaluation strictly to the child's own
195    /// `session_permissions` and optional workspace/worktree overrides.
196    #[must_use]
197    pub fn for_child(
198        &self,
199        session_permissions: Option<ProcessSessionPermissionView>,
200        child_override: Option<ChildWorkspacePolicyOverride>,
201    ) -> Self {
202        Self {
203            baseline: Arc::clone(&self.baseline),
204            session_permissions,
205            child_override: child_override.map(Arc::new),
206        }
207    }
208
209    /// Returns a point-in-time `Arc` snapshot of the shared policy baseline.
210    #[must_use]
211    pub fn baseline_snapshot(&self) -> Arc<LivePolicyBaseline> {
212        Arc::clone(
213            &self
214                .baseline
215                .read()
216                .unwrap_or_else(std::sync::PoisonError::into_inner),
217        )
218    }
219
220    /// Atomically replaces the shared policy baseline under a single lock.
221    pub fn replace_baseline(&self, next: LivePolicyBaseline) {
222        *self
223            .baseline
224            .write()
225            .unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::new(next);
226    }
227
228    /// Returns whether workspace sandbox restrictions are currently active.
229    #[must_use]
230    pub fn is_restricted(&self) -> bool {
231        self.baseline_snapshot().restricted
232    }
233
234    /// Returns whether writes inside the workspace are currently allowed.
235    #[must_use]
236    pub fn workspace_writable(&self) -> bool {
237        let baseline = self.baseline_snapshot();
238        let child_writable = self
239            .child_override
240            .as_ref()
241            .is_none_or(|override_cfg| override_cfg.workspace_writable);
242        if !baseline.restricted {
243            return child_writable;
244        }
245        let parent_writable = baseline
246            .workspace_access
247            .as_ref()
248            .is_none_or(WorkspaceAccessPolicy::workspace_writable);
249        parent_writable && child_writable
250    }
251
252    /// Returns whether the active network baseline allows local loopback targets.
253    #[must_use]
254    pub fn network_allow_local(&self) -> bool {
255        self.baseline_snapshot().network_access.allow_local()
256    }
257
258    /// Returns the currently active `ProductPrivate` protected credential paths.
259    #[must_use]
260    pub fn product_private_paths(&self) -> Vec<PathBuf> {
261        self.baseline_snapshot().product_private_paths.clone()
262    }
263
264    /// Evaluates filesystem read access for `path` against the active baseline,
265    /// this session's grants, and optional single-action `once_grants`.
266    #[must_use]
267    pub fn evaluate_read(&self, path: &Path, once_grants: &[PathAccessRule]) -> PathEvaluation {
268        self.evaluate_path(path, PathAccess::ReadOnly, once_grants)
269    }
270
271    /// Evaluates filesystem write access for `path` against the active baseline,
272    /// this session's grants, and optional single-action `once_grants`.
273    #[must_use]
274    pub fn evaluate_write(&self, path: &Path, once_grants: &[PathAccessRule]) -> PathEvaluation {
275        self.evaluate_path(path, PathAccess::ReadWrite, once_grants)
276    }
277
278    /// Evaluates filesystem access for `path` in either `--sandbox workspace`
279    /// or `--sandbox off` mode using a single authoritative evaluation pass.
280    #[must_use]
281    pub fn evaluate_path(
282        &self,
283        path: &Path,
284        requested: PathAccess,
285        once_grants: &[PathAccessRule],
286    ) -> PathEvaluation {
287        let baseline = self.baseline_snapshot();
288        if !baseline.restricted {
289            let git_metadata = crate::is_git_metadata_path(path);
290            if is_protected_in_unrestricted_mode(&baseline.product_private_paths, path) {
291                let decision =
292                    if crate::access_policy::once_grants_cover_path(once_grants, path, requested) {
293                        PathAccessDecision::Allow
294                    } else {
295                        PathAccessDecision::RequireReview
296                    };
297                return PathEvaluation::protected(decision, git_metadata);
298            }
299            if requested == PathAccess::ReadWrite
300                && self
301                    .child_override
302                    .as_ref()
303                    .is_some_and(|override_cfg| !override_cfg.workspace_writable)
304            {
305                return PathEvaluation::deny(PathDenialReason::ReadOnlyWorkspace, git_metadata);
306            }
307            return PathEvaluation::allow(git_metadata);
308        }
309
310        let Some(base_policy) = baseline.workspace_access.as_ref() else {
311            return PathEvaluation::allow(crate::is_git_metadata_path(path));
312        };
313        let session = self.session_snapshot();
314        base_policy.evaluate_with_child_override(
315            self.child_override.as_deref(),
316            path,
317            requested,
318            session.as_ref(),
319            once_grants,
320        )
321    }
322
323    /// Evaluates outbound HTTP(S) access to `host` against the active baseline,
324    /// this session's grants, and optional single-action `once_domains`.
325    #[must_use]
326    pub fn evaluate_network_host(
327        &self,
328        host: &str,
329        once_domains: &[String],
330    ) -> NetworkAccessDecision {
331        let baseline = self.baseline_snapshot();
332        let session = self.session_snapshot();
333        baseline
334            .network_access
335            .evaluate_host_with_session(host, session.as_ref(), once_domains)
336    }
337
338    /// Evaluates access to a browser `data:` document against the active baseline.
339    #[must_use]
340    pub fn evaluate_data_url(&self) -> NetworkAccessDecision {
341        self.baseline_snapshot().network_access.evaluate_data_url()
342    }
343
344    fn session_snapshot(&self) -> Option<ProcessSessionPermissionSnapshot> {
345        self.session_permissions
346            .as_ref()
347            .and_then(|view| view.snapshot().ok())
348    }
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354    use crate::{PathAccessRuleSource, ProcessSessionPermissions};
355    use merry_core::CapabilityPolicy;
356
357    #[test]
358    fn child_handle_tracks_live_baseline_while_isolating_session_grants() {
359        let temp = tempfile::tempdir().expect("tempdir");
360        let workspace = temp.path().join("workspace");
361        let external = temp.path().join("external.txt");
362        let secret_dir = temp.path().join("providers");
363        std::fs::create_dir_all(&workspace).expect("workspace");
364        std::fs::create_dir_all(&secret_dir).expect("secret dir");
365        std::fs::write(&external, "hello").expect("external");
366
367        let parent_session = ProcessSessionPermissions::new();
368        let child_session = ProcessSessionPermissions::new();
369
370        let initial = LivePolicyBaseline::new(
371            true,
372            Some(WorkspaceAccessPolicy::new(&workspace, true)),
373            vec![secret_dir.clone()],
374            NetworkAccessPolicy::new(CapabilityPolicy::Ask, true),
375        );
376        let parent = LivePolicyHandle::new(initial).with_session_permissions(parent_session.view());
377        let child = parent.for_child(
378            Some(child_session.view()),
379            Some(ChildWorkspacePolicyOverride::new(false)),
380        );
381
382        // Child approves a session domain grant; parent does NOT inherit it.
383        child_session
384            .retain_domain_grants(["docs.rs".to_owned()])
385            .expect("retain domain");
386        assert_eq!(
387            child.evaluate_network_host("docs.rs", &[]),
388            NetworkAccessDecision::Allow
389        );
390        assert_eq!(
391            parent.evaluate_network_host("docs.rs", &[]),
392            NetworkAccessDecision::RequireReview
393        );
394
395        // Child is read-only inside workspace even when parent is writable.
396        let ws_file = workspace.join("src.rs");
397        assert_eq!(
398            parent.evaluate_write(&ws_file, &[]).decision,
399            PathAccessDecision::Allow
400        );
401        assert_eq!(
402            child.evaluate_write(&ws_file, &[]).decision,
403            PathAccessDecision::Deny
404        );
405
406        // Parent flips baseline to unrestricted (`--sandbox off`) + `network = deny`.
407        parent.replace_baseline(LivePolicyBaseline::new(
408            false,
409            None,
410            vec![secret_dir.clone()],
411            NetworkAccessPolicy::new(CapabilityPolicy::Deny, true),
412        ));
413        assert!(!child.is_restricted());
414        assert_eq!(
415            child.evaluate_read(&external, &[]).decision,
416            PathAccessDecision::Allow
417        );
418        assert_eq!(
419            child.evaluate_network_host("docs.rs", &[]),
420            NetworkAccessDecision::Deny
421        );
422        // Built-in ProductPrivate remains approval-gated with protected_target=true in off mode.
423        let secret_eval = child.evaluate_read(&secret_dir.join("key.json"), &[]);
424        assert_eq!(secret_eval.decision, PathAccessDecision::RequireReview);
425        assert!(secret_eval.protected_target);
426
427        // Adding a saved workspace path rule under workspace mode flows immediately to child.
428        parent.replace_baseline(LivePolicyBaseline::new(
429            true,
430            Some(
431                WorkspaceAccessPolicy::new(&workspace, true).with_static_rules([
432                    PathAccessRule::new(
433                        &external,
434                        PathAccess::ReadOnly,
435                        PathAccessRuleSource::WorkspacePermissions,
436                    ),
437                ]),
438            ),
439            vec![secret_dir],
440            NetworkAccessPolicy::new(CapabilityPolicy::Ask, true),
441        ));
442        assert!(child.is_restricted());
443        assert_eq!(
444            child.evaluate_read(&external, &[]).decision,
445            PathAccessDecision::Allow
446        );
447    }
448}