From b0601ad270e9f00adaad33560461d70a528089bc Mon Sep 17 00:00:00 2001 From: Nikita Fishbakh Date: Tue, 10 Nov 2026 11:34:22 +0100 Subject: [PATCH 1/7] CM-77702: Scan images attached to Copilot prompts for secrets The UserPromptSubmit hook gets only the prompt text, but by the time it runs Copilot has saved every attached image to disk. The Copilot integration now finds them (@path mentions and pasted images in Copilot CLI; send-time copies and pastes in VS Code, saved since the session's previous prompt), and the prompt handler sends them with the text in one scan, so a secret in a screenshot blocks the prompt like a secret in its text. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 + cycode/cli/apps/ai_guardrails/ides/base.py | 12 ++ cycode/cli/apps/ai_guardrails/ides/copilot.py | 114 +++++++++- .../ai_guardrails/scan/guardrail_config.py | 12 +- .../cli/apps/ai_guardrails/scan/handlers.py | 66 ++++-- cycode/cli/apps/ai_guardrails/scan/payload.py | 3 + .../apps/ai_guardrails/scan/prompt_images.py | 176 ++++++++++++++++ .../apps/ai_guardrails/scan/scan_command.py | 16 +- cycode/cli/apps/ai_guardrails/scan/utils.py | 22 +- cycode/cli/files_collector/file_excluder.py | 4 +- .../files_collector/models/in_memory_zip.py | 9 +- cycode/cli/models.py | 15 +- cycode/cli/printers/tables/table_printer.py | 4 +- .../cli/printers/utils/code_snippet_syntax.py | 8 +- cycode/cli/utils/scan_batch.py | 3 +- cycode/cli/utils/string_utils.py | 8 +- .../ai_guardrails/ides/test_contract.py | 7 + .../ai_guardrails/ides/test_copilot.py | 146 +++++++++++++ .../commands/ai_guardrails/scan/conftest.py | 9 +- .../scan/test_guardrail_config.py | 33 +++ .../ai_guardrails/scan/test_handlers.py | 144 ++++++++++++- .../ai_guardrails/scan/test_prompt_images.py | 199 ++++++++++++++++++ .../ai_guardrails/scan/test_scan_command.py | 128 ++++++++++- .../cli/files_collector/test_in_memory_zip.py | 16 ++ tests/cli/models/test_document.py | 46 ++++ 25 files changed, 1145 insertions(+), 57 deletions(-) create mode 100644 cycode/cli/apps/ai_guardrails/scan/prompt_images.py create mode 100644 tests/cli/commands/ai_guardrails/scan/test_prompt_images.py create mode 100644 tests/cli/models/test_document.py diff --git a/README.md b/README.md index 2f4207e9..66c3ca6a 100644 --- a/README.md +++ b/README.md @@ -755,6 +755,8 @@ 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, unless your tenant turns image scanning off, 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/base.py b/cycode/cli/apps/ai_guardrails/ides/base.py index ace69ec2..6b956fb6 100644 --- a/cycode/cli/apps/ai_guardrails/ides/base.py +++ b/cycode/cli/apps/ai_guardrails/ides/base.py @@ -159,6 +159,18 @@ def is_synthetic_prompt(self, raw_payload: dict) -> bool: def parse_hook_payload(self, raw_payload: dict) -> AIHookPayload: """Normalize a raw stdin payload into the canonical ``AIHookPayload``.""" + def collect_prompt_images(self, raw_payload: dict) -> list[str]: + """Return the paths of the images attached to a prompt, to scan along with its text. + + ``scan_command`` calls it only for prompt events of a tenant that scans images, and only + in the process that runs the scan (never in a parent about to detach): collecting may + move per-session state forward, so a second call for the same prompt finds nothing. + + Default: ``[]`` (attachments are out of the hook's reach). Override for IDEs that leave + them on disk. + """ + return [] + @abstractmethod def build_hook_response(self, decision: HookDecision) -> dict: """Translate a canonical ``HookDecision`` into the IDE-specific JSON. diff --git a/cycode/cli/apps/ai_guardrails/ides/copilot.py b/cycode/cli/apps/ai_guardrails/ides/copilot.py index 01a1738c..447fa263 100644 --- a/cycode/cli/apps/ai_guardrails/ides/copilot.py +++ b/cycode/cli/apps/ai_guardrails/ides/copilot.py @@ -19,12 +19,18 @@ Copilot hooks have no matchers, so ``PreToolUse`` fires for every tool; tools we don't scan pass through as raw event names, which match no handler and allow immediately. + +A ``UserPromptSubmit`` payload carries the prompt text only, never its attachments, +but by the time the hook runs Copilot has saved every attached image to disk; see +``Copilot.collect_prompt_images`` for where each runtime puts them. """ import json import os import platform import re +import tempfile +import time from collections.abc import Iterable from pathlib import Path from typing import ClassVar @@ -40,6 +46,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 ( + get_prompt_mark, + modified_between, + save_prompt_mark, + select_prompt_images, +) from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType from cycode.logger import get_logger @@ -97,6 +109,23 @@ _SCAN_COMMAND = f'{CYCODE_SCAN_PROMPT_COMMAND} --ide copilot' _SESSION_START_COMMAND = f'{CYCODE_SESSION_START_COMMAND} --ide copilot' +# Copilot CLI leaves an `@path` mention in the prompt as typed: quoted, with +# backslash-escaped spaces (a file dragged into a terminal), or plain up to the next +# whitespace. Never mid-word, so an email address is not a mention. +_MENTION_PATTERN = re.compile(r'(? Path: """Resolve Copilot's user-scope home directory (honors ``$COPILOT_HOME``).""" @@ -118,13 +147,18 @@ def _vscode_agent_plugins_dir() -> Path: return Path.home() / '.vscode' / 'agent-plugins' -def _vscode_user_dir() -> Path: - """Per-platform VS Code user settings directory.""" +def _vscode_user_data_dir(product_name: str = 'Code') -> Path: + """Per-platform VS Code user data directory; ``product_name`` is 'Code' or 'Code - Insiders'.""" if platform.system() == 'Darwin': - return Path.home() / 'Library' / 'Application Support' / 'Code' / 'User' + return Path.home() / 'Library' / 'Application Support' / product_name if platform.system() == 'Windows': - return Path.home() / 'AppData' / 'Roaming' / 'Code' / 'User' - return Path.home() / '.config' / 'Code' / 'User' + return Path.home() / 'AppData' / 'Roaming' / product_name + return Path.home() / '.config' / product_name + + +def _vscode_user_dir() -> Path: + """Per-platform VS Code user settings directory.""" + return _vscode_user_data_dir() / 'User' def _vscode_mcp_config_path() -> Path: @@ -380,6 +414,52 @@ def split_mcp_tool_name(tool_name: str, server_names: Iterable[str]) -> tuple[st return None, rest or None +# --- prompt images ------------------------------------------------------------------ + + +def _mentioned_files(prompt: str, cwd: str | None) -> list[Path]: + """Existing files named by `@` mentions, resolved against the hook's cwd.""" + base = Path(cwd) if cwd else Path() + files = [] + for match in _MENTION_PATTERN.finditer(prompt): + token = match.group(1) + if len(token) > 1 and token[0] == token[-1] and token[0] in '"\'': + spellings = [token[1:-1]] + else: + if os.sep == '/': + token = token.replace('\\ ', ' ') + # The mention may end a sentence ("look at @shot.png.") + spellings = [token, token.rstrip(_MENTION_TRAILING_PUNCTUATION)] + for spelling in spellings: + path = base / os.path.expanduser(spelling) + if os.path.isfile(path): + files.append(path) + break + return files + + +def _pasted_cli_images(prompt: str) -> list[Path]: + """Images pasted into Copilot CLI, saved in the temp directory its placeholder names.""" + temp_dir = Path(tempfile.gettempdir()) + # The base name only: the placeholder is prompt text, so it must not lead outside the temp directory + return [temp_dir / os.path.basename(name) for name in _PASTED_IMAGE_PATTERN.findall(prompt)] + + +def _vscode_saved_attachments(since: float, until: float) -> list[Path]: + """Attachment files VS Code saved in ``[since, until)``. + + Send-time copies come before pastes, so a paste found in both keeps the name it + was attached under once the duplicate is dropped. + """ + copies: list[Path] = [] + pastes: list[Path] = [] + for product_name in _VSCODE_PRODUCT_NAMES: + user_data_dir = _vscode_user_data_dir(product_name) + copies.extend(user_data_dir.glob(_VSCODE_ATTACHMENT_COPIES_GLOB)) + pastes.extend(user_data_dir.joinpath(*_VSCODE_PASTED_IMAGES_DIR_PARTS).glob('*')) + return [*modified_between(copies, since, until), *modified_between(pastes, since, until)] + + class Copilot(IDE): name: ClassVar[str] = 'copilot' display_name: ClassVar[str] = 'GitHub Copilot' @@ -450,6 +530,30 @@ def parse_hook_payload(self, raw_payload: dict) -> AIHookPayload: mcp_arguments=mcp_arguments, ) + def collect_prompt_images(self, raw_payload: dict) -> list[str]: + """Images attached to a prompt, found where Copilot saved them before the hook ran. + + Copilot CLI names its attachments in the prompt: an `@path` mention as typed, or + a pasted image's placeholder. VS Code names none, so its attachments are the files + it saved since the session's previous prompt (see prompt_images). + """ + session_id = raw_payload.get('session_id') + prompt = raw_payload.get('prompt') or '' + now = time.time() + since = get_prompt_mark(session_id, now) + + images = select_prompt_images( + [ + *_mentioned_files(prompt, raw_payload.get('cwd')), + *_pasted_cli_images(prompt), + *_vscode_saved_attachments(since, now), + ] + ) + save_prompt_mark(session_id, now) + + logger.debug('Collected prompt images, %s', {'images_count': len(images), 'since': since}) + return images + def build_hook_response(self, decision: HookDecision) -> dict: if decision.action == DecisionAction.ALLOW: # Neutral allow: {} means "no objection", leaving VS Code's own diff --git a/cycode/cli/apps/ai_guardrails/scan/guardrail_config.py b/cycode/cli/apps/ai_guardrails/scan/guardrail_config.py index d1e59f98..466b4311 100644 --- a/cycode/cli/apps/ai_guardrails/scan/guardrail_config.py +++ b/cycode/cli/apps/ai_guardrails/scan/guardrail_config.py @@ -105,6 +105,13 @@ def sensitive_globs(self) -> list: globs = settings.get('globs') return globs if isinstance(globs, list) and globs else _default_sensitive_globs() + def scans_prompt_images(self) -> bool: + """Whether images attached to a prompt are scanned along with its text. + + Only a platform that reads text out of images sends the setting, so a missing value means text only. + """ + return (self._guardrails.get(BlockReason.SECRETS_IN_PROMPT) or {}).get('scan_images') is True + def is_expired(self) -> bool: return time.time() - self.fetched_at > self.ttl_seconds @@ -129,7 +136,10 @@ def cell(guardrail_key: str) -> str: def action(guardrail_key: str) -> str: return PolicyMode.BLOCK.value if cell(guardrail_key) == GuardrailCellMode.BLOCK else PolicyMode.WARN.value - policy.setdefault('prompt', {})['action'] = action(BlockReason.SECRETS_IN_PROMPT) + prompt = policy.setdefault('prompt', {}) + prompt['action'] = action(BlockReason.SECRETS_IN_PROMPT) + # Unlike the modes, no built-in default: a cold start can't know the platform reads images, so text only. + prompt['scan_images'] = config is not None and config.scans_prompt_images() file_read = policy.setdefault('file_read', {}) file_read['scan_content'] = cell(BlockReason.SECRETS_IN_FILE) != GuardrailCellMode.OFF diff --git a/cycode/cli/apps/ai_guardrails/scan/handlers.py b/cycode/cli/apps/ai_guardrails/scan/handlers.py index 81c699db..adb07122 100644 --- a/cycode/cli/apps/ai_guardrails/scan/handlers.py +++ b/cycode/cli/apps/ai_guardrails/scan/handlers.py @@ -27,6 +27,7 @@ from cycode.cli.apps.ai_guardrails.scan.mcp_server_status import is_enforced, load_mcp_server_statuses from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload from cycode.cli.apps.ai_guardrails.scan.policy import get_policy_value +from cycode.cli.apps.ai_guardrails.scan.prompt_images import image_file_name, read_prompt_image from cycode.cli.apps.ai_guardrails.scan.types import ( SECRETS_BLOCK_REASON_BY_EVENT_TYPE, AiHookEventType, @@ -47,6 +48,8 @@ HandlerFn = Callable[[typer.Context, AIHookPayload, dict], HookDecision] +_TEXT_DOCUMENT_NAME = 'prompt-content.txt' + def _ignore_commands(shas: tuple[str, ...]) -> list[str]: """Ready-to-run ignore commands, one per finding, in the order the findings are listed. @@ -112,7 +115,7 @@ def _parse_verdict(verdict: str | None) -> GuardrailsMode | None: def handle_before_submit_prompt(ctx: typer.Context, payload: AIHookPayload, policy: dict) -> HookDecision: - """Scan prompt text for secrets before it's sent to the AI model.""" + """Scan prompt text, and the images attached to it, for secrets before it's sent to the AI model.""" ai_client = ctx.obj['ai_security_client'] prompt = payload.prompt or '' @@ -126,13 +129,7 @@ def handle_before_submit_prompt(ctx: typer.Context, payload: AIHookPayload, poli error_message = None try: - scan_outcome = _scan_text_for_secrets( - ctx, - clipped, - timeout_ms, - payload=payload, - event_type=AiHookEventType.PROMPT, - ) + scan_outcome = _scan_prompt_for_secrets(ctx, clipped, payload.image_paths, timeout_ms, payload=payload) scan_id = scan_outcome.scan_id if scan_outcome.violation_summary: @@ -538,22 +535,63 @@ def _perform_scan( ) -def _scan_text_for_secrets( +def _scan_documents_for_secrets( ctx: typer.Context, - text: str, + documents: list[Document], timeout_ms: int, payload: AIHookPayload, event_type: AiHookEventType, ) -> ScanOutcome: - """Scan text content for secrets using Cycode CLI.""" - if not text: + """Scan in-memory documents for secrets, all in one scan.""" + if not documents: return NO_SCAN - document = Document(path='prompt-content.txt', content=text, is_git_diff_format=False) scan_ctx = _setup_scan_context(ctx) timeout_seconds = timeout_ms / 1000.0 scan_parameters = build_ai_guardrails_scan_parameters(scan_ctx, None, payload, event_type) - return _perform_scan(scan_ctx, [document], scan_parameters, timeout_seconds) + return _perform_scan(scan_ctx, documents, scan_parameters, timeout_seconds) + + +def _scan_text_for_secrets( + ctx: typer.Context, + text: str, + timeout_ms: int, + payload: AIHookPayload, + event_type: AiHookEventType, +) -> ScanOutcome: + """Scan text content for secrets using Cycode CLI.""" + documents = [Document(path=_TEXT_DOCUMENT_NAME, content=text, is_git_diff_format=False)] if text else [] + return _scan_documents_for_secrets(ctx, documents, timeout_ms, payload, event_type) + + +def _image_documents(image_paths: list[str]) -> list[Document]: + """One bytes document per attached image. + + The entry name keeps an image extension because the server picks the files to read text out of by extension as + well as signature. The original path stays on the document, to name the image in the block message. + """ + documents = [] + for index, image_path in enumerate(image_paths, start=1): + content = read_prompt_image(image_path) + if content is None: + logger.debug('Attached image is gone or no longer scannable, %s', {'path': image_path}) + continue + name = f'image-{index}-{image_file_name(image_path, content)}' + documents.append(Document(path=name, content=content, is_git_diff_format=False, absolute_path=image_path)) + return documents + + +def _scan_prompt_for_secrets( + ctx: typer.Context, + text: str, + image_paths: list[str], + timeout_ms: int, + payload: AIHookPayload, +) -> ScanOutcome: + """Scan the prompt text and its attached images for secrets; no text and no images means no scan.""" + documents = [Document(path=_TEXT_DOCUMENT_NAME, content=text, is_git_diff_format=False)] if text else [] + documents.extend(_image_documents(image_paths)) + return _scan_documents_for_secrets(ctx, documents, timeout_ms, payload, AiHookEventType.PROMPT) def _scan_path_for_secrets( diff --git a/cycode/cli/apps/ai_guardrails/scan/payload.py b/cycode/cli/apps/ai_guardrails/scan/payload.py index 668d878a..8a8e93df 100644 --- a/cycode/cli/apps/ai_guardrails/scan/payload.py +++ b/cycode/cli/apps/ai_guardrails/scan/payload.py @@ -33,6 +33,9 @@ class AIHookPayload: # Event-specific data prompt: str | None = None # PROMPT events + # Images attached to the prompt, scanned with its text. Filled by scan_command (IDE.collect_prompt_images), + # not at parse time: collecting moves per-session state forward, so only the process that scans may do it. + image_paths: list[str] = field(default_factory=list) file_path: str | None = None # FILE_READ events mcp_server_name: str | None = None # MCP_EXECUTION events mcp_tool_name: str | None = None diff --git a/cycode/cli/apps/ai_guardrails/scan/prompt_images.py b/cycode/cli/apps/ai_guardrails/scan/prompt_images.py new file mode 100644 index 00000000..7f77d407 --- /dev/null +++ b/cycode/cli/apps/ai_guardrails/scan/prompt_images.py @@ -0,0 +1,176 @@ +"""Images attached to an AI prompt, scanned for secrets along with its text. + +Some IDEs (GitHub Copilot) save a prompt's attachments to disk before its hook runs, yet never name them in the +hook payload. The IDE integration finds the candidates (``IDE.collect_prompt_images``); this module holds what is +IDE-agnostic about them: the filters every candidate passes, and the per-session prompt marks that turn "files saved +for this prompt" into "files saved since the session's previous prompt". + +A session's first prompt looks back a fixed time rather than to session start: VS Code fires SessionStart together +with the first prompt, after its attachments were already saved. +""" + +import hashlib +import json +import os +import stat +from collections.abc import Iterable +from pathlib import Path + +from cycode.cli.consts import CYCODE_CONFIGURATION_DIRECTORY, FILE_MAX_SIZE_LIMIT_IN_BYTES +from cycode.cli.utils.path_utils import atomic_write_text, quarantine_corrupt_file +from cycode.logger import get_logger + +logger = get_logger('AI Guardrails') + +PROMPT_MARKS_FILE_NAME = 'ai-guardrails-prompt-marks.json' + +# Each image is read by OCR on the server, within the IDE's hook timeout +MAX_PROMPT_IMAGES = 5 + +# Covers a paste made a while before sending, without reaching far into other chats' images +FIRST_PROMPT_LOOKBACK_SECONDS = 600 + +# A session idle this long loses its mark; if it comes back, its next prompt falls back to the lookback +_MARK_RETENTION_SECONDS = 7 * 24 * 60 * 60 + +# The formats the server reads text out of, by signature (a file's own extension can be wrong or missing), with the +# extensions that name each one +_IMAGE_FORMATS = ( + (b'\x89PNG\r\n\x1a\n', ('.png',)), + (b'\xff\xd8\xff', ('.jpg', '.jpeg')), +) +_SIGNATURE_LENGTH = max(len(signature) for signature, _ in _IMAGE_FORMATS) + + +def get_prompt_marks_path() -> Path: + return Path.home() / CYCODE_CONFIGURATION_DIRECTORY / PROMPT_MARKS_FILE_NAME + + +def _load_marks() -> dict[str, float]: + """``{session_id: timestamp}``; empty when the file is absent, or corrupt (then it is moved aside).""" + path = get_prompt_marks_path() + if not path.exists(): + return {} + + try: + with open(path, encoding='UTF-8') as file: + marks = json.load(file) + if not isinstance(marks, dict): + raise TypeError('prompt marks are not an object') + return {str(session_id): float(timestamp) for session_id, timestamp in marks.items()} + except Exception as e: + logger.warning('Prompt marks file is corrupt and will be moved aside', exc_info=e) + quarantine_corrupt_file(str(path)) + return {} + + +def get_prompt_mark(session_id: str | None, now: float) -> float: + """Where a prompt's attachments start: the session's previous prompt, or the first-prompt lookback.""" + mark = _load_marks().get(session_id) if session_id else None + if mark is None: + return now - FIRST_PROMPT_LOOKBACK_SECONDS + # A mark from before the clock was set back must not hide every new file + return min(mark, now) + + +def save_prompt_mark(session_id: str | None, now: float) -> None: + """Move the session's mark to ``now`` and drop the marks of long-idle sessions. Never raises. + + Unlocked read-modify-write: two sessions prompting at the same moment may lose one update, which only sends that + session's next prompt back to the lookback. The atomic write keeps the file whole. + """ + if not session_id: + return + + marks = _load_marks() + marks[session_id] = now + cutoff = now - _MARK_RETENTION_SECONDS + marks = {key: timestamp for key, timestamp in marks.items() if timestamp >= cutoff} + + path = get_prompt_marks_path() + try: + path.parent.mkdir(parents=True, exist_ok=True) + atomic_write_text(str(path), json.dumps(marks)) + except Exception as e: + logger.debug('Failed to save prompt marks', exc_info=e) + + +def modified_between(paths: Iterable[Path], since: float, until: float) -> list[Path]: + """The paths last modified in ``[since, until)``, oldest first (the order they were attached in). + + Half-open so that each file belongs to exactly one prompt: a file saved while this prompt's images are being + collected is left to the next prompt, whose window starts where this one ends. + """ + dated = [] + for path in paths: + try: + modified_at = path.stat().st_mtime + except OSError: + continue + if since <= modified_at < until: + dated.append((modified_at, path)) + return [path for _, path in sorted(dated, key=lambda item: item[0])] + + +def _image_extensions(content: bytes) -> tuple[str, ...]: + return next((extensions for signature, extensions in _IMAGE_FORMATS if content.startswith(signature)), ()) + + +def read_prompt_image(path: str | os.PathLike) -> bytes | None: + """The bytes of a scannable image - a regular PNG or JPEG file within the size limit - or None. + + Regular files only, checked before opening: an `@` mention can name a FIFO or a device, and reading one would + hang the hook. The signature is read first, so a mentioned source file is never read in full. + """ + try: + file_stat = os.stat(path) + if not stat.S_ISREG(file_stat.st_mode) or file_stat.st_size > FILE_MAX_SIZE_LIMIT_IN_BYTES: + return None + with open(path, 'rb') as file: + head = file.read(_SIGNATURE_LENGTH) + if not _image_extensions(head): + return None + # One byte past the limit tells a file that grew since the stat + content = head + file.read(FILE_MAX_SIZE_LIMIT_IN_BYTES + 1 - len(head)) + except (OSError, ValueError) as e: + logger.debug('Failed to read a prompt image candidate, %s', {'path': str(path)}, exc_info=e) + return None + + return content if len(content) <= FILE_MAX_SIZE_LIMIT_IN_BYTES else None + + +def image_file_name(path: str, content: bytes) -> str: + """The file's name, plus the extension of its actual format when its own extension doesn't name that format.""" + name = os.path.basename(path) + extensions = _image_extensions(content) + if extensions and os.path.splitext(name)[1].lower() not in extensions: + name += extensions[0] + return name + + +def select_prompt_images(candidates: Iterable[str | os.PathLike]) -> list[str]: + """The candidates to scan, in order: scannable images (see read_prompt_image), each content once, at most + MAX_PROMPT_IMAGES. + + Once per content because one attachment can be on disk twice: VS Code saves a paste when it is made and copies + it again when the prompt is sent. + """ + selected: list[str] = [] + seen_digests: set[str] = set() + for candidate in candidates: + content = read_prompt_image(candidate) + if content is None: + continue + + digest = hashlib.sha256(content).hexdigest() + if digest in seen_digests: + continue + + if len(selected) == MAX_PROMPT_IMAGES: + logger.debug('More images than a prompt scans; skipping the rest, %s', {'max_images': MAX_PROMPT_IMAGES}) + break + + seen_digests.add(digest) + selected.append(str(candidate)) + + return selected diff --git a/cycode/cli/apps/ai_guardrails/scan/scan_command.py b/cycode/cli/apps/ai_guardrails/scan/scan_command.py index 23b02424..6f1d08f4 100644 --- a/cycode/cli/apps/ai_guardrails/scan/scan_command.py +++ b/cycode/cli/apps/ai_guardrails/scan/scan_command.py @@ -18,7 +18,7 @@ from cycode.cli.apps.ai_guardrails.scan.detach import is_detached_child, respawn_detached from cycode.cli.apps.ai_guardrails.scan.guardrail_config import apply_platform_config, load_guardrail_config from cycode.cli.apps.ai_guardrails.scan.handlers import get_handler_for_event, should_detach_scan -from cycode.cli.apps.ai_guardrails.scan.policy import load_policy +from cycode.cli.apps.ai_guardrails.scan.policy import get_policy_value, load_policy from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType from cycode.cli.apps.ai_guardrails.scan.utils import output_json, read_stdin_text, safe_json_parse from cycode.cli.exceptions.custom_exceptions import HttpUnauthorizedError @@ -87,6 +87,15 @@ def _should_skip_payload(ide_integration: IDE, payload: dict | None) -> bool: return False +def _collect_prompt_images(ide_integration: IDE, payload: dict) -> list[str]: + """Best-effort: an image that can't be collected goes unscanned, but the prompt text is still scanned.""" + try: + return ide_integration.collect_prompt_images(payload) + except Exception as e: + logger.debug('Failed to collect prompt images, scanning the text only', exc_info=e) + return [] + + def _initialize_clients(ctx: typer.Context) -> None: """Initialize API clients. @@ -169,6 +178,11 @@ def scan_command( try: _initialize_clients(ctx) + if event_name == AiHookEventType.PROMPT and get_policy_value(policy, 'prompt', 'scan_images', default=False): + # Here rather than in parse_hook_payload: collecting moves the session's prompt mark forward, so it + # runs once, after the detach decision - a parent that detached would leave its child nothing to find. + unified_payload.image_paths = _collect_prompt_images(ide_integration, payload) + decision = handler(ctx, unified_payload, policy) logger.debug('Hook handler completed', extra={'event_name': event_name, 'action': decision.action.value}) output_json(ide_integration.build_hook_response(decision)) diff --git a/cycode/cli/apps/ai_guardrails/scan/utils.py b/cycode/cli/apps/ai_guardrails/scan/utils.py index 988c37b5..bc88332a 100644 --- a/cycode/cli/apps/ai_guardrails/scan/utils.py +++ b/cycode/cli/apps/ai_guardrails/scan/utils.py @@ -17,7 +17,7 @@ from cycode.cli.utils.string_utils import obfuscate_text if TYPE_CHECKING: - from cycode.cli.models import LocalScanResult + from cycode.cli.models import Document, LocalScanResult from cycode.cyclient.models import Detection # Keeps the hook message readable when a single file trips dozens of detections @@ -101,17 +101,23 @@ def output_json(obj: dict) -> None: print(json.dumps(obj), end='') # noqa: T201 -def _describe_detection(detection: 'Detection', content: str) -> str: +def _describe_detection(detection: 'Detection', document: 'Document') -> str: details = detection.detection_details description = detection.type or detection.message + if isinstance(document.content, bytes): + # An attached image: its line and position point into text the server read out of it, which the developer + # never sees. Its name is what tells them which attachment to remove. + image_name = os.path.basename(document.absolute_path or document.path) + return f'{description} in image "{image_name}"' + line = details.get('line') if isinstance(line, int) and line >= 0: description += f' (line {line + 1})' # the scanner reports 0-based lines start, length = details.get('start_position'), details.get('length') if isinstance(start, int) and isinstance(length, int) and start >= 0 and length > 0: - value = content[start : start + length] + value = document.text_content[start : start + length] if value: description += f': {obfuscate_text(value)}' @@ -126,14 +132,16 @@ def build_violation_summary( The masked value and hash are safe to display; the value itself is not. Detections excluded by an existing ignore rule are already gone from `document_detections`, so only what actually blocked is listed. """ - # Keyed by value hash so a repeated value is listed once; detections without one key by their description + # Keyed by value hash so a repeated value is listed once; detections without one key by their description. + # Per document too: the same value in the prompt and in an attached image is two places to remove it from. finding_by_key = {} for local_scan_result in local_scan_results: for document_detections in local_scan_result.document_detections: + document = document_detections.document for detection in document_detections.detections: - description = _describe_detection(detection, document_detections.document.content) + description = _describe_detection(detection, document) sha = detection.detection_details.get('sha512') - finding_by_key.setdefault(sha or description, (sha, description)) + finding_by_key.setdefault((document.path, sha or description), (sha, description)) listed = list(finding_by_key.values())[:max_lines] lines = [_build_severity_line(local_scan_results)] + [f' - {description}' for _, description in listed] @@ -141,7 +149,7 @@ def build_violation_summary( if remaining: lines.append(f' - ...and {remaining} more') - return '\n'.join(lines), tuple(sha for sha, _ in listed if sha) + return '\n'.join(lines), tuple(dict.fromkeys(sha for sha, _ in listed if sha)) def _build_severity_line(local_scan_results: list['LocalScanResult']) -> str: diff --git a/cycode/cli/files_collector/file_excluder.py b/cycode/cli/files_collector/file_excluder.py index 066d7669..bc1e0121 100644 --- a/cycode/cli/files_collector/file_excluder.py +++ b/cycode/cli/files_collector/file_excluder.py @@ -36,7 +36,7 @@ def _does_file_exceed_max_size_limit(filename: str) -> bool: return get_file_size(filename) > consts.FILE_MAX_SIZE_LIMIT_IN_BYTES -def _does_document_exceed_max_size_limit(content: str) -> bool: +def _does_document_exceed_max_size_limit(content: str | bytes) -> bool: return get_content_size(content) > consts.FILE_MAX_SIZE_LIMIT_IN_BYTES @@ -145,7 +145,7 @@ def _is_relevant_file_to_scan(self, scan_type: str, filename: str) -> bool: return not (scan_type == consts.SCA_SCAN_TYPE and not _is_file_relevant_for_sca_scan(filename)) - def _is_relevant_document_to_scan(self, scan_type: str, filename: str, content: str) -> bool: + def _is_relevant_document_to_scan(self, scan_type: str, filename: str, content: str | bytes) -> bool: if not self._is_relevant_file_to_scan_common(scan_type, filename): return False diff --git a/cycode/cli/files_collector/models/in_memory_zip.py b/cycode/cli/files_collector/models/in_memory_zip.py index b83e4833..9b6fe2ad 100644 --- a/cycode/cli/files_collector/models/in_memory_zip.py +++ b/cycode/cli/files_collector/models/in_memory_zip.py @@ -47,17 +47,16 @@ def __init__(self) -> None: self._files_count = 0 self._extension_statistics = defaultdict(int) - def append(self, filename: str, unique_id: str | None, content: str) -> None: + def append(self, filename: str, unique_id: str | None, content: str | bytes) -> None: self._files_count += 1 self._extension_statistics[Path(filename).suffix] += 1 if unique_id: filename = concat_unique_id(filename, unique_id) - # Encode content to bytes with error handling to handle surrogate characters - # that cannot be encoded to UTF-8. Use 'replace' to replace invalid characters - # with the Unicode replacement character (U+FFFD). - content_bytes = content.encode('utf-8', errors='replace') + # Bytes (an image) go in unchanged. Text is encoded with 'replace' so surrogate characters + # that cannot be encoded to UTF-8 become '?' instead of failing the scan. + content_bytes = content if isinstance(content, bytes) else content.encode('utf-8', errors='replace') self.zip.writestr(filename, content_bytes) def close(self) -> None: diff --git a/cycode/cli/models.py b/cycode/cli/models.py index c797aedf..ccd2e8d7 100644 --- a/cycode/cli/models.py +++ b/cycode/cli/models.py @@ -8,19 +8,30 @@ class Document: def __init__( self, path: str, - content: str, + content: str | bytes, is_git_diff_format: bool = False, unique_id: str | None = None, absolute_path: str | None = None, ) -> None: self.path = path + # bytes for binary content scanned as is (an image attached to an AI prompt); text otherwise self.content = content self.is_git_diff_format = is_git_diff_format self.unique_id = unique_id self.absolute_path = absolute_path + @property + def text_content(self) -> str: + """The content as text; '' for binary content. + + The server reads the text out of binary content (OCR of an image) and reports positions into that text, + which never exists locally, so there is no line or value to cut out of it here. + """ + return self.content if isinstance(self.content, str) else '' + def __repr__(self) -> str: - return f'path:{self.path}, content:{self.content}' + content = f'<{len(self.content)} bytes>' if isinstance(self.content, bytes) else self.content + return f'path:{self.path}, content:{content}' class DocumentDetections: diff --git a/cycode/cli/printers/tables/table_printer.py b/cycode/cli/printers/tables/table_printer.py index 4468ef9f..b7c540df 100644 --- a/cycode/cli/printers/tables/table_printer.py +++ b/cycode/cli/printers/tables/table_printer.py @@ -84,11 +84,11 @@ def _enrich_table_with_detection_code_segment_values( if self.scan_type == SECRET_SCAN_TYPE: detection_line = detection_details.get('line', -1) - detection_column = get_position_in_line(document.content, detection_details.get('start_position', -1)) + detection_column = get_position_in_line(document.text_content, detection_details.get('start_position', -1)) violation_length = detection_details.get('length', -1) violation = '' - file_content_lines = document.content.splitlines() + file_content_lines = document.text_content.splitlines() if detection_line < len(file_content_lines): line = file_content_lines[detection_line] violation = line[detection_column : detection_column + violation_length] diff --git a/cycode/cli/printers/utils/code_snippet_syntax.py b/cycode/cli/printers/utils/code_snippet_syntax.py index ceb2cc35..780c485a 100644 --- a/cycode/cli/printers/utils/code_snippet_syntax.py +++ b/cycode/cli/printers/utils/code_snippet_syntax.py @@ -50,11 +50,11 @@ def _get_code_snippet_syntax_from_file( detection_details = detection.detection_details detection_line = get_detection_line(scan_type, detection) start_line_index = _get_code_segment_start_line(detection_line, lines_to_display_before) - detection_position = get_position_in_line(document.content, detection_details.get('start_position', -1)) + detection_position = get_position_in_line(document.text_content, detection_details.get('start_position', -1)) violation_length = detection_details.get('length', -1) code_lines_to_render = [] - document_content_lines = document.content.splitlines() + document_content_lines = document.text_content.splitlines() total_lines_to_display = lines_to_display_before + 1 + lines_to_display_after for line_index in range(total_lines_to_display): @@ -89,9 +89,9 @@ def _get_code_snippet_syntax_from_git_diff( detection_position = detection_details.get('start_position', -1) violation_length = detection_details.get('length', -1) - document_content_lines = document.content.splitlines() + document_content_lines = document.text_content.splitlines() line_content = document_content_lines[detection_line] if 0 <= detection_line < len(document_content_lines) else '' - detection_position_in_line = get_position_in_line(document.content, detection_position) + detection_position_in_line = get_position_in_line(document.text_content, detection_position) if scan_type == consts.SECRET_SCAN_TYPE and obfuscate: violation = line_content[detection_position_in_line : detection_position_in_line + violation_length] line_content = line_content.replace(violation, obfuscate_text(violation)) diff --git a/cycode/cli/utils/scan_batch.py b/cycode/cli/utils/scan_batch.py index 5375b7a4..490b5b00 100644 --- a/cycode/cli/utils/scan_batch.py +++ b/cycode/cli/utils/scan_batch.py @@ -61,7 +61,8 @@ def split_documents_into_batches( current_size = 0 current_batch = [] for document in documents: - document_size = len(document.content.encode('UTF-8')) + content = document.content + document_size = len(content) if isinstance(content, bytes) else len(content.encode('UTF-8')) exceeds_max_size = current_size + document_size > max_size if exceeds_max_size: diff --git a/cycode/cli/utils/string_utils.py b/cycode/cli/utils/string_utils.py index 43931239..23400150 100644 --- a/cycode/cli/utils/string_utils.py +++ b/cycode/cli/utils/string_utils.py @@ -22,14 +22,14 @@ def obfuscate_text(text: str) -> str: obfuscate_regex = re.compile(r'[^+\-\s]') -def is_binary_content(content: str) -> bool: - """Get the first 1024 chars and check if it's binary or not.""" +def is_binary_content(content: str | bytes) -> bool: + """Get the first 1024 chars (or bytes) and check if it's binary or not.""" chunk = content[:1024] - chunk_bytes = convert_string_to_bytes(chunk) + chunk_bytes = chunk if isinstance(chunk, bytes) else convert_string_to_bytes(chunk) return is_binary_string(chunk_bytes) -def get_content_size(content: str) -> int: +def get_content_size(content: str | bytes) -> int: return getsizeof(content) diff --git a/tests/cli/commands/ai_guardrails/ides/test_contract.py b/tests/cli/commands/ai_guardrails/ides/test_contract.py index 44ba8d73..4d784a0f 100644 --- a/tests/cli/commands/ai_guardrails/ides/test_contract.py +++ b/tests/cli/commands/ai_guardrails/ides/test_contract.py @@ -8,6 +8,7 @@ from pathlib import Path import pytest +from pyfakefs.fake_filesystem import FakeFilesystem from cycode.cli.apps.ai_guardrails.ides import IDES from cycode.cli.apps.ai_guardrails.ides.base import IDE, DecisionAction, HookDecision @@ -145,6 +146,12 @@ def test_get_skills_returns_path_content_dicts(ide: IDE) -> None: assert isinstance(skill.get('content'), str) +def test_collect_prompt_images_finds_nothing_on_an_empty_disk(ide: IDE, fs: FakeFilesystem) -> None: + """Most IDEs never collect images; none returns an image that isn't there.""" + images = ide.collect_prompt_images({'session_id': 'session-1', 'prompt': '@shot.png [image: pasted.png]'}) + assert images == [] + + # HookDecision helpers diff --git a/tests/cli/commands/ai_guardrails/ides/test_copilot.py b/tests/cli/commands/ai_guardrails/ides/test_copilot.py index 7914e76a..2ced268b 100644 --- a/tests/cli/commands/ai_guardrails/ides/test_copilot.py +++ b/tests/cli/commands/ai_guardrails/ides/test_copilot.py @@ -6,8 +6,11 @@ import json import os +import tempfile +import time from pathlib import Path +import pytest from pyfakefs.fake_filesystem import FakeFilesystem from pytest_mock import MockerFixture @@ -16,8 +19,15 @@ Copilot, _read_copilot_plugin, _vscode_mcp_config_path, + _vscode_user_data_dir, split_mcp_tool_name, ) +from cycode.cli.apps.ai_guardrails.scan.prompt_images import ( + FIRST_PROMPT_LOOKBACK_SECONDS, + get_prompt_mark, + get_prompt_marks_path, + save_prompt_mark, +) from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType _VSCODE_PROMPT_PAYLOAD = { @@ -545,3 +555,139 @@ def test_get_skills_reads_user_scope_skills(fs: FakeFilesystem) -> None: def test_get_skills_no_skills_dir_returns_empty(fs: FakeFilesystem) -> None: assert Copilot().get_skills() == [] + + +# --- prompt images ---------------------------------------------------------------- + + +def _png(marker: bytes) -> bytes: + return b'\x89PNG\r\n\x1a\n' + marker + + +def _create_file(fs: FakeFilesystem, path: Path, content: bytes, modified_at: float | None = None) -> str: + fs.create_file(path, contents=content) + if modified_at is not None: + os.utime(path, (modified_at, modified_at)) + return str(path) + + +def _vscode_copy(fs: FakeFilesystem, name: str, content: bytes, modified_at: float, product_name: str = 'Code') -> str: + """A send-time copy of an attachment, in a chat's session data.""" + path = _vscode_user_data_dir(product_name) / 'agentSessionData' / 'chat-1' / 'attachments' / 'uuid-1' / name + return _create_file(fs, path, content, modified_at) + + +def _vscode_paste(fs: FakeFilesystem, name: str, content: bytes, modified_at: float, product_name: str = 'Code') -> str: + """A paste, saved when it was made to VS Code's shared chat-images folder.""" + path = _vscode_user_data_dir(product_name) / 'User' / 'workspaceStorage' / 'vscode-chat-images' / name + return _create_file(fs, path, content, modified_at) + + +def test_collect_prompt_images_finds_cli_mentions_against_cwd(fs: FakeFilesystem) -> None: + shot = _create_file(fs, Path('/Users/user/project/docs/shot.png'), _png(b'shot')) + spaced = _create_file(fs, Path('/Users/user/project/My Shot.png'), _png(b'spaced')) + absolute = _create_file(fs, Path('/elsewhere/abs.png'), _png(b'abs')) + _create_file(fs, Path('/Users/user/project/notes.txt'), b'not an image') + _create_file(fs, Path('/Users/user/project/example.com'), _png(b'not mentioned')) + payload = { + **_AGENT_PROMPT_PAYLOAD, + 'prompt': ( + 'compare @docs/shot.png, @"My Shot.png" and @/elsewhere/abs.png with @notes.txt ' + '(not @missing.png). Mail me@example.com' + ), + } + + images = Copilot().collect_prompt_images(payload) + + assert images == [shot, spaced, absolute] + + +@pytest.mark.skipif(os.sep != '/', reason='a backslash is a path separator on Windows') +def test_collect_prompt_images_unescapes_spaces_in_a_dragged_path(fs: FakeFilesystem) -> None: + shot = _create_file(fs, Path('/Users/user/Desktop/Screenshot 2026-11-09 at 10.15.32.png'), _png(b'shot')) + payload = {**_AGENT_PROMPT_PAYLOAD, 'prompt': r'@/Users/user/Desktop/Screenshot\ 2026-11-09\ at\ 10.15.32.png ?'} + + assert Copilot().collect_prompt_images(payload) == [shot] + + +def test_collect_prompt_images_finds_cli_paste_in_the_temp_dir(fs: FakeFilesystem) -> None: + temp_dir = Path(tempfile.gettempdir()) + pasted = _create_file(fs, temp_dir / 'copilot-image-3f2a9c.png', _png(b'pasted')) + _create_file(fs, Path('/etc/outside.png'), _png(b'outside')) + payload = { + **_AGENT_PROMPT_PAYLOAD, + 'prompt': 'what is this? [image: copilot-image-3f2a9c.png] and [image: ../../etc/outside.png]', + } + + # The placeholder is prompt text: only its base name is looked up, inside the temp directory + assert Copilot().collect_prompt_images(payload) == [pasted] + + +@pytest.mark.parametrize('system', ['Darwin', 'Linux', 'Windows']) +@pytest.mark.parametrize('product_name', ['Code', 'Code - Insiders']) +def test_collect_prompt_images_finds_vscode_attachments( + fs: FakeFilesystem, mocker: MockerFixture, system: str, product_name: str +) -> None: + mocker.patch('cycode.cli.apps.ai_guardrails.ides.copilot.platform.system', return_value=system) + now = time.time() + copy = _vscode_copy(fs, 'diagram.png', _png(b'copy'), now - 5, product_name) + paste = _vscode_paste(fs, 'image-1784034535752.png', _png(b'paste'), now - 20, product_name) + + images = Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD) + + # Copies first, then pastes + assert images == [copy, paste] + + +@pytest.mark.parametrize( + ('system', 'base_parts'), + [ + ('Darwin', ('Library', 'Application Support')), + ('Linux', ('.config',)), + ('Windows', ('AppData', 'Roaming')), + ], +) +def test_vscode_user_data_dir_per_platform(mocker: MockerFixture, system: str, base_parts: tuple[str, ...]) -> None: + mocker.patch('cycode.cli.apps.ai_guardrails.ides.copilot.platform.system', return_value=system) + + assert _vscode_user_data_dir() == Path.home().joinpath(*base_parts, 'Code') + assert _vscode_user_data_dir('Code - Insiders') == Path.home().joinpath(*base_parts, 'Code - Insiders') + assert _vscode_mcp_config_path() == Path.home().joinpath(*base_parts, 'Code', 'User', 'mcp.json') + + +def test_collect_prompt_images_keeps_a_paste_saved_twice_once(fs: FakeFilesystem) -> None: + """The Copilot harness copies a paste on send, so the same bytes are in both folders.""" + now = time.time() + copy = _vscode_copy(fs, 'image.png', _png(b'same'), now - 2) + _vscode_paste(fs, 'image-1784034535752.png', _png(b'same'), now - 30) + + assert Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD) == [copy] + + +def test_first_prompt_takes_vscode_attachments_from_the_lookback(fs: FakeFilesystem) -> None: + now = time.time() + recent = _vscode_paste(fs, 'image-recent.png', _png(b'recent'), now - (FIRST_PROMPT_LOOKBACK_SECONDS - 60)) + _vscode_paste(fs, 'image-old.png', _png(b'old'), now - (FIRST_PROMPT_LOOKBACK_SECONDS + 60)) + + assert Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD) == [recent] + + +def test_later_prompt_takes_vscode_attachments_since_the_previous_one(fs: FakeFilesystem) -> None: + session_id = _VSCODE_PROMPT_PAYLOAD['session_id'] + now = time.time() + save_prompt_mark(session_id, now - 60) + _vscode_paste(fs, 'image-previous-prompt.png', _png(b'previous'), now - 120) + current = _vscode_paste(fs, 'image-this-prompt.png', _png(b'current'), now - 10) + + assert Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD) == [current] + # The mark moved to this prompt, so its images are not collected again by the next one + assert get_prompt_mark(session_id, time.time()) >= now + assert Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD) == [] + + +def test_collect_prompt_images_marks_only_the_prompting_session(fs: FakeFilesystem) -> None: + Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD) + Copilot().collect_prompt_images({k: v for k, v in _AGENT_PROMPT_PAYLOAD.items() if k != 'session_id'}) + + marks = json.loads(get_prompt_marks_path().read_text(encoding='utf-8')) + assert list(marks) == [_VSCODE_PROMPT_PAYLOAD['session_id']] diff --git a/tests/cli/commands/ai_guardrails/scan/conftest.py b/tests/cli/commands/ai_guardrails/scan/conftest.py index 4e5d85b6..4909de1a 100644 --- a/tests/cli/commands/ai_guardrails/scan/conftest.py +++ b/tests/cli/commands/ai_guardrails/scan/conftest.py @@ -10,6 +10,7 @@ def resolved_guardrails_payload( mcp: str = 'Report', globs: list | None = None, mcp_server: str | None = None, + scan_images: bool | None = None, ) -> dict: """A platform resolved-config payload with the given per-guardrail modes for the cursor agent.""" payload = { @@ -26,6 +27,8 @@ def resolved_guardrails_payload( {'key': 'secrets_in_mcp_args', 'event_type': 'McpExecution', 'agents': {'cursor': mcp}}, ], } + if scan_images is not None: + payload['guardrails'][0]['scan_images'] = scan_images if mcp_server is not None: payload['guardrails'].append( { @@ -38,9 +41,9 @@ def resolved_guardrails_payload( return payload -def platform_config(fetched_at: float | None = None, **modes: str | None) -> GuardrailConfig: - """A cached platform config; keyword args are the per-guardrail modes (see resolved_guardrails_payload).""" +def platform_config(fetched_at: float | None = None, **settings: str | bool | None) -> GuardrailConfig: + """A cached platform config; keyword args are the per-guardrail settings (see resolved_guardrails_payload).""" return GuardrailConfig( - payload=resolved_guardrails_payload(**modes), + payload=resolved_guardrails_payload(**settings), fetched_at=time.time() if fetched_at is None else fetched_at, ) diff --git a/tests/cli/commands/ai_guardrails/scan/test_guardrail_config.py b/tests/cli/commands/ai_guardrails/scan/test_guardrail_config.py index 90065d93..cd7eed64 100644 --- a/tests/cli/commands/ai_guardrails/scan/test_guardrail_config.py +++ b/tests/cli/commands/ai_guardrails/scan/test_guardrail_config.py @@ -203,3 +203,36 @@ def test_apply_platform_config_mcp_server_cells() -> None: assert policy['mcp']['check_server'] is True assert policy['mcp']['server_action'] == 'warn' assert policy['mcp']['action'] == 'warn' + + +# --- images attached to prompts --- + + +def test_prompt_images_are_scanned_only_when_the_platform_says_so() -> None: + assert _config(scan_images=True).scans_prompt_images() is True + assert _config(scan_images=False).scans_prompt_images() is False + # A platform that predates the setting doesn't read images, so a missing value means text only + assert _config().scans_prompt_images() is False + + +def test_prompt_images_setting_ignores_other_guardrails() -> None: + payload = _payload() + payload['guardrails'][1]['scan_images'] = True # secrets_in_file + assert GuardrailConfig(payload=payload, fetched_at=time.time()).scans_prompt_images() is False + + +@pytest.mark.parametrize( + ('config', 'expected'), + [ + (None, False), # no cache: nothing says the platform reads images + (_config(), False), + (_config(scan_images=False), False), + (_config(scan_images=True), True), + ], +) +def test_apply_platform_config_sets_prompt_scan_images(config: GuardrailConfig | None, expected: bool) -> None: + policy: dict = {} + + apply_platform_config(policy, config, 'copilot') + + assert policy['prompt']['scan_images'] is expected diff --git a/tests/cli/commands/ai_guardrails/scan/test_handlers.py b/tests/cli/commands/ai_guardrails/scan/test_handlers.py index 41ab6c33..91c6f12f 100644 --- a/tests/cli/commands/ai_guardrails/scan/test_handlers.py +++ b/tests/cli/commands/ai_guardrails/scan/test_handlers.py @@ -74,7 +74,7 @@ def default_policy() -> dict[str, Any]: # Tests for handle_before_submit_prompt -@patch('cycode.cli.apps.ai_guardrails.scan.handlers._scan_text_for_secrets') +@patch('cycode.cli.apps.ai_guardrails.scan.handlers._scan_prompt_for_secrets') def test_handle_before_submit_prompt_no_secrets( mock_scan: MagicMock, mock_ctx: MagicMock, mock_payload: AIHookPayload, default_policy: dict[str, Any] ) -> None: @@ -92,7 +92,7 @@ def test_handle_before_submit_prompt_no_secrets( assert call_args.kwargs['block_reason'] is None -@patch('cycode.cli.apps.ai_guardrails.scan.handlers._scan_text_for_secrets') +@patch('cycode.cli.apps.ai_guardrails.scan.handlers._scan_prompt_for_secrets') def test_handle_before_submit_prompt_with_secrets_blocked( mock_scan: MagicMock, mock_ctx: MagicMock, mock_payload: AIHookPayload, default_policy: dict[str, Any] ) -> None: @@ -125,7 +125,7 @@ def test_handle_before_submit_prompt_with_secrets_blocked( ) -@patch('cycode.cli.apps.ai_guardrails.scan.handlers._scan_text_for_secrets') +@patch('cycode.cli.apps.ai_guardrails.scan.handlers._scan_prompt_for_secrets') def test_handle_before_submit_prompt_with_secrets_warned( mock_scan: MagicMock, mock_ctx: MagicMock, mock_payload: AIHookPayload, default_policy: dict[str, Any] ) -> None: @@ -141,7 +141,7 @@ def test_handle_before_submit_prompt_with_secrets_warned( assert call_args.args[2] == AIHookOutcome.WARNED -@patch('cycode.cli.apps.ai_guardrails.scan.handlers._scan_text_for_secrets') +@patch('cycode.cli.apps.ai_guardrails.scan.handlers._scan_prompt_for_secrets') def test_handle_before_submit_prompt_scan_failure_fail_open( mock_scan: MagicMock, mock_ctx: MagicMock, mock_payload: AIHookPayload, default_policy: dict[str, Any] ) -> None: @@ -158,7 +158,7 @@ def test_handle_before_submit_prompt_scan_failure_fail_open( assert call_args.kwargs['block_reason'] == BlockReason.SCAN_FAILURE -@patch('cycode.cli.apps.ai_guardrails.scan.handlers._scan_text_for_secrets') +@patch('cycode.cli.apps.ai_guardrails.scan.handlers._scan_prompt_for_secrets') def test_handle_before_submit_prompt_scan_failure_fail_closed( mock_scan: MagicMock, mock_ctx: MagicMock, mock_payload: AIHookPayload, default_policy: dict[str, Any] ) -> None: @@ -550,6 +550,140 @@ def test_violation_summary_lists_findings_without_a_sha() -> None: assert shas == () +# Tests for images attached to prompts + +_PNG = b'\x89PNG\r\n\x1a\n' + b'\x00\x00\x00\rIHDR' +_JPEG = b'\xff\xd8\xff\xe0' + b'\x00\x10JFIF' + + +def _scanned_documents(mock_perform_scan: MagicMock) -> list[Document]: + return mock_perform_scan.call_args.args[1] + + +@patch('cycode.cli.apps.ai_guardrails.scan.handlers._perform_scan', return_value=ScanOutcome(scan_id='scan-id-1')) +def test_prompt_and_its_images_are_scanned_together( + mock_perform_scan: MagicMock, mock_ctx: MagicMock, mock_payload: AIHookPayload, default_policy: dict, fs: Any +) -> None: + fs.create_file('/images/shot.png', contents=_PNG) + fs.create_file('/images/Screenshot', contents=_JPEG) + mock_payload.image_paths = ['/images/shot.png', '/images/Screenshot'] + + result = handle_before_submit_prompt(mock_ctx, mock_payload, default_policy) + + assert result == HookDecision.allow(AiHookEventType.PROMPT) + mock_perform_scan.assert_called_once() + documents = _scanned_documents(mock_perform_scan) + # Image entries keep an image extension: the server picks what to read text out of by extension and signature + assert [document.path for document in documents] == [ + 'prompt-content.txt', + 'image-1-shot.png', + 'image-2-Screenshot.jpg', + ] + assert documents[0].content == 'Test prompt' + assert documents[1].content == _PNG + assert documents[2].content == _JPEG + assert documents[2].absolute_path == '/images/Screenshot' + # One scan, one event, labelled as a prompt + assert mock_perform_scan.call_args.args[2]['metadata']['ai_guardrails']['detection_source'] == 'secrets_in_prompt' + mock_ctx.obj['ai_security_client'].create_event.assert_called_once() + assert mock_ctx.obj['ai_security_client'].create_event.call_args.kwargs['scan_id'] == 'scan-id-1' + + +@patch('cycode.cli.apps.ai_guardrails.scan.handlers._perform_scan', return_value=ScanOutcome(scan_id='scan-id-1')) +def test_prompt_with_only_an_image_is_scanned( + mock_perform_scan: MagicMock, mock_ctx: MagicMock, mock_payload: AIHookPayload, default_policy: dict, fs: Any +) -> None: + fs.create_file('/images/shot.png', contents=_PNG) + mock_payload.prompt = '' + mock_payload.image_paths = ['/images/shot.png'] + + handle_before_submit_prompt(mock_ctx, mock_payload, default_policy) + + assert [document.path for document in _scanned_documents(mock_perform_scan)] == ['image-1-shot.png'] + + +@patch('cycode.cli.apps.ai_guardrails.scan.handlers._perform_scan') +def test_prompt_without_text_or_images_is_not_scanned( + mock_perform_scan: MagicMock, mock_ctx: MagicMock, mock_payload: AIHookPayload, default_policy: dict, fs: Any +) -> None: + mock_payload.prompt = '' + # Gone between collection and the scan: nothing left to send + mock_payload.image_paths = ['/images/deleted.png'] + + result = handle_before_submit_prompt(mock_ctx, mock_payload, default_policy) + + assert result == HookDecision.allow(AiHookEventType.PROMPT) + mock_perform_scan.assert_not_called() + assert mock_ctx.obj['ai_security_client'].create_event.call_args.kwargs['scan_id'] is None + + +def _image_finding_scan(batch: list[Document]) -> tuple[str, None, LocalScanResult]: + """A server answer with one Block-verdict secret in the prompt text and one in the attached image.""" + + def detection(sha: str) -> Detection: + return Detection( + detection_type_id='type-id', + type='GitHub Token', + message='Hardcoded secret', + detection_details={'sha512': sha, 'line': 0, 'start_position': 0, 'length': 4}, + detection_rule_id='rule-id', + severity='High', + ) + + text_document, image_document = batch + return ( + 'scan-id-1', + None, + LocalScanResult( + scan_id='scan-id-1', + report_url=None, + document_detections=[ + DocumentDetections(document=text_document, detections=[detection('sha-text')]), + DocumentDetections(document=image_document, detections=[detection('sha-image')]), + ], + issue_detected=True, + detections_count=2, + relevant_detections_count=2, + verdict='Block', + ), + ) + + +def test_blocked_prompt_names_the_image_the_secret_is_in( + mock_ctx: MagicMock, mock_payload: AIHookPayload, default_policy: dict, fs: Any +) -> None: + fs.create_file('/attachments/uuid-1/diagram.png', contents=_PNG) + mock_payload.prompt = 'ghp_ in the text' + mock_payload.image_paths = ['/attachments/uuid-1/diagram.png'] + + with patch( + 'cycode.cli.apps.ai_guardrails.scan.handlers._get_scan_documents_thread_func', + return_value=_image_finding_scan, + ): + result = handle_before_submit_prompt(mock_ctx, mock_payload, default_policy) + + assert result.action == DecisionAction.DENY + assert ' - GitHub Token (line 1): g**_\n' in result.user_message + # Positions in an image point into text the server read out of it: the developer is told the file instead + assert ' - GitHub Token in image "diagram.png"\n' in result.user_message + assert 'ignore --by-sha sha-image' in result.user_message + assert mock_ctx.obj['ai_security_client'].create_event.call_args.args[2] == AIHookOutcome.BLOCKED + + +def test_violation_summary_lists_a_value_once_per_document() -> None: + """The same value in the prompt and in an image is two places to remove it from, but one value to ignore.""" + local_scan_result = _local_scan_result_with_detections('sha-aaa') + image = Document(path='image-1-shot.png', content=_PNG, absolute_path='/pasted/copilot-image-1.png') + local_scan_result.document_detections.append( + DocumentDetections(document=image, detections=local_scan_result.document_detections[0].detections) + ) + + summary, shas = build_violation_summary([local_scan_result]) + + assert summary.splitlines()[1:] == [' - GitHub Token', ' - GitHub Token in image "copilot-image-1.png"'] + assert shas == ('sha-aaa',) + + # Tests for handle_before_mcp_execution diff --git a/tests/cli/commands/ai_guardrails/scan/test_prompt_images.py b/tests/cli/commands/ai_guardrails/scan/test_prompt_images.py new file mode 100644 index 00000000..ef51aa70 --- /dev/null +++ b/tests/cli/commands/ai_guardrails/scan/test_prompt_images.py @@ -0,0 +1,199 @@ +"""Tests for prompt image filters and the per-session prompt marks.""" + +import json +import os +import time +from pathlib import Path + +import pytest +from pyfakefs.fake_filesystem import FakeFilesystem + +from cycode.cli.apps.ai_guardrails.scan.prompt_images import ( + FIRST_PROMPT_LOOKBACK_SECONDS, + MAX_PROMPT_IMAGES, + get_prompt_mark, + get_prompt_marks_path, + image_file_name, + modified_between, + read_prompt_image, + save_prompt_mark, + select_prompt_images, +) +from cycode.cli.consts import FILE_MAX_SIZE_LIMIT_IN_BYTES + +PNG_SIGNATURE = b'\x89PNG\r\n\x1a\n' +JPEG_SIGNATURE = b'\xff\xd8\xff\xe0' + + +def png(marker: bytes = b'') -> bytes: + return PNG_SIGNATURE + b'\x00\x00\x00\rIHDR' + marker + + +def jpeg(marker: bytes = b'') -> bytes: + return JPEG_SIGNATURE + b'\x00\x10JFIF' + marker + + +@pytest.fixture(autouse=True) +def _fake_fs(fs: FakeFilesystem) -> FakeFilesystem: + return fs + + +# --- prompt marks --- + + +def test_first_prompt_looks_back_a_fixed_time() -> None: + now = time.time() + + assert get_prompt_mark('session-1', now) == now - FIRST_PROMPT_LOOKBACK_SECONDS + # No session id to keep a mark under: every prompt looks back + assert get_prompt_mark(None, now) == now - FIRST_PROMPT_LOOKBACK_SECONDS + + +def test_saved_mark_bounds_the_next_prompt_of_that_session_only() -> None: + now = time.time() + save_prompt_mark('session-1', now - 30) + + assert get_prompt_mark('session-1', now) == now - 30 + assert get_prompt_mark('session-2', now) == now - FIRST_PROMPT_LOOKBACK_SECONDS + + +def test_saving_without_a_session_id_writes_nothing() -> None: + save_prompt_mark(None, time.time()) + + assert not get_prompt_marks_path().exists() + + +def test_mark_after_now_is_clamped() -> None: + """A mark written before the clock was set back must not hide every new file.""" + now = time.time() + save_prompt_mark('session-1', now + 3600) + + assert get_prompt_mark('session-1', now) == now + + +def test_marks_of_sessions_idle_for_a_week_are_pruned_on_save() -> None: + now = time.time() + save_prompt_mark('stale', now - 8 * 24 * 60 * 60) + save_prompt_mark('recent', now - 6 * 24 * 60 * 60) + + save_prompt_mark('current', now) + + marks = json.loads(get_prompt_marks_path().read_text(encoding='utf-8')) + assert set(marks) == {'recent', 'current'} + + +@pytest.mark.parametrize('content', ['not json {', '["a list"]', '{"session-1": "not a number"}']) +def test_corrupt_marks_are_moved_aside(fs: FakeFilesystem, content: str) -> None: + path = get_prompt_marks_path() + fs.create_file(str(path), contents=content) + now = time.time() + + assert get_prompt_mark('session-1', now) == now - FIRST_PROMPT_LOOKBACK_SECONDS + assert not path.exists() + assert Path(f'{path}.corrupt').exists() + + # The next save starts a fresh file + save_prompt_mark('session-1', now) + assert get_prompt_mark('session-1', now + 1) == now + + +# --- modified_between --- + + +def test_modified_between_is_half_open_and_oldest_first(fs: FakeFilesystem) -> None: + # Whole seconds: a fractional mtime may not survive the round trip through nanoseconds exactly + now = float(int(time.time())) + since = now - 100 + files = {} + for name, modified_at in ( + ('newer.png', now - 10), + ('older.png', now - 50), + ('at-since.png', since), + ('before.png', since - 1), + ('at-until.png', now), + ): + files[name] = fs.create_file(f'/attachments/{name}').path + os.utime(files[name], (modified_at, modified_at)) + + selected = modified_between([Path(path) for path in files.values()], since, now) + + # The file stamped exactly `until` belongs to the next prompt, whose window starts there + assert [path.name for path in selected] == ['at-since.png', 'older.png', 'newer.png'] + + +def test_modified_between_skips_vanished_files() -> None: + assert modified_between([Path('/attachments/gone.png')], 0, time.time()) == [] + + +# --- filters --- + + +def test_png_and_jpeg_are_read_by_signature_whatever_their_extension(fs: FakeFilesystem) -> None: + fs.create_file('/images/shot.png', contents=png()) + fs.create_file('/images/photo.jpeg', contents=jpeg()) + fs.create_file('/images/no-extension', contents=png()) + fs.create_file('/images/fake.png', contents=b'GIF89a not a png') + fs.create_file('/images/notes.txt', contents='hello') + + assert read_prompt_image('/images/shot.png') == png() + assert read_prompt_image('/images/photo.jpeg') == jpeg() + assert read_prompt_image('/images/no-extension') == png() + assert read_prompt_image('/images/fake.png') is None + assert read_prompt_image('/images/notes.txt') is None + + +def test_only_regular_files_within_the_size_limit_are_read(fs: FakeFilesystem) -> None: + fs.create_dir('/images/a-directory.png') + fs.create_file('/images/at-limit.png', contents=png().ljust(FILE_MAX_SIZE_LIMIT_IN_BYTES, b'\x00')) + fs.create_file('/images/over-limit.png', contents=png().ljust(FILE_MAX_SIZE_LIMIT_IN_BYTES + 1, b'\x00')) + + assert read_prompt_image('/images/a-directory.png') is None + assert read_prompt_image('/images/missing.png') is None + assert len(read_prompt_image('/images/at-limit.png')) == FILE_MAX_SIZE_LIMIT_IN_BYTES + assert read_prompt_image('/images/over-limit.png') is None + + +def test_select_keeps_order_and_drops_non_images(fs: FakeFilesystem) -> None: + fs.create_file('/images/b.png', contents=png(b'b')) + fs.create_file('/images/a.jpg', contents=jpeg(b'a')) + fs.create_file('/images/readme.md', contents='# hi') + + selected = select_prompt_images(['/images/b.png', '/images/readme.md', Path('/images/a.jpg'), '/images/gone.png']) + + assert selected == ['/images/b.png', str(Path('/images/a.jpg'))] + + +def test_select_keeps_one_path_per_content(fs: FakeFilesystem) -> None: + """VS Code saves a paste when it is made and copies it again on send: one image, two files.""" + fs.create_file('/sent/image.png', contents=png(b'same')) + fs.create_file('/pasted/image-1784034535752.png', contents=png(b'same')) + fs.create_file('/pasted/image-1784034535999.png', contents=png(b'other')) + + selected = select_prompt_images( + ['/sent/image.png', '/pasted/image-1784034535752.png', '/pasted/image-1784034535999.png'] + ) + + assert selected == ['/sent/image.png', '/pasted/image-1784034535999.png'] + + +def test_select_caps_the_number_of_images(fs: FakeFilesystem) -> None: + paths = [] + for index in range(MAX_PROMPT_IMAGES + 2): + paths.append(f'/images/{index}.png') + fs.create_file(paths[-1], contents=png(str(index).encode())) + # Same content as 0.png: the copy is listed first, and 0.png then takes no slot under the cap + fs.create_file('/images/copy.png', contents=png(b'0')) + + selected = select_prompt_images(['/images/copy.png', *paths]) + + assert selected == ['/images/copy.png', *paths[1:MAX_PROMPT_IMAGES]] + assert len(selected) == MAX_PROMPT_IMAGES + + +def test_image_file_name_names_the_actual_format() -> None: + assert image_file_name('/x/shot.png', png()) == 'shot.png' + assert image_file_name('/x/photo.JPEG', jpeg()) == 'photo.JPEG' + assert image_file_name('/x/photo.jpg', jpeg()) == 'photo.jpg' + # The server picks images by extension as well as signature, so a missing or wrong one is completed + assert image_file_name('/x/screenshot', png()) == 'screenshot.png' + assert image_file_name('/x/actually-a-jpeg.png', jpeg()) == 'actually-a-jpeg.png.jpg' diff --git a/tests/cli/commands/ai_guardrails/scan/test_scan_command.py b/tests/cli/commands/ai_guardrails/scan/test_scan_command.py index f6afccb6..374b1d27 100644 --- a/tests/cli/commands/ai_guardrails/scan/test_scan_command.py +++ b/tests/cli/commands/ai_guardrails/scan/test_scan_command.py @@ -1,20 +1,24 @@ """Tests for AI guardrails scan command.""" import json +import os import time from io import StringIO from unittest.mock import MagicMock import pytest +from pyfakefs.fake_filesystem import FakeFilesystem from pytest_mock import MockerFixture from typer.testing import CliRunner from cycode.cli.apps.ai_guardrails import app as ai_guardrails_app from cycode.cli.apps.ai_guardrails.ides.base import HookDecision +from cycode.cli.apps.ai_guardrails.ides.copilot import Copilot, _vscode_user_data_dir from cycode.cli.apps.ai_guardrails.scan.guardrail_config import GuardrailConfig +from cycode.cli.apps.ai_guardrails.scan.prompt_images import get_prompt_marks_path from cycode.cli.apps.ai_guardrails.scan.scan_command import scan_command from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType -from tests.cli.commands.ai_guardrails.scan.conftest import platform_config +from tests.cli.commands.ai_guardrails.scan.conftest import platform_config, resolved_guardrails_payload @pytest.fixture(autouse=True) @@ -569,6 +573,128 @@ def test_failed_respawn_falls_back_to_synchronous_scan( handler.assert_called_once() +def _copilot_config(prompt: str = 'Block', **settings: str | bool | None) -> GuardrailConfig: + """A cached platform config whose copilot cells are Block, except the prompt one given.""" + payload = resolved_guardrails_payload(**settings) + for guardrail in payload['guardrails']: + guardrail['agents']['copilot'] = prompt if guardrail['key'] == 'secrets_in_prompt' else 'Block' + return GuardrailConfig(payload=payload, fetched_at=time.time()) + + +class TestPromptImages: + """Images attached to Copilot prompts: collected once, when the tenant scans them, by the process that scans.""" + + _PAYLOAD = { # noqa: RUF012 + 'timestamp': '2026-11-09T10:15:32.000Z', + 'hook_event_name': 'UserPromptSubmit', + 'session_id': 'session-images-1', + 'prompt': 'what does this screenshot say?', + } + + @pytest.fixture + def respawn(self, mocker: MockerFixture) -> MagicMock: + return mocker.patch('cycode.cli.apps.ai_guardrails.scan.scan_command.respawn_detached', return_value=True) + + @pytest.fixture + def handler(self, mocker: MockerFixture, respawn: MagicMock) -> MagicMock: + mocker.patch('cycode.cli.apps.ai_guardrails.scan.scan_command._initialize_clients') + handler = MagicMock(return_value=HookDecision.allow(AiHookEventType.PROMPT)) + mocker.patch('cycode.cli.apps.ai_guardrails.scan.scan_command.get_handler_for_event', return_value=handler) + mocker.patch('cycode.cli.apps.ai_guardrails.scan.scan_command.load_policy', return_value={'fail_open': True}) + return handler + + @pytest.fixture + def collect(self, mocker: MockerFixture) -> MagicMock: + return mocker.patch.object(Copilot, 'collect_prompt_images', return_value=['/pasted/copilot-image-1.png']) + + def _run(self, mock_ctx: MagicMock, mocker: MockerFixture, config: GuardrailConfig | None, payload: dict) -> None: + mocker.patch('sys.stdin', StringIO(json.dumps(payload))) + mocker.patch('cycode.cli.apps.ai_guardrails.scan.scan_command.load_guardrail_config', return_value=config) + scan_command(mock_ctx, ide='copilot') + + def test_images_are_collected_when_the_tenant_scans_them( + self, mock_ctx: MagicMock, mocker: MockerFixture, handler: MagicMock, collect: MagicMock, respawn: MagicMock + ) -> None: + self._run(mock_ctx, mocker, _copilot_config(scan_images=True), self._PAYLOAD) + + respawn.assert_not_called() + collect.assert_called_once_with(self._PAYLOAD) + assert handler.call_args.args[1].image_paths == ['/pasted/copilot-image-1.png'] + + @pytest.mark.parametrize('config', [None, _copilot_config(), _copilot_config(scan_images=False)]) + def test_text_only_without_the_setting( + self, + mock_ctx: MagicMock, + mocker: MockerFixture, + handler: MagicMock, + collect: MagicMock, + config: GuardrailConfig | None, + ) -> None: + self._run(mock_ctx, mocker, config, self._PAYLOAD) + + collect.assert_not_called() + handler.assert_called_once() + assert handler.call_args.args[1].image_paths == [] + + def test_only_prompt_events_collect_images( + self, mock_ctx: MagicMock, mocker: MockerFixture, handler: MagicMock, collect: MagicMock, fs: FakeFilesystem + ) -> None: + fs.create_file('/Users/user/.gitconfig') + payload = { + 'timestamp': '2026-11-09T10:15:33.000Z', + 'hook_event_name': 'PreToolUse', + 'session_id': 'session-images-1', + 'tool_name': 'read_file', + 'tool_input': {'filePath': '/Users/user/.gitconfig'}, + } + + self._run(mock_ctx, mocker, _copilot_config(scan_images=True), payload) + + collect.assert_not_called() + handler.assert_called_once() + + def test_failed_collection_still_scans_the_text( + self, mock_ctx: MagicMock, mocker: MockerFixture, handler: MagicMock, collect: MagicMock + ) -> None: + collect.side_effect = RuntimeError('unexpected') + + self._run(mock_ctx, mocker, _copilot_config(scan_images=True), self._PAYLOAD) + + handler.assert_called_once() + assert handler.call_args.args[1].image_paths == [] + + def test_images_are_collected_by_the_detached_child_not_the_parent( + self, + mock_ctx: MagicMock, + mocker: MockerFixture, + monkeypatch: pytest.MonkeyPatch, + handler: MagicMock, + respawn: MagicMock, + fs: FakeFilesystem, + ) -> None: + """Collecting moves the session's prompt mark past the image, so a parent that collected before detaching + would leave the child that scans nothing to find.""" + paste = _vscode_user_data_dir() / 'User' / 'workspaceStorage' / 'vscode-chat-images' / 'image-1.png' + fs.create_file(paste, contents=b'\x89PNG\r\n\x1a\n' + b'pasted') + os.utime(paste, (time.time() - 5, time.time() - 5)) + config = _copilot_config(prompt='Report', scan_images=True) # the parent detaches + + monkeypatch.delenv('_CYCODE_DETACHED', raising=False) + self._run(mock_ctx, mocker, config, self._PAYLOAD) + + respawn.assert_called_once() + handler.assert_not_called() + assert not get_prompt_marks_path().exists() + + monkeypatch.setenv('_CYCODE_DETACHED', '1') + self._run(mock_ctx, mocker, config, self._PAYLOAD) + + respawn.assert_called_once() + handler.assert_called_once() + assert handler.call_args.args[1].image_paths == [str(paste)] + assert self._PAYLOAD['session_id'] in json.loads(get_prompt_marks_path().read_text(encoding='utf-8')) + + class TestDefaultIdeParameterViaCli: """Tests that verify default IDE parameter works correctly via CLI invocation.""" diff --git a/tests/cli/files_collector/test_in_memory_zip.py b/tests/cli/files_collector/test_in_memory_zip.py index afd807e5..f81acebb 100644 --- a/tests/cli/files_collector/test_in_memory_zip.py +++ b/tests/cli/files_collector/test_in_memory_zip.py @@ -195,3 +195,19 @@ def test_is_rolled_over_matches_the_interpreter(monkeypatch: 'MonkeyPatch', spoo assert zip_file.is_rolled_over is rolled_by_interpreter zip_file.cleanup() + + +def test_append_bytes_round_trips_unchanged() -> None: + """Binary content (an image attached to an AI prompt) must reach the server byte for byte.""" + image = b'\x89PNG\r\n\x1a\n' + bytes(range(256)) + b'\xff\xfe\xed' + zip_file = InMemoryZip() + zip_file.append('image-1-shot.png', None, image) + zip_file.append('prompt-content.txt', None, 'text \udc96 stays utf-8') + zip_file.close() + + with zipfile.ZipFile(BytesIO(zip_file.read()), 'r') as zf: + assert zf.read('image-1-shot.png') == image + # Text keeps the surrogate-safe encoding + assert zf.read('prompt-content.txt') == b'text ? stays utf-8' + + assert zip_file.extension_statistics == {'.png': 1, '.txt': 1} diff --git a/tests/cli/models/test_document.py b/tests/cli/models/test_document.py new file mode 100644 index 00000000..d838762f --- /dev/null +++ b/tests/cli/models/test_document.py @@ -0,0 +1,46 @@ +"""Binary (bytes) documents must be safe everywhere a document's content is read.""" + +from cycode.cli.models import Document +from cycode.cli.printers.utils.code_snippet_syntax import get_code_snippet_syntax +from cycode.cli.utils.scan_batch import split_documents_into_batches +from cycode.cli.utils.string_utils import is_binary_content +from cycode.cyclient.models import Detection + +_IMAGE = b'\x89PNG\r\n\x1a\n' + b'\x00' * 100 + + +def test_text_content_is_empty_for_bytes() -> None: + assert Document('prompt-content.txt', 'some text').text_content == 'some text' + assert Document('image-1-shot.png', _IMAGE).text_content == '' + + +def test_repr_does_not_dump_bytes() -> None: + assert repr(Document('image-1-shot.png', _IMAGE)) == f'path:image-1-shot.png, content:<{len(_IMAGE)} bytes>' + assert repr(Document('a.txt', 'abc')) == 'path:a.txt, content:abc' + + +def test_batches_count_bytes_as_they_are() -> None: + documents = [Document('image-1-shot.png', _IMAGE), Document('prompt-content.txt', 'ΓΌ')] + + assert split_documents_into_batches('secret', documents) == [documents] + + +def test_bytes_content_is_binary() -> None: + assert is_binary_content(_IMAGE) is True + assert is_binary_content('plain text') is False + + +def test_code_snippet_of_a_bytes_document_is_empty() -> None: + """Positions on an image point into text the server read out of it; there is nothing local to show.""" + detection = Detection( + detection_type_id='type-id', + type='GitHub Token', + message='Hardcoded secret', + detection_details={'line': 0, 'start_position': 3, 'length': 10}, + detection_rule_id='rule-id', + severity='High', + ) + + snippet = get_code_snippet_syntax('secret', 'scan', detection, Document('image-1-shot.png', _IMAGE)) + + assert snippet.code == '' From 1ca6c876a33c17e28147937a1b372fd084c25c83 Mon Sep 17 00:00:00 2001 From: Nikita Fishbakh Date: Tue, 10 Nov 2026 12:32:58 +0100 Subject: [PATCH 2/7] CM-77702: Read every @ mention on its own A mention whose quote was left open read to the next quote anywhere in the prompt, so the image mentions in between went unscanned. Co-Authored-By: Claude Opus 5.5 --- cycode/cli/apps/ai_guardrails/ides/copilot.py | 6 ++++-- .../cli/commands/ai_guardrails/ides/test_copilot.py | 12 ++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/cycode/cli/apps/ai_guardrails/ides/copilot.py b/cycode/cli/apps/ai_guardrails/ides/copilot.py index 447fa263..984a022c 100644 --- a/cycode/cli/apps/ai_guardrails/ides/copilot.py +++ b/cycode/cli/apps/ai_guardrails/ides/copilot.py @@ -111,8 +111,10 @@ # Copilot CLI leaves an `@path` mention in the prompt as typed: quoted, with # backslash-escaped spaces (a file dragged into a terminal), or plain up to the next -# whitespace. Never mid-word, so an email address is not a mention. -_MENTION_PATTERN = re.compile(r'(? None: + second = _create_file(fs, Path('/Users/user/project/second.png'), _png(b'second')) + third = _create_file(fs, Path('/Users/user/project/third.png'), _png(b'third')) + payload = { + **_AGENT_PROMPT_PAYLOAD, + 'prompt': 'see @"first shot.png and @second.png, then @third.png "done"', + } + + # The open quote reads to the next quote, but every mention in between is still its own + assert Copilot().collect_prompt_images(payload) == [second, third] + + @pytest.mark.skipif(os.sep != '/', reason='a backslash is a path separator on Windows') def test_collect_prompt_images_unescapes_spaces_in_a_dragged_path(fs: FakeFilesystem) -> None: shot = _create_file(fs, Path('/Users/user/Desktop/Screenshot 2026-11-09 at 10.15.32.png'), _png(b'shot')) From ae0f7d0f3d8e06fbb06e5f5f0fb161e76abb1972 Mon Sep 17 00:00:00 2001 From: Nikita Fishbakh Date: Thu, 12 Nov 2026 17:16:07 +0100 Subject: [PATCH 3/7] CM-77702: Always send images attached to a prompt The server decides whether to scan them, so the CLI no longer reads an image setting from the guardrail config. Co-Authored-By: Claude Opus 5.5 --- cycode/cli/apps/ai_guardrails/ides/base.py | 6 ++-- .../ai_guardrails/scan/guardrail_config.py | 12 +------ .../apps/ai_guardrails/scan/scan_command.py | 5 +-- .../commands/ai_guardrails/scan/conftest.py | 9 ++--- .../scan/test_guardrail_config.py | 33 ------------------ .../ai_guardrails/scan/test_scan_command.py | 34 ++++++++----------- 6 files changed, 24 insertions(+), 75 deletions(-) diff --git a/cycode/cli/apps/ai_guardrails/ides/base.py b/cycode/cli/apps/ai_guardrails/ides/base.py index 6b956fb6..c6eccba1 100644 --- a/cycode/cli/apps/ai_guardrails/ides/base.py +++ b/cycode/cli/apps/ai_guardrails/ides/base.py @@ -162,9 +162,9 @@ def parse_hook_payload(self, raw_payload: dict) -> AIHookPayload: def collect_prompt_images(self, raw_payload: dict) -> list[str]: """Return the paths of the images attached to a prompt, to scan along with its text. - ``scan_command`` calls it only for prompt events of a tenant that scans images, and only - in the process that runs the scan (never in a parent about to detach): collecting may - move per-session state forward, so a second call for the same prompt finds nothing. + ``scan_command`` calls it for every prompt event, only in the process that runs the scan + (never in a parent about to detach): collecting may move per-session state forward, so a + second call for the same prompt finds nothing. The platform decides whether to read them. Default: ``[]`` (attachments are out of the hook's reach). Override for IDEs that leave them on disk. diff --git a/cycode/cli/apps/ai_guardrails/scan/guardrail_config.py b/cycode/cli/apps/ai_guardrails/scan/guardrail_config.py index 466b4311..d1e59f98 100644 --- a/cycode/cli/apps/ai_guardrails/scan/guardrail_config.py +++ b/cycode/cli/apps/ai_guardrails/scan/guardrail_config.py @@ -105,13 +105,6 @@ def sensitive_globs(self) -> list: globs = settings.get('globs') return globs if isinstance(globs, list) and globs else _default_sensitive_globs() - def scans_prompt_images(self) -> bool: - """Whether images attached to a prompt are scanned along with its text. - - Only a platform that reads text out of images sends the setting, so a missing value means text only. - """ - return (self._guardrails.get(BlockReason.SECRETS_IN_PROMPT) or {}).get('scan_images') is True - def is_expired(self) -> bool: return time.time() - self.fetched_at > self.ttl_seconds @@ -136,10 +129,7 @@ def cell(guardrail_key: str) -> str: def action(guardrail_key: str) -> str: return PolicyMode.BLOCK.value if cell(guardrail_key) == GuardrailCellMode.BLOCK else PolicyMode.WARN.value - prompt = policy.setdefault('prompt', {}) - prompt['action'] = action(BlockReason.SECRETS_IN_PROMPT) - # Unlike the modes, no built-in default: a cold start can't know the platform reads images, so text only. - prompt['scan_images'] = config is not None and config.scans_prompt_images() + policy.setdefault('prompt', {})['action'] = action(BlockReason.SECRETS_IN_PROMPT) file_read = policy.setdefault('file_read', {}) file_read['scan_content'] = cell(BlockReason.SECRETS_IN_FILE) != GuardrailCellMode.OFF diff --git a/cycode/cli/apps/ai_guardrails/scan/scan_command.py b/cycode/cli/apps/ai_guardrails/scan/scan_command.py index 6f1d08f4..b573ac7c 100644 --- a/cycode/cli/apps/ai_guardrails/scan/scan_command.py +++ b/cycode/cli/apps/ai_guardrails/scan/scan_command.py @@ -18,7 +18,7 @@ from cycode.cli.apps.ai_guardrails.scan.detach import is_detached_child, respawn_detached from cycode.cli.apps.ai_guardrails.scan.guardrail_config import apply_platform_config, load_guardrail_config from cycode.cli.apps.ai_guardrails.scan.handlers import get_handler_for_event, should_detach_scan -from cycode.cli.apps.ai_guardrails.scan.policy import get_policy_value, load_policy +from cycode.cli.apps.ai_guardrails.scan.policy import load_policy from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType from cycode.cli.apps.ai_guardrails.scan.utils import output_json, read_stdin_text, safe_json_parse from cycode.cli.exceptions.custom_exceptions import HttpUnauthorizedError @@ -178,7 +178,8 @@ def scan_command( try: _initialize_clients(ctx) - if event_name == AiHookEventType.PROMPT and get_policy_value(policy, 'prompt', 'scan_images', default=False): + if event_name == AiHookEventType.PROMPT: + # Always sent: the platform decides whether to read them (its Scan attached images setting). # Here rather than in parse_hook_payload: collecting moves the session's prompt mark forward, so it # runs once, after the detach decision - a parent that detached would leave its child nothing to find. unified_payload.image_paths = _collect_prompt_images(ide_integration, payload) diff --git a/tests/cli/commands/ai_guardrails/scan/conftest.py b/tests/cli/commands/ai_guardrails/scan/conftest.py index 4909de1a..4e5d85b6 100644 --- a/tests/cli/commands/ai_guardrails/scan/conftest.py +++ b/tests/cli/commands/ai_guardrails/scan/conftest.py @@ -10,7 +10,6 @@ def resolved_guardrails_payload( mcp: str = 'Report', globs: list | None = None, mcp_server: str | None = None, - scan_images: bool | None = None, ) -> dict: """A platform resolved-config payload with the given per-guardrail modes for the cursor agent.""" payload = { @@ -27,8 +26,6 @@ def resolved_guardrails_payload( {'key': 'secrets_in_mcp_args', 'event_type': 'McpExecution', 'agents': {'cursor': mcp}}, ], } - if scan_images is not None: - payload['guardrails'][0]['scan_images'] = scan_images if mcp_server is not None: payload['guardrails'].append( { @@ -41,9 +38,9 @@ def resolved_guardrails_payload( return payload -def platform_config(fetched_at: float | None = None, **settings: str | bool | None) -> GuardrailConfig: - """A cached platform config; keyword args are the per-guardrail settings (see resolved_guardrails_payload).""" +def platform_config(fetched_at: float | None = None, **modes: str | None) -> GuardrailConfig: + """A cached platform config; keyword args are the per-guardrail modes (see resolved_guardrails_payload).""" return GuardrailConfig( - payload=resolved_guardrails_payload(**settings), + payload=resolved_guardrails_payload(**modes), fetched_at=time.time() if fetched_at is None else fetched_at, ) diff --git a/tests/cli/commands/ai_guardrails/scan/test_guardrail_config.py b/tests/cli/commands/ai_guardrails/scan/test_guardrail_config.py index cd7eed64..90065d93 100644 --- a/tests/cli/commands/ai_guardrails/scan/test_guardrail_config.py +++ b/tests/cli/commands/ai_guardrails/scan/test_guardrail_config.py @@ -203,36 +203,3 @@ def test_apply_platform_config_mcp_server_cells() -> None: assert policy['mcp']['check_server'] is True assert policy['mcp']['server_action'] == 'warn' assert policy['mcp']['action'] == 'warn' - - -# --- images attached to prompts --- - - -def test_prompt_images_are_scanned_only_when_the_platform_says_so() -> None: - assert _config(scan_images=True).scans_prompt_images() is True - assert _config(scan_images=False).scans_prompt_images() is False - # A platform that predates the setting doesn't read images, so a missing value means text only - assert _config().scans_prompt_images() is False - - -def test_prompt_images_setting_ignores_other_guardrails() -> None: - payload = _payload() - payload['guardrails'][1]['scan_images'] = True # secrets_in_file - assert GuardrailConfig(payload=payload, fetched_at=time.time()).scans_prompt_images() is False - - -@pytest.mark.parametrize( - ('config', 'expected'), - [ - (None, False), # no cache: nothing says the platform reads images - (_config(), False), - (_config(scan_images=False), False), - (_config(scan_images=True), True), - ], -) -def test_apply_platform_config_sets_prompt_scan_images(config: GuardrailConfig | None, expected: bool) -> None: - policy: dict = {} - - apply_platform_config(policy, config, 'copilot') - - assert policy['prompt']['scan_images'] is expected diff --git a/tests/cli/commands/ai_guardrails/scan/test_scan_command.py b/tests/cli/commands/ai_guardrails/scan/test_scan_command.py index 374b1d27..2d8e5692 100644 --- a/tests/cli/commands/ai_guardrails/scan/test_scan_command.py +++ b/tests/cli/commands/ai_guardrails/scan/test_scan_command.py @@ -573,16 +573,17 @@ def test_failed_respawn_falls_back_to_synchronous_scan( handler.assert_called_once() -def _copilot_config(prompt: str = 'Block', **settings: str | bool | None) -> GuardrailConfig: +def _copilot_config(prompt: str = 'Block') -> GuardrailConfig: """A cached platform config whose copilot cells are Block, except the prompt one given.""" - payload = resolved_guardrails_payload(**settings) + payload = resolved_guardrails_payload() for guardrail in payload['guardrails']: guardrail['agents']['copilot'] = prompt if guardrail['key'] == 'secrets_in_prompt' else 'Block' return GuardrailConfig(payload=payload, fetched_at=time.time()) class TestPromptImages: - """Images attached to Copilot prompts: collected once, when the tenant scans them, by the process that scans.""" + """Images attached to Copilot prompts: always collected, once, by the process that scans. The platform decides + whether to read them.""" _PAYLOAD = { # noqa: RUF012 'timestamp': '2026-11-09T10:15:32.000Z', @@ -612,29 +613,22 @@ def _run(self, mock_ctx: MagicMock, mocker: MockerFixture, config: GuardrailConf mocker.patch('cycode.cli.apps.ai_guardrails.scan.scan_command.load_guardrail_config', return_value=config) scan_command(mock_ctx, ide='copilot') - def test_images_are_collected_when_the_tenant_scans_them( - self, mock_ctx: MagicMock, mocker: MockerFixture, handler: MagicMock, collect: MagicMock, respawn: MagicMock - ) -> None: - self._run(mock_ctx, mocker, _copilot_config(scan_images=True), self._PAYLOAD) - - respawn.assert_not_called() - collect.assert_called_once_with(self._PAYLOAD) - assert handler.call_args.args[1].image_paths == ['/pasted/copilot-image-1.png'] - - @pytest.mark.parametrize('config', [None, _copilot_config(), _copilot_config(scan_images=False)]) - def test_text_only_without_the_setting( + # No cached config (a cold start) falls back to the built-in modes; images are collected either way. + @pytest.mark.parametrize('config', [None, _copilot_config()]) + def test_images_are_always_collected_for_a_prompt( self, mock_ctx: MagicMock, mocker: MockerFixture, handler: MagicMock, collect: MagicMock, + respawn: MagicMock, config: GuardrailConfig | None, ) -> None: self._run(mock_ctx, mocker, config, self._PAYLOAD) - collect.assert_not_called() - handler.assert_called_once() - assert handler.call_args.args[1].image_paths == [] + respawn.assert_not_called() + collect.assert_called_once_with(self._PAYLOAD) + assert handler.call_args.args[1].image_paths == ['/pasted/copilot-image-1.png'] def test_only_prompt_events_collect_images( self, mock_ctx: MagicMock, mocker: MockerFixture, handler: MagicMock, collect: MagicMock, fs: FakeFilesystem @@ -648,7 +642,7 @@ def test_only_prompt_events_collect_images( 'tool_input': {'filePath': '/Users/user/.gitconfig'}, } - self._run(mock_ctx, mocker, _copilot_config(scan_images=True), payload) + self._run(mock_ctx, mocker, _copilot_config(), payload) collect.assert_not_called() handler.assert_called_once() @@ -658,7 +652,7 @@ def test_failed_collection_still_scans_the_text( ) -> None: collect.side_effect = RuntimeError('unexpected') - self._run(mock_ctx, mocker, _copilot_config(scan_images=True), self._PAYLOAD) + self._run(mock_ctx, mocker, _copilot_config(), self._PAYLOAD) handler.assert_called_once() assert handler.call_args.args[1].image_paths == [] @@ -677,7 +671,7 @@ def test_images_are_collected_by_the_detached_child_not_the_parent( paste = _vscode_user_data_dir() / 'User' / 'workspaceStorage' / 'vscode-chat-images' / 'image-1.png' fs.create_file(paste, contents=b'\x89PNG\r\n\x1a\n' + b'pasted') os.utime(paste, (time.time() - 5, time.time() - 5)) - config = _copilot_config(prompt='Report', scan_images=True) # the parent detaches + config = _copilot_config(prompt='Report') # the parent detaches monkeypatch.delenv('_CYCODE_DETACHED', raising=False) self._run(mock_ctx, mocker, config, self._PAYLOAD) From b73d74ecbffbe63669533f85c7914c36edf43b28 Mon Sep 17 00:00:00 2001 From: Nikita Fishbakh Date: Mon, 16 Nov 2026 09:35:59 +0100 Subject: [PATCH 4/7] CM-77702: Take VS Code attachments only from the prompting session's chat Every VS Code chat's attachments saved since the session's previous prompt were taken, so a prompt could be blocked by an image attached in another window, and a Copilot CLI prompt could pick up VS Code attachments. The chat is now the one whose session database records the hook's session id. The shared folder of pasted images is no longer read: agent sessions copy every sent attachment into the chat's folder, and that folder also holds images that were pasted but never sent. Co-Authored-By: Claude Opus 5.5 --- cycode/cli/apps/ai_guardrails/ides/copilot.py | 64 ++++++--- .../ai_guardrails/ides/test_copilot.py | 122 ++++++++++++++---- .../ai_guardrails/scan/test_scan_command.py | 10 +- 3 files changed, 150 insertions(+), 46 deletions(-) diff --git a/cycode/cli/apps/ai_guardrails/ides/copilot.py b/cycode/cli/apps/ai_guardrails/ides/copilot.py index 984a022c..0a25c468 100644 --- a/cycode/cli/apps/ai_guardrails/ides/copilot.py +++ b/cycode/cli/apps/ai_guardrails/ides/copilot.py @@ -29,9 +29,11 @@ import os import platform import re +import sqlite3 import tempfile import time from collections.abc import Iterable +from contextlib import closing from pathlib import Path from typing import ClassVar from urllib.parse import urlparse @@ -120,13 +122,14 @@ # in the temp directory. _PASTED_IMAGE_PATTERN = re.compile(r'\[image:\s*([^\]\r\n]+?)\s*\]') -# VS Code (stable and Insiders) saves attachments in two places. The Copilot harness -# copies them into the chat's session data when the prompt is sent - under VS Code's -# chat id, not the hook's session_id, hence every chat. A paste, in either harness, is -# also saved to one shared folder when it is pasted. +# VS Code (stable and Insiders) agent sessions copy a prompt's attachments into the +# chat's session data when it is sent. That folder is named after VS Code's chat id, not +# the hook's session_id; the chat's session database records the agent runtime's session +# id, which is the hook's, under one of these keys. _VSCODE_PRODUCT_NAMES = ('Code', 'Code - Insiders') _VSCODE_ATTACHMENT_COPIES_GLOB = 'agentSessionData/*/attachments/*/*' -_VSCODE_PASTED_IMAGES_DIR_PARTS = ('User', 'workspaceStorage', 'vscode-chat-images') +_VSCODE_CHAT_DB_NAME = 'session.db' +_VSCODE_CHAT_SESSION_KEYS = ('defaultChatProviderData', 'agentHost.chatProviderData') def _copilot_home() -> Path: @@ -447,19 +450,47 @@ def _pasted_cli_images(prompt: str) -> list[Path]: return [temp_dir / os.path.basename(name) for name in _PASTED_IMAGE_PATTERN.findall(prompt)] -def _vscode_saved_attachments(since: float, until: float) -> list[Path]: - """Attachment files VS Code saved in ``[since, until)``. +def _vscode_chat_session_id(chat_dir: Path) -> str | None: + """The agent runtime's session id that VS Code recorded for a chat, or None.""" + db_path = chat_dir / _VSCODE_CHAT_DB_NAME + if not db_path.is_file(): + return None + placeholders = ', '.join('?' * len(_VSCODE_CHAT_SESSION_KEYS)) + query = f'SELECT value FROM session_metadata WHERE key IN ({placeholders})' # noqa: S608 + try: + # Read-only: VS Code keeps writing to the file while the chat is open + 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(query, _VSCODE_CHAT_SESSION_KEYS)] + except sqlite3.Error as e: + logger.debug('Failed to read a VS Code chat session database, %s', {'path': str(db_path)}, exc_info=e) + return None + for value in values: + try: + session_id = json.loads(value).get('sdkSessionId') + except (TypeError, ValueError, AttributeError): + continue + if isinstance(session_id, str) and session_id: + return session_id + return None + + +def _vscode_saved_attachments(session_id: str | None, since: float, until: float) -> list[Path]: + """Attachment files VS Code saved in ``[since, until)`` for this session's chat. - Send-time copies come before pastes, so a paste found in both keeps the name it - was attached under once the duplicate is dropped. + Other chats' attachments, in any window, never count. A prompt with no VS Code chat + of its own (Copilot CLI, or VS Code's local chat) gets none. """ + if not session_id: + return [] copies: list[Path] = [] - pastes: list[Path] = [] for product_name in _VSCODE_PRODUCT_NAMES: - user_data_dir = _vscode_user_data_dir(product_name) - copies.extend(user_data_dir.glob(_VSCODE_ATTACHMENT_COPIES_GLOB)) - pastes.extend(user_data_dir.joinpath(*_VSCODE_PASTED_IMAGES_DIR_PARTS).glob('*')) - return [*modified_between(copies, since, until), *modified_between(pastes, since, until)] + copies.extend(_vscode_user_data_dir(product_name).glob(_VSCODE_ATTACHMENT_COPIES_GLOB)) + recent = modified_between(copies, since, until) + # /attachments// + chats_of_this_session = { + chat_dir for chat_dir in {path.parents[2] for path in recent} if _vscode_chat_session_id(chat_dir) == session_id + } + return [path for path in recent if path.parents[2] in chats_of_this_session] class Copilot(IDE): @@ -537,7 +568,8 @@ def collect_prompt_images(self, raw_payload: dict) -> list[str]: Copilot CLI names its attachments in the prompt: an `@path` mention as typed, or a pasted image's placeholder. VS Code names none, so its attachments are the files - it saved since the session's previous prompt (see prompt_images). + it saved for this session's chat since the session's previous prompt (see + prompt_images). """ session_id = raw_payload.get('session_id') prompt = raw_payload.get('prompt') or '' @@ -548,7 +580,7 @@ def collect_prompt_images(self, raw_payload: dict) -> list[str]: [ *_mentioned_files(prompt, raw_payload.get('cwd')), *_pasted_cli_images(prompt), - *_vscode_saved_attachments(since, now), + *_vscode_saved_attachments(session_id, since, now), ] ) save_prompt_mark(session_id, now) diff --git a/tests/cli/commands/ai_guardrails/ides/test_copilot.py b/tests/cli/commands/ai_guardrails/ides/test_copilot.py index db62612f..d4de425b 100644 --- a/tests/cli/commands/ai_guardrails/ides/test_copilot.py +++ b/tests/cli/commands/ai_guardrails/ides/test_copilot.py @@ -6,6 +6,7 @@ import json import os +import sqlite3 import tempfile import time from pathlib import Path @@ -18,6 +19,7 @@ from cycode.cli.apps.ai_guardrails.ides.copilot import ( Copilot, _read_copilot_plugin, + _vscode_chat_session_id, _vscode_mcp_config_path, _vscode_user_data_dir, split_mcp_tool_name, @@ -571,16 +573,28 @@ def _create_file(fs: FakeFilesystem, path: Path, content: bytes, modified_at: fl return str(path) -def _vscode_copy(fs: FakeFilesystem, name: str, content: bytes, modified_at: float, product_name: str = 'Code') -> str: +def _vscode_copy( + fs: FakeFilesystem, + name: str, + content: bytes, + modified_at: float, + product_name: str = 'Code', + chat: str = 'chat-1', +) -> str: """A send-time copy of an attachment, in a chat's session data.""" - path = _vscode_user_data_dir(product_name) / 'agentSessionData' / 'chat-1' / 'attachments' / 'uuid-1' / name + path = _vscode_user_data_dir(product_name) / 'agentSessionData' / chat / 'attachments' / 'uuid-1' / name return _create_file(fs, path, content, modified_at) -def _vscode_paste(fs: FakeFilesystem, name: str, content: bytes, modified_at: float, product_name: str = 'Code') -> str: - """A paste, saved when it was made to VS Code's shared chat-images folder.""" - path = _vscode_user_data_dir(product_name) / 'User' / 'workspaceStorage' / 'vscode-chat-images' / name - return _create_file(fs, path, content, modified_at) +@pytest.fixture +def vscode_chats(mocker: MockerFixture) -> dict[str, str]: + """The session id each VS Code chat folder records; its database is read in the tests further down.""" + chats = {'chat-1': _VSCODE_PROMPT_PAYLOAD['session_id'], 'chat-2': 'another-session'} + mocker.patch( + 'cycode.cli.apps.ai_guardrails.ides.copilot._vscode_chat_session_id', + side_effect=lambda chat_dir: chats.get(chat_dir.name), + ) + return chats def test_collect_prompt_images_finds_cli_mentions_against_cwd(fs: FakeFilesystem) -> None: @@ -638,17 +652,33 @@ def test_collect_prompt_images_finds_cli_paste_in_the_temp_dir(fs: FakeFilesyste @pytest.mark.parametrize('system', ['Darwin', 'Linux', 'Windows']) @pytest.mark.parametrize('product_name', ['Code', 'Code - Insiders']) def test_collect_prompt_images_finds_vscode_attachments( - fs: FakeFilesystem, mocker: MockerFixture, system: str, product_name: str + fs: FakeFilesystem, mocker: MockerFixture, vscode_chats: dict[str, str], system: str, product_name: str ) -> None: mocker.patch('cycode.cli.apps.ai_guardrails.ides.copilot.platform.system', return_value=system) now = time.time() - copy = _vscode_copy(fs, 'diagram.png', _png(b'copy'), now - 5, product_name) - paste = _vscode_paste(fs, 'image-1784034535752.png', _png(b'paste'), now - 20, product_name) + first = _vscode_copy(fs, 'diagram.png', _png(b'first'), now - 20, product_name) + second = _vscode_copy(fs, 'image.png', _png(b'second'), now - 5, product_name) + + # In the order they were attached + assert Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD) == [first, second] + + +def test_collect_prompt_images_skips_another_chats_attachments( + fs: FakeFilesystem, vscode_chats: dict[str, str] +) -> None: + now = time.time() + own = _vscode_copy(fs, 'own.png', _png(b'own'), now - 5) + _vscode_copy(fs, 'other.png', _png(b'other'), now - 5, chat='chat-2') + _vscode_copy(fs, 'unknown.png', _png(b'unknown'), now - 5, chat='chat-without-a-session') - images = Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD) + assert Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD) == [own] - # Copies first, then pastes - assert images == [copy, paste] + +def test_cli_prompt_takes_no_vscode_attachments(fs: FakeFilesystem, vscode_chats: dict[str, str]) -> None: + _vscode_copy(fs, 'image.png', _png(b'vscode'), time.time() - 5) + payload = {**_AGENT_PROMPT_PAYLOAD, 'session_id': 'copilot-cli-session'} + + assert Copilot().collect_prompt_images(payload) == [] @pytest.mark.parametrize( @@ -667,29 +697,24 @@ def test_vscode_user_data_dir_per_platform(mocker: MockerFixture, system: str, b assert _vscode_mcp_config_path() == Path.home().joinpath(*base_parts, 'Code', 'User', 'mcp.json') -def test_collect_prompt_images_keeps_a_paste_saved_twice_once(fs: FakeFilesystem) -> None: - """The Copilot harness copies a paste on send, so the same bytes are in both folders.""" - now = time.time() - copy = _vscode_copy(fs, 'image.png', _png(b'same'), now - 2) - _vscode_paste(fs, 'image-1784034535752.png', _png(b'same'), now - 30) - - assert Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD) == [copy] - - -def test_first_prompt_takes_vscode_attachments_from_the_lookback(fs: FakeFilesystem) -> None: +def test_first_prompt_takes_vscode_attachments_from_the_lookback( + fs: FakeFilesystem, vscode_chats: dict[str, str] +) -> None: now = time.time() - recent = _vscode_paste(fs, 'image-recent.png', _png(b'recent'), now - (FIRST_PROMPT_LOOKBACK_SECONDS - 60)) - _vscode_paste(fs, 'image-old.png', _png(b'old'), now - (FIRST_PROMPT_LOOKBACK_SECONDS + 60)) + recent = _vscode_copy(fs, 'image-recent.png', _png(b'recent'), now - (FIRST_PROMPT_LOOKBACK_SECONDS - 60)) + _vscode_copy(fs, 'image-old.png', _png(b'old'), now - (FIRST_PROMPT_LOOKBACK_SECONDS + 60)) assert Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD) == [recent] -def test_later_prompt_takes_vscode_attachments_since_the_previous_one(fs: FakeFilesystem) -> None: +def test_later_prompt_takes_vscode_attachments_since_the_previous_one( + fs: FakeFilesystem, vscode_chats: dict[str, str] +) -> None: session_id = _VSCODE_PROMPT_PAYLOAD['session_id'] now = time.time() save_prompt_mark(session_id, now - 60) - _vscode_paste(fs, 'image-previous-prompt.png', _png(b'previous'), now - 120) - current = _vscode_paste(fs, 'image-this-prompt.png', _png(b'current'), now - 10) + _vscode_copy(fs, 'image-previous-prompt.png', _png(b'previous'), now - 120) + current = _vscode_copy(fs, 'image-this-prompt.png', _png(b'current'), now - 10) assert Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD) == [current] # The mark moved to this prompt, so its images are not collected again by the next one @@ -703,3 +728,46 @@ def test_collect_prompt_images_marks_only_the_prompting_session(fs: FakeFilesyst marks = json.loads(get_prompt_marks_path().read_text(encoding='utf-8')) assert list(marks) == [_VSCODE_PROMPT_PAYLOAD['session_id']] + + +# --- the session a VS Code chat records (a real SQLite file, so no fake filesystem) --------- + + +def _chat_db(tmp_path: Path, rows: dict[str, str] | None) -> Path: + chat_dir = tmp_path / 'chat-1' + chat_dir.mkdir() + if rows is not None: + with sqlite3.connect(chat_dir / 'session.db') as connection: + connection.execute('CREATE TABLE session_metadata (key TEXT NOT NULL PRIMARY KEY, value TEXT NOT NULL)') + connection.executemany('INSERT INTO session_metadata VALUES (?, ?)', rows.items()) + connection.close() + return chat_dir + + +@pytest.mark.parametrize('key', ['defaultChatProviderData', 'agentHost.chatProviderData']) +def test_vscode_chat_session_id_reads_the_agent_session(tmp_path: Path, key: str) -> None: + chat_dir = _chat_db(tmp_path, {'isRead': 'true', key: json.dumps({'sdkSessionId': 'session-1'})}) + + assert _vscode_chat_session_id(chat_dir) == 'session-1' + + +@pytest.mark.parametrize( + 'rows', + [ + None, # no database + {'isRead': 'true'}, # a chat that isn't an agent session + {'defaultChatProviderData': 'not json'}, + {'defaultChatProviderData': json.dumps({'sdkSessionId': ''})}, + {'defaultChatProviderData': json.dumps(['sdkSessionId'])}, + ], +) +def test_vscode_chat_session_id_none_without_an_agent_session(tmp_path: Path, rows: dict[str, str] | None) -> None: + assert _vscode_chat_session_id(_chat_db(tmp_path, rows)) is None + + +def test_vscode_chat_session_id_none_for_an_unreadable_database(tmp_path: Path) -> None: + chat_dir = tmp_path / 'chat-1' + chat_dir.mkdir() + (chat_dir / 'session.db').write_bytes(b'not a database') + + assert _vscode_chat_session_id(chat_dir) is None diff --git a/tests/cli/commands/ai_guardrails/scan/test_scan_command.py b/tests/cli/commands/ai_guardrails/scan/test_scan_command.py index 2d8e5692..992d2c26 100644 --- a/tests/cli/commands/ai_guardrails/scan/test_scan_command.py +++ b/tests/cli/commands/ai_guardrails/scan/test_scan_command.py @@ -582,8 +582,8 @@ def _copilot_config(prompt: str = 'Block') -> GuardrailConfig: class TestPromptImages: - """Images attached to Copilot prompts: always collected, once, by the process that scans. The platform decides - whether to read them.""" + """Images attached to Copilot prompts: always collected, once, by the process that scans. The server decides + whether to scan them.""" _PAYLOAD = { # noqa: RUF012 'timestamp': '2026-11-09T10:15:32.000Z', @@ -668,9 +668,13 @@ def test_images_are_collected_by_the_detached_child_not_the_parent( ) -> None: """Collecting moves the session's prompt mark past the image, so a parent that collected before detaching would leave the child that scans nothing to find.""" - paste = _vscode_user_data_dir() / 'User' / 'workspaceStorage' / 'vscode-chat-images' / 'image-1.png' + paste = _vscode_user_data_dir() / 'agentSessionData' / 'chat-1' / 'attachments' / 'uuid-1' / 'image-1.png' fs.create_file(paste, contents=b'\x89PNG\r\n\x1a\n' + b'pasted') os.utime(paste, (time.time() - 5, time.time() - 5)) + mocker.patch( + 'cycode.cli.apps.ai_guardrails.ides.copilot._vscode_chat_session_id', + return_value=self._PAYLOAD['session_id'], + ) config = _copilot_config(prompt='Report') # the parent detaches monkeypatch.delenv('_CYCODE_DETACHED', raising=False) From 41607411182a579e70d867cd3a177627992d031b Mon Sep 17 00:00:00 2001 From: Nikita Fishbakh Date: Mon, 16 Nov 2026 09:36:01 +0100 Subject: [PATCH 5/7] CM-77702: Say in the README that attached images are always sent Co-Authored-By: Claude Opus 5.5 --- README.md | 3 +-- cycode/cli/apps/ai_guardrails/ides/base.py | 2 +- cycode/cli/apps/ai_guardrails/scan/prompt_images.py | 6 +++--- cycode/cli/apps/ai_guardrails/scan/scan_command.py | 2 +- cycode/cli/models.py | 4 ++-- 5 files changed, 8 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 66c3ca6a..9ef79fc0 100644 --- a/README.md +++ b/README.md @@ -755,8 +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, unless your tenant turns image scanning off, PNG and JPEG images attached to a prompt -are sent along with its text. +For GitHub Copilot, 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/base.py b/cycode/cli/apps/ai_guardrails/ides/base.py index c6eccba1..4f2dbb3b 100644 --- a/cycode/cli/apps/ai_guardrails/ides/base.py +++ b/cycode/cli/apps/ai_guardrails/ides/base.py @@ -164,7 +164,7 @@ def collect_prompt_images(self, raw_payload: dict) -> list[str]: ``scan_command`` calls it for every prompt event, only in the process that runs the scan (never in a parent about to detach): collecting may move per-session state forward, so a - second call for the same prompt finds nothing. The platform decides whether to read them. + second call for the same prompt finds nothing. The server decides whether to scan them. Default: ``[]`` (attachments are out of the hook's reach). Override for IDEs that leave them on disk. diff --git a/cycode/cli/apps/ai_guardrails/scan/prompt_images.py b/cycode/cli/apps/ai_guardrails/scan/prompt_images.py index 7f77d407..c2533b4e 100644 --- a/cycode/cli/apps/ai_guardrails/scan/prompt_images.py +++ b/cycode/cli/apps/ai_guardrails/scan/prompt_images.py @@ -24,16 +24,16 @@ PROMPT_MARKS_FILE_NAME = 'ai-guardrails-prompt-marks.json' -# Each image is read by OCR on the server, within the IDE's hook timeout +# Each image adds to the scan's time, which the IDE's hook timeout bounds MAX_PROMPT_IMAGES = 5 -# Covers a paste made a while before sending, without reaching far into other chats' images +# Covers attachments saved a while before the prompt was sent FIRST_PROMPT_LOOKBACK_SECONDS = 600 # A session idle this long loses its mark; if it comes back, its next prompt falls back to the lookback _MARK_RETENTION_SECONDS = 7 * 24 * 60 * 60 -# The formats the server reads text out of, by signature (a file's own extension can be wrong or missing), with the +# The image formats sent for scanning, by signature (a file's own extension can be wrong or missing), with the # extensions that name each one _IMAGE_FORMATS = ( (b'\x89PNG\r\n\x1a\n', ('.png',)), diff --git a/cycode/cli/apps/ai_guardrails/scan/scan_command.py b/cycode/cli/apps/ai_guardrails/scan/scan_command.py index b573ac7c..4ec4e9a8 100644 --- a/cycode/cli/apps/ai_guardrails/scan/scan_command.py +++ b/cycode/cli/apps/ai_guardrails/scan/scan_command.py @@ -179,7 +179,7 @@ def scan_command( _initialize_clients(ctx) if event_name == AiHookEventType.PROMPT: - # Always sent: the platform decides whether to read them (its Scan attached images setting). + # Always sent: the server decides whether to scan them. # Here rather than in parse_hook_payload: collecting moves the session's prompt mark forward, so it # runs once, after the detach decision - a parent that detached would leave its child nothing to find. unified_payload.image_paths = _collect_prompt_images(ide_integration, payload) diff --git a/cycode/cli/models.py b/cycode/cli/models.py index ccd2e8d7..b2a4d441 100644 --- a/cycode/cli/models.py +++ b/cycode/cli/models.py @@ -24,8 +24,8 @@ def __init__( def text_content(self) -> str: """The content as text; '' for binary content. - The server reads the text out of binary content (OCR of an image) and reports positions into that text, - which never exists locally, so there is no line or value to cut out of it here. + Positions the server reports for binary content don't point into anything stored locally, so there is no + line or value to cut out of it here. """ return self.content if isinstance(self.content, str) else '' From ecc9184d00657dd1373958106fb281975ac3bf44 Mon Sep 17 00:00:00 2001 From: Nikita Fishbakh Date: Mon, 16 Nov 2026 12:10:28 +0100 Subject: [PATCH 6/7] CM-77702: Keep bytes support to where image documents go The file excluder, its string helpers and the console printers never see an image document, so they are back to their text-only versions. Co-Authored-By: Claude Opus 5.5 --- cycode/cli/files_collector/file_excluder.py | 4 +-- cycode/cli/printers/tables/table_printer.py | 4 +-- .../cli/printers/utils/code_snippet_syntax.py | 8 +++--- cycode/cli/utils/string_utils.py | 8 +++--- tests/cli/models/test_document.py | 26 +------------------ 5 files changed, 13 insertions(+), 37 deletions(-) diff --git a/cycode/cli/files_collector/file_excluder.py b/cycode/cli/files_collector/file_excluder.py index bc1e0121..066d7669 100644 --- a/cycode/cli/files_collector/file_excluder.py +++ b/cycode/cli/files_collector/file_excluder.py @@ -36,7 +36,7 @@ def _does_file_exceed_max_size_limit(filename: str) -> bool: return get_file_size(filename) > consts.FILE_MAX_SIZE_LIMIT_IN_BYTES -def _does_document_exceed_max_size_limit(content: str | bytes) -> bool: +def _does_document_exceed_max_size_limit(content: str) -> bool: return get_content_size(content) > consts.FILE_MAX_SIZE_LIMIT_IN_BYTES @@ -145,7 +145,7 @@ def _is_relevant_file_to_scan(self, scan_type: str, filename: str) -> bool: return not (scan_type == consts.SCA_SCAN_TYPE and not _is_file_relevant_for_sca_scan(filename)) - def _is_relevant_document_to_scan(self, scan_type: str, filename: str, content: str | bytes) -> bool: + def _is_relevant_document_to_scan(self, scan_type: str, filename: str, content: str) -> bool: if not self._is_relevant_file_to_scan_common(scan_type, filename): return False diff --git a/cycode/cli/printers/tables/table_printer.py b/cycode/cli/printers/tables/table_printer.py index b7c540df..4468ef9f 100644 --- a/cycode/cli/printers/tables/table_printer.py +++ b/cycode/cli/printers/tables/table_printer.py @@ -84,11 +84,11 @@ def _enrich_table_with_detection_code_segment_values( if self.scan_type == SECRET_SCAN_TYPE: detection_line = detection_details.get('line', -1) - detection_column = get_position_in_line(document.text_content, detection_details.get('start_position', -1)) + detection_column = get_position_in_line(document.content, detection_details.get('start_position', -1)) violation_length = detection_details.get('length', -1) violation = '' - file_content_lines = document.text_content.splitlines() + file_content_lines = document.content.splitlines() if detection_line < len(file_content_lines): line = file_content_lines[detection_line] violation = line[detection_column : detection_column + violation_length] diff --git a/cycode/cli/printers/utils/code_snippet_syntax.py b/cycode/cli/printers/utils/code_snippet_syntax.py index 780c485a..ceb2cc35 100644 --- a/cycode/cli/printers/utils/code_snippet_syntax.py +++ b/cycode/cli/printers/utils/code_snippet_syntax.py @@ -50,11 +50,11 @@ def _get_code_snippet_syntax_from_file( detection_details = detection.detection_details detection_line = get_detection_line(scan_type, detection) start_line_index = _get_code_segment_start_line(detection_line, lines_to_display_before) - detection_position = get_position_in_line(document.text_content, detection_details.get('start_position', -1)) + detection_position = get_position_in_line(document.content, detection_details.get('start_position', -1)) violation_length = detection_details.get('length', -1) code_lines_to_render = [] - document_content_lines = document.text_content.splitlines() + document_content_lines = document.content.splitlines() total_lines_to_display = lines_to_display_before + 1 + lines_to_display_after for line_index in range(total_lines_to_display): @@ -89,9 +89,9 @@ def _get_code_snippet_syntax_from_git_diff( detection_position = detection_details.get('start_position', -1) violation_length = detection_details.get('length', -1) - document_content_lines = document.text_content.splitlines() + document_content_lines = document.content.splitlines() line_content = document_content_lines[detection_line] if 0 <= detection_line < len(document_content_lines) else '' - detection_position_in_line = get_position_in_line(document.text_content, detection_position) + detection_position_in_line = get_position_in_line(document.content, detection_position) if scan_type == consts.SECRET_SCAN_TYPE and obfuscate: violation = line_content[detection_position_in_line : detection_position_in_line + violation_length] line_content = line_content.replace(violation, obfuscate_text(violation)) diff --git a/cycode/cli/utils/string_utils.py b/cycode/cli/utils/string_utils.py index 23400150..43931239 100644 --- a/cycode/cli/utils/string_utils.py +++ b/cycode/cli/utils/string_utils.py @@ -22,14 +22,14 @@ def obfuscate_text(text: str) -> str: obfuscate_regex = re.compile(r'[^+\-\s]') -def is_binary_content(content: str | bytes) -> bool: - """Get the first 1024 chars (or bytes) and check if it's binary or not.""" +def is_binary_content(content: str) -> bool: + """Get the first 1024 chars and check if it's binary or not.""" chunk = content[:1024] - chunk_bytes = chunk if isinstance(chunk, bytes) else convert_string_to_bytes(chunk) + chunk_bytes = convert_string_to_bytes(chunk) return is_binary_string(chunk_bytes) -def get_content_size(content: str | bytes) -> int: +def get_content_size(content: str) -> int: return getsizeof(content) diff --git a/tests/cli/models/test_document.py b/tests/cli/models/test_document.py index d838762f..569cd866 100644 --- a/tests/cli/models/test_document.py +++ b/tests/cli/models/test_document.py @@ -1,10 +1,7 @@ -"""Binary (bytes) documents must be safe everywhere a document's content is read.""" +"""Binary (bytes) documents, as the guardrails scan sends attached images.""" from cycode.cli.models import Document -from cycode.cli.printers.utils.code_snippet_syntax import get_code_snippet_syntax from cycode.cli.utils.scan_batch import split_documents_into_batches -from cycode.cli.utils.string_utils import is_binary_content -from cycode.cyclient.models import Detection _IMAGE = b'\x89PNG\r\n\x1a\n' + b'\x00' * 100 @@ -23,24 +20,3 @@ def test_batches_count_bytes_as_they_are() -> None: documents = [Document('image-1-shot.png', _IMAGE), Document('prompt-content.txt', 'ΓΌ')] assert split_documents_into_batches('secret', documents) == [documents] - - -def test_bytes_content_is_binary() -> None: - assert is_binary_content(_IMAGE) is True - assert is_binary_content('plain text') is False - - -def test_code_snippet_of_a_bytes_document_is_empty() -> None: - """Positions on an image point into text the server read out of it; there is nothing local to show.""" - detection = Detection( - detection_type_id='type-id', - type='GitHub Token', - message='Hardcoded secret', - detection_details={'line': 0, 'start_position': 3, 'length': 10}, - detection_rule_id='rule-id', - severity='High', - ) - - snippet = get_code_snippet_syntax('secret', 'scan', detection, Document('image-1-shot.png', _IMAGE)) - - assert snippet.code == '' From 59975ebb4014c8b53a13488e226f42cbe3fe8699 Mon Sep 17 00:00:00 2001 From: Nikita Fishbakh Date: Mon, 16 Nov 2026 12:10:28 +0100 Subject: [PATCH 7/7] CM-77702: Read each attached image once Collecting the images already reads and checks every file, so the bytes now travel with the path to the scan instead of being read and checked again. Prompt, text and file-read scans also share one scan helper. Co-Authored-By: Claude Opus 5.5 --- cycode/cli/apps/ai_guardrails/ides/base.py | 5 +- cycode/cli/apps/ai_guardrails/ides/copilot.py | 3 +- .../cli/apps/ai_guardrails/scan/handlers.py | 71 ++++++++----------- cycode/cli/apps/ai_guardrails/scan/payload.py | 6 +- .../apps/ai_guardrails/scan/prompt_images.py | 32 +++++---- .../apps/ai_guardrails/scan/scan_command.py | 2 +- .../ai_guardrails/ides/test_copilot.py | 25 ++++--- .../ai_guardrails/scan/test_handlers.py | 24 +++---- .../ai_guardrails/scan/test_prompt_images.py | 35 ++++----- .../ai_guardrails/scan/test_scan_command.py | 13 ++-- 10 files changed, 113 insertions(+), 103 deletions(-) diff --git a/cycode/cli/apps/ai_guardrails/ides/base.py b/cycode/cli/apps/ai_guardrails/ides/base.py index 4f2dbb3b..626e7869 100644 --- a/cycode/cli/apps/ai_guardrails/ides/base.py +++ b/cycode/cli/apps/ai_guardrails/ides/base.py @@ -21,6 +21,7 @@ from typing import ClassVar from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload +from cycode.cli.apps.ai_guardrails.scan.prompt_images import PromptImage from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType @@ -159,8 +160,8 @@ def is_synthetic_prompt(self, raw_payload: dict) -> bool: def parse_hook_payload(self, raw_payload: dict) -> AIHookPayload: """Normalize a raw stdin payload into the canonical ``AIHookPayload``.""" - def collect_prompt_images(self, raw_payload: dict) -> list[str]: - """Return the paths of the images attached to a prompt, to scan along with its text. + def collect_prompt_images(self, raw_payload: dict) -> list[PromptImage]: + """Return the images attached to a prompt, read once, to scan along with its text. ``scan_command`` calls it for every prompt event, only in the process that runs the scan (never in a parent about to detach): collecting may move per-session state forward, so a diff --git a/cycode/cli/apps/ai_guardrails/ides/copilot.py b/cycode/cli/apps/ai_guardrails/ides/copilot.py index 0a25c468..caff99a3 100644 --- a/cycode/cli/apps/ai_guardrails/ides/copilot.py +++ b/cycode/cli/apps/ai_guardrails/ides/copilot.py @@ -49,6 +49,7 @@ 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, get_prompt_mark, modified_between, save_prompt_mark, @@ -563,7 +564,7 @@ def parse_hook_payload(self, raw_payload: dict) -> AIHookPayload: mcp_arguments=mcp_arguments, ) - def collect_prompt_images(self, raw_payload: dict) -> list[str]: + def collect_prompt_images(self, raw_payload: dict) -> list[PromptImage]: """Images attached to a prompt, found where Copilot saved them before the hook ran. Copilot CLI names its attachments in the prompt: an `@path` mention as typed, or diff --git a/cycode/cli/apps/ai_guardrails/scan/handlers.py b/cycode/cli/apps/ai_guardrails/scan/handlers.py index adb07122..a3505dac 100644 --- a/cycode/cli/apps/ai_guardrails/scan/handlers.py +++ b/cycode/cli/apps/ai_guardrails/scan/handlers.py @@ -12,7 +12,7 @@ import os import sys import threading -from collections.abc import Callable +from collections.abc import Callable, Sequence from dataclasses import dataclass from gettext import ngettext from typing import TYPE_CHECKING, Any, NamedTuple @@ -27,7 +27,7 @@ from cycode.cli.apps.ai_guardrails.scan.mcp_server_status import is_enforced, load_mcp_server_statuses from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload from cycode.cli.apps.ai_guardrails.scan.policy import get_policy_value -from cycode.cli.apps.ai_guardrails.scan.prompt_images import image_file_name, read_prompt_image +from cycode.cli.apps.ai_guardrails.scan.prompt_images import PromptImage from cycode.cli.apps.ai_guardrails.scan.types import ( SECRETS_BLOCK_REASON_BY_EVENT_TYPE, AiHookEventType, @@ -129,7 +129,9 @@ def handle_before_submit_prompt(ctx: typer.Context, payload: AIHookPayload, poli error_message = None try: - scan_outcome = _scan_prompt_for_secrets(ctx, clipped, payload.image_paths, timeout_ms, payload=payload) + scan_outcome = _scan_text_for_secrets( + ctx, clipped, timeout_ms, payload=payload, event_type=AiHookEventType.PROMPT, images=payload.images + ) scan_id = scan_outcome.scan_id if scan_outcome.violation_summary: @@ -541,57 +543,47 @@ def _scan_documents_for_secrets( timeout_ms: int, payload: AIHookPayload, event_type: AiHookEventType, + paths: tuple[str, ...] | None = None, ) -> ScanOutcome: - """Scan in-memory documents for secrets, all in one scan.""" + """Scan in-memory documents for secrets, all in one scan; no documents means no scan.""" if not documents: return NO_SCAN scan_ctx = _setup_scan_context(ctx) timeout_seconds = timeout_ms / 1000.0 - scan_parameters = build_ai_guardrails_scan_parameters(scan_ctx, None, payload, event_type) + scan_parameters = build_ai_guardrails_scan_parameters(scan_ctx, paths, payload, event_type) return _perform_scan(scan_ctx, documents, scan_parameters, timeout_seconds) -def _scan_text_for_secrets( - ctx: typer.Context, - text: str, - timeout_ms: int, - payload: AIHookPayload, - event_type: AiHookEventType, -) -> ScanOutcome: - """Scan text content for secrets using Cycode CLI.""" - documents = [Document(path=_TEXT_DOCUMENT_NAME, content=text, is_git_diff_format=False)] if text else [] - return _scan_documents_for_secrets(ctx, documents, timeout_ms, payload, event_type) - - -def _image_documents(image_paths: list[str]) -> list[Document]: +def _image_documents(images: Sequence[PromptImage]) -> list[Document]: """One bytes document per attached image. - The entry name keeps an image extension because the server picks the files to read text out of by extension as - well as signature. The original path stays on the document, to name the image in the block message. + The entry name keeps an image extension because the server picks the files to scan by extension as well as + signature. The original path stays on the document, to name the image in the block message. """ - documents = [] - for index, image_path in enumerate(image_paths, start=1): - content = read_prompt_image(image_path) - if content is None: - logger.debug('Attached image is gone or no longer scannable, %s', {'path': image_path}) - continue - name = f'image-{index}-{image_file_name(image_path, content)}' - documents.append(Document(path=name, content=content, is_git_diff_format=False, absolute_path=image_path)) - return documents - - -def _scan_prompt_for_secrets( + return [ + Document( + path=f'image-{index}-{image.file_name}', + content=image.content, + is_git_diff_format=False, + absolute_path=image.path, + ) + for index, image in enumerate(images, start=1) + ] + + +def _scan_text_for_secrets( ctx: typer.Context, text: str, - image_paths: list[str], timeout_ms: int, payload: AIHookPayload, + event_type: AiHookEventType, + images: Sequence[PromptImage] = (), ) -> ScanOutcome: - """Scan the prompt text and its attached images for secrets; no text and no images means no scan.""" + """Scan text, and the images attached with it, for secrets in one scan.""" documents = [Document(path=_TEXT_DOCUMENT_NAME, content=text, is_git_diff_format=False)] if text else [] - documents.extend(_image_documents(image_paths)) - return _scan_documents_for_secrets(ctx, documents, timeout_ms, payload, AiHookEventType.PROMPT) + documents.extend(_image_documents(images)) + return _scan_documents_for_secrets(ctx, documents, timeout_ms, payload, event_type) def _scan_path_for_secrets( @@ -614,9 +606,8 @@ def _scan_path_for_secrets( content = f.read(max_bytes) timeout_ms = get_policy_value(policy, 'secrets', 'timeout_ms', default=30000) - timeout_seconds = timeout_ms / 1000.0 document = Document(path=os.path.basename(file_path), content=content, is_git_diff_format=False) - scan_ctx = _setup_scan_context(ctx) - scan_parameters = build_ai_guardrails_scan_parameters(scan_ctx, (file_path,), payload, AiHookEventType.FILE_READ) - return _perform_scan(scan_ctx, [document], scan_parameters, timeout_seconds) + return _scan_documents_for_secrets( + ctx, [document], timeout_ms, payload, AiHookEventType.FILE_READ, paths=(file_path,) + ) diff --git a/cycode/cli/apps/ai_guardrails/scan/payload.py b/cycode/cli/apps/ai_guardrails/scan/payload.py index 8a8e93df..1681a436 100644 --- a/cycode/cli/apps/ai_guardrails/scan/payload.py +++ b/cycode/cli/apps/ai_guardrails/scan/payload.py @@ -7,6 +7,10 @@ import uuid from dataclasses import dataclass, field +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from cycode.cli.apps.ai_guardrails.scan.prompt_images import PromptImage @dataclass @@ -35,7 +39,7 @@ class AIHookPayload: prompt: str | None = None # PROMPT events # Images attached to the prompt, scanned with its text. Filled by scan_command (IDE.collect_prompt_images), # not at parse time: collecting moves per-session state forward, so only the process that scans may do it. - image_paths: list[str] = field(default_factory=list) + images: list['PromptImage'] = field(default_factory=list) file_path: str | None = None # FILE_READ events mcp_server_name: str | None = None # MCP_EXECUTION events mcp_tool_name: str | None = None diff --git a/cycode/cli/apps/ai_guardrails/scan/prompt_images.py b/cycode/cli/apps/ai_guardrails/scan/prompt_images.py index c2533b4e..8713ff4d 100644 --- a/cycode/cli/apps/ai_guardrails/scan/prompt_images.py +++ b/cycode/cli/apps/ai_guardrails/scan/prompt_images.py @@ -14,6 +14,7 @@ import os import stat from collections.abc import Iterable +from dataclasses import dataclass from pathlib import Path from cycode.cli.consts import CYCODE_CONFIGURATION_DIRECTORY, FILE_MAX_SIZE_LIMIT_IN_BYTES @@ -139,23 +140,30 @@ def read_prompt_image(path: str | os.PathLike) -> bytes | None: return content if len(content) <= FILE_MAX_SIZE_LIMIT_IN_BYTES else None -def image_file_name(path: str, content: bytes) -> str: - """The file's name, plus the extension of its actual format when its own extension doesn't name that format.""" - name = os.path.basename(path) - extensions = _image_extensions(content) - if extensions and os.path.splitext(name)[1].lower() not in extensions: - name += extensions[0] - return name +@dataclass(frozen=True) +class PromptImage: + """An image attached to a prompt, read once when it is collected: where it was, and its bytes.""" + path: str + content: bytes -def select_prompt_images(candidates: Iterable[str | os.PathLike]) -> list[str]: + @property + def file_name(self) -> str: + """The file's name, plus the extension of its actual format when its own extension doesn't name it.""" + name = os.path.basename(self.path) + extensions = _image_extensions(self.content) + if extensions and os.path.splitext(name)[1].lower() not in extensions: + name += extensions[0] + return name + + +def select_prompt_images(candidates: Iterable[str | os.PathLike]) -> list[PromptImage]: """The candidates to scan, in order: scannable images (see read_prompt_image), each content once, at most MAX_PROMPT_IMAGES. - Once per content because one attachment can be on disk twice: VS Code saves a paste when it is made and copies - it again when the prompt is sent. + Once per content because the same image can be attached twice, for example pasted and also mentioned by path. """ - selected: list[str] = [] + selected: list[PromptImage] = [] seen_digests: set[str] = set() for candidate in candidates: content = read_prompt_image(candidate) @@ -171,6 +179,6 @@ def select_prompt_images(candidates: Iterable[str | os.PathLike]) -> list[str]: break seen_digests.add(digest) - selected.append(str(candidate)) + selected.append(PromptImage(path=str(candidate), content=content)) return selected diff --git a/cycode/cli/apps/ai_guardrails/scan/scan_command.py b/cycode/cli/apps/ai_guardrails/scan/scan_command.py index 4ec4e9a8..c75c5653 100644 --- a/cycode/cli/apps/ai_guardrails/scan/scan_command.py +++ b/cycode/cli/apps/ai_guardrails/scan/scan_command.py @@ -182,7 +182,7 @@ def scan_command( # Always sent: the server decides whether to scan them. # Here rather than in parse_hook_payload: collecting moves the session's prompt mark forward, so it # runs once, after the detach decision - a parent that detached would leave its child nothing to find. - unified_payload.image_paths = _collect_prompt_images(ide_integration, payload) + unified_payload.images = _collect_prompt_images(ide_integration, payload) decision = handler(ctx, unified_payload, policy) logger.debug('Hook handler completed', extra={'event_name': event_name, 'action': decision.action.value}) diff --git a/tests/cli/commands/ai_guardrails/ides/test_copilot.py b/tests/cli/commands/ai_guardrails/ides/test_copilot.py index d4de425b..c5aee5ba 100644 --- a/tests/cli/commands/ai_guardrails/ides/test_copilot.py +++ b/tests/cli/commands/ai_guardrails/ides/test_copilot.py @@ -26,6 +26,7 @@ ) from cycode.cli.apps.ai_guardrails.scan.prompt_images import ( FIRST_PROMPT_LOOKBACK_SECONDS, + PromptImage, get_prompt_mark, get_prompt_marks_path, save_prompt_mark, @@ -562,6 +563,10 @@ def test_get_skills_no_skills_dir_returns_empty(fs: FakeFilesystem) -> None: # --- prompt images ---------------------------------------------------------------- +def _paths(images: list[PromptImage]) -> list[str]: + return [image.path for image in images] + + def _png(marker: bytes) -> bytes: return b'\x89PNG\r\n\x1a\n' + marker @@ -613,7 +618,7 @@ def test_collect_prompt_images_finds_cli_mentions_against_cwd(fs: FakeFilesystem images = Copilot().collect_prompt_images(payload) - assert images == [shot, spaced, absolute] + assert _paths(images) == [shot, spaced, absolute] def test_collect_prompt_images_reads_every_mention_after_an_unclosed_quote(fs: FakeFilesystem) -> None: @@ -625,7 +630,7 @@ def test_collect_prompt_images_reads_every_mention_after_an_unclosed_quote(fs: F } # The open quote reads to the next quote, but every mention in between is still its own - assert Copilot().collect_prompt_images(payload) == [second, third] + assert _paths(Copilot().collect_prompt_images(payload)) == [second, third] @pytest.mark.skipif(os.sep != '/', reason='a backslash is a path separator on Windows') @@ -633,7 +638,7 @@ def test_collect_prompt_images_unescapes_spaces_in_a_dragged_path(fs: FakeFilesy shot = _create_file(fs, Path('/Users/user/Desktop/Screenshot 2026-11-09 at 10.15.32.png'), _png(b'shot')) payload = {**_AGENT_PROMPT_PAYLOAD, 'prompt': r'@/Users/user/Desktop/Screenshot\ 2026-11-09\ at\ 10.15.32.png ?'} - assert Copilot().collect_prompt_images(payload) == [shot] + assert _paths(Copilot().collect_prompt_images(payload)) == [shot] def test_collect_prompt_images_finds_cli_paste_in_the_temp_dir(fs: FakeFilesystem) -> None: @@ -646,7 +651,7 @@ def test_collect_prompt_images_finds_cli_paste_in_the_temp_dir(fs: FakeFilesyste } # The placeholder is prompt text: only its base name is looked up, inside the temp directory - assert Copilot().collect_prompt_images(payload) == [pasted] + assert _paths(Copilot().collect_prompt_images(payload)) == [pasted] @pytest.mark.parametrize('system', ['Darwin', 'Linux', 'Windows']) @@ -660,7 +665,7 @@ def test_collect_prompt_images_finds_vscode_attachments( second = _vscode_copy(fs, 'image.png', _png(b'second'), now - 5, product_name) # In the order they were attached - assert Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD) == [first, second] + assert _paths(Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD)) == [first, second] def test_collect_prompt_images_skips_another_chats_attachments( @@ -671,14 +676,14 @@ def test_collect_prompt_images_skips_another_chats_attachments( _vscode_copy(fs, 'other.png', _png(b'other'), now - 5, chat='chat-2') _vscode_copy(fs, 'unknown.png', _png(b'unknown'), now - 5, chat='chat-without-a-session') - assert Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD) == [own] + assert _paths(Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD)) == [own] def test_cli_prompt_takes_no_vscode_attachments(fs: FakeFilesystem, vscode_chats: dict[str, str]) -> None: _vscode_copy(fs, 'image.png', _png(b'vscode'), time.time() - 5) payload = {**_AGENT_PROMPT_PAYLOAD, 'session_id': 'copilot-cli-session'} - assert Copilot().collect_prompt_images(payload) == [] + assert _paths(Copilot().collect_prompt_images(payload)) == [] @pytest.mark.parametrize( @@ -704,7 +709,7 @@ def test_first_prompt_takes_vscode_attachments_from_the_lookback( recent = _vscode_copy(fs, 'image-recent.png', _png(b'recent'), now - (FIRST_PROMPT_LOOKBACK_SECONDS - 60)) _vscode_copy(fs, 'image-old.png', _png(b'old'), now - (FIRST_PROMPT_LOOKBACK_SECONDS + 60)) - assert Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD) == [recent] + assert _paths(Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD)) == [recent] def test_later_prompt_takes_vscode_attachments_since_the_previous_one( @@ -716,10 +721,10 @@ def test_later_prompt_takes_vscode_attachments_since_the_previous_one( _vscode_copy(fs, 'image-previous-prompt.png', _png(b'previous'), now - 120) current = _vscode_copy(fs, 'image-this-prompt.png', _png(b'current'), now - 10) - assert Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD) == [current] + assert _paths(Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD)) == [current] # The mark moved to this prompt, so its images are not collected again by the next one assert get_prompt_mark(session_id, time.time()) >= now - assert Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD) == [] + assert _paths(Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD)) == [] def test_collect_prompt_images_marks_only_the_prompting_session(fs: FakeFilesystem) -> None: diff --git a/tests/cli/commands/ai_guardrails/scan/test_handlers.py b/tests/cli/commands/ai_guardrails/scan/test_handlers.py index 91c6f12f..44f4bb60 100644 --- a/tests/cli/commands/ai_guardrails/scan/test_handlers.py +++ b/tests/cli/commands/ai_guardrails/scan/test_handlers.py @@ -26,6 +26,7 @@ ) from cycode.cli.apps.ai_guardrails.scan.mcp_server_status import McpServerStatuses from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload +from cycode.cli.apps.ai_guardrails.scan.prompt_images import PromptImage from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType, AIHookOutcome, BlockReason from cycode.cli.apps.ai_guardrails.scan.utils import MAX_VIOLATION_DETAIL_LINES, build_violation_summary from cycode.cli.models import Document, DocumentDetections, LocalScanResult @@ -74,7 +75,7 @@ def default_policy() -> dict[str, Any]: # Tests for handle_before_submit_prompt -@patch('cycode.cli.apps.ai_guardrails.scan.handlers._scan_prompt_for_secrets') +@patch('cycode.cli.apps.ai_guardrails.scan.handlers._scan_text_for_secrets') def test_handle_before_submit_prompt_no_secrets( mock_scan: MagicMock, mock_ctx: MagicMock, mock_payload: AIHookPayload, default_policy: dict[str, Any] ) -> None: @@ -92,7 +93,7 @@ def test_handle_before_submit_prompt_no_secrets( assert call_args.kwargs['block_reason'] is None -@patch('cycode.cli.apps.ai_guardrails.scan.handlers._scan_prompt_for_secrets') +@patch('cycode.cli.apps.ai_guardrails.scan.handlers._scan_text_for_secrets') def test_handle_before_submit_prompt_with_secrets_blocked( mock_scan: MagicMock, mock_ctx: MagicMock, mock_payload: AIHookPayload, default_policy: dict[str, Any] ) -> None: @@ -125,7 +126,7 @@ def test_handle_before_submit_prompt_with_secrets_blocked( ) -@patch('cycode.cli.apps.ai_guardrails.scan.handlers._scan_prompt_for_secrets') +@patch('cycode.cli.apps.ai_guardrails.scan.handlers._scan_text_for_secrets') def test_handle_before_submit_prompt_with_secrets_warned( mock_scan: MagicMock, mock_ctx: MagicMock, mock_payload: AIHookPayload, default_policy: dict[str, Any] ) -> None: @@ -141,7 +142,7 @@ def test_handle_before_submit_prompt_with_secrets_warned( assert call_args.args[2] == AIHookOutcome.WARNED -@patch('cycode.cli.apps.ai_guardrails.scan.handlers._scan_prompt_for_secrets') +@patch('cycode.cli.apps.ai_guardrails.scan.handlers._scan_text_for_secrets') def test_handle_before_submit_prompt_scan_failure_fail_open( mock_scan: MagicMock, mock_ctx: MagicMock, mock_payload: AIHookPayload, default_policy: dict[str, Any] ) -> None: @@ -158,7 +159,7 @@ def test_handle_before_submit_prompt_scan_failure_fail_open( assert call_args.kwargs['block_reason'] == BlockReason.SCAN_FAILURE -@patch('cycode.cli.apps.ai_guardrails.scan.handlers._scan_prompt_for_secrets') +@patch('cycode.cli.apps.ai_guardrails.scan.handlers._scan_text_for_secrets') def test_handle_before_submit_prompt_scan_failure_fail_closed( mock_scan: MagicMock, mock_ctx: MagicMock, mock_payload: AIHookPayload, default_policy: dict[str, Any] ) -> None: @@ -564,9 +565,7 @@ def _scanned_documents(mock_perform_scan: MagicMock) -> list[Document]: def test_prompt_and_its_images_are_scanned_together( mock_perform_scan: MagicMock, mock_ctx: MagicMock, mock_payload: AIHookPayload, default_policy: dict, fs: Any ) -> None: - fs.create_file('/images/shot.png', contents=_PNG) - fs.create_file('/images/Screenshot', contents=_JPEG) - mock_payload.image_paths = ['/images/shot.png', '/images/Screenshot'] + mock_payload.images = [PromptImage('/images/shot.png', _PNG), PromptImage('/images/Screenshot', _JPEG)] result = handle_before_submit_prompt(mock_ctx, mock_payload, default_policy) @@ -593,9 +592,8 @@ def test_prompt_and_its_images_are_scanned_together( def test_prompt_with_only_an_image_is_scanned( mock_perform_scan: MagicMock, mock_ctx: MagicMock, mock_payload: AIHookPayload, default_policy: dict, fs: Any ) -> None: - fs.create_file('/images/shot.png', contents=_PNG) mock_payload.prompt = '' - mock_payload.image_paths = ['/images/shot.png'] + mock_payload.images = [PromptImage('/images/shot.png', _PNG)] handle_before_submit_prompt(mock_ctx, mock_payload, default_policy) @@ -607,8 +605,7 @@ def test_prompt_without_text_or_images_is_not_scanned( mock_perform_scan: MagicMock, mock_ctx: MagicMock, mock_payload: AIHookPayload, default_policy: dict, fs: Any ) -> None: mock_payload.prompt = '' - # Gone between collection and the scan: nothing left to send - mock_payload.image_paths = ['/images/deleted.png'] + mock_payload.images = [] result = handle_before_submit_prompt(mock_ctx, mock_payload, default_policy) @@ -652,9 +649,8 @@ def detection(sha: str) -> Detection: def test_blocked_prompt_names_the_image_the_secret_is_in( mock_ctx: MagicMock, mock_payload: AIHookPayload, default_policy: dict, fs: Any ) -> None: - fs.create_file('/attachments/uuid-1/diagram.png', contents=_PNG) mock_payload.prompt = 'ghp_ in the text' - mock_payload.image_paths = ['/attachments/uuid-1/diagram.png'] + mock_payload.images = [PromptImage('/attachments/uuid-1/diagram.png', _PNG)] with patch( 'cycode.cli.apps.ai_guardrails.scan.handlers._get_scan_documents_thread_func', diff --git a/tests/cli/commands/ai_guardrails/scan/test_prompt_images.py b/tests/cli/commands/ai_guardrails/scan/test_prompt_images.py index ef51aa70..edbdd417 100644 --- a/tests/cli/commands/ai_guardrails/scan/test_prompt_images.py +++ b/tests/cli/commands/ai_guardrails/scan/test_prompt_images.py @@ -11,9 +11,9 @@ from cycode.cli.apps.ai_guardrails.scan.prompt_images import ( FIRST_PROMPT_LOOKBACK_SECONDS, MAX_PROMPT_IMAGES, + PromptImage, get_prompt_mark, get_prompt_marks_path, - image_file_name, modified_between, read_prompt_image, save_prompt_mark, @@ -160,20 +160,21 @@ def test_select_keeps_order_and_drops_non_images(fs: FakeFilesystem) -> None: selected = select_prompt_images(['/images/b.png', '/images/readme.md', Path('/images/a.jpg'), '/images/gone.png']) - assert selected == ['/images/b.png', str(Path('/images/a.jpg'))] + assert selected == [ + PromptImage(path='/images/b.png', content=png(b'b')), + PromptImage(path=str(Path('/images/a.jpg')), content=jpeg(b'a')), + ] def test_select_keeps_one_path_per_content(fs: FakeFilesystem) -> None: - """VS Code saves a paste when it is made and copies it again on send: one image, two files.""" - fs.create_file('/sent/image.png', contents=png(b'same')) - fs.create_file('/pasted/image-1784034535752.png', contents=png(b'same')) - fs.create_file('/pasted/image-1784034535999.png', contents=png(b'other')) + """The same image can be attached twice, for example pasted and also mentioned by path.""" + fs.create_file('/pasted/image.png', contents=png(b'same')) + fs.create_file('/mentioned/image.png', contents=png(b'same')) + fs.create_file('/mentioned/other.png', contents=png(b'other')) - selected = select_prompt_images( - ['/sent/image.png', '/pasted/image-1784034535752.png', '/pasted/image-1784034535999.png'] - ) + selected = select_prompt_images(['/pasted/image.png', '/mentioned/image.png', '/mentioned/other.png']) - assert selected == ['/sent/image.png', '/pasted/image-1784034535999.png'] + assert [image.path for image in selected] == ['/pasted/image.png', '/mentioned/other.png'] def test_select_caps_the_number_of_images(fs: FakeFilesystem) -> None: @@ -186,14 +187,14 @@ def test_select_caps_the_number_of_images(fs: FakeFilesystem) -> None: selected = select_prompt_images(['/images/copy.png', *paths]) - assert selected == ['/images/copy.png', *paths[1:MAX_PROMPT_IMAGES]] + assert [image.path for image in selected] == ['/images/copy.png', *paths[1:MAX_PROMPT_IMAGES]] assert len(selected) == MAX_PROMPT_IMAGES -def test_image_file_name_names_the_actual_format() -> None: - assert image_file_name('/x/shot.png', png()) == 'shot.png' - assert image_file_name('/x/photo.JPEG', jpeg()) == 'photo.JPEG' - assert image_file_name('/x/photo.jpg', jpeg()) == 'photo.jpg' +def test_prompt_image_file_name_names_the_actual_format() -> None: + assert PromptImage('/x/shot.png', png()).file_name == 'shot.png' + assert PromptImage('/x/photo.JPEG', jpeg()).file_name == 'photo.JPEG' + assert PromptImage('/x/photo.jpg', jpeg()).file_name == 'photo.jpg' # The server picks images by extension as well as signature, so a missing or wrong one is completed - assert image_file_name('/x/screenshot', png()) == 'screenshot.png' - assert image_file_name('/x/actually-a-jpeg.png', jpeg()) == 'actually-a-jpeg.png.jpg' + assert PromptImage('/x/screenshot', png()).file_name == 'screenshot.png' + assert PromptImage('/x/actually-a-jpeg.png', jpeg()).file_name == 'actually-a-jpeg.png.jpg' diff --git a/tests/cli/commands/ai_guardrails/scan/test_scan_command.py b/tests/cli/commands/ai_guardrails/scan/test_scan_command.py index 992d2c26..88234e72 100644 --- a/tests/cli/commands/ai_guardrails/scan/test_scan_command.py +++ b/tests/cli/commands/ai_guardrails/scan/test_scan_command.py @@ -15,7 +15,7 @@ from cycode.cli.apps.ai_guardrails.ides.base import HookDecision from cycode.cli.apps.ai_guardrails.ides.copilot import Copilot, _vscode_user_data_dir from cycode.cli.apps.ai_guardrails.scan.guardrail_config import GuardrailConfig -from cycode.cli.apps.ai_guardrails.scan.prompt_images import get_prompt_marks_path +from cycode.cli.apps.ai_guardrails.scan.prompt_images import PromptImage, get_prompt_marks_path from cycode.cli.apps.ai_guardrails.scan.scan_command import scan_command from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType from tests.cli.commands.ai_guardrails.scan.conftest import platform_config, resolved_guardrails_payload @@ -581,6 +581,9 @@ def _copilot_config(prompt: str = 'Block') -> GuardrailConfig: return GuardrailConfig(payload=payload, fetched_at=time.time()) +_PASTED_IMAGE = PromptImage(path='/pasted/copilot-image-1.png', content=b'\x89PNG\r\n\x1a\n' + b'pasted') + + class TestPromptImages: """Images attached to Copilot prompts: always collected, once, by the process that scans. The server decides whether to scan them.""" @@ -606,7 +609,7 @@ def handler(self, mocker: MockerFixture, respawn: MagicMock) -> MagicMock: @pytest.fixture def collect(self, mocker: MockerFixture) -> MagicMock: - return mocker.patch.object(Copilot, 'collect_prompt_images', return_value=['/pasted/copilot-image-1.png']) + return mocker.patch.object(Copilot, 'collect_prompt_images', return_value=[_PASTED_IMAGE]) def _run(self, mock_ctx: MagicMock, mocker: MockerFixture, config: GuardrailConfig | None, payload: dict) -> None: mocker.patch('sys.stdin', StringIO(json.dumps(payload))) @@ -628,7 +631,7 @@ def test_images_are_always_collected_for_a_prompt( respawn.assert_not_called() collect.assert_called_once_with(self._PAYLOAD) - assert handler.call_args.args[1].image_paths == ['/pasted/copilot-image-1.png'] + assert handler.call_args.args[1].images == [_PASTED_IMAGE] def test_only_prompt_events_collect_images( self, mock_ctx: MagicMock, mocker: MockerFixture, handler: MagicMock, collect: MagicMock, fs: FakeFilesystem @@ -655,7 +658,7 @@ def test_failed_collection_still_scans_the_text( self._run(mock_ctx, mocker, _copilot_config(), self._PAYLOAD) handler.assert_called_once() - assert handler.call_args.args[1].image_paths == [] + assert handler.call_args.args[1].images == [] def test_images_are_collected_by_the_detached_child_not_the_parent( self, @@ -689,7 +692,7 @@ def test_images_are_collected_by_the_detached_child_not_the_parent( respawn.assert_called_once() handler.assert_called_once() - assert handler.call_args.args[1].image_paths == [str(paste)] + assert [image.path for image in handler.call_args.args[1].images] == [str(paste)] assert self._PAYLOAD['session_id'] in json.loads(get_prompt_marks_path().read_text(encoding='utf-8'))