Skip to main content

merry_process/process_runner/
permissions.rs

1use super::{background::BackgroundSupervisor, environment::WorkspaceProcessEnvironment, review};
2use crate::resolve_host_path;
3use merry_runtime::{
4    HostIntegration, PathAccess, PathAccessRule, PathAccessRuleSource, PermissionRequest,
5    PermissionedProcessRunnerFactory, PreparedProcessPermission, ProcessActionIntent,
6    ProcessPathGrant, ProcessPathGrantConstraint, ProcessRunner, ProcessRunnerError,
7    ProcessSessionPermissionView, ProcessSessionPermissions, RequestedCapability,
8    SessionPermissionedProcessRunnerFactory,
9};
10use std::{
11    ffi::OsStr,
12    path::{Component, Path, PathBuf},
13    sync::Arc,
14};
15
16/// Host-process runner that confines each process action.
17///
18/// Linux applies Landlock and, unless the action was granted network, a seccomp
19/// filter. macOS applies a Seatbelt profile. The Merry process itself stays
20/// unrestricted.
21#[derive(Debug, Clone)]
22pub struct WorkspaceProcessRunner {
23    pub(super) cwd_root: PathBuf,
24    pub(super) environment: WorkspaceProcessEnvironment,
25    pub(super) network_allowed: bool,
26    pub(super) path_rules: Vec<PathAccessRule>,
27    /// Paths explicitly requested by this action (never inherited from earlier
28    /// session-retained grants) that Landlock must verify exist before exec.
29    pub(super) action_required_rules: Vec<PathAccessRule>,
30    pub(super) session_permissions: Option<ProcessSessionPermissionView>,
31    pub(super) configuration_error: Option<String>,
32    workspace_writable: bool,
33    /// Keeps background children after `run` returns. Session drop kills them.
34    pub(super) background: BackgroundSupervisor,
35}
36
37impl WorkspaceProcessRunner {
38    /// Creates a per-action workspace runner rooted at a workspace path.
39    #[must_use]
40    pub fn new_at_workspace_root(root: impl Into<PathBuf>) -> Self {
41        Self {
42            cwd_root: root.into(),
43            environment: WorkspaceProcessEnvironment::from_current_process(),
44            network_allowed: false,
45            path_rules: Vec::new(),
46            action_required_rules: Vec::new(),
47            session_permissions: None,
48            configuration_error: None,
49            workspace_writable: true,
50            background: BackgroundSupervisor::new(),
51        }
52    }
53
54    pub(crate) fn with_background(mut self, background: BackgroundSupervisor) -> Self {
55        self.background = background;
56        self
57    }
58
59    /// Keeps the workspace readable and not writable.
60    ///
61    /// Baseline paths such as `/tmp` stay writable. This does not turn the
62    /// sandbox off.
63    #[must_use]
64    pub fn read_only_workspace(mut self) -> Self {
65        self.workspace_writable = false;
66        self
67    }
68
69    /// Sets the environment layout visible to child processes.
70    #[must_use]
71    pub fn with_environment(mut self, environment: WorkspaceProcessEnvironment) -> Self {
72        self.environment = environment;
73        self
74    }
75
76    /// Allows network access for child process actions.
77    #[must_use]
78    pub fn allow_network(mut self) -> Self {
79        self.network_allowed = true;
80        self
81    }
82
83    /// Installs trusted path rules for child process actions.
84    #[must_use]
85    pub fn with_path_rules(mut self, rules: impl IntoIterator<Item = PathAccessRule>) -> Self {
86        self.path_rules = rules.into_iter().collect();
87        self
88    }
89
90    /// Shares session-scoped approved capabilities with the permissioned runner factory.
91    #[must_use]
92    pub fn with_session_permissions(mut self, permissions: ProcessSessionPermissions) -> Self {
93        self.session_permissions = Some(permissions.view());
94        self
95    }
96
97    /// Rejects allow-list conflicts before a session can run a command.
98    ///
99    /// # Errors
100    ///
101    /// Returns the same conflict `plan_for` would return for these rules when a
102    /// deny, review, or private path sits inside an allowed directory.
103    pub(crate) fn ensure_sandbox_rules(&self) -> Result<(), ProcessRunnerError> {
104        if let Some(message) = self.configuration_error.clone() {
105            return Err(ProcessRunnerError::infrastructure(message));
106        }
107        let environment = self.environment.validate_for_workspace(&self.cwd_root)?;
108        let path_rules = normalize_path_rules(self.path_rules.clone());
109        crate::confinement::check_sandbox_rules(
110            &self.cwd_root,
111            &environment,
112            &path_rules,
113            self.workspace_writable,
114        )
115    }
116
117    pub(super) fn plan_for(
118        &self,
119        intent: &ProcessActionIntent,
120    ) -> Result<crate::confinement::SandboxLaunch, ProcessRunnerError> {
121        if let Some(message) = self.configuration_error.clone() {
122            return Err(ProcessRunnerError::infrastructure(message));
123        }
124        let environment = self.environment.validate_for_workspace(&self.cwd_root)?;
125        let session_snapshot = self
126            .session_permissions
127            .as_ref()
128            .map(ProcessSessionPermissionView::snapshot)
129            .transpose()?;
130        let mut environment = environment;
131        let mut path_rules = self.path_rules.clone();
132        if let Some(snapshot) = session_snapshot {
133            path_rules.extend(snapshot.path_rules().iter().cloned());
134            environment =
135                environment.with_host_integrations(snapshot.host_integrations().iter().copied());
136        }
137        path_rules = normalize_path_rules(path_rules);
138        crate::confinement::prepare_launch(
139            intent,
140            &self.cwd_root,
141            &environment,
142            self.network_allowed,
143            &path_rules,
144            &self.action_required_rules,
145            self.workspace_writable,
146        )
147    }
148}
149
150/// Builds a workspace runner from an approved permission request.
151///
152/// Filesystem access stays governed by the configured path rules and the
153/// session-scoped capabilities already approved by the runtime. Approved
154/// ordinary path and host-integration requests are retained for later actions
155/// in the same session. Network requests and paths marked for review stay
156/// action-scoped.
157#[derive(Debug, Clone)]
158pub struct WorkspaceProcessRunnerFactory {
159    pub(super) cwd_root: PathBuf,
160    pub(super) environment: WorkspaceProcessEnvironment,
161    pub(super) path_rules: Vec<PathAccessRule>,
162    network_requests_allowed: bool,
163    pub(super) session_permissions: Option<ProcessSessionPermissionView>,
164    workspace_writable: bool,
165    /// Shared by every runner this factory builds. `runner_for` drops its
166    /// runner when the tool call returns, so background children cannot live
167    /// only on that runner.
168    background: BackgroundSupervisor,
169}
170
171impl WorkspaceProcessRunnerFactory {
172    /// Creates a workspace-sandbox runner factory rooted at a workspace path.
173    #[must_use]
174    pub fn new_at_workspace_root(root: impl Into<PathBuf>) -> Self {
175        Self {
176            cwd_root: root.into(),
177            environment: WorkspaceProcessEnvironment::from_current_process(),
178            path_rules: Vec::new(),
179            network_requests_allowed: true,
180            session_permissions: None,
181            workspace_writable: true,
182            background: BackgroundSupervisor::new(),
183        }
184    }
185
186    pub(crate) fn with_background(mut self, background: BackgroundSupervisor) -> Self {
187        self.background = background;
188        self
189    }
190
191    /// Keeps the workspace readable and not writable for every child runner.
192    #[must_use]
193    pub fn read_only_workspace(mut self) -> Self {
194        self.workspace_writable = false;
195        self
196    }
197
198    /// Sets the environment layout used by every materialized child runner.
199    #[must_use]
200    pub fn with_environment(mut self, environment: WorkspaceProcessEnvironment) -> Self {
201        self.environment = environment;
202        self
203    }
204
205    /// Installs trusted path rules shared by each materialized runner.
206    #[must_use]
207    pub fn with_path_rules(mut self, rules: impl IntoIterator<Item = PathAccessRule>) -> Self {
208        self.path_rules = rules.into_iter().collect();
209        self
210    }
211
212    /// Sets whether network capability requests can proceed to review.
213    ///
214    /// Defaults to true without preauthorizing access. False rejects requests
215    /// during validation and materialization, including direct runner creation.
216    #[must_use]
217    pub fn with_network_requests_allowed(mut self, allowed: bool) -> Self {
218        self.network_requests_allowed = allowed;
219        self
220    }
221
222    /// Attaches a read-only capability view and returns the runtime-owned
223    /// retention decorator. Configure backend-specific options before attaching it.
224    #[must_use]
225    pub fn with_session_permissions(
226        mut self,
227        permissions: ProcessSessionPermissions,
228    ) -> SessionPermissionedProcessRunnerFactory<Self> {
229        self.session_permissions = Some(permissions.view());
230        permissions.with_factory(self)
231    }
232
233    fn requested_path_rules_for_request(
234        &self,
235        request: &PermissionRequest,
236        effective_rules: &[PathAccessRule],
237    ) -> Result<(Vec<PathAccessRule>, Vec<PathAccessRule>), ProcessRunnerError> {
238        let mut new_rules = Vec::new();
239        let mut action_required = Vec::new();
240        for capability in request.requested() {
241            let RequestedCapability::Path(requested) = capability else {
242                continue;
243            };
244            let path = materialize_requested_path(&self.cwd_root, requested.path());
245            let effective_access =
246                effective_requested_path_access(&path, requested.access(), effective_rules)?;
247            let rule = PathAccessRule::new(
248                path.clone(),
249                effective_access,
250                PathAccessRuleSource::PermissionReview,
251            );
252            action_required.push(rule.clone());
253            let needs_review = review::required(&self.path_rules, &path);
254            if needs_review || !path_rule_covers(effective_rules, &path, effective_access) {
255                new_rules.push(rule);
256            }
257        }
258        Ok((new_rules, action_required))
259    }
260
261    fn requested_host_integrations_for_request(
262        &self,
263        request: &PermissionRequest,
264    ) -> Vec<HostIntegration> {
265        request
266            .requested()
267            .iter()
268            .filter_map(|capability| match capability {
269                RequestedCapability::HostIntegration(integration) => Some(*integration),
270                _ => None,
271            })
272            .collect()
273    }
274
275    pub(super) fn build_runner(&self, request: &PermissionRequest) -> WorkspaceProcessRunner {
276        match self.prepare_runner(request) {
277            Ok((runner, _)) => runner,
278            Err(error) => {
279                let mut runner = WorkspaceProcessRunner::new_at_workspace_root(&self.cwd_root);
280                runner.configuration_error = Some(error.to_string());
281                runner.background = self.background.clone();
282                runner
283            }
284        }
285    }
286
287    fn prepare_runner(
288        &self,
289        request: &PermissionRequest,
290    ) -> Result<(WorkspaceProcessRunner, Vec<ProcessPathGrant>), ProcessRunnerError> {
291        self.validate_network_request(request)?;
292        let mut environment = self.environment.validate_for_workspace(&self.cwd_root)?;
293        let integrations = self.requested_host_integrations_for_request(request);
294        environment.validate_requested_host_integrations(&integrations)?;
295        let snapshot = self
296            .session_permissions
297            .as_ref()
298            .map(ProcessSessionPermissionView::snapshot)
299            .transpose()?
300            .unwrap_or_default();
301        let mut path_rules = self.path_rules.clone();
302        path_rules.extend(snapshot.path_rules().iter().cloned());
303        path_rules = normalize_path_rules(path_rules);
304        let (requested_rules, action_required_rules) =
305            self.requested_path_rules_for_request(request, &path_rules)?;
306        let grants = requested_rules
307            .iter()
308            .map(|rule| {
309                let constraint = if review::required(&self.path_rules, rule.path()) {
310                    ProcessPathGrantConstraint::ReviewRequired
311                } else if is_git_metadata_path(rule.path())
312                    || (rule.access() == PathAccess::ReadWrite
313                        && is_product_readonly_write_target(&self.path_rules, rule.path()))
314                {
315                    ProcessPathGrantConstraint::ProtectedMetadata
316                } else {
317                    ProcessPathGrantConstraint::Ordinary
318                };
319                ProcessPathGrant::new(
320                    PathAccessRule::new(
321                        resolve_host_path(rule.path()),
322                        rule.access(),
323                        rule.source(),
324                    ),
325                    constraint,
326                )
327            })
328            .collect();
329        path_rules.extend(requested_rules);
330        path_rules = normalize_path_rules(path_rules);
331        environment = environment
332            .with_host_integrations(integrations)
333            .with_host_integrations(snapshot.host_integrations().iter().copied());
334        let mut runner = WorkspaceProcessRunner::new_at_workspace_root(self.cwd_root.clone())
335            .with_environment(environment)
336            .with_path_rules(path_rules);
337        if !self.workspace_writable {
338            runner = runner.read_only_workspace();
339        }
340        if request.requests_network() {
341            runner = runner.allow_network();
342        }
343        runner.action_required_rules = action_required_rules;
344        runner.session_permissions = self.session_permissions.clone();
345        runner.background = self.background.clone();
346        runner.ensure_sandbox_rules()?;
347        Ok((runner, grants))
348    }
349
350    /// Enforces the capability ceiling before review, grants, or runner construction.
351    fn validate_network_request(
352        &self,
353        request: &PermissionRequest,
354    ) -> Result<(), ProcessRunnerError> {
355        if request.requests_network() && !self.network_requests_allowed {
356            return Err(ProcessRunnerError::infrastructure(
357                "network requests are disabled by the configured process capability ceiling",
358            ));
359        }
360        Ok(())
361    }
362}
363
364impl PermissionedProcessRunnerFactory for WorkspaceProcessRunnerFactory {
365    fn validate_request(&self, request: &PermissionRequest) -> Result<(), ProcessRunnerError> {
366        self.prepare_runner(request).map(|_| ())
367    }
368
369    fn request_capabilities_are_satisfied(
370        &self,
371        request: &PermissionRequest,
372    ) -> Result<bool, ProcessRunnerError> {
373        self.validate_network_request(request)?;
374        let environment = self.environment.validate_for_workspace(&self.cwd_root)?;
375        let snapshot = self
376            .session_permissions
377            .as_ref()
378            .map(ProcessSessionPermissionView::snapshot)
379            .transpose()?
380            .unwrap_or_default();
381
382        let requested_integrations = self.requested_host_integrations_for_request(request);
383        environment.validate_requested_host_integrations(&requested_integrations)?;
384        if request.requests_network() {
385            return Ok(false);
386        }
387
388        let mut available_integrations = environment.host_integrations.clone();
389        available_integrations.extend(snapshot.host_integrations().iter().copied());
390        available_integrations.sort_unstable();
391        available_integrations.dedup();
392        if requested_integrations
393            .iter()
394            .any(|integration| !available_integrations.contains(integration))
395        {
396            return Ok(false);
397        }
398
399        let mut rules = self.path_rules.clone();
400        rules.extend(snapshot.path_rules().iter().cloned());
401        let rules = normalize_path_rules(rules);
402        for capability in request.requested() {
403            let satisfied = match capability {
404                RequestedCapability::Network => false,
405                RequestedCapability::HostIntegration(_) => true,
406                RequestedCapability::Path(requested) => {
407                    let path = materialize_requested_path(&self.cwd_root, requested.path());
408                    !review::required(&self.path_rules, &path)
409                        && path_rule_covers(&rules, &path, requested.access())
410                }
411            };
412            if !satisfied {
413                return Ok(false);
414            }
415        }
416        Ok(true)
417    }
418
419    fn runner_for(&self, request: &PermissionRequest) -> Arc<dyn ProcessRunner> {
420        Arc::new(self.build_runner(request))
421    }
422
423    fn prepare_approved_request(
424        &self,
425        request: &PermissionRequest,
426    ) -> Result<PreparedProcessPermission, ProcessRunnerError> {
427        let (runner, grants) = self.prepare_runner(request)?;
428        Ok(PreparedProcessPermission::new(Arc::new(runner), grants))
429    }
430}
431
432fn materialize_requested_path(root: &Path, requested: &str) -> PathBuf {
433    let path = Path::new(requested);
434    if path.is_absolute() {
435        path.to_path_buf()
436    } else {
437        root.join(path)
438    }
439}
440
441fn effective_requested_path_access(
442    requested_path: &Path,
443    requested_access: PathAccess,
444    configured_rules: &[PathAccessRule],
445) -> Result<PathAccess, ProcessRunnerError> {
446    let requested_path = resolve_host_path(requested_path);
447    if let Some(rule) = effective_deny_rule(configured_rules, &requested_path) {
448        return Err(ProcessRunnerError::infrastructure(format!(
449            "requested path `{}` is denied by configured path policy `{}`",
450            requested_path.display(),
451            rule.path().display()
452        )));
453    }
454    if let Some(denied_child) = covers_denied_descendant(configured_rules, &requested_path) {
455        return Err(ProcessRunnerError::infrastructure(format!(
456            "requested path `{}` covers denied path `{}`; narrow the request so it excludes protected paths",
457            requested_path.display(),
458            denied_child.path().display()
459        )));
460    }
461    if let Some(review_child) = covers_review_descendant(configured_rules, &requested_path) {
462        return Err(ProcessRunnerError::infrastructure(format!(
463            "requested path `{}` covers review_paths entry `{}`; request access on `{}` directly or narrow the request",
464            requested_path.display(),
465            review_child.path().display(),
466            review_child.path().display()
467        )));
468    }
469    if requested_access == PathAccess::ReadWrite
470        && let Some(readonly_child) =
471            covers_protected_readonly_descendant(configured_rules, &requested_path)
472    {
473        return Err(ProcessRunnerError::infrastructure(format!(
474            "requested writable path `{}` covers Merry protected read-only path `{}`; request write access on `{}` directly or narrow the request",
475            requested_path.display(),
476            readonly_child.path().display(),
477            readonly_child.path().display()
478        )));
479    }
480
481    if is_trusted_global_read_only(configured_rules, &requested_path) {
482        // Explicit global read-only rules are a hard ceiling. Git metadata
483        // baselines and Merry's default `ProductReadOnly` directories are
484        // intentionally different: a reviewed action may temporarily overlay
485        // them directly, but the grant is never session-persistent.
486        return Ok(PathAccess::ReadOnly);
487    }
488
489    Ok(requested_access)
490}
491
492fn path_rule_covers(
493    rules: &[PathAccessRule],
494    requested_path: &Path,
495    requested_access: PathAccess,
496) -> bool {
497    if requested_access == PathAccess::Deny {
498        return false;
499    }
500    let resolved_target = resolve_host_path(requested_path);
501    if effective_deny_rule(rules, &resolved_target).is_some()
502        || covers_denied_descendant(rules, &resolved_target).is_some()
503        || covers_review_descendant(rules, &resolved_target).is_some()
504    {
505        return false;
506    }
507    if requested_access == PathAccess::ReadWrite
508        && (is_trusted_global_read_only(rules, &resolved_target)
509            || covers_protected_readonly_descendant(rules, &resolved_target).is_some())
510    {
511        return false;
512    }
513
514    rules
515        .iter()
516        .filter(|rule| {
517            path_matches_resolved(&resolved_target, rule.path())
518                && rule.access() != PathAccess::Deny
519        })
520        .max_by_key(|rule| resolved_path_depth(rule.path()))
521        .is_some_and(|rule| rule.access().covers(requested_access))
522}
523
524fn effective_deny_rule<'a>(
525    rules: &'a [PathAccessRule],
526    resolved_target: &Path,
527) -> Option<&'a PathAccessRule> {
528    let deny_rule = deepest_matching_rule(rules, resolved_target, |rule| {
529        rule.access() == PathAccess::Deny
530    })?;
531    let deny_depth = resolved_path_depth(deny_rule.path());
532    let ro_depth = deepest_matching_rule(rules, resolved_target, |rule| {
533        rule.access() == PathAccess::ReadOnly
534            && rule.source() == PathAccessRuleSource::ProductReadOnly
535    })
536    .map(|rule| resolved_path_depth(rule.path()));
537    (!matches!(ro_depth, Some(depth) if depth > deny_depth)).then_some(deny_rule)
538}
539
540fn covers_denied_descendant<'a>(
541    rules: &'a [PathAccessRule],
542    resolved_target: &Path,
543) -> Option<&'a PathAccessRule> {
544    strict_descendant_rule(
545        rules,
546        resolved_target,
547        |rule| rule.access() == PathAccess::Deny,
548        |_| true,
549    )
550}
551
552fn covers_review_descendant<'a>(
553    rules: &'a [PathAccessRule],
554    resolved_target: &Path,
555) -> Option<&'a PathAccessRule> {
556    strict_descendant_rule(
557        rules,
558        resolved_target,
559        PathAccessRule::review_required,
560        |_| true,
561    )
562}
563
564fn covers_protected_readonly_descendant<'a>(
565    rules: &'a [PathAccessRule],
566    resolved_target: &Path,
567) -> Option<&'a PathAccessRule> {
568    strict_descendant_rule(
569        rules,
570        resolved_target,
571        |rule| {
572            rule.access() == PathAccess::ReadOnly
573                && rule.source() == PathAccessRuleSource::ProductReadOnly
574        },
575        |rule_path| !is_explicitly_writable_by_trusted_config(rules, rule_path),
576    )
577}
578
579fn strict_descendant_rule<'a>(
580    rules: &'a [PathAccessRule],
581    resolved_target: &Path,
582    matches_rule: impl Fn(&PathAccessRule) -> bool,
583    matches_resolved: impl Fn(&Path) -> bool,
584) -> Option<&'a PathAccessRule> {
585    rules.iter().find(|rule| {
586        if !matches_rule(rule) {
587            return false;
588        }
589        let rule_path = resolve_host_path(rule.path());
590        rule_path != resolved_target
591            && rule_path.starts_with(resolved_target)
592            && matches_resolved(&rule_path)
593    })
594}
595
596fn is_trusted_global_read_only(rules: &[PathAccessRule], resolved_target: &Path) -> bool {
597    rules.iter().any(|rule| {
598        path_matches_resolved(resolved_target, rule.path())
599            && rule.access() == PathAccess::ReadOnly
600            && rule.source() == PathAccessRuleSource::TrustedGlobalConfig
601    })
602}
603
604fn is_explicitly_writable_by_trusted_config(
605    rules: &[PathAccessRule],
606    resolved_target: &Path,
607) -> bool {
608    rules.iter().any(|rule| {
609        path_matches_resolved(resolved_target, rule.path())
610            && rule.access() == PathAccess::ReadWrite
611            && rule.source() == PathAccessRuleSource::TrustedGlobalConfig
612    })
613}
614
615fn is_product_readonly_write_target(rules: &[PathAccessRule], requested_path: &Path) -> bool {
616    let resolved_target = resolve_host_path(requested_path);
617    let Some(ro_rule) = deepest_matching_rule(rules, &resolved_target, |rule| {
618        rule.access() == PathAccess::ReadOnly
619            && rule.source() == PathAccessRuleSource::ProductReadOnly
620    }) else {
621        return false;
622    };
623    let ro_depth = resolved_path_depth(ro_rule.path());
624    let writable_override_depth = deepest_matching_rule(rules, &resolved_target, |rule| {
625        rule.access() == PathAccess::ReadWrite
626            && matches!(
627                rule.source(),
628                PathAccessRuleSource::TrustedGlobalConfig
629                    | PathAccessRuleSource::DurableMemory
630                    | PathAccessRuleSource::ProductConfig
631            )
632    })
633    .map(|rule| resolved_path_depth(rule.path()));
634    let writable_beats_ro = matches!(
635        writable_override_depth,
636        Some(depth)
637            if depth > ro_depth
638                || (depth == ro_depth
639                    && is_explicitly_writable_by_trusted_config(rules, &resolved_target))
640    );
641    !writable_beats_ro
642}
643
644fn deepest_matching_rule<'a>(
645    rules: &'a [PathAccessRule],
646    resolved_target: &Path,
647    predicate: impl Fn(&PathAccessRule) -> bool,
648) -> Option<&'a PathAccessRule> {
649    rules
650        .iter()
651        .filter(|rule| predicate(rule) && path_matches_resolved(resolved_target, rule.path()))
652        .max_by_key(|rule| resolved_path_depth(rule.path()))
653}
654
655fn path_matches_resolved(resolved_target: &Path, rule_path: &Path) -> bool {
656    let rule_path = resolve_host_path(rule_path);
657    resolved_target == rule_path || resolved_target.starts_with(&rule_path)
658}
659
660fn normalize_path_rules(rules: Vec<PathAccessRule>) -> Vec<PathAccessRule> {
661    let has_review = rules.iter().any(PathAccessRule::review_required);
662    let mut action_rules = Vec::new();
663    let mut merged =
664        std::collections::BTreeMap::<PathBuf, (PathAccess, PathAccessRuleSource)>::new();
665    for rule in rules {
666        if rule.review_required()
667            || (has_review && rule.source() == PathAccessRuleSource::PermissionReview)
668        {
669            action_rules.push(rule);
670            continue;
671        }
672        let access = rule.access();
673        let key = resolve_host_path(rule.path());
674        let entry = merged.entry(key).or_insert((access, rule.source()));
675        (entry.0, entry.1) = merged_path_rule(entry.0, entry.1, access, rule.source());
676    }
677    let mut rules = merged
678        .into_iter()
679        .map(|(path, (access, source))| PathAccessRule::new(path, access, source))
680        .collect::<Vec<_>>();
681    rules.extend(action_rules);
682    rules.sort_by(|left, right| {
683        path_depth(left.path())
684            .cmp(&path_depth(right.path()))
685            .then_with(|| left.path().cmp(right.path()))
686    });
687    rules
688}
689
690fn merged_path_rule(
691    left_access: PathAccess,
692    left_source: PathAccessRuleSource,
693    right_access: PathAccess,
694    right_source: PathAccessRuleSource,
695) -> (PathAccess, PathAccessRuleSource) {
696    if left_access == PathAccess::Deny {
697        return (left_access, left_source);
698    }
699    if right_access == PathAccess::Deny {
700        return (right_access, right_source);
701    }
702
703    let left_is_hard_read_only = left_access == PathAccess::ReadOnly
704        && left_source == PathAccessRuleSource::TrustedGlobalConfig;
705    let right_is_hard_read_only = right_access == PathAccess::ReadOnly
706        && right_source == PathAccessRuleSource::TrustedGlobalConfig;
707    if left_is_hard_read_only {
708        return (left_access, left_source);
709    }
710    if right_is_hard_read_only {
711        return (right_access, right_source);
712    }
713
714    let left_is_reviewed_write = left_access == PathAccess::ReadWrite
715        && left_source == PathAccessRuleSource::PermissionReview;
716    let right_is_reviewed_write = right_access == PathAccess::ReadWrite
717        && right_source == PathAccessRuleSource::PermissionReview;
718    if left_is_reviewed_write {
719        return (left_access, left_source);
720    }
721    if right_is_reviewed_write {
722        return (right_access, right_source);
723    }
724
725    match (left_access, right_access) {
726        (PathAccess::ReadWrite, _) => (left_access, left_source),
727        (_, PathAccess::ReadWrite) => (right_access, right_source),
728        _ => (PathAccess::ReadOnly, left_source),
729    }
730}
731
732pub(super) fn is_git_metadata_path(path: &Path) -> bool {
733    resolve_host_path(path)
734        .components()
735        .any(|component| matches!(component, Component::Normal(name) if name == OsStr::new(".git")))
736}
737
738fn resolved_path_depth(path: &Path) -> usize {
739    path_depth(&resolve_host_path(path))
740}
741
742fn path_depth(path: &Path) -> usize {
743    path.components().count()
744}