Skip to main content

merry_runtime/
access_policy.rs

1//! Unified filesystem access policy shared by in-process workspace tools,
2//! host-process sandbox backends, and workspace persistence guards.
3//!
4//! This module is pure Rust with zero process spawning (`fork`/`exec`), so it
5//! works identically across desktop CLI, headless SDKs, Windows, and Apple App
6//! Sandbox targets (`rootshell` on iOS / Mac Catalyst / visionOS).
7
8use crate::{
9    ChildWorkspacePolicyOverride, PathAccess, PathAccessRule, PathAccessRuleSource,
10    ProcessSessionPermissionSnapshot, ProcessSessionPermissionView,
11};
12use merry_core::HostPathPolicy;
13use std::{
14    fs,
15    path::{Component, Path, PathBuf},
16};
17
18/// Three-state decision produced by [`WorkspaceAccessPolicy`].
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum PathAccessDecision {
21    /// Path is authorized by workspace, static rules, session grants, or once grants.
22    Allow,
23    /// Path is outside current grants and requires permission admission review.
24    RequireReview,
25    /// Path is blocked by a hard policy ceiling (`Deny`, trusted global
26    /// `ReadOnly` write ceiling, read-only workspace, or descendant coverage
27    /// of a protected path) and cannot be escalated by runtime approval.
28    Deny,
29}
30
31/// Specific reason a path evaluation returned [`PathAccessDecision::Deny`].
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum PathDenialReason {
34    /// Blocked by a user-configured or non-`ProductPrivate` hard `Deny` rule.
35    UserHardDeny,
36    /// Write blocked by a `TrustedGlobalConfig` `ReadOnly` hard write ceiling.
37    UserReadOnlyCeiling,
38    /// Write blocked because the active workspace is read-only.
39    ReadOnlyWorkspace,
40    /// Directory grant covers a strictly nested denied path.
41    CoversDeniedDescendant,
42    /// Writable directory grant covers a strictly nested Merry `ProductReadOnly` path.
43    CoversProtectedReadOnlyDescendant,
44    /// Requested `PathAccess::Deny` is never an executable grant.
45    InvalidAccess,
46}
47
48/// Structured result of evaluating a path against Merry's single authoritative
49/// filesystem access policy.
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub struct PathEvaluation {
52    /// Final three-state admission decision.
53    pub decision: PathAccessDecision,
54    /// Whether the target hits a built-in Merry protected path (`ProductPrivate`
55    /// or `ProductReadOnly` write) that must remain `Once`-only and default-`Deny`.
56    pub protected_target: bool,
57    /// Whether the lexical or canonical target touches `.git` metadata.
58    pub git_metadata: bool,
59    /// Specific reason when `decision == PathAccessDecision::Deny`.
60    pub denial_reason: Option<PathDenialReason>,
61}
62
63impl PathEvaluation {
64    #[must_use]
65    pub(crate) const fn allow(git_metadata: bool) -> Self {
66        Self {
67            decision: PathAccessDecision::Allow,
68            protected_target: false,
69            git_metadata,
70            denial_reason: None,
71        }
72    }
73
74    #[must_use]
75    pub(crate) const fn require_review(git_metadata: bool) -> Self {
76        Self {
77            decision: PathAccessDecision::RequireReview,
78            protected_target: false,
79            git_metadata,
80            denial_reason: None,
81        }
82    }
83
84    #[must_use]
85    pub(crate) const fn deny(reason: PathDenialReason, git_metadata: bool) -> Self {
86        Self {
87            decision: PathAccessDecision::Deny,
88            protected_target: false,
89            git_metadata,
90            denial_reason: Some(reason),
91        }
92    }
93
94    #[must_use]
95    pub(crate) const fn protected(decision: PathAccessDecision, git_metadata: bool) -> Self {
96        Self {
97            decision,
98            protected_target: true,
99            git_metadata,
100            denial_reason: None,
101        }
102    }
103}
104
105/// Pre-resolved static path rule so hot-path evaluations never repeat
106/// `fs::canonicalize()` syscalls across multiple precedence passes.
107#[derive(Debug, Clone)]
108pub(crate) struct ResolvedPathRule {
109    pub(crate) resolved: PathBuf,
110    pub(crate) depth: usize,
111    pub(crate) access: PathAccess,
112    pub(crate) source: PathAccessRuleSource,
113}
114
115impl ResolvedPathRule {
116    pub(crate) fn from_rule(rule: &PathAccessRule) -> Self {
117        let resolved = resolve_rule_path(rule.path());
118        let depth = resolved.components().count();
119        Self {
120            resolved,
121            depth,
122            access: rule.access(),
123            source: rule.source(),
124        }
125    }
126}
127
128/// Single-source-of-truth filesystem allowlist evaluated by in-process file
129/// tools (`read_file`, `apply_patch`), host-process sandboxes (`merry-process`),
130/// and persistence guards (`merry-app`).
131#[derive(Debug, Clone)]
132pub struct WorkspaceAccessPolicy {
133    workspace_root: PathBuf,
134    workspace_root_canonical: PathBuf,
135    workspace_writable: bool,
136    static_rules: Vec<ResolvedPathRule>,
137    session_permissions: Option<ProcessSessionPermissionView>,
138}
139
140impl WorkspaceAccessPolicy {
141    /// Creates an access policy rooted at `workspace_root`.
142    #[must_use]
143    pub fn new(workspace_root: impl Into<PathBuf>, workspace_writable: bool) -> Self {
144        let workspace_root = normalize_path_lexically(&workspace_root.into());
145        let workspace_root_canonical = resolve_path_with_existing_ancestor(&workspace_root);
146        Self {
147            workspace_root,
148            workspace_root_canonical,
149            workspace_writable,
150            static_rules: Vec::new(),
151            session_permissions: None,
152        }
153    }
154
155    /// Installs static baseline, trusted-config, and product path rules,
156    /// canonicalizing each rule path once up front.
157    #[must_use]
158    pub fn with_static_rules(mut self, rules: impl IntoIterator<Item = PathAccessRule>) -> Self {
159        self.static_rules = rules
160            .into_iter()
161            .map(|rule| ResolvedPathRule::from_rule(&rule))
162            .collect();
163        self
164    }
165
166    /// Attaches a live read-only view of session-approved capability grants.
167    #[must_use]
168    pub fn with_session_permissions(mut self, view: ProcessSessionPermissionView) -> Self {
169        self.session_permissions = Some(view);
170        self
171    }
172
173    /// Returns the workspace root path.
174    #[must_use]
175    pub fn workspace_root(&self) -> &Path {
176        &self.workspace_root
177    }
178
179    /// Returns whether writes inside the workspace are permitted.
180    #[must_use]
181    pub const fn workspace_writable(&self) -> bool {
182        self.workspace_writable
183    }
184
185    /// Returns canonicalized `ProductPrivate` paths configured in static rules.
186    #[must_use]
187    pub fn product_private_paths(&self) -> Vec<PathBuf> {
188        self.static_rules
189            .iter()
190            .filter(|entry| {
191                entry.access == PathAccess::Deny
192                    && entry.source == PathAccessRuleSource::ProductPrivate
193            })
194            .map(|entry| entry.resolved.clone())
195            .collect()
196    }
197
198    /// Evaluates read access for `path` under the current policy, attached
199    /// session grants, and optional single-action `once_grants`.
200    #[must_use]
201    pub fn evaluate_read(&self, path: &Path, once_grants: &[PathAccessRule]) -> PathAccessDecision {
202        let snapshot = self
203            .session_permissions
204            .as_ref()
205            .and_then(|view| view.snapshot().ok());
206        self.evaluate_path(path, PathAccess::ReadOnly, snapshot.as_ref(), once_grants)
207            .decision
208    }
209
210    /// Evaluates write access for `path` under the current policy, attached
211    /// session grants, and optional single-action `once_grants`.
212    #[must_use]
213    pub fn evaluate_write(
214        &self,
215        path: &Path,
216        once_grants: &[PathAccessRule],
217    ) -> PathAccessDecision {
218        let snapshot = self
219            .session_permissions
220            .as_ref()
221            .and_then(|view| view.snapshot().ok());
222        self.evaluate_path(path, PathAccess::ReadWrite, snapshot.as_ref(), once_grants)
223            .decision
224    }
225
226    /// Pure single-path evaluation returning structured decision, protected
227    /// target flag, `.git` flag, and denial reason.
228    #[must_use]
229    pub fn evaluate_path(
230        &self,
231        path: &Path,
232        requested: PathAccess,
233        session: Option<&ProcessSessionPermissionSnapshot>,
234        once_grants: &[PathAccessRule],
235    ) -> PathEvaluation {
236        self.evaluate_inner(None, path, requested, session, once_grants, false)
237    }
238
239    /// Evaluates a single path with an optional child-session override without
240    /// cloning `static_rules` or re-canonicalizing rule paths.
241    #[must_use]
242    pub(crate) fn evaluate_with_child_override(
243        &self,
244        child: Option<&ChildWorkspacePolicyOverride>,
245        path: &Path,
246        requested: PathAccess,
247        session: Option<&ProcessSessionPermissionSnapshot>,
248        once_grants: &[PathAccessRule],
249    ) -> PathEvaluation {
250        self.evaluate_inner(child, path, requested, session, once_grants, false)
251    }
252
253    /// Pure directory-grant evaluation (used by process sandboxes) that also
254    /// rejects grants covering strictly nested denied or `ProductReadOnly` paths.
255    #[must_use]
256    pub fn evaluate_directory_grant(
257        &self,
258        path: &Path,
259        requested: PathAccess,
260        session: Option<&ProcessSessionPermissionSnapshot>,
261        once_grants: &[PathAccessRule],
262    ) -> PathEvaluation {
263        self.evaluate_inner(None, path, requested, session, once_grants, true)
264    }
265
266    /// Returns whether `path` is already covered at `requested` access by
267    /// configured static rules or retained session grants (independent of
268    /// implicit workspace membership), and not blocked by any ceiling or
269    /// descendant constraint.
270    #[must_use]
271    pub fn explicit_rules_cover(
272        &self,
273        path: &Path,
274        requested: PathAccess,
275        session: Option<&ProcessSessionPermissionSnapshot>,
276    ) -> bool {
277        let eval = self.evaluate_directory_grant(path, requested, session, &[]);
278        if eval.decision != PathAccessDecision::Allow {
279            return false;
280        }
281        let resolved = resolve_rule_path(path);
282        let session_rules = session
283            .map(ProcessSessionPermissionSnapshot::path_rules)
284            .unwrap_or(&[]);
285        resolved_and_dynamic_rules_cover_path(
286            self.static_rules.iter(),
287            session_rules.iter(),
288            &resolved,
289            requested,
290        )
291    }
292
293    /// Returns whether `path` targets a built-in Merry protected path
294    /// (`ProductPrivate` or `ProductReadOnly` write).
295    #[must_use]
296    pub fn is_protected_target(&self, path: &Path, requested: PathAccess) -> bool {
297        let resolved = resolve_rule_path(path);
298        requires_built_in_product_review(&self.static_rules, &[], &resolved, requested)
299    }
300
301    /// Returns the blocking rule path when a directory grant is rejected by a
302    /// hard deny or descendant coverage rule, for actionable error messages.
303    #[must_use]
304    pub fn blocking_rule_path(&self, path: &Path, requested: PathAccess) -> Option<PathBuf> {
305        let resolved = resolve_rule_path(path);
306        if let Some(rule_path) = effective_user_hard_deny_path(&self.static_rules, &[], &resolved) {
307            return Some(rule_path);
308        }
309        if let Some(child_path) = covered_denied_descendant_path(&self.static_rules, &[], &resolved)
310        {
311            return Some(child_path);
312        }
313        if requested == PathAccess::ReadWrite
314            && let Some(child_path) =
315                covered_protected_readonly_descendant_path(&self.static_rules, &[], &resolved)
316        {
317            return Some(child_path);
318        }
319        None
320    }
321
322    fn evaluate_inner(
323        &self,
324        child: Option<&ChildWorkspacePolicyOverride>,
325        path: &Path,
326        requested: PathAccess,
327        session: Option<&ProcessSessionPermissionSnapshot>,
328        once_grants: &[PathAccessRule],
329        check_descendants: bool,
330    ) -> PathEvaluation {
331        let lexical = normalize_path_lexically(path);
332        let resolved = resolve_path_with_existing_ancestor(&lexical);
333        let git_metadata = is_git_metadata_path_parts(&lexical, &resolved);
334
335        if requested == PathAccess::Deny {
336            return PathEvaluation::deny(PathDenialReason::InvalidAccess, git_metadata);
337        }
338
339        let (effective_root, effective_writable, extra_rules) = match child {
340            Some(override_cfg) => (
341                override_cfg
342                    .workspace_root_canonical()
343                    .unwrap_or(&self.workspace_root_canonical),
344                self.workspace_writable && override_cfg.workspace_writable(),
345                override_cfg.extra_resolved_rules(),
346            ),
347            None => (
348                self.workspace_root_canonical.as_path(),
349                self.workspace_writable,
350                &[][..],
351            ),
352        };
353        let in_workspace = path_within(&resolved, effective_root);
354
355        // 1. User-configured hard ceilings always win over built-in product
356        //    review and runtime approvals.
357        if let Some(reason) = user_hard_ceiling_reason(
358            &self.static_rules,
359            extra_rules,
360            &resolved,
361            requested,
362            in_workspace,
363            effective_writable,
364            effective_root.components().count(),
365        ) {
366            return PathEvaluation::deny(reason, git_metadata);
367        }
368
369        // 2. Directory grants (process sandbox) must not cover strictly nested
370        //    denied or protected read-only paths.
371        if check_descendants {
372            if covered_denied_descendant_path(&self.static_rules, extra_rules, &resolved).is_some()
373            {
374                return PathEvaluation::deny(
375                    PathDenialReason::CoversDeniedDescendant,
376                    git_metadata,
377                );
378            }
379            if requested == PathAccess::ReadWrite
380                && covered_protected_readonly_descendant_path(
381                    &self.static_rules,
382                    extra_rules,
383                    &resolved,
384                )
385                .is_some()
386            {
387                return PathEvaluation::deny(
388                    PathDenialReason::CoversProtectedReadOnlyDescendant,
389                    git_metadata,
390                );
391            }
392        }
393
394        // 3. Built-in Merry product protections (`ProductPrivate` credentials
395        //    and `ProductReadOnly` writes) require explicit single-action review.
396        if requires_built_in_product_review(&self.static_rules, extra_rules, &resolved, requested) {
397            let decision = if dynamic_rules_cover_path(once_grants.iter(), &resolved, requested) {
398                PathAccessDecision::Allow
399            } else {
400                PathAccessDecision::RequireReview
401            };
402            return PathEvaluation::protected(decision, git_metadata);
403        }
404
405        // 4. Only the resolved canonical target determines workspace membership;
406        //    `.git` writes are excluded from automatic workspace writability.
407        if in_workspace && !(requested == PathAccess::ReadWrite && git_metadata) {
408            return match requested {
409                PathAccess::ReadOnly => PathEvaluation::allow(git_metadata),
410                PathAccess::ReadWrite if effective_writable => PathEvaluation::allow(git_metadata),
411                PathAccess::ReadWrite | PathAccess::Deny => {
412                    PathEvaluation::deny(PathDenialReason::ReadOnlyWorkspace, git_metadata)
413                }
414            };
415        }
416
417        let session_rules = session
418            .map(ProcessSessionPermissionSnapshot::path_rules)
419            .unwrap_or(&[]);
420        if resolved_and_dynamic_rules_cover_path(
421            self.static_rules.iter().chain(extra_rules.iter()),
422            once_grants.iter().chain(session_rules.iter()),
423            &resolved,
424            requested,
425        ) {
426            PathEvaluation::allow(git_metadata)
427        } else {
428            PathEvaluation::require_review(git_metadata)
429        }
430    }
431}
432
433fn chained_rules<'a>(
434    base: &'a [ResolvedPathRule],
435    extra: &'a [ResolvedPathRule],
436) -> impl Iterator<Item = &'a ResolvedPathRule> + Clone {
437    base.iter().chain(extra.iter())
438}
439
440fn effective_user_hard_deny_path(
441    base: &[ResolvedPathRule],
442    extra: &[ResolvedPathRule],
443    resolved: &Path,
444) -> Option<PathBuf> {
445    chained_rules(base, extra)
446        .filter(|entry| {
447            entry.access == PathAccess::Deny && entry.source != PathAccessRuleSource::ProductPrivate
448        })
449        .filter(|entry| path_within(resolved, &entry.resolved))
450        .max_by_key(|entry| entry.depth)
451        .map(|entry| entry.resolved.clone())
452}
453
454fn user_hard_ceiling_reason(
455    base: &[ResolvedPathRule],
456    extra: &[ResolvedPathRule],
457    resolved: &Path,
458    requested: PathAccess,
459    in_workspace: bool,
460    workspace_writable: bool,
461    workspace_depth: usize,
462) -> Option<PathDenialReason> {
463    if effective_user_hard_deny_path(base, extra, resolved).is_some() {
464        return Some(PathDenialReason::UserHardDeny);
465    }
466
467    if requested == PathAccess::ReadWrite {
468        let deepest_trusted_ro_depth = chained_rules(base, extra)
469            .filter(|entry| {
470                entry.access == PathAccess::ReadOnly
471                    && entry.source == PathAccessRuleSource::TrustedGlobalConfig
472                    && path_within(resolved, &entry.resolved)
473            })
474            .map(|entry| entry.depth)
475            .max();
476        if let Some(ro_depth) = deepest_trusted_ro_depth {
477            let deeper_writable_workspace =
478                in_workspace && workspace_writable && workspace_depth > ro_depth;
479            let deeper_trusted_rw = chained_rules(base, extra).any(|entry| {
480                entry.access == PathAccess::ReadWrite
481                    && entry.source == PathAccessRuleSource::TrustedGlobalConfig
482                    && entry.depth > ro_depth
483                    && path_within(resolved, &entry.resolved)
484            });
485            if !deeper_writable_workspace && !deeper_trusted_rw {
486                return Some(PathDenialReason::UserReadOnlyCeiling);
487            }
488        }
489    }
490
491    None
492}
493
494fn covered_denied_descendant_path(
495    base: &[ResolvedPathRule],
496    extra: &[ResolvedPathRule],
497    resolved: &Path,
498) -> Option<PathBuf> {
499    chained_rules(base, extra)
500        .filter(|entry| entry.access == PathAccess::Deny)
501        .find_map(|entry| {
502            (entry.resolved != resolved && entry.resolved.starts_with(resolved))
503                .then(|| entry.resolved.clone())
504        })
505}
506
507fn trusted_global_rw_overrides_product_ro<'a>(
508    mut rules: impl Iterator<Item = &'a ResolvedPathRule>,
509    target: &Path,
510    ro_depth: usize,
511) -> bool {
512    rules.any(|entry| {
513        entry.access == PathAccess::ReadWrite
514            && entry.source == PathAccessRuleSource::TrustedGlobalConfig
515            && entry.depth >= ro_depth
516            && path_within(target, &entry.resolved)
517    })
518}
519
520fn covered_protected_readonly_descendant_path(
521    base: &[ResolvedPathRule],
522    extra: &[ResolvedPathRule],
523    resolved: &Path,
524) -> Option<PathBuf> {
525    let rules = chained_rules(base, extra);
526    rules
527        .clone()
528        .filter(|entry| {
529            entry.access == PathAccess::ReadOnly
530                && entry.source == PathAccessRuleSource::ProductReadOnly
531        })
532        .find_map(|entry| {
533            let covered = entry.resolved != resolved && entry.resolved.starts_with(resolved);
534            if !covered {
535                return None;
536            }
537            let explicitly_writable =
538                trusted_global_rw_overrides_product_ro(rules.clone(), &entry.resolved, entry.depth);
539            (!explicitly_writable).then(|| entry.resolved.clone())
540        })
541}
542
543fn requires_built_in_product_review(
544    base: &[ResolvedPathRule],
545    extra: &[ResolvedPathRule],
546    resolved: &Path,
547    requested: PathAccess,
548) -> bool {
549    let rules = chained_rules(base, extra);
550    let deepest_private_depth = rules
551        .clone()
552        .filter(|entry| {
553            entry.access == PathAccess::Deny
554                && entry.source == PathAccessRuleSource::ProductPrivate
555                && path_within(resolved, &entry.resolved)
556        })
557        .map(|entry| entry.depth)
558        .max();
559    if let Some(private_depth) = deepest_private_depth {
560        let deeper_product_ro = requested == PathAccess::ReadOnly
561            && rules.clone().any(|entry| {
562                entry.access == PathAccess::ReadOnly
563                    && entry.source == PathAccessRuleSource::ProductReadOnly
564                    && entry.depth > private_depth
565                    && path_within(resolved, &entry.resolved)
566            });
567        if !deeper_product_ro {
568            return true;
569        }
570    }
571
572    if requested == PathAccess::ReadWrite {
573        let deepest_product_ro_depth = rules
574            .clone()
575            .filter(|entry| {
576                entry.access == PathAccess::ReadOnly
577                    && entry.source == PathAccessRuleSource::ProductReadOnly
578                    && path_within(resolved, &entry.resolved)
579            })
580            .map(|entry| entry.depth)
581            .max();
582        if let Some(ro_depth) = deepest_product_ro_depth {
583            let writable_beats_ro =
584                trusted_global_rw_overrides_product_ro(rules.clone(), resolved, ro_depth)
585                    || rules.clone().any(|entry| {
586                        entry.access == PathAccess::ReadWrite
587                            && matches!(
588                                entry.source,
589                                PathAccessRuleSource::ProductConfig
590                                    | PathAccessRuleSource::DurableMemory
591                            )
592                            && entry.depth > ro_depth
593                            && path_within(resolved, &entry.resolved)
594                    });
595            if !writable_beats_ro {
596                return true;
597            }
598        }
599    }
600
601    false
602}
603
604/// Extracts canonicalized `ProductPrivate` paths from a slice of path rules.
605#[must_use]
606pub fn extract_product_private_paths(rules: &[PathAccessRule]) -> Vec<PathBuf> {
607    rules
608        .iter()
609        .filter(|rule| {
610            rule.access() == PathAccess::Deny
611                && rule.source() == PathAccessRuleSource::ProductPrivate
612        })
613        .map(|rule| resolve_rule_path(rule.path()))
614        .collect()
615}
616
617/// Checks whether single-action `once_grants` cover `path` at `requested` access.
618#[must_use]
619pub fn once_grants_cover_path(
620    once_grants: &[PathAccessRule],
621    path: &Path,
622    requested: PathAccess,
623) -> bool {
624    let resolved = resolve_rule_path(path);
625    dynamic_rules_cover_path(once_grants.iter(), &resolved, requested)
626}
627
628/// Returns whether `path` hits or overlaps (as descendant OR ancestor) any
629/// built-in Merry `ProductPrivate` path in unrestricted (`--sandbox off`) mode.
630#[must_use]
631pub fn is_protected_in_unrestricted_mode(product_private_paths: &[PathBuf], path: &Path) -> bool {
632    let lexical = normalize_path_lexically(path);
633    let resolved = resolve_path_with_existing_ancestor(&lexical);
634    product_private_paths.iter().any(|private| {
635        let resolved_private = resolve_rule_path(private);
636        path_overlaps(&resolved, &resolved_private) || path_overlaps(&lexical, &resolved_private)
637    })
638}
639
640/// Returns whether `path` is a protected Merry host path (or covers one as an
641/// ancestor) and therefore must never be persisted to `workspace-permissions.json`.
642#[must_use]
643pub fn is_protected_host_path_for_persistence(
644    path: &Path,
645    access: PathAccess,
646    policy: &HostPathPolicy,
647) -> bool {
648    let lexical = normalize_path_lexically(path);
649    let resolved = resolve_path_with_existing_ancestor(&lexical);
650    for denied in policy.denied() {
651        let resolved_denied = resolve_rule_path(denied);
652        if path_overlaps(&resolved, &resolved_denied) || path_overlaps(&lexical, &resolved_denied) {
653            return true;
654        }
655    }
656    if access == PathAccess::ReadWrite {
657        for ro in policy.product_readonly() {
658            let resolved_ro = resolve_rule_path(ro);
659            if !(path_overlaps(&resolved, &resolved_ro) || path_overlaps(&lexical, &resolved_ro)) {
660                continue;
661            }
662            let ro_depth = resolved_ro.components().count();
663            let deeper_writable = policy
664                .product_writable_config()
665                .iter()
666                .map(PathBuf::as_path)
667                .chain(policy.durable_memory_root())
668                .any(|writable| {
669                    let resolved_writable = resolve_rule_path(writable);
670                    path_within(&resolved, &resolved_writable)
671                        && resolved_writable.components().count() > ro_depth
672                });
673            if !deeper_writable {
674                return true;
675            }
676        }
677    }
678    false
679}
680
681/// Returns whether `path` (either lexically or after resolving symlinks on its
682/// existing ancestor) targets `.git` metadata.
683#[must_use]
684pub fn is_git_metadata_path(path: &Path) -> bool {
685    let lexical = normalize_path_lexically(path);
686    let resolved = resolve_path_with_existing_ancestor(&lexical);
687    is_git_metadata_path_parts(&lexical, &resolved)
688}
689
690fn is_git_metadata_path_parts(lexical: &Path, resolved: &Path) -> bool {
691    has_git_component(lexical) || has_git_component(resolved)
692}
693
694fn has_git_component(path: &Path) -> bool {
695    path.components()
696        .any(|component| matches!(component, Component::Normal(name) if name == ".git"))
697}
698
699fn update_best_match(
700    best_match: &mut Option<(usize, PathAccess, PathAccessRuleSource)>,
701    depth: usize,
702    access: PathAccess,
703    source: PathAccessRuleSource,
704) {
705    let should_replace = match *best_match {
706        None => true,
707        Some((best_depth, best_access, best_source)) => {
708            depth > best_depth
709                || (depth == best_depth
710                    && precedence(access, source) > precedence(best_access, best_source))
711        }
712    };
713    if should_replace {
714        *best_match = Some((depth, access, source));
715    }
716}
717
718fn dynamic_rules_cover_path<'a>(
719    rules: impl IntoIterator<Item = &'a PathAccessRule>,
720    resolved: &Path,
721    requested: PathAccess,
722) -> bool {
723    resolved_and_dynamic_rules_cover_path(std::iter::empty(), rules, resolved, requested)
724}
725
726fn resolved_and_dynamic_rules_cover_path<'a>(
727    static_rules: impl IntoIterator<Item = &'a ResolvedPathRule>,
728    dynamic_rules: impl IntoIterator<Item = &'a PathAccessRule>,
729    resolved: &Path,
730    requested: PathAccess,
731) -> bool {
732    let mut best_match: Option<(usize, PathAccess, PathAccessRuleSource)> = None;
733    for entry in static_rules {
734        if path_within(resolved, &entry.resolved) {
735            update_best_match(&mut best_match, entry.depth, entry.access, entry.source);
736        }
737    }
738    for rule in dynamic_rules {
739        let rule_resolved = resolve_rule_path(rule.path());
740        if path_within(resolved, &rule_resolved) {
741            update_best_match(
742                &mut best_match,
743                rule_resolved.components().count(),
744                rule.access(),
745                rule.source(),
746            );
747        }
748    }
749    best_match.is_some_and(|(_, access, _)| access.covers(requested))
750}
751
752pub(crate) fn resolve_rule_path(path: &Path) -> PathBuf {
753    resolve_path_with_existing_ancestor(&normalize_path_lexically(path))
754}
755
756fn precedence(access: PathAccess, source: PathAccessRuleSource) -> u8 {
757    if access == PathAccess::Deny {
758        return 4;
759    }
760    if access == PathAccess::ReadOnly && source == PathAccessRuleSource::TrustedGlobalConfig {
761        return 3;
762    }
763    if access == PathAccess::ReadWrite {
764        return 2;
765    }
766    1
767}
768
769fn path_within(target: &Path, root: &Path) -> bool {
770    target == root || target.starts_with(root)
771}
772
773fn path_overlaps(left: &Path, right: &Path) -> bool {
774    left == right || left.starts_with(right) || right.starts_with(left)
775}
776
777/// Canonicalizes `path`, or canonicalizes its deepest existing ancestor and
778/// appends the remaining lexical components, simplifying Windows verbatim prefixes.
779#[must_use]
780pub fn resolve_path_with_existing_ancestor(path: &Path) -> PathBuf {
781    let lexical = normalize_path_lexically(path);
782    if let Ok(canonical) = fs::canonicalize(&lexical) {
783        return merry_core::host_paths::simplify_verbatim_path(&canonical);
784    }
785    let mut suffix = Vec::new();
786    let mut current = lexical.as_path();
787    while let Some(parent) = current.parent() {
788        if let Some(name) = current.file_name() {
789            suffix.push(name.to_os_string());
790        }
791        if let Ok(canonical_parent) = fs::canonicalize(parent) {
792            let mut resolved = merry_core::host_paths::simplify_verbatim_path(&canonical_parent);
793            for part in suffix.into_iter().rev() {
794                resolved.push(part);
795            }
796            return resolved;
797        }
798        current = parent;
799    }
800    lexical
801}
802
803/// Lexically normalizes `.` and `..` components without touching the filesystem.
804#[must_use]
805pub fn normalize_path_lexically(path: &Path) -> PathBuf {
806    let mut normalized = PathBuf::new();
807    let is_absolute = path.is_absolute();
808    for component in path.components() {
809        match component {
810            Component::Prefix(prefix) => normalized.push(prefix.as_os_str()),
811            Component::RootDir => normalized.push(component.as_os_str()),
812            Component::CurDir => {}
813            Component::ParentDir => {
814                if !normalized.pop() && !is_absolute {
815                    normalized.push("..");
816                }
817            }
818            Component::Normal(part) => normalized.push(part),
819        }
820    }
821    normalized
822}
823
824#[cfg(test)]
825#[path = "access_policy_tests.rs"]
826mod tests;