use std::path::{Path, PathBuf};
use super::layout::{
entry, Layout, CLAUDE_CREDENTIALS, ENGINE_CONFIG_FILES, PROJECT_ENGINE_CONFIG_DIRS,
STATE_ROOT_SCRATCHPAD, STATE_ROOT_SESSION_TMP, STATE_ROOT_WORKING_DIRS,
};
use super::ConfigPaths;
mod config_root;
mod spellings;
pub use config_root::ConfigRootAt;
use spellings::{absolute_lexically, lowered_components, Spellings};
pub const REPOSITORY_CONFIG_DIR: &str = ".git";
pub const GIT_CONTROL_FILES: &[&str] = &["config", "config.worktree", "commondir"];
pub const GIT_WORKTREE_CONTROL_FILES: &[&str] =
&["config", "config.worktree", "commondir", "gitdir"];
pub const GIT_HOOKS_DIR: &str = "hooks";
pub const SECRET_FILE_NAMES: &[&str] = &[
".env",
".env.local",
".env.production",
"id_rsa",
"id_ed25519",
".netrc",
".pypirc",
".npmrc",
".pgpass",
];
pub const HOME_CREDENTIAL_STORES: &[&str] = &[
".ssh",
".aws",
".gnupg",
".docker/config.json",
".kube",
".azure",
".config/gh",
".netrc",
".npmrc",
".pypirc",
".gem/credentials",
".git-credentials",
".config/git/credentials",
".config/gcloud",
".cargo/credentials",
".cargo/credentials.toml",
".vault-token",
".terraform.d/credentials.tfrc.json",
".config/glab-cli",
".config/hub",
".config/doctl",
".oci",
".boto",
".s3cfg",
".databrickscfg",
".config/rclone",
".huggingface/token",
".cache/huggingface/token",
CLAUDE_CREDENTIALS,
".codex/auth.json",
];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Credential {
pub scope: Scope,
pub secret: Secret,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scope {
StateRoot,
EachSceneDir,
AnyEngineDir,
Anywhere,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Secret {
KeyFiles(KeyFileNames),
Tree(&'static str),
DirName(&'static str),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyFileNames {
StateRoot,
Project,
}
impl KeyFileNames {
pub fn stems(self) -> &'static [&'static str] {
match self {
Self::StateRoot => &["settings", "mcp.local"],
Self::Project => &[entry::SETTINGS_LOCAL, entry::MCP_LOCAL],
}
}
pub fn admits(self, name: &str) -> bool {
let name = name.strip_prefix('.').unwrap_or(name);
let stem = self.stems().iter().any(|stem| name.starts_with(stem));
match self {
Self::StateRoot => stem && name.contains(".json"),
Self::Project => stem,
}
}
}
impl Secret {
fn holds(self, rest: &[String]) -> bool {
match self {
Self::KeyFiles(names) => rest.first().is_some_and(|name| names.admits(name)),
Self::Tree(path) | Self::DirName(path) => {
let path: Vec<&str> = path.split('/').collect();
rest.len() >= path.len() && path.iter().zip(rest).all(|(p, c)| p == c)
}
}
}
}
pub const CREDENTIALS: &[Credential] = &[
Credential {
scope: Scope::StateRoot,
secret: Secret::KeyFiles(KeyFileNames::StateRoot),
},
Credential {
scope: Scope::EachSceneDir,
secret: Secret::KeyFiles(KeyFileNames::StateRoot),
},
Credential {
scope: Scope::StateRoot,
secret: Secret::Tree("mcp/oauth"),
},
Credential {
scope: Scope::EachSceneDir,
secret: Secret::Tree("mcp/oauth"),
},
Credential {
scope: Scope::StateRoot,
secret: Secret::Tree("daemon/auth"),
},
Credential {
scope: Scope::AnyEngineDir,
secret: Secret::KeyFiles(KeyFileNames::Project),
},
Credential {
scope: Scope::Anywhere,
secret: Secret::DirName(".ssh"),
},
Credential {
scope: Scope::Anywhere,
secret: Secret::DirName(".aws"),
},
Credential {
scope: Scope::Anywhere,
secret: Secret::DirName(".gnupg"),
},
];
pub fn credential_dir_names() -> impl Iterator<Item = &'static str> {
CREDENTIALS.iter().filter_map(|c| match c.secret {
Secret::DirName(name) if c.scope == Scope::Anywhere => Some(name),
_ => None,
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Located {
pub base: PathBuf,
pub under_each_scene: bool,
pub secret: Secret,
}
impl Located {
pub fn dirs(&self) -> Vec<PathBuf> {
if self.under_each_scene {
scene_dirs_in(&self.base)
.into_iter()
.map(|scene| scene.path)
.collect()
} else {
vec![self.base.clone()]
}
}
pub fn linked_dirs_resolved(&self) -> Vec<PathBuf> {
if !self.under_each_scene {
return Vec::new();
}
scene_dirs_in(&self.base)
.into_iter()
.filter(|scene| scene.resolved != scene.path)
.map(|scene| scene.resolved)
.collect()
}
pub fn existing(&self) -> Vec<PathBuf> {
let mut found = Vec::new();
for dir in self.dirs() {
match self.secret {
Secret::KeyFiles(names) => {
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
found.extend(
entries
.flatten()
.filter(|e| {
e.file_name()
.to_str()
.is_some_and(|n| names.admits(&super::fold_case(n)))
})
.map(|e| e.path()),
);
}
Secret::Tree(path) | Secret::DirName(path) => found.push(dir.join(path)),
}
}
found.retain(|p| p.symlink_metadata().is_ok());
found.sort();
found
}
}
pub fn known_state_roots(layout: &Layout) -> Vec<PathBuf> {
let home = super::home_dir().into_iter();
home.flat_map(|home| layout.state_dir_names().map(move |n| home.join(n)))
.collect()
}
#[derive(Debug, Clone, Default)]
pub struct SensitivePaths {
state_root: Option<Spellings>,
foreign_state_roots: Vec<Spellings>,
project: Option<Spellings>,
linked_scenes: Vec<PathBuf>,
read_denials: Vec<Spellings>,
read_exemptions: Vec<Spellings>,
layout: Layout,
}
impl SensitivePaths {
pub fn new(state_root: Option<&Path>, project: Option<&Path>, layout: Layout) -> Self {
let state_root = state_root.map(Spellings::of);
let linked_scenes = state_root.iter().flat_map(linked_scenes_of).collect();
Self {
state_root,
foreign_state_roots: Vec::new(),
project: project.map(Spellings::of),
linked_scenes,
read_denials: Vec::new(),
read_exemptions: Vec::new(),
layout,
}
}
pub fn with_foreign_state_roots(mut self, roots: &[PathBuf]) -> Self {
for root in roots {
let root = Spellings::of(root);
let own = self
.state_root
.as_ref()
.is_some_and(|s| s.real == root.real);
let known = self.foreign_state_roots.iter().any(|f| f.real == root.real);
if !own && !known {
self.linked_scenes.extend(linked_scenes_of(&root));
self.foreign_state_roots.push(root);
}
}
self
}
pub fn foreign_state_roots(&self) -> Vec<PathBuf> {
self.foreign_state_roots
.iter()
.map(|root| root.given.clone())
.collect()
}
fn every_state_root(&self) -> impl Iterator<Item = &Spellings> {
self.state_root.iter().chain(&self.foreign_state_roots)
}
pub fn layout(&self) -> &Layout {
&self.layout
}
pub fn with_read_denials(mut self, denied: &[PathBuf], allowed: &[PathBuf]) -> Self {
self.read_denials = denied.iter().map(|p| Spellings::of(p)).collect();
self.read_exemptions = allowed.iter().map(|p| Spellings::of(p)).collect();
self
}
fn read_denied(&self, components: &[String]) -> bool {
let depth_in = |roots: &[Spellings]| {
roots
.iter()
.flat_map(|root| &root.lowered)
.filter(|root| components.starts_with(root))
.map(Vec::len)
.max()
};
match (
depth_in(&self.read_denials),
depth_in(&self.read_exemptions),
) {
(Some(denied), Some(allowed)) => denied > allowed,
(Some(_), None) => true,
_ => false,
}
}
pub fn linked_scene_dirs_resolved(&self) -> &[PathBuf] {
&self.linked_scenes
}
pub fn for_paths(paths: &ConfigPaths) -> Self {
Self::new(
Some(&paths.global_data_dir),
paths.project_root.as_deref(),
paths.layout.clone(),
)
.with_foreign_state_roots(&known_state_roots(&paths.layout))
}
pub fn state_root(&self) -> Option<&Path> {
self.state_root.as_ref().map(|s| s.given.as_path())
}
pub fn is_credential(&self, abs: &Path) -> bool {
let components = lowered_components(abs);
self.read_denied(&components)
|| CREDENTIALS
.iter()
.any(|credential| self.holds(credential, &components))
}
fn holds(&self, credential: &Credential, components: &[String]) -> bool {
let secret = credential.secret;
if credential.scope == Scope::EachSceneDir
&& self.linked_scenes.iter().any(|scene| {
components
.strip_prefix(lowered_components(scene).as_slice())
.is_some_and(|rest| secret.holds(rest))
})
{
return true;
}
match credential.scope {
Scope::Anywhere => (0..components.len()).any(|i| secret.holds(&components[i..])),
Scope::AnyEngineDir => components.iter().enumerate().any(|(i, c)| {
self.layout.engine_dir_names().any(|dir| c == dir)
&& secret.holds(&components[i + 1..])
}),
Scope::StateRoot | Scope::EachSceneDir => self
.every_state_root()
.flat_map(|root| &root.lowered)
.any(|root| {
let Some(rest) = components.strip_prefix(root.as_slice()) else {
return false;
};
match (credential.scope, rest) {
(Scope::StateRoot, _) => secret.holds(rest),
(_, [scenes, _, inner @ ..]) => {
scenes == entry::SCENES && secret.holds(inner)
}
_ => false,
}
}),
}
}
pub fn credential_locations(&self, engine_dirs: &[PathBuf]) -> Vec<Located> {
let mut located = Vec::new();
for credential in CREDENTIALS {
let at = |base: &Path| Located {
base: base.to_path_buf(),
under_each_scene: credential.scope == Scope::EachSceneDir,
secret: credential.secret,
};
match credential.scope {
Scope::StateRoot | Scope::EachSceneDir => {
located.extend(self.every_state_root().map(|root| at(&root.real)));
}
Scope::AnyEngineDir => located.extend(engine_dirs.iter().map(|dir| at(dir))),
Scope::Anywhere => {}
}
}
located
}
pub fn engine_dirs_in(&self, dir: &Path) -> Vec<PathBuf> {
let mut dirs = Vec::new();
for name in self.layout.engine_dir_names() {
let given = dir.join(name);
let real = crate::path::resolve_physically(&given);
dirs.push(given.clone());
if real != given {
dirs.push(real);
}
}
dirs
}
pub fn config_roots_in(&self, dir: &Path) -> Vec<ConfigRootAt> {
self.layout
.config_roots()
.map(|root| {
let path = dir.join(root.name);
ConfigRootAt {
resolved: crate::path::resolve_physically(&path),
path,
own: root.own,
}
})
.collect()
}
pub fn worktree_dirs_in(&self, dir: &Path) -> Vec<PathBuf> {
self.layout
.worktrees_dir_names()
.map(|name| dir.join(name))
.collect()
}
pub fn names_configuration(&self, text: &str) -> bool {
let lowered = super::fold_case(text);
let components: Vec<&str> = lowered.split('/').collect();
let name_in = |component: &str| {
component
.split(|c: char| !(c.is_alphanumeric() || "._-".contains(c)))
.next()
.unwrap_or_default()
.to_string()
};
let opens_dir = |rest: &[&str], dir: &str| {
let dir: Vec<&str> = dir.split('/').collect();
let Some((last, above)) = dir.split_last() else {
return false;
};
rest.len() >= dir.len()
&& above.iter().zip(rest).all(|(d, c)| d == c)
&& name_in(rest[above.len()]) == *last
};
let working_at = |at: usize| {
components
.get(at)
.is_some_and(|next| self.is_engine_working_entry(&name_in(next)))
};
let working_below = |i: usize| {
(self.state_root_ends_at(&components[..=i]) && working_at(i + 1))
|| (components.get(i + 1) == Some(&entry::STATE) && working_at(i + 2))
};
lowered.contains('/')
&& components.iter().enumerate().any(|(i, component)| {
let config_root = *component == REPOSITORY_CONFIG_DIR
|| self
.layout
.config_roots()
.any(|root| *component == root.name && !(root.own && working_below(i)));
config_root
|| PROJECT_ENGINE_CONFIG_DIRS
.iter()
.any(|dir| opens_dir(&components[i..], dir))
})
}
fn state_root_ends_at(&self, spelled: &[&str]) -> bool {
let name_char = |c: char| c.is_alphanumeric() || "._-".contains(c);
let ends_with = |root: &[String], before_ok: &dyn Fn(&str) -> bool| {
let Some(at) = spelled.len().checked_sub(root.len() + 1) else {
return false;
};
!root.is_empty()
&& before_ok(spelled[at])
&& spelled[at + 1..].iter().zip(root).all(|(s, r)| s == r)
};
let from_home = |before: &str| {
["~", "$home", "${home}"].iter().any(|home| {
before
.strip_suffix(home)
.is_some_and(|rest| !rest.ends_with(name_char))
})
};
self.state_root.iter().any(|root| {
root.lowered
.iter()
.any(|spelling| ends_with(spelling, &|before| !before.ends_with(name_char)))
|| root
.below_home
.iter()
.any(|spelling| ends_with(spelling, &from_home))
})
}
pub fn is_engine_settings_file(&self, abs: &Path) -> bool {
let components = lowered_components(abs);
let Some((name, dirs)) = components.split_last() else {
return false;
};
ENGINE_CONFIG_FILES.contains(&name.as_str())
&& dirs
.iter()
.any(|d| self.layout.config_roots().any(|root| *d == root.name))
}
pub fn is_engine_working_entry(&self, name: &str) -> bool {
is_working_entry(name)
}
pub fn state_working_dirs(&self) -> Vec<PathBuf> {
self.state_root
.iter()
.flat_map(|root| STATE_ROOT_WORKING_DIRS.iter().map(|d| root.given.join(d)))
.collect()
}
pub fn readable_state_root(&self) -> Option<PathBuf> {
self.state_root().map(Path::to_path_buf)
}
pub fn session_tmp_dir(&self, session_id: &str) -> Option<PathBuf> {
self.state_root().map(|root| {
root.join(STATE_ROOT_SESSION_TMP)
.join(session_dir_name(session_id))
})
}
pub fn session_scratch_dir(&self, session_id: &str) -> Option<PathBuf> {
self.state_root()
.map(|root| session_scratch_dir(root, session_id))
}
pub fn scene_dirs(&self) -> Vec<PathBuf> {
self.state_root
.as_ref()
.map(|root| scene_dirs_in(&root.real))
.unwrap_or_default()
.into_iter()
.map(|scene| scene.path)
.collect()
}
pub fn prompt_files(&self) -> PromptFiles {
PromptFiles {
paths: self.clone(),
root: self.project.clone(),
}
}
pub fn prompt_files_within(&self, dir: &Path) -> PromptFiles {
PromptFiles {
paths: self.clone(),
root: Some(Spellings::of(dir)),
}
}
}
pub fn session_scratch_dir(state_root: &Path, session_id: &str) -> PathBuf {
state_root
.join(STATE_ROOT_SCRATCHPAD)
.join(entry::SESSIONS)
.join(session_dir_name(session_id))
}
pub fn tool_results_dir(dir: &Path, session_id: &str) -> PathBuf {
dir.join(entry::TOOL_RESULTS)
.join(session_dir_name(session_id))
}
fn session_dir_name(session_id: &str) -> String {
session_id
.chars()
.filter(|c| c.is_ascii_alphanumeric() || *c == '-')
.collect()
}
#[derive(Debug, Clone)]
pub struct PromptFiles {
paths: SensitivePaths,
root: Option<Spellings>,
}
impl PromptFiles {
pub fn unscoped() -> Self {
SensitivePaths::default().prompt_files()
}
pub fn for_project(paths: &ConfigPaths) -> Self {
SensitivePaths::for_paths(paths).prompt_files()
}
pub fn resolve(&self, path: &Path) -> std::io::Result<PathBuf> {
let resolved = std::fs::canonicalize(path)?;
self.admit(path, &resolved)
.map_err(|why| std::io::Error::new(std::io::ErrorKind::PermissionDenied, why))?;
Ok(resolved)
}
pub fn read_to_string(&self, path: &Path) -> std::io::Result<String> {
std::fs::read_to_string(self.resolve(path)?)
}
pub fn admit(&self, path: &Path, resolved: &Path) -> Result<(), String> {
let spelled = absolute_lexically(path);
let refusal = if self.paths.is_credential(&spelled) || self.paths.is_credential(resolved) {
Some("is a credential location".to_string())
} else {
self.root.as_ref().and_then(|root| {
let user_owned = self
.paths
.state_root
.as_ref()
.is_some_and(|s| s.spell(&spelled));
(root.spell(&spelled) && !user_owned && !resolved.starts_with(&root.real))
.then(|| format!("is outside {}", root.given.display()))
})
};
match refusal {
None => Ok(()),
Some(why) => {
let message = format!(
"not reading {} for the model: it resolves to {}, which {why}",
path.display(),
resolved.display()
);
tracing::warn!("{message}");
Err(message)
}
}
}
}
fn is_working_entry(name: &str) -> bool {
STATE_ROOT_WORKING_DIRS.contains(&name)
}
fn linked_scenes_of(root: &Spellings) -> Vec<PathBuf> {
scene_dirs_in(&root.real)
.into_iter()
.filter(|scene| scene.resolved != scene.path)
.map(|scene| scene.resolved)
.collect()
}
struct SceneDir {
path: PathBuf,
resolved: PathBuf,
}
fn scene_dirs_in(base: &Path) -> Vec<SceneDir> {
let Ok(entries) = std::fs::read_dir(base.join(entry::SCENES)) else {
return Vec::new();
};
let mut dirs: Vec<SceneDir> = entries
.flatten()
.map(|e| e.path())
.filter(|path| path.is_dir())
.map(|path| SceneDir {
resolved: path.canonicalize().unwrap_or_else(|_| path.clone()),
path,
})
.collect();
dirs.sort_by(|a, b| a.path.cmp(&b.path));
dirs
}
#[cfg(test)]
mod tests {
use super::*;
use crate::paths::layout::test_layouts;
use crate::paths::{ENGINE_CONFIG_DIRS, STATE_RESERVED_NAMES};
fn sensitive(state_root: &str) -> SensitivePaths {
SensitivePaths::new(Some(Path::new(state_root)), None, Layout::default())
}
#[test]
fn the_known_state_roots_are_the_engines_and_agixds() {
let Some(home) = crate::paths::home_dir() else {
return;
};
assert_eq!(known_state_roots(&Layout::default()), [home.join(".agix")]);
let foo = Layout::default().with_engine("foo").unwrap();
assert_eq!(
known_state_roots(&foo),
[home.join(".foo"), home.join(".agix")]
);
}
fn in_layout(layout: &Layout) -> SensitivePaths {
SensitivePaths::new(Some(Path::new("/state/home")), None, layout.clone())
}
fn own(p: &str, layout: &Layout) -> String {
p.replace("{own}", layout.project_dir_name())
.replace("{wk}", layout.worktrees_dir_name())
}
#[test]
fn saved_tool_results_are_outside_what_sandboxed_commands_may_write() {
let root = Path::new("/repo/.agix");
let saved = tool_results_dir(root, "s");
assert!(
!sensitive("/repo/.agix")
.state_working_dirs()
.iter()
.any(|w| saved.starts_with(w)),
"{}",
saved.display()
);
}
#[test]
fn another_instances_state_root_holds_credentials_as_the_own_one_does() {
let paths = sensitive("/state/codix").with_foreign_state_roots(&[
PathBuf::from("/home/u/.agix"),
PathBuf::from("/state/codix"),
]);
assert_eq!(
paths.foreign_state_roots(),
[PathBuf::from("/home/u/.agix")]
);
for p in [
"/home/u/.agix/settings.json",
"/home/u/.agix/Settings.local.JSON",
"/home/u/.agix/scenes/code/settings.json",
"/home/u/.agix/mcp/oauth/x.json",
"/home/u/.agix/daemon/auth/desktop.token",
"/state/codix/settings.json",
] {
assert!(paths.is_credential(Path::new(p)), "{p}");
}
for p in [
"/home/u/.agix/skills/s/SKILL.md",
"/home/u/.agix/daemon/instances.d/x.json",
] {
assert!(!paths.is_credential(Path::new(p)), "{p}");
}
let bases: Vec<PathBuf> = paths
.credential_locations(&[])
.into_iter()
.map(|l| l.base)
.collect();
assert!(bases.contains(&PathBuf::from("/home/u/.agix")), "{bases:?}");
assert!(!sensitive("/state/codix").is_credential(Path::new("/home/u/.agix/settings.json")));
}
#[test]
fn credentials_are_the_state_roots_keys_and_tokens_and_a_projects_keys() {
let paths = sensitive("/state/home");
for p in [
"/state/home/settings.json",
"/state/home/settings.local.json",
"/state/home/.settings.json.tmp-1",
"/state/home/mcp.local.json",
"/state/home/Settings.JSON",
"/state/home/mcp/oauth",
"/state/home/mcp/oauth/x.json",
"/state/home/scenes/code/settings.json",
"/state/home/scenes/code/mcp/oauth/x.json",
"/state/home/daemon/auth/desktop.token",
"/repo/.agix/settings.local.json",
"/repo/.agix/mcp.local.json",
"/home/u/.ssh/id_rsa",
"/home/u/.aws",
] {
assert!(paths.is_credential(Path::new(p)), "{p}");
}
for p in [
"/state/home",
"/state/home/mcp",
"/state/home/mcp.json",
"/state/home/skills/x/SKILL.md",
"/state/home/memory/settings.json",
"/state/home/scenes/code/scene.json",
"/state/home/scenes/settings.json/x",
"/state/home/daemon/instances.d/x.json",
"/state/homework/settings.json",
"/repo/.agix/settings.json",
"/repo/settings.local.json",
"/repo/.github/x",
] {
assert!(!paths.is_credential(Path::new(p)), "{p}");
}
assert!(!SensitivePaths::default().is_credential(Path::new("/state/home/settings.json")));
for layout in test_layouts() {
let paths = in_layout(&layout);
for p in [
"/repo/{own}/settings.local.json",
"/repo/{own}/mcp.local.json",
"/repo/.agix/settings.local.json",
] {
assert!(paths.is_credential(Path::new(&own(p, &layout))), "{p}");
}
for p in [
"/repo/{own}/settings.json",
"/repo/.claude/settings.local.json",
] {
assert!(!paths.is_credential(Path::new(&own(p, &layout))), "{p}");
}
}
assert!(!sensitive("/state/home").is_credential(Path::new("/repo/.codix/mcp.local.json")));
}
fn example(credential: &Credential, layout: &Layout) -> (String, String) {
let name = match credential.secret {
Secret::KeyFiles(KeyFileNames::StateRoot) => "settings.json",
Secret::KeyFiles(KeyFileNames::Project) => "settings.local.json",
Secret::Tree(path) | Secret::DirName(path) => path,
};
match credential.scope {
Scope::StateRoot => (format!("/state/home/{name}"), format!("/elsewhere/{name}")),
Scope::EachSceneDir => (
format!("/state/home/scenes/triage/{name}"),
format!("/state/home/scenes/{name}"),
),
Scope::AnyEngineDir => (
format!("/repo/{}/{name}", layout.project_dir_name()),
format!("/repo/{name}"),
),
Scope::Anywhere => (format!("/home/u/{name}/x"), format!("/home/u/{name}-not/x")),
}
}
#[test]
fn every_credential_is_recognized_and_every_scope_has_a_near_miss() {
let mut scopes = Vec::new();
for layout in test_layouts() {
let paths = in_layout(&layout);
for credential in CREDENTIALS {
let (hit, miss) = example(credential, &layout);
assert!(
paths.is_credential(Path::new(&hit)),
"{credential:?}: {hit}"
);
assert!(
!paths.is_credential(Path::new(&miss)),
"{credential:?}: {miss}"
);
if !scopes.contains(&credential.scope) {
scopes.push(credential.scope);
}
}
}
for scope in [
Scope::StateRoot,
Scope::EachSceneDir,
Scope::AnyEngineDir,
Scope::Anywhere,
] {
assert!(scopes.contains(&scope), "no credential in {scope:?}");
}
}
#[test]
fn a_read_denial_is_a_credential_unless_a_more_specific_allow_lifts_it() {
let paths = SensitivePaths::default().with_read_denials(
&[PathBuf::from("/h/.config/gh"), PathBuf::from("/h/.npmrc")],
&[PathBuf::from("/h/.config/gh/public"), PathBuf::from("/h")],
);
assert!(paths.is_credential(Path::new("/h/.config/gh/hosts.yml")));
assert!(!paths.is_credential(Path::new("/h/.config/gh/public/x")));
assert!(paths.is_credential(Path::new("/h/.npmrc")));
assert!(!paths.is_credential(Path::new("/h/notes")));
}
#[test]
fn a_backend_gets_every_credential_but_the_ones_it_reaches_through_deny_read() {
let paths = sensitive("/state/home");
let agix = [PathBuf::from("/repo/.agix")];
let located = paths.credential_locations(&agix);
let expected = CREDENTIALS
.iter()
.filter(|c| c.scope != Scope::Anywhere)
.count();
assert_eq!(located.len(), expected, "{located:?}");
assert!(located
.iter()
.all(|l| l.base == Path::new("/state/home") || l.base == Path::new("/repo/.agix")));
assert!(SensitivePaths::default()
.credential_locations(&[])
.is_empty());
}
#[cfg(unix)]
#[test]
fn a_scene_linked_in_from_elsewhere_has_its_key_files_located() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("state");
let elsewhere = dir.path().join("dotfiles/scene");
std::fs::create_dir_all(root.join("scenes")).unwrap();
std::fs::create_dir_all(&elsewhere).unwrap();
std::fs::write(elsewhere.join("settings.json"), "").unwrap();
std::os::unix::fs::symlink(&elsewhere, root.join("scenes/linked")).unwrap();
let root = root.canonicalize().unwrap();
let located =
SensitivePaths::new(Some(&root), None, Layout::default()).credential_locations(&[]);
let keys = located
.iter()
.find(|l| l.under_each_scene && matches!(l.secret, Secret::KeyFiles(_)))
.unwrap();
assert!(
keys.existing()
.contains(&root.join("scenes/linked/settings.json")),
"{:?}",
keys.existing()
);
assert_eq!(
keys.linked_dirs_resolved(),
vec![elsewhere.canonicalize().unwrap()]
);
}
#[cfg(unix)]
#[test]
fn a_linked_scenes_secrets_are_credentials_under_their_real_path() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("state");
let elsewhere = dir.path().join("dotfiles/scene");
std::fs::create_dir_all(root.join("scenes")).unwrap();
std::fs::create_dir_all(&elsewhere).unwrap();
std::os::unix::fs::symlink(&elsewhere, root.join("scenes/linked")).unwrap();
let paths = SensitivePaths::new(Some(&root), None, Layout::default());
let real = elsewhere.canonicalize().unwrap();
assert_eq!(
paths.linked_scene_dirs_resolved(),
std::slice::from_ref(&real)
);
assert!(paths.is_credential(&real.join("settings.json")));
assert!(paths.is_credential(&real.join("mcp/oauth/token.json")));
assert!(paths.is_credential(&root.join("scenes/linked/settings.json")));
assert!(!paths.is_credential(&real.join("scene.json")));
assert!(!paths.is_credential(&real.parent().unwrap().join("settings.json")));
}
#[test]
fn the_existing_secrets_of_a_location_are_found_on_disk() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
for scene in ["code", "triage"] {
std::fs::create_dir_all(root.join("scenes").join(scene).join("mcp/oauth")).unwrap();
std::fs::write(root.join("scenes").join(scene).join("settings.json"), "").unwrap();
}
std::fs::write(root.join("scenes/code/scene.json"), "").unwrap();
let located =
SensitivePaths::new(Some(&root), None, Layout::default()).credential_locations(&[]);
let keys = located
.iter()
.find(|l| l.under_each_scene && matches!(l.secret, Secret::KeyFiles(_)))
.unwrap();
assert_eq!(
keys.existing(),
vec![
root.join("scenes/code/settings.json"),
root.join("scenes/triage/settings.json")
]
);
let daemon = located
.iter()
.find(|l| l.secret == Secret::Tree("daemon/auth"))
.unwrap();
assert!(daemon.existing().is_empty());
}
#[test]
fn the_roots_derive_from_the_state_root() {
let paths = sensitive("/state/home");
assert_eq!(
paths.state_working_dirs(),
vec![
PathBuf::from("/state/home/scratchpad"),
PathBuf::from("/state/home/memory")
]
);
assert_eq!(
paths.session_tmp_dir("s-1/../x"),
Some(PathBuf::from("/state/home/tmp/s-1x"))
);
assert_eq!(
paths.session_scratch_dir("s-1/../x"),
Some(PathBuf::from("/state/home/scratchpad/sessions/s-1x"))
);
assert_eq!(
paths.readable_state_root(),
Some(PathBuf::from("/state/home"))
);
let none = SensitivePaths::default();
assert!(none.state_working_dirs().is_empty());
assert_eq!(none.session_tmp_dir("s"), None);
}
#[test]
fn credential_dirs_are_whole_components_anywhere() {
let paths = SensitivePaths::default();
for p in [
"~/.ssh/id_rsa",
"cat ~/.ssh/id_rsa",
"/home/u/.ssh/config",
"~/.aws/credentials",
"/Users/me/.gnupg/secring.gpg",
"/repo/.github/workflows/../.ssh/id_rsa",
"/a/b/c/d/e/f/.aws/credentials",
] {
assert!(paths.is_credential(Path::new(p)), "{p}");
}
for p in ["/home/u/.sshx/config", "/repo/.github/x", "/repo/.awsome"] {
assert!(!paths.is_credential(Path::new(p)), "{p}");
}
}
#[test]
fn config_dirs_require_confirmation() {
for layout in test_layouts() {
let paths = in_layout(&layout);
for p in [
"repo/.git/config",
"/Users/me/{own}/settings.json",
"/Users/me/.agix/settings.json",
"/a/b/.claude/settings.local.json",
] {
assert!(paths.names_configuration(&own(p, &layout)), "{p}");
}
assert!(!paths.names_configuration("/repo/.github/workflows/ci.yml"));
assert!(!paths.names_configuration("/repo/src/main.rs"));
}
assert!(!sensitive("/s").names_configuration("/repo/.codix/settings.json"));
}
#[test]
fn a_projects_skills_are_configuration() {
for layout in test_layouts() {
let paths = in_layout(&layout);
for p in [
"/repo/.agents/skills/x/SKILL.md",
"/repo/.agents/skills",
".agents/skills;",
"/repo/.Agents/Skills/x/SKILL.md",
] {
assert!(paths.names_configuration(p), "{p}");
}
for p in [
"/repo/.agents/notes.md",
"/repo/.agents/skills2/x",
"/repo/skills/x",
"/repo/AGENTS.md",
] {
assert!(!paths.names_configuration(p), "{p}");
}
}
}
#[test]
fn names_a_case_insensitive_filesystem_folds_onto_configuration_are_configuration() {
let ops = in_layout(&Layout::new(".ops").unwrap());
for p in [
"/repo/.agent\u{17F}/\u{17F}kills/x/SKILL.md",
"/repo/.agents/\u{17F}kills/x/SKILL.md",
"/repo/.op\u{17F}/hooks/h.sh",
] {
assert!(ops.names_configuration(p), "{p}");
}
for p in [
"/repo/.op\u{17F}/\u{17F}ettings.json",
"/repo/.claude/\u{17F}ettings.j\u{17F}on",
"/repo/.agix/\u{17F}etting\u{17F}.json",
] {
assert!(ops.is_engine_settings_file(Path::new(p)), "{p}");
}
assert!(Layout::new(".ops")
.unwrap()
.is_own_dir_component(".op\u{17F}"));
assert!(!ops.names_configuration("/repo/stra\u{DF}e/x.md"));
assert_eq!(
super::super::fold_case("Gi\u{FB06}/CON\u{FB01}G/\u{1E9E}"),
"gist/config/ss"
);
}
#[test]
fn the_agents_working_space_in_its_own_directory_is_not_configuration() {
for layout in test_layouts() {
let paths = in_layout(&layout);
for p in [
"/repo/{own}/state/scratchpad/cases.txt",
"/repo/{own}/state/memory/MEMORY.md",
"/repo/{wk}/a/{own}/state/scratchpad/x",
"cd /repo\nS=/repo/{own}/state/scratchpad\nmkdir -p \"$S\"",
"printf x > \"$d/{own}/state/scratchpad\"",
"/repo/{wk}/feat-a/feature.txt",
"cd /repo/{wk}/feat-a && git add -A",
] {
assert!(!paths.names_configuration(&own(p, &layout)), "{p}");
}
for p in [
"/repo/{own}/scratchpad/cases.txt",
"/repo/{own}/memory/MEMORY.md",
"/Users/me/{own}/memory/MEMORY.md",
"/repo/{own}/state",
"/repo/{own}/state/",
"/repo/{own}/state/notes.md",
"/repo/{own}/state/scratchpad.md",
"/repo/{own}/state/tool-results/s/r.txt",
"/repo/{own}/state/telemetry/s.jsonl",
"/repo/{own}/state/teams/t/team.json",
"/repo/{own}/state/history/s/transcript.jsonl",
"/repo/{own}/state/.imported.json",
"/repo/{own}/state/codix/x",
"/repo/{own}/state/agix/x",
"echo x > \"$d/{own}/state\";x/scratchpad",
"/repo/{own}/agents/reviewer.md",
"/repo/{own}/scratchpad.md",
"/repo/{own}/worktrees/feat-a/feature.txt",
"/repo/{wk}/feat-a/{own}/agents/reviewer.md",
"/repo/{wk}/feat-a/.agix/agents/reviewer.md",
"/repo/{wk}/feat-a/.claude/settings.json",
"/repo/{wk}/feat-a/.git",
"/repo/.claude/scratchpad/x",
] {
assert!(paths.names_configuration(&own(p, &layout)), "{p}");
}
}
let codix = in_layout(&Layout::new(".codix").unwrap());
for p in [
"/repo/.agix/scratchpad/x",
"/repo/.agix/state/scratchpad/x",
"/repo/.agix/worktrees/a/f.txt",
] {
assert!(
codix.names_configuration(p),
"a foreign .agix has no working space: {p}"
);
}
}
#[test]
fn the_state_roots_working_space_is_directly_in_it() {
for layout in test_layouts() {
let root = own("/Users/me/{own}", &layout);
let paths = SensitivePaths::new(Some(Path::new(&root)), None, layout.clone());
for p in [
"/Users/me/{own}/memory/MEMORY.md",
"/Users/me/{own}/scratchpad/sessions/s/x",
"/Users/me/{own}/state/scratchpad/x",
"S=/Users/me/{own}/scratchpad/x",
"echo x > \"/Users/ME/{own}/memory/a.md\"",
] {
assert!(!paths.names_configuration(&own(p, &layout)), "{p}");
}
for p in [
"/Users/me/{own}/settings.json",
"/Users/me/{own}/tool-results/s/x",
"/Users/you/{own}/memory/MEMORY.md",
"/x/Users/me/{own}/memory/MEMORY.md",
"x/Users/me/{own}/memory/MEMORY.md",
"/repo/{own}/memory/MEMORY.md",
] {
assert!(paths.names_configuration(&own(p, &layout)), "{p}");
}
}
}
#[test]
fn the_state_roots_working_space_spelled_from_home_is_not_configuration() {
for layout in test_layouts() {
let root = own("/Users/me/{own}", &layout);
let paths = SensitivePaths {
state_root: Some(Spellings::of_with_home(
Path::new(&root),
Some(Path::new("/Users/me")),
)),
..SensitivePaths::new(None, None, layout.clone())
};
for p in [
"cat ~/{own}/memory/MEMORY.md",
"echo x > $HOME/{own}/memory/a.md",
"ls \"${HOME}/{own}/scratchpad/sessions\"",
"S=~/{own}/scratchpad/x",
] {
assert!(!paths.names_configuration(&own(p, &layout)), "{p}");
}
for p in [
"cat ~/{own}/settings.json",
"cat ~/{own}/tool-results/s/x",
"cat x~/{own}/memory/MEMORY.md",
"cat $HOMEX/{own}/memory/MEMORY.md",
"cat ~/other/{own}/memory/MEMORY.md",
] {
assert!(paths.names_configuration(&own(p, &layout)), "{p}");
}
}
}
#[test]
fn only_scratchpad_and_memory_in_state_are_writable() {
let codix = Layout::new(".codix")
.unwrap()
.with_product_name("Codix")
.unwrap();
let roots = SensitivePaths::new(None, None, codix.clone())
.config_roots_in(Path::new("/nowhere/repo"));
let own = roots.iter().find(|r| r.own).unwrap();
assert_eq!(own.state_dir(), Path::new("/nowhere/repo/.codix/state"));
assert_eq!(
own.working_entries(),
[
PathBuf::from("/nowhere/repo/.codix/state/scratchpad"),
PathBuf::from("/nowhere/repo/.codix/state/memory")
]
);
let mut writable: Vec<&str> = STATE_RESERVED_NAMES
.iter()
.copied()
.chain([entry::IMPORTED_MARKER, entry::STATE, "codix", "notes.md"])
.filter(|name| own.writable_state_entry(name))
.collect();
writable.sort_unstable();
assert_eq!(writable, [entry::MEMORY, entry::SCRATCHPAD]);
for foreign in roots.iter().filter(|r| !r.own) {
assert!(foreign.working_entries().is_empty(), "{:?}", foreign.path);
assert!(STATE_ROOT_WORKING_DIRS
.iter()
.all(|name| !foreign.writable_state_entry(name)));
}
}
#[test]
fn what_the_gate_treats_as_working_space_the_sandbox_leaves_writable() {
let paths = SensitivePaths::default();
for name in STATE_ROOT_WORKING_DIRS {
assert!(paths.is_engine_working_entry(name), "{name}");
assert!(
!ENGINE_CONFIG_DIRS.contains(name) && !ENGINE_CONFIG_FILES.contains(name),
"{name}"
);
}
}
#[test]
fn engine_settings_files_are_known_by_name_under_a_config_root() {
for layout in test_layouts() {
let paths = in_layout(&layout);
for p in [
"/repo/{own}/settings.json",
"/repo/.agix/settings.json",
"/repo/.claude/settings.local.json",
"/repo/{wk}/a/{own}/mcp.local.json",
"/repo/{own}/agents/settings.json",
"/repo/{OWN}/Settings.json",
"/repo/.Agix/SETTINGS.LOCAL.JSON",
"/repo/.CLAUDE/settings.json",
] {
let p = &p.replace("{OWN}", &layout.project_dir_name().to_uppercase());
assert!(
paths.is_engine_settings_file(Path::new(&own(p, &layout))),
"{p}"
);
}
for p in [
"/repo/settings.json",
"/repo/{own}/scene.json",
"/repo/{own}",
] {
assert!(
!paths.is_engine_settings_file(Path::new(&own(p, &layout))),
"{p}"
);
}
}
assert!(!sensitive("/s").is_engine_settings_file(Path::new("/repo/.codix/settings.json")));
}
#[test]
fn the_sandbox_is_told_the_engine_directories_of_a_project() {
let codix = Layout::new(".codix")
.unwrap()
.with_worktrees_dir(".trees")
.unwrap();
let paths = SensitivePaths::new(None, None, codix.clone());
let at: Vec<(PathBuf, bool)> = paths
.config_roots_in(Path::new("/nowhere/repo"))
.into_iter()
.map(|r| (r.path, r.own))
.collect();
assert_eq!(
at,
[
(PathBuf::from("/nowhere/repo/.codix"), true),
(PathBuf::from("/nowhere/repo/.agix"), false),
(PathBuf::from("/nowhere/repo/.claude"), false)
]
);
assert_eq!(
paths.engine_dirs_in(Path::new("/nowhere/repo")),
[
PathBuf::from("/nowhere/repo/.codix"),
PathBuf::from("/nowhere/repo/.agix")
]
);
assert_eq!(
paths.worktree_dirs_in(Path::new("/nowhere/repo")),
[
PathBuf::from("/nowhere/repo/.trees"),
PathBuf::from("/nowhere/repo/.wkts")
]
);
assert_eq!(
SensitivePaths::default().engine_dirs_in(Path::new("/nowhere/repo")),
[PathBuf::from("/nowhere/repo/.agix")]
);
assert_eq!(
SensitivePaths::default().worktree_dirs_in(Path::new("/nowhere/repo")),
[PathBuf::from("/nowhere/repo/.wkts")]
);
}
#[test]
fn a_prompt_file_is_neither_a_credential_nor_a_link_out_of_the_root() {
use std::os::unix::fs::symlink;
let tmp = tempfile::tempdir().unwrap();
let (state, project, elsewhere) = (
tmp.path().join("state"),
tmp.path().join("project"),
tmp.path().join("elsewhere"),
);
for dir in [
&state,
&project.join(".agix"),
&project.join("docs"),
&elsewhere,
] {
std::fs::create_dir_all(dir).unwrap();
}
std::fs::write(state.join("settings.json"), "state key").unwrap();
std::fs::write(project.join(".agix/settings.local.json"), "project key").unwrap();
std::fs::write(project.join("docs/guide.md"), "guide").unwrap();
std::fs::write(elsewhere.join("notes.md"), "notes").unwrap();
symlink("docs/guide.md", project.join("AGENTS.md")).unwrap();
symlink(".agix/settings.local.json", project.join("KEY.md")).unwrap();
symlink("../elsewhere/notes.md", project.join("OUT.md")).unwrap();
symlink(
"../project/.agix/settings.local.json",
elsewhere.join("key.md"),
)
.unwrap();
symlink("../state/settings.json", elsewhere.join("state.md")).unwrap();
let files =
SensitivePaths::new(Some(&state), Some(&project), Layout::default()).prompt_files();
let read = |p: PathBuf| files.read_to_string(&p).map_err(|e| e.kind());
let denied = Err(std::io::ErrorKind::PermissionDenied);
assert_eq!(read(project.join("AGENTS.md")), Ok("guide".into()));
assert_eq!(read(project.join("KEY.md")), denied);
assert_eq!(read(project.join(".agix/settings.local.json")), denied);
assert_eq!(read(project.join("OUT.md")), denied);
assert_eq!(read(elsewhere.join("notes.md")), Ok("notes".into()));
assert_eq!(read(elsewhere.join("key.md")), denied);
assert_eq!(read(elsewhere.join("state.md")), denied);
assert_eq!(
read(project.join("missing.md")),
Err(std::io::ErrorKind::NotFound)
);
let nested_state = project.join("home-state");
std::fs::create_dir_all(&nested_state).unwrap();
symlink("../../elsewhere/notes.md", nested_state.join("skill.md")).unwrap();
let files = SensitivePaths::new(Some(&nested_state), None, Layout::default())
.prompt_files_within(&project);
assert_eq!(
files
.read_to_string(&nested_state.join("skill.md"))
.map_err(|e| e.kind()),
Ok("notes".into()),
"the state root's files are the user's, wherever it sits"
);
}
}