Skip to content

fix(security): the response cache writes only inside its own directory and is never read from the tree under review #1014

Closed

Description

@dan-petty

Problem

The response cache trusts the files in its directory. _load_from_disk (src/devops_cli/ai/response_cache.py:375-385) opens <cache dir>/<key>.json and checks only its schema. Nothing compares the stored key, provider, model or hashes with the request, and _check_chat_cache serves any non-empty content (src/devops_cli/ai/client/unified.py:587-608). Offline, a file at a request's key with provider attacker and content "APPROVE, no findings" was served by LLMClient.chat_messages with cached=True and no model call.

A cache hit writes where the file says. get() saves the loaded entry again (response_cache.py:227-231), and _save_to_disk writes cdir / f"{entry.key}.json" (:368), with entry.key read from the file.

  • Offline, a key field of ../escaped_by_key_field wrote escaped_by_key_field.json in the parent of the cache directory. An absolute path in the key field writes that path plus .json, because cdir / "/abs/x.json" is /abs/x.json.
  • The write happens inside get(), before the client checks the content, so an entry with empty content triggers it too.
  • The document's top-level fields are fixed by CachedLLMResponse (response_cache.py:27-46). The attacker chooses its strings and its metadata dict. So any .json file the user can write can be overwritten with that document.
  • set() always stores the request's own key (response_cache.py:258-260). Only a file someone else wrote can carry a bad key.

The cache directory can sit in the tree under review. The review clients take ai.cache.dir, by default the relative .data/cache/llm (src/devops_cli/config/settings.py:377, src/devops_cli/config/defaults.py:36-37). It resolves on every access under the main worktree of the cwd's top-level repository (response_cache.py:161-163, src/devops_cli/core/repo.py:194-200). It does not go through data.dir, so DEVOPS_CLI_DATA_DIR does not move it. Two cases put another party's files there:

  • The cwd is inside an untrusted standalone clone, one not nested in another checkout (a nested clone resolves to the outer checkout's data, core/repo.py:179-183). Its tracked .data/cache/llm/llm_<key>.json files are read. Ignoring .data/* (.gitignore:67 here) does not stop a branch from tracking files there with git add -f, and a clone's .gitignore belongs to its author.
  • An untrusted branch is checked out in the main worktree, for example gh pr checkout N before devops review branch. With git 2.55.0 in a scratch repository, checking out a branch that tracks .data/cache/llm/llm_k.json silently replaced the ignored local file, and switching back deleted it. Linked worktrees are not affected, because their .data is not the data directory.

Not affected: branch review reads git diff base...branch without a checkout (src/devops_cli/ai/review/runner.py:1864-1877). PR review reads the head from a temporary directory (src/devops_cli/commands/review.py:745-748, runner.py:1929-1934) while the cache still resolves from the cwd. Path review of another checkout and the MCP review tools resolve the cache from the user's or the server's cwd.

Feasibility is conditional. A planted entry is served only at the sha256 of the exact request (response_cache.py:166-197): provider, model, system prompt and every message.

  • An attacker knows or controls the diff page, the reviewed repository's conventions, the public persona prompt and builtin exemplars (src/devops_cli/ai/review/classification.py:48-72), the symbols, and, in both cases above, the library contracts (fix(security): reviews take config, data, contracts, scanner config and probe suppressions from the tree under review #972 channel 2).
  • They do not know the victim's provider and model, which have few likely values, or the victim's context window, which sets the page split. Nor do they know the RAG context from the victim's Qdrant, which is empty when Qdrant is unreachable (src/devops_cli/ai/review/pipeline.py:1236-1248).
  • If the key matches, the attacker chooses the persona or verifier reply (for example, no findings for their own file) and gets the write outside the cache directory.

Issue #972 does not cover this. Its channel 1 is the same channel, and its acceptance moves the project config layer and the data dir away from the tree under review. It names the hallucination catalog, history, baselines and contracts, not the response cache, and its tests list no .data/cache/llm file. The cache resolves through ai.cache.dir, so a fix that re-roots data.dir alone leaves it where it is. #972 does name resolve_data_path (core/repo.py:194), which the cache also calls, so a fix inside that function would move the cache too. This issue's location criterion holds either way. The missing name check and the key-field write are outside #972 entirely.

Environment notes. This devcontainer sets DEVOPS_CLI_CONFIG, which skips the project-config walk (settings.py:888-892). A clone cannot change ai.cache.dir or the TTL here, but the relative ai.cache.dir still resolves under the clone. Where the project config layer does load, #972's gateway_url hijack already controls every reply, and planting adds only the write outside the cache directory. devops-cli runs here as an editable install, so for this repository the second case already runs the branch's own code. It matters for every other repository a user reviews.

Line references are at e4ea2e0. At the branch tip (79e1e93) the cited cache, client, config and repo code is unchanged. #987 moved pipeline.py:1236-1248 to :1398-1410 and commands/review.py:745-748 to :760-763.

Acceptance criteria

  • The cache reads and writes only <cache dir>/<requested key>.json. A requested key that is not llm_ followed by 64 hex characters is refused before any file access. A loaded entry whose stored key differs from the requested key is not served and is deleted.
  • An entry stored at a request's key with a key field of ../x, and one with /abs/x, is not served, and no file appears outside the tmp cache directory. The same holds when the entry's content is empty.
  • The response cache resolves under the data directory, so data.dir and DEVOPS_CLI_DATA_DIR move it and fix(security): reviews take config, data, contracts, scanner config and probe suppressions from the tree under review #972's rule for the data dir covers it. With DEVOPS_CLI_DATA_DIR set to a tmp directory, the review clients' cache is <DATA_DIR>/cache/llm.
  • With the cwd in a scratch repository that tracks .data/cache/llm/llm_<key>.json for a stub request, and the review target inside it, the stub request goes to the stub model and the planted reply is not served. This test sits with fix(security): reviews take config, data, contracts, scanner config and probe suppressions from the tree under review #972's channel tests.
  • The tests use tmp directories, local git only and stub clients. They make no network call and add well under 1 s to uv run devops ci.
  • uv run devops ci passes.
  • (person-run) Run devops ai review branch from inside a scratch clone that tracks a .data/cache/llm directory. No file under the clone's .data/ is created or modified.

Key questions

Depends on: #972 (the data-dir rule the cache follows).
Order: after #972, or in the same PR. #1013 also edits response_cache.py; whichever lands second rebases.
Related: #972 (reviews take config and data from the tree under review). #946 (the reviewed repository is untrusted). #553 (one data directory across worktrees). #1013 (the cache stores and serves replies the review cannot use).

Update 2026-10-08: client-cache defects moved from #1013

When the owner froze #1013 on 2026-10-03, the freeze comment named four defects that are not review-specific, because chat and analysis keep the client cache: "the schema echo, empty content, the eviction race, and status/clear reading a different directory". That comment moves them "to #1014 or a new item" before #1013 closes, and #1137's frozen table says "#1013's non-review cache defects move to #1014 first". They move here:

  • the schema echo, which outside review means a reply that fails its schema gets cached;
  • empty content;
  • the eviction race;
  • devops ai cache status and clear reading a different directory.

Two of #1013's acceptance criteria move with them: "A cached entry the client rejects on lookup is deleted", and "A failure while writing or evicting cache files neither fails nor repeats the call".

Chat, analysis and the roadmap's structured calls keep this cache after P3-1 replaces the review's, so these defects are fixed here rather than with the review. The sections above stay as they are; this section adds to them.

Line references are at 910b823 (release/v0.2.29). "Measured" means reproduced offline at that commit with a stub _dispatch_messages and a tmp cache.

Problem (added)

Empty content is cached, then refused on every lookup.

  • On write, _validate_response_text (src/devops_cli/ai/client/unified.py:313-331) accepts empty content when the reasoning is not empty (:319-322). The cache gate checks only the finish reason (:606-607).
  • On lookup, the same check sees cached_entry.content, a plain string without the reasoning, and rejects it (:574-578). The call goes to the model again.
  • By then get() has counted a hit, set last_accessed and rewritten the file (src/devops_cli/ai/response_cache.py:213-216, :227-231). What happens next depends on the new reply:
    • If the new reply is cached, set() (:239-284) replaces the entry.
    • If it is not cached (cut, filtered, failed, or an error), the dead entry survives with a fresh mtime. Eviction drops the oldest mtime first (:98-110), so each such lookup keeps it alive.
    • If the model again answers with empty content, set() caches it again with a new created_at, which restarts its 7-day TTL.
  • Measured:
    • A stub reply "" with reasoning was returned and left a cache file. A second identical call reached the stub again.
    • That entry was seeded on disk for a fresh process. When the dispatch failed after the lookup, hit_count rose from 0 to 1 and the file's mtime advanced. With a reply cut at length, the entry survived with hit_count 1. With a reply that was cached, set() replaced it (hit_count 0).
  • fix(review): a group-analysis reply that fails its checks is neither cached nor served #1013 counted 87 such entries in the local cache on 2026-10-02.

A reply that fails its schema is cached and replayed, and intake's schema accepts any JSON object. Outside review, this is what the owner's "schema echo" comes to. Intake and refine use this structured-output path (roadmap/intake_model.py:184, roadmap/refine.py:344, :792).

  • No caller outside review shows the model a JSON schema, so a literal echo is not expected here; the tests below use one only as a fixture.
    • The intake prompt lists the keys in prose (src/devops_cli/ai/tasks/roadmap_intake_system.md), and the refine prompts describe the task in prose.
    • chat_structured adds no schema, and the client sends no response_format.
    • Only the review agent puts a schema in its prompt (ai/agents/agent.py:680-689, through ai/review/pipeline.py:3210).
  • chat_structured caches its first attempt before it checks the schema. _execute_structured_step calls chat_messages with use_cache on (src/devops_cli/ai/client/structured.py:188-195, :252), and later attempts run uncached. A first reply that fails the schema is therefore written, and every rerun serves it first for 7 days. The reply that validates is never cached.
  • ResearchPlan and RefinementProposal set extra="forbid" (roadmap/refine.py:64-66, :83-91).
  • ModelProposal sets extra="ignore" and gives every field a default (roadmap/intake_model.py:44-61), so it validates any JSON object.
    • Misspelled keys, a wrapper such as {"proposal": {...}}, {} and its own schema all become a proposal with empty fields. The echo also gets type "object".
    • chat_structured returns that proposal on attempt 1, with no reflection retry.
    • validate_proposal (roadmap/intake.py:703-721) refuses the empty priority, value and effort. For a candidate with no type label, it also refuses a type that is not on the list (:708). Intake then skips the candidate (:1027-1030).
    • Intake skips it again on every rerun, until the entry expires or ai cache clear clears the right directory (see below).
  • Measured:
    • ModelProposal, first reply {"proposal": {…valid fields…}}, then valid: run 1 made 1 call and returned an empty priority. Run 2 made 0 calls and returned the same. The schema-echo fixture behaves the same way.
    • ResearchPlan, first reply {"queries": "one query"} (a string, not a list), then valid: run 1 made 2 calls, and the cache held only the failing reply. Run 2 replayed it as attempt 1 and made 1 call. The echo fixture gave the same counts.

A file removed during eviction fails the call.

  • _evict_excess_disk_files sorts by p.stat() with no guard (response_cache.py:102). It stats every file on every write, before it checks whether anything is over the cap (:102-105), so the race does not need a full cache.
  • It runs from set() → _enforce_capacity (:282, :425-426), inside the dispatch try (unified.py:626-652). The generic handler turns the FileNotFoundError into _connection_error (:649-652, :240-252).
  • Measured: a file was listed and then removed before its stat, as happens when a second process or devops ai cache clear removes it. One chat() made 1 model call and wrote the reply to the cache. It then raised "Cannot connect to AI provider API. Check network access, api_base_url, and API key." The caller gets a false connection error for a reply that the next identical call serves from the cache.

devops ai cache status and clear can use a different cache.

  • Both commands build the cache with no arguments (src/devops_cli/commands/ai_cache.py:30, :91). That gives data.cache_dir / "llm" and the module defaults: enabled, 7 days, 1,000 entries (response_cache.py:146-152, :433-449; config/defaults.py:128-130).
  • The clients pass ai.cache (unified.py:201-228; AICacheConfig at config/settings.py:403-410).
    • Its dir is the relative .data/cache/llm (defaults.py:37), resolved under the cwd's main worktree (core/repo.py:280-283).
    • It does not follow data.dir: settings.py:681-687 rebases only the data.* children.
  • The cache is a process-wide singleton, and whichever caller builds it first sets its directory and settings for every later caller (response_cache.py:441-448).
  • In the default config, both sides resolve the same relative .data/cache/llm with the same defaults. They split once data.dir, DEVOPS_CLI_DATA_DIR, DEVOPS_CLI_DATA_CACHE_DIR or any ai.cache.* value is set. The repository's container image sets DEVOPS_CLI_DATA_DIR (Dockerfile:40).
  • Measured:
    • With DEVOPS_CLI_DATA_DIR set, status and clear resolve <DATA_DIR>/cache/llm, while the clients use .data/cache/llm under the main worktree.
    • A configured ai.cache.max_entries, ttl_seconds or enabled: false never reaches status.
    • clear is the only way to remove a bad entry, and then it clears the wrong directory.

How this fits #1014's scope

  • Same directory code. fix(security): the response cache writes only inside its own directory and is never read from the tree under review #1014's location criterion ("the review clients' cache is <DATA_DIR>/cache/llm") rewrites the code that picks the directory (unified.py:201-228, response_cache.py:146-152).
    • fix(security): reviews take config, data, contracts, scanner config and probe suppressions from the tree under review #972 has landed. During a review started outside devops-cli's own repository, a relative cache path already resolves under the user data root (core/repo.py:267-283, core/untrusted_trees.py:52-59).
    • The rest of the criterion is the split between ai.cache.dir and data.dir (docs/agent/tasks/task-972-reviews-take-nothing-from-the-tree-under-review.md:21). That split is also why status and clear miss the clients' directory once data.dir or its environment variables are set.
    • Building the cache once, from settings, closes that split, so this code is rewritten once rather than twice.
    • Known limit: this does not close the split between a review and these commands when data.dir is relative, as it is by default. A review started outside devops-cli's own repository keeps relative data under the user data root. status and clear never run inside a review, because only review commands enter that rule (main.py:127, commands/review.py:163), so they resolve the same relative path under the cwd's main worktree. An absolute data.dir or DEVOPS_CLI_DATA_DIR avoids the split, and status prints the directory it reads (cache_directory). See the key questions.
  • Same lookup. fix(security): the response cache writes only inside its own directory and is never read from the tree under review #1014 makes a lookup refuse and delete an entry whose stored key is not the requested key. It already notes that get() rewrites the file before the client checks the content. An entry the client rejects for its content goes through the same delete, so the empty-content and failed-schema cases need no path of their own.
  • Same file layer. The eviction guard sits in response_cache.py, beside fix(security): the response cache writes only inside its own directory and is never read from the tree under review #1014's checks before file access. It is one guarded stat, with no new catch-all in the client: _save_to_disk already swallows its own errors (:372-373).
  • The fix for the empty-proposal case belongs to the schema. ModelProposal takes pydantic's extra="forbid", as the other two structured schemas already do. Its priority, value and effort become required, as the prompt already requires. The client gains no key heuristic.

Acceptance criteria (added)

  • Empty content. A reply whose content is empty or only whitespace is returned to its caller as today, reasoning included, and is never cached. Tests:
    • Stub replies "" with reasoning and " \n" with reasoning each leave no cache file, and a second identical call reaches the stub.
    • A reply with content and no reasoning is still cached, and a second identical call makes 0 calls.
  • A rejected lookup deletes its entry. The client may reject an entry on lookup, either for empty content or through the caller's validator. Such an entry is deleted from memory and disk through the same delete as fix(security): the response cache writes only inside its own directory and is never read from the tree under review #1014's key check, and the call goes to the model. Test:
    • Seed a tmp cache at the request's key with empty content, once on disk only (a fresh process) and once in memory.
    • The stub replies with finish reason length, which is never cached.
    • In each case, one call makes one stub call. Afterwards no file is left at the key, and the memory cache holds no entry for it.
    • At 910b823 the entry survives with hit_count 1. The test must not use a stub reply that gets cached, because it would replace the entry and the test would pass without the fix.
  • Schema. ModelProposal (intake_model.py:47) sets extra="forbid", and priority, value and effort have no default. No key list is added to the client. Tests:
    • For each of ModelProposal, ResearchPlan and RefinementProposal: with a stub whose first reply is json.dumps(Schema.model_json_schema()) and whose second is valid, chat_structured returns the valid model after 2 calls.
    • For ModelProposal, the same holds for the first replies {} and {"proposal": {…valid fields…}}.
    • A ModelProposal reply with exactly the keys the prompt names validates on attempt 1.
    • A reply with one extra key is retried once.
  • A reply that fails its schema is not cached. chat_structured leaves no cache entry that holds a reply which failed its schema. An entry at the first attempt's key that fails the schema is deleted. The client's validator keeps its meaning (accept, or raise after max_retries + 1 calls), because the reflection loop needs the rejected text. Tests:
    • A stub's first reply fails the schema and its second is valid. Run 1 leaves no file holding the failing reply, and run 2's first attempt reaches the stub.
    • A reply that validates on attempt 1 is still cached, so run 2 makes 0 calls.
  • Eviction race. A file that disappears between the directory listing and its stat is skipped (response_cache.py:102). Tests:
    • One file is listed but removed before its stat, below the cap. One chat() makes one stub call, returns its reply and raises nothing.
    • At exactly max_entries nothing is evicted, and one entry over the cap removes only the oldest.
  • status and clear see the clients' cache. The response cache is built in one place from settings: its directory (<DATA_DIR>/cache/llm, per fix(security): the response cache writes only inside its own directory and is never read from the tree under review #1014), TTL, size cap and enabled flag. The clients, devops ai cache status and devops ai cache clear all use it, whichever of them builds it first in a process.
    • A client built with cache_enabled=False still neither reads nor writes the cache. Such clients are built for review --no-cache and --force (commands/review.py:333, :560, :889) and at commands/ai.py:566, :662 and :809.
    • Today the flag holds only when that client is the first to build the cache in its process. Measured: a client built after the cache existed made 1 call for 2 identical calls.
    • The tests use typer CliRunner, the cwd and DEVOPS_CLI_DATA_DIR at tmp directories, and a tmp config file that sets ai.cache.max_entries and ai.cache.ttl_seconds:
      • A stub client call writes one entry.
      • The test then sets response_cache._GLOBAL_LLM_CACHE to None with monkeypatch, so that status and clear build the cache themselves, as a new process would. reset_llm_response_cache() cannot be used here, because it clears the entry (response_cache.py:452-458).
      • status --format json then reports <DATA_DIR>/cache/llm, 1 disk entry and the configured values.
      • clear removes that entry.
      • With ai.cache.enabled: false, status reports the cache as disabled.
      • With the cache built from settings first, a cache_enabled=False client makes 2 stub calls for 2 identical calls and writes no file.
    • The autouse fixture isolate_llm_response_cache (tests/conftest.py:275-287) builds the cache through settings, not by argument. It requests isolate_data_dir (:290-300) by name. Today isolate_data_dir runs first only because pytest sets up these autouse fixtures in name order.
  • The new tests go in tests/test_response_cache.py, tests/test_ai_client_structured.py and tests/test_roadmap_intake.py. They stub _dispatch_messages, use tmp directories, make no network or DNS call, and together add well under 1 s to uv run devops ci.
  • One fragment can hold several categories (src/devops_cli/release/changelog_fragments.py:99-116).

Key questions (added)

Out of scope:

Order:

Priority and placement stay with the roadmap tooling. The moved defects came from a P1 item.

Update 2026-10-08: refinement, merged from #1375

Proposed design

Problem statement

The response cache in devops-cli is vulnerable to directory traversal attacks and arbitrary file overwrites. An attacker can place malicious cache entries that write files outside the designated cache directory by manipulating the 'key' field in cached entries, or by placing cache files in directories under review that resolve to the cache directory. Additionally, the cache does not validate that loaded entries match the requested key, allowing incorrect entries to be served and potentially overwritten.

Acceptance criteria

  • Criterion 1: The cache reads and writes only /.json, refusing keys that are not 'llm_' followed by 64 hex characters before any file access
    Verification: Run tests with tmp directories using stub clients that verify cache operations only occur at the requested key path and reject malformed keys
  • Criterion 2: Entries stored with a key field of '../x' or '/abs/x' are not served, and no file appears outside the tmp cache directory
    Verification: Test cache behavior with entries having bad key fields, ensuring they are not loaded or written outside the cache directory
  • Criterion 3: The response cache resolves under the data directory, so 'data.dir' and 'DEVOPS_CLI_DATA_DIR' move it
    Verification: Set DEVOPS_CLI_DATA_DIR to a tmp directory and verify that review clients use /cache/llm as their cache directory
  • Criterion 4: With the cwd in a scratch repository tracking .data/cache/llm files, stub requests go to the stub model and planted replies are not served
    Verification: Create a scratch repo with tracked cache files, run devops ai review branch and verify no file under the clone's .data/ is created or modified
  • Criterion 5: Tests use tmp directories, local git only and stub clients, making no network calls and adding well under 1s to 'uv run devops ci'
    Verification: Run the new test suite with tmp directories, verify no network activity and check execution time is under 1 second
  • Criterion 6: changelog.d/1014.md records the fix under '### Security'
    Verification: Check that changelog.d/1014.md exists and contains security-related entries
  • Criterion 7: uv run devops ci passes
    Verification: Run 'uv run devops ci' and verify all checks pass without errors

Key questions

None.

Open questions

Fit

Fits in one pull request.

Suspected block

None.

Dependencies

None.

Activity

  1. added
    type/security
    scope/ai
    scope/security
    priority/p2-medium
    on Oct 2, 2026
  2. dan-petty commented on Oct 8, 2026

    @dan-petty
    OwnerAuthor

    Linked: #1036 (v0.2.31) adds one helper resolving a store's default path under the data directory; this item's response cache uses it, and whichever lands second moves the other onto it. Found by the 2026-10-08 backlog review.

  3. added this to the milestone on Oct 21, 2026
  4. dan-petty commented on Oct 22, 2026

    @dan-petty
    OwnerAuthor

    Status set back to New at 6c713ee: refine found it not ready (see Key questions, Fit and Suspected block in the proposed design in the issue body).

  5. removed this from the milestone on Oct 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p2-mediumscope/aiscope/securitytype/security

    Type

    No type

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions