Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
94 changes: 94 additions & 0 deletions cycode/cli/apps/ai_guardrails/ides/cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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."""
Expand All @@ -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
Expand Down Expand Up @@ -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'
Expand Down Expand Up @@ -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:
Expand Down
170 changes: 169 additions & 1 deletion tests/cli/commands/ai_guardrails/ides/test_cursor.py
Original file line number Diff line number Diff line change
@@ -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


Expand Down Expand Up @@ -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')
Loading