From 6eb42d5376f757e635101bde2c93ca8fa500f270 Mon Sep 17 00:00:00 2001 From: Nikita Fishbakh Date: Tue, 17 Nov 2026 11:07:27 +0100 Subject: [PATCH 1/3] CM-78367: Scan images attached to Codex prompts for secrets Codex's prompt hook gets the prompt text only, with an [Image #N] chip per attached image. The terminal UI saves an image pasted from the clipboard as codex-clipboard-.png in the temp directory and keeps it. The hook now sends the newest pastes of the last hour that no earlier prompt of the session sent (read from its transcript), one per chip, plus @path mentions, with the prompt text in one scan. Codex records a prompt only after its hook lets it through, so a blocked prompt sent again is scanned again. Images dragged in, picked from the @ popup or passed with --image, and the VS Code extension's attachments, are not named anywhere the hook can read. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- cycode/cli/apps/ai_guardrails/ides/codex.py | 68 +++++++++++ .../commands/ai_guardrails/ides/test_codex.py | 112 ++++++++++++++++++ 3 files changed, 181 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 70974c61..53d52bb3 100644 --- a/README.md +++ b/README.md @@ -755,7 +755,7 @@ prompts, files the agent reads, and MCP tool arguments are scanned for secrets b Scanning happens server-side, so the scanned content leaves the machine: the prompt text, the contents of files the agent reads, and MCP tool arguments are sent to your Cycode tenant to be checked for secrets. -For GitHub Copilot and Claude Code, PNG and JPEG images attached to a prompt are sent along with its text. +For GitHub Copilot, Claude Code and Codex, PNG and JPEG images attached to a prompt are sent along with its text. Each event is also reported with context about the developer and the machine, so a finding can be attributed to the device and user it came from. Some of this is personal data: diff --git a/cycode/cli/apps/ai_guardrails/ides/codex.py b/cycode/cli/apps/ai_guardrails/ides/codex.py index cb8e6deb..62b5869f 100644 --- a/cycode/cli/apps/ai_guardrails/ides/codex.py +++ b/cycode/cli/apps/ai_guardrails/ides/codex.py @@ -4,6 +4,8 @@ import os import re import sys +import tempfile +import time from collections.abc import Iterator from pathlib import Path from typing import ClassVar @@ -25,6 +27,12 @@ from cycode.cli.apps.ai_guardrails.ides._skill_utils import walk_plugin_skills, walk_skill_dirs from cycode.cli.apps.ai_guardrails.ides.base import IDE, DecisionAction, HookDecision from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload +from cycode.cli.apps.ai_guardrails.scan.prompt_images import ( + PromptImage, + mentioned_files, + modified_between, + select_prompt_images, +) from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType from cycode.cli.utils.jwt_utils import decode_jwt_unverified from cycode.logger import get_logger @@ -43,6 +51,16 @@ _SCAN_COMMAND = f'{CYCODE_SCAN_PROMPT_COMMAND} --ide codex' _SESSION_START_COMMAND = f'{CYCODE_SESSION_START_COMMAND} --ide codex' +# The prompt names each attached image only by an [Image #N] chip. Codex's terminal UI saves an image pasted from the +# clipboard as codex-clipboard-.png in the temp directory and keeps it; an image dragged in, picked from the +# @ popup or passed with --image is attached from where it is, and nothing names it. +_IMAGE_CHIP_PATTERN = re.compile(r'\[Image #(\d+)\]') +_CLIPBOARD_IMAGE_GLOB = 'codex-clipboard-*.png' +_CLIPBOARD_IMAGE_NAME_PATTERN = re.compile(r'codex-clipboard-[A-Za-z0-9]+\.png') +_CLIPBOARD_IMAGE_NAME_PREFIX = 'codex-clipboard-' +# How long after its paste a prompt may still be sent with the image +_CLIPBOARD_IMAGE_MAX_AGE_SECONDS = 60 * 60 + def _codex_home() -> Path: """Resolve Codex's user-scope home directory. @@ -229,6 +247,41 @@ def _enable_codex_hooks_feature(scope: str, repo_path: Path | None = None) -> tu return False, f'Failed to write Codex config at {config_path}' +# --- prompt images ------------------------------------------------------------ + + +def _sent_clipboard_image_names(transcript_path: object) -> set[str]: + """Names of the clipboard images the session's earlier prompts sent, as its transcript records them. + + Codex records a prompt only once its hook lets it through, so a blocked prompt sent again finds its images again. + """ + if not isinstance(transcript_path, str) or not transcript_path: + return set() + names: set[str] = set() + try: + with open(transcript_path, encoding='utf-8', errors='replace') as transcript: + for line in transcript: + if _CLIPBOARD_IMAGE_NAME_PREFIX in line: + names.update(_CLIPBOARD_IMAGE_NAME_PATTERN.findall(line)) + except OSError as e: + logger.debug('Failed to read the Codex transcript, %s', {'path': transcript_path}, exc_info=e) + return names + + +def _pasted_clipboard_images(prompt: str, transcript_path: object, now: float) -> list[Path]: + """The newest recent clipboard pastes no earlier prompt sent, one per [Image #N] chip in the prompt. + + A chip doesn't say whether its image was pasted or dragged in, so a prompt with a dragged image may take an + unrelated recent paste as well. + """ + chips_count = len(set(_IMAGE_CHIP_PATTERN.findall(prompt))) + if not chips_count: + return [] + sent = _sent_clipboard_image_names(transcript_path) + pastes = [path for path in Path(tempfile.gettempdir()).glob(_CLIPBOARD_IMAGE_GLOB) if path.name not in sent] + return modified_between(pastes, now - _CLIPBOARD_IMAGE_MAX_AGE_SECONDS, now)[-chips_count:] + + class Codex(IDE): name: ClassVar[str] = 'codex' display_name: ClassVar[str] = 'Codex' @@ -302,6 +355,21 @@ def parse_hook_payload(self, raw_payload: dict) -> AIHookPayload: mcp_arguments=mcp_arguments, ) + def collect_prompt_images(self, raw_payload: dict) -> list[PromptImage]: + """Images attached to a prompt: clipboard pastes, one per chip, and `@path` mentions. + + The payload names no image, and the transcript records a prompt only after its hook. + """ + prompt = raw_payload.get('prompt') or '' + images = select_prompt_images( + [ + *_pasted_clipboard_images(prompt, raw_payload.get('transcript_path'), time.time()), + *mentioned_files(prompt, raw_payload.get('cwd')), + ] + ) + logger.debug('Collected prompt images, %s', {'images_count': len(images)}) + return images + def build_hook_response(self, decision: HookDecision) -> dict: # Codex hook response shapes: # - allow: empty (no objection). Older Codex runtimes reject an explicit diff --git a/tests/cli/commands/ai_guardrails/ides/test_codex.py b/tests/cli/commands/ai_guardrails/ides/test_codex.py index e69ef0b7..233798e3 100644 --- a/tests/cli/commands/ai_guardrails/ides/test_codex.py +++ b/tests/cli/commands/ai_guardrails/ides/test_codex.py @@ -2,7 +2,10 @@ import base64 import json +import os import sys +import tempfile +import time from pathlib import Path from unittest.mock import patch @@ -18,6 +21,7 @@ _load_codex_config, _read_codex_plugin, ) +from cycode.cli.apps.ai_guardrails.scan.prompt_images import PromptImage from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType if sys.version_info >= (3, 11): @@ -460,3 +464,111 @@ def test_get_skills_reads_user_scope_skills(fs: FakeFilesystem) -> None: def test_get_skills_no_skills_dir_returns_empty(fs: FakeFilesystem) -> None: assert Codex().get_skills() == [] + + +# --- prompt images ---------------------------------------------------------------- + + +def _png(marker: bytes) -> bytes: + return b'\x89PNG\r\n\x1a\n' + marker + + +def _paste(fs: FakeFilesystem, name: str, modified_at: float) -> str: + """An image the terminal UI saved from the clipboard.""" + path = Path(tempfile.gettempdir()) / f'codex-clipboard-{name}.png' + fs.create_file(path, contents=_png(name.encode())) + os.utime(path, (modified_at, modified_at)) + return str(path) + + +def _transcript(fs: FakeFilesystem, *sent: str) -> str: + """A session transcript whose earlier prompts sent these images, as Codex records them.""" + path = '/Users/user/.codex/sessions/2026/11/17/rollout-session-1.jsonl' + lines = [json.dumps({'type': 'session_meta', 'payload': {'id': 'session-1'}})] + for index, image in enumerate(sent, start=1): + content = [ + {'type': 'input_text', 'text': f''}, + {'type': 'input_image', 'image_url': 'data:image/png;base64,iVBORw0KGgo='}, + {'type': 'input_text', 'text': ''}, + ] + lines.append(json.dumps({'type': 'response_item', 'payload': {'role': 'user', 'content': content}})) + fs.create_file(path, contents='\n'.join(lines) + '\n') + return path + + +def _prompt_payload(prompt: str, transcript_path: str | None = None) -> dict: + return { + 'hook_event_name': 'UserPromptSubmit', + 'session_id': 'session-1', + 'turn_id': 'turn-1', + 'transcript_path': transcript_path, + 'cwd': '/Users/user/project', + 'prompt': prompt, + } + + +def _paths(images: list[PromptImage]) -> list[str]: + return [image.path for image in images] + + +def test_collect_prompt_images_takes_the_newest_paste_per_chip(fs: FakeFilesystem) -> None: + now = time.time() + _paste(fs, 'Old111', now - 300) + middle = _paste(fs, 'Mid222', now - 60) + newest = _paste(fs, 'New333', now - 5) + + images = Codex().collect_prompt_images(_prompt_payload('[Image #1] [Image #2] what changed?', _transcript(fs))) + + # Oldest first, the order they were pasted in + assert _paths(images) == [middle, newest] + + +def test_collect_prompt_images_skips_pastes_an_earlier_prompt_sent(fs: FakeFilesystem) -> None: + now = time.time() + earlier = _paste(fs, 'Earlier1', now - 120) + unsent = _paste(fs, 'Unsent22', now - 60) + _paste(fs, 'Sent3333', now - 5) + transcript = _transcript(fs, earlier, str(Path(tempfile.gettempdir()) / 'codex-clipboard-Sent3333.png')) + + # A prompt blocked before isn't in the transcript, so its paste is found again when it is sent again + assert _paths(Codex().collect_prompt_images(_prompt_payload('[Image #1] again', transcript))) == [unsent] + + +def test_collect_prompt_images_takes_no_paste_without_a_chip(fs: FakeFilesystem) -> None: + _paste(fs, 'Recent11', time.time() - 5) + + assert Codex().collect_prompt_images(_prompt_payload('no image here', _transcript(fs))) == [] + + +def test_collect_prompt_images_counts_a_repeated_chip_once(fs: FakeFilesystem) -> None: + now = time.time() + _paste(fs, 'First111', now - 60) + newest = _paste(fs, 'Second22', now - 5) + + payload = _prompt_payload('compare [Image #1] with itself: [Image #1]', _transcript(fs)) + + assert _paths(Codex().collect_prompt_images(payload)) == [newest] + + +def test_collect_prompt_images_ignores_pastes_older_than_an_hour(fs: FakeFilesystem) -> None: + _paste(fs, 'Stale111', time.time() - 2 * 60 * 60) + + assert Codex().collect_prompt_images(_prompt_payload('[Image #1]', _transcript(fs))) == [] + + +@pytest.mark.parametrize('transcript_path', [None, '', '/missing/rollout.jsonl']) +def test_collect_prompt_images_without_a_transcript_takes_recent_pastes( + fs: FakeFilesystem, transcript_path: str | None +) -> None: + pasted = _paste(fs, 'Recent11', time.time() - 5) + + assert _paths(Codex().collect_prompt_images(_prompt_payload('[Image #1]', transcript_path))) == [pasted] + + +def test_collect_prompt_images_finds_mentions_against_cwd(fs: FakeFilesystem) -> None: + shot = Path('/Users/user/project/docs/shot.png') + fs.create_file(shot, contents=_png(b'shot')) + + images = Codex().collect_prompt_images(_prompt_payload('explain @docs/shot.png', _transcript(fs))) + + assert _paths(images) == [str(shot)] From 111060163877fa6cd248eee1683d8d156ac3e4c3 Mon Sep 17 00:00:00 2001 From: Nikita Fishbakh Date: Tue, 17 Nov 2026 16:39:10 +0100 Subject: [PATCH 2/3] CM-78367: Take no Codex paste for a prompt without a transcript Codex sends a second prompt to title a new thread. It has no transcript and quotes the user's prompt, chips included, so it took the paste the user's prompt had just sent and scanned it again. Without a transcript nothing tells a sent paste from an unsent one, so no paste is taken. The docstring also says what a live run showed: a dragged image, or one picked from the @ popup, gets a chip but no paste, so the prompt takes the newest unsent paste in its place. Co-Authored-By: Claude Opus 5.5 --- cycode/cli/apps/ai_guardrails/ides/codex.py | 12 ++++++------ .../commands/ai_guardrails/ides/test_codex.py | 16 +++++++++++++--- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/cycode/cli/apps/ai_guardrails/ides/codex.py b/cycode/cli/apps/ai_guardrails/ides/codex.py index 62b5869f..c6ce0c89 100644 --- a/cycode/cli/apps/ai_guardrails/ides/codex.py +++ b/cycode/cli/apps/ai_guardrails/ides/codex.py @@ -250,13 +250,11 @@ def _enable_codex_hooks_feature(scope: str, repo_path: Path | None = None) -> tu # --- prompt images ------------------------------------------------------------ -def _sent_clipboard_image_names(transcript_path: object) -> set[str]: +def _sent_clipboard_image_names(transcript_path: str) -> set[str]: """Names of the clipboard images the session's earlier prompts sent, as its transcript records them. Codex records a prompt only once its hook lets it through, so a blocked prompt sent again finds its images again. """ - if not isinstance(transcript_path, str) or not transcript_path: - return set() names: set[str] = set() try: with open(transcript_path, encoding='utf-8', errors='replace') as transcript: @@ -271,11 +269,13 @@ def _sent_clipboard_image_names(transcript_path: object) -> set[str]: def _pasted_clipboard_images(prompt: str, transcript_path: object, now: float) -> list[Path]: """The newest recent clipboard pastes no earlier prompt sent, one per [Image #N] chip in the prompt. - A chip doesn't say whether its image was pasted or dragged in, so a prompt with a dragged image may take an - unrelated recent paste as well. + A chip doesn't say whether its image was pasted, dragged in or picked from the @ popup, so a prompt with a dragged + or picked image takes the newest unsent paste in its place. Without a transcript nothing tells a sent paste from an + unsent one, so none is taken: the prompt Codex sends to title a new thread has none and quotes the user's prompt, + chips included. """ chips_count = len(set(_IMAGE_CHIP_PATTERN.findall(prompt))) - if not chips_count: + if not chips_count or not isinstance(transcript_path, str) or not transcript_path: return [] sent = _sent_clipboard_image_names(transcript_path) pastes = [path for path in Path(tempfile.gettempdir()).glob(_CLIPBOARD_IMAGE_GLOB) if path.name not in sent] diff --git a/tests/cli/commands/ai_guardrails/ides/test_codex.py b/tests/cli/commands/ai_guardrails/ides/test_codex.py index 233798e3..4b4065db 100644 --- a/tests/cli/commands/ai_guardrails/ides/test_codex.py +++ b/tests/cli/commands/ai_guardrails/ides/test_codex.py @@ -556,13 +556,23 @@ def test_collect_prompt_images_ignores_pastes_older_than_an_hour(fs: FakeFilesys assert Codex().collect_prompt_images(_prompt_payload('[Image #1]', _transcript(fs))) == [] -@pytest.mark.parametrize('transcript_path', [None, '', '/missing/rollout.jsonl']) -def test_collect_prompt_images_without_a_transcript_takes_recent_pastes( +@pytest.mark.parametrize('transcript_path', [None, '']) +def test_collect_prompt_images_takes_no_paste_without_a_transcript( fs: FakeFilesystem, transcript_path: str | None ) -> None: + _paste(fs, 'Recent11', time.time() - 5) + # The prompt Codex sends to title a new thread has no transcript and quotes the user's prompt, chips included + title_prompt = 'Generate a concise, single-line task title.\n\nUser prompt:\nwhat does it say? [Image #1]' + + assert Codex().collect_prompt_images(_prompt_payload(title_prompt, transcript_path)) == [] + + +def test_collect_prompt_images_takes_recent_pastes_before_the_transcript_is_written(fs: FakeFilesystem) -> None: pasted = _paste(fs, 'Recent11', time.time() - 5) - assert _paths(Codex().collect_prompt_images(_prompt_payload('[Image #1]', transcript_path))) == [pasted] + payload = _prompt_payload('[Image #1]', '/Users/user/.codex/sessions/2026/11/17/rollout-new.jsonl') + + assert _paths(Codex().collect_prompt_images(payload)) == [pasted] def test_collect_prompt_images_finds_mentions_against_cwd(fs: FakeFilesystem) -> None: From c97ec9e13bdd94c8d3a350744269ec5e5b71482b Mon Sep 17 00:00:00 2001 From: Nikita Fishbakh Date: Tue, 17 Nov 2026 16:56:47 +0100 Subject: [PATCH 3/3] CM-78368: Scan images attached to Cursor prompts for secrets (#594) Co-authored-by: Claude Opus 5.5 --- README.md | 2 +- cycode/cli/apps/ai_guardrails/ides/cursor.py | 94 ++++++++++ .../ai_guardrails/ides/test_cursor.py | 170 +++++++++++++++++- 3 files changed, 264 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 53d52bb3..8a119206 100644 --- a/README.md +++ b/README.md @@ -755,7 +755,7 @@ prompts, files the agent reads, and MCP tool arguments are scanned for secrets b Scanning happens server-side, so the scanned content leaves the machine: the prompt text, the contents of files the agent reads, and MCP tool arguments are sent to your Cycode tenant to be checked for secrets. -For GitHub Copilot, Claude Code and Codex, PNG and JPEG images attached to a prompt are sent along with its text. +For GitHub Copilot, Claude Code, Codex and Cursor, PNG and JPEG images attached to a prompt are sent along with its text. Each event is also reported with context about the developer and the machine, so a finding can be attributed to the device and user it came from. Some of this is personal data: diff --git a/cycode/cli/apps/ai_guardrails/ides/cursor.py b/cycode/cli/apps/ai_guardrails/ides/cursor.py index 0dab8c5e..4af08472 100644 --- a/cycode/cli/apps/ai_guardrails/ides/cursor.py +++ b/cycode/cli/apps/ai_guardrails/ides/cursor.py @@ -2,14 +2,20 @@ import json import platform +import sqlite3 +import time +from contextlib import closing from pathlib import Path from typing import ClassVar +from urllib.parse import urlparse +from urllib.request import url2pathname from cycode.cli.apps.ai_guardrails.consts import CYCODE_SCAN_PROMPT_COMMAND, CYCODE_SESSION_START_COMMAND from cycode.cli.apps.ai_guardrails.ides._plugin_utils import build_global_config_files from cycode.cli.apps.ai_guardrails.ides._skill_utils import walk_skill_dirs from cycode.cli.apps.ai_guardrails.ides.base import IDE, DecisionAction, HookDecision from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload +from cycode.cli.apps.ai_guardrails.scan.prompt_images import PromptImage, select_prompt_images from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType from cycode.logger import get_logger @@ -31,6 +37,16 @@ _SCAN_COMMAND = CYCODE_SCAN_PROMPT_COMMAND _SESSION_START_COMMAND = f'{CYCODE_SESSION_START_COMMAND} --ide cursor' +# The hook payload names no image attached to a prompt; Cursor's own record of the prompt does. It is the +# conversation's bubble whose requestId is the hook's generation_id, in the cursorDiskKV table of Cursor's global +# state database, and context.selectedImages lists each pasted, dropped or picked image, saved in the workspace's +# storage when it is attached. An @-mentioned file is only a link the agent may read later, not an attachment. +# Cursor starts saving the record just before it runs the hook, so the record may take a moment to appear. +_STATE_DB_PATH_PARTS = ('User', 'globalStorage', 'state.vscdb') +_PROMPT_RECORD_QUERY = 'SELECT value FROM cursorDiskKV WHERE key >= ? AND key < ? AND instr(value, ?) > 0' +_PROMPT_RECORD_WAIT_SECONDS = 1.0 +_PROMPT_RECORD_POLL_SECONDS = 0.2 + def _user_hooks_dir() -> Path: """Per-platform Cursor user-scope settings directory.""" @@ -41,6 +57,15 @@ def _user_hooks_dir() -> Path: return Path.home() / '.config' / 'Cursor' +def _cursor_user_data_dir() -> Path: + """Per-platform Cursor user data directory.""" + if platform.system() == 'Darwin': + return Path.home() / 'Library' / 'Application Support' / 'Cursor' + if platform.system() == 'Windows': + return Path.home() / 'AppData' / 'Roaming' / 'Cursor' + return Path.home() / '.config' / 'Cursor' + + def _cursor_mcp_config_path() -> Path: """User-scope Cursor MCP config path (``~/.cursor/mcp.json``, all platforms).""" return Path.home() / '.cursor' / _MCP_CONFIG_FILENAME @@ -102,6 +127,68 @@ def _resolve_mcp_server_name(raw_payload: dict) -> str | None: return command +# --- prompt images ------------------------------------------------------------ + + +def _image_file_path(value: object) -> str | None: + """A selected image's file, given as a path or a file URI.""" + if not isinstance(value, str) or not value: + return None + if value.startswith('file:'): + return url2pathname(urlparse(value).path) + return value + + +def _prompt_record_image_paths(db_path: Path, conversation_id: str, generation_id: str) -> list[str] | None: + """The image files Cursor's record of the prompt lists; None while there is no record.""" + key_range = (f'bubbleId:{conversation_id}:', f'bubbleId:{conversation_id};') + # Read-only: Cursor keeps writing to the file + with closing(sqlite3.connect(f'{db_path.resolve().as_uri()}?mode=ro', uri=True, timeout=1)) as connection: + values = [value for (value,) in connection.execute(_PROMPT_RECORD_QUERY, (*key_range, generation_id))] + + paths: list[str] | None = None + for value in values: + try: + bubble = json.loads(value) + except (TypeError, ValueError): + continue + if not isinstance(bubble, dict) or bubble.get('requestId') != generation_id: + continue + paths = paths or [] + context = bubble.get('context') + selected = context.get('selectedImages') if isinstance(context, dict) else None + for image in selected if isinstance(selected, list) else []: + path = _image_file_path(image.get('path')) if isinstance(image, dict) else None + if path: + paths.append(path) + return paths + + +def _prompt_record_images(conversation_id: object, generation_id: object) -> list[str]: + """The image files Cursor's record of the prompt lists, waiting a moment for the record to be saved.""" + if not isinstance(conversation_id, str) or not conversation_id: + return [] + if not isinstance(generation_id, str) or not generation_id: + return [] + db_path = _cursor_user_data_dir().joinpath(*_STATE_DB_PATH_PARTS) + if not db_path.is_file(): + return [] + + deadline = time.monotonic() + _PROMPT_RECORD_WAIT_SECONDS + while True: + try: + paths = _prompt_record_image_paths(db_path, conversation_id, generation_id) + except sqlite3.Error as e: + logger.debug('Failed to read Cursor state database, %s', {'path': str(db_path)}, exc_info=e) + return [] + if paths is not None: + return paths + if time.monotonic() >= deadline: + logger.debug('Cursor has not saved the prompt yet, scanning its text only') + return [] + time.sleep(_PROMPT_RECORD_POLL_SECONDS) + + class Cursor(IDE): name: ClassVar[str] = 'cursor' display_name: ClassVar[str] = 'Cursor' @@ -140,6 +227,13 @@ def parse_hook_payload(self, raw_payload: dict) -> AIHookPayload: mcp_arguments=(raw_payload.get('arguments') or raw_payload.get('tool_input') or raw_payload.get('input')), ) + def collect_prompt_images(self, raw_payload: dict) -> list[PromptImage]: + """Images attached to a prompt, as Cursor's record of the prompt lists them.""" + paths = _prompt_record_images(raw_payload.get('conversation_id'), raw_payload.get('generation_id')) + images = select_prompt_images(paths) + logger.debug('Collected prompt images, %s', {'images_count': len(images)}) + return images + def build_hook_response(self, decision: HookDecision) -> dict: if decision.event_type == AiHookEventType.PROMPT: if decision.action == DecisionAction.ALLOW: diff --git a/tests/cli/commands/ai_guardrails/ides/test_cursor.py b/tests/cli/commands/ai_guardrails/ides/test_cursor.py index f54e6752..7761bcfb 100644 --- a/tests/cli/commands/ai_guardrails/ides/test_cursor.py +++ b/tests/cli/commands/ai_guardrails/ides/test_cursor.py @@ -1,14 +1,18 @@ """Cursor IDE integration tests (payload parsing, response building, MCP context).""" import json +import sqlite3 +from contextlib import closing from pathlib import Path from typing import Any from unittest.mock import patch +import pytest from pyfakefs.fake_filesystem import FakeFilesystem +from pytest_mock import MockerFixture from cycode.cli.apps.ai_guardrails.ides.base import HookDecision -from cycode.cli.apps.ai_guardrails.ides.cursor import Cursor +from cycode.cli.apps.ai_guardrails.ides.cursor import Cursor, _cursor_user_data_dir from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType @@ -248,3 +252,167 @@ def test_get_skills_reads_user_scope_skills(fs: FakeFilesystem) -> None: def test_get_skills_no_skills_dir_returns_empty(fs: FakeFilesystem) -> None: assert Cursor().get_skills() == [] + + +# --- prompt images (a real SQLite file, so no fake filesystem) ------------------------ + +_CONVERSATION_ID = '6f1c2d3e-4b5a-4c6d-8e7f-9a0b1c2d3e4f' +_GENERATION_ID = 'a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d' + + +def _png(marker: bytes) -> bytes: + return b'\x89PNG\r\n\x1a\n' + marker + + +@pytest.fixture +def cursor_user_data(tmp_path: Path, mocker: MockerFixture) -> Path: + user_data = tmp_path / 'Cursor' + mocker.patch('cycode.cli.apps.ai_guardrails.ides.cursor._cursor_user_data_dir', return_value=user_data) + mocker.patch('cycode.cli.apps.ai_guardrails.ides.cursor._PROMPT_RECORD_WAIT_SECONDS', 0) + return user_data + + +def _state_db(user_data: Path, bubbles: dict[str, object]) -> Path: + """Cursor's global state database, holding these bubbles of the conversation (by bubble id).""" + db_path = user_data / 'User' / 'globalStorage' / 'state.vscdb' + db_path.parent.mkdir(parents=True) + with closing(sqlite3.connect(db_path)) as connection, connection: + connection.execute('CREATE TABLE cursorDiskKV (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB)') + connection.executemany( + 'INSERT INTO cursorDiskKV VALUES (?, ?)', + [(key, value if isinstance(value, str) else json.dumps(value)) for key, value in bubbles.items()], + ) + return db_path + + +def _bubble(request_id: str, *image_paths: str) -> dict: + return { + 'type': 1, + 'requestId': request_id, + 'context': { + 'selectedImages': [{'uuid': f'uuid-{index}', 'path': path} for index, path in enumerate(image_paths)] + }, + } + + +def _image(directory: Path, name: str) -> str: + path = directory / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(_png(name.encode())) + return str(path) + + +def _prompt_payload(**overrides: object) -> dict: + return { + 'hook_event_name': 'beforeSubmitPrompt', + 'conversation_id': _CONVERSATION_ID, + 'generation_id': _GENERATION_ID, + 'prompt': 'what does this screenshot show?', + 'attachments': [], + **overrides, + } + + +def test_collect_prompt_images_reads_the_prompts_record(cursor_user_data: Path, tmp_path: Path) -> None: + pasted = _image(cursor_user_data / 'User' / 'workspaceStorage' / 'ws-1' / 'images', 'image-uuid-1.png') + mentioned = _image(tmp_path / 'project', 'diagram.png') + earlier = _image(tmp_path / 'project', 'earlier.png') + other = _image(tmp_path / 'project', 'other.png') + _state_db( + cursor_user_data, + { + f'bubbleId:{_CONVERSATION_ID}:bubble-1': _bubble('earlier-generation', earlier), + f'bubbleId:{_CONVERSATION_ID}:bubble-2': _bubble(_GENERATION_ID, pasted, Path(mentioned).as_uri()), + 'bubbleId:another-conversation:bubble-3': _bubble(_GENERATION_ID, other), + f'composerData:{_CONVERSATION_ID}': {'latestChatGenerationUUID': _GENERATION_ID}, + }, + ) + + images = Cursor().collect_prompt_images(_prompt_payload()) + + assert [image.path for image in images] == [pasted, mentioned] + + +def test_collect_prompt_images_finds_nothing_in_a_record_without_images(cursor_user_data: Path) -> None: + _state_db(cursor_user_data, {f'bubbleId:{_CONVERSATION_ID}:bubble-1': _bubble(_GENERATION_ID)}) + + assert Cursor().collect_prompt_images(_prompt_payload()) == [] + + +def test_collect_prompt_images_waits_for_the_record( + cursor_user_data: Path, tmp_path: Path, mocker: MockerFixture +) -> None: + pasted = _image(tmp_path / 'images', 'pasted.png') + db_path = _state_db(cursor_user_data, {}) + mocker.patch('cycode.cli.apps.ai_guardrails.ides.cursor._PROMPT_RECORD_WAIT_SECONDS', 5) + + def save_the_record(_: float) -> None: + with closing(sqlite3.connect(db_path)) as connection, connection: + key = f'bubbleId:{_CONVERSATION_ID}:bubble-1' + connection.execute( + 'INSERT INTO cursorDiskKV VALUES (?, ?)', (key, json.dumps(_bubble(_GENERATION_ID, pasted))) + ) + + sleep = mocker.patch('cycode.cli.apps.ai_guardrails.ides.cursor.time.sleep', side_effect=save_the_record) + + assert [image.path for image in Cursor().collect_prompt_images(_prompt_payload())] == [pasted] + sleep.assert_called_once() + + +def test_collect_prompt_images_gives_up_when_the_record_never_comes(cursor_user_data: Path) -> None: + _state_db(cursor_user_data, {f'bubbleId:{_CONVERSATION_ID}:bubble-1': _bubble('earlier-generation')}) + + assert Cursor().collect_prompt_images(_prompt_payload()) == [] + + +@pytest.mark.parametrize( + 'overrides', + [{'conversation_id': None}, {'generation_id': ''}, {'conversation_id': 7}, {'generation_id': ['x']}], +) +def test_collect_prompt_images_needs_both_ids(cursor_user_data: Path, tmp_path: Path, overrides: dict) -> None: + pasted = _image(tmp_path / 'images', 'pasted.png') + _state_db(cursor_user_data, {f'bubbleId:{_CONVERSATION_ID}:bubble-1': _bubble(_GENERATION_ID, pasted)}) + + assert Cursor().collect_prompt_images(_prompt_payload(**overrides)) == [] + + +def test_collect_prompt_images_without_a_state_database(cursor_user_data: Path) -> None: + assert Cursor().collect_prompt_images(_prompt_payload()) == [] + + +def test_collect_prompt_images_skips_an_unreadable_database(cursor_user_data: Path) -> None: + db_path = cursor_user_data / 'User' / 'globalStorage' / 'state.vscdb' + db_path.parent.mkdir(parents=True) + db_path.write_bytes(b'not a database') + + assert Cursor().collect_prompt_images(_prompt_payload()) == [] + + +def test_collect_prompt_images_skips_malformed_records(cursor_user_data: Path, tmp_path: Path) -> None: + pasted = _image(tmp_path / 'images', 'pasted.png') + _state_db( + cursor_user_data, + { + f'bubbleId:{_CONVERSATION_ID}:bubble-1': f'not json {_GENERATION_ID}', + f'bubbleId:{_CONVERSATION_ID}:bubble-2': { + 'requestId': _GENERATION_ID, + 'context': {'selectedImages': [None, {'path': 7}, {'path': ''}, {'path': pasted}]}, + }, + }, + ) + + assert [image.path for image in Cursor().collect_prompt_images(_prompt_payload())] == [pasted] + + +@pytest.mark.parametrize( + ('system', 'base_parts'), + [ + ('Darwin', ('Library', 'Application Support')), + ('Linux', ('.config',)), + ('Windows', ('AppData', 'Roaming')), + ], +) +def test_cursor_user_data_dir_per_platform(mocker: MockerFixture, system: str, base_parts: tuple[str, ...]) -> None: + mocker.patch('cycode.cli.apps.ai_guardrails.ides.cursor.platform.system', return_value=system) + + assert _cursor_user_data_dir() == Path.home().joinpath(*base_parts, 'Cursor')