Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
fix(cli): make following user-owned symlinks an opt-in per call site
TheStranjer8622d6a0ed49
diff --git a/src/cli/cli.c b/src/cli/cli.cindex 7badf1724..5f8cf82fe 100644--- a/src/cli/cli.c+++ b/src/cli/cli.c@@ -643,7 +643,7 @@ static bool cli_activation_production_context_init(cli_activation_production_concbm_canonical_path(requested_cache, context->canonical_cache,sizeof(context->canonical_cache));if (!cache_ready && requested_cache && requested_cache[0] &&- cbm_mkdir_p(requested_cache, 0700)) {+ cbm_mkdir_p_ex(requested_cache, 0700, CBM_MKDIR_FOLLOW_OWNED)) {cache_ready = cbm_canonical_path(requested_cache, context->canonical_cache,sizeof(context->canonical_cache));}@@ -1425,8 +1425,12 @@ const char *cbm_get_codex_instructions(void) {/* ── Recursive mkdir (via compat_fs) ──────────────────────────── */+/* Every caller here creates a directory under the user's own configuration+ * (skills, instruction files, the cache), so a symlink the user owns on the+ * way there is the user's own arrangement and is followed. Repository-derived+ * paths never come through this wrapper. */static int mkdirp(const char *path, int mode) {- return (int)cbm_mkdir_p(path, mode) ? 0 : CLI_ERR;+ return (int)cbm_mkdir_p_ex(path, mode, CBM_MKDIR_FOLLOW_OWNED) ? 0 : CLI_ERR;}/* Legacy migration may remove an empty directory, but never recursively@@ -5336,7 +5340,7 @@ bool cbm_install_hook_gate_script(const char *home, const char *binary_path) {if (hooks_written <= 0 || (size_t)hooks_written >= sizeof(hooks_dir)) {return false;}- if (!cbm_mkdir_p(hooks_dir, CLI_OCTAL_PERM)) {+ if (!cbm_mkdir_p_ex(hooks_dir, CLI_OCTAL_PERM, CBM_MKDIR_FOLLOW_OWNED)) {return false;}@@ -5389,7 +5393,7 @@ static bool cbm_install_session_reminder_script(const char *home, const char *biif (hooks_written <= 0 || (size_t)hooks_written >= sizeof(hooks_dir)) {return false;}- if (!cbm_mkdir_p(hooks_dir, CLI_OCTAL_PERM)) {+ if (!cbm_mkdir_p_ex(hooks_dir, CLI_OCTAL_PERM, CBM_MKDIR_FOLLOW_OWNED)) {return false;}@@ -5583,7 +5587,7 @@ static bool cbm_install_subagent_reminder_script(const char *home, const char *bif (hooks_written <= 0 || (size_t)hooks_written >= sizeof(hooks_dir)) {return false;}- if (!cbm_mkdir_p(hooks_dir, CLI_OCTAL_PERM)) {+ if (!cbm_mkdir_p_ex(hooks_dir, CLI_OCTAL_PERM, CBM_MKDIR_FOLLOW_OWNED)) {return false;}@@ -7650,7 +7654,9 @@ static bool prepare_config_parent(const char *path) {return slash != NULL;}*slash = '\0';- return cbm_mkdir_p(parent, CLI_OCTAL_PERM);+ /* Agent roots live under HOME / XDG / the client's own config-dir+ * variable, so a symlink the user owns on the way is followed (#1722). */+ return cbm_mkdir_p_ex(parent, CLI_OCTAL_PERM, CBM_MKDIR_FOLLOW_OWNED);}typedef struct {@@ -8189,7 +8195,7 @@ static void install_copilot_durable_context(const char *home, const char *binaryreturn;}bool hook_ok = true;- if (!dry_run && (!cbm_mkdir_p(hooks_dir, CLI_OCTAL_PERM) ||+ if (!dry_run && (!cbm_mkdir_p_ex(hooks_dir, CLI_OCTAL_PERM, CBM_MKDIR_FOLLOW_OWNED) ||cbm_upsert_copilot_hooks(binary_path, hook_path) != CLI_OK)) {hook_ok = false;record_agent_config_error(false, "Copilot", "lifecycle_hook_install", hook_path);@@ -8935,7 +8941,7 @@ static void install_cli_agent_configs(const cbm_detected_agents_t *agents, constif (!dry_run && !g_install_plan) {char cfg_dir[CLI_BUF_1K];snprintf(cfg_dir, sizeof(cfg_dir), "%s/.gemini/config", home);- cbm_mkdir_p(cfg_dir, CLI_OCTAL_PERM);+ cbm_mkdir_p_ex(cfg_dir, CLI_OCTAL_PERM, CBM_MKDIR_FOLLOW_OWNED);}install_generic_agent_config("Antigravity", binary_path, cp, ip, dry_run,cbm_upsert_antigravity_mcp);@@ -9244,7 +9250,7 @@ static void install_editor_agent_configs(const cbm_detected_agents_t *agents, cosnprintf(skills_dir, sizeof(skills_dir), "%s/.junie/skills", home);snprintf(agent_path, sizeof(agent_path), "%s/.junie/agents/codebase-memory.md", home);if (!dry_run && !g_install_plan) {- cbm_mkdir_p(sd, CLI_OCTAL_PERM);+ cbm_mkdir_p_ex(sd, CLI_OCTAL_PERM, CBM_MKDIR_FOLLOW_OWNED);}bool direct_profiles_ready = install_generic_agent_config("Junie", binary_path, cp, NULL,dry_run, cbm_upsert_junie_mcp);diff --git a/src/cli/config_json_like.c b/src/cli/config_json_like.cindex dc16c3c5c..21ed11309 100644--- a/src/cli/config_json_like.c+++ b/src/cli/config_json_like.c@@ -1498,12 +1498,17 @@ static char *jl_parent_directory(const char *path) {return cbm_strndup(path, (size_t)(separator - path));}+/* Every document written through this editor is a client's own configuration+ * file under HOME / XDG / the client's config-dir variable, so a symlink the+ * user owns on the way to it is followed. Repository-derived paths are never+ * edited here. */static int jl_ensure_parent(const char *path) {char *parent = jl_parent_directory(path);if (!parent) {return -1;}- int result = strcmp(parent, ".") == 0 || cbm_mkdir_p(parent, 0755) ? 0 : -1;+ int result =+ strcmp(parent, ".") == 0 || cbm_mkdir_p_ex(parent, 0755, CBM_MKDIR_FOLLOW_OWNED) ? 0 : -1;free(parent);return result;}diff --git a/src/cli/hook_augment.c b/src/cli/hook_augment.cindex ccc94bfa2..eb0ad8000 100644--- a/src/cli/hook_augment.c+++ b/src/cli/hook_augment.c@@ -113,7 +113,7 @@ static void ha_open_crumb_log(int deadline_ms) {}char dir[CBM_SZ_1K];snprintf(dir, sizeof(dir), "%s/.cache/codebase-memory-mcp/logs", home);- cbm_mkdir_p(dir, 0755);+ cbm_mkdir_p_ex(dir, 0755, CBM_MKDIR_FOLLOW_OWNED);snprintf(path, sizeof(path), "%s/hook-augment-timeouts.log", dir);}g_ha_crumb_fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0644);diff --git a/src/daemon/application.c b/src/daemon/application.cindex 69ff52ec7..9ab6b1ddc 100644--- a/src/daemon/application.c+++ b/src/daemon/application.c@@ -639,7 +639,8 @@ static bool application_unique_recovery_file(char out[APPLICATION_PATH_CAP], conint written;if (application_cache_dir(cache)) {written = snprintf(directory, sizeof(directory), "%s/logs", cache);- if (written <= 0 || written >= (int)sizeof(directory) || !cbm_mkdir_p(directory, 0700)) {+ if (written <= 0 || written >= (int)sizeof(directory) ||+ !cbm_mkdir_p_ex(directory, 0700, CBM_MKDIR_FOLLOW_OWNED)) {return false;}} else {diff --git a/src/foundation/compat_fs.c b/src/foundation/compat_fs.cindex 77fc72ff4..c28f2a542 100644--- a/src/foundation/compat_fs.c+++ b/src/foundation/compat_fs.c@@ -558,6 +558,13 @@ bool cbm_mkdir_p(const char *path, int mode) {return ok;}+bool cbm_mkdir_p_ex(const char *path, int mode, unsigned int policy) {+ /* The Windows walk has its own reparse-point policy (see+ * cbm_windows_mkdir_component); the POSIX symlink policy does not apply. */+ (void)policy;+ return cbm_mkdir_p(path, mode);+}+int cbm_unlink(const char *path) {wchar_t *wpath = cbm_path_to_wide(path);if (!wpath) {@@ -839,18 +846,42 @@ FILE *cbm_fopen(const char *path, const char *mode) {/* Symlink policy for the parent-chain walk. Every component is opened with* O_NOFOLLOW; a symlink is followed only when its OWNER is trusted, never by- * default. Trusted owners are root (distro /home indirection, macOS /tmp:- * only root can create those, so they are outside the attacker model) and the- * invoking account itself: a link the caller owns is the caller's own- * arrangement, not something planted on them. That second case is how dotfile- * managers and configs kept on another volume look (~/.config/opencode ->- * /mnt/...), and refusing it made every agent-config write under such a root- * fail with an opaque agent_config error. It is the same rule the Linux- * kernel's fs.protected_symlinks applies, and the ancestor policy the- * activation transaction already uses. A link owned by any OTHER account- * (planted in a group- or world-writable ancestor) stays refused, and a- * privileged install (euid 0) still refuses user-owned links. */-static int cbm_open_directory_component(int parent, const char *component, int flags) {+ * default. Root-owned links are trusted everywhere (distro /home indirection,+ * macOS /tmp: only root can create those, so they are outside the attacker+ * model). A link owned by the invoking account is trusted only where the+ * caller opted in with CBM_MKDIR_FOLLOW_OWNED: for a path rooted in the user's+ * own configuration such a link is the user's own arrangement (a dotfile+ * manager, ~/.config/opencode -> /mnt/...), and refusing it made every+ * agent-config write under such a root fail with an opaque agent_config+ * error. It is not trusted for a path derived from a repository, where git+ * creates symlinks owned by whoever cloned, so "user-owned" says nothing about+ * "user-intended". The rule is the one the Linux kernel's+ * fs.protected_symlinks applies, and the ancestor policy the activation+ * transaction already uses. A link owned by any OTHER account (planted in a+ * group- or world-writable ancestor) stays refused, and a privileged walk+ * (euid 0) still refuses user-owned links.+ *+ * Inspecting the link and following it are two steps, so what the follow+ * lands on is checked as well: the opened target must be a directory owned by+ * root or the invoking user, and not world-writable unless sticky. An account+ * that can swap the link between the two steps (it needs write access to the+ * parent, which the walk holds open) therefore cannot steer the walk into a+ * directory it controls or into one where anyone can pre-plant entries. This+ * is the before/after idiom the activation transaction uses around its own+ * opens. */+static bool cbm_walk_link_trusted(uid_t owner, bool follow_owned) {+ return owner == 0U || (follow_owned && owner == geteuid());+}++static bool cbm_walk_target_trusted(const struct stat *target) {+ bool trusted_owner = target->st_uid == 0U || target->st_uid == geteuid();+ bool world_writable = (target->st_mode & S_IWOTH) != 0;+ bool sticky = (target->st_mode & S_ISVTX) != 0;+ return S_ISDIR(target->st_mode) && trusted_owner && (!world_writable || sticky);+}++static int cbm_open_directory_component(int parent, const char *component, int flags,+ bool follow_owned) {int descriptor = openat(parent, component, flags);#if defined(O_NOFOLLOW) && defined(AT_SYMLINK_NOFOLLOW)if (descriptor < 0) {@@ -859,20 +890,35 @@ static int cbm_open_directory_component(int parent, const char *component, int fint open_errno = errno;struct stat state;if (fstatat(parent, component, &state, AT_SYMLINK_NOFOLLOW) == 0 &&- S_ISLNK(state.st_mode) && (state.st_uid == 0U || state.st_uid == geteuid())) {- descriptor = openat(parent, component, flags & ~O_NOFOLLOW);- } else {+ S_ISLNK(state.st_mode) && cbm_walk_link_trusted(state.st_uid, follow_owned)) {+ int followed = openat(parent, component, flags & ~O_NOFOLLOW);+ struct stat target;+ if (followed >= 0 && fstat(followed, &target) == 0 &&+ cbm_walk_target_trusted(&target)) {+ descriptor = followed;+ } else if (followed >= 0) {+ (void)close(followed);+ }+ }+ if (descriptor < 0) {errno = open_errno;}}+#else+ (void)follow_owned;#endifreturn descriptor;}bool cbm_mkdir_p(const char *path, int mode) {+ return cbm_mkdir_p_ex(path, mode, 0U);+}++bool cbm_mkdir_p_ex(const char *path, int mode, unsigned int policy) {if (!path || path[0] == '\0') {return false;}+ bool follow_owned = (policy & CBM_MKDIR_FOLLOW_OWNED) != 0U;char *tmp = strdup(path);if (!tmp) {return false;@@ -905,12 +951,12 @@ bool cbm_mkdir_p(const char *path, int mode) {*separator = '\0';}if (cursor[0] != '\0' && strcmp(cursor, ".") != 0) {- int next = cbm_open_directory_component(directory, cursor, flags);+ int next = cbm_open_directory_component(directory, cursor, flags, follow_owned);if (next < 0 && errno == ENOENT) {if (mkdirat(directory, cursor, (mode_t)mode) != 0 && errno != EEXIST) {ok = false;} else {- next = cbm_open_directory_component(directory, cursor, flags);+ next = cbm_open_directory_component(directory, cursor, flags, follow_owned);}}if (ok && next < 0) {diff --git a/src/foundation/compat_fs.h b/src/foundation/compat_fs.hindex 240ebceae..a3ff7c352 100644--- a/src/foundation/compat_fs.h+++ b/src/foundation/compat_fs.h@@ -56,9 +56,25 @@ int cbm_pclose(FILE *f);/* ── File operations ──────────────────────────────────────────── */-/* Create directory (and parents). mode is ignored on Windows. Returns true on success. */+/* Create directory (and parents). mode is ignored on Windows. Returns true on success.+ * A symlink component is followed only when root owns it (cbm_mkdir_p_ex). */bool cbm_mkdir_p(const char *path, int mode);+/* cbm_mkdir_p with a per-call-site symlink policy.+ *+ * CBM_MKDIR_FOLLOW_OWNED also follows a symlink component owned by the invoking+ * user. Opt in ONLY for paths rooted in the user's own configuration -- HOME,+ * XDG, CBM_CACHE_DIR: agent roots, config, cache and log directories -- where a+ * link the user owns is the user's own arrangement (a dotfile manager, a config+ * tree kept on another volume). Never for a path derived from a repository:+ * git creates symlinks owned by whoever cloned, so a checked-in+ * `.codebase-memory -> ~/.ssh` is user-owned without being user-intended.+ * Whatever a followed link lands on must itself be a directory owned by root+ * or the invoking user and not world-writable unless sticky. Windows ignores+ * the policy. */+enum { CBM_MKDIR_FOLLOW_OWNED = 1U << 0 };+bool cbm_mkdir_p_ex(const char *path, int mode, unsigned int policy);+/* Delete a file. Returns 0 on success. */int cbm_unlink(const char *path);/* Remove <db_path>-wal/-shm/-journal. MUST be called by any path installing a freshdiff --git a/src/main.c b/src/main.cindex 67eced2f2..dc41d704b 100644--- a/src/main.c+++ b/src/main.c@@ -1231,7 +1231,7 @@ static main_build_identity_status_t main_build_identity(cbm_daemon_build_identit* only the resulting canonical path, so retargeting the original alias* cannot move storage after cohort admission. */bool cache_ready = cbm_canonical_path(cache, canonical_cache, sizeof(canonical_cache));- if (!cache_ready && cbm_mkdir_p(cache, 0700)) {+ if (!cache_ready && cbm_mkdir_p_ex(cache, 0700, CBM_MKDIR_FOLLOW_OWNED)) {cache_ready = cbm_canonical_path(cache, canonical_cache, sizeof(canonical_cache));}if (!cache_ready || !cbm_is_dir(canonical_cache)) {diff --git a/src/mcp/index_supervisor.c b/src/mcp/index_supervisor.cindex eed78f418..f565a8bea 100644--- a/src/mcp/index_supervisor.c+++ b/src/mcp/index_supervisor.c@@ -564,7 +564,8 @@ static bool worker_unique_file(char *out, size_t out_size, const char *kind) {if (have_cache) {char directory[INDEX_WORKER_PATH_CAP];written = snprintf(directory, sizeof(directory), "%s/logs", cache_copy);- if (written <= 0 || written >= (int)sizeof(directory) || !cbm_mkdir_p(directory, 0700)) {+ if (written <= 0 || written >= (int)sizeof(directory) ||+ !cbm_mkdir_p_ex(directory, 0700, CBM_MKDIR_FOLLOW_OWNED)) {return false;}written = snprintf(out, out_size, "%s/.worker-%s-XXXXXX", directory, kind);diff --git a/src/mcp/mcp.c b/src/mcp/mcp.cindex 50adb6d4e..245c9fda3 100644--- a/src/mcp/mcp.c+++ b/src/mcp/mcp.c@@ -8085,7 +8085,7 @@ static bool write_skip_logfile(const char *project, const cbm_file_error_t *errs}char logdir[CBM_SZ_1K];snprintf(logdir, sizeof(logdir), "%s/logs", cdir);- cbm_mkdir_p(logdir, 0755);+ cbm_mkdir_p_ex(logdir, 0755, CBM_MKDIR_FOLLOW_OWNED);snprintf(path, sizeof(path), "%s/%s-%lld.log", logdir, project ? project : "index",(long long)time(NULL));}@@ -8303,7 +8303,7 @@ static void supervisor_tmp_path(char *out, size_t out_sz, const char *suffix) {if (cdir && cdir[0]) {char logdir[CBM_SZ_1K];snprintf(logdir, sizeof(logdir), "%s/logs", cdir);- cbm_mkdir_p(logdir, 0755);+ cbm_mkdir_p_ex(logdir, 0755, CBM_MKDIR_FOLLOW_OWNED);snprintf(out, out_sz, "%s/.supervisor-%d%s", logdir, (int)getpid(), suffix);} else {snprintf(out, out_sz, ".supervisor-%d%s", (int)getpid(), suffix);@@ -11258,7 +11258,8 @@ static bool mcp_command_output_path(char out[CBM_SZ_2K]) {int written;if (cache && cache[0]) {written = snprintf(directory, sizeof(directory), "%s/logs", cache);- if (written <= 0 || written >= (int)sizeof(directory) || !cbm_mkdir_p(directory, 0700)) {+ if (written <= 0 || written >= (int)sizeof(directory) ||+ !cbm_mkdir_p_ex(directory, 0700, CBM_MKDIR_FOLLOW_OWNED)) {return false;}} else {diff --git a/src/pipeline/artifact.c b/src/pipeline/artifact.cindex df73708b9..2dd368c28 100644--- a/src/pipeline/artifact.c+++ b/src/pipeline/artifact.c@@ -967,6 +967,10 @@ int cbm_artifact_export(const char *db_path, const char *repo_path, const char *if (dir_len < 0 || (size_t)dir_len >= sizeof(art_dir)) {return artifact_export_fail("prepare_artifact_dir", repo_path, "path_too_long", 0);}+ /* Deliberately the STRICT walk: art_dir is inside the checkout being+ * indexed, where a symlink is a checked-in file owned by whoever cloned.+ * A repository shipping `.codebase-memory -> ~/.ssh` must not redirect+ * this write, so user-owned links are not followed here. */errno = 0;if (!cbm_mkdir_p(art_dir, ART_DIR_PERMS)) {return artifact_export_fail("prepare_artifact_dir", art_dir, "mkdir_or_not_directory",@@ -1141,7 +1145,7 @@ int cbm_artifact_import(const char *repo_path, const char *cache_db_path) {char *last_slash = strrchr(cache_dir, '/');if (last_slash) {*last_slash = '\0';- cbm_mkdir_p(cache_dir, ART_DIR_PERMS);+ cbm_mkdir_p_ex(cache_dir, ART_DIR_PERMS, CBM_MKDIR_FOLLOW_OWNED);}artifact_file_error_t ioerr;diff --git a/src/pipeline/pipeline.c b/src/pipeline/pipeline.cindex 938437549..ec60159ed 100644--- a/src/pipeline/pipeline.c+++ b/src/pipeline/pipeline.c@@ -1946,7 +1946,7 @@ static int dump_and_persist_hashes(cbm_pipeline_t *p, const cbm_file_hash_t *bas#endifif (last_slash) {*last_slash = '\0';- cbm_mkdir_p(db_dir, CBM_DIR_PERMS);+ cbm_mkdir_p_ex(db_dir, CBM_DIR_PERMS, CBM_MKDIR_FOLLOW_OWNED);}cbm_file_hash_t *manifest = NULL;@@ -2400,7 +2400,7 @@ static bool ensure_db_parent(const char *path) {return true;}*slash = '\0';- bool ok = dir[0] == '\0' || cbm_mkdir_p(dir, CBM_DIR_PERMS);+ bool ok = dir[0] == '\0' || cbm_mkdir_p_ex(dir, CBM_DIR_PERMS, CBM_MKDIR_FOLLOW_OWNED);free(dir);return ok;}diff --git a/src/ui/config.c b/src/ui/config.cindex 0694f7e77..3a8c7afce 100644--- a/src/ui/config.c+++ b/src/ui/config.c@@ -391,7 +391,7 @@ bool cbm_ui_config_save(const cbm_ui_config_t *cfg) {char dir[CBM_SZ_1K];bool directory_ready = config_parent_directory(path, dir, sizeof(dir));if (directory_ready && !cbm_is_dir(dir)) {- directory_ready = cbm_mkdir_p(dir, 0750) || cbm_is_dir(dir);+ directory_ready = cbm_mkdir_p_ex(dir, 0750, CBM_MKDIR_FOLLOW_OWNED) || cbm_is_dir(dir);}if (!directory_ready) {cbm_log_error("ui.config.write_fail", "path", path, "reason", "create_directory");diff --git a/tests/test_artifact.c b/tests/test_artifact.cindex 7657b3faa..a7d96cdd9 100644--- a/tests/test_artifact.c+++ b/tests/test_artifact.c@@ -8,9 +8,13 @@#include "foundation/compat.h"#include "foundation/compat_fs.h"#include "foundation/log.h"+#include "foundation/platform.h"#include <sys/stat.h>#include <stdio.h>+#ifndef _WIN32+#include <unistd.h> /* symlink for the checked-in artifact-dir link */+#endif#include <stdarg.h>#include <string.h>@@ -392,6 +396,67 @@ TEST(pipeline_persistence_export_failure_returns_error) {PASS();}+/* A checkout can ship `.codebase-memory` as a symlink. Git creates it owned by+ * whoever cloned, so it is user-owned without being user-intended, and the+ * export uses the plain walk that does not follow user-owned links: nothing+ * may land behind the link, and the failure names the stage. With the link+ * gone the same export succeeds, so the refusal was the link and nothing+ * else. */+TEST(artifact_export_refuses_symlinked_artifact_dir) {+#ifdef _WIN32+ SKIP_PLATFORM("POSIX symlink contract");+#else+ setup_artifact_test();+ create_test_db(g_db);++ char outside[1024];+ char artifact_link[1024];+ snprintf(outside, sizeof(outside), "%s/outside", g_tmpdir);+ snprintf(artifact_link, sizeof(artifact_link), "%s/%s", g_repo, CBM_ARTIFACT_DIR);+ ASSERT_TRUE(cbm_mkdir_p(outside, 0755));+ ASSERT_EQ(symlink(outside, artifact_link), 0);+ /* Git creates the link owned by whoever cloned. A root run must model+ * that account as non-root: root-owned links are trusted infrastructure+ * for every walk, which is the pre-existing contract. */+ if (geteuid() == 0) {+ enum { CLONING_UID = 65533 };+ ASSERT_EQ(lchown(artifact_link, CLONING_UID, CLONING_UID), 0);+ }++ int rc = cbm_artifact_export(g_db, g_repo, "test-proj", CBM_ARTIFACT_FAST);+ ASSERT_NEQ(rc, 0);+ const char *err = cbm_artifact_export_last_error();+ ASSERT_NOT_NULL(err);+ ASSERT_NOT_NULL(strstr(err, "prepare_artifact_dir"));++ /* Nothing landed behind the link: not the artifact, not its metadata,+ * not the .gitattributes the export writes first, nothing at all. */+ char leaked[1024];+ snprintf(leaked, sizeof(leaked), "%s/%s", outside, CBM_ARTIFACT_FILENAME);+ ASSERT_FALSE(cbm_file_exists(leaked));+ snprintf(leaked, sizeof(leaked), "%s/%s", outside, CBM_ARTIFACT_META);+ ASSERT_FALSE(cbm_file_exists(leaked));+ snprintf(leaked, sizeof(leaked), "%s/.gitattributes", outside);+ ASSERT_FALSE(cbm_file_exists(leaked));+ cbm_dir_t *listing = cbm_opendir(outside);+ ASSERT_NOT_NULL(listing);+ int entries = 0;+ for (cbm_dirent_t *entry = cbm_readdir(listing); entry; entry = cbm_readdir(listing)) {+ if (strcmp(entry->name, ".") != 0 && strcmp(entry->name, "..") != 0) {+ entries++;+ }+ }+ cbm_closedir(listing);+ ASSERT_EQ(entries, 0);++ ASSERT_EQ(cbm_unlink(artifact_link), 0);+ ASSERT_EQ(cbm_artifact_export(g_db, g_repo, "test-proj", CBM_ARTIFACT_FAST), 0);++ cleanup_dir(g_tmpdir);+ PASS();+#endif+}+TEST(artifact_null_safety) {ASSERT_NEQ(cbm_artifact_export(NULL, "/tmp", "p", 0), 0);ASSERT_NEQ(cbm_artifact_export("/tmp/x.db", NULL, "p", 0), 0);@@ -1040,6 +1105,7 @@ SUITE(artifact) {RUN_TEST(artifact_export_rename_failure_logs_specific_error);RUN_TEST(pipeline_persistence_export_failure_returns_error);RUN_TEST(artifact_import_rejects_size_mismatch);+ RUN_TEST(artifact_export_refuses_symlinked_artifact_dir);RUN_TEST(artifact_null_safety);RUN_TEST(artifact_export_marks_clean_basis);RUN_TEST(artifact_reconcile_restamps_unchanged);diff --git a/tests/test_cli.c b/tests/test_cli.cindex eff50f770..d4d243e74 100644--- a/tests/test_cli.c+++ b/tests/test_cli.c@@ -9840,9 +9840,10 @@ TEST(cli_mcp_installers_preserve_foreign_same_name_entries) {* /home indirection, macOS /tmp): only root can create them, so they are* outside the attacker model. A link owned by ANY OTHER account is the* planted-link case the O_NOFOLLOW parent-chain walk exists for, and stays- * refused. Only root can create a foreign-owned link, so the refusal leg is- * exercised when the suite runs as root (containers); the follow leg runs- * everywhere. */+ * refused, and so is a user-owned link when the installer itself runs as+ * root. Only root can create a link owned by someone else, so both refusal+ * legs are exercised when the suite runs as root (containers); the follow leg+ * runs everywhere. */TEST(cli_installer_follows_symlinked_agent_roots_only_for_trusted_owners) {#ifdef _WIN32SKIP_PLATFORM("POSIX symlink parent-chain contract");@@ -9850,10 +9851,13 @@ TEST(cli_installer_follows_symlinked_agent_roots_only_for_trusted_owners) {char tmpdir[256];char own_target[256];char foreign_target[256];+ char user_target[256];snprintf(tmpdir, sizeof(tmpdir), "/tmp/cli-linked-roots-XXXXXX");snprintf(own_target, sizeof(own_target), "/tmp/cli-linked-own-XXXXXX");snprintf(foreign_target, sizeof(foreign_target), "/tmp/cli-linked-foreign-XXXXXX");- if (!cbm_mkdtemp(tmpdir) || !cbm_mkdtemp(own_target) || !cbm_mkdtemp(foreign_target))+ snprintf(user_target, sizeof(user_target), "/tmp/cli-linked-user-XXXXXX");+ if (!cbm_mkdtemp(tmpdir) || !cbm_mkdtemp(own_target) || !cbm_mkdtemp(foreign_target) ||+ !cbm_mkdtemp(user_target))FAIL("cbm_mkdtemp failed");char qoder_link[512];snprintf(qoder_link, sizeof(qoder_link), "%s/.qoder", tmpdir);@@ -9901,18 +9905,49 @@ TEST(cli_installer_follows_symlinked_agent_roots_only_for_trusted_owners) {}}+ /* Refusal leg (root only): a privileged install into another account's+ * home. Home, link and target are all owned by that account and the walk+ * runs as euid 0, which trusts only root-owned links, so the user's link+ * is refused and nothing lands in the target. This pins the claim that+ * following user-owned links never extends to a root-run install. */+ bool user_refused = true;+ bool user_setup_ok = true;+ if (geteuid() == 0) {+ enum { LINKED_HOME_UID = 65533 };+ user_setup_ok = cbm_unlink(qoder_link) == 0 && symlink(user_target, qoder_link) == 0 &&+ lchown(qoder_link, LINKED_HOME_UID, LINKED_HOME_UID) == 0 &&+ chown(user_target, LINKED_HOME_UID, LINKED_HOME_UID) == 0 &&+ chown(tmpdir, LINKED_HOME_UID, LINKED_HOME_UID) == 0;+ if (user_setup_ok) {+ int user_rc =+ cbm_install_agent_configs(tmpdir, "/opt/codebase-memory-mcp", false, false);+ char user_settings[512];+ char user_skill[512];+ snprintf(user_settings, sizeof(user_settings), "%s/settings.json", user_target);+ snprintf(user_skill, sizeof(user_skill), "%s/skills/codebase-memory/SKILL.md",+ user_target);+ user_refused =+ user_rc != 0 && stat(user_settings, &state) != 0 && stat(user_skill, &state) != 0;+ }+ }+restore_test_env("HOME", saved_home);restore_test_env("PATH", saved_path);cbm_unlink(qoder_link);test_rmdir_r(tmpdir);test_rmdir_r(own_target);test_rmdir_r(foreign_target);+ test_rmdir_r(user_target);if (!foreign_setup_ok)FAIL("could not plant a foreign-owned link while running as root");+ if (!user_setup_ok)+ FAIL("could not plant a user-owned link and home while running as root");if (own_rc != 0 || !followed)FAIL("installer must follow an agent root symlinked by the invoking account");if (!foreign_refused)FAIL("installer must not follow an agent root symlinked by another account");+ if (!user_refused)+ FAIL("a root-run installer must not follow an agent root symlinked by the home's owner");PASS();#endif}diff --git a/tests/test_platform.c b/tests/test_platform.cindex f8f929e9b..849ad083b 100644--- a/tests/test_platform.c+++ b/tests/test_platform.c@@ -12,6 +12,9 @@#include <stdatomic.h>#include <stdlib.h>#include <unistd.h>+#ifndef _WIN32+#include <sys/stat.h> /* chmod for the symlink-policy mode legs */+#endif#ifdef __linux__/* Linux-only cgroup tests need stdio for FILE*, stdlib for mkdtemp,@@ -78,12 +81,15 @@ TEST(platform_file_apis_survive_max_path_overflow) {}/* A directory reached through a symlink the invoking account owns is that- * account's own arrangement (a dotfile manager, a config tree kept on another- * volume: ~/.config/opencode -> /mnt/...), not a planted link, so the- * parent-chain walk follows it and creates the missing tail INSIDE the target- * -- the trust fs.protected_symlinks applies. A dangling link of the same- * owner still fails closed: nothing is created on either side of it. */-TEST(platform_mkdir_p_follows_symlink_owned_by_caller) {+ * account's own arrangement ONLY where the caller says so. The plain walk+ * (cbm_mkdir_p) keeps refusing such a link: it is what repository-derived+ * paths use, where a user-owned link can be a checked-in file. A caller that+ * opts in with CBM_MKDIR_FOLLOW_OWNED -- paths rooted in HOME, XDG or the+ * cache, the dotfile-manager shape ~/.config/opencode -> /mnt/... -- walks+ * through it and creates the missing tail INSIDE the target. Even opted in, a+ * dangling link or a link to a regular file fails closed with nothing created+ * on either side. */+TEST(platform_mkdir_p_follows_own_symlink_only_when_opted_in) {#ifdef _WIN32SKIP_PLATFORM("POSIX symlink ownership contract");#else@@ -95,16 +101,43 @@ TEST(platform_mkdir_p_follows_symlink_owned_by_caller) {char target[CBM_SZ_1K];char link[CBM_SZ_1K];char through_link[CBM_SZ_1K];+ char child[CBM_SZ_1K];char created[CBM_SZ_1K];(void)snprintf(target, sizeof(target), "%s/target", base);(void)snprintf(link, sizeof(link), "%s/link", base);(void)snprintf(through_link, sizeof(through_link), "%s/child/grandchild", link);+ (void)snprintf(child, sizeof(child), "%s/child", target);(void)snprintf(created, sizeof(created), "%s/child/grandchild", target);ASSERT_TRUE(cbm_mkdir_p(target, 0700));ASSERT_EQ(symlink(target, link), 0);- ASSERT_TRUE(cbm_mkdir_p(through_link, 0700));- ASSERT_TRUE(cbm_is_dir(created));+ /* "Own" means owned by the invoking account. Root owns everything it+ * creates and root-owned links are trusted by BOTH walks, so under euid 0+ * the link is given to a non-root account to keep the contrast real: then+ * the plain walk refuses it, and so does the opted-in walk, because a+ * privileged walk never follows a user's link. */+ bool privileged = geteuid() == 0;+ enum { LINK_OWNER_UID = 65533 };+ if (privileged) {+ ASSERT_EQ(lchown(link, LINK_OWNER_UID, LINK_OWNER_UID), 0);+ }++ /* The plain walk refuses the user-owned link and creates nothing. */+ ASSERT_FALSE(cbm_mkdir_p(through_link, 0700));+ ASSERT_FALSE(cbm_is_dir(child));++ if (privileged) {+ ASSERT_FALSE(cbm_mkdir_p_ex(through_link, 0700, CBM_MKDIR_FOLLOW_OWNED));+ ASSERT_FALSE(cbm_is_dir(child));+ /* Root-owned again: infrastructure, followed by both walks as always. */+ ASSERT_EQ(lchown(link, 0, 0), 0);+ ASSERT_TRUE(cbm_mkdir_p(through_link, 0700));+ ASSERT_TRUE(cbm_is_dir(created));+ } else {+ /* The opted-in walk follows it into the target. */+ ASSERT_TRUE(cbm_mkdir_p_ex(through_link, 0700, CBM_MKDIR_FOLLOW_OWNED));+ ASSERT_TRUE(cbm_is_dir(created));+ }char dangling[CBM_SZ_1K];char through_dangling[CBM_SZ_1K];@@ -113,17 +146,227 @@ TEST(platform_mkdir_p_follows_symlink_owned_by_caller) {(void)snprintf(through_dangling, sizeof(through_dangling), "%s/child", dangling);(void)snprintf(dangling_target, sizeof(dangling_target), "%s/missing", base);ASSERT_EQ(symlink("missing", dangling), 0);- ASSERT_FALSE(cbm_mkdir_p(through_dangling, 0700));+ ASSERT_FALSE(cbm_mkdir_p_ex(through_dangling, 0700, CBM_MKDIR_FOLLOW_OWNED));ASSERT_FALSE(cbm_is_dir(dangling_target));+ /* An own link to a regular FILE is not a directory to walk into: refused,+ * and the file it points at is left exactly as it was. */+ char file_target[CBM_SZ_1K];+ char file_link[CBM_SZ_1K];+ char through_file_link[CBM_SZ_1K];+ (void)snprintf(file_target, sizeof(file_target), "%s/file", base);+ (void)snprintf(file_link, sizeof(file_link), "%s/file-link", base);+ (void)snprintf(through_file_link, sizeof(through_file_link), "%s/child", file_link);+ FILE *file = cbm_fopen(file_target, "wb");+ ASSERT_NOT_NULL(file);+ ASSERT_GTE(fputs("data\n", file), 0);+ ASSERT_EQ(fclose(file), 0);+ ASSERT_EQ(symlink(file_target, file_link), 0);+ ASSERT_FALSE(cbm_mkdir_p_ex(through_file_link, 0700, CBM_MKDIR_FOLLOW_OWNED));+ ASSERT_FALSE(cbm_is_dir(file_target));+ ASSERT_EQ(cbm_file_size(file_target), 5);++ ASSERT_EQ(cbm_unlink(file_link), 0);+ ASSERT_EQ(cbm_unlink(file_target), 0);ASSERT_EQ(cbm_unlink(dangling), 0);ASSERT_EQ(cbm_unlink(link), 0);ASSERT_EQ(cbm_rmdir(created), 0);- char *slash = strrchr(created, '/');+ ASSERT_EQ(cbm_rmdir(child), 0);+ ASSERT_EQ(cbm_rmdir(target), 0);+ ASSERT_EQ(cbm_rmdir(base), 0);+ PASS();+#endif+}++/* The trust an opted-in walk extends to a symlink is bounded on BOTH ends of+ * the link. What the follow lands on must be a directory owned by root or the+ * invoking user and not world-writable unless sticky; the mode legs bind on+ * every run. Two more legs need root, because a non-root process cannot give+ * a file away: a target owned by another account is refused even behind a+ * root-owned link, and a link owned by a non-root account is refused when the+ * walk itself runs as root, so a privileged install never follows a user's+ * link. Each refusal is followed by restoring the state and walking again,+ * which pins that state as the reason for the refusal. */+TEST(platform_mkdir_p_symlink_trust_is_bounded_by_owner_and_mode) {+#ifdef _WIN32+ SKIP_PLATFORM("POSIX symlink ownership contract");+#else+ char base[CBM_SZ_512];+ int written = snprintf(base, sizeof(base), "/tmp/cbm-linkowner-XXXXXX");+ ASSERT_TRUE(written > 0 && written < (int)sizeof(base));+ ASSERT_NOT_NULL(cbm_mkdtemp(base));++ char target[CBM_SZ_1K];+ char link[CBM_SZ_1K];+ (void)snprintf(target, sizeof(target), "%s/target", base);+ (void)snprintf(link, sizeof(link), "%s/link", base);+ ASSERT_TRUE(cbm_mkdir_p(target, 0700));+ ASSERT_EQ(symlink(target, link), 0);++ static const char *const children[] = {"control", "world-writable", "sticky",+ "private", "foreign-target", "target-restored",+ "user-link", "link-restored"};+ enum {+ CHILD_CONTROL,+ CHILD_WORLD_WRITABLE,+ CHILD_STICKY,+ CHILD_PRIVATE,+ CHILD_FOREIGN_TARGET,+ CHILD_TARGET_RESTORED,+ CHILD_USER_LINK,+ CHILD_LINK_RESTORED+ };+ char through_link[CBM_SZ_1K];+ char created[CBM_SZ_1K];+#define LINKOWNER_PATHS(index) \+ do { \+ (void)snprintf(through_link, sizeof(through_link), "%s/%s", link, children[index]); \+ (void)snprintf(created, sizeof(created), "%s/%s", target, children[index]); \+ } while (0)++ LINKOWNER_PATHS(CHILD_CONTROL);+ ASSERT_TRUE(cbm_mkdir_p_ex(through_link, 0700, CBM_MKDIR_FOLLOW_OWNED));+ ASSERT_TRUE(cbm_is_dir(created));++ /* World-writable target without the sticky bit: anyone could pre-plant+ * entries in it, so it is refused. Sticky (the /tmp shape) is fine, and+ * so is an ordinary private directory. */+ ASSERT_EQ(chmod(target, 0777), 0);+ LINKOWNER_PATHS(CHILD_WORLD_WRITABLE);+ ASSERT_FALSE(cbm_mkdir_p_ex(through_link, 0700, CBM_MKDIR_FOLLOW_OWNED));+ ASSERT_FALSE(cbm_is_dir(created));+ ASSERT_EQ(chmod(target, 01777), 0);+ LINKOWNER_PATHS(CHILD_STICKY);+ ASSERT_TRUE(cbm_mkdir_p_ex(through_link, 0700, CBM_MKDIR_FOLLOW_OWNED));+ ASSERT_TRUE(cbm_is_dir(created));+ ASSERT_EQ(chmod(target, 0755), 0);+ LINKOWNER_PATHS(CHILD_PRIVATE);+ ASSERT_TRUE(cbm_mkdir_p_ex(through_link, 0700, CBM_MKDIR_FOLLOW_OWNED));+ ASSERT_TRUE(cbm_is_dir(created));++ if (geteuid() == 0) {+ enum { FOREIGN_UID = 65534, USER_UID = 65533 };++ /* Root-owned link, target owned by another account: refused. */+ ASSERT_EQ(chown(target, FOREIGN_UID, FOREIGN_UID), 0);+ LINKOWNER_PATHS(CHILD_FOREIGN_TARGET);+ ASSERT_FALSE(cbm_mkdir_p_ex(through_link, 0700, CBM_MKDIR_FOLLOW_OWNED));+ ASSERT_FALSE(cbm_is_dir(created));+ ASSERT_EQ(chown(target, 0, 0), 0);+ LINKOWNER_PATHS(CHILD_TARGET_RESTORED);+ ASSERT_TRUE(cbm_mkdir_p_ex(through_link, 0700, CBM_MKDIR_FOLLOW_OWNED));+ ASSERT_TRUE(cbm_is_dir(created));++ /* Link AND target owned by a non-root account -- the shape of a+ * privileged install into that account's home -- walked as root:+ * refused even when opted in, because root trusts only root-owned+ * links. */+ ASSERT_EQ(lchown(link, USER_UID, USER_UID), 0);+ ASSERT_EQ(chown(target, USER_UID, USER_UID), 0);+ LINKOWNER_PATHS(CHILD_USER_LINK);+ ASSERT_FALSE(cbm_mkdir_p_ex(through_link, 0700, CBM_MKDIR_FOLLOW_OWNED));+ ASSERT_FALSE(cbm_is_dir(created));+ ASSERT_EQ(lchown(link, 0, 0), 0);+ ASSERT_EQ(chown(target, 0, 0), 0);+ LINKOWNER_PATHS(CHILD_LINK_RESTORED);+ ASSERT_TRUE(cbm_mkdir_p_ex(through_link, 0700, CBM_MKDIR_FOLLOW_OWNED));+ ASSERT_TRUE(cbm_is_dir(created));+ }+#undef LINKOWNER_PATHS++ for (size_t index = 0; index < sizeof(children) / sizeof(children[0]); index++) {+ (void)snprintf(created, sizeof(created), "%s/%s", target, children[index]);+ if (cbm_is_dir(created)) {+ ASSERT_EQ(cbm_rmdir(created), 0);+ }+ }+ ASSERT_EQ(cbm_unlink(link), 0);+ ASSERT_EQ(cbm_rmdir(target), 0);+ ASSERT_EQ(cbm_rmdir(base), 0);+ PASS();+#endif+}++/* The policy is per CALL SITE, not per path. The same user-owned link is+ * followed by the opted-in walk a configuration root uses and refused by the+ * plain walk a checkout uses: `~/.claude -> ~/dotfiles/claude` works for the+ * installer, while a repository that ships `.codebase-memory -> <a directory+ * the user owns>` cannot redirect the artifact writer. Under euid 0 the+ * checked-in link is demoted to a non-root owner, since root-owned links are+ * trusted by both walks and a privileged walk never follows a user's link. */+TEST(platform_mkdir_p_follow_owned_is_per_call_site) {+#ifdef _WIN32+ SKIP_PLATFORM("POSIX symlink ownership contract");+#else+ char base[CBM_SZ_512];+ int written = snprintf(base, sizeof(base), "/tmp/cbm-linksite-XXXXXX");+ ASSERT_TRUE(written > 0 && written < (int)sizeof(base));+ ASSERT_NOT_NULL(cbm_mkdtemp(base));++ /* The dotfile-manager shape under a home directory. */+ char dotfiles[CBM_SZ_1K];+ char claude_link[CBM_SZ_1K];+ char agents_through_link[CBM_SZ_1K];+ char agents_in_dotfiles[CBM_SZ_1K];+ (void)snprintf(dotfiles, sizeof(dotfiles), "%s/home/dotfiles/claude", base);+ (void)snprintf(claude_link, sizeof(claude_link), "%s/home/.claude", base);+ (void)snprintf(agents_through_link, sizeof(agents_through_link), "%s/agents", claude_link);+ (void)snprintf(agents_in_dotfiles, sizeof(agents_in_dotfiles), "%s/agents", dotfiles);+ ASSERT_TRUE(cbm_mkdir_p(dotfiles, 0700));+ ASSERT_EQ(symlink(dotfiles, claude_link), 0);+ ASSERT_TRUE(cbm_mkdir_p_ex(agents_through_link, 0700, CBM_MKDIR_FOLLOW_OWNED));+ ASSERT_TRUE(cbm_is_dir(agents_in_dotfiles));++ /* A checked-in link inside a repository, pointing at a directory the+ * same user owns: the plain walk refuses it and creates nothing behind+ * it. The identical link IS followed once opted in, so the refusal comes+ * from the call site's policy and nothing else. */+ char outside[CBM_SZ_1K];+ char artifact_link[CBM_SZ_1K];+ char artifacts_through_link[CBM_SZ_1K];+ char artifacts_outside[CBM_SZ_1K];+ (void)snprintf(outside, sizeof(outside), "%s/outside", base);+ (void)snprintf(artifact_link, sizeof(artifact_link), "%s/repo/.codebase-memory", base);+ (void)snprintf(artifacts_through_link, sizeof(artifacts_through_link), "%s/artifacts",+ artifact_link);+ (void)snprintf(artifacts_outside, sizeof(artifacts_outside), "%s/artifacts", outside);+ char repo[CBM_SZ_1K];+ (void)snprintf(repo, sizeof(repo), "%s/repo", base);+ ASSERT_TRUE(cbm_mkdir_p(outside, 0700));+ ASSERT_TRUE(cbm_mkdir_p(repo, 0700));+ ASSERT_EQ(symlink(outside, artifact_link), 0);+ /* Git creates the checked-in link owned by whoever cloned. A root run+ * must model that account as non-root: root-owned links are trusted+ * infrastructure for both walks, which is the pre-existing contract. */+ bool privileged = geteuid() == 0;+ enum { CLONING_UID = 65533 };+ if (privileged) {+ ASSERT_EQ(lchown(artifact_link, CLONING_UID, CLONING_UID), 0);+ }+ ASSERT_FALSE(cbm_mkdir_p(artifacts_through_link, 0700));+ ASSERT_FALSE(cbm_is_dir(artifacts_outside));+ if (!privileged) {+ /* Same link, opted in: followed. Not under euid 0, where a privileged+ * walk never follows a user's link whatever the call site says. */+ ASSERT_TRUE(cbm_mkdir_p_ex(artifacts_through_link, 0700, CBM_MKDIR_FOLLOW_OWNED));+ ASSERT_TRUE(cbm_is_dir(artifacts_outside));+ ASSERT_EQ(cbm_rmdir(artifacts_outside), 0);+ }++ ASSERT_EQ(cbm_unlink(artifact_link), 0);+ ASSERT_EQ(cbm_rmdir(repo), 0);+ ASSERT_EQ(cbm_rmdir(outside), 0);+ ASSERT_EQ(cbm_rmdir(agents_in_dotfiles), 0);+ ASSERT_EQ(cbm_unlink(claude_link), 0);+ ASSERT_EQ(cbm_rmdir(dotfiles), 0);+ char *slash = strrchr(dotfiles, '/');ASSERT_NOT_NULL(slash);*slash = '\0';- ASSERT_EQ(cbm_rmdir(created), 0);- ASSERT_EQ(cbm_rmdir(target), 0);+ ASSERT_EQ(cbm_rmdir(dotfiles), 0); /* home/dotfiles */+ slash = strrchr(dotfiles, '/');+ ASSERT_NOT_NULL(slash);+ *slash = '\0';+ ASSERT_EQ(cbm_rmdir(dotfiles), 0); /* home */ASSERT_EQ(cbm_rmdir(base), 0);PASS();#endif@@ -810,7 +1053,9 @@ TEST(cgroup_no_mem_files) {SUITE(platform) {RUN_TEST(platform_file_apis_survive_max_path_overflow);- RUN_TEST(platform_mkdir_p_follows_symlink_owned_by_caller);+ RUN_TEST(platform_mkdir_p_follows_own_symlink_only_when_opted_in);+ RUN_TEST(platform_mkdir_p_symlink_trust_is_bounded_by_owner_and_mode);+ RUN_TEST(platform_mkdir_p_follow_owned_is_per_call_site);RUN_TEST(platform_mkstemp_and_mkdtemp_survive_non_ascii_directory);RUN_TEST(platform_mkdtemp_is_thread_safe);RUN_TEST(platform_counter_scaling_avoids_intermediate_overflow);