use std::{
collections::BTreeSet,
fs,
path::{Component, PathBuf},
sync::Arc,
};
use merry_core::HostPathPolicy;
use merry_runtime::{
LivePolicyHandle, PathAccess, PathAccessDecision, PathAccessRule, PathEvaluation,
PermissionedAction, RequestedCapability, RequestedPathCapability, ToolPermissionRequirement,
normalize_path_lexically, once_grants_cover_path, resolve_path_with_existing_ancestor,
};
use crate::{
config::{WorkspaceToolConfigError, WorkspaceToolLimits, WorkspaceToolsConfig},
errors::{DomainError, ERROR_PATH_DENIED},
external_tree::ExternalTreePolicy,
path::ValidatedToolPath,
};
#[derive(Debug)]
pub(crate) struct WorkspaceToolState {
pub(crate) root: PathBuf,
pub(crate) readonly_resource_roots: Vec<PathBuf>,
pub(crate) limits: WorkspaceToolLimits,
pub(crate) read_scope: Option<Vec<String>>,
pub(crate) patch_write_scope: Option<Vec<String>>,
pub(crate) read_forbidden_paths: Vec<String>,
pub(crate) forbidden_paths: Vec<String>,
pub(crate) host_path_policy: HostPathPolicy,
pub(crate) access_policy: Option<LivePolicyHandle>,
pub(crate) external_tree_policy: Option<Arc<dyn ExternalTreePolicy>>,
}
pub(crate) enum ReadAccessPolicyError {
Denied(DomainError),
PermissionRequired(Box<ToolPermissionRequirement>),
}
impl WorkspaceToolState {
pub(crate) fn new(config: WorkspaceToolsConfig) -> Result<Self, WorkspaceToolConfigError> {
validate_limits(&config.limits)?;
let root = canonical_root(config.root)?;
let mut readonly_resource_roots = Vec::with_capacity(config.readonly_resource_roots.len());
for resource_root in config.readonly_resource_roots {
if let Some(canonical) = canonical_optional_root(resource_root)?
&& canonical != root
{
readonly_resource_roots.push(canonical);
}
}
let read_scope = match config.read_scope {
Some(paths) => Some(normalize_scope_paths(paths)?),
None => None,
};
let patch_write_scope = match config.patch_write_scope {
Some(paths) => Some(normalize_scope_paths(paths)?),
None => None,
};
let read_forbidden_paths = normalize_scope_paths(config.forbidden_paths)?;
let mut forbidden_paths = read_forbidden_paths.clone();
for path in normalize_scope_paths(config.write_forbidden_paths)? {
if !forbidden_paths.iter().any(|existing| existing == &path) {
forbidden_paths.push(path);
}
}
let writable_product_roots = config
.host_path_policy
.product_writable_config()
.iter()
.cloned()
.chain(
config
.host_path_policy
.durable_memory_root()
.map(PathBuf::from),
)
.chain(
config
.external_tree_policy
.as_ref()
.map(|policy| policy.root().to_path_buf()),
);
let host_path_policy = HostPathPolicy::new()
.with_denied(normalize_host_paths(
config.host_path_policy.denied().iter().cloned(),
))
.with_product_readonly(normalize_host_paths(
config.host_path_policy.product_readonly().iter().cloned(),
))
.with_product_writable_config(normalize_host_paths(writable_product_roots));
Ok(Self {
root,
readonly_resource_roots,
limits: config.limits,
read_scope,
patch_write_scope,
read_forbidden_paths,
forbidden_paths,
host_path_policy,
access_policy: config.access_policy,
external_tree_policy: config.external_tree_policy,
})
}
pub(crate) fn is_denied_for_read(&self, path: &std::path::Path) -> bool {
if self.host_path_policy.denied().is_empty() {
return false;
}
let lexical = normalize_path_lexically(path);
let resolved = resolve_path_with_existing_ancestor(&lexical);
self.host_path_policy.is_denied_for_read(&lexical)
|| self.host_path_policy.is_denied_for_read(&resolved)
}
fn enforce_product_readonly(&self) -> bool {
self.access_policy
.as_ref()
.is_none_or(LivePolicyHandle::is_restricted)
}
pub(crate) fn is_denied_for_write(&self, path: &std::path::Path) -> bool {
if !self.enforce_product_readonly() {
return self.is_denied_for_read(path);
}
if self.host_path_policy.denied().is_empty()
&& self.host_path_policy.product_readonly().is_empty()
{
return false;
}
let lexical = normalize_path_lexically(path);
let resolved = resolve_path_with_existing_ancestor(&lexical);
self.host_path_policy.is_denied_for_write(&lexical)
|| self.host_path_policy.is_denied_for_write(&resolved)
}
pub(crate) fn is_readonly_product_path(&self, path: &std::path::Path) -> bool {
if !self.enforce_product_readonly() || self.host_path_policy.product_readonly().is_empty() {
return false;
}
let lexical = normalize_path_lexically(path);
let resolved = resolve_path_with_existing_ancestor(&lexical);
self.host_path_policy.is_product_readonly(&lexical)
&& self.host_path_policy.is_product_readonly(&resolved)
}
pub(crate) fn read_roots(&self) -> impl Iterator<Item = &PathBuf> {
std::iter::once(&self.root).chain(self.readonly_resource_roots.iter())
}
pub(crate) fn has_runtime_permission_review(&self) -> bool {
self.access_policy.is_some()
}
pub(crate) fn once_grants_cover(
&self,
once_grants: &[PathAccessRule],
path: &std::path::Path,
requested: PathAccess,
) -> bool {
once_grants_cover_path(once_grants, path, requested)
}
pub(crate) fn is_hard_denied_for_read(
&self,
path: &std::path::Path,
once_grants: &[PathAccessRule],
) -> bool {
if !self.has_runtime_permission_review() {
return self.is_denied_for_read(path);
}
let Some(live) = self.access_policy.as_ref() else {
return false;
};
live.evaluate_read(path, once_grants).decision == PathAccessDecision::Deny
}
pub(crate) fn authorize_read_access_policy(
&self,
resolved: &std::path::Path,
once_grants: &[PathAccessRule],
) -> Result<(), ReadAccessPolicyError> {
let Some(live) = self.access_policy.as_ref() else {
return Ok(());
};
let eval = live.evaluate_read(resolved, once_grants);
if eval.decision == PathAccessDecision::Deny {
return Err(ReadAccessPolicyError::Denied(DomainError::new(
ERROR_PATH_DENIED,
"path is denied by configured workspace access policy",
)));
}
if eval.protected_target || self.is_denied_for_read(resolved) {
if eval.decision == PathAccessDecision::Allow
&& self.once_grants_cover(once_grants, resolved, PathAccess::ReadOnly)
{
return Ok(());
}
if !eval.protected_target
&& self.once_grants_cover(once_grants, resolved, PathAccess::ReadOnly)
{
return Ok(());
}
return Err(build_read_permission_requirement(
resolved,
"read_file targeted Merry protected credentials path",
true,
));
}
if eval.decision == PathAccessDecision::Allow {
return Ok(());
}
if self.is_readonly_product_path(resolved)
|| self
.readonly_resource_roots
.iter()
.any(|root| resolved.starts_with(root))
|| self
.external_tree_policy
.as_ref()
.is_some_and(|tree| tree.governs_path(resolved))
{
return Ok(());
}
Err(build_read_permission_requirement(
resolved,
"read_file targeted a path outside the active workspace access policy",
false,
))
}
pub(crate) fn evaluate_write_access_policy(
&self,
resolved: &std::path::Path,
once_grants: &[PathAccessRule],
) -> PathEvaluation {
let Some(live) = self.access_policy.as_ref() else {
return PathEvaluation {
decision: PathAccessDecision::Allow,
protected_target: false,
git_metadata: merry_runtime::is_git_metadata_path(resolved),
denial_reason: None,
};
};
let eval = live.evaluate_write(resolved, once_grants);
if eval.decision == PathAccessDecision::Deny {
return eval;
}
if eval.protected_target || self.is_denied_for_write(resolved) {
let allowed = self.once_grants_cover(once_grants, resolved, PathAccess::ReadWrite);
return PathEvaluation {
decision: if allowed {
PathAccessDecision::Allow
} else {
PathAccessDecision::RequireReview
},
protected_target: true,
git_metadata: eval.git_metadata,
denial_reason: None,
};
}
if eval.decision == PathAccessDecision::Allow {
return eval;
}
if self
.external_tree_policy
.as_ref()
.is_some_and(|tree| tree.governs_path(resolved))
|| self
.host_path_policy
.product_writable_config()
.iter()
.any(|root| resolved.starts_with(root))
{
return PathEvaluation {
decision: PathAccessDecision::Allow,
protected_target: false,
git_metadata: eval.git_metadata,
denial_reason: None,
};
}
eval
}
pub(crate) fn validate_read_boundary(
&self,
path: &ValidatedToolPath,
resolved: &std::path::Path,
) -> Result<(), DomainError> {
if !self.has_runtime_permission_review() && self.is_denied_for_read(resolved) {
return Err(DomainError::new(
ERROR_PATH_DENIED,
"path is denied by Merry security policy",
));
}
if self.is_readonly_product_path(resolved) {
return Ok(());
}
if self
.readonly_resource_roots
.iter()
.any(|root| resolved.starts_with(root))
{
return Ok(());
}
if let Some(policy) = &self.external_tree_policy
&& policy.governs_path(resolved)
{
return Ok(());
}
let scope_path = path.relative_spelling();
if let Some(scope_path) = scope_path
&& matches_any_scope_path(scope_path, &self.read_forbidden_paths)
{
return Err(DomainError::new(
ERROR_PATH_DENIED,
"workspace read path is forbidden by the child workspace scope",
));
}
let Some(read_scope) = &self.read_scope else {
return Ok(());
};
match scope_path {
Some(scope_path) if matches_any_scope_path(scope_path, read_scope) => Ok(()),
_ => {
let message = if read_scope.is_empty() {
"workspace read path is outside the configured read scope; this read scope allows no workspace files"
} else {
"workspace read path is outside the configured read scope"
};
Err(DomainError::new(ERROR_PATH_DENIED, message))
}
}
}
}
fn canonical_root(root: PathBuf) -> Result<PathBuf, WorkspaceToolConfigError> {
if !root.exists() {
return Err(WorkspaceToolConfigError::RootNotFound { root });
}
let canonical =
fs::canonicalize(&root).map_err(|source| WorkspaceToolConfigError::RootCanonicalize {
root: root.clone(),
source,
})?;
if !canonical.is_dir() {
return Err(WorkspaceToolConfigError::RootNotDirectory { root });
}
Ok(canonical)
}
fn canonical_optional_root(root: PathBuf) -> Result<Option<PathBuf>, WorkspaceToolConfigError> {
match canonical_root(root) {
Ok(canonical) => Ok(Some(canonical)),
Err(WorkspaceToolConfigError::RootNotFound { .. })
| Err(WorkspaceToolConfigError::RootNotDirectory { .. }) => Ok(None),
Err(error) => Err(error),
}
}
fn normalize_scope_paths(paths: Vec<PathBuf>) -> Result<Vec<String>, WorkspaceToolConfigError> {
let paths = paths
.into_iter()
.map(normalize_scope_path)
.collect::<Result<BTreeSet<_>, _>>()?;
Ok(paths.into_iter().collect())
}
fn normalize_scope_path(path: PathBuf) -> Result<String, WorkspaceToolConfigError> {
let Some(path_text) = path.to_str() else {
return Err(WorkspaceToolConfigError::InvalidScopePath { path });
};
if path_text == "." {
return Ok(String::new());
}
if path_text.is_empty()
|| path.is_absolute()
|| path_text.contains('\\')
|| path_text.chars().any(char::is_control)
|| path_text
.split('/')
.any(|segment| matches!(segment, "" | "." | ".."))
{
return Err(WorkspaceToolConfigError::InvalidScopePath { path });
}
let mut components = Vec::new();
for component in path.components() {
match component {
Component::Normal(value) => {
let Some(value) = value.to_str() else {
return Err(WorkspaceToolConfigError::InvalidScopePath { path });
};
components.push(value.to_owned());
}
Component::CurDir
| Component::ParentDir
| Component::RootDir
| Component::Prefix(_) => {
return Err(WorkspaceToolConfigError::InvalidScopePath { path });
}
}
}
if components.is_empty() {
return Err(WorkspaceToolConfigError::InvalidScopePath { path });
}
Ok(components.join("/"))
}
pub(crate) fn matches_any_scope_path(relative: &str, scope_paths: &[String]) -> bool {
scope_paths
.iter()
.any(|scope_path| matches_scope_path(relative, scope_path))
}
fn matches_scope_path(relative: &str, scope_path: &str) -> bool {
scope_path.is_empty()
|| relative == scope_path
|| relative
.strip_prefix(scope_path)
.is_some_and(|suffix| suffix.starts_with('/'))
}
fn validate_limits(limits: &WorkspaceToolLimits) -> Result<(), WorkspaceToolConfigError> {
for (name, value) in [
("max_read_bytes", limits.max_read_bytes),
("max_read_lines", limits.max_read_lines),
("max_write_bytes", limits.max_write_bytes),
("max_patch_bytes", limits.max_patch_bytes),
] {
if value == 0 {
return Err(WorkspaceToolConfigError::InvalidLimit { name });
}
}
Ok(())
}
fn normalize_host_paths(paths: impl IntoIterator<Item = PathBuf>) -> Vec<PathBuf> {
let mut normalized = BTreeSet::new();
for path in paths {
if !path.is_absolute() {
continue;
}
let lexical = normalize_path_lexically(&path);
let resolved = resolve_path_with_existing_ancestor(&lexical);
normalized.insert(lexical);
normalized.insert(resolved);
}
normalized.into_iter().collect()
}
fn build_read_permission_requirement(
resolved: &std::path::Path,
reason: &str,
protected_target: bool,
) -> ReadAccessPolicyError {
let target = resolved.to_string_lossy().into_owned();
let capability = match RequestedPathCapability::new(target.clone(), PathAccess::ReadOnly) {
Ok(cap) => RequestedCapability::Path(cap),
Err(error) => {
return ReadAccessPolicyError::Denied(DomainError::new(
ERROR_PATH_DENIED,
format!(
"external read target `{target}` is outside the active workspace access policy and cannot be requested for approval: {error}"
),
));
}
};
let mut requirement = ToolPermissionRequirement::new(
PermissionedAction::FileRead { path: target },
vec![capability],
Some(reason.to_owned()),
);
if protected_target {
requirement = requirement.with_protected_target();
}
ReadAccessPolicyError::PermissionRequired(Box::new(requirement))
}