hardening: storage permissions, ATTACH path escaping, project-config privilege stripping

Closed
TR
5mo ago
+315-126

Three defense-in-depth hardenings, one commit each:

  1. Escape SQLite ATTACH path (tool-owner-backfill.ts): the OpenCode DB path was interpolated into ATTACH '...' unescaped; a path containing a single quote breaks the statement. Now escaped (' → ''; ATTACH does not support bound parameters). Test covers a path containing a quote.

  2. Storage permissions (storage-db.ts, embedding-local.ts): context.db holds raw conversation history. The storage dir (and models cache dir) are now created/chmod'd 0700 and context.db/-wal/-shm chmod'd 0600. Best-effort with try/catch, skipped on win32. Test asserts modes (skipped on win32).

  3. Project-config privilege stripping (project-security.ts): project-level config merges over user config, so a repo-supplied magic-context.jsonc could redirect embedding to an arbitrary endpoint (memory text is POSTed to ${endpoint}/embeddings), enable dreamer/sidekick (agents allowed bash/write/edit), or override historian routing. stripUnsafeProjectConfigFields() now also strips embedding, historian, dreamer, sidekick (whole objects) and memory.git_commit_indexing from project config — these are user-config-only now, consistent with the existing strip of auto_update/sqlite/hidden-agent fields. CONFIGURATION.md documents the trust boundary.


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.


Summary by cubic

Hardens storage and config security and fixes a SQLite ATTACH path bug. Prevents local data leaks, blocks repo-driven privilege escalation, and makes backfill robust for paths with quotes.

  • Bug Fixes
    • Escape SQLite ATTACH path in tool-owner backfill (handles single quotes; ATTACH can’t use bound params).
    • Restrict storage permissions: storage dir 0700; context.db/-wal/-shm 0600 (best-effort; skipped on Windows).
    • Strip unsafe project-config keys: drop embedding, historian, dreamer, sidekick (entire blocks), and memory.git_commit_indexing; disable {env:}/{file:} token expansion in project config; document the trust boundary in CONFIGURATION.md.

Greptile Summary

Three independent hardening commits: SQLite ATTACH path escaping, filesystem permission tightening on the storage dir and DB files, and a stronger project-config privilege strip that now drops entire embedding/historian/dreamer/sidekick blocks (previously only dangerous sub-fields were removed). All changes are well-tested and the documentation is updated.

  • ATTACH escaping (tool-owner-backfill.ts): replaceAll("'", "''") is the correct SQL-literal escape for a context where bound parameters are unavailable; regression test covers an end-to-end path with a quote in the directory name.
  • Storage permissions (storage-db.ts, embedding-local.ts): storage dir created/chmoded to 0700, DB file and WAL/SHM sidecars to 0600; best-effort, Windows-skipped, chmod placed after WAL-mode init so sidecars exist before the call.
  • Project-config stripping (project-security.ts): upgrading from field-level to block-level strip closes routing-override and enablement vectors the previous approach left open; however, dropInheritedEmbeddingKeyOnRedirect is now unreachable in production (see inline comment).

Confidence Score: 4/5

Safe to merge — all three hardening changes behave correctly and the tests cover the key scenarios. One function in project-security.ts is now unreachable in practice and should be cleaned up in a follow-up.

The ATTACH escaping and permission tightening are straightforward and well-tested. The project-config strip is the most significant change and is correct in its effect, but it leaves dropInheritedEmbeddingKeyOnRedirect as dead code: both call sites in config/index.ts pass the already-stripped projectRaw, so the function's early-return guard fires on every invocation and the key-drop logic never runs. This does not reopen any protection gap (the full-block strip is strictly stronger), but it creates a misleading safety net that future contributors may rely on or be confused by.

packages/plugin/src/config/project-security.ts — dropInheritedEmbeddingKeyOnRedirect and its two call sites in config/index.ts can be removed.

Important Files Changed

FilenameOverview
packages/plugin/src/features/magic-context/tool-owner-backfill.tsAdds single-quote escaping via replaceAll("'", "''") before ATTACH — correct standard SQL literal escape for a context that does not support bound parameters.
packages/plugin/src/config/project-security.tsHardens project config stripping to drop entire embedding/historian/dreamer/sidekick blocks and memory.git_commit_indexing; correct and thorough, but dropInheritedEmbeddingKeyOnRedirect is now dead code (see comment).
packages/plugin/src/features/magic-context/storage-db.tsAdds ensureSecureStorageDir (mkdir + chmod 0700) and restrictDatabaseFilePermissions (chmod 0600 on db/-wal/-shm); best-effort, Windows-skipped, correctly placed after WAL-mode init creates sidecars.
packages/plugin/src/features/magic-context/memory/embedding-local.tsAdds mkdir mode 0o700 + best-effort chmodSync on the model cache dir, consistent with the storage-db pattern.
packages/plugin/src/features/magic-context/tool-owner-backfill.test.tsNew test exercises ATTACH with a quote-containing path end-to-end; XDG_DATA_HOME is correctly restored by the existing afterEach.
packages/plugin/src/features/magic-context/storage-db.test.tsNew test asserts 0o700 on storage dir and 0o600 on DB files; correctly skipped on win32.
packages/plugin/src/config/project-security.test.tsUpdated tests correctly cover the new full-block strip behavior; dropInheritedEmbeddingKeyOnRedirect tests still pass but test the function in isolation rather than through the production call path where it is now unreachable.
packages/plugin/src/config/index.test.tsToken-expansion tests updated to use non-stripped fields (cache_ttl/disabled_hooks); new user-only-settings tests cover dreamer and memory.git_commit_indexing stripping.
CONFIGURATION.mdAdds trust boundary documentation for project config; accurately describes the new strip set and token-expansion behavior.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[loadPluginConfig called] --> B[Load user config\nexpand tokens]
    A --> C[Load project config\nNO token expansion]

    C --> D[stripUnsafeProjectConfigFields\nprojectRaw mutated in-place]
    D -->|deletes| E["auto_update\nsqlite\nembedding ← NEW\nhistorian ← NEW\ndreamer ← NEW\nsidekick ← NEW\nmemory.git_commit_indexing ← NEW"]

    D --> F[deepMergeRawConfig\nuser + project]
    B --> F

    F --> G[dropInheritedEmbeddingKeyOnRedirect\n⚠ now dead code:\nprojectRaw.embedding always absent]

    G --> H[parsePluginConfig / Zod]
    H --> I[MagicContextConfig returned]

    style E fill:#f9d,stroke:#c66
    style G fill:#ffd,stroke:#aa0

Comments Outside Diff (1)

  1. packages/plugin/src/config/project-security.ts, line 119-161 (link)

    P2 dropInheritedEmbeddingKeyOnRedirect is now dead code in every production call path. Both call sites in config/index.ts call stripUnsafeProjectConfigFields(projectRaw) first, which deletes projectRaw.embedding unconditionally. The very first guard in this function (if (!isPlainObject(projectRaw.embedding)) return []) will always short-circuit because embedding is absent by the time the function is called. The function provides zero additional protection and its unit tests in project-security.test.ts test it in isolation (without stripping first), so they do not surface the dead-code condition. Consider removing the function and its call sites now that the full-strip approach supersedes it.

Reviews (1): Last reviewed commit: "plugin: strip agent and embedding overri..." | Re-trigger Greptile