use crate::{
ChildWorkspacePolicyOverride, PathAccess, PathAccessRule, PathAccessRuleSource,
ProcessSessionPermissionSnapshot, ProcessSessionPermissionView,
};
use merry_core::HostPathPolicy;
use std::{
fs,
path::{Component, Path, PathBuf},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathAccessDecision {
Allow,
RequireReview,
Deny,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathDenialReason {
UserHardDeny,
UserReadOnlyCeiling,
ReadOnlyWorkspace,
CoversDeniedDescendant,
CoversProtectedReadOnlyDescendant,
InvalidAccess,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PathEvaluation {
pub decision: PathAccessDecision,
pub protected_target: bool,
pub git_metadata: bool,
pub denial_reason: Option<PathDenialReason>,
}
impl PathEvaluation {
#[must_use]
pub(crate) const fn allow(git_metadata: bool) -> Self {
Self {
decision: PathAccessDecision::Allow,
protected_target: false,
git_metadata,
denial_reason: None,
}
}
#[must_use]
pub(crate) const fn require_review(git_metadata: bool) -> Self {
Self {
decision: PathAccessDecision::RequireReview,
protected_target: false,
git_metadata,
denial_reason: None,
}
}
#[must_use]
pub(crate) const fn deny(reason: PathDenialReason, git_metadata: bool) -> Self {
Self {
decision: PathAccessDecision::Deny,
protected_target: false,
git_metadata,
denial_reason: Some(reason),
}
}
#[must_use]
pub(crate) const fn protected(decision: PathAccessDecision, git_metadata: bool) -> Self {
Self {
decision,
protected_target: true,
git_metadata,
denial_reason: None,
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct ResolvedPathRule {
pub(crate) resolved: PathBuf,
pub(crate) depth: usize,
pub(crate) access: PathAccess,
pub(crate) source: PathAccessRuleSource,
}
impl ResolvedPathRule {
pub(crate) fn from_rule(rule: &PathAccessRule) -> Self {
let resolved = resolve_rule_path(rule.path());
let depth = resolved.components().count();
Self {
resolved,
depth,
access: rule.access(),
source: rule.source(),
}
}
}
#[derive(Debug, Clone)]
pub struct WorkspaceAccessPolicy {
workspace_root: PathBuf,
workspace_root_canonical: PathBuf,
workspace_writable: bool,
static_rules: Vec<ResolvedPathRule>,
session_permissions: Option<ProcessSessionPermissionView>,
}
impl WorkspaceAccessPolicy {
#[must_use]
pub fn new(workspace_root: impl Into<PathBuf>, workspace_writable: bool) -> Self {
let workspace_root = normalize_path_lexically(&workspace_root.into());
let workspace_root_canonical = resolve_path_with_existing_ancestor(&workspace_root);
Self {
workspace_root,
workspace_root_canonical,
workspace_writable,
static_rules: Vec::new(),
session_permissions: None,
}
}
#[must_use]
pub fn with_static_rules(mut self, rules: impl IntoIterator<Item = PathAccessRule>) -> Self {
self.static_rules = rules
.into_iter()
.map(|rule| ResolvedPathRule::from_rule(&rule))
.collect();
self
}
#[must_use]
pub fn with_session_permissions(mut self, view: ProcessSessionPermissionView) -> Self {
self.session_permissions = Some(view);
self
}
#[must_use]
pub fn workspace_root(&self) -> &Path {
&self.workspace_root
}
#[must_use]
pub const fn workspace_writable(&self) -> bool {
self.workspace_writable
}
#[must_use]
pub fn product_private_paths(&self) -> Vec<PathBuf> {
self.static_rules
.iter()
.filter(|entry| {
entry.access == PathAccess::Deny
&& entry.source == PathAccessRuleSource::ProductPrivate
})
.map(|entry| entry.resolved.clone())
.collect()
}
#[must_use]
pub fn evaluate_read(&self, path: &Path, once_grants: &[PathAccessRule]) -> PathAccessDecision {
let snapshot = self
.session_permissions
.as_ref()
.and_then(|view| view.snapshot().ok());
self.evaluate_path(path, PathAccess::ReadOnly, snapshot.as_ref(), once_grants)
.decision
}
#[must_use]
pub fn evaluate_write(
&self,
path: &Path,
once_grants: &[PathAccessRule],
) -> PathAccessDecision {
let snapshot = self
.session_permissions
.as_ref()
.and_then(|view| view.snapshot().ok());
self.evaluate_path(path, PathAccess::ReadWrite, snapshot.as_ref(), once_grants)
.decision
}
#[must_use]
pub fn evaluate_path(
&self,
path: &Path,
requested: PathAccess,
session: Option<&ProcessSessionPermissionSnapshot>,
once_grants: &[PathAccessRule],
) -> PathEvaluation {
self.evaluate_inner(None, path, requested, session, once_grants, false)
}
#[must_use]
pub(crate) fn evaluate_with_child_override(
&self,
child: Option<&ChildWorkspacePolicyOverride>,
path: &Path,
requested: PathAccess,
session: Option<&ProcessSessionPermissionSnapshot>,
once_grants: &[PathAccessRule],
) -> PathEvaluation {
self.evaluate_inner(child, path, requested, session, once_grants, false)
}
#[must_use]
pub fn evaluate_directory_grant(
&self,
path: &Path,
requested: PathAccess,
session: Option<&ProcessSessionPermissionSnapshot>,
once_grants: &[PathAccessRule],
) -> PathEvaluation {
self.evaluate_inner(None, path, requested, session, once_grants, true)
}
#[must_use]
pub fn explicit_rules_cover(
&self,
path: &Path,
requested: PathAccess,
session: Option<&ProcessSessionPermissionSnapshot>,
) -> bool {
let eval = self.evaluate_directory_grant(path, requested, session, &[]);
if eval.decision != PathAccessDecision::Allow {
return false;
}
let resolved = resolve_rule_path(path);
let session_rules = session
.map(ProcessSessionPermissionSnapshot::path_rules)
.unwrap_or(&[]);
resolved_and_dynamic_rules_cover_path(
self.static_rules.iter(),
session_rules.iter(),
&resolved,
requested,
)
}
#[must_use]
pub fn is_protected_target(&self, path: &Path, requested: PathAccess) -> bool {
let resolved = resolve_rule_path(path);
requires_built_in_product_review(&self.static_rules, &[], &resolved, requested)
}
#[must_use]
pub fn blocking_rule_path(&self, path: &Path, requested: PathAccess) -> Option<PathBuf> {
let resolved = resolve_rule_path(path);
if let Some(rule_path) = effective_user_hard_deny_path(&self.static_rules, &[], &resolved) {
return Some(rule_path);
}
if let Some(child_path) = covered_denied_descendant_path(&self.static_rules, &[], &resolved)
{
return Some(child_path);
}
if requested == PathAccess::ReadWrite
&& let Some(child_path) =
covered_protected_readonly_descendant_path(&self.static_rules, &[], &resolved)
{
return Some(child_path);
}
None
}
fn evaluate_inner(
&self,
child: Option<&ChildWorkspacePolicyOverride>,
path: &Path,
requested: PathAccess,
session: Option<&ProcessSessionPermissionSnapshot>,
once_grants: &[PathAccessRule],
check_descendants: bool,
) -> PathEvaluation {
let lexical = normalize_path_lexically(path);
let resolved = resolve_path_with_existing_ancestor(&lexical);
let git_metadata = is_git_metadata_path_parts(&lexical, &resolved);
if requested == PathAccess::Deny {
return PathEvaluation::deny(PathDenialReason::InvalidAccess, git_metadata);
}
let (effective_root, effective_writable, extra_rules) = match child {
Some(override_cfg) => (
override_cfg
.workspace_root_canonical()
.unwrap_or(&self.workspace_root_canonical),
self.workspace_writable && override_cfg.workspace_writable(),
override_cfg.extra_resolved_rules(),
),
None => (
self.workspace_root_canonical.as_path(),
self.workspace_writable,
&[][..],
),
};
let in_workspace = path_within(&resolved, effective_root);
if let Some(reason) = user_hard_ceiling_reason(
&self.static_rules,
extra_rules,
&resolved,
requested,
in_workspace,
effective_writable,
effective_root.components().count(),
) {
return PathEvaluation::deny(reason, git_metadata);
}
if check_descendants {
if covered_denied_descendant_path(&self.static_rules, extra_rules, &resolved).is_some()
{
return PathEvaluation::deny(
PathDenialReason::CoversDeniedDescendant,
git_metadata,
);
}
if requested == PathAccess::ReadWrite
&& covered_protected_readonly_descendant_path(
&self.static_rules,
extra_rules,
&resolved,
)
.is_some()
{
return PathEvaluation::deny(
PathDenialReason::CoversProtectedReadOnlyDescendant,
git_metadata,
);
}
}
if requires_built_in_product_review(&self.static_rules, extra_rules, &resolved, requested) {
let decision = if dynamic_rules_cover_path(once_grants.iter(), &resolved, requested) {
PathAccessDecision::Allow
} else {
PathAccessDecision::RequireReview
};
return PathEvaluation::protected(decision, git_metadata);
}
if in_workspace && !(requested == PathAccess::ReadWrite && git_metadata) {
return match requested {
PathAccess::ReadOnly => PathEvaluation::allow(git_metadata),
PathAccess::ReadWrite if effective_writable => PathEvaluation::allow(git_metadata),
PathAccess::ReadWrite | PathAccess::Deny => {
PathEvaluation::deny(PathDenialReason::ReadOnlyWorkspace, git_metadata)
}
};
}
let session_rules = session
.map(ProcessSessionPermissionSnapshot::path_rules)
.unwrap_or(&[]);
if resolved_and_dynamic_rules_cover_path(
self.static_rules.iter().chain(extra_rules.iter()),
once_grants.iter().chain(session_rules.iter()),
&resolved,
requested,
) {
PathEvaluation::allow(git_metadata)
} else {
PathEvaluation::require_review(git_metadata)
}
}
}
fn chained_rules<'a>(
base: &'a [ResolvedPathRule],
extra: &'a [ResolvedPathRule],
) -> impl Iterator<Item = &'a ResolvedPathRule> + Clone {
base.iter().chain(extra.iter())
}
fn effective_user_hard_deny_path(
base: &[ResolvedPathRule],
extra: &[ResolvedPathRule],
resolved: &Path,
) -> Option<PathBuf> {
chained_rules(base, extra)
.filter(|entry| {
entry.access == PathAccess::Deny && entry.source != PathAccessRuleSource::ProductPrivate
})
.filter(|entry| path_within(resolved, &entry.resolved))
.max_by_key(|entry| entry.depth)
.map(|entry| entry.resolved.clone())
}
fn user_hard_ceiling_reason(
base: &[ResolvedPathRule],
extra: &[ResolvedPathRule],
resolved: &Path,
requested: PathAccess,
in_workspace: bool,
workspace_writable: bool,
workspace_depth: usize,
) -> Option<PathDenialReason> {
if effective_user_hard_deny_path(base, extra, resolved).is_some() {
return Some(PathDenialReason::UserHardDeny);
}
if requested == PathAccess::ReadWrite {
let deepest_trusted_ro_depth = chained_rules(base, extra)
.filter(|entry| {
entry.access == PathAccess::ReadOnly
&& entry.source == PathAccessRuleSource::TrustedGlobalConfig
&& path_within(resolved, &entry.resolved)
})
.map(|entry| entry.depth)
.max();
if let Some(ro_depth) = deepest_trusted_ro_depth {
let deeper_writable_workspace =
in_workspace && workspace_writable && workspace_depth > ro_depth;
let deeper_trusted_rw = chained_rules(base, extra).any(|entry| {
entry.access == PathAccess::ReadWrite
&& entry.source == PathAccessRuleSource::TrustedGlobalConfig
&& entry.depth > ro_depth
&& path_within(resolved, &entry.resolved)
});
if !deeper_writable_workspace && !deeper_trusted_rw {
return Some(PathDenialReason::UserReadOnlyCeiling);
}
}
}
None
}
fn covered_denied_descendant_path(
base: &[ResolvedPathRule],
extra: &[ResolvedPathRule],
resolved: &Path,
) -> Option<PathBuf> {
chained_rules(base, extra)
.filter(|entry| entry.access == PathAccess::Deny)
.find_map(|entry| {
(entry.resolved != resolved && entry.resolved.starts_with(resolved))
.then(|| entry.resolved.clone())
})
}
fn trusted_global_rw_overrides_product_ro<'a>(
mut rules: impl Iterator<Item = &'a ResolvedPathRule>,
target: &Path,
ro_depth: usize,
) -> bool {
rules.any(|entry| {
entry.access == PathAccess::ReadWrite
&& entry.source == PathAccessRuleSource::TrustedGlobalConfig
&& entry.depth >= ro_depth
&& path_within(target, &entry.resolved)
})
}
fn covered_protected_readonly_descendant_path(
base: &[ResolvedPathRule],
extra: &[ResolvedPathRule],
resolved: &Path,
) -> Option<PathBuf> {
let rules = chained_rules(base, extra);
rules
.clone()
.filter(|entry| {
entry.access == PathAccess::ReadOnly
&& entry.source == PathAccessRuleSource::ProductReadOnly
})
.find_map(|entry| {
let covered = entry.resolved != resolved && entry.resolved.starts_with(resolved);
if !covered {
return None;
}
let explicitly_writable =
trusted_global_rw_overrides_product_ro(rules.clone(), &entry.resolved, entry.depth);
(!explicitly_writable).then(|| entry.resolved.clone())
})
}
fn requires_built_in_product_review(
base: &[ResolvedPathRule],
extra: &[ResolvedPathRule],
resolved: &Path,
requested: PathAccess,
) -> bool {
let rules = chained_rules(base, extra);
let deepest_private_depth = rules
.clone()
.filter(|entry| {
entry.access == PathAccess::Deny
&& entry.source == PathAccessRuleSource::ProductPrivate
&& path_within(resolved, &entry.resolved)
})
.map(|entry| entry.depth)
.max();
if let Some(private_depth) = deepest_private_depth {
let deeper_product_ro = requested == PathAccess::ReadOnly
&& rules.clone().any(|entry| {
entry.access == PathAccess::ReadOnly
&& entry.source == PathAccessRuleSource::ProductReadOnly
&& entry.depth > private_depth
&& path_within(resolved, &entry.resolved)
});
if !deeper_product_ro {
return true;
}
}
if requested == PathAccess::ReadWrite {
let deepest_product_ro_depth = rules
.clone()
.filter(|entry| {
entry.access == PathAccess::ReadOnly
&& entry.source == PathAccessRuleSource::ProductReadOnly
&& path_within(resolved, &entry.resolved)
})
.map(|entry| entry.depth)
.max();
if let Some(ro_depth) = deepest_product_ro_depth {
let writable_beats_ro =
trusted_global_rw_overrides_product_ro(rules.clone(), resolved, ro_depth)
|| rules.clone().any(|entry| {
entry.access == PathAccess::ReadWrite
&& matches!(
entry.source,
PathAccessRuleSource::ProductConfig
| PathAccessRuleSource::DurableMemory
)
&& entry.depth > ro_depth
&& path_within(resolved, &entry.resolved)
});
if !writable_beats_ro {
return true;
}
}
}
false
}
#[must_use]
pub fn extract_product_private_paths(rules: &[PathAccessRule]) -> Vec<PathBuf> {
rules
.iter()
.filter(|rule| {
rule.access() == PathAccess::Deny
&& rule.source() == PathAccessRuleSource::ProductPrivate
})
.map(|rule| resolve_rule_path(rule.path()))
.collect()
}
#[must_use]
pub fn once_grants_cover_path(
once_grants: &[PathAccessRule],
path: &Path,
requested: PathAccess,
) -> bool {
let resolved = resolve_rule_path(path);
dynamic_rules_cover_path(once_grants.iter(), &resolved, requested)
}
#[must_use]
pub fn is_protected_in_unrestricted_mode(product_private_paths: &[PathBuf], path: &Path) -> bool {
let lexical = normalize_path_lexically(path);
let resolved = resolve_path_with_existing_ancestor(&lexical);
product_private_paths.iter().any(|private| {
let resolved_private = resolve_rule_path(private);
path_overlaps(&resolved, &resolved_private) || path_overlaps(&lexical, &resolved_private)
})
}
#[must_use]
pub fn is_protected_host_path_for_persistence(
path: &Path,
access: PathAccess,
policy: &HostPathPolicy,
) -> bool {
let lexical = normalize_path_lexically(path);
let resolved = resolve_path_with_existing_ancestor(&lexical);
for denied in policy.denied() {
let resolved_denied = resolve_rule_path(denied);
if path_overlaps(&resolved, &resolved_denied) || path_overlaps(&lexical, &resolved_denied) {
return true;
}
}
if access == PathAccess::ReadWrite {
for ro in policy.product_readonly() {
let resolved_ro = resolve_rule_path(ro);
if !(path_overlaps(&resolved, &resolved_ro) || path_overlaps(&lexical, &resolved_ro)) {
continue;
}
let ro_depth = resolved_ro.components().count();
let deeper_writable = policy
.product_writable_config()
.iter()
.map(PathBuf::as_path)
.chain(policy.durable_memory_root())
.any(|writable| {
let resolved_writable = resolve_rule_path(writable);
path_within(&resolved, &resolved_writable)
&& resolved_writable.components().count() > ro_depth
});
if !deeper_writable {
return true;
}
}
}
false
}
#[must_use]
pub fn is_git_metadata_path(path: &Path) -> bool {
let lexical = normalize_path_lexically(path);
let resolved = resolve_path_with_existing_ancestor(&lexical);
is_git_metadata_path_parts(&lexical, &resolved)
}
fn is_git_metadata_path_parts(lexical: &Path, resolved: &Path) -> bool {
has_git_component(lexical) || has_git_component(resolved)
}
fn has_git_component(path: &Path) -> bool {
path.components()
.any(|component| matches!(component, Component::Normal(name) if name == ".git"))
}
fn update_best_match(
best_match: &mut Option<(usize, PathAccess, PathAccessRuleSource)>,
depth: usize,
access: PathAccess,
source: PathAccessRuleSource,
) {
let should_replace = match *best_match {
None => true,
Some((best_depth, best_access, best_source)) => {
depth > best_depth
|| (depth == best_depth
&& precedence(access, source) > precedence(best_access, best_source))
}
};
if should_replace {
*best_match = Some((depth, access, source));
}
}
fn dynamic_rules_cover_path<'a>(
rules: impl IntoIterator<Item = &'a PathAccessRule>,
resolved: &Path,
requested: PathAccess,
) -> bool {
resolved_and_dynamic_rules_cover_path(std::iter::empty(), rules, resolved, requested)
}
fn resolved_and_dynamic_rules_cover_path<'a>(
static_rules: impl IntoIterator<Item = &'a ResolvedPathRule>,
dynamic_rules: impl IntoIterator<Item = &'a PathAccessRule>,
resolved: &Path,
requested: PathAccess,
) -> bool {
let mut best_match: Option<(usize, PathAccess, PathAccessRuleSource)> = None;
for entry in static_rules {
if path_within(resolved, &entry.resolved) {
update_best_match(&mut best_match, entry.depth, entry.access, entry.source);
}
}
for rule in dynamic_rules {
let rule_resolved = resolve_rule_path(rule.path());
if path_within(resolved, &rule_resolved) {
update_best_match(
&mut best_match,
rule_resolved.components().count(),
rule.access(),
rule.source(),
);
}
}
best_match.is_some_and(|(_, access, _)| access.covers(requested))
}
pub(crate) fn resolve_rule_path(path: &Path) -> PathBuf {
resolve_path_with_existing_ancestor(&normalize_path_lexically(path))
}
fn precedence(access: PathAccess, source: PathAccessRuleSource) -> u8 {
if access == PathAccess::Deny {
return 4;
}
if access == PathAccess::ReadOnly && source == PathAccessRuleSource::TrustedGlobalConfig {
return 3;
}
if access == PathAccess::ReadWrite {
return 2;
}
1
}
fn path_within(target: &Path, root: &Path) -> bool {
target == root || target.starts_with(root)
}
fn path_overlaps(left: &Path, right: &Path) -> bool {
left == right || left.starts_with(right) || right.starts_with(left)
}
#[must_use]
pub fn resolve_path_with_existing_ancestor(path: &Path) -> PathBuf {
let lexical = normalize_path_lexically(path);
if let Ok(canonical) = fs::canonicalize(&lexical) {
return merry_core::host_paths::simplify_verbatim_path(&canonical);
}
let mut suffix = Vec::new();
let mut current = lexical.as_path();
while let Some(parent) = current.parent() {
if let Some(name) = current.file_name() {
suffix.push(name.to_os_string());
}
if let Ok(canonical_parent) = fs::canonicalize(parent) {
let mut resolved = merry_core::host_paths::simplify_verbatim_path(&canonical_parent);
for part in suffix.into_iter().rev() {
resolved.push(part);
}
return resolved;
}
current = parent;
}
lexical
}
#[must_use]
pub fn normalize_path_lexically(path: &Path) -> PathBuf {
let mut normalized = PathBuf::new();
let is_absolute = path.is_absolute();
for component in path.components() {
match component {
Component::Prefix(prefix) => normalized.push(prefix.as_os_str()),
Component::RootDir => normalized.push(component.as_os_str()),
Component::CurDir => {}
Component::ParentDir => {
if !normalized.pop() && !is_absolute {
normalized.push("..");
}
}
Component::Normal(part) => normalized.push(part),
}
}
normalized
}
#[cfg(test)]
#[path = "access_policy_tests.rs"]
mod tests;