Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(wiki): confine page I/O to the project tree

AkitaOnRails16c5ce43a7db
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 20b2a554..a6ca76c9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
provider. (#1026)
### Fixed
+- Confined wiki reads, writes, indexing, recovery, and lifecycle cleanup to real
+ project-tree directories by refusing symbolic links and filesystem reparse
+ points at namespace roots or descendants. (#NNN)
- Fixed `memory_handoff_list` MCP tool calls being counted under writes in
`client_activity`: the read-only inspection tool is now classified as a read
in `tool_call_is_write`. (#1088)
diff --git a/SECURITY.md b/SECURITY.md
index 023097b4..0825f609 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -78,7 +78,14 @@ what the project is and is not designed to defend against.
`(workspace_id, project_id)`. A purge operation for project A cannot
delete files that also belong to project B. Entity lookup filters at the
project CTE and page boundaries; V38 triggers reject mismatched
- workspace/project entities and cross-project entity/page links.
+ workspace/project entities and cross-project entity/page links. The wiki
+ directory is imported, operator-editable content and is therefore treated as
+ untrusted: symbolic links and filesystem reparse points at the wiki root,
+ workspace/project roots, or any descendant are refused for page reads,
+ writes, indexing, recovery, and lifecycle cleanup. These component checks
+ protect against links already present when an operation runs; they do not
+ claim descriptor-relative protection against a concurrently malicious process
+ running as the same operating-system user.
- **Entity text remains bounded local data.** Consolidator output and
hand-edited `entities:` frontmatter cross the same normalization boundary:
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 71f2b2d1..abd25fbf 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -854,6 +854,9 @@ async fn handle_backup(State(state): State<Arc<AdminState>>) -> Response {
}
async fn build_backup_tarball_file(state: &AdminState) -> anyhow::Result<tokio::fs::File> {
+ let wiki_dir = state.data_dir.join("wiki");
+ ai_memory_wiki::validate_wiki_tree(&wiki_dir)
+ .map_err(|error| anyhow::anyhow!("validating wiki tree: {error}"))?;
let staging = tempfile::tempdir()?;
let snapshot_path = staging.path().join("memory.sqlite");
info!(snapshot = %snapshot_path.display(), "snapshotting SQLite for backup");
@@ -870,7 +873,8 @@ async fn build_backup_tarball_file(state: &AdminState) -> anyhow::Result<tokio::
tar.mode(tar::HeaderMode::Deterministic);
tar.follow_symlinks(false);
- let wiki_dir = state.data_dir.join("wiki");
+ ai_memory_wiki::validate_wiki_tree(&wiki_dir)
+ .map_err(|error| anyhow::anyhow!("validating wiki tree before archive: {error}"))?;
if wiki_dir.is_dir() {
tar.append_dir_all("wiki", &wiki_dir)
.map_err(|e| anyhow::anyhow!("archiving wiki/: {e}"))?;
@@ -947,11 +951,8 @@ async fn build_okf_bundle_file(
proj: ai_memory_core::ProjectId,
project_name: &str,
) -> anyhow::Result<tokio::fs::File> {
- let bundle_dir = state
- .data_dir
- .join("wiki")
- .join(ws.to_string())
- .join(proj.to_string());
+ state.wiki.validate_project_tree(ws, proj)?;
+ let bundle_dir = state.wiki.project_root(ws, proj);
if !bundle_dir.is_dir() {
anyhow::bail!("project has no wiki directory yet");
}
@@ -5389,6 +5390,9 @@ async fn delete_workspace_core(
actor,
..Default::default()
};
+ if let Err(error) = state.wiki.validate_workspace_tree(ws_id) {
+ return Err(internal_err(error.to_string()));
+ }
let resolved_purge_ctx = match state
.wiki
.admit_purge_workspace(ws_id, Some(purge_ctx))
@@ -5826,6 +5830,14 @@ async fn true_move_project(
// A true move targets a FRESH destination, so its dir must not already
// exist. Wiki::move_project_workspace repeats this check under the
// exclusive mutation guard before it renames anything.
+ state
+ .wiki
+ .validate_project_tree(src_ws, src_proj)
+ .map_err(|error| internal_err(error.to_string()))?;
+ state
+ .wiki
+ .validate_project_tree(dst_ws, src_proj)
+ .map_err(|error| internal_err(error.to_string()))?;
let dst_dir = state.wiki.project_root(dst_ws, src_proj);
if dst_dir.exists() {
return Err((
@@ -6668,6 +6680,10 @@ async fn move_planned_session(
}
}
+ state
+ .wiki
+ .validate_project_tree(plan.from.0, plan.from.1)
+ .map_err(move_session_wiki_err)?;
let cwd_warning = move_session_cwd_warning(plan.cwd.as_deref(), &plan.to_label.project);
let file_name = format!("{sid}.md");
let src_file = state
@@ -6712,6 +6728,10 @@ async fn move_planned_session(
// too so the dry run predicts what the wiki re-checks under its lock. When
// the source scope IS the destination (single-form re-home) there is no
// file to move and the wiki skips the file step too.
+ state
+ .wiki
+ .validate_project_tree(to.0, to.1)
+ .map_err(move_session_wiki_err)?;
let dst_file = state
.wiki
.project_root(to.0, to.1)
diff --git a/crates/ai-memory-mcp/tests/suite/admin_backup.rs b/crates/ai-memory-mcp/tests/suite/admin_backup.rs
index 006c7530..abc8941e 100644
--- a/crates/ai-memory-mcp/tests/suite/admin_backup.rs
+++ b/crates/ai-memory-mcp/tests/suite/admin_backup.rs
@@ -213,14 +213,63 @@ fn create_test_symlink_file(target: &std::path::Path, link: &std::path::Path) ->
}
}
+#[cfg(unix)]
+fn create_test_symlink_dir(target: &std::path::Path, link: &std::path::Path) -> bool {
+ std::os::unix::fs::symlink(target, link).unwrap();
+ true
+}
+
+#[cfg(windows)]
+fn create_test_symlink_dir(target: &std::path::Path, link: &std::path::Path) -> bool {
+ match std::os::windows::fs::symlink_dir(target, link) {
+ Ok(()) => true,
+ Err(e) if e.raw_os_error() == Some(1314) => {
+ eprintln!("skipping directory reparse assertion: Windows privilege unavailable");
+ false
+ }
+ Err(e) => panic!(
+ "failed to create test directory link {}: {e}",
+ link.display()
+ ),
+ }
+}
+
+#[tokio::test]
+async fn backup_refuses_redirected_git_metadata_before_returning_an_archive() {
+ let tmp = TempDir::new().unwrap();
+ let (state, _store) = make_state(&tmp).await;
+ std::fs::write(state.wiki.root().join(".git/commondir"), "../outside\n").unwrap();
+
+ let response = admin_router(state)
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/admin/backup")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
+ assert_eq!(
+ response
+ .headers()
+ .get("content-type")
+ .and_then(|value| value.to_str().ok()),
+ Some("application/json")
+ );
+}
+
#[cfg(any(unix, windows))]
#[tokio::test]
-async fn backup_does_not_dereference_wiki_symlinks() {
+async fn backup_refuses_wiki_leaf_links_before_returning_an_archive() {
let tmp = TempDir::new().unwrap();
let (state, _store) = make_state(&tmp).await;
let wiki_dir = tmp.path().join("wiki");
std::fs::create_dir_all(&wiki_dir).unwrap();
+ let archive_marker = tmp.path().join("archive-created");
+ assert!(!archive_marker.exists());
let secret = tmp.path().join("outside-secret.md");
let secret_body = "outside secret must not enter backup";
std::fs::write(&secret, secret_body).unwrap();
@@ -239,27 +288,57 @@ async fn backup_does_not_dereference_wiki_symlinks() {
)
.await
.unwrap();
- assert_eq!(resp.status(), StatusCode::OK);
-
- let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
+ assert_eq!(
+ resp.headers()
+ .get("content-type")
+ .and_then(|value| value.to_str().ok()),
+ Some("application/json")
+ );
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
- let decoder = GzDecoder::new(bytes.as_ref());
- let mut archive = Archive::new(decoder);
- for entry in archive.entries().expect("tarball must be readable") {
- let mut entry = entry.expect("entry must be readable");
- if !entry.header().entry_type().is_file() {
- continue;
- }
- let mut body = Vec::new();
- entry
- .read_to_end(&mut body)
- .expect("regular file entry must be readable");
- assert!(
- !body
- .windows(secret_body.len())
- .any(|window| window == secret_body.as_bytes()),
- "backup must not include symlink target contents"
- );
+ assert!(
+ !body
+ .windows(secret_body.len())
+ .any(|window| window == secret_body.as_bytes()),
+ "refusal must not disclose the external canary"
+ );
+}
+
+#[cfg(any(unix, windows))]
+#[tokio::test]
+async fn backup_refuses_linked_wiki_directories_before_returning_an_archive() {
+ let tmp = TempDir::new().unwrap();
+ let (state, _store) = make_state(&tmp).await;
+ let outside = tmp.path().join("outside");
+ std::fs::create_dir(&outside).unwrap();
+ let canary = outside.join("canary.md");
+ std::fs::write(&canary, "outside directory canary").unwrap();
+ if !create_test_symlink_dir(&outside, &state.wiki.root().join("linked")) {
+ return;
}
+
+ let response = admin_router(state)
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/admin/backup")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
+ assert_eq!(
+ response
+ .headers()
+ .get("content-type")
+ .and_then(|value| value.to_str().ok()),
+ Some("application/json")
+ );
+ assert_eq!(
+ std::fs::read_to_string(canary).unwrap(),
+ "outside directory canary"
+ );
}
diff --git a/crates/ai-memory-mcp/tests/suite/admin_move.rs b/crates/ai-memory-mcp/tests/suite/admin_move.rs
index 7916af4d..71c4e1c8 100644
--- a/crates/ai-memory-mcp/tests/suite/admin_move.rs
+++ b/crates/ai-memory-mcp/tests/suite/admin_move.rs
@@ -848,12 +848,10 @@ async fn ids(
(ws_id, proj_id)
}
-/// W1: when the on-disk dir rename fails mid true-move, the SQL re-stamp is
-/// rolled back so NOTHING moves (no DB-ahead-of-disk split-brain). We force the
-/// rename to fail by planting a FILE where the destination workspace dir would
-/// be created.
+/// A non-directory namespace component is refused before the project move, so
+/// neither disk nor SQLite changes.
#[tokio::test]
-async fn true_move_rolls_back_when_dir_rename_fails() {
+async fn true_move_refuses_an_invalid_destination_namespace_without_db_changes() {
let tmp = TempDir::new().unwrap();
let (state, store) = make_state(&tmp).await;
seed_page(&store, &state.wiki, "src", "proj", "notes/a.md", "body a").await;
@@ -882,7 +880,7 @@ async fn true_move_rolls_back_when_dir_rename_fails() {
body["error"]
.as_str()
.unwrap_or("")
- .contains("nothing changed"),
+ .contains("not a directory"),
"{body}"
);
@@ -2946,7 +2944,7 @@ async fn delete_workspace_reject_policy_aborts_before_db_or_disk_destruction() {
}
#[tokio::test]
-async fn delete_workspace_reports_partial_disk_failure_and_dispatches_notification() {
+async fn delete_workspace_refuses_invalid_namespace_before_db_or_notification() {
let (url, rx) = spawn_capture_hook().await;
let tmp = TempDir::new().unwrap();
@@ -2978,28 +2976,28 @@ async fn delete_workspace_reports_partial_disk_failure_and_dispatches_notificati
)
.await;
- assert_eq!(resp.status(), StatusCode::OK);
+ assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
let body = body_json(resp).await;
assert!(
- body["files_deleted"].as_array().unwrap().is_empty(),
+ body["error"]
+ .as_str()
+ .unwrap_or("")
+ .contains("not a directory"),
"{body}"
);
- assert_eq!(body["files_failed"].as_array().unwrap().len(), 1, "{body}");
assert!(
store
.reader
.find_workspace("victim".into())
.await
.unwrap()
- .is_none(),
- "DB delete should still commit and be reported as partial filesystem failure"
+ .is_some(),
+ "namespace refusal must leave DB rows intact"
+ );
+ assert!(
+ tokio::time::timeout(std::time::Duration::from_millis(100), rx)
+ .await
+ .is_err(),
+ "a refused operation must not notify observers"
);
-
- let payload = tokio::time::timeout(std::time::Duration::from_secs(2), rx)
- .await
- .expect("async purge_workspace dispatch should fire")
- .unwrap();
- assert_eq!(payload["ctx"]["op"], "purge_workspace");
- assert_eq!(payload["ctx"]["workspace"], "victim");
- assert_eq!(payload["ctx"]["partial_failure"], true);
}
diff --git a/crates/ai-memory-mcp/tests/suite/admin_read_page.rs b/crates/ai-memory-mcp/tests/suite/admin_read_page.rs
index a9649189..f5553922 100644
--- a/crates/ai-memory-mcp/tests/suite/admin_read_page.rs
+++ b/crates/ai-memory-mcp/tests/suite/admin_read_page.rs
@@ -48,6 +48,11 @@ async fn body_json(resp: axum::response::Response) -> serde_json::Value {
serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null)
}
+#[cfg(unix)]
+fn symlink(target: &std::path::Path, link: &std::path::Path) {
+ std::os::unix::fs::symlink(target, link).unwrap();
+}
+
/// A page present in the store but NOT on disk (the index is ahead of the
/// filesystem) is still served — from the DB copy — rather than 404ing.
#[tokio::test]
@@ -153,6 +158,58 @@ async fn read_page_serves_on_disk_page() {
assert!(body.get("served_from").is_none(), "{body}");
}
+#[cfg(unix)]
+#[tokio::test]
+async fn read_page_does_not_db_fallback_through_a_symlink() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default".to_string())
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch".to_string(), None)
+ .await
+ .unwrap();
+ let path = PagePath::new("notes/linked.md").unwrap();
+ state
+ .wiki
+ .write_page(WritePageRequest {
+ workspace_id: ws,
+ project_id: proj,
+ path: path.clone(),
+ frontmatter: serde_json::json!({"title": "Stored Copy"}),
+ body: "database fallback must stay hidden".to_string(),
+ tier: Tier::Semantic,
+ pinned: false,
+ title: Some("Stored Copy".into()),
+ admission_ctx: None,
+ author_id: None,
+ actor: ai_memory_core::ActorContext::anonymous(),
+ evidence: Vec::new(),
+ })
+ .await
+ .unwrap();
+ let outside = TempDir::new().unwrap();
+ let canary = outside.path().join("page.md");
+ std::fs::write(&canary, "outside canary").unwrap();
+ let abs = state.wiki.abs_path(ws, proj, &path);
+ std::fs::remove_file(&abs).unwrap();
+ symlink(&canary, &abs);
+
+ let resp = get(
+ state,
+ "/admin/read-page?workspace=default&project=scratch&path=notes%2Flinked.md",
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
+ let body = body_json(resp).await;
+ assert!(body["error"].as_str().unwrap_or("").contains("confinement"));
+ assert!(body.get("served_from").is_none(), "{body}");
+}
+
/// A malformed markdown source must not be hidden by the DB fallback. The disk
/// file is the source of truth; parse errors need to be visible to operators.
#[tokio::test]
diff --git a/crates/ai-memory-wiki/src/backup.rs b/crates/ai-memory-wiki/src/backup.rs
index 3dc1c5c0..4e79734d 100644
--- a/crates/ai-memory-wiki/src/backup.rs
+++ b/crates/ai-memory-wiki/src/backup.rs
@@ -136,6 +136,7 @@ fn create_pre_migration_backup_inner(
dest_override: Option<&Path>,
in_container: bool,
) -> WikiResult<BackupReceipt> {
+ crate::confinement::inspect_tree_if_present(&data_dir.join("wiki"))?;
// One spelling for every comparison below: `destination_dir` returns a
// canonical path, so the walk must produce canonical paths too or the
// self-exclusion guards (`path == dest_dir`, `path == archive_path`)
@@ -144,6 +145,7 @@ fn create_pre_migration_backup_inner(
let data_dir = &data_dir
.canonicalize()
.unwrap_or_else(|_| data_dir.to_path_buf());
+ crate::confinement::inspect_tree(data_dir)?;
let dest_dir = destination_dir(dest_override, data_dir, in_container)?;
let stamp = jiff::Timestamp::now().strftime("%Y%m%d-%H%M%S").to_string();
let archive_path = dest_dir.join(format!("ai-memory-backup-{label}-{stamp}.tar.gz"));
@@ -164,8 +166,14 @@ fn create_pre_migration_backup_inner(
let rel = path
.strip_prefix(data_dir)
.map_err(|e| WikiError::Io(std::io::Error::other(e)))?;
- let ft = entry.file_type()?;
- if ft.is_dir() {
+ let metadata = std::fs::symlink_metadata(&path)?;
+ if crate::confinement::is_link_like(&metadata) {
+ return Err(WikiError::Confinement {
+ path,
+ reason: "symbolic links and reparse points are not allowed in backups",
+ });
+ }
+ if metadata.is_dir() {
// Never archive the destination itself (a container
// default of <data_dir>/backups, or an override
// pointed inside the data dir) — self-inclusion
@@ -174,7 +182,7 @@ fn create_pre_migration_backup_inner(
continue;
}
stack.push(path);
- } else if ft.is_file() {
+ } else if metadata.is_file() {
let file_name = path.file_name().and_then(|n| n.to_str());
if path == archive_path
|| file_name == Some("pre-migration-backup.json.tmp")
@@ -192,8 +200,6 @@ fn create_pre_migration_backup_inner(
tar.append_path_with_name(&path, rel)?;
expected += 1;
}
- // Symlinks are skipped: nothing in a data dir should be
- // one, and following one out of the tree must not happen.
}
}
tar.into_inner()?.finish()?;
@@ -264,6 +270,26 @@ mod tests {
tmp
}
+ #[cfg(unix)]
+ #[test]
+ fn a_pre_migration_backup_refuses_a_linked_wiki_tree_without_an_archive() {
+ let data = data_dir_with_content();
+ let outside = TempDir::new().unwrap();
+ std::fs::write(outside.path().join("canary.md"), "outside canary").unwrap();
+ std::os::unix::fs::symlink(outside.path(), data.path().join("wiki/linked")).unwrap();
+ let dest = TempDir::new().unwrap();
+
+ assert!(matches!(
+ create_pre_migration_backup(data.path(), "test", Some(dest.path())),
+ Err(WikiError::Confinement { .. })
+ ));
+ assert_eq!(std::fs::read_dir(dest.path()).unwrap().count(), 0);
+ assert_eq!(
+ std::fs::read_to_string(outside.path().join("canary.md")).unwrap(),
+ "outside canary"
+ );
+ }
+
#[test]
fn a_backup_archives_everything_and_writes_a_receipt() {
let data = data_dir_with_content();
diff --git a/crates/ai-memory-wiki/src/confinement.rs b/crates/ai-memory-wiki/src/confinement.rs
new file mode 100644
index 00000000..6884335a
--- /dev/null
+++ b/crates/ai-memory-wiki/src/confinement.rs
@@ -0,0 +1,307 @@
+//! Filesystem confinement for the namespaced wiki tree.
+
+use std::path::{Component, Path, PathBuf};
+
+use ai_memory_core::{ProjectId, WorkspaceId};
+
+use crate::error::{WikiError, WikiResult};
+
+#[derive(Clone, Copy)]
+pub(crate) enum Prepare {
+ Inspect,
+ Parents,
+ Directory,
+}
+
+pub(crate) fn initialize_root(root: &Path) -> WikiResult<()> {
+ match std::fs::symlink_metadata(root) {
+ Ok(metadata) => require_directory(root, &metadata),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
+ std::fs::create_dir(root)?;
+ inspect_created_directory(root)
+ }
+ Err(error) => Err(error.into()),
+ }
+}
+
+pub(crate) fn project_root(
+ root: &Path,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ prepare: Prepare,
+) -> WikiResult<PathBuf> {
+ tree_path(
+ root,
+ &PathBuf::from(workspace_id.to_string()).join(project_id.to_string()),
+ prepare,
+ )
+}
+
+pub(crate) fn project_path(
+ root: &Path,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ relative: &Path,
+ prepare: Prepare,
+) -> WikiResult<PathBuf> {
+ tree_path(
+ root,
+ &PathBuf::from(workspace_id.to_string())
+ .join(project_id.to_string())
+ .join(relative),
+ prepare,
+ )
+}
+
+pub(crate) fn workspace_path(
+ root: &Path,
+ workspace_id: WorkspaceId,
+ prepare: Prepare,
+) -> WikiResult<PathBuf> {
+ tree_path(root, Path::new(&workspace_id.to_string()), prepare)
+}
+
+pub(crate) fn tree_path(root: &Path, relative: &Path, prepare: Prepare) -> WikiResult<PathBuf> {
+ validate_relative(relative)?;
+ inspect_root(root)?;
+ let components: Vec<_> = relative.components().collect();
+ let ancestor_count = match prepare {
+ Prepare::Inspect | Prepare::Parents => components.len().saturating_sub(1),
+ Prepare::Directory => components.len(),
+ };
+ let create = !matches!(prepare, Prepare::Inspect);
+ let mut current = root.to_path_buf();
+ let mut missing = false;
+ for component in components.iter().take(ancestor_count) {
+ current.push(component.as_os_str());
+ match std::fs::symlink_metadata(&current) {
+ Ok(metadata) => require_directory(&current, &metadata)?,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
+ missing = true;
+ if create {
+ std::fs::create_dir(&current)?;
+ inspect_created_directory(&current)?;
+ }
+ }
+ Err(error) => return Err(error.into()),
+ }
+ if missing && !create {
+ break;
+ }
+ }
+
+ let target = root.join(relative);
+ if !matches!(prepare, Prepare::Directory) && !missing {
+ inspect_final(&target)?;
+ }
+ Ok(target)
+}
+
+/// Validate the complete wiki tree and its in-root repository metadata.
+///
+/// # Errors
+/// Returns [`WikiError::Confinement`] for symbolic links, reparse points,
+/// redirected repository metadata, or a working tree outside `root`.
+pub fn validate_wiki_tree(root: &Path) -> WikiResult<()> {
+ let git_dir = inspect_git_directory(root)?;
+ inspect_tree_except(root, &[git_dir.as_path()])
+}
+
+pub(crate) fn inspect_tree(root: &Path) -> WikiResult<()> {
+ inspect_tree_except(root, &[])
+}
+
+pub(crate) fn inspect_git_directory(root: &Path) -> WikiResult<PathBuf> {
+ inspect_root(root)?;
+ let git_dir = root.join(".git");
+ let metadata = std::fs::symlink_metadata(&git_dir).map_err(|error| {
+ if error.kind() == std::io::ErrorKind::NotFound {
+ WikiError::Confinement {
+ path: git_dir.clone(),
+ reason: "wiki repository metadata directory is missing",
+ }
+ } else {
+ error.into()
+ }
+ })?;
+ if is_link_like(&metadata) || !metadata.is_dir() {
+ return Err(WikiError::Confinement {
+ path: git_dir,
+ reason: "wiki repository metadata must be an in-root ordinary directory",
+ });
+ }
+ for relative in [
+ "commondir",
+ "objects/info/alternates",
+ "objects/info/http-alternates",
+ ] {
+ let redirect = git_dir.join(relative);
+ match std::fs::symlink_metadata(&redirect) {
+ Ok(_) => {
+ return Err(WikiError::Confinement {
+ path: redirect,
+ reason: "wiki repository metadata must not redirect outside its in-root .git directory",
+ });
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
+ Err(error) => return Err(error.into()),
+ }
+ }
+ inspect_tree(&git_dir)?;
+ inspect_configured_worktree(root, &git_dir)?;
+ Ok(git_dir)
+}
+
+fn inspect_configured_worktree(root: &Path, git_dir: &Path) -> WikiResult<()> {
+ for config_path in [git_dir.join("config"), git_dir.join("config.worktree")] {
+ if !config_path.is_file() {
+ continue;
+ }
+ let config = git2::Config::open(&config_path).map_err(|error| {
+ WikiError::Io(std::io::Error::other(format!(
+ "could not inspect wiki repository config {}: {error}",
+ config_path.display()
+ )))
+ })?;
+ let Ok(configured) = config.get_string("core.worktree") else {
+ continue;
+ };
+ let configured = PathBuf::from(configured);
+ let worktree = if configured.is_absolute() {
+ configured
+ } else {
+ git_dir.join(configured)
+ };
+ if worktree.canonicalize()? != root.canonicalize()? {
+ return Err(WikiError::Confinement {
+ path: config_path,
+ reason: "wiki repository working directory escapes the wiki root",
+ });
+ }
+ }
+ Ok(())
+}
+
+pub(crate) fn inspect_tree_if_present(root: &Path) -> WikiResult<()> {
+ match std::fs::symlink_metadata(root) {
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ _ => inspect_tree(root),
+ }
+}
+
+pub(crate) fn inspect_tree_except(root: &Path, excluded_roots: &[&Path]) -> WikiResult<()> {
+ match std::fs::symlink_metadata(root) {
+ Ok(metadata) => require_directory(root, &metadata)?,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
+ Err(error) => return Err(error.into()),
+ }
+ let mut stack = vec![root.to_path_buf()];
+ while let Some(directory) = stack.pop() {
+ for entry in std::fs::read_dir(&directory)? {
+ let entry = entry?;
+ let path = entry.path();
+ let metadata = std::fs::symlink_metadata(&path)?;
+ if is_link_like(&metadata) {
+ return Err(confined(&path));
+ }
+ if excluded_roots.iter().any(|excluded| path == *excluded) {
+ continue;
+ }
+ if metadata.is_dir() {
+ stack.push(path);
+ }
+ }
+ }
+ Ok(())
+}
+
+/// Whether metadata identifies a symbolic link or Windows reparse point.
+#[must_use]
+pub(crate) fn is_link_like(metadata: &std::fs::Metadata) -> bool {
+ #[cfg(windows)]
+ {
+ use std::os::windows::fs::MetadataExt as _;
+ const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0400;
+ metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
+ }
+ #[cfg(not(windows))]
+ {
+ metadata.file_type().is_symlink()
+ }
+}
+
+fn inspect_root(root: &Path) -> WikiResult<()> {
+ let metadata = std::fs::symlink_metadata(root)?;
+ require_directory(root, &metadata)
+}
+
+fn inspect_final(path: &Path) -> WikiResult<()> {
+ match std::fs::symlink_metadata(path) {
+ Ok(metadata) if is_link_like(&metadata) => Err(confined(path)),
+ Ok(_) => Ok(()),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(error) => Err(error.into()),
+ }
+}
+
+fn inspect_created_directory(path: &Path) -> WikiResult<()> {
+ let metadata = std::fs::symlink_metadata(path)?;
+ require_directory(path, &metadata)
+}
+
+fn require_directory(path: &Path, metadata: &std::fs::Metadata) -> WikiResult<()> {
+ if is_link_like(metadata) {
+ return Err(confined(path));
+ }
+ if !metadata.is_dir() {
+ return Err(WikiError::Io(std::io::Error::new(
+ std::io::ErrorKind::NotADirectory,
+ format!("wiki path component is not a directory: {}", path.display()),
+ )));
+ }
+ Ok(())
+}
+
+fn validate_relative(relative: &Path) -> WikiResult<()> {
+ if relative.as_os_str().is_empty()
+ || relative
+ .components()
+ .any(|component| !matches!(component, Component::Normal(_)))
+ {
+ return Err(WikiError::Confinement {
+ path: relative.to_path_buf(),
+ reason: "path is not a normalized relative wiki path",
+ });
+ }
+ Ok(())
+}
+
+fn confined(path: &Path) -> WikiError {
+ WikiError::Confinement {
+ path: path.to_path_buf(),
+ reason: "symbolic links and reparse points are not allowed in the wiki project tree",
+ }
+}
+
+#[cfg(test)]
+#[allow(clippy::disallowed_methods)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn link_metadata_helper_accepts_regular_entries() {
+ let temp = tempfile::tempdir().unwrap();
+ let file = temp.path().join("file");
+ std::fs::write(&file, b"x").unwrap();
+ assert!(!is_link_like(&std::fs::symlink_metadata(file).unwrap()));
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn link_metadata_helper_rejects_dangling_links() {
+ let temp = tempfile::tempdir().unwrap();
+ let link = temp.path().join("link");
+ std::os::unix::fs::symlink(temp.path().join("missing"), &link).unwrap();
+ assert!(is_link_like(&std::fs::symlink_metadata(link).unwrap()));
+ }
+}
diff --git a/crates/ai-memory-wiki/src/error.rs b/crates/ai-memory-wiki/src/error.rs
index 4b4d6231..a2f83217 100644
--- a/crates/ai-memory-wiki/src/error.rs
+++ b/crates/ai-memory-wiki/src/error.rs
@@ -2,6 +2,7 @@
use ai_memory_core::MemoryError;
use ai_memory_store::StoreError;
+use std::path::PathBuf;
use thiserror::Error;
/// Result alias used throughout the wiki crate.
@@ -15,6 +16,15 @@ pub enum WikiError {
#[error(transparent)]
Io(#[from] std::io::Error),
+ /// A wiki filesystem path crossed a symbolic-link or reparse-point boundary.
+ #[error("wiki path confinement refused {path}: {reason}")]
+ Confinement {
+ /// Path that failed confinement.
+ path: PathBuf,
+ /// Stable classification of the refusal.
+ reason: &'static str,
+ },
+
/// Atomic-write tempfile crate error.
#[error(transparent)]
Persist(#[from] tempfile::PersistError),
@@ -77,6 +87,16 @@ pub enum WikiError {
GitOwner(String),
}
+pub(crate) fn into_io_error(error: WikiError) -> std::io::Error {
+ match error {
+ WikiError::Io(error) => error,
+ error @ WikiError::Confinement { .. } => {
+ std::io::Error::new(std::io::ErrorKind::PermissionDenied, error.to_string())
+ }
+ error => std::io::Error::other(error.to_string()),
+ }
+}
+
impl From<serde_yaml::Error> for WikiError {
fn from(value: serde_yaml::Error) -> Self {
Self::Yaml(value.to_string())
diff --git a/crates/ai-memory-wiki/src/git.rs b/crates/ai-memory-wiki/src/git.rs
index 93151ab2..227c5c1f 100644
--- a/crates/ai-memory-wiki/src/git.rs
+++ b/crates/ai-memory-wiki/src/git.rs
@@ -116,6 +116,160 @@ pub struct Checkpoint {
enum CommitGit2Error {
Open(git2::Error),
Other(git2::Error),
+ Wiki(WikiError),
+}
+
+enum OpenRepositoryError {
+ Git(git2::Error),
+ Wiki(WikiError),
+}
+
+fn open_validated_repository(root: &Path) -> Result<Repository, OpenRepositoryError> {
+ let expected_git_dir =
+ crate::confinement::inspect_git_directory(root).map_err(OpenRepositoryError::Wiki)?;
+ let repo = Repository::open(root).map_err(OpenRepositoryError::Git)?;
+ let workdir = repo.workdir().ok_or_else(|| {
+ OpenRepositoryError::Wiki(WikiError::Confinement {
+ path: root.to_path_buf(),
+ reason: "wiki repository must have a working tree",
+ })
+ })?;
+ let canonical_root = root
+ .canonicalize()
+ .map_err(WikiError::from)
+ .map_err(OpenRepositoryError::Wiki)?;
+ let canonical_workdir = workdir
+ .canonicalize()
+ .map_err(WikiError::from)
+ .map_err(OpenRepositoryError::Wiki)?;
+ let canonical_git_dir = repo
+ .path()
+ .canonicalize()
+ .map_err(WikiError::from)
+ .map_err(OpenRepositoryError::Wiki)?;
+ let canonical_common_dir = repo
+ .commondir()
+ .canonicalize()
+ .map_err(WikiError::from)
+ .map_err(OpenRepositoryError::Wiki)?;
+ let canonical_expected_git_dir = expected_git_dir
+ .canonicalize()
+ .map_err(WikiError::from)
+ .map_err(OpenRepositoryError::Wiki)?;
+ if canonical_workdir != canonical_root {
+ return Err(OpenRepositoryError::Wiki(WikiError::Confinement {
+ path: workdir.to_path_buf(),
+ reason: "wiki repository working directory escapes the wiki root",
+ }));
+ }
+ if canonical_git_dir != canonical_expected_git_dir
+ || canonical_common_dir != canonical_expected_git_dir
+ {
+ return Err(OpenRepositoryError::Wiki(WikiError::Confinement {
+ path: repo.path().to_path_buf(),
+ reason: "wiki repository metadata escapes the in-root .git directory",
+ }));
+ }
+ Ok(repo)
+}
+
+fn map_open_error(error: OpenRepositoryError) -> WikiError {
+ match error {
+ OpenRepositoryError::Git(error) => map_git_err(error),
+ OpenRepositoryError::Wiki(error) => error,
+ }
+}
+
+fn validate_repository_or_allow_cli_fallback(root: &Path) -> WikiResult<()> {
+ match open_validated_repository(root) {
+ Ok(_) => Ok(()),
+ Err(OpenRepositoryError::Git(error))
+ if cfg!(windows) && should_try_commit_cli_fallback(&error) =>
+ {
+ validate_cli_fallback_root(root)
+ }
+ Err(error) => Err(map_open_error(error)),
+ }
+}
+
+fn validate_cli_fallback_root(root: &Path) -> WikiResult<()> {
+ let git_dir = crate::confinement::inspect_git_directory(root)?;
+ crate::confinement::inspect_tree_except(root, &[git_dir.as_path()])?;
+ let worktree = git_resolved_path(root, "--show-toplevel")?;
+ let resolved_git_dir = git_resolved_path(root, "--absolute-git-dir")?;
+ let common_dir = git_resolved_path(root, "--git-common-dir")?;
+ validate_resolved_repository_paths(root, &git_dir, &worktree, &resolved_git_dir, &common_dir)
+}
+
+fn git_resolved_path(root: &Path, argument: &str) -> WikiResult<PathBuf> {
+ let output = git_command(root)
+ .args(["rev-parse", "--path-format=absolute", argument])
+ .output()?;
+ if !output.status.success() {
+ return Err(WikiError::Io(std::io::Error::other(format!(
+ "git repository validation exited with status {}: {}",
+ output.status,
+ String::from_utf8_lossy(&output.stderr)
+ ))));
+ }
+ let raw = String::from_utf8_lossy(&output.stdout);
+ let path = PathBuf::from(raw.trim());
+ if path.as_os_str().is_empty() {
+ return Err(WikiError::Confinement {
+ path: root.to_path_buf(),
+ reason: "git CLI returned an empty repository path",
+ });
+ }
+ if !path.is_absolute() {
+ return Err(WikiError::Confinement {
+ path,
+ reason: "git CLI returned a non-absolute repository path",
+ });
+ }
+ Ok(path)
+}
+
+fn validate_resolved_repository_paths(
+ root: &Path,
+ expected_git_dir: &Path,
+ worktree: &Path,
+ git_dir: &Path,
+ common_dir: &Path,
+) -> WikiResult<()> {
+ let canonical_root = root.canonicalize()?;
+ let canonical_expected_git_dir = expected_git_dir.canonicalize()?;
+ let canonical_worktree = worktree.canonicalize()?;
+ let canonical_git_dir = git_dir.canonicalize()?;
+ let canonical_common_dir = common_dir.canonicalize()?;
+ if canonical_worktree != canonical_root {
+ return Err(WikiError::Confinement {
+ path: worktree.to_path_buf(),
+ reason: "git CLI resolved a working directory outside the wiki root",
+ });
+ }
+ if canonical_git_dir != canonical_expected_git_dir
+ || canonical_common_dir != canonical_expected_git_dir
+ {
+ return Err(WikiError::Confinement {
+ path: git_dir.to_path_buf(),
+ reason: "git CLI resolved metadata outside the in-root .git directory",
+ });
+ }
+ Ok(())
+}
+
+fn git_command(root: &Path) -> std::process::Command {
+ let mut command = std::process::Command::new("git");
+ command
+ .env_remove("GIT_DIR")
+ .env_remove("GIT_WORK_TREE")
+ .env_remove("GIT_COMMON_DIR")
+ .env_remove("GIT_INDEX_FILE")
+ .env_remove("GIT_OBJECT_DIRECTORY")
+ .env_remove("GIT_ALTERNATE_OBJECT_DIRECTORIES")
+ .arg("-C")
+ .arg(root);
+ command
}
impl GitAdapter {
@@ -125,13 +279,19 @@ impl GitAdapter {
/// # Errors
/// Propagates any underlying libgit2 error.
pub fn open_or_init(root: &Path) -> WikiResult<Self> {
- std::fs::create_dir_all(root)?;
- match Repository::open(root) {
- Ok(_) => debug!(root = %root.display(), "wiki repo already initialised"),
- Err(_) => {
+ crate::confinement::initialize_root(root)?;
+ let git_dir = root.join(".git");
+ match std::fs::symlink_metadata(&git_dir) {
+ Ok(_) => {
+ validate_repository_or_allow_cli_fallback(root)?;
+ debug!(root = %root.display(), "wiki repo already initialised");
+ }
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
debug!(root = %root.display(), "initialising wiki repo");
init_repo(root)?;
+ validate_repository_or_allow_cli_fallback(root)?;
}
+ Err(error) => return Err(error.into()),
}
Ok(Self {
root: root.to_path_buf(),
@@ -221,21 +381,43 @@ impl GitAdapter {
/// # Errors
/// Propagates any underlying libgit2 error.
pub fn commit_all(&self, message: &str) -> WikiResult<Option<git2::Oid>> {
+ self.commit_all_with_fallback(message, commit_all_fallback)
+ }
+
+ fn commit_all_with_fallback<F>(
+ &self,
+ message: &str,
+ fallback: F,
+ ) -> WikiResult<Option<git2::Oid>>
+ where
+ F: FnOnce(&Path, &str, git2::Error) -> WikiResult<Option<git2::Oid>>,
+ {
+ let git_dir = crate::confinement::inspect_git_directory(&self.root)?;
+ crate::confinement::inspect_tree_except(&self.root, &[git_dir.as_path()])?;
match self.commit_all_git2(message) {
Ok(result) => Ok(result),
- Err(CommitGit2Error::Open(e)) if should_try_commit_cli_fallback(&e) => {
- commit_all_fallback(&self.root, message, e)
- }
- Err(CommitGit2Error::Open(e) | CommitGit2Error::Other(e)) => Err(map_git_err(e)),
+ Err(CommitGit2Error::Open(error)) => commit_open_error_with_fallback_on(
+ cfg!(windows),
+ &self.root,
+ message,
+ error,
+ fallback,
+ ),
+ Err(CommitGit2Error::Other(error)) => Err(map_git_err(error)),
+ Err(CommitGit2Error::Wiki(error)) => Err(error),
}
}
fn commit_all_git2(&self, message: &str) -> Result<Option<git2::Oid>, CommitGit2Error> {
let mut slot = self.commit_lock.lock().unwrap_or_else(|e| e.into_inner());
if slot.is_none() {
- let repo = Repository::open(&self.root).map_err(CommitGit2Error::Open)?;
+ let repo = open_validated_repository(&self.root).map_err(|error| match error {
+ OpenRepositoryError::Git(error) => CommitGit2Error::Open(error),
+ OpenRepositoryError::Wiki(error) => CommitGit2Error::Wiki(error),
+ })?;
*slot = Some(Open { repo, head: None });
}
+ crate::confinement::inspect_git_directory(&self.root).map_err(CommitGit2Error::Wiki)?;
let open = slot.as_mut().expect("opened above");
let head_now = open.repo.head().ok().and_then(|h| h.target());
if open.head.is_some() && open.head != head_now {
@@ -413,20 +595,32 @@ impl GitAdapter {
Ok(Some(oid))
}
- /// Count commits reachable from HEAD. Returns 0 for an empty repo.
+ /// Count commits reachable from HEAD. Returns 0 for an empty or unreadable repo.
/// Useful for the test suite + for `ai-memory status`.
#[must_use]
pub fn commit_count(&self) -> usize {
- let Ok(repo) = Repository::open(&self.root) else {
- return commit_count_fallback(&self.root);
+ self.commit_count_checked().unwrap_or(0)
+ }
+
+ pub(crate) fn commit_count_checked(&self) -> WikiResult<usize> {
+ let repo = match open_validated_repository(&self.root) {
+ Ok(repo) => repo,
+ Err(OpenRepositoryError::Git(error)) => {
+ #[cfg(windows)]
+ if should_try_commit_cli_fallback(&error) {
+ return commit_count_fallback_checked(&self.root);
+ }
+ return Err(map_git_err(error));
+ }
+ Err(OpenRepositoryError::Wiki(error)) => return Err(error),
};
let Ok(mut walk) = repo.revwalk() else {
- return 0;
+ return Ok(0);
};
if walk.push_head().is_err() {
- return 0;
+ return Ok(0);
}
- walk.count()
+ Ok(walk.count())
}
/// Return the most recent commits reachable from HEAD.
@@ -436,13 +630,20 @@ impl GitAdapter {
/// # Errors
/// Propagates any underlying libgit2 error.
pub fn recent_checkpoints(&self, limit: usize) -> WikiResult<Vec<Checkpoint>> {
+ let repo = match open_validated_repository(&self.root) {
+ Ok(repo) => repo,
+ Err(OpenRepositoryError::Git(error)) => {
+ #[cfg(windows)]
+ if should_try_commit_cli_fallback(&error) {
+ return recent_checkpoints_fallback(&self.root, limit, error);
+ }
+ return Err(map_git_err(error));
+ }
+ Err(OpenRepositoryError::Wiki(error)) => return Err(error),
+ };
if limit == 0 {
return Ok(Vec::new());
}
- let repo = match Repository::open(&self.root) {
- Ok(repo) => repo,
- Err(e) => return recent_checkpoints_fallback(&self.root, limit, map_git_err(e)),
- };
let mut walk = repo.revwalk().map_err(map_git_err)?;
if walk.push_head().is_err() {
return Ok(Vec::new());
@@ -473,9 +674,16 @@ impl GitAdapter {
/// # Errors
/// Returns [`WikiError`] when the revision, path, or blob cannot be read.
pub fn file_at_rev(&self, rev: &str, path: &Path) -> WikiResult<Vec<u8>> {
- let repo = match Repository::open(&self.root) {
+ let repo = match open_validated_repository(&self.root) {
Ok(repo) => repo,
- Err(e) => return file_at_rev_fallback(&self.root, rev, path, map_git_err(e)),
+ Err(OpenRepositoryError::Git(error)) => {
+ #[cfg(windows)]
+ if should_try_commit_cli_fallback(&error) {
+ return file_at_rev_fallback(&self.root, rev, path, map_git_err(error));
+ }
+ return Err(map_git_err(error));
+ }
+ Err(OpenRepositoryError::Wiki(error)) => return Err(error),
};
let object = repo.revparse_single(rev).map_err(map_git_err)?;
let commit = object.peel_to_commit().map_err(map_git_err)?;
@@ -502,6 +710,16 @@ impl GitAdapter {
/// read it" would drop the commit).
#[allow(clippy::disallowed_methods)]
impl GitAdapter {
+ fn confined(&self, path: &Path, prepare: crate::confinement::Prepare) -> WikiResult<PathBuf> {
+ let relative = path
+ .strip_prefix(&self.root)
+ .map_err(|_| WikiError::Confinement {
+ path: path.to_path_buf(),
+ reason: "path is outside the wiki root",
+ })?;
+ crate::confinement::tree_path(&self.root, relative, prepare)
+ }
+
fn writing(&self) -> MutexGuard<'_, Option<Open>> {
self.commit_lock.lock().unwrap_or_else(|e| e.into_inner())
}
@@ -512,8 +730,9 @@ impl GitAdapter {
/// Propagates the filesystem error.
pub fn write_atomic(&self, path: &Path, bytes: &[u8]) -> WikiResult<()> {
let _writing = self.writing();
- crate::atomic::write_atomic(path, bytes)?;
- self.mark_written(path);
+ let path = self.confined(path, crate::confinement::Prepare::Parents)?;
+ crate::atomic::write_atomic(&path, bytes)?;
+ self.mark_written(&path);
Ok(())
}
@@ -522,10 +741,11 @@ impl GitAdapter {
&self,
tmp: tempfile::NamedTempFile,
path: &Path,
- ) -> Result<std::fs::File, tempfile::PersistError> {
+ ) -> WikiResult<std::fs::File> {
let _writing = self.writing();
- let file = crate::atomic::persist_with_retry(tmp, path)?;
- self.mark_written(path);
+ let path = self.confined(path, crate::confinement::Prepare::Parents)?;
+ let file = crate::atomic::persist_with_retry(tmp, &path)?;
+ self.mark_written(&path);
Ok(file)
}
@@ -534,20 +754,21 @@ impl GitAdapter {
/// # Errors
/// Propagates the filesystem error.
pub fn append(&self, path: &Path, bytes: &[u8]) -> std::io::Result<()> {
+ self.append_checked(path, bytes)
+ .map_err(crate::error::into_io_error)
+ }
+
+ pub(crate) fn append_checked(&self, path: &Path, bytes: &[u8]) -> WikiResult<()> {
let _writing = self.writing();
use std::io::Write as _;
- if let Some(parent) = path.parent()
- && !parent.as_os_str().is_empty()
- {
- std::fs::create_dir_all(parent)?;
- }
+ let path = self.confined(path, crate::confinement::Prepare::Parents)?;
let mut file = std::fs::OpenOptions::new()
.create(true)
.append(true)
- .open(path)?;
+ .open(&path)?;
file.write_all(bytes)?;
file.sync_data()?;
- self.mark_written(path);
+ self.mark_written(&path);
Ok(())
}
@@ -556,10 +777,17 @@ impl GitAdapter {
/// # Errors
/// Propagates the filesystem error.
pub fn rename(&self, from: &Path, to: &Path) -> std::io::Result<()> {
+ self.rename_checked(from, to)
+ .map_err(crate::error::into_io_error)
+ }
+
+ pub(crate) fn rename_checked(&self, from: &Path, to: &Path) -> WikiResult<()> {
let _writing = self.writing();
- std::fs::rename(from, to)?;
- self.mark_written(from);
- self.mark_written(to);
+ let from = self.confined(from, crate::confinement::Prepare::Inspect)?;
+ let to = self.confined(to, crate::confinement::Prepare::Parents)?;
+ std::fs::rename(&from, &to)?;
+ self.mark_written(&from);
+ self.mark_written(&to);
Ok(())
}
@@ -568,9 +796,15 @@ impl GitAdapter {
/// # Errors
/// Propagates the filesystem error.
pub fn remove_file(&self, path: &Path) -> std::io::Result<()> {
+ self.remove_file_checked(path)
+ .map_err(crate::error::into_io_error)
+ }
+
+ pub(crate) fn remove_file_checked(&self, path: &Path) -> WikiResult<()> {
let _writing = self.writing();
- std::fs::remove_file(path)?;
- self.mark_written(path);
+ let path = self.confined(path, crate::confinement::Prepare::Inspect)?;
+ std::fs::remove_file(&path)?;
+ self.mark_written(&path);
Ok(())
}
@@ -579,9 +813,15 @@ impl GitAdapter {
/// # Errors
/// Propagates the filesystem error.
pub fn remove_dir_all(&self, path: &Path) -> std::io::Result<()> {
+ self.remove_dir_all_checked(path)
+ .map_err(crate::error::into_io_error)
+ }
+
+ pub(crate) fn remove_dir_all_checked(&self, path: &Path) -> WikiResult<()> {
let _writing = self.writing();
- std::fs::remove_dir_all(path)?;
- self.mark_written(path);
+ let path = self.confined(path, crate::confinement::Prepare::Inspect)?;
+ std::fs::remove_dir_all(&path)?;
+ self.mark_written(&path);
Ok(())
}
}
@@ -642,22 +882,51 @@ fn stage_paths(
Ok(paths.len())
}
+fn commit_open_error_with_fallback_on<F>(
+ windows: bool,
+ root: &Path,
+ message: &str,
+ error: git2::Error,
+ fallback: F,
+) -> WikiResult<Option<git2::Oid>>
+where
+ F: FnOnce(&Path, &str, git2::Error) -> WikiResult<Option<git2::Oid>>,
+{
+ if should_try_commit_cli_fallback_on(windows, &error) {
+ validate_cli_fallback_root(root)?;
+ fallback(root, message, error)
+ } else {
+ Err(map_git_err(error))
+ }
+}
+
+fn should_try_commit_cli_fallback(error: &git2::Error) -> bool {
+ should_try_commit_cli_fallback_on(cfg!(windows), error)
+}
+
+fn should_try_commit_cli_fallback_on(windows: bool, error: &git2::Error) -> bool {
+ !matches!(error.code(), ErrorCode::Owner)
+ && (matches!(error.code(), ErrorCode::NotFound)
+ || windows
+ && matches!(error.class(), git2::ErrorClass::Os)
+ && error.message().contains("failed to resolve path"))
+}
+
#[cfg(windows)]
fn commit_all_fallback(
root: &Path,
message: &str,
original: git2::Error,
) -> WikiResult<Option<git2::Oid>> {
+ validate_cli_fallback_root(root)?;
warn!(error = %original, root = %root.display(), "libgit2 commit failed; trying git CLI fallback");
run_git(root, ["add", "-A"])?;
- let diff = std::process::Command::new("git")
- .arg("-C")
- .arg(root)
+ let diff = git_command(root)
.args(["diff", "--cached", "--quiet", "--exit-code"])
.status()
- .map_err(|e| {
+ .map_err(|error| {
WikiError::Io(std::io::Error::other(format!(
- "{original}; git diff fallback failed to start: {e}"
+ "{original}; git diff fallback failed to start: {error}"
)))
})?;
if diff.success() {
@@ -692,58 +961,27 @@ fn commit_all_fallback(
Err(map_git_err(original))
}
-fn should_try_commit_cli_fallback(error: &git2::Error) -> bool {
- if matches!(error.code(), ErrorCode::NotFound) {
- return true;
- }
-
- // An owner-check failure must NOT fall back to the git CLI: the CLI runs
- // the same CVE-2022-24765 ownership guard and would refuse identically, so
- // a fallback would only mask the real cause. Let it map through to
- // `WikiError::GitOwner` and surface at ERROR instead.
- if matches!(error.code(), ErrorCode::Owner) {
- return false;
- }
-
- #[cfg(windows)]
- {
- // On native Windows, libgit2 can fail to reopen a freshly initialised
- // wiki repo under dot-prefixed temp dirs with an OS path-resolution
- // error. The fallback still runs only for Repository::open failures;
- // real permission or repo corruption errors must also pass through the
- // Git CLI before they are treated as recoverable.
- if matches!(error.class(), git2::ErrorClass::Os)
- && error.message().contains("failed to resolve path")
- {
- return true;
- }
- }
-
- false
-}
-
#[cfg(windows)]
-fn commit_count_fallback(root: &Path) -> usize {
- let Ok(out) = git_output(root, ["rev-list", "--count", "HEAD"]) else {
- return 0;
- };
+fn commit_count_fallback_checked(root: &Path) -> WikiResult<usize> {
+ validate_cli_fallback_root(root)?;
+ let out = git_output(root, ["rev-list", "--count", "HEAD"])?;
String::from_utf8_lossy(&out.stdout)
.trim()
.parse()
- .unwrap_or(0)
-}
-
-#[cfg(not(windows))]
-fn commit_count_fallback(_root: &Path) -> usize {
- 0
+ .map_err(|error| {
+ WikiError::Io(std::io::Error::other(format!(
+ "git fallback returned an invalid commit count: {error}"
+ )))
+ })
}
#[cfg(windows)]
fn recent_checkpoints_fallback(
root: &Path,
limit: usize,
- original: WikiError,
+ original: git2::Error,
) -> WikiResult<Vec<Checkpoint>> {
+ validate_cli_fallback_root(root)?;
warn!(error = %original, root = %root.display(), "libgit2 log failed; trying git CLI fallback");
let limit = limit.to_string();
let out = git_output(root, ["log", "-n", &limit, "--format=%H%x1f%s%x1f%ct"])?;
@@ -768,15 +1006,6 @@ fn recent_checkpoints_fallback(
Ok(checkpoints)
}
-#[cfg(not(windows))]
-fn recent_checkpoints_fallback(
- _root: &Path,
- _limit: usize,
- original: WikiError,
-) -> WikiResult<Vec<Checkpoint>> {
- Err(original)
-}
-
#[cfg(windows)]
fn file_at_rev_fallback(
root: &Path,
@@ -784,6 +1013,7 @@ fn file_at_rev_fallback(
path: &Path,
original: WikiError,
) -> WikiResult<Vec<u8>> {
+ validate_cli_fallback_root(root)?;
warn!(error = %original, root = %root.display(), "libgit2 show failed; trying git CLI fallback");
let rel = slash_path(path);
let spec = format!("{rev}:{rel}");
@@ -791,41 +1021,44 @@ fn file_at_rev_fallback(
Ok(out.stdout)
}
-#[cfg(not(windows))]
-fn file_at_rev_fallback(
- _root: &Path,
- _rev: &str,
- _path: &Path,
- original: WikiError,
-) -> WikiResult<Vec<u8>> {
- Err(original)
-}
-
fn init_repo(root: &Path) -> WikiResult<()> {
match Repository::init(root) {
Ok(_) => Ok(()),
- Err(e) => init_repo_fallback(root, e),
+ Err(error) => init_error_with_fallback_on(cfg!(windows), root, error, init_repo_fallback),
+ }
+}
+
+fn init_error_with_fallback_on<F>(
+ windows: bool,
+ root: &Path,
+ error: git2::Error,
+ fallback: F,
+) -> WikiResult<()>
+where
+ F: FnOnce(&Path, git2::Error) -> WikiResult<()>,
+{
+ if !windows {
+ return Err(map_git_err(error));
+ }
+ validate_init_fallback_root(root)?;
+ fallback(root, error)
+}
+
+fn validate_init_fallback_root(root: &Path) -> WikiResult<()> {
+ crate::confinement::initialize_root(root)?;
+ match std::fs::symlink_metadata(root.join(".git")) {
+ Ok(_) => validate_cli_fallback_root(root),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(error) => Err(error.into()),
}
}
#[cfg(windows)]
fn init_repo_fallback(root: &Path, original: git2::Error) -> WikiResult<()> {
+ validate_init_fallback_root(root)?;
warn!(error = %original, root = %root.display(), "libgit2 init failed; trying git CLI fallback");
- let status = std::process::Command::new("git")
- .arg("init")
- .arg("-q")
- .arg(root)
- .status()
- .map_err(|io| {
- WikiError::Io(std::io::Error::other(format!(
- "{original}; git init fallback failed to start: {io}"
- )))
- })?;
- if status.success() {
- Ok(())
- } else {
- Err(map_git_err(original))
- }
+ run_git(root, ["init", "-q"])?;
+ validate_cli_fallback_root(root)
}
#[cfg(not(windows))]
@@ -835,12 +1068,10 @@ fn init_repo_fallback(_root: &Path, original: git2::Error) -> WikiResult<()> {
#[cfg(windows)]
fn run_git<const N: usize>(root: &Path, args: [&str; N]) -> WikiResult<()> {
- let status = std::process::Command::new("git")
- .arg("-C")
- .arg(root)
+ let status = git_command(root)
.args(args)
.status()
- .map_err(|e| WikiError::Io(std::io::Error::other(e.to_string())))?;
+ .map_err(|error| WikiError::Io(std::io::Error::other(error.to_string())))?;
if status.success() {
Ok(())
} else {
@@ -852,19 +1083,17 @@ fn run_git<const N: usize>(root: &Path, args: [&str; N]) -> WikiResult<()> {
#[cfg(windows)]
fn git_output<const N: usize>(root: &Path, args: [&str; N]) -> WikiResult<std::process::Output> {
- let out = std::process::Command::new("git")
- .arg("-C")
- .arg(root)
+ let output = git_command(root)
.args(args)
.output()
- .map_err(|e| WikiError::Io(std::io::Error::other(e.to_string())))?;
- if out.status.success() {
- Ok(out)
+ .map_err(|error| WikiError::Io(std::io::Error::other(error.to_string())))?;
+ if output.status.success() {
+ Ok(output)
} else {
Err(WikiError::Io(std::io::Error::other(format!(
"git fallback exited with status {}: {}",
- out.status,
- String::from_utf8_lossy(&out.stderr)
+ output.status,
+ String::from_utf8_lossy(&output.stderr)
))))
}
}
@@ -895,14 +1124,429 @@ mod tests {
.unwrap()
}
+ #[test]
+ fn commit_count_public_api_remains_a_plain_usize() {
+ let tmp = tempdir();
+ let root = tmp.path().join("wiki");
+ let adapter = GitAdapter::open_or_init(&root).unwrap();
+ let count: usize = adapter.commit_count();
+ assert_eq!(count, 0);
+ }
+
+ #[test]
+ fn windows_commit_fallback_accepts_established_eligible_errors() {
+ let eligible = git2::Error::new(
+ ErrorCode::GenericError,
+ git2::ErrorClass::Os,
+ "failed to resolve path 'C:\\wiki\\.git'",
+ );
+ assert!(should_try_commit_cli_fallback_on(true, &eligible));
+ assert!(!should_try_commit_cli_fallback_on(false, &eligible));
+
+ let wrong_class = git2::Error::new(
+ ErrorCode::GenericError,
+ git2::ErrorClass::Repository,
+ "failed to resolve path 'C:\\wiki\\.git'",
+ );
+ assert!(!should_try_commit_cli_fallback_on(true, &wrong_class));
+ let not_found = git2::Error::new(
+ ErrorCode::NotFound,
+ git2::ErrorClass::Repository,
+ "not found",
+ );
+ assert!(should_try_commit_cli_fallback_on(true, &not_found));
+ assert!(should_try_commit_cli_fallback_on(false, &not_found));
+
+ let owner = git2::Error::new(
+ ErrorCode::Owner,
+ git2::ErrorClass::Os,
+ "failed to resolve path 'C:\\wiki\\.git'",
+ );
+ assert!(!should_try_commit_cli_fallback_on(true, &owner));
+ let wrong_message = git2::Error::new(
+ ErrorCode::GenericError,
+ git2::ErrorClass::Os,
+ "repository is corrupt",
+ );
+ assert!(!should_try_commit_cli_fallback_on(true, &wrong_message));
+ }
+
+ #[test]
+ fn public_filesystem_wrappers_preserve_io_signatures_and_non_not_found_confinement() {
+ fn assert_signatures(
+ append: fn(&GitAdapter, &Path, &[u8]) -> std::io::Result<()>,
+ rename: fn(&GitAdapter, &Path, &Path) -> std::io::Result<()>,
+ remove_file: fn(&GitAdapter, &Path) -> std::io::Result<()>,
+ remove_dir_all: fn(&GitAdapter, &Path) -> std::io::Result<()>,
+ ) {
+ let _ = (append, rename, remove_file, remove_dir_all);
+ }
+ assert_signatures(
+ GitAdapter::append,
+ GitAdapter::rename,
+ GitAdapter::remove_file,
+ GitAdapter::remove_dir_all,
+ );
+
+ let tmp = tempdir();
+ let root = tmp.path().join("wiki");
+ let adapter = GitAdapter::open_or_init(&root).unwrap();
+ let outside = tmp.path().join("outside");
+ std::fs::create_dir(&outside).unwrap();
+ let linked = root.join("linked");
+ if !link_directory(&outside, &linked) {
+ return;
+ }
+ let error = adapter.append(&linked.join("log.md"), b"x").unwrap_err();
+ assert_eq!(error.kind(), std::io::ErrorKind::PermissionDenied);
+ }
+
+ #[test]
+ fn windows_init_error_dispatches_fallback_after_root_preflight() {
+ use std::sync::atomic::{AtomicBool, Ordering};
+
+ let tmp = tempdir();
+ let root = tmp.path().join("wiki");
+ std::fs::create_dir(&root).unwrap();
+ let called = AtomicBool::new(false);
+ let error = git2::Error::new(
+ ErrorCode::GenericError,
+ git2::ErrorClass::Os,
+ "failed to initialize repository",
+ );
+
+ init_error_with_fallback_on(true, &root, error, |validated, _| {
+ assert_eq!(validated, root);
+ called.store(true, Ordering::Relaxed);
+ Ok(())
+ })
+ .unwrap();
+ assert!(called.load(Ordering::Relaxed));
+ }
+
+ #[cfg(any(unix, windows))]
+ #[test]
+ fn invalid_root_never_reaches_init_fallback() {
+ use std::sync::atomic::{AtomicBool, Ordering};
+
+ let tmp = tempdir();
+ let outside = tmp.path().join("outside");
+ let root = tmp.path().join("wiki");
+ std::fs::create_dir(&outside).unwrap();
+ if !link_directory(&outside, &root) {
+ return;
+ }
+ let called = AtomicBool::new(false);
+ let error = git2::Error::new(
+ ErrorCode::GenericError,
+ git2::ErrorClass::Os,
+ "failed to initialize repository",
+ );
+
+ assert!(matches!(
+ init_error_with_fallback_on(true, &root, error, |_, _| {
+ called.store(true, Ordering::Relaxed);
+ Ok(())
+ }),
+ Err(WikiError::Confinement { .. })
+ ));
+ assert!(!called.load(Ordering::Relaxed));
+ }
+
#[test]
fn init_is_idempotent_and_creates_dotgit() {
let tmp = tempdir();
let root = tmp.path().join("wiki");
- let _adapter = GitAdapter::open_or_init(&root).unwrap();
+ let adapter = GitAdapter::open_or_init(&root).unwrap();
assert!(root.join(".git").is_dir());
- // Second open is a no-op.
- let _adapter2 = GitAdapter::open_or_init(&root).unwrap();
+ let adapter2 = GitAdapter::open_or_init(&root).unwrap();
+ assert_eq!(adapter.commit_count(), 0);
+ assert!(adapter2.recent_checkpoints(1).unwrap().is_empty());
+ }
+
+ #[cfg(unix)]
+ fn link_directory(target: &Path, link: &Path) -> bool {
+ std::os::unix::fs::symlink(target, link).unwrap();
+ true
+ }
+
+ #[cfg(windows)]
+ fn link_directory(target: &Path, link: &Path) -> bool {
+ match std::os::windows::fs::symlink_dir(target, link) {
+ Ok(()) => true,
+ Err(error) if error.raw_os_error() == Some(1314) => {
+ eprintln!("skipping .git reparse assertion: Windows privilege unavailable");
+ false
+ }
+ Err(error) => panic!("failed to create .git directory link: {error}"),
+ }
+ }
+
+ #[cfg(any(unix, windows))]
+ #[test]
+ fn git_metadata_link_is_refused_without_touching_external_repository() {
+ let tmp = tempdir();
+ let root = tmp.path().join("wiki");
+ std::fs::create_dir(&root).unwrap();
+ let external = tmp.path().join("external-git");
+ Repository::init_bare(&external).unwrap();
+ let before = std::fs::read(external.join("HEAD")).unwrap();
+ if !link_directory(&external, &root.join(".git")) {
+ return;
+ }
+
+ assert!(matches!(
+ GitAdapter::open_or_init(&root),
+ Err(WikiError::Confinement { .. })
+ ));
+ assert_eq!(std::fs::read(external.join("HEAD")).unwrap(), before);
+ }
+
+ #[cfg(any(unix, windows))]
+ #[test]
+ fn eligible_windows_open_error_dispatches_the_fallback_after_validation() {
+ use std::sync::atomic::{AtomicBool, Ordering};
+
+ let tmp = tempdir();
+ let root = tmp.path().join("wiki");
+ let adapter = GitAdapter::open_or_init(&root).unwrap();
+ let called = AtomicBool::new(false);
+ let error = git2::Error::new(
+ ErrorCode::GenericError,
+ git2::ErrorClass::Os,
+ "failed to resolve path 'C:\\wiki\\.git'",
+ );
+
+ assert!(
+ commit_open_error_with_fallback_on(
+ true,
+ &adapter.root,
+ "fallback",
+ error,
+ |root, message, _| {
+ assert_eq!(root, adapter.root);
+ assert_eq!(message, "fallback");
+ called.store(true, Ordering::Relaxed);
+ Ok(None)
+ },
+ )
+ .unwrap()
+ .is_none()
+ );
+ assert!(called.load(Ordering::Relaxed));
+ }
+
+ fn assert_eligible_fallback_is_refused(root: &Path) {
+ use std::sync::atomic::{AtomicBool, Ordering};
+
+ let called = AtomicBool::new(false);
+ let error = git2::Error::new(
+ ErrorCode::GenericError,
+ git2::ErrorClass::Os,
+ "failed to resolve path 'C:\\wiki\\.git'",
+ );
+ assert!(
+ commit_open_error_with_fallback_on(true, root, "refused", error, |_, _, _| {
+ called.store(true, Ordering::Relaxed);
+ Ok(None)
+ },)
+ .is_err()
+ );
+ assert!(!called.load(Ordering::Relaxed));
+ }
+
+ #[cfg(any(unix, windows))]
+ #[test]
+ fn linked_git_metadata_never_reaches_commit_fallback() {
+ let tmp = tempdir();
+ let root = tmp.path().join("wiki");
+ let adapter = GitAdapter::open_or_init(&root).unwrap();
+ adapter.close();
+ let original = root.join(".git-original");
+ std::fs::rename(root.join(".git"), &original).unwrap();
+ if !link_directory(&original, &root.join(".git")) {
+ return;
+ }
+
+ assert_eligible_fallback_is_refused(&adapter.root);
+ }
+
+ #[test]
+ fn gitfile_metadata_never_reaches_commit_fallback() {
+ let tmp = tempdir();
+ let root = tmp.path().join("wiki");
+ let adapter = GitAdapter::open_or_init(&root).unwrap();
+ adapter.close();
+ let original = root.join(".git-original");
+ std::fs::rename(root.join(".git"), &original).unwrap();
+ std::fs::write(
+ root.join(".git"),
+ format!("gitdir: {}\n", original.display()),
+ )
+ .unwrap();
+
+ assert_eligible_fallback_is_refused(&adapter.root);
+ }
+
+ #[test]
+ fn out_of_root_worktree_never_reaches_commit_fallback() {
+ let tmp = tempdir();
+ let root = tmp.path().join("wiki");
+ let adapter = GitAdapter::open_or_init(&root).unwrap();
+ let outside = tmp.path().join("outside");
+ std::fs::create_dir(&outside).unwrap();
+ Repository::open(&root)
+ .unwrap()
+ .config()
+ .unwrap()
+ .set_str("core.worktree", outside.to_str().unwrap())
+ .unwrap();
+
+ assert_eligible_fallback_is_refused(&adapter.root);
+ }
+
+ #[test]
+ fn fallback_preflight_refuses_invalid_git_metadata() {
+ let tmp = tempdir();
+ let root = tmp.path().join("wiki");
+ let adapter = GitAdapter::open_or_init(&root).unwrap();
+ std::fs::write(root.join(".git/commondir"), "../outside\n").unwrap();
+
+ assert!(matches!(
+ validate_cli_fallback_root(&adapter.root),
+ Err(WikiError::Confinement { .. })
+ ));
+ }
+
+ #[test]
+ fn fallback_resolved_paths_must_match_the_validated_repository() {
+ let tmp = tempdir();
+ let root = tmp.path().join("wiki");
+ let adapter = GitAdapter::open_or_init(&root).unwrap();
+ let git_dir = root.join(".git");
+ let outside = tmp.path().join("outside");
+ std::fs::create_dir(&outside).unwrap();
+
+ assert!(
+ validate_resolved_repository_paths(&root, &git_dir, &root, &git_dir, &git_dir,).is_ok()
+ );
+ for (worktree, resolved_git_dir, common_dir) in [
+ (outside.as_path(), git_dir.as_path(), git_dir.as_path()),
+ (root.as_path(), outside.as_path(), git_dir.as_path()),
+ (root.as_path(), git_dir.as_path(), outside.as_path()),
+ ] {
+ assert!(matches!(
+ validate_resolved_repository_paths(
+ &root,
+ &git_dir,
+ worktree,
+ resolved_git_dir,
+ common_dir,
+ ),
+ Err(WikiError::Confinement { .. })
+ ));
+ }
+ assert_eq!(adapter.root(), root);
+ }
+
+ #[test]
+ fn gitfile_redirect_outside_is_refused_without_touching_target() {
+ let tmp = tempdir();
+ let root = tmp.path().join("wiki");
+ std::fs::create_dir(&root).unwrap();
+ let external = tmp.path().join("external-git");
+ Repository::init_bare(&external).unwrap();
+ let before = std::fs::read(external.join("HEAD")).unwrap();
+ std::fs::write(
+ root.join(".git"),
+ format!("gitdir: {}\n", external.display()),
+ )
+ .unwrap();
+
+ assert!(matches!(
+ GitAdapter::open_or_init(&root),
+ Err(WikiError::Confinement { .. })
+ ));
+ assert_eq!(std::fs::read(external.join("HEAD")).unwrap(), before);
+ }
+
+ #[test]
+ fn git_metadata_redirect_files_are_refused_before_repository_open() {
+ for relative in [
+ "commondir",
+ "objects/info/alternates",
+ "objects/info/http-alternates",
+ ] {
+ let tmp = tempdir();
+ let root = tmp.path().join("wiki");
+ let adapter = GitAdapter::open_or_init(&root).unwrap();
+ let redirect = root.join(".git").join(relative);
+ std::fs::create_dir_all(redirect.parent().unwrap()).unwrap();
+ std::fs::write(&redirect, "../outside\n").unwrap();
+
+ assert!(matches!(
+ adapter.recent_checkpoints(0),
+ Err(WikiError::Confinement { .. })
+ ));
+ }
+ }
+
+ #[test]
+ fn configured_worktree_outside_the_wiki_root_is_refused() {
+ let tmp = tempdir();
+ let root = tmp.path().join("wiki");
+ let external = tmp.path().join("external-worktree");
+ std::fs::create_dir(&external).unwrap();
+ std::fs::write(external.join("canary"), "outside canary").unwrap();
+ let repo = Repository::init(&root).unwrap();
+ repo.config()
+ .unwrap()
+ .set_str("core.worktree", external.to_str().unwrap())
+ .unwrap();
+ drop(repo);
+
+ assert!(matches!(
+ GitAdapter::open_or_init(&root),
+ Err(WikiError::Confinement { .. })
+ ));
+ assert_eq!(
+ std::fs::read_to_string(external.join("canary")).unwrap(),
+ "outside canary"
+ );
+ }
+
+ #[cfg(any(unix, windows))]
+ #[test]
+ fn checkpoint_and_revision_reads_refuse_a_replaced_git_directory() {
+ let (_tmp, root, adapter) = committed(&[("a.md", "one")]);
+ adapter.close();
+ let original = root.join(".git-original");
+ std::fs::rename(root.join(".git"), &original).unwrap();
+ let external = root.parent().unwrap().join("external-git");
+ Repository::init_bare(&external).unwrap();
+ let before = std::fs::read(external.join("HEAD")).unwrap();
+ if !link_directory(&external, &root.join(".git")) {
+ return;
+ }
+
+ assert!(matches!(
+ adapter.commit_all("refused"),
+ Err(WikiError::Confinement { .. })
+ ));
+ assert!(matches!(
+ adapter.recent_checkpoints(1),
+ Err(WikiError::Confinement { .. })
+ ));
+ assert!(matches!(
+ adapter.file_at_rev("HEAD", Path::new("a.md")),
+ Err(WikiError::Confinement { .. })
+ ));
+ assert!(matches!(
+ adapter.commit_count_checked(),
+ Err(WikiError::Confinement { .. })
+ ));
+ assert_eq!(adapter.commit_count(), 0);
+ assert_eq!(std::fs::read(external.join("HEAD")).unwrap(), before);
}
#[test]
@@ -1275,35 +1919,14 @@ mod tests {
assert!(!is_racy_read(&other_message));
}
- /// A libgit2 owner-check failure is not silently "recovered": it must not
- /// trigger the git CLI fallback (the CLI enforces the same CVE-2022-24765
- /// guard and would refuse identically), and it must map to the distinct
- /// `GitOwner` variant so startup can surface it at ERROR. A generic error
- /// still maps to the opaque I/O variant — proving the classification bites.
#[test]
- fn owner_error_is_surfaced_not_recovered() {
+ fn owner_error_is_surfaced_distinctly() {
let owner = git2::Error::new(
ErrorCode::Owner,
git2::ErrorClass::Config,
"repository path is not owned by current user",
);
- assert!(
- !should_try_commit_cli_fallback(&owner),
- "an owner error must not fall back to the git CLI (same guard)"
- );
- assert!(
- matches!(map_git_err(owner), WikiError::GitOwner(_)),
- "an owner error must map to the distinct GitOwner variant"
- );
-
- // Control: a NotFound error still asks for the CLI fallback, and a
- // generic error is still the opaque I/O variant (not GitOwner).
- let not_found = git2::Error::new(
- ErrorCode::NotFound,
- git2::ErrorClass::Repository,
- "not found",
- );
- assert!(should_try_commit_cli_fallback(&not_found));
+ assert!(matches!(map_git_err(owner), WikiError::GitOwner(_)));
let generic = git2::Error::new(
ErrorCode::GenericError,
git2::ErrorClass::Os,
diff --git a/crates/ai-memory-wiki/src/lib.rs b/crates/ai-memory-wiki/src/lib.rs
index ef50f6d3..da4daa14 100644
--- a/crates/ai-memory-wiki/src/lib.rs
+++ b/crates/ai-memory-wiki/src/lib.rs
@@ -8,6 +8,7 @@
pub mod admission;
mod atomic;
pub mod backup;
+mod confinement;
mod error;
mod git;
mod ledger;
@@ -21,6 +22,7 @@ pub use admission::{
MAX_RESPONSE_BYTES, WebhookConfig,
};
pub use atomic::write_atomic;
+pub use confinement::validate_wiki_tree;
pub use error::{WikiError, WikiResult};
pub use git::{COMMIT_AUTHOR_EMAIL, COMMIT_AUTHOR_NAME, GitAdapter};
pub use ledger::is_rotated_event_ledger;
diff --git a/crates/ai-memory-wiki/src/migrations/m2026_09_okf_conformance.rs b/crates/ai-memory-wiki/src/migrations/m2026_09_okf_conformance.rs
index 27d1de09..54fa8be2 100644
--- a/crates/ai-memory-wiki/src/migrations/m2026_09_okf_conformance.rs
+++ b/crates/ai-memory-wiki/src/migrations/m2026_09_okf_conformance.rs
@@ -70,6 +70,8 @@ pub fn snapshot_before_db_migration(
data_dir: &Path,
dest_override: Option<&Path>,
) -> WikiResult<Option<crate::backup::BackupReceipt>> {
+ let wiki_root = data_dir.join("wiki");
+ crate::confinement::inspect_tree(&wiki_root)?;
if crate::backup::BackupReceipt::load(data_dir).is_some_and(|r| r.archive_present()) {
// A prior boot in this same upgrade already captured the pre-migration
// state; do not overwrite it with a now-partially-migrated snapshot.
@@ -102,6 +104,7 @@ impl WikiMigration for OkfConformance {
}
async fn up(&self, writer: &WriterHandle, wiki_root: &Path) -> WikiResult<()> {
+ crate::confinement::inspect_tree(wiki_root)?;
let data_dir = wiki_root.parent().ok_or_else(|| {
WikiError::Io(std::io::Error::other("wiki root has no parent data dir"))
})?;
@@ -152,6 +155,7 @@ impl WikiMigration for OkfConformance {
// 2. Checkpoint whatever the tree holds before touching it.
let git = crate::git::GitAdapter::open_or_init(wiki_root)?;
+ crate::confinement::inspect_git_directory(wiki_root)?;
git.commit_all("pre-okf-migration checkpoint")?;
// 3. DB pass — in place, through the single writer.
@@ -177,6 +181,7 @@ impl WikiMigration for OkfConformance {
ensure_bundle_indexes(&git)?;
// 5. One commit for the whole rewrite.
+ crate::confinement::inspect_git_directory(wiki_root)?;
git.commit_all("okf-migration: conform wiki to OKF v0.2")?;
tracing::info!(
rows = migrated.len(),
diff --git a/crates/ai-memory-wiki/src/watcher.rs b/crates/ai-memory-wiki/src/watcher.rs
index 3a0693de..efeecc8a 100644
--- a/crates/ai-memory-wiki/src/watcher.rs
+++ b/crates/ai-memory-wiki/src/watcher.rs
@@ -247,13 +247,16 @@ async fn handle_event(wiki: &Wiki, event: notify_debouncer_full::DebouncedEvent)
continue;
};
let ft = metadata.file_type();
- if ft.is_symlink() {
+ if crate::confinement::is_link_like(&metadata) {
continue;
}
if ft.is_dir() {
let Some((ws, proj, proj_root)) = extract_project_dir_ids(wiki.root(), raw_path) else {
continue;
};
+ if wiki.validate_project_root(ws, proj).is_err() {
+ continue;
+ }
reindex_project_dir(wiki, ws, proj, proj_root).await;
continue;
}
@@ -269,6 +272,9 @@ async fn handle_event(wiki: &Wiki, event: notify_debouncer_full::DebouncedEvent)
let Some((ws, proj, page_path)) = extract_project_ids(wiki.root(), raw_path) else {
continue;
};
+ if wiki.validate_page_path(ws, proj, &page_path).is_err() {
+ continue;
+ }
if is_pending_path(&page_path) {
continue;
}
@@ -311,6 +317,9 @@ async fn reindex_project_dir(
proj: ProjectId,
proj_root: std::path::PathBuf,
) -> bool {
+ if wiki.validate_project_root(ws, proj).is_err() {
+ return false;
+ }
// Same orphan guard `reconcile` applies (#613), for the other way a
// project directory reaches the indexer. A filesystem event on a rowless
// directory would otherwise walk it and warn once per page, which is the
@@ -740,6 +749,17 @@ async fn reconcile(
pub(crate) fn walk_project_dirs(
wiki_root: &Path,
) -> WikiResult<Vec<(WorkspaceId, ProjectId, std::path::PathBuf)>> {
+ let root_metadata = match std::fs::symlink_metadata(wiki_root) {
+ Ok(metadata) => metadata,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
+ Err(error) => return Err(error.into()),
+ };
+ if crate::confinement::is_link_like(&root_metadata) {
+ return Err(WikiError::Confinement {
+ path: wiki_root.to_path_buf(),
+ reason: "symbolic links and reparse points are not allowed in the wiki project tree",
+ });
+ }
let mut out = Vec::new();
let ws_read = match std::fs::read_dir(wiki_root) {
Ok(r) => r,
@@ -748,7 +768,8 @@ pub(crate) fn walk_project_dirs(
};
for ws_entry in ws_read {
let ws_entry = ws_entry?;
- if !ws_entry.file_type()?.is_dir() {
+ let ws_metadata = std::fs::symlink_metadata(ws_entry.path())?;
+ if crate::confinement::is_link_like(&ws_metadata) || !ws_metadata.is_dir() {
continue;
}
let ws_name = ws_entry.file_name();
@@ -764,7 +785,8 @@ pub(crate) fn walk_project_dirs(
};
for proj_entry in proj_read {
let proj_entry = proj_entry?;
- if !proj_entry.file_type()?.is_dir() {
+ let proj_metadata = std::fs::symlink_metadata(proj_entry.path())?;
+ if crate::confinement::is_link_like(&proj_metadata) || !proj_metadata.is_dir() {
continue;
}
let proj_name = proj_entry.file_name();
@@ -849,6 +871,17 @@ pub(crate) fn walk_markdown_partial(root: &Path) -> WikiResult<(Vec<PagePath>, b
let mut partial = false;
let mut stack = vec![root.to_path_buf()];
while let Some(dir) = stack.pop() {
+ let metadata = match std::fs::symlink_metadata(&dir) {
+ Ok(metadata) => metadata,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
+ partial = true;
+ continue;
+ }
+ Err(error) => return Err(error.into()),
+ };
+ if crate::confinement::is_link_like(&metadata) {
+ continue;
+ }
let read = match std::fs::read_dir(&dir) {
Ok(r) => r,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
@@ -860,14 +893,9 @@ pub(crate) fn walk_markdown_partial(root: &Path) -> WikiResult<(Vec<PagePath>, b
for entry in read {
let entry = entry?;
let path = entry.path();
- let ft = entry.file_type()?;
- // Skip symlinks entirely. An attacker with write access to
- // the wiki/ dir could otherwise plant a symlink to /etc/hosts,
- // /home/user/.ssh/id_ed25519 etc. and have the watcher
- // index the target's content. The sanitiser would still
- // scrub credentials, but we'd be reading files we
- // shouldn't be reading. (Audit critical #3.)
- if ft.is_symlink() {
+ let metadata = std::fs::symlink_metadata(&path)?;
+ let ft = metadata.file_type();
+ if crate::confinement::is_link_like(&metadata) {
continue;
}
if ft.is_dir() {
@@ -967,6 +995,24 @@ mod tests {
true
}
+ #[cfg(windows)]
+ fn create_test_symlink_dir(target: &Path, link: &Path) -> bool {
+ match std::os::windows::fs::symlink_dir(target, link) {
+ Ok(()) => true,
+ Err(e) if e.raw_os_error() == Some(1314) => {
+ eprintln!("skipping directory reparse assertion: Windows privilege unavailable");
+ false
+ }
+ Err(e) => panic!("failed to create directory link {}: {e}", link.display()),
+ }
+ }
+
+ #[cfg(unix)]
+ fn create_test_symlink_dir(target: &Path, link: &Path) -> bool {
+ std::os::unix::fs::symlink(target, link).unwrap();
+ true
+ }
+
async fn setup() -> (TempDir, Store, Wiki, WorkspaceId, ProjectId) {
let tmp = TempDir::new().unwrap();
let store = Store::open(tmp.path()).unwrap();
@@ -1705,9 +1751,47 @@ mod tests {
);
}
+ #[cfg(any(unix, windows))]
+ #[test]
+ fn walk_markdown_skips_linked_directories_and_their_ledgers() {
+ let tmp = TempDir::new().unwrap();
+ let project = tmp.path().join("project");
+ let outside = tmp.path().join("outside");
+ std::fs::create_dir(&project).unwrap();
+ std::fs::create_dir(&outside).unwrap();
+ std::fs::write(project.join("control.md"), "control\n").unwrap();
+ std::fs::write(outside.join("page.md"), "outside page\n").unwrap();
+ std::fs::write(
+ outside.join("log-2026-10.md"),
+ "## [2026-10-01T00:00:00Z] stop | outside ledger\n",
+ )
+ .unwrap();
+ if !create_test_symlink_dir(&outside, &project.join("linked")) {
+ return;
+ }
+
+ let found = walk_markdown(&project).unwrap();
+ assert_eq!(found, vec![PagePath::new("control.md").unwrap()]);
+ }
+
/// Direct notify events must use the same symlink guard as full-tree walks;
/// otherwise a symlinked markdown file can be opened before reconciliation
/// gets a chance to skip it.
+ #[test]
+ fn shared_link_like_helper_accepts_regular_files_and_directories() {
+ let tmp = TempDir::new().unwrap();
+ let directory = tmp.path().join("directory");
+ let file = tmp.path().join("file.md");
+ std::fs::create_dir(&directory).unwrap();
+ std::fs::write(&file, "control").unwrap();
+ assert!(!crate::confinement::is_link_like(
+ &std::fs::symlink_metadata(directory).unwrap()
+ ));
+ assert!(!crate::confinement::is_link_like(
+ &std::fs::symlink_metadata(file).unwrap()
+ ));
+ }
+
#[cfg(any(unix, windows))]
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn direct_file_event_skips_symlink() {
diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rs
index be7eeb17..4c77d760 100644
--- a/crates/ai-memory-wiki/src/wiki.rs
+++ b/crates/ai-memory-wiki/src/wiki.rs
@@ -17,6 +17,9 @@ use ai_memory_store::{
use tokio::sync::RwLock;
use crate::admission::{AdmissionChain, AdmissionContext, AdmissionOp};
+use crate::confinement::{
+ Prepare, project_path, project_root as confined_project_root, tree_path, workspace_path,
+};
use crate::error::{WikiError, WikiResult};
use crate::git::{Checkpoint, GitAdapter};
use crate::markdown::{Markdown, derive_title, emit, parse};
@@ -207,7 +210,7 @@ impl Wiki {
/// created.
pub fn new(data_dir: &Path, writer: WriterHandle) -> WikiResult<Self> {
let root = data_dir.join("wiki");
- std::fs::create_dir_all(&root)?;
+ crate::confinement::initialize_root(&root)?;
let git = GitAdapter::open_or_init(&root)?;
Ok(Self {
root,
@@ -334,6 +337,7 @@ impl Wiki {
/// # Errors
/// Propagates [`WikiError`] from the git adapter.
pub fn commit_all(&self, message: &str) -> WikiResult<Option<git2::Oid>> {
+ self.inspect_wiki_tree()?;
self.git.commit_all(message)
}
@@ -349,8 +353,25 @@ impl Wiki {
file_name: &str,
bytes: &[u8],
) -> std::io::Result<PathBuf> {
- let path = self.project_root(workspace_id, project_id).join(file_name);
- self.git.append(&path, bytes)?;
+ self.append_under_project_checked(workspace_id, project_id, file_name, bytes)
+ .map_err(crate::error::into_io_error)
+ }
+
+ pub(crate) fn append_under_project_checked(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ file_name: &str,
+ bytes: &[u8],
+ ) -> WikiResult<PathBuf> {
+ let path = project_path(
+ &self.root,
+ workspace_id,
+ project_id,
+ Path::new(file_name),
+ Prepare::Parents,
+ )?;
+ self.git.append_checked(&path, bytes)?;
Ok(path)
}
/// Return the most recent wiki git checkpoints, newest first.
@@ -370,9 +391,8 @@ impl Wiki {
/// # Errors
/// Propagates [`WikiError`] from the git adapter.
pub fn ensure_upgrade_baseline_checkpoint(&self) -> WikiResult<Option<git2::Oid>> {
- if self.git.commit_count() == 0 {
- self.git
- .commit_all("upgrade baseline: existing wiki tree before recovery checkpoints")
+ if self.git.commit_count_checked()? == 0 {
+ self.commit_all("upgrade baseline: existing wiki tree before recovery checkpoints")
} else {
Ok(None)
}
@@ -424,7 +444,11 @@ impl Wiki {
to_workspace: WorkspaceId,
admission_ctx: Option<AdmissionContext>,
) -> WikiResult<MoveSummary> {
+ self.inspect_project_tree(from_workspace, project_id)?;
+ self.inspect_project_tree(to_workspace, project_id)?;
let _guard = self.mutation_lock.write().await;
+ self.inspect_project_tree(from_workspace, project_id)?;
+ self.inspect_project_tree(to_workspace, project_id)?;
let resolved_ctx = if let Some(chain) = &self.admission_chain {
let mut ctx = admission_ctx.unwrap_or_default();
ctx.op = AdmissionOp::MoveProject;
@@ -436,8 +460,8 @@ impl Wiki {
None
};
- let src = self.project_root(from_workspace, project_id);
- let dst = self.project_root(to_workspace, project_id);
+ let src = self.confined_project_root(from_workspace, project_id, Prepare::Inspect)?;
+ let dst = self.confined_project_root(to_workspace, project_id, Prepare::Parents)?;
if dst.exists() {
return Err(crate::WikiError::DestinationExists(
@@ -446,10 +470,7 @@ impl Wiki {
}
let renamed = if src.exists() {
- if let Some(parent) = dst.parent() {
- std::fs::create_dir_all(parent)?;
- }
- self.git.rename(&src, &dst)?;
+ self.git.rename_checked(&src, &dst)?;
true
} else {
// Nothing on disk to move (a project with zero written pages).
@@ -468,17 +489,12 @@ impl Wiki {
Ok(summary)
}
Err(e) => {
- if renamed {
- if let Some(parent) = src.parent() {
- std::fs::create_dir_all(parent)?;
- }
- if let Err(rollback_err) = self.git.rename(&dst, &src) {
- return Err(crate::WikiError::Io(std::io::Error::other(format!(
- "INCONSISTENT STATE: files moved but DB re-stamp failed ({e}) and dir rename-back also failed ({rollback_err}); manually move {} -> {} or finish the re-stamp",
- dst.display(),
- src.display()
- ))));
- }
+ if renamed && let Err(rollback_err) = self.git.rename_checked(&dst, &src) {
+ return Err(crate::WikiError::Io(std::io::Error::other(format!(
+ "INCONSISTENT STATE: files moved but DB re-stamp failed ({e}) and dir rename-back also failed ({rollback_err}); manually move {} -> {} or finish the re-stamp",
+ dst.display(),
+ src.display()
+ ))));
}
Err(e.into())
}
@@ -517,7 +533,11 @@ impl Wiki {
author_id: Option<UserId>,
admission_ctx: Option<AdmissionContext>,
) -> WikiResult<MoveSessionOutcome> {
+ self.inspect_project_tree(from.0, from.1)?;
+ self.inspect_project_tree(to.0, to.1)?;
let _guard = self.mutation_lock.write().await;
+ self.inspect_project_tree(from.0, from.1)?;
+ self.inspect_project_tree(to.0, to.1)?;
let resolved_ctx = if let Some(chain) = &self.admission_chain {
let mut ctx = admission_ctx.unwrap_or_default();
ctx.op = AdmissionOp::MoveSession;
@@ -529,17 +549,23 @@ impl Wiki {
};
let file_name = format!("{session_id}.md");
- let src = self
- .project_root(from.0, from.1)
- .join("sessions")
- .join(&file_name);
+ let src = project_path(
+ &self.root,
+ from.0,
+ from.1,
+ &PathBuf::from("sessions").join(&file_name),
+ Prepare::Inspect,
+ )?;
let parked = if from != to && src.is_file() {
let target = match pages {
PagesMode::Move => {
- let dst = self
- .project_root(to.0, to.1)
- .join("sessions")
- .join(&file_name);
+ let dst = project_path(
+ &self.root,
+ to.0,
+ to.1,
+ &PathBuf::from("sessions").join(&file_name),
+ Prepare::Parents,
+ )?;
if dst.exists() {
return Err(WikiError::DestinationPageExists(dst.display().to_string()));
}
@@ -551,10 +577,7 @@ impl Wiki {
src.with_file_name(format!(".ai-memory-tmp.move-session.{file_name}"))
}
};
- if let Some(parent) = target.parent() {
- std::fs::create_dir_all(parent)?;
- }
- self.git.rename(&src, &target)?;
+ self.git.rename_checked(&src, &target)?;
Some(target)
} else {
None
@@ -572,7 +595,7 @@ impl Wiki {
(Some(tmp), PagesMode::Regenerate) => {
// The rows are retired; a leftover temp file is
// ignored by the watcher, so this is best-effort.
- if let Err(e) = self.git.remove_file(tmp) {
+ if let Err(e) = self.git.remove_file_checked(tmp) {
tracing::warn!(
error = %e,
path = %tmp.display(),
@@ -589,7 +612,7 @@ impl Wiki {
}
Err(e) => {
if let Some(target) = parked
- && let Err(rollback_err) = self.git.rename(&target, &src)
+ && let Err(rollback_err) = self.git.rename_checked(&target, &src)
{
return Err(WikiError::Io(std::io::Error::other(format!(
"INCONSISTENT STATE: session page file moved but DB re-stamp failed ({e}) and moving it back also failed ({rollback_err}); manually move {} -> {}",
@@ -670,7 +693,13 @@ impl Wiki {
return;
}
};
- let ws_dir = self.root.join(workspace_id.to_string());
+ let ws_dir = match workspace_path(&self.root, workspace_id, Prepare::Directory) {
+ Ok(path) => path,
+ Err(error) => {
+ tracing::warn!(%error, "scope-manifest path confinement failed (non-fatal)");
+ return;
+ }
+ };
let mut project_fm = serde_json::json!({ "project": scope.project_name });
if let Some(repo_path) = scope.repo_path {
project_fm["repo_path"] = serde_json::Value::String(repo_path);
@@ -681,7 +710,9 @@ impl Wiki {
serde_json::json!({ "workspace": scope.workspace_name }),
)
.and_then(|_| {
- self.write_scope_manifest(&ws_dir.join(project_id.to_string()), project_fm)
+ let project_dir =
+ self.confined_project_root(workspace_id, project_id, Prepare::Directory)?;
+ self.write_scope_manifest(&project_dir, project_fm)
});
match written {
Ok(_) => {
@@ -717,11 +748,94 @@ impl Wiki {
project_id: ProjectId,
path: &PagePath,
) -> WikiResult<Markdown> {
- let abs = self.abs_path(workspace_id, project_id, path);
+ let abs = self.confined_page_path(workspace_id, project_id, path, Prepare::Inspect)?;
let raw = std::fs::read_to_string(&abs)?;
parse(&raw)
}
+ fn confined_project_root(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ prepare: Prepare,
+ ) -> WikiResult<PathBuf> {
+ confined_project_root(&self.root, workspace_id, project_id, prepare)
+ }
+
+ /// Refuse a project tree containing a symbolic link or reparse point.
+ ///
+ /// # Errors
+ /// Returns [`WikiError::Confinement`] for any linked component.
+ pub fn validate_project_tree(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ ) -> WikiResult<()> {
+ self.inspect_project_tree(workspace_id, project_id)
+ }
+
+ pub(crate) fn validate_project_root(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ ) -> WikiResult<()> {
+ self.confined_project_root(workspace_id, project_id, Prepare::Inspect)
+ .map(|_| ())
+ }
+
+ pub(crate) fn validate_page_path(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ path: &PagePath,
+ ) -> WikiResult<()> {
+ self.confined_page_path(workspace_id, project_id, path, Prepare::Inspect)
+ .map(|_| ())
+ }
+
+ /// Refuse a workspace tree containing a symbolic link or reparse point.
+ ///
+ /// # Errors
+ /// Returns [`WikiError::Confinement`] for any linked component.
+ pub fn validate_workspace_tree(&self, workspace_id: WorkspaceId) -> WikiResult<()> {
+ self.inspect_workspace_tree(workspace_id)
+ }
+
+ fn inspect_wiki_tree(&self) -> WikiResult<()> {
+ let git_dir = crate::confinement::inspect_git_directory(&self.root)?;
+ crate::confinement::inspect_tree_except(&self.root, &[git_dir.as_path()])
+ }
+
+ fn inspect_project_tree(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ ) -> WikiResult<()> {
+ let root = self.confined_project_root(workspace_id, project_id, Prepare::Inspect)?;
+ crate::confinement::inspect_tree_if_present(&root)
+ }
+
+ fn inspect_workspace_tree(&self, workspace_id: WorkspaceId) -> WikiResult<()> {
+ let root = workspace_path(&self.root, workspace_id, Prepare::Inspect)?;
+ crate::confinement::inspect_tree_if_present(&root)
+ }
+
+ fn confined_page_path(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ path: &PagePath,
+ prepare: Prepare,
+ ) -> WikiResult<PathBuf> {
+ project_path(
+ &self.root,
+ workspace_id,
+ project_id,
+ Path::new(path.as_str()),
+ prepare,
+ )
+ }
+
/// Restore one page from a git checkpoint and reindex it into the store.
///
/// The checkpoint path is resolved through the UUID-backed wiki layout, so
@@ -741,6 +855,7 @@ impl Wiki {
path: PagePath,
rev: &str,
) -> WikiResult<PageId> {
+ self.confined_page_path(workspace_id, project_id, &path, Prepare::Inspect)?;
let rel = PathBuf::from(workspace_id.to_string())
.join(project_id.to_string())
.join(path.as_str());
@@ -759,10 +874,7 @@ impl Wiki {
let _guard = self.mutation_lock.read().await;
self.ensure_project_workspace(workspace_id, project_id)
.await?;
- let abs = self.abs_path(workspace_id, project_id, &path);
- if let Some(parent) = abs.parent() {
- std::fs::create_dir_all(parent)?;
- }
+ let abs = self.confined_page_path(workspace_id, project_id, &path, Prepare::Parents)?;
self.git.write_atomic(&abs, raw.as_bytes())?;
let id = self
.writer
@@ -842,7 +954,9 @@ impl Wiki {
admission_ctx: Option<AdmissionContext>,
author_id: Option<ai_memory_core::UserId>,
) -> WikiResult<()> {
+ self.confined_page_path(workspace_id, project_id, path, Prepare::Inspect)?;
let _guard = self.mutation_lock.read().await;
+ self.confined_page_path(workspace_id, project_id, path, Prepare::Inspect)?;
self.ensure_project_workspace(workspace_id, project_id)
.await?;
self.remove_page_locked(
@@ -878,6 +992,7 @@ impl Wiki {
expected_latest_id: PageId,
admission_ctx: Option<AdmissionContext>,
) -> WikiResult<bool> {
+ self.confined_page_path(workspace_id, project_id, path, Prepare::Inspect)?;
let _guard = self.mutation_lock.write().await;
self.ensure_project_workspace(workspace_id, project_id)
.await?;
@@ -918,6 +1033,7 @@ impl Wiki {
expected_latest_id: PageId,
admission_ctx: Option<AdmissionContext>,
) -> WikiResult<bool> {
+ self.confined_page_path(workspace_id, project_id, path, Prepare::Inspect)?;
let _guard = self.mutation_lock.write().await;
self.ensure_project_workspace(workspace_id, project_id)
.await?;
@@ -993,6 +1109,7 @@ impl Wiki {
path: &PagePath,
expected_latest_id: PageId,
) -> WikiResult<bool> {
+ self.confined_page_path(workspace_id, project_id, path, Prepare::Inspect)?;
let _guard = self.mutation_lock.write().await;
self.ensure_project_workspace(workspace_id, project_id)
.await?;
@@ -1006,7 +1123,7 @@ impl Wiki {
if current != Some(expected_latest_id) {
return Ok(false);
}
- let abs = self.abs_path(workspace_id, project_id, path);
+ let abs = self.confined_page_path(workspace_id, project_id, path, Prepare::Inspect)?;
if abs.try_exists()? {
// The file came back (e.g. a slow atomic-save pattern beyond the
// two-pass window, or a deliberate rewrite mid-check). Leave the
@@ -1050,6 +1167,7 @@ impl Wiki {
admission_ctx: Option<AdmissionContext>,
removal: PageStoreRemoval,
) -> WikiResult<bool> {
+ self.confined_page_path(workspace_id, project_id, path, Prepare::Inspect)?;
let mut resolved_ctx = None;
if let Some(chain) = &self.admission_chain {
let mut ctx = admission_ctx.unwrap_or_default();
@@ -1059,11 +1177,11 @@ impl Wiki {
chain.notify(Some(path.as_str()), &ctx).await?;
resolved_ctx = Some(ctx);
}
- let abs = self.abs_path(workspace_id, project_id, path);
+ let abs = self.confined_page_path(workspace_id, project_id, path, Prepare::Inspect)?;
let quarantined = match quarantine_file(&self.git, &abs) {
Ok(path) => path,
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
- Err(e) => return Err(crate::WikiError::Io(e)),
+ Err(WikiError::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => None,
+ Err(e) => return Err(e),
};
let delete_result = match removal {
@@ -1107,7 +1225,7 @@ impl Wiki {
}
if let Some(quarantine) = quarantined {
- self.git.remove_file(&quarantine)?;
+ self.git.remove_file_checked(&quarantine)?;
}
if let (Some(chain), Some(ctx)) = (&self.admission_chain, &resolved_ctx) {
@@ -1136,6 +1254,7 @@ impl Wiki {
tombstone_id: PageId,
cutoff_us: i64,
) -> WikiResult<usize> {
+ self.confined_page_path(workspace_id, project_id, path, Prepare::Inspect)?;
let _guard = self.mutation_lock.write().await;
self.ensure_project_workspace(workspace_id, project_id)
.await?;
@@ -1146,7 +1265,7 @@ impl Wiki {
let mut current_latest = reader
.latest_page_id_by_ids(workspace_id, project_id, path.as_str().to_string())
.await?;
- let abs = self.abs_path(workspace_id, project_id, path);
+ let abs = self.confined_page_path(workspace_id, project_id, path, Prepare::Inspect)?;
if current_latest.is_none() && abs.try_exists()? {
// Deliberately drops any `PendingEmbed`: this whole function runs
// under the exclusive write lock (`_guard` above, held until
@@ -1189,6 +1308,7 @@ impl Wiki {
project_id: ProjectId,
admission_ctx: Option<AdmissionContext>,
) -> WikiResult<()> {
+ self.inspect_project_tree(workspace_id, project_id)?;
let ctx = self
.admit_purge_project(workspace_id, project_id, admission_ctx)
.await?;
@@ -1209,6 +1329,7 @@ impl Wiki {
project_id: ProjectId,
admission_ctx: Option<AdmissionContext>,
) -> WikiResult<Option<AdmissionContext>> {
+ self.inspect_project_tree(workspace_id, project_id)?;
if let Some(chain) = &self.admission_chain {
let mut ctx = admission_ctx.unwrap_or_default();
ctx.op = AdmissionOp::PurgeProject;
@@ -1233,6 +1354,7 @@ impl Wiki {
project_id: ProjectId,
admission_ctx: Option<AdmissionContext>,
) -> WikiResult<Option<AdmissionContext>> {
+ self.inspect_project_tree(workspace_id, project_id)?;
if let Some(chain) = &self.admission_chain {
let mut ctx = admission_ctx.unwrap_or_default();
ctx.op = AdmissionOp::PurgeSession;
@@ -1256,6 +1378,7 @@ impl Wiki {
workspace_id: WorkspaceId,
admission_ctx: Option<AdmissionContext>,
) -> WikiResult<Option<AdmissionContext>> {
+ self.inspect_workspace_tree(workspace_id)?;
if let Some(chain) = &self.admission_chain {
let mut ctx = admission_ctx.unwrap_or_default();
ctx.op = AdmissionOp::PurgeWorkspace;
@@ -1356,6 +1479,7 @@ impl Wiki {
op: AdmissionOp,
actor: ActorContext,
) -> WikiResult<()> {
+ self.confined_page_path(workspace_id, project_id, path, Prepare::Inspect)?;
if let Some(chain) = &self.admission_chain {
let mut ctx = AdmissionContext {
op,
@@ -1379,11 +1503,12 @@ impl Wiki {
project_id: ProjectId,
) -> WikiResult<()> {
let _guard = self.mutation_lock.write().await;
- let root = self.project_root(workspace_id, project_id);
- match self.git.remove_dir_all(&root) {
+ self.inspect_project_tree(workspace_id, project_id)?;
+ let root = self.confined_project_root(workspace_id, project_id, Prepare::Inspect)?;
+ match self.git.remove_dir_all_checked(&root) {
Ok(()) => Ok(()),
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
- Err(e) => Err(crate::WikiError::Io(e)),
+ Err(WikiError::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(e) => Err(e),
}
}
@@ -1395,11 +1520,12 @@ impl Wiki {
/// Returns [`WikiError::Io`] on filesystem errors other than NotFound.
pub async fn remove_workspace_dir(&self, workspace_id: WorkspaceId) -> WikiResult<()> {
let _guard = self.mutation_lock.write().await;
- let root = self.root.join(workspace_id.to_string());
- match self.git.remove_dir_all(&root) {
+ self.inspect_workspace_tree(workspace_id)?;
+ let root = workspace_path(&self.root, workspace_id, Prepare::Inspect)?;
+ match self.git.remove_dir_all_checked(&root) {
Ok(()) => Ok(()),
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
- Err(e) => Err(crate::WikiError::Io(e)),
+ Err(WikiError::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(e) => Err(e),
}
}
@@ -1441,7 +1567,9 @@ impl Wiki {
author_id: Option<UserId>,
compaction: ai_memory_store::Compaction,
) -> WikiResult<PurgeSessionOutcome> {
+ self.inspect_project_tree(workspace_id, project_id)?;
let _guard = self.mutation_lock.write().await;
+ self.inspect_project_tree(workspace_id, project_id)?;
// Always `Commit`: a caller that only wants a preview (the HTTP
// handler's `dry_run` branch) goes straight through
// `WriterHandle::purge_session` instead, bypassing this wrapper
@@ -1462,12 +1590,12 @@ impl Wiki {
let mut files_failed = Vec::new();
for path in &summary.removed_paths {
let abs = self.abs_path(workspace_id, project_id, path);
- match self.git.remove_file(&abs) {
+ match self.git.remove_file_checked(&abs) {
Ok(()) => {
sync_parent_best_effort(&abs);
files_deleted.push(path.clone());
}
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
+ Err(WikiError::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => {
tracing::warn!(
operation = "purge-session",
@@ -1524,6 +1652,13 @@ impl Wiki {
project_id: ProjectId,
proposal_id: AutoImproveProposalId,
) -> WikiResult<PathBuf> {
+ project_path(
+ &self.root,
+ workspace_id,
+ project_id,
+ Path::new(&artifact_path_for(proposal_id)),
+ Prepare::Inspect,
+ )?;
let reader = self.store_reader.as_ref().ok_or_else(|| {
ai_memory_wiki_error("auto-improve sidecar write requires a store reader")
})?;
@@ -1552,6 +1687,7 @@ impl Wiki {
author_id: Option<UserId>,
admission_ctx: Option<AdmissionContext>,
) -> WikiResult<ApproveAutoImproveProposalResult> {
+ self.inspect_project_tree(workspace_id, project_id)?;
let reader = self
.store_reader
.as_ref()
@@ -1563,6 +1699,7 @@ impl Wiki {
let path = detail.summary.target_path.clone();
path.ensure_portable()?;
+ self.confined_page_path(workspace_id, project_id, &path, Prepare::Inspect)?;
let mut frontmatter = serde_json::json!({
"kind": detail.summary.kind,
"title": detail.summary.title,
@@ -1633,9 +1770,10 @@ impl Wiki {
let result = {
let _guard = self.mutation_lock.write().await;
+ self.confined_page_path(workspace_id, project_id, &path, Prepare::Inspect)?;
self.ensure_project_workspace(workspace_id, project_id)
.await?;
- let abs = self.abs_path(workspace_id, project_id, &path);
+ let abs = self.confined_page_path(workspace_id, project_id, &path, Prepare::Parents)?;
let installed =
replace_file_with_rollback_snapshot(&self.git, &abs, emitted.as_bytes())?;
match self
@@ -1696,6 +1834,7 @@ impl Wiki {
project_id: ProjectId,
path: PagePath,
) -> WikiResult<PageId> {
+ self.confined_page_path(workspace_id, project_id, &path, Prepare::Inspect)?;
if is_pending_path(&path) {
return Err(ai_memory_wiki_error(
"refusing to index pending proposal sidecar",
@@ -1707,6 +1846,7 @@ impl Wiki {
// would block every other write in the wiki for its duration.
let (id, pending_embed) = {
let _guard = self.mutation_lock.read().await;
+ self.confined_page_path(workspace_id, project_id, &path, Prepare::Inspect)?;
self.ensure_project_workspace(workspace_id, project_id)
.await?;
self.reindex_page_locked(workspace_id, project_id, path)
@@ -1741,14 +1881,9 @@ impl Wiki {
path: PagePath,
) -> WikiResult<(PageId, Option<PendingEmbed>)> {
let _page_guard = self.lock_page(workspace_id, project_id, &path).await;
- let abs = self.abs_path(workspace_id, project_id, &path);
- if std::fs::symlink_metadata(&abs)?.file_type().is_symlink() {
- return Err(WikiError::Io(std::io::Error::other(format!(
- "refusing to reindex symlinked page {}",
- path.as_str()
- ))));
- }
- let md = self.read_page(workspace_id, project_id, &path)?;
+ let abs = self.confined_page_path(workspace_id, project_id, &path, Prepare::Inspect)?;
+ let raw = std::fs::read_to_string(&abs)?;
+ let md = parse(&raw)?;
let title = derive_title(&md.frontmatter, &md.body, &path);
let links = crate::markdown::extract_all_links(&md.frontmatter, &md.body, &path);
// Markdown is the source of truth: preserve explicit tier/pinned
@@ -1835,7 +1970,7 @@ impl Wiki {
};
WikiError::Io(std::io::Error::new(error.kind(), message))
})?;
- if meta.file_type().is_symlink() {
+ if crate::confinement::is_link_like(&meta) {
return Err(WikiError::Io(std::io::Error::other(format!(
"refusing to read symlinked scope manifest {}",
path.display()
@@ -1873,6 +2008,7 @@ impl Wiki {
/// [`Self::backfill_scope_manifests`] repairs trees written by older
/// ones on every start.
pub async fn reindex_all(&self) -> WikiResult<ReindexSummary> {
+ self.inspect_wiki_tree()?;
let root = self.root().to_path_buf();
let project_dirs =
tokio::task::spawn_blocking(move || crate::watcher::walk_project_dirs(&root))
@@ -1979,6 +2115,13 @@ impl Wiki {
dir: &Path,
mut frontmatter: serde_json::Value,
) -> WikiResult<bool> {
+ let relative = dir
+ .strip_prefix(&self.root)
+ .map_err(|_| WikiError::Confinement {
+ path: dir.to_path_buf(),
+ reason: "scope manifest directory is outside the wiki root",
+ })?;
+ let dir = tree_path(&self.root, relative, Prepare::Directory)?;
// OKF conformance at the manifest choke point: every non-reserved
// .md needs a `type`, and the startup backfill's byte-compare must
// agree with what the OKF migration writes — a typeless emit here
@@ -1996,7 +2139,7 @@ impl Wiki {
})?;
let path = dir.join("_meta.md");
match std::fs::symlink_metadata(&path) {
- Ok(meta) if meta.file_type().is_symlink() => {
+ Ok(meta) if crate::confinement::is_link_like(&meta) => {
return Err(WikiError::Io(std::io::Error::other(format!(
"refusing to update symlinked scope manifest {}",
path.display()
@@ -2009,7 +2152,6 @@ impl Wiki {
}
Ok(_) | Err(_) => {}
}
- std::fs::create_dir_all(dir)?;
self.git.write_atomic(&path, content.as_bytes())?;
Ok(true)
}
@@ -2031,7 +2173,7 @@ impl Wiki {
let scopes = reader.list_all_scopes().await?;
let mut written = 0;
for ws in workspaces {
- let ws_dir = self.root().join(ws.workspace_id.to_string());
+ let ws_dir = workspace_path(&self.root, ws.workspace_id, Prepare::Directory)?;
if self.write_scope_manifest(
&ws_dir,
serde_json::json!({ "workspace": ws.workspace_name }),
@@ -2040,12 +2182,13 @@ impl Wiki {
}
}
for s in scopes {
- let ws_dir = self.root().join(s.workspace_id.to_string());
+ let project_dir =
+ self.confined_project_root(s.workspace_id, s.project_id, Prepare::Directory)?;
let mut fm = serde_json::json!({ "project": s.project_name });
if let Some(rp) = s.repo_path {
fm["repo_path"] = serde_json::Value::String(rp);
}
- if self.write_scope_manifest(&ws_dir.join(s.project_id.to_string()), fm)? {
+ if self.write_scope_manifest(&project_dir, fm)? {
written += 1;
}
}
@@ -2062,13 +2205,19 @@ impl Wiki {
/// # Errors
/// Returns [`WikiError`] for store, filesystem or git errors.
pub async fn repair_date_only_stale_after(&self) -> WikiResult<(u64, usize)> {
+ self.inspect_wiki_tree()?;
let _guard = self.mutation_lock.write().await;
+ self.inspect_wiki_tree()?;
let repair = self.writer.repair_date_only_stale_after().await?;
let mut files = 0;
for page in &repair.date_only_pages {
- let abs = self
- .project_root(page.workspace_id, page.project_id)
- .join(&page.path);
+ let page_path = PagePath::new(&page.path)?;
+ let abs = self.confined_page_path(
+ page.workspace_id,
+ page.project_id,
+ &page_path,
+ Prepare::Inspect,
+ )?;
let raw = match std::fs::read_to_string(&abs) {
Ok(raw) => raw,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
@@ -2083,8 +2232,7 @@ impl Wiki {
}
}
if files > 0 {
- self.git
- .commit_all("okf: repair date-only stale_after on existing pages")?;
+ self.commit_all("okf: repair date-only stale_after on existing pages")?;
}
Ok((repair.rows_repaired, files))
}
@@ -2106,6 +2254,12 @@ impl Wiki {
// supported platform, before anything is written.
for req in &requests {
req.path.ensure_portable()?;
+ self.confined_page_path(
+ req.workspace_id,
+ req.project_id,
+ &req.path,
+ Prepare::Inspect,
+ )?;
}
// Pre-compute markdown for each request. Filesystem work happens only
// after the mutation guard + project/workspace validation below.
@@ -2173,6 +2327,14 @@ impl Wiki {
let (ids, dispatches) = {
let _guard = self.mutation_lock.read().await;
+ for (req, _, _, _) in &staged {
+ self.confined_page_path(
+ req.workspace_id,
+ req.project_id,
+ &req.path,
+ Prepare::Inspect,
+ )?;
+ }
// Serialize every path in this batch against concurrent single-page
// or batch writers to the same path (#607). Sorted acquisition
// keeps a batch deadlock-free against any other writer.
@@ -2187,13 +2349,18 @@ impl Wiki {
std::path::PathBuf,
Option<AdmissionContext>,
)> = Vec::with_capacity(staged.len());
- for (req, emitted, abs, ctx) in staged {
+ for (req, emitted, _abs, ctx) in staged {
self.ensure_project_workspace(req.workspace_id, req.project_id)
.await?;
+ let abs = self.confined_page_path(
+ req.workspace_id,
+ req.project_id,
+ &req.path,
+ Prepare::Parents,
+ )?;
let parent = abs.parent().ok_or_else(|| {
ai_memory_wiki_error("page path has no parent (cannot stage tempfile)")
})?;
- std::fs::create_dir_all(parent)?;
let mut tmp = tempfile::Builder::new()
.prefix(".ai-memory-tmp.")
.tempfile_in(parent)?;
@@ -2326,6 +2493,12 @@ impl Wiki {
/// # Errors
/// Returns [`WikiError`] for any filesystem, parsing, or store error.
pub async fn write_page(&self, req: WritePageRequest) -> WikiResult<PageId> {
+ self.confined_page_path(
+ req.workspace_id,
+ req.project_id,
+ &req.path,
+ Prepare::Inspect,
+ )?;
// Reject a path that cannot be materialised and checkpointed on every
// supported platform, before anything is written.
//
@@ -2439,12 +2612,10 @@ impl Wiki {
// writer's and leave disk disagreeing with the DB `latest` row
// (#607). Different paths still proceed concurrently.
let _page_guard = self.lock_page(workspace_id, project_id, &path).await;
+ self.confined_page_path(workspace_id, project_id, &path, Prepare::Inspect)?;
self.ensure_project_workspace(workspace_id, project_id)
.await?;
- let abs = self.abs_path(workspace_id, project_id, &path);
- if let Some(parent) = abs.parent() {
- std::fs::create_dir_all(parent)?;
- }
+ let abs = self.confined_page_path(workspace_id, project_id, &path, Prepare::Parents)?;
let installed =
replace_file_with_rollback_snapshot(&self.git, &abs, emitted.as_bytes())?;
@@ -2926,10 +3097,10 @@ fn rollback_installed_files(git: &GitAdapter, installed: &[InstalledFile]) -> Wi
for file in installed.iter().rev() {
match &file.previous {
Some(bytes) => git.write_atomic(&file.path, bytes)?,
- None => match git.remove_file(&file.path) {
+ None => match git.remove_file_checked(&file.path) {
Ok(()) => sync_parent_best_effort(&file.path),
- Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
- Err(e) => return Err(WikiError::Io(e)),
+ Err(WikiError::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {}
+ Err(e) => return Err(e),
},
}
}
@@ -2949,21 +3120,21 @@ fn rollback_or_inconsistent<E: std::fmt::Display>(
Ok(())
}
-fn quarantine_file(git: &GitAdapter, path: &Path) -> std::io::Result<Option<PathBuf>> {
+fn quarantine_file(git: &GitAdapter, path: &Path) -> WikiResult<Option<PathBuf>> {
let Some(parent) = path.parent() else {
- return Err(std::io::Error::other(
+ return Err(WikiError::Io(std::io::Error::other(
"page path has no parent (cannot quarantine delete)",
- ));
+ )));
};
let tmp = tempfile::Builder::new()
.prefix(".ai-memory-delete.")
.tempfile_in(parent)?;
let (_file, quarantine) = tmp.keep().map_err(|e| e.error)?;
- git.remove_file(&quarantine)?;
- match git.rename(path, &quarantine) {
+ git.remove_file_checked(&quarantine)?;
+ match git.rename_checked(path, &quarantine) {
Ok(()) => Ok(Some(quarantine)),
Err(e) => {
- let _ = git.remove_file(&quarantine);
+ let _ = git.remove_file_checked(&quarantine);
Err(e)
}
}
@@ -2976,7 +3147,7 @@ fn restore_quarantined_file(
page_path: &PagePath,
) {
if let Some(quarantine) = quarantined
- && let Err(error) = git.rename(quarantine, path)
+ && let Err(error) = git.rename_checked(quarantine, path)
{
tracing::error!(
path = %page_path.as_str(),
@@ -3791,6 +3962,305 @@ mod tests {
(store, wiki, ws, proj)
}
+ #[test]
+ fn append_under_project_public_api_remains_io_result() {
+ let method: fn(&Wiki, WorkspaceId, ProjectId, &str, &[u8]) -> std::io::Result<PathBuf> =
+ Wiki::append_under_project;
+ let _ = method;
+ }
+
+ #[cfg(unix)]
+ fn symlink(target: &Path, link: &Path) {
+ std::os::unix::fs::symlink(target, link).unwrap();
+ }
+
+ #[cfg(unix)]
+ fn assert_confined<T>(result: WikiResult<T>) {
+ assert!(
+ matches!(result, Err(WikiError::Confinement { .. })),
+ "expected confinement refusal"
+ );
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn page_reads_refuse_leaf_and_ancestor_symlinks_without_fallback_classification() {
+ let tmp = TempDir::new().unwrap();
+ let (_store, wiki, ws, proj) = scoped(&tmp).await;
+ let outside = TempDir::new().unwrap();
+ let outside_page = outside.path().join("page.md");
+ std::fs::write(&outside_page, "# Outside\n\ncanary\n").unwrap();
+ let project = wiki.project_root(ws, proj);
+ std::fs::create_dir_all(&project).unwrap();
+
+ let leaf = PagePath::new("leaf.md").unwrap();
+ symlink(&outside_page, &wiki.abs_path(ws, proj, &leaf));
+ let leaf_error = wiki.read_page(ws, proj, &leaf).unwrap_err();
+ assert!(matches!(leaf_error, WikiError::Confinement { .. }));
+ assert!(
+ !matches!(leaf_error, WikiError::Io(ref error) if error.kind() == std::io::ErrorKind::NotFound)
+ );
+
+ let outside_dir = outside.path().join("tree");
+ std::fs::create_dir(&outside_dir).unwrap();
+ std::fs::write(outside_dir.join("page.md"), "# Outside ancestor\n").unwrap();
+ symlink(&outside_dir, &project.join("linked"));
+ assert_confined(wiki.read_page(ws, proj, &PagePath::new("linked/page.md").unwrap()));
+
+ let dangling = PagePath::new("dangling.md").unwrap();
+ symlink(
+ &outside.path().join("missing.md"),
+ &wiki.abs_path(ws, proj, &dangling),
+ );
+ assert_confined(wiki.read_page(ws, proj, &dangling));
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn page_mutations_refuse_ancestor_symlink_and_leave_outside_and_store_unchanged() {
+ let tmp = TempDir::new().unwrap();
+ let (store, wiki, ws, proj) = scoped(&tmp).await;
+ let outside = TempDir::new().unwrap();
+ let project = wiki.project_root(ws, proj);
+ std::fs::create_dir_all(&project).unwrap();
+ std::fs::write(outside.path().join("write.md"), "outside canary").unwrap();
+ symlink(outside.path(), &project.join("linked"));
+
+ assert_confined(
+ wiki.write_page(req(
+ ws,
+ proj,
+ "linked/write.md",
+ "blocked",
+ serde_json::json!({}),
+ ))
+ .await,
+ );
+ assert_confined(
+ wiki.apply_batch(vec![req(
+ ws,
+ proj,
+ "linked/batch.md",
+ "blocked",
+ serde_json::json!({}),
+ )])
+ .await,
+ );
+ assert_confined(
+ wiki.delete_page(
+ ws,
+ proj,
+ &PagePath::new("linked/write.md").unwrap(),
+ None,
+ None,
+ )
+ .await,
+ );
+ assert_eq!(
+ std::fs::read_to_string(outside.path().join("write.md")).unwrap(),
+ "outside canary"
+ );
+ assert!(!outside.path().join("batch.md").exists());
+ assert!(
+ store
+ .reader
+ .search_pages("blocked".into(), 10, None)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn confinement_refusal_happens_before_blocking_and_observer_admission() {
+ use axum::Router;
+ use axum::extract::State;
+ use axum::http::StatusCode;
+ use axum::routing::post;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ let calls = Arc::new(AtomicUsize::new(0));
+ let app = Router::new()
+ .route(
+ "/observe",
+ post(|State(calls): State<Arc<AtomicUsize>>| async move {
+ calls.fetch_add(1, Ordering::SeqCst);
+ StatusCode::NO_CONTENT
+ }),
+ )
+ .with_state(calls.clone());
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+
+ let tmp = TempDir::new().unwrap();
+ let (_store, wiki, ws, proj) = scoped(&tmp).await;
+ let outside = TempDir::new().unwrap();
+ let project = wiki.project_root(ws, proj);
+ std::fs::create_dir_all(&project).unwrap();
+ symlink(outside.path(), &project.join("linked"));
+ let wiki = wiki.with_admission_chain(
+ AdmissionChain::new(vec![WebhookConfig {
+ name: "observer".into(),
+ url: format!("http://{address}/observe"),
+ timeout_ms: 1_000,
+ failure_policy: FailurePolicy::Ignore,
+ events: vec![AdmissionOp::WritePage, AdmissionOp::Delete],
+ blocking: true,
+ }])
+ .unwrap(),
+ );
+
+ assert_confined(
+ wiki.write_page(req(
+ ws,
+ proj,
+ "linked/write.md",
+ "blocked",
+ serde_json::json!({}),
+ ))
+ .await,
+ );
+ assert_confined(
+ wiki.delete_page(
+ ws,
+ proj,
+ &PagePath::new("linked/delete.md").unwrap(),
+ None,
+ None,
+ )
+ .await,
+ );
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ assert_eq!(calls.load(Ordering::SeqCst), 0);
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn restore_and_reindex_refuse_ancestor_symlink_without_touching_canary_or_db() {
+ let tmp = TempDir::new().unwrap();
+ let (store, wiki, ws, proj) = scoped(&tmp).await;
+ let committed = PagePath::new("notes/source.md").unwrap();
+ wiki.write_page(req(
+ ws,
+ proj,
+ committed.as_str(),
+ "safe",
+ serde_json::json!({}),
+ ))
+ .await
+ .unwrap();
+ wiki.commit_all("fixture").unwrap();
+
+ let outside = TempDir::new().unwrap();
+ let canary = outside.path().join("target.md");
+ std::fs::write(&canary, "canary").unwrap();
+ symlink(outside.path(), &wiki.project_root(ws, proj).join("linked"));
+ let linked = PagePath::new("linked/target.md").unwrap();
+ assert_confined(wiki.reindex_page(ws, proj, linked.clone()).await);
+ assert_confined(
+ wiki.restore_page_from_checkpoint(ws, proj, linked.clone(), "HEAD")
+ .await,
+ );
+ assert_eq!(std::fs::read_to_string(&canary).unwrap(), "canary");
+ assert!(
+ store
+ .reader
+ .page_body_by_ids(ws, proj, linked.as_str())
+ .await
+ .unwrap()
+ .is_none()
+ );
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn linked_wiki_root_is_refused_during_construction() {
+ let tmp = TempDir::new().unwrap();
+ let outside = TempDir::new().unwrap();
+ symlink(outside.path(), &tmp.path().join("wiki"));
+ let store = Store::open(tmp.path()).unwrap();
+ assert!(matches!(
+ Wiki::new(tmp.path(), store.writer.clone()),
+ Err(WikiError::Confinement { .. })
+ ));
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn linked_or_dangling_scope_roots_are_refused_but_real_roots_work() {
+ let tmp = TempDir::new().unwrap();
+ let (store, wiki, ws, proj) = scoped(&tmp).await;
+ wiki.write_page(req(
+ ws,
+ proj,
+ "notes/control.md",
+ "control",
+ serde_json::json!({}),
+ ))
+ .await
+ .unwrap();
+
+ let outside = TempDir::new().unwrap();
+ let linked_ws = WorkspaceId::new();
+ symlink(outside.path(), &wiki.root().join(linked_ws.to_string()));
+ assert_confined(
+ wiki.write_page(req(
+ linked_ws,
+ ProjectId::new(),
+ "notes/refused.md",
+ "blocked",
+ serde_json::json!({}),
+ ))
+ .await,
+ );
+
+ let workspace = wiki.root().join(ws.to_string());
+ let linked_project = ProjectId::new();
+ symlink(outside.path(), &workspace.join(linked_project.to_string()));
+ assert_confined(
+ wiki.write_page(req(
+ ws,
+ linked_project,
+ "notes/refused.md",
+ "blocked",
+ serde_json::json!({}),
+ ))
+ .await,
+ );
+
+ let dangling_project = ProjectId::new();
+ symlink(
+ &outside.path().join("missing"),
+ &workspace.join(dangling_project.to_string()),
+ );
+ assert_confined(
+ wiki.write_page(req(
+ ws,
+ dangling_project,
+ "notes/refused.md",
+ "blocked",
+ serde_json::json!({}),
+ ))
+ .await,
+ );
+ assert_eq!(
+ wiki.read_page(ws, proj, &PagePath::new("notes/control.md").unwrap())
+ .unwrap()
+ .body,
+ "control"
+ );
+ assert!(
+ store
+ .reader
+ .search_pages("blocked".into(), 10, None)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ }
+
#[tokio::test]
async fn write_page_embeds_frontmatter_abstract_and_cleans_stale_rows() {
let tmp = TempDir::new().unwrap();
@@ -4887,7 +5357,7 @@ mod tests {
.hard_delete_decay_tombstone(ws, proj, &path, page_id, i64::MAX)
.await
.expect_err("symlinked recreation must fail closed");
- assert!(error.to_string().contains("symlinked page"), "{error}");
+ assert!(matches!(error, WikiError::Confinement { .. }), "{error}");
assert_eq!(
store
.reader
@@ -6713,7 +7183,7 @@ mod tests {
let err = wiki.reindex_all().await.unwrap_err();
assert!(
- err.to_string().contains("symlinked scope manifest"),
+ matches!(err, WikiError::Confinement { .. }),
"reindex must reject symlinked manifests, got {err:#}"
);
}
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 2218ad9f..bf32e0e4 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -38,6 +38,7 @@ boundary not yet built.
| 5a | Pages shared: `author_id` is never a read filter (invariant #16) | `ai-memory-store/src/reader.rs` `search_pages`/`page_body_by_ids` — `author_id` is an attribution JOIN only, never a WHERE term | `multi_session.rs` — a page with a **non-null** `author_id` (operator A) is readable by operator B in the same project | STRONG |
| 5b | Page supersession (loser stays reachable) | `ai-memory-store/src/ops.rs` `upsert_page_in_tx` — demote `is_latest=0` (never delete) + `supersedes` chain | `multi_session.rs` `concurrent_writes_to_one_path_supersede_rather_than_destroy`; `retrieval_superseded.rs` | STRONG |
| 5c | Watcher reindex and Wiki writes share per-page serialization (invariant #16) | `ai-memory-wiki/src/wiki.rs` `reindex_page` takes `mutation_lock.read` before `reindex_page_locked` takes `lock_page`, covering disk read through the single-writer upsert; callers already holding the exclusive global guard do not reacquire it. `write_page` uses the same page mutex and `apply_batch` retains sorted, deduplicated locks; embedding runs after both guards are released | `wiki.rs` `reindex_page_lock_waits_before_reading_and_allows_another_path` (transient snapshot refused while locked, another path progresses, release indexes the committed bytes without rewriting disk), `reindex_page_lock_serializes_write_through_the_upsert` and `reindex_page_lock_and_reversed_duplicate_batches_do_not_deadlock` (real concurrent operations, final disk/SQL winner and supersession ancestry preserved); all three fail with the reindex page guard removed. `reindex_page_lock_releases_both_guards_before_embedding` checks both body and abstract embedding; `decay_cleanup_reindex_does_not_embed_under_the_exclusive_lock` covers the exclusive caller | STRONG for a shared Wiki handle and its clones. External editors and independently constructed Wiki handles do not participate in these locks |
+| 5d | Wiki project-tree filesystem confinement | `ai-memory-wiki/src/confinement.rs` checks the wiki root, workspace/project roots, every existing ancestor, the final component, and the in-root ordinary `.git` directory with link-aware metadata; repository workdir/gitdir/commondir are containment-checked after opening, and write parents are created one component at a time and rechecked. `Wiki` checks before admission and again under mutation/page locks, while `GitAdapter` rechecks immediately before writes, appends, renames, and removals. Direct reindex, checkpoint restore, manifests, auto-improvement artifacts, ledger append, startup repair, purge/session moves, rollback, migrations, and git tree staging use the same boundary. Confinement is a distinct `WikiError` and therefore cannot trigger missing-file DB fallback | `wiki.rs` `page_reads_refuse_leaf_and_ancestor_symlinks_without_fallback_classification`, `ai-memory-mcp` `admin_read_page.rs` `read_page_does_not_db_fallback_through_a_symlink`, `page_mutations_refuse_ancestor_symlink_and_leave_outside_and_store_unchanged`, `confinement_refusal_happens_before_blocking_and_observer_admission`, `restore_and_reindex_refuse_ancestor_symlink_without_touching_canary_or_db`; `git.rs` `git_metadata_link_is_refused_without_touching_external_repository`, `gitfile_redirect_outside_is_refused_without_touching_target`, `git_metadata_redirect_files_are_refused_before_repository_open`, `configured_worktree_outside_the_wiki_root_is_refused`, `linked_git_metadata_never_reaches_commit_fallback`, `gitfile_metadata_never_reaches_commit_fallback`, `out_of_root_worktree_never_reaches_commit_fallback`, `fallback_preflight_refuses_invalid_git_metadata`, `windows_commit_fallback_accepts_established_eligible_errors`, `eligible_windows_open_error_dispatches_the_fallback_after_validation`, `windows_init_error_dispatches_fallback_after_root_preflight`, `invalid_root_never_reaches_init_fallback`, `checkpoint_and_revision_reads_refuse_a_replaced_git_directory`, and ordinary-repository/API controls `init_is_idempotent_and_creates_dotgit`; `linked_wiki_root_is_refused_during_construction`, `linked_or_dangling_scope_roots_are_refused_but_real_roots_work`, existing `decay_cleanup_refuses_to_reindex_a_symlinked_recreation` and `reindex_rejects_symlinked_scope_manifest`; `ai-memory-mcp` `admin_move.rs` `true_move_refuses_an_invalid_destination_namespace_without_db_changes` and `delete_workspace_refuses_invalid_namespace_before_db_or_notification`; `admin_backup.rs` `backup_refuses_redirected_git_metadata_before_returning_an_archive`, `backup_refuses_wiki_leaf_links_before_returning_an_archive`, `backup_refuses_linked_wiki_directories_before_returning_an_archive`, and ordinary archive controls; `watcher.rs` `direct_file_event_skips_symlink`, `walk_markdown_skips_linked_directories_and_their_ledgers`, and `shared_link_like_helper_accepts_regular_files_and_directories` (Windows directory-link coverage exercises reparse metadata when privilege is available); `backup.rs` `a_pre_migration_backup_refuses_a_linked_wiki_tree_without_an_archive`; `confinement.rs` metadata-helper controls run on every platform | STRONG for imported/static links and same-process mutations. Component checks do not claim descriptor-relative protection against a concurrently malicious same-user process; Windows reparse behavior requires the `windows` PR label/full CI |
| 6 | Active-project pointer (PerActor, no clobber) | `ai-memory-core/src/active_project.rs` `set_for`/`lookup_for` (fail-closed on `Mismatch`) | `active_project.rs` `parallel_harnesses_of_one_user_keep_separate_pointers`, `two_operators_never_read_each_others_pointer`, `a_session_mismatch_fails_closed_once_anything_has_been_keyed` | STRONG |
| 6b | Native `_meta` routing coordinate is routing-only (never grants identity) | `ai-memory-mcp/src/server.rs` `attach_native_session` reads only `_meta["ai.opencode/sessionID"]` into `ActorKey.session_id` (trimmed, non-empty-string-validated); `user` still comes from the authenticated `ActorContext`, so a forged `_meta` cannot cross a user/scope boundary — it only selects a session slot behind the existing `active_project` guard | `server.rs` `native_session_metadata_is_routing_only_and_preserves_precedence`, `native_session_metadata_validates_strings_without_granting_identity`; `autoscope_multiuser.rs` `native_metadata_routes_concurrent_reads_and_writes_to_hook_workspaces` (#864) | STRONG |
| 6c | Per-user slot namespaces stay per operator (`[slots] per_user`) | `ai-memory-mcp/src/server.rs` `place_slot_mutation`, shared by `place_slot_write` (`memory_write_page`) and `place_slot_delete` (`memory_delete_page`): a non-admin's generic `_slots/<name>.md` is redirected to their own `_slots/u-<operator>/` namespace, a path inside another operator's namespace is refused, admins bypass, and nothing changes with the flag off (#1083) | `slot_identity.rs` `oidc_operator_cannot_delete_another_operators_personal_slot`, `oidc_operator_deleting_shared_slot_path_deletes_their_personal_slot` (shared slot survives), legitimate controls `oidc_operator_can_delete_their_own_personal_slot_explicitly`, `admin_can_delete_shared_and_personal_slots` | STRONG |