use crate::{
NetworkAccessDecision, NetworkAccessPolicy, PathAccess, PathAccessDecision, PathAccessRule,
PathDenialReason, PathEvaluation, ProcessSessionPermissionSnapshot,
ProcessSessionPermissionView, WorkspaceAccessPolicy,
access_policy::{ResolvedPathRule, resolve_rule_path},
is_protected_in_unrestricted_mode,
};
use std::{
path::{Path, PathBuf},
sync::{Arc, RwLock},
};
#[derive(Debug, Clone)]
pub struct LivePolicyBaseline {
restricted: bool,
workspace_access: Option<WorkspaceAccessPolicy>,
product_private_paths: Vec<PathBuf>,
network_access: NetworkAccessPolicy,
}
impl LivePolicyBaseline {
#[must_use]
pub fn new(
restricted: bool,
workspace_access: Option<WorkspaceAccessPolicy>,
product_private_paths: Vec<PathBuf>,
network_access: NetworkAccessPolicy,
) -> Self {
Self {
restricted,
workspace_access,
product_private_paths,
network_access,
}
}
#[must_use]
pub const fn is_restricted(&self) -> bool {
self.restricted
}
#[must_use]
pub fn workspace_access(&self) -> Option<&WorkspaceAccessPolicy> {
self.workspace_access.as_ref()
}
#[must_use]
pub fn product_private_paths(&self) -> &[PathBuf] {
&self.product_private_paths
}
#[must_use]
pub fn network_access(&self) -> &NetworkAccessPolicy {
&self.network_access
}
}
#[derive(Debug, Clone)]
pub struct ChildWorkspacePolicyOverride {
workspace_root_canonical: Option<PathBuf>,
workspace_writable: bool,
extra_resolved_rules: Vec<ResolvedPathRule>,
}
impl ChildWorkspacePolicyOverride {
#[must_use]
pub fn new(workspace_writable: bool) -> Self {
Self {
workspace_root_canonical: None,
workspace_writable,
extra_resolved_rules: Vec::new(),
}
}
#[must_use]
pub fn with_workspace_root(mut self, root: impl Into<PathBuf>) -> Self {
self.workspace_root_canonical = Some(resolve_rule_path(&root.into()));
self
}
#[must_use]
pub fn with_extra_path_rules(
mut self,
rules: impl IntoIterator<Item = PathAccessRule>,
) -> Self {
self.extra_resolved_rules = rules
.into_iter()
.map(|rule| ResolvedPathRule::from_rule(&rule))
.collect();
self
}
#[must_use]
pub(crate) fn workspace_root_canonical(&self) -> Option<&Path> {
self.workspace_root_canonical.as_deref()
}
#[must_use]
pub const fn workspace_writable(&self) -> bool {
self.workspace_writable
}
#[must_use]
pub(crate) fn extra_resolved_rules(&self) -> &[ResolvedPathRule] {
&self.extra_resolved_rules
}
}
#[derive(Debug, Clone)]
pub struct LivePolicyHandle {
baseline: Arc<RwLock<Arc<LivePolicyBaseline>>>,
session_permissions: Option<ProcessSessionPermissionView>,
child_override: Option<Arc<ChildWorkspacePolicyOverride>>,
}
impl LivePolicyHandle {
#[must_use]
pub fn new(baseline: LivePolicyBaseline) -> Self {
Self {
baseline: Arc::new(RwLock::new(Arc::new(baseline))),
session_permissions: None,
child_override: None,
}
}
#[must_use]
pub fn for_workspace(policy: Option<WorkspaceAccessPolicy>) -> Self {
let product_private_paths = policy
.as_ref()
.map(WorkspaceAccessPolicy::product_private_paths)
.unwrap_or_default();
Self::new(LivePolicyBaseline::new(
policy.is_some(),
policy,
product_private_paths,
NetworkAccessPolicy::default(),
))
}
#[must_use]
pub fn for_network(policy: NetworkAccessPolicy) -> Self {
let session_view = policy.session_permissions_view();
let mut handle = Self::new(LivePolicyBaseline::new(false, None, Vec::new(), policy));
if let Some(view) = session_view {
handle = handle.with_session_permissions(view);
}
handle
}
#[must_use]
pub fn with_session_permissions(mut self, view: ProcessSessionPermissionView) -> Self {
self.session_permissions = Some(view);
self
}
#[must_use]
pub fn for_child(
&self,
session_permissions: Option<ProcessSessionPermissionView>,
child_override: Option<ChildWorkspacePolicyOverride>,
) -> Self {
Self {
baseline: Arc::clone(&self.baseline),
session_permissions,
child_override: child_override.map(Arc::new),
}
}
#[must_use]
pub fn baseline_snapshot(&self) -> Arc<LivePolicyBaseline> {
Arc::clone(
&self
.baseline
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner),
)
}
pub fn replace_baseline(&self, next: LivePolicyBaseline) {
*self
.baseline
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::new(next);
}
#[must_use]
pub fn is_restricted(&self) -> bool {
self.baseline_snapshot().restricted
}
#[must_use]
pub fn workspace_writable(&self) -> bool {
let baseline = self.baseline_snapshot();
let child_writable = self
.child_override
.as_ref()
.is_none_or(|override_cfg| override_cfg.workspace_writable);
if !baseline.restricted {
return child_writable;
}
let parent_writable = baseline
.workspace_access
.as_ref()
.is_none_or(WorkspaceAccessPolicy::workspace_writable);
parent_writable && child_writable
}
#[must_use]
pub fn network_allow_local(&self) -> bool {
self.baseline_snapshot().network_access.allow_local()
}
#[must_use]
pub fn product_private_paths(&self) -> Vec<PathBuf> {
self.baseline_snapshot().product_private_paths.clone()
}
#[must_use]
pub fn evaluate_read(&self, path: &Path, once_grants: &[PathAccessRule]) -> PathEvaluation {
self.evaluate_path(path, PathAccess::ReadOnly, once_grants)
}
#[must_use]
pub fn evaluate_write(&self, path: &Path, once_grants: &[PathAccessRule]) -> PathEvaluation {
self.evaluate_path(path, PathAccess::ReadWrite, once_grants)
}
#[must_use]
pub fn evaluate_path(
&self,
path: &Path,
requested: PathAccess,
once_grants: &[PathAccessRule],
) -> PathEvaluation {
let baseline = self.baseline_snapshot();
if !baseline.restricted {
let git_metadata = crate::is_git_metadata_path(path);
if is_protected_in_unrestricted_mode(&baseline.product_private_paths, path) {
let decision =
if crate::access_policy::once_grants_cover_path(once_grants, path, requested) {
PathAccessDecision::Allow
} else {
PathAccessDecision::RequireReview
};
return PathEvaluation::protected(decision, git_metadata);
}
if requested == PathAccess::ReadWrite
&& self
.child_override
.as_ref()
.is_some_and(|override_cfg| !override_cfg.workspace_writable)
{
return PathEvaluation::deny(PathDenialReason::ReadOnlyWorkspace, git_metadata);
}
return PathEvaluation::allow(git_metadata);
}
let Some(base_policy) = baseline.workspace_access.as_ref() else {
return PathEvaluation::allow(crate::is_git_metadata_path(path));
};
let session = self.session_snapshot();
base_policy.evaluate_with_child_override(
self.child_override.as_deref(),
path,
requested,
session.as_ref(),
once_grants,
)
}
#[must_use]
pub fn evaluate_network_host(
&self,
host: &str,
once_domains: &[String],
) -> NetworkAccessDecision {
let baseline = self.baseline_snapshot();
let session = self.session_snapshot();
baseline
.network_access
.evaluate_host_with_session(host, session.as_ref(), once_domains)
}
#[must_use]
pub fn evaluate_data_url(&self) -> NetworkAccessDecision {
self.baseline_snapshot().network_access.evaluate_data_url()
}
fn session_snapshot(&self) -> Option<ProcessSessionPermissionSnapshot> {
self.session_permissions
.as_ref()
.and_then(|view| view.snapshot().ok())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{PathAccessRuleSource, ProcessSessionPermissions};
use merry_core::CapabilityPolicy;
#[test]
fn child_handle_tracks_live_baseline_while_isolating_session_grants() {
let temp = tempfile::tempdir().expect("tempdir");
let workspace = temp.path().join("workspace");
let external = temp.path().join("external.txt");
let secret_dir = temp.path().join("providers");
std::fs::create_dir_all(&workspace).expect("workspace");
std::fs::create_dir_all(&secret_dir).expect("secret dir");
std::fs::write(&external, "hello").expect("external");
let parent_session = ProcessSessionPermissions::new();
let child_session = ProcessSessionPermissions::new();
let initial = LivePolicyBaseline::new(
true,
Some(WorkspaceAccessPolicy::new(&workspace, true)),
vec![secret_dir.clone()],
NetworkAccessPolicy::new(CapabilityPolicy::Ask, true),
);
let parent = LivePolicyHandle::new(initial).with_session_permissions(parent_session.view());
let child = parent.for_child(
Some(child_session.view()),
Some(ChildWorkspacePolicyOverride::new(false)),
);
child_session
.retain_domain_grants(["docs.rs".to_owned()])
.expect("retain domain");
assert_eq!(
child.evaluate_network_host("docs.rs", &[]),
NetworkAccessDecision::Allow
);
assert_eq!(
parent.evaluate_network_host("docs.rs", &[]),
NetworkAccessDecision::RequireReview
);
let ws_file = workspace.join("src.rs");
assert_eq!(
parent.evaluate_write(&ws_file, &[]).decision,
PathAccessDecision::Allow
);
assert_eq!(
child.evaluate_write(&ws_file, &[]).decision,
PathAccessDecision::Deny
);
parent.replace_baseline(LivePolicyBaseline::new(
false,
None,
vec![secret_dir.clone()],
NetworkAccessPolicy::new(CapabilityPolicy::Deny, true),
));
assert!(!child.is_restricted());
assert_eq!(
child.evaluate_read(&external, &[]).decision,
PathAccessDecision::Allow
);
assert_eq!(
child.evaluate_network_host("docs.rs", &[]),
NetworkAccessDecision::Deny
);
let secret_eval = child.evaluate_read(&secret_dir.join("key.json"), &[]);
assert_eq!(secret_eval.decision, PathAccessDecision::RequireReview);
assert!(secret_eval.protected_target);
parent.replace_baseline(LivePolicyBaseline::new(
true,
Some(
WorkspaceAccessPolicy::new(&workspace, true).with_static_rules([
PathAccessRule::new(
&external,
PathAccess::ReadOnly,
PathAccessRuleSource::WorkspacePermissions,
),
]),
),
vec![secret_dir],
NetworkAccessPolicy::new(CapabilityPolicy::Ask, true),
));
assert!(child.is_restricted());
assert_eq!(
child.evaluate_read(&external, &[]).decision,
PathAccessDecision::Allow
);
}
}