From 57e8f9b672c515e159b31ceb38ec01c6ed7997fb Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Mon, 26 Oct 2026 18:18:02 +0000 Subject: [PATCH 1/6] docs(openspec): plan 1014-response-cache-directory-traversal --- .../.openspec.yaml | 2 + .../design.md | 46 +++++++++++++++ .../proposal.md | 56 +++++++++++++++++++ .../specs/llm-response-cache/spec.md | 46 +++++++++++++++ .../tasks.md | 24 ++++++++ 5 files changed, 174 insertions(+) create mode 100644 openspec/changes/1014-response-cache-directory-traversal/.openspec.yaml create mode 100644 openspec/changes/1014-response-cache-directory-traversal/design.md create mode 100644 openspec/changes/1014-response-cache-directory-traversal/proposal.md create mode 100644 openspec/changes/1014-response-cache-directory-traversal/specs/llm-response-cache/spec.md create mode 100644 openspec/changes/1014-response-cache-directory-traversal/tasks.md diff --git a/openspec/changes/1014-response-cache-directory-traversal/.openspec.yaml b/openspec/changes/1014-response-cache-directory-traversal/.openspec.yaml new file mode 100644 index 0000000000..d58ba02327 --- /dev/null +++ b/openspec/changes/1014-response-cache-directory-traversal/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-10-26 diff --git a/openspec/changes/1014-response-cache-directory-traversal/design.md b/openspec/changes/1014-response-cache-directory-traversal/design.md new file mode 100644 index 0000000000..b224b41a47 --- /dev/null +++ b/openspec/changes/1014-response-cache-directory-traversal/design.md @@ -0,0 +1,46 @@ +# Design + +## Context + +See proposal.md for motivation and problem analysis. The LLM response cache stores serialised JSON responses to avoid redundant model dispatches. It runs both as an in-memory dictionary and on the filesystem under the configured cache directory. + +## Goals / Non-Goals + +**Goals:** +- Confine all response cache file reads and writes strictly to `/.json`. +- Reject malformed or relative keys before filesystem access. +- Invalidate and delete any loaded cache file whose stored `key` does not match the requested key. +- Align cache directory resolution strictly with `data.dir` and `DEVOPS_CLI_DATA_DIR`. +- Ensure clients with `cache_enabled=False` bypass cache reads and writes completely. +- Exclude empty text responses and responses failing schema validation from the cache. + +**Non-Goals:** +- Cryptographic signatures for cached entries (not needed once directory isolation and untrusted tree isolation prevent unauthorized writes). +- Backward compatibility for `ai.cache.dir` (pre-1.0 alpha software). + +## Decisions + +### Decision: Validate keys with strict pattern checking before filesystem access +Check that the requested key starts with `llm_` and contains exactly 64 hexadecimal characters. Any key failing this condition immediately returns `None` for lookups or is rejected on writes, without invoking any filesystem operations. +Rejected alternative: Path resolution and normalization checks (such as `resolve().is_relative_to()`). Evidence: Path resolution still touches the filesystem or parses arbitrary string paths, leaving potential edge cases or symlink complexities. Validating the key format upfront prevents arbitrary path creation entirely. + +### Decision: Enforce key equality upon disk load +When loading a cached JSON file from disk, compare the entry `key` attribute against the requested key. If they differ, delete the disk file immediately and treat the lookup as a cache miss. +Rejected alternative: Overwriting the entry key on load. Evidence: Overwriting would allow malicious entries with bad keys to rewrite files or propagate invalid entries across calls. + +### Decision: Re-root cache directly under `data.cache_dir / "llm"` +Remove `ai.cache.dir` from `AICacheConfig`. Build the global singleton cache using `settings.data.cache_dir / CONST_LLM_CACHE_DIR_NAME`. +Rejected alternative: Retaining `ai.cache.dir` with fallbacks. Evidence: Dual configuration paths caused the divergence between review runners and `ai cache status/clear` commands. Pre-1.0 policy removes obsolete shims. + +### Decision: Delete rejected cached entries upon client lookup validation +In `unified.py: _check_chat_cache`, if `_validate_response_text(cached_entry.content, validator)` fails, delete the entry from both memory and disk via `cache.delete(cache_key)`. +Rejected alternative: Leaving rejected entries on disk until TTL expiry. Evidence: Leaving rejected entries caused repeated failed lookups, bumped access times, and prevented clean replacement. + +### Decision: ModelProposal schema enforcement via Pydantic +Set `extra="forbid"` on `ModelProposal` and remove default values from `priority`, `value`, and `effort`. +Rejected alternative: Manual key validation in `chat_structured`. Evidence: Schema enforcement belongs in the Pydantic model definition. Adding ad-hoc dictionary validation in the client introduces fragile heuristics. + +## Risks / Trade-offs + +- [Risk] Existing tests that used arbitrary short test keys (such as `llm_1`) will fail key validation. + → Mitigation: Update test fixtures in `tests/test_response_cache.py` to use valid 64-hex SHA-256 keys or helper methods. diff --git a/openspec/changes/1014-response-cache-directory-traversal/proposal.md b/openspec/changes/1014-response-cache-directory-traversal/proposal.md new file mode 100644 index 0000000000..6975ab895b --- /dev/null +++ b/openspec/changes/1014-response-cache-directory-traversal/proposal.md @@ -0,0 +1,56 @@ +# Proposal + +## Why + +Issue #1014: the response cache trusts the files in its directory and does not validate that loaded entries match requested keys. +An attacker can place malicious entries with directory traversal sequences in the key field or in the directory under review. +This can overwrite files outside the cache directory or serve attacker-controlled model responses without model calls. +Furthermore, empty responses and responses failing schema validation were improperly cached, while cache status and clear commands could resolve an inconsistent cache directory. + +## What Changes + +- The response cache reads and writes only files named `/.json`. +- Cache keys must be `llm_` followed by 64 hexadecimal characters. The cache refuses malformed keys before file access. +- When a loaded entry contains a key field that differs from the requested key, the cache deletes the disk file and does not serve it. +- The cache resolves under `/cache/llm` through settings, so `data.dir` and `DEVOPS_CLI_DATA_DIR` move it. +- `ai.cache.dir` is removed from configuration because the cache directory belongs to `data.dir`. +- The CLI commands `devops ai cache status` and `devops ai cache clear` build from settings and inspect `/cache/llm`. +- A client created with `cache_enabled=False` neither reads nor writes the cache, even when a singleton cache exists. +- Model responses with empty or whitespace-only content are never cached. +- When the client rejects a cached entry on lookup, it deletes the entry from memory and disk. +- In `ModelProposal`, set `extra="forbid"` and make `priority`, `value`, and `effort` required fields. +- `chat_structured` does not store replies that fail schema validation in the cache. +- The change fits in one pull request. + +## Capabilities + +### New Capabilities + +- `llm-response-cache`: how LLM responses are cached, validated, and isolated on the workstation filesystem. + +### Modified Capabilities + +None. + +## Impact + +- `src/devops_cli/ai/response_cache.py`: key validation, safe lookup, entry deletion, and settings-driven singleton initialization. +- `src/devops_cli/ai/client/unified.py`: empty-content caching exclusion, entry deletion on rejected lookup, and cache resolution. +- `src/devops_cli/config/settings.py` and `src/devops_cli/config/defaults.py`: remove `ai.cache.dir`. +- `src/devops_cli/roadmap/intake_model.py`: update `ModelProposal` schema. +- `tests/test_response_cache.py`, `tests/test_ai_client_structured.py`, `tests/test_review_untrusted_tree.py`, `tests/conftest.py`. + +## Feasibility + +- The code. At `origin/main` 30c6fa18, `LLMResponseCache` in `src/devops_cli/ai/response_cache.py` resolves `cache_dir` without key validation before file access. +- Key traversal. Testing with keys containing `../` or `/abs/` confirms path concatenation directly without canonical directory confinement. +- Settings alignment. Reviewing `settings.py` confirms `AICacheConfig` previously maintained a distinct `dir` setting decoupled from `DataConfig`. +- Structured schema. Testing `ModelProposal` confirms `extra="ignore"` permits invalid or echo schemas unless restricted by `extra="forbid"`. +- Unit tests verify all isolation requirements offline in temporary directories with local git repositories and stubs. + +## Existing Tool Considered + +- Disk caching: standard filesystem operations using Python `pathlib.Path` and stdlib `hashlib`. +- SQLite or third-party cache (such as `diskcache`): adds unnecessary binary dependencies and concurrency overhead for simple file-based responses. +- Building the validation logic in-tree requires minimal tokens and adds zero new runtime dependencies. +- Internal code removed: deletes `AICacheConfig.dir` and custom directory routing branches. diff --git a/openspec/changes/1014-response-cache-directory-traversal/specs/llm-response-cache/spec.md b/openspec/changes/1014-response-cache-directory-traversal/specs/llm-response-cache/spec.md new file mode 100644 index 0000000000..aaa7d417c3 --- /dev/null +++ b/openspec/changes/1014-response-cache-directory-traversal/specs/llm-response-cache/spec.md @@ -0,0 +1,46 @@ +# Spec Delta + +## Purpose + +Provides secure persistent caching for LLM responses, ensuring strict directory isolation and preventing malicious traversal attacks. + +## ADDED Requirements + +### Requirement: Cache keys are validated before file access +The response cache SHALL accept only keys that begin with `llm_` followed by 64 hexadecimal characters. The cache SHALL reject any malformed key before accessing or modifying the filesystem. + +#### Scenario: Malformed key rejected +- **WHEN** a caller requests or stores an entry with a key that contains directory traversal sequences or non-hexadecimal characters +- **THEN** the cache rejects the operation without accessing or writing files + +### Requirement: Loaded entries must match requested keys +The response cache SHALL verify that loaded entries contain a key identical to the requested key. If the stored key in the file differs from the requested key, the cache SHALL delete the disk file and return no entry. + +#### Scenario: Stored key mismatch +- **WHEN** a cached JSON file on disk contains a key that differs from the requested key +- **THEN** the cache deletes the file on disk and returns a cache miss + +### Requirement: Cache directory resolves under data directory +The response cache SHALL resolve its storage directory under `/cache/llm`. The configuration `data.dir` and the environment variable `DEVOPS_CLI_DATA_DIR` SHALL determine the cache root. + +#### Scenario: Custom data directory configured +- **WHEN** `DEVOPS_CLI_DATA_DIR` is set to an isolated directory +- **THEN** all cache operations and CLI commands read and write inside `/cache/llm` + +### Requirement: Empty and schema-failing responses are not cached +The AI client SHALL not store responses whose content is empty or contains only whitespace in the cache. The structured client SHALL not store replies that fail schema validation. + +#### Scenario: Empty response with thinking block +- **WHEN** a model returns an empty text response containing thinking blocks +- **THEN** the client returns the response to the caller and writes no cache file + +#### Scenario: Response fails schema validation +- **WHEN** a structured model response fails Pydantic schema validation on attempt 1 +- **THEN** the client deletes any invalid entry at the key and stores no failing reply + +### Requirement: Disabled cache clients bypass cache +An AI client configured with disabled caching SHALL neither read nor write the response cache. + +#### Scenario: Cache disabled client execution +- **WHEN** an AI client is initialized with `cache_enabled=False` +- **THEN** multiple identical requests dispatch to the provider and create no cache files diff --git a/openspec/changes/1014-response-cache-directory-traversal/tasks.md b/openspec/changes/1014-response-cache-directory-traversal/tasks.md new file mode 100644 index 0000000000..3dda430aee --- /dev/null +++ b/openspec/changes/1014-response-cache-directory-traversal/tasks.md @@ -0,0 +1,24 @@ +# Tasks + +## 1. Response cache directory confinement and key validation + +- [ ] 1.1 Write failing tests in `tests/test_response_cache.py` asserting that keys must be `llm_` followed by 64 hexadecimal characters, that malformed keys (`../x`, `/abs/x`, non-hex) are rejected before any filesystem access, that entries on disk with mismatched keys are deleted and not served, and that `delete()` removes entries from memory and disk. Verify with `uv run devops ci test tests/test_response_cache.py`. +- [ ] 1.2 Implement `is_valid_cache_key`, strict key validation before disk operations, key equality verification on disk load, and `delete()` in `src/devops_cli/ai/response_cache.py`. Update existing tests in `tests/test_response_cache.py` that used arbitrary non-hex keys. Verify with `uv run devops ci test tests/test_response_cache.py` and `uv run mypy src/devops_cli/ai/response_cache.py`. +- [ ] 1.3 Regenerate CLI documentation. Verify with `uv run devops docs generate --sync-readme` and `uv run devops docs check`. + +## 2. Response cache configuration and singleton alignment + +- [ ] 2.1 Write failing tests in `tests/test_response_cache.py` asserting that the cache directory resolves under `/cache/llm`, that `devops ai cache status` and `devops ai cache clear` read settings, and that a client initialized with `cache_enabled=False` neither reads nor writes the cache even when a singleton cache exists. Verify with `uv run devops ci test tests/test_response_cache.py`. +- [ ] 2.2 Remove `dir` from `AICacheConfig` in `src/devops_cli/config/settings.py` and remove `DEFAULT_LLM_CACHE_DATA_DIR` in `src/devops_cli/config/defaults.py`. Update `get_llm_response_cache()` and `_resolve_llm_cache()` in `src/devops_cli/ai/client/unified.py` to build from settings and isolate disabled clients. Update `isolate_llm_response_cache` in `tests/conftest.py` to build via settings and request `isolate_data_dir`. Verify with `uv run devops ci test tests/test_response_cache.py tests/test_data_dir_configuration.py`. +- [ ] 2.3 Regenerate CLI documentation. Verify with `uv run devops docs generate --sync-readme` and `uv run devops docs check`. + +## 3. Client caching exclusions, rejected entry cleanup, and structured schema enforcement + +- [ ] 3.1 Write failing tests in `tests/test_response_cache.py`, `tests/test_ai_client_structured.py`, and `tests/test_review_untrusted_tree.py` asserting that empty content replies with thinking blocks are not cached, that rejected lookups delete the entry from memory and disk, that `ModelProposal` forbids extra fields and requires `priority`, `value`, and `effort`, that structured replies failing schema validation are not cached, and that a clone tracking `.data/cache/llm/` files does not serve planted replies. Verify with `uv run devops ci test tests/test_response_cache.py tests/test_ai_client_structured.py tests/test_review_untrusted_tree.py`. +- [ ] 3.2 Update `_check_chat_cache` and `_handle_successful_chat_dispatch` in `src/devops_cli/ai/client/unified.py` to delete rejected lookup entries and bypass caching for empty responses. Update `ModelProposal` in `src/devops_cli/roadmap/intake_model.py` with `extra="forbid"` and required fields. Verify with `uv run devops ci test tests/test_response_cache.py tests/test_ai_client_structured.py tests/test_roadmap_intake.py tests/test_review_untrusted_tree.py`. +- [ ] 3.3 Regenerate CLI documentation and verify full suite. Verify with `uv run devops docs generate --sync-readme`, `uv run devops docs check`, and `uv run devops ci`. + +## Workflow follow-up + +- Pending a person: run `devops ai review branch` from inside a scratch clone that tracks a `.data/cache/llm` directory and verify no file under the clone's `.data/` is created or modified. +- Pending a person: review the diff in tuicr (tuicr -r origin/main..HEAD). From 4e5319a7b581111f6d9d86c686d1fc77b1b5d08c Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Mon, 26 Oct 2026 18:25:09 +0000 Subject: [PATCH 2/6] fix(ai): validate response cache keys and confine filesystem access Validate response cache keys before any disk lookup or write operation. Reject malformed keys, directory traversal patterns, and absolute paths. Ensure disk entries match their filename key before use. --- .../tasks.md | 6 +- src/devops_cli/ai/response_cache.py | 53 +++++++- src/devops_cli/config/constants.py | 6 + tests/test_response_cache.py | 124 ++++++++++++++++-- 4 files changed, 169 insertions(+), 20 deletions(-) diff --git a/openspec/changes/1014-response-cache-directory-traversal/tasks.md b/openspec/changes/1014-response-cache-directory-traversal/tasks.md index 3dda430aee..650db4909f 100644 --- a/openspec/changes/1014-response-cache-directory-traversal/tasks.md +++ b/openspec/changes/1014-response-cache-directory-traversal/tasks.md @@ -2,9 +2,9 @@ ## 1. Response cache directory confinement and key validation -- [ ] 1.1 Write failing tests in `tests/test_response_cache.py` asserting that keys must be `llm_` followed by 64 hexadecimal characters, that malformed keys (`../x`, `/abs/x`, non-hex) are rejected before any filesystem access, that entries on disk with mismatched keys are deleted and not served, and that `delete()` removes entries from memory and disk. Verify with `uv run devops ci test tests/test_response_cache.py`. -- [ ] 1.2 Implement `is_valid_cache_key`, strict key validation before disk operations, key equality verification on disk load, and `delete()` in `src/devops_cli/ai/response_cache.py`. Update existing tests in `tests/test_response_cache.py` that used arbitrary non-hex keys. Verify with `uv run devops ci test tests/test_response_cache.py` and `uv run mypy src/devops_cli/ai/response_cache.py`. -- [ ] 1.3 Regenerate CLI documentation. Verify with `uv run devops docs generate --sync-readme` and `uv run devops docs check`. +- [x] 1.1 Write failing tests in `tests/test_response_cache.py` asserting that keys must be `llm_` followed by 64 hexadecimal characters, that malformed keys (`../x`, `/abs/x`, non-hex) are rejected before any filesystem access, that entries on disk with mismatched keys are deleted and not served, and that `delete()` removes entries from memory and disk. Verify with `uv run devops ci test tests/test_response_cache.py`. +- [x] 1.2 Implement `is_valid_cache_key`, strict key validation before disk operations, key equality verification on disk load, and `delete()` in `src/devops_cli/ai/response_cache.py`. Update existing tests in `tests/test_response_cache.py` that used arbitrary non-hex keys. Verify with `uv run devops ci test tests/test_response_cache.py` and `uv run mypy src/devops_cli/ai/response_cache.py`. +- [x] 1.3 Regenerate CLI documentation. Verify with `uv run devops docs generate --sync-readme` and `uv run devops docs check`. ## 2. Response cache configuration and singleton alignment diff --git a/src/devops_cli/ai/response_cache.py b/src/devops_cli/ai/response_cache.py index 025cdab5d5..929952293e 100644 --- a/src/devops_cli/ai/response_cache.py +++ b/src/devops_cli/ai/response_cache.py @@ -12,6 +12,11 @@ from pydantic import BaseModel, ConfigDict, Field +from devops_cli.config.constants import ( + CONST_HEX_CHARACTERS, + CONST_LLM_CACHE_KEY_PREFIX, + CONST_SHA256_HEX_LENGTH, +) from devops_cli.config.defaults import ( DEFAULT_LLM_CACHE_ENABLED, DEFAULT_LLM_CACHE_MAX_ENTRIES, @@ -145,6 +150,17 @@ def _find_starting_point_candidates( ] +def is_valid_cache_key(key: Any) -> bool: + """Validate that key is 'llm_' followed by 64 hexadecimal characters.""" + if not isinstance(key, str): + return False + expected_len = len(CONST_LLM_CACHE_KEY_PREFIX) + CONST_SHA256_HEX_LENGTH + if len(key) != expected_len or not key.startswith(CONST_LLM_CACHE_KEY_PREFIX): + return False + hex_part = key[len(CONST_LLM_CACHE_KEY_PREFIX) :] + return all(c in CONST_HEX_CHARACTERS for c in hex_part) + + class LLMResponseCache: """Multi-tiered in-memory and persistent disk cache for LLM responses.""" @@ -210,13 +226,18 @@ def generate_key( def get(self, key: str) -> CachedLLMResponse | None: """Retrieve a cached LLM response by key if valid and not expired.""" - if not self.enabled: + if not self.enabled or not is_valid_cache_key(key): return None with self._lock: # 1. Check memory cache first cached = self._memory_cache.get(key) if cached is not None: + if cached.key != key: + del self._memory_cache[key] + self._delete_disk_file(key) + self._misses += 1 + return None if cached.is_expired(self.ttl_seconds): del self._memory_cache[key] self._delete_disk_file(key) @@ -245,6 +266,14 @@ def get(self, key: str) -> CachedLLMResponse | None: self._misses += 1 return None + def delete(self, key: str) -> None: + """Delete a cache entry from memory and disk.""" + if not is_valid_cache_key(key): + return + with self._lock: + self._memory_cache.pop(key, None) + self._delete_disk_file(key) + def set( self, key: str, @@ -286,7 +315,7 @@ def set( response_model=response_model, ) - if not self.enabled: + if not self.enabled or not is_valid_cache_key(key): return entry with self._lock: @@ -374,6 +403,8 @@ def get_stats(self) -> ResponseCacheStats: def _save_to_disk(self, entry: CachedLLMResponse) -> None: """Save a single cached response entry to disk atomically.""" + if not is_valid_cache_key(entry.key): + return try: cdir = self._resolve_cache_dir() cdir.mkdir(parents=True, exist_ok=True) @@ -386,12 +417,18 @@ def _save_to_disk(self, entry: CachedLLMResponse) -> None: def _load_from_disk(self, key: str) -> CachedLLMResponse | None: """Load a cached response entry from disk if present.""" + if not is_valid_cache_key(key): + return None try: target_file = self._resolve_cache_dir() / f"{key}.json" if not target_file.is_file(): return None data = target_file.read_text(encoding="utf-8") - return CachedLLMResponse.model_validate_json(data) + entry = CachedLLMResponse.model_validate_json(data) + if entry.key != key: + self._delete_disk_file(key) + return None + return entry except Exception as exc: logger.debug("Failed to load LLM response cache file for key '%s': %s", key, exc) return None @@ -404,8 +441,16 @@ def _load_all_valid_disk_entries(self) -> list[CachedLLMResponse]: return entries for p in cdir.glob("llm_*.json"): try: + if not is_valid_cache_key(p.stem): + continue data = p.read_text(encoding="utf-8") item = CachedLLMResponse.model_validate_json(data) + if item.key != p.stem: + try: + p.unlink() + except OSError: + pass + continue if not item.is_expired(self.ttl_seconds): entries.append(item) except Exception: @@ -414,6 +459,8 @@ def _load_all_valid_disk_entries(self) -> list[CachedLLMResponse]: def _delete_disk_file(self, key: str) -> None: """Delete a single cache file on disk.""" + if not is_valid_cache_key(key): + return try: target = self._resolve_cache_dir() / f"{key}.json" if target.exists(): diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 55f9fda958..37f96b2587 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -653,6 +653,12 @@ # a Linux filesystem, which multiplies the gate's time for a workspace checked out on them. CONST_SLOW_WORKSPACE_FSTYPES: Final[frozenset[str]] = frozenset({"9p", "drvfs"}) CONST_LLM_CACHE_DIR_NAME = "llm" +# The prefix of an LLM response cache key. +CONST_LLM_CACHE_KEY_PREFIX: Final[str] = "llm_" +# The length of the SHA-256 digest in hexadecimal format. +CONST_SHA256_HEX_LENGTH: Final[int] = 64 +# The valid hexadecimal characters for cache key verification. +CONST_HEX_CHARACTERS: Final[frozenset[str]] = frozenset("0123456789abcdefABCDEF") # The incremental mypy caches of reviews, below the data cache directory, one for each reviewed # tree, Python version and environment lock (#2034). CONST_MYPY_CACHE_DIR_NAME: Final[str] = "mypy" diff --git a/tests/test_response_cache.py b/tests/test_response_cache.py index c72558b172..ae2ad919e7 100644 --- a/tests/test_response_cache.py +++ b/tests/test_response_cache.py @@ -3,6 +3,7 @@ from __future__ import annotations import functools +import hashlib import json import time from pathlib import Path @@ -35,6 +36,11 @@ def clean_cache(tmp_path: Path) -> LLMResponseCache: return cache +def _valid_test_key(tag: str) -> str: + """Return a deterministic valid 64-hex SHA-256 cache key for test usage.""" + return f"llm_{hashlib.sha256(tag.encode('utf-8')).hexdigest()}" + + def test_cache_key_generation_deterministic() -> None: """Verify deterministic SHA-256 generation across varied message shapes.""" k1 = LLMResponseCache.generate_key("ollama", "gemma4:26b", "sys-1", "user prompt") @@ -54,7 +60,7 @@ def test_cache_key_generation_deterministic() -> None: def test_cache_set_and_get_memory_and_disk(clean_cache: LLMResponseCache) -> None: """Verify storing and loading from memory and disk cache.""" - key = "llm_test_key_123" + key = _valid_test_key("test_key_123") entry = clean_cache.set( key=key, provider="ollama", @@ -93,7 +99,7 @@ def test_cache_ttl_expiration(tmp_path: Path) -> None: enabled=True, ttl_seconds=60.0, ) - key = "llm_expiring_key" + key = _valid_test_key("expiring_key") entry = short_cache.set( key=key, provider="ollama", @@ -118,7 +124,7 @@ def test_cache_ttl_expiration(tmp_path: Path) -> None: def test_starting_point_lookup_and_formatting(clean_cache: LLMResponseCache) -> None: """Verify looking up cached response by context_tag and formatting baseline starting point.""" clean_cache.set( - key="llm_item_v1", + key=_valid_test_key("item_v1"), provider="ollama", model="gemma4:26b", system="sys", @@ -151,11 +157,11 @@ def test_cache_capacity_enforcement(tmp_path: Path) -> None: enabled=True, max_entries=2, ) - small_cache.set("llm_1", "p", "m", "s", "p1", "c1") + small_cache.set(_valid_test_key("1"), "p", "m", "s", "p1", "c1") time.sleep(0.01) - small_cache.set("llm_2", "p", "m", "s", "p2", "c2") + small_cache.set(_valid_test_key("2"), "p", "m", "s", "p2", "c2") time.sleep(0.01) - small_cache.set("llm_3", "p", "m", "s", "p3", "c3") + small_cache.set(_valid_test_key("3"), "p", "m", "s", "p3", "c3") stats = small_cache.get_stats() assert stats.memory_entries <= 2 @@ -164,9 +170,11 @@ def test_cache_capacity_enforcement(tmp_path: Path) -> None: def test_cache_clear_and_stats(clean_cache: LLMResponseCache) -> None: """Verify cache clear and statistics computation.""" - clean_cache.set("llm_k1", "ollama", "gemma4:26b", "sys", "p1", "c1") - clean_cache.get("llm_k1") # hit - clean_cache.get("llm_nonexistent") # miss + k_k1 = _valid_test_key("k1") + k_nonexistent = _valid_test_key("nonexistent") + clean_cache.set(k_k1, "ollama", "gemma4:26b", "sys", "p1", "c1") + clean_cache.get(k_k1) # hit + clean_cache.get(k_nonexistent) # miss stats = clean_cache.get_stats() assert stats.hits == 1 @@ -223,11 +231,13 @@ def test_a_cache_entry_keeps_the_backend_and_model_that_served_it( prompt="prompt", content="reply", ) - store(key="llm_served", served_by="https://example.com:11434", response_model="served-model") - store(key="llm_unserved") + k_served = _valid_test_key("served") + k_unserved = _valid_test_key("unserved") + store(key=k_served, served_by="https://example.com:11434", response_model="served-model") + store(key=k_unserved) clean_cache._memory_cache.clear() - read = [clean_cache.get(key) for key in ("llm_served", "llm_unserved")] + read = [clean_cache.get(key) for key in (k_served, k_unserved)] assert [ (entry.model, entry.served_by, entry.response_model) for entry in read if entry is not None @@ -310,7 +320,7 @@ def test_llm_client_starting_point_warm_refinement( # Prime cache with an initial version tagged with context_tag clean_cache.set( - key="llm_prime_key", + key=_valid_test_key("prime_key"), provider="ollama", model="gemma4:26b", system="system prompt", @@ -390,7 +400,7 @@ def test_ai_cache_cli_commands(clean_cache: LLMResponseCache) -> None: runner = CliRunner() # Populate cache entry - clean_cache.set("llm_cmd_test", "ollama", "gemma4:26b", "sys", "prompt", "content") + clean_cache.set(_valid_test_key("cmd_test"), "ollama", "gemma4:26b", "sys", "prompt", "content") # Test status table res_status = runner.invoke(ai_app, ["cache", "status"]) @@ -433,3 +443,89 @@ def test_ai_config_append_cache_deduplication_and_migration() -> None: assert migrated_cfg.append_cache is True assert migrated_cfg.cache.append_cache is True assert "append_cache" not in migrated_cfg.model_dump(mode="json") + + +def test_cache_refuses_malformed_keys_before_file_access(clean_cache: LLMResponseCache) -> None: + """Verify keys not matching 'llm_' followed by 64 hex characters are refused.""" + invalid_keys = [ + "../escaped", + "/abs/path", + "llm_short", + "llm_" + "a" * 63, + "llm_" + "a" * 65, + "llm_" + "a" * 63 + "z", + "not_llm_" + "a" * 60, + ] + for bad_key in invalid_keys: + assert clean_cache.get(bad_key) is None + entry = clean_cache.set(bad_key, "p", "m", "s", "p", "c") + assert entry.key == bad_key + assert bad_key not in clean_cache._memory_cache + cdir = clean_cache._resolve_cache_dir() + assert not list(cdir.glob("*")) + if hasattr(clean_cache, "delete"): + clean_cache.delete(bad_key) + + +def test_loaded_entry_with_mismatched_key_is_not_served_and_deleted( + clean_cache: LLMResponseCache, +) -> None: + """Verify that a disk entry whose stored key field differs from requested key is deleted + and not served, and no file is created outside the cache directory.""" + cdir = clean_cache._resolve_cache_dir() + cdir.mkdir(parents=True, exist_ok=True) + req_key = "llm_" + "a" * 64 + + # 1. Entry stored with key field "../escaped_by_key_field" + parent_file = cdir.parent / "escaped_by_key_field.json" + if parent_file.exists(): + parent_file.unlink() + + bad_entry = { + "key": "../escaped_by_key_field", + "provider": "ollama", + "model": "m", + "system_hash": "sys", + "prompt_hash": "prompt", + "content": "malicious content", + } + target_file = cdir / f"{req_key}.json" + target_file.write_text(json.dumps(bad_entry), encoding="utf-8") + + assert clean_cache.get(req_key) is None + assert not target_file.exists() + assert not parent_file.exists() + + # 2. Entry stored with absolute key field and empty content + abs_target = Path("/tmp/abs_escaped.json") + if abs_target.exists(): + abs_target.unlink() + + bad_entry_abs = { + "key": str(abs_target.with_suffix("")), + "provider": "ollama", + "model": "m", + "system_hash": "sys", + "prompt_hash": "prompt", + "content": "", + } + target_file.write_text(json.dumps(bad_entry_abs), encoding="utf-8") + + assert clean_cache.get(req_key) is None + assert not target_file.exists() + assert not abs_target.exists() + + +def test_cache_delete_removes_entry_from_memory_and_disk( + clean_cache: LLMResponseCache, +) -> None: + """Verify delete() removes entry from memory and disk.""" + valid_key = "llm_" + "b" * 64 + clean_cache.set(valid_key, "ollama", "gemma", "sys", "prompt", "content") + assert valid_key in clean_cache._memory_cache + target_file = clean_cache._resolve_cache_dir() / f"{valid_key}.json" + assert target_file.exists() + + clean_cache.delete(valid_key) + assert valid_key not in clean_cache._memory_cache + assert not target_file.exists() From db5564a0afcfed4542d5f86f0934b5eaa689698f Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Mon, 26 Oct 2026 18:31:33 +0000 Subject: [PATCH 3/6] fix(ai): align response cache resolution with data configuration Remove obsolete dir field from response cache configuration. Derive the response cache location directly from the data cache directory. Ensure the singleton cache instance initializes from user configuration. Ensure clients with disabled caching isolate themselves from global state. --- docs/CONFIGURATION.md | 2 +- .../tasks.md | 6 +- src/devops_cli/ai/client/unified.py | 15 +- src/devops_cli/ai/response_cache.py | 32 ++++- src/devops_cli/config/defaults.py | 2 - src/devops_cli/config/settings.py | 2 - tests/conftest.py | 5 +- tests/test_data_dir_configuration.py | 2 - tests/test_response_cache.py | 130 +++++++++++++++++- 9 files changed, 158 insertions(+), 38 deletions(-) diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 3a41e0b0a6..e972e3b204 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -202,7 +202,7 @@ AI code review, multi-agent pipelines, RAG semantic search, and embeddings. | `timeout` | `Union` | - | - | Seconds each LLM request waits for its reply; `ai.tasks..timeout` sets one task's. Unset, a request waits 3600 s, and a review's analysis requests 1200 s | | `tasks` | `AITasksConfig` | `chat=AITaskOverride(provider=None, model=None, reasoning_effort=None, supports_reasoning=None, use_model_sampling=None, temperature=None, top_p=None, context_window=None, num_ctx=None, max_tokens=None, ollama_urls=None, ollama_max_parallel=None, api_base_url=None, max_retries=None, timeout=None) metadata=AITaskOverride(provider=None, model=None, reasoning_effort=None, supports_reasoning=None, use_model_sampling=None, temperature=None, top_p=None, context_window=None, num_ctx=None, max_tokens=None, ollama_urls=None, ollama_max_parallel=None, api_base_url=None, max_retries=None, timeout=None) analysis=AITaskOverride(provider=None, model=None, reasoning_effort=None, supports_reasoning=None, use_model_sampling=None, temperature=None, top_p=None, context_window=None, num_ctx=None, max_tokens=None, ollama_urls=None, ollama_max_parallel=None, api_base_url=None, max_retries=None, timeout=None) verification=AITaskOverride(provider=None, model=None, reasoning_effort=None, supports_reasoning=None, use_model_sampling=None, temperature=None, top_p=None, context_window=None, num_ctx=None, max_tokens=None, ollama_urls=None, ollama_max_parallel=None, api_base_url=None, max_retries=None, timeout=None) compose=AITaskOverride(provider=None, model=None, reasoning_effort=None, supports_reasoning=None, use_model_sampling=None, temperature=None, top_p=None, context_window=None, num_ctx=None, max_tokens=None, ollama_urls=None, ollama_max_parallel=None, api_base_url=None, max_retries=None, timeout=None) embedding=AITaskOverride(provider=None, model='qwen3-embedding:0.6b', reasoning_effort=None, supports_reasoning=None, use_model_sampling=None, temperature=None, top_p=None, context_window=None, num_ctx=None, max_tokens=None, ollama_urls=None, ollama_max_parallel=None, api_base_url=None, max_retries=None, timeout=None)` | - | - | | `rag` | `AIRAGConfig` | `enabled=True top_k=5 score_threshold=0.35 chunk_size=2400 chunk_overlap=240` | - | - | -| `cache` | `AICacheConfig` | `enabled=True dir=PosixPath('.data/cache/llm') ttl_seconds=604800 max_entries=1000 append_cache=False` | - | - | +| `cache` | `AICacheConfig` | `enabled=True ttl_seconds=604800 max_entries=1000 append_cache=False` | - | - | | `task_name` | `Union` | - | - | - | ## Open WebUI Configuration (`open_webui`) diff --git a/openspec/changes/1014-response-cache-directory-traversal/tasks.md b/openspec/changes/1014-response-cache-directory-traversal/tasks.md index 650db4909f..7c4df214d7 100644 --- a/openspec/changes/1014-response-cache-directory-traversal/tasks.md +++ b/openspec/changes/1014-response-cache-directory-traversal/tasks.md @@ -8,9 +8,9 @@ ## 2. Response cache configuration and singleton alignment -- [ ] 2.1 Write failing tests in `tests/test_response_cache.py` asserting that the cache directory resolves under `/cache/llm`, that `devops ai cache status` and `devops ai cache clear` read settings, and that a client initialized with `cache_enabled=False` neither reads nor writes the cache even when a singleton cache exists. Verify with `uv run devops ci test tests/test_response_cache.py`. -- [ ] 2.2 Remove `dir` from `AICacheConfig` in `src/devops_cli/config/settings.py` and remove `DEFAULT_LLM_CACHE_DATA_DIR` in `src/devops_cli/config/defaults.py`. Update `get_llm_response_cache()` and `_resolve_llm_cache()` in `src/devops_cli/ai/client/unified.py` to build from settings and isolate disabled clients. Update `isolate_llm_response_cache` in `tests/conftest.py` to build via settings and request `isolate_data_dir`. Verify with `uv run devops ci test tests/test_response_cache.py tests/test_data_dir_configuration.py`. -- [ ] 2.3 Regenerate CLI documentation. Verify with `uv run devops docs generate --sync-readme` and `uv run devops docs check`. +- [x] 2.1 Write failing tests in `tests/test_response_cache.py` asserting that the cache directory resolves under `/cache/llm`, that `devops ai cache status` and `devops ai cache clear` read settings, and that a client initialized with `cache_enabled=False` neither reads nor writes the cache even when a singleton cache exists. Verify with `uv run devops ci test tests/test_response_cache.py`. +- [x] 2.2 Remove `dir` from `AICacheConfig` in `src/devops_cli/config/settings.py` and remove `DEFAULT_LLM_CACHE_DATA_DIR` in `src/devops_cli/config/defaults.py`. Update `get_llm_response_cache()` and `_resolve_llm_cache()` in `src/devops_cli/ai/client/unified.py` to build from settings and isolate disabled clients. Update `isolate_llm_response_cache` in `tests/conftest.py` to build via settings and request `isolate_data_dir`. Verify with `uv run devops ci test tests/test_response_cache.py tests/test_data_dir_configuration.py`. +- [x] 2.3 Regenerate CLI documentation. Verify with `uv run devops docs generate --sync-readme` and `uv run devops docs check`. ## 3. Client caching exclusions, rejected entry cleanup, and structured schema enforcement diff --git a/src/devops_cli/ai/client/unified.py b/src/devops_cli/ai/client/unified.py index 83132e4d99..fd0d943d7b 100644 --- a/src/devops_cli/ai/client/unified.py +++ b/src/devops_cli/ai/client/unified.py @@ -6,7 +6,6 @@ import threading import time from collections.abc import Callable, Generator -from pathlib import Path from typing import TYPE_CHECKING, Any from urllib.parse import urlparse, urlsplit @@ -169,12 +168,6 @@ def _resolve_llm_cache(config: AIConfig | None, cache_enabled: bool | None) -> A cache_enabled = getattr(cache_cfg, "enabled", True) if cache_cfg is not None else True if not isinstance(cache_enabled, bool): cache_enabled = True - cache_dir_raw = getattr(cache_cfg, "dir", None) if cache_cfg is not None else None - cache_dir: Path | None = None - if isinstance(cache_dir_raw, Path): - cache_dir = cache_dir_raw - elif isinstance(cache_dir_raw, str): - cache_dir = Path(cache_dir_raw) cache_ttl = getattr(cache_cfg, "ttl_seconds", 86400 * 7) if cache_cfg is not None else 86400 * 7 if not isinstance(cache_ttl, (int, float)): cache_ttl = 86400 * 7 @@ -186,17 +179,11 @@ def _resolve_llm_cache(config: AIConfig | None, cache_enabled: bool | None) -> A if not cache_enabled: return LLMResponseCache( - cache_dir=cache_dir, enabled=False, ttl_seconds=cache_ttl, max_entries=cache_max, ) - return get_llm_response_cache( - cache_dir=cache_dir, - enabled=cache_enabled, - ttl_seconds=cache_ttl, - max_entries=cache_max, - ) + return get_llm_response_cache() class LLMClient( diff --git a/src/devops_cli/ai/response_cache.py b/src/devops_cli/ai/response_cache.py index 929952293e..084d4e0249 100644 --- a/src/devops_cli/ai/response_cache.py +++ b/src/devops_cli/ai/response_cache.py @@ -491,19 +491,37 @@ def _enforce_capacity(self) -> None: def get_llm_response_cache( cache_dir: Path | None = None, - enabled: bool = DEFAULT_LLM_CACHE_ENABLED, - ttl_seconds: float = float(DEFAULT_LLM_CACHE_TTL_SECONDS), - max_entries: int = DEFAULT_LLM_CACHE_MAX_ENTRIES, + enabled: bool | None = None, + ttl_seconds: float | None = None, + max_entries: int | None = None, ) -> LLMResponseCache: """Retrieve global singleton LLM response cache instance.""" global _GLOBAL_LLM_CACHE with _CACHE_LOCK: if _GLOBAL_LLM_CACHE is None: + from devops_cli.config.constants import CONST_LLM_CACHE_DIR_NAME + from devops_cli.config.settings import load_settings + + settings = load_settings() + resolved_cache_dir = ( + cache_dir + if cache_dir is not None + else settings.data.cache_dir / CONST_LLM_CACHE_DIR_NAME + ) + resolved_enabled = enabled if enabled is not None else settings.ai.cache.enabled + resolved_ttl = ( + float(ttl_seconds) + if ttl_seconds is not None + else float(settings.ai.cache.ttl_seconds) + ) + resolved_max_entries = ( + max_entries if max_entries is not None else settings.ai.cache.max_entries + ) _GLOBAL_LLM_CACHE = LLMResponseCache( - cache_dir=cache_dir, - enabled=enabled, - ttl_seconds=ttl_seconds, - max_entries=max_entries, + cache_dir=resolved_cache_dir, + enabled=resolved_enabled, + ttl_seconds=resolved_ttl, + max_entries=resolved_max_entries, ) return _GLOBAL_LLM_CACHE diff --git a/src/devops_cli/config/defaults.py b/src/devops_cli/config/defaults.py index 33d3c7207e..052fbb3b64 100644 --- a/src/devops_cli/config/defaults.py +++ b/src/devops_cli/config/defaults.py @@ -15,7 +15,6 @@ CONST_CONFIG_DIR, CONST_DOCS_DIR_PATH, CONST_FEEDBACK_DATASET_NAME, - CONST_LLM_CACHE_DIR_NAME, CONST_LOGS_DIR_NAME, CONST_MODELS_DIR_NAME, CONST_RAG_DIR_NAME, @@ -33,7 +32,6 @@ DEFAULT_LOGS_DATA_DIR = DEFAULT_DATA_DIR / CONST_LOGS_DIR_NAME DEFAULT_MODELS_DATA_DIR = DEFAULT_DATA_DIR / CONST_MODELS_DIR_NAME DEFAULT_CACHE_DATA_DIR = DEFAULT_DATA_DIR / CONST_CACHE_DIR_NAME -DEFAULT_LLM_CACHE_DATA_DIR = DEFAULT_CACHE_DATA_DIR / CONST_LLM_CACHE_DIR_NAME DEFAULT_BENCHMARKS_DATA_DIR = DEFAULT_DATA_DIR / CONST_BENCHMARKS_DIR_NAME DEFAULT_AUDIT_LOG_PATH = DEFAULT_LOGS_DATA_DIR / CONST_AUDIT_LOG_NAME DEFAULT_FEEDBACK_DATASET_PATH = DEFAULT_DATA_DIR / CONST_FEEDBACK_DATASET_NAME diff --git a/src/devops_cli/config/settings.py b/src/devops_cli/config/settings.py index f513d4c77a..febb31affb 100644 --- a/src/devops_cli/config/settings.py +++ b/src/devops_cli/config/settings.py @@ -72,7 +72,6 @@ DEFAULT_DATA_DIR, DEFAULT_FEEDBACK_DATASET_PATH, DEFAULT_HTTP_TIMEOUT_SECONDS, - DEFAULT_LLM_CACHE_DATA_DIR, DEFAULT_LLM_CACHE_ENABLED, DEFAULT_LLM_CACHE_MAX_ENTRIES, DEFAULT_LLM_CACHE_TTL_SECONDS, @@ -475,7 +474,6 @@ class AIRAGConfig(BaseModel): class AICacheConfig(BaseModel): model_config = ConfigDict(frozen=False, validate_assignment=True, hide_input_in_errors=True) enabled: bool = DEFAULT_LLM_CACHE_ENABLED - dir: Path = DEFAULT_LLM_CACHE_DATA_DIR ttl_seconds: int = Field(default=DEFAULT_LLM_CACHE_TTL_SECONDS, gt=0) max_entries: int = Field(default=DEFAULT_LLM_CACHE_MAX_ENTRIES, gt=0) append_cache: bool = False diff --git a/tests/conftest.py b/tests/conftest.py index 229ea0820d..709f7d84a0 100755 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -724,7 +724,7 @@ def reset_dry_run_state(): @pytest.fixture(autouse=True) -def isolate_llm_response_cache(tmp_path: Path): +def isolate_llm_response_cache(isolate_data_dir: Path): """Ensure LLM response cache is isolated per test to prevent cross-test cache hits.""" from devops_cli.ai.response_cache import ( get_llm_response_cache, @@ -732,8 +732,7 @@ def isolate_llm_response_cache(tmp_path: Path): ) reset_llm_response_cache() - test_cache_dir = tmp_path / "test_llm_cache" - get_llm_response_cache(cache_dir=test_cache_dir, enabled=True) + get_llm_response_cache() yield reset_llm_response_cache() diff --git a/tests/test_data_dir_configuration.py b/tests/test_data_dir_configuration.py index 13f7b51a18..c860c290eb 100644 --- a/tests/test_data_dir_configuration.py +++ b/tests/test_data_dir_configuration.py @@ -27,7 +27,6 @@ def test_default_data_constants_and_settings() -> None: DEFAULT_CACHE_DATA_DIR, DEFAULT_DATA_DIR, DEFAULT_FEEDBACK_DATASET_PATH, - DEFAULT_LLM_CACHE_DATA_DIR, DEFAULT_LOGS_DATA_DIR, DEFAULT_MODELS_DATA_DIR, DEFAULT_RAG_DATA_DIR, @@ -42,7 +41,6 @@ def test_default_data_constants_and_settings() -> None: assert DEFAULT_LOGS_DATA_DIR == Path(".data/logs") assert DEFAULT_MODELS_DATA_DIR == Path(".data/models") assert DEFAULT_CACHE_DATA_DIR == Path(".data/cache") - assert DEFAULT_LLM_CACHE_DATA_DIR == Path(".data/cache/llm") assert DEFAULT_BENCHMARKS_DATA_DIR == Path(".data/benchmarks") assert DEFAULT_RAG_DATA_DIR == Path(".data/rag") assert DEFAULT_AUDIT_LOG_PATH == Path(".data/logs/audit.jsonl") diff --git a/tests/test_response_cache.py b/tests/test_response_cache.py index ae2ad919e7..99d71bead7 100644 --- a/tests/test_response_cache.py +++ b/tests/test_response_cache.py @@ -233,7 +233,11 @@ def test_a_cache_entry_keeps_the_backend_and_model_that_served_it( ) k_served = _valid_test_key("served") k_unserved = _valid_test_key("unserved") - store(key=k_served, served_by="https://example.com:11434", response_model="served-model") + store( + key=k_served, + served_by="https://example.com:11434", + response_model="served-model", + ) store(key=k_unserved) clean_cache._memory_cache.clear() @@ -264,7 +268,9 @@ def _served_gateway_client( } headers = {CONST_AI_GATEWAY_SERVED_BY_HEADER: served_by} sent = route_client( - client, monkeypatch, lambda _request: httpx2.Response(200, json=body, headers=headers) + client, + monkeypatch, + lambda _request: httpx2.Response(200, json=body, headers=headers), ) return client, sent @@ -302,7 +308,12 @@ def test_the_backend_a_cached_gateway_reply_records_carries_no_credentials( text = entry_file.read_text(encoding="utf-8") entry = json.loads(text) - assert ("secret" in text, entry["served_by"], entry["response_model"], entry["model"]) == ( + assert ( + "secret" in text, + entry["served_by"], + entry["response_model"], + entry["model"], + ) == ( False, "https://example.com:11434", "served-model", @@ -445,7 +456,9 @@ def test_ai_config_append_cache_deduplication_and_migration() -> None: assert "append_cache" not in migrated_cfg.model_dump(mode="json") -def test_cache_refuses_malformed_keys_before_file_access(clean_cache: LLMResponseCache) -> None: +def test_cache_refuses_malformed_keys_before_file_access( + clean_cache: LLMResponseCache, +) -> None: """Verify keys not matching 'llm_' followed by 64 hex characters are refused.""" invalid_keys = [ "../escaped", @@ -529,3 +542,112 @@ def test_cache_delete_removes_entry_from_memory_and_disk( clean_cache.delete(valid_key) assert valid_key not in clean_cache._memory_cache assert not target_file.exists() + + +def test_response_cache_resolves_under_data_cache_dir( + isolate_data_dir: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Verify that get_llm_response_cache resolves under /cache/llm and AICacheConfig has no dir.""" + from devops_cli.config.constants import CONST_LLM_CACHE_DIR_NAME + from devops_cli.config.settings import AICacheConfig, reset_settings_cache + + assert "dir" not in AICacheConfig.model_fields + + reset_llm_response_cache() + reset_settings_cache() + custom_data = isolate_data_dir / "custom_data_dir" + monkeypatch.setenv("DEVOPS_CLI_DATA_DIR", str(custom_data)) + reset_settings_cache() + + cache = get_llm_response_cache() + expected_cache_dir = custom_data / "cache" / CONST_LLM_CACHE_DIR_NAME + assert cache.cache_dir == expected_cache_dir + + +def test_ai_cache_status_and_clear_read_settings( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Verify devops ai cache status and clear read settings and inspect /cache/llm.""" + from typer.testing import CliRunner + + from devops_cli.commands.ai import app as ai_app + from devops_cli.config.settings import reset_settings_cache + + data_dir = tmp_path / "custom_data" + cfg_file = tmp_path / "config.yaml" + cfg_file.write_text( + "ai:\n" + " provider: ollama\n" + " cache:\n" + " enabled: false\n" + " max_entries: 777\n" + " ttl_seconds: 9999\n", + encoding="utf-8", + ) + monkeypatch.setenv("DEVOPS_CLI_DATA_DIR", str(data_dir)) + monkeypatch.setenv("DEVOPS_CLI_CONFIG", str(cfg_file)) + monkeypatch.setattr("devops_cli.config.settings.CONFIG_PATH", cfg_file) + reset_llm_response_cache() + reset_settings_cache() + + runner = CliRunner() + res_status = runner.invoke(ai_app, ["cache", "status", "--format", "json"]) + assert res_status.exit_code == 0 + data = json.loads(res_status.output) + assert data["enabled"] is False + assert data["max_entries"] == 777 + assert data["ttl_seconds"] == 9999 + expected_dir = data_dir / "cache" / "llm" + assert Path(data["cache_directory"]) == expected_dir + + expected_dir.mkdir(parents=True, exist_ok=True) + test_key = _valid_test_key("clear_target") + file_path = expected_dir / f"{test_key}.json" + file_path.write_text("{}", encoding="utf-8") + assert file_path.exists() + + res_clear = runner.invoke(ai_app, ["cache", "clear"]) + assert res_clear.exit_code == 0 + assert not file_path.exists() + + +def test_client_with_cache_disabled_never_reads_or_writes_cache( + isolate_data_dir: Path, monkeypatch: pytest.MonkeyPatch, public_dns: str +) -> None: + """Verify that LLMClient with cache_enabled=False neither reads nor writes the cache even when + a global singleton cache exists and is enabled.""" + from devops_cli.ai.client import LLMClient + from devops_cli.config.settings import AIConfig + from tests.llm_stream_fakes import route_client + + reset_llm_response_cache() + cache_dir = isolate_data_dir / "cache" / "llm" + singleton = get_llm_response_cache(cache_dir=cache_dir, enabled=True) + + config = AIConfig( + provider="gateway", model="demo-model", gateway_url="http://example.com:4000/v1" + ) + client = LLMClient(config=config, api_key="sk", cache_enabled=False) + + body = { + "model": "demo-model", + "choices": [{"message": {"content": "fresh reply"}, "finish_reason": "stop"}], + "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}, + } + sent = route_client(client, monkeypatch, lambda _req: httpx2.Response(200, json=body)) + + res1 = client.chat("system", "hello") + res2 = client.chat("system", "hello") + + assert len(sent) == 2 + assert res1.cached is False + assert res2.cached is False + + stats = singleton.get_stats() + assert stats.hits == 0 + assert stats.misses == 0 + assert stats.memory_entries == 0 + assert stats.disk_entries == 0 + + cache_files = list(cache_dir.glob("*.json")) + assert cache_files == [] From f06cc64b116bbb6d62099ba85132a8ad6ac40f40 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Mon, 26 Oct 2026 18:36:14 +0000 Subject: [PATCH 4/6] fix(ai): delete rejected cache entries and bypass caching for empty responses Delete cached entries from memory and disk when validator rejects content. Do not cache empty or whitespace responses that contain thinking blocks. Enforce strict schema validation and required fields in ModelProposal. --- .../tasks.md | 6 +- src/devops_cli/ai/client/unified.py | 13 +++-- src/devops_cli/roadmap/intake_model.py | 8 +-- tests/test_ai_client_structured.py | 27 ++++++++- tests/test_response_cache.py | 58 +++++++++++++++++++ tests/test_review_untrusted_tree.py | 38 ++++++++++++ 6 files changed, 138 insertions(+), 12 deletions(-) diff --git a/openspec/changes/1014-response-cache-directory-traversal/tasks.md b/openspec/changes/1014-response-cache-directory-traversal/tasks.md index 7c4df214d7..38b8950051 100644 --- a/openspec/changes/1014-response-cache-directory-traversal/tasks.md +++ b/openspec/changes/1014-response-cache-directory-traversal/tasks.md @@ -14,9 +14,9 @@ ## 3. Client caching exclusions, rejected entry cleanup, and structured schema enforcement -- [ ] 3.1 Write failing tests in `tests/test_response_cache.py`, `tests/test_ai_client_structured.py`, and `tests/test_review_untrusted_tree.py` asserting that empty content replies with thinking blocks are not cached, that rejected lookups delete the entry from memory and disk, that `ModelProposal` forbids extra fields and requires `priority`, `value`, and `effort`, that structured replies failing schema validation are not cached, and that a clone tracking `.data/cache/llm/` files does not serve planted replies. Verify with `uv run devops ci test tests/test_response_cache.py tests/test_ai_client_structured.py tests/test_review_untrusted_tree.py`. -- [ ] 3.2 Update `_check_chat_cache` and `_handle_successful_chat_dispatch` in `src/devops_cli/ai/client/unified.py` to delete rejected lookup entries and bypass caching for empty responses. Update `ModelProposal` in `src/devops_cli/roadmap/intake_model.py` with `extra="forbid"` and required fields. Verify with `uv run devops ci test tests/test_response_cache.py tests/test_ai_client_structured.py tests/test_roadmap_intake.py tests/test_review_untrusted_tree.py`. -- [ ] 3.3 Regenerate CLI documentation and verify full suite. Verify with `uv run devops docs generate --sync-readme`, `uv run devops docs check`, and `uv run devops ci`. +- [x] 3.1 Write failing tests in `tests/test_response_cache.py`, `tests/test_ai_client_structured.py`, and `tests/test_review_untrusted_tree.py` asserting that empty content replies with thinking blocks are not cached, that rejected lookups delete the entry from memory and disk, that `ModelProposal` forbids extra fields and requires `priority`, `value`, and `effort`, that structured replies failing schema validation are not cached, and that a clone tracking `.data/cache/llm/` files does not serve planted replies. Verify with `uv run devops ci test tests/test_response_cache.py tests/test_ai_client_structured.py tests/test_review_untrusted_tree.py`. +- [x] 3.2 Update `_check_chat_cache` and `_handle_successful_chat_dispatch` in `src/devops_cli/ai/client/unified.py` to delete rejected lookup entries and bypass caching for empty responses. Update `ModelProposal` in `src/devops_cli/roadmap/intake_model.py` with `extra="forbid"` and required fields. Verify with `uv run devops ci test tests/test_response_cache.py tests/test_ai_client_structured.py tests/test_roadmap_intake.py tests/test_review_untrusted_tree.py`. +- [x] 3.3 Regenerate CLI documentation and verify full suite. Verify with `uv run devops docs generate --sync-readme`, `uv run devops docs check`, and `uv run devops ci`. ## Workflow follow-up diff --git a/src/devops_cli/ai/client/unified.py b/src/devops_cli/ai/client/unified.py index fd0d943d7b..7948cb0f0d 100644 --- a/src/devops_cli/ai/client/unified.py +++ b/src/devops_cli/ai/client/unified.py @@ -632,9 +632,10 @@ def _check_chat_cache( ) -> LLMResponse | None: """Check cache for existing valid response.""" cached_entry = self._cache.get(cache_key) - if cached_entry is None or not self._validate_response_text( - cached_entry.content, validator - ): + if cached_entry is None: + return None + if not self._validate_response_text(cached_entry.content, validator): + self._cache.delete(cache_key) return None span_h.set_attribute("llm.cached", True) span_h.set_attribute("llm.wall_seconds", 0.0) @@ -685,7 +686,11 @@ def _handle_successful_chat_dispatch( identical call reaches the provider again rather than the cut reply. """ self._record_chat_telemetry(span_h, res) - if use_cache and res.finish_reason not in CONST_UNCACHED_FINISH_REASONS: + if ( + use_cache + and res.finish_reason not in CONST_UNCACHED_FINISH_REASONS + and bool(res.content and res.content.strip()) + ): self._cache_chat_entry(cache_key, system, out_messages, res, context_tag) return res diff --git a/src/devops_cli/roadmap/intake_model.py b/src/devops_cli/roadmap/intake_model.py index 1458b1d603..0026be9e51 100644 --- a/src/devops_cli/roadmap/intake_model.py +++ b/src/devops_cli/roadmap/intake_model.py @@ -61,7 +61,7 @@ class ModelProposal(BaseModel): both items ask for before it names an original (#1755). """ - model_config = ConfigDict(extra="ignore") + model_config = ConfigDict(extra="forbid") shared_change: str = "" # A number, or text such as "#740": code reads it, and `related_to`, against the shortlist. @@ -71,11 +71,11 @@ class ModelProposal(BaseModel): related_reason: str = "" type: str = "" type_reason: str = "" - priority: str = "" + priority: str priority_reason: str = "" - value: str = "" + value: str value_reason: str = "" - effort: str = "" + effort: str effort_reason: str = "" evidence: ModelEvidence | None = None evidence_reason: str = "" diff --git a/tests/test_ai_client_structured.py b/tests/test_ai_client_structured.py index 4300e3e71d..90e869d3cc 100644 --- a/tests/test_ai_client_structured.py +++ b/tests/test_ai_client_structured.py @@ -326,7 +326,9 @@ def _sent_system() -> str: def _cached_texts(tmp_path: Path) -> list[str]: """The reply each entry the per-test response cache wrote to disk holds.""" - files = (tmp_path / "test_llm_cache").rglob("*.json") + from devops_cli.ai.response_cache import get_llm_response_cache + + files = get_llm_response_cache()._resolve_cache_dir().rglob("*.json") return [json.loads(path.read_text(encoding="utf-8"))["content"] for path in files] @@ -544,3 +546,26 @@ def test_the_validation_error_holds_no_key_the_model_invented( False, False, ) + + +def test_model_proposal_schema_forbids_extra_and_requires_fields() -> None: + """Verify ModelProposal forbids extra fields and requires priority, value, and effort.""" + from pydantic import ValidationError + + from devops_cli.roadmap.intake_model import ModelProposal + + assert ModelProposal.model_config.get("extra") == "forbid" + + # Extra fields are rejected + with pytest.raises(ValidationError): + ModelProposal.model_validate( + {"priority": "P1", "value": "High", "effort": "Low", "unrecognized_extra": "bad"} + ) + + # Missing required fields (priority, value, effort) are rejected + with pytest.raises(ValidationError): + ModelProposal.model_validate({"value": "High", "effort": "Low"}) + with pytest.raises(ValidationError): + ModelProposal.model_validate({"priority": "P1", "effort": "Low"}) + with pytest.raises(ValidationError): + ModelProposal.model_validate({"priority": "P1", "value": "High"}) diff --git a/tests/test_response_cache.py b/tests/test_response_cache.py index 99d71bead7..6971b5e9bc 100644 --- a/tests/test_response_cache.py +++ b/tests/test_response_cache.py @@ -651,3 +651,61 @@ def test_client_with_cache_disabled_never_reads_or_writes_cache( cache_files = list(cache_dir.glob("*.json")) assert cache_files == [] + + +def test_empty_content_with_thinking_is_not_cached( + isolate_data_dir: Path, monkeypatch: pytest.MonkeyPatch, public_dns: str +) -> None: + """Verify that an LLM response with empty content and thinking blocks is returned to the + caller but is never saved to the response cache.""" + reset_llm_response_cache() + cache_dir = isolate_data_dir / "cache" / "llm" + cache = get_llm_response_cache(cache_dir=cache_dir, enabled=True) + + config = AIConfig( + provider="gateway", model="demo-model", gateway_url="http://example.com:4000/v1" + ) + client = LLMClient(config=config, api_key="sk") + + body = { + "model": "demo-model", + "choices": [ + { + "message": {"content": " ", "reasoning_content": "deep thoughts"}, + "finish_reason": "stop", + } + ], + "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}, + } + route_client(client, monkeypatch, lambda _req: httpx2.Response(200, json=body)) + + res = client.chat("system", "prompt") + assert res.content == " " + assert res.thinking == "deep thoughts" + assert res.cached is False + + stats = cache.get_stats() + assert stats.disk_entries == 0 + assert stats.memory_entries == 0 + assert list(cache_dir.glob("*.json")) == [] + + +def test_check_chat_cache_deletes_rejected_entry(clean_cache: LLMResponseCache) -> None: + """Verify that when a cached response fails validator validation during _check_chat_cache, + the entry is purged from both in-memory cache and disk.""" + from unittest.mock import MagicMock + + config = AIConfig( + provider="gateway", model="demo-model", gateway_url="http://example.com:4000/v1" + ) + client = LLMClient(config=config, api_key="sk") + client._cache = clean_cache + valid_k = _valid_test_key("rejected_lookup") + clean_cache.set(valid_k, "gateway", "demo-model", "sys", "prompt", "rejected text") + assert clean_cache.get(valid_k) is not None + assert (clean_cache._resolve_cache_dir() / f"{valid_k}.json").exists() + + res = client._check_chat_cache(valid_k, lambda text: False, MagicMock()) + assert res is None + assert clean_cache.get(valid_k) is None + assert not (clean_cache._resolve_cache_dir() / f"{valid_k}.json").exists() diff --git a/tests/test_review_untrusted_tree.py b/tests/test_review_untrusted_tree.py index b639e78963..75a655c528 100644 --- a/tests/test_review_untrusted_tree.py +++ b/tests/test_review_untrusted_tree.py @@ -855,3 +855,41 @@ def test_an_installed_devops_cli_trusts_no_repository( exit_code, gateways, ) == ([False, False], 0, [_USER_GATEWAY]) + + +def test_untrusted_tree_planted_cache_is_never_served( + hostile_repo: Path, user_level: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Verify that a hostile repository tracking planted files under .data/cache/llm/ + is never read by the response cache during a review in that untrusted tree.""" + import hashlib + + from devops_cli.ai.response_cache import get_llm_response_cache, reset_llm_response_cache + + planted_dir = hostile_repo / ".data" / "cache" / "llm" + planted_dir.mkdir(parents=True, exist_ok=True) + planted_key = "llm_" + hashlib.sha256(b"hostile_prompt").hexdigest() + planted_file = planted_dir / f"{planted_key}.json" + planted_file.write_text( + json.dumps( + { + "key": planted_key, + "provider": "gateway", + "model": "demo-model", + "system_hash": "sys", + "prompt_hash": "prompt", + "content": "PLANTED MALICIOUS FINDINGS", + } + ), + encoding="utf-8", + ) + + def check_cache(_: Settings) -> str | None: + reset_llm_response_cache() + cache = get_llm_response_cache() + res = cache.get(planted_key) + return res.content if res is not None else None + + exit_code, [content] = _seen_by_a_review(hostile_repo, check_cache, monkeypatch) + assert exit_code == 0 + assert content is None From 74bd23705019cc2509e21525b36d5160d1642865 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Mon, 26 Oct 2026 18:42:46 +0000 Subject: [PATCH 5/6] test(ai): align test cache inspections with data directory isolation Update review group analysis tests to inspect isolated cache directory. Update telemetry instruments test to use valid cache key format. Avoid hardcoded temporary directory path in response cache test. --- tests/test_response_cache.py | 2 +- tests/test_review_group_analysis.py | 4 +++- tests/test_telemetry_instruments.py | 6 ++++-- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/tests/test_response_cache.py b/tests/test_response_cache.py index 6971b5e9bc..1d320c2e55 100644 --- a/tests/test_response_cache.py +++ b/tests/test_response_cache.py @@ -510,7 +510,7 @@ def test_loaded_entry_with_mismatched_key_is_not_served_and_deleted( assert not parent_file.exists() # 2. Entry stored with absolute key field and empty content - abs_target = Path("/tmp/abs_escaped.json") + abs_target = (cdir.parent / "abs_escaped.json").resolve() if abs_target.exists(): abs_target.unlink() diff --git a/tests/test_review_group_analysis.py b/tests/test_review_group_analysis.py index 9c72a0f538..7383a6b14b 100644 --- a/tests/test_review_group_analysis.py +++ b/tests/test_review_group_analysis.py @@ -1643,7 +1643,9 @@ def _analyze_plan(client: LLMClient) -> tuple[Any, list[str], bool]: def _cache_entries(tmp_path: Path) -> list[dict[str, Any]]: """The entries the per-test response cache wrote to disk.""" - files = (tmp_path / "test_llm_cache").rglob("*.json") + from devops_cli.ai.response_cache import get_llm_response_cache + + files = get_llm_response_cache()._resolve_cache_dir().rglob("*.json") return [json.loads(path.read_text(encoding="utf-8")) for path in files] diff --git a/tests/test_telemetry_instruments.py b/tests/test_telemetry_instruments.py index 9693321e33..9b7d2f8a5d 100644 --- a/tests/test_telemetry_instruments.py +++ b/tests/test_telemetry_instruments.py @@ -735,9 +735,11 @@ def test_response_cache_lookups_and_writes_send_no_metric_of_their_own( ) -> None: """Verify a cache write, hit and miss send nothing: the requests counter's `cached` label carries the hits, and a gauge of 1 from a short-lived process counted nothing (#816).""" + valid_key = "llm_" + "a" * 64 + missing_key = "llm_" + "b" * 64 cache = get_llm_response_cache() - cache.set("llm_key", "openai", "gpt-4o", "system", "user", "reply") - lookups = (cache.get("llm_key") is not None, cache.get("llm_missing") is None) + cache.set(valid_key, "openai", "gpt-4o", "system", "user", "reply") + lookups = (cache.get(valid_key) is not None, cache.get(missing_key) is None) assert (lookups, captured.metrics) == ((True, True), []) From c0892adb1e0875f7bde945c7ed10474027655ccd Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Mon, 26 Oct 2026 18:36:41 +0000 Subject: [PATCH 6/6] chore(openspec): archive 1014-response-cache-directory-traversal Archive OpenSpec change 1014-response-cache-directory-traversal. Promote the llm-response-cache specification. --- .../.openspec.yaml | 0 .../design.md | 0 .../proposal.md | 0 .../specs/llm-response-cache/spec.md | 0 .../tasks.md | 0 openspec/specs/llm-response-cache/spec.md | 45 +++++++++++++++++++ 6 files changed, 45 insertions(+) rename openspec/changes/{1014-response-cache-directory-traversal => archive/2026-10-26-1014-response-cache-directory-traversal}/.openspec.yaml (100%) rename openspec/changes/{1014-response-cache-directory-traversal => archive/2026-10-26-1014-response-cache-directory-traversal}/design.md (100%) rename openspec/changes/{1014-response-cache-directory-traversal => archive/2026-10-26-1014-response-cache-directory-traversal}/proposal.md (100%) rename openspec/changes/{1014-response-cache-directory-traversal => archive/2026-10-26-1014-response-cache-directory-traversal}/specs/llm-response-cache/spec.md (100%) rename openspec/changes/{1014-response-cache-directory-traversal => archive/2026-10-26-1014-response-cache-directory-traversal}/tasks.md (100%) create mode 100644 openspec/specs/llm-response-cache/spec.md diff --git a/openspec/changes/1014-response-cache-directory-traversal/.openspec.yaml b/openspec/changes/archive/2026-10-26-1014-response-cache-directory-traversal/.openspec.yaml similarity index 100% rename from openspec/changes/1014-response-cache-directory-traversal/.openspec.yaml rename to openspec/changes/archive/2026-10-26-1014-response-cache-directory-traversal/.openspec.yaml diff --git a/openspec/changes/1014-response-cache-directory-traversal/design.md b/openspec/changes/archive/2026-10-26-1014-response-cache-directory-traversal/design.md similarity index 100% rename from openspec/changes/1014-response-cache-directory-traversal/design.md rename to openspec/changes/archive/2026-10-26-1014-response-cache-directory-traversal/design.md diff --git a/openspec/changes/1014-response-cache-directory-traversal/proposal.md b/openspec/changes/archive/2026-10-26-1014-response-cache-directory-traversal/proposal.md similarity index 100% rename from openspec/changes/1014-response-cache-directory-traversal/proposal.md rename to openspec/changes/archive/2026-10-26-1014-response-cache-directory-traversal/proposal.md diff --git a/openspec/changes/1014-response-cache-directory-traversal/specs/llm-response-cache/spec.md b/openspec/changes/archive/2026-10-26-1014-response-cache-directory-traversal/specs/llm-response-cache/spec.md similarity index 100% rename from openspec/changes/1014-response-cache-directory-traversal/specs/llm-response-cache/spec.md rename to openspec/changes/archive/2026-10-26-1014-response-cache-directory-traversal/specs/llm-response-cache/spec.md diff --git a/openspec/changes/1014-response-cache-directory-traversal/tasks.md b/openspec/changes/archive/2026-10-26-1014-response-cache-directory-traversal/tasks.md similarity index 100% rename from openspec/changes/1014-response-cache-directory-traversal/tasks.md rename to openspec/changes/archive/2026-10-26-1014-response-cache-directory-traversal/tasks.md diff --git a/openspec/specs/llm-response-cache/spec.md b/openspec/specs/llm-response-cache/spec.md new file mode 100644 index 0000000000..a742baf2e8 --- /dev/null +++ b/openspec/specs/llm-response-cache/spec.md @@ -0,0 +1,45 @@ +# llm-response-cache Specification + +## Purpose +Provides secure persistent caching for LLM responses, ensuring strict directory isolation and preventing malicious traversal attacks. + +## Requirements + +### Requirement: Cache keys are validated before file access +The response cache SHALL accept only keys that begin with `llm_` followed by 64 hexadecimal characters. The cache SHALL reject any malformed key before accessing or modifying the filesystem. + +#### Scenario: Malformed key rejected +- **WHEN** a caller requests or stores an entry with a key that contains directory traversal sequences or non-hexadecimal characters +- **THEN** the cache rejects the operation without accessing or writing files + +### Requirement: Loaded entries must match requested keys +The response cache SHALL verify that loaded entries contain a key identical to the requested key. If the stored key in the file differs from the requested key, the cache SHALL delete the disk file and return no entry. + +#### Scenario: Stored key mismatch +- **WHEN** a cached JSON file on disk contains a key that differs from the requested key +- **THEN** the cache deletes the file on disk and returns a cache miss + +### Requirement: Cache directory resolves under data directory +The response cache SHALL resolve its storage directory under `/cache/llm`. The configuration `data.dir` and the environment variable `DEVOPS_CLI_DATA_DIR` SHALL determine the cache root. + +#### Scenario: Custom data directory configured +- **WHEN** `DEVOPS_CLI_DATA_DIR` is set to an isolated directory +- **THEN** all cache operations and CLI commands read and write inside `/cache/llm` + +### Requirement: Empty and schema-failing responses are not cached +The AI client SHALL not store responses whose content is empty or contains only whitespace in the cache. The structured client SHALL not store replies that fail schema validation. + +#### Scenario: Empty response with thinking block +- **WHEN** a model returns an empty text response containing thinking blocks +- **THEN** the client returns the response to the caller and writes no cache file + +#### Scenario: Response fails schema validation +- **WHEN** a structured model response fails Pydantic schema validation on attempt 1 +- **THEN** the client deletes any invalid entry at the key and stores no failing reply + +### Requirement: Disabled cache clients bypass cache +An AI client configured with disabled caching SHALL neither read nor write the response cache. + +#### Scenario: Cache disabled client execution +- **WHEN** an AI client is initialized with `cache_enabled=False` +- **THEN** multiple identical requests dispatch to the provider and create no cache files