diff --git a/README.md b/README.md index 2f4207e9..9ef79fc0 100644 --- a/README.md +++ b/README.md @@ -755,6 +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, 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..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,6 +160,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[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 + 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. + """ + 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..caff99a3 100644 --- a/cycode/cli/apps/ai_guardrails/ides/copilot.py +++ b/cycode/cli/apps/ai_guardrails/ides/copilot.py @@ -19,13 +19,21 @@ 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 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 @@ -40,6 +48,13 @@ from cycode.cli.apps.ai_guardrails.ides._skill_utils import walk_plugin_skills, walk_skill_dirs from cycode.cli.apps.ai_guardrails.ides.base import IDE, DecisionAction, HookDecision from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload +from cycode.cli.apps.ai_guardrails.scan.prompt_images import ( + PromptImage, + 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 +112,26 @@ _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. A lookahead, so +# every `@` is read on its own: a quote left open must not swallow the mentions after +# it, and a quoted path never spans lines. +_MENTION_PATTERN = re.compile(r'(? Path: """Resolve Copilot's user-scope home directory (honors ``$COPILOT_HOME``).""" @@ -118,13 +153,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 +420,80 @@ 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_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. + + 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] = [] + for product_name in _VSCODE_PRODUCT_NAMES: + 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): name: ClassVar[str] = 'copilot' display_name: ClassVar[str] = 'GitHub Copilot' @@ -450,6 +564,31 @@ def parse_hook_payload(self, raw_payload: dict) -> AIHookPayload: mcp_arguments=mcp_arguments, ) + def collect_prompt_images(self, raw_payload: dict) -> list[PromptImage]: + """Images attached to a prompt, 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 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 '' + 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(session_id, 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/handlers.py b/cycode/cli/apps/ai_guardrails/scan/handlers.py index 81c699db..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,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 PromptImage 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 '' @@ -127,11 +130,7 @@ def handle_before_submit_prompt(ctx: typer.Context, payload: AIHookPayload, poli try: scan_outcome = _scan_text_for_secrets( - ctx, - clipped, - timeout_ms, - payload=payload, - event_type=AiHookEventType.PROMPT, + ctx, clipped, timeout_ms, payload=payload, event_type=AiHookEventType.PROMPT, images=payload.images ) scan_id = scan_outcome.scan_id @@ -538,22 +537,53 @@ 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, + paths: tuple[str, ...] | None = None, ) -> ScanOutcome: - """Scan text content for secrets using Cycode CLI.""" - if not text: + """Scan in-memory documents for secrets, all in one scan; no documents means no 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) + scan_parameters = build_ai_guardrails_scan_parameters(scan_ctx, paths, payload, event_type) + return _perform_scan(scan_ctx, documents, scan_parameters, timeout_seconds) + + +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 scan by extension as well as + signature. The original path stays on the document, to name the image in the block message. + """ + 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, + timeout_ms: int, + payload: AIHookPayload, + event_type: AiHookEventType, + images: Sequence[PromptImage] = (), +) -> ScanOutcome: + """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(images)) + return _scan_documents_for_secrets(ctx, documents, timeout_ms, payload, event_type) def _scan_path_for_secrets( @@ -576,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 668d878a..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 @@ -33,6 +37,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. + 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 new file mode 100644 index 00000000..8713ff4d --- /dev/null +++ b/cycode/cli/apps/ai_guardrails/scan/prompt_images.py @@ -0,0 +1,184 @@ +"""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 dataclasses import dataclass +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 adds to the scan's time, which the IDE's hook timeout bounds +MAX_PROMPT_IMAGES = 5 + +# 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 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',)), + (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 + + +@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 + + @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 the same image can be attached twice, for example pasted and also mentioned by path. + """ + selected: list[PromptImage] = [] + 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(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 23b02424..c75c5653 100644 --- a/cycode/cli/apps/ai_guardrails/scan/scan_command.py +++ b/cycode/cli/apps/ai_guardrails/scan/scan_command.py @@ -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,12 @@ def scan_command( try: _initialize_clients(ctx) + if event_name == AiHookEventType.PROMPT: + # 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.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}) 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/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..b2a4d441 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. + + 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 '' + 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/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/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..c5aee5ba 100644 --- a/tests/cli/commands/ai_guardrails/ides/test_copilot.py +++ b/tests/cli/commands/ai_guardrails/ides/test_copilot.py @@ -6,8 +6,12 @@ import json import os +import sqlite3 +import tempfile +import time from pathlib import Path +import pytest from pyfakefs.fake_filesystem import FakeFilesystem from pytest_mock import MockerFixture @@ -15,9 +19,18 @@ 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, ) +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, +) from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType _VSCODE_PROMPT_PAYLOAD = { @@ -545,3 +558,221 @@ 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 _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 + + +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', + 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 / 'attachments' / 'uuid-1' / 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: + 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 _paths(images) == [shot, spaced, absolute] + + +def test_collect_prompt_images_reads_every_mention_after_an_unclosed_quote(fs: FakeFilesystem) -> 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 _paths(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')) + payload = {**_AGENT_PROMPT_PAYLOAD, 'prompt': r'@/Users/user/Desktop/Screenshot\ 2026-11-09\ at\ 10.15.32.png ?'} + + assert _paths(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 _paths(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, 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() + 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 _paths(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') + + 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 _paths(Copilot().collect_prompt_images(payload)) == [] + + +@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_first_prompt_takes_vscode_attachments_from_the_lookback( + fs: FakeFilesystem, vscode_chats: dict[str, str] +) -> None: + now = time.time() + 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 _paths(Copilot().collect_prompt_images(_VSCODE_PROMPT_PAYLOAD)) == [recent] + + +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_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 _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 _paths(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']] + + +# --- 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_handlers.py b/tests/cli/commands/ai_guardrails/scan/test_handlers.py index 41ab6c33..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 @@ -550,6 +551,135 @@ 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: + mock_payload.images = [PromptImage('/images/shot.png', _PNG), PromptImage('/images/Screenshot', _JPEG)] + + 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: + mock_payload.prompt = '' + mock_payload.images = [PromptImage('/images/shot.png', _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 = '' + mock_payload.images = [] + + 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: + mock_payload.prompt = 'ghp_ in the text' + mock_payload.images = [PromptImage('/attachments/uuid-1/diagram.png', _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..edbdd417 --- /dev/null +++ b/tests/cli/commands/ai_guardrails/scan/test_prompt_images.py @@ -0,0 +1,200 @@ +"""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, + PromptImage, + get_prompt_mark, + get_prompt_marks_path, + 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 == [ + 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: + """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(['/pasted/image.png', '/mentioned/image.png', '/mentioned/other.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: + 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 [image.path for image in selected] == ['/images/copy.png', *paths[1:MAX_PROMPT_IMAGES]] + assert len(selected) == MAX_PROMPT_IMAGES + + +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 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 f6afccb6..88234e72 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 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 +from tests.cli.commands.ai_guardrails.scan.conftest import platform_config, resolved_guardrails_payload @pytest.fixture(autouse=True) @@ -569,6 +573,129 @@ def test_failed_respawn_falls_back_to_synchronous_scan( handler.assert_called_once() +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() + 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()) + + +_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.""" + + _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_IMAGE]) + + 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') + + # 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) + + respawn.assert_not_called() + collect.assert_called_once_with(self._PAYLOAD) + 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 + ) -> 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(), 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(), self._PAYLOAD) + + handler.assert_called_once() + assert handler.call_args.args[1].images == [] + + 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() / '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) + 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 [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')) + + 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..569cd866 --- /dev/null +++ b/tests/cli/models/test_document.py @@ -0,0 +1,22 @@ +"""Binary (bytes) documents, as the guardrails scan sends attached images.""" + +from cycode.cli.models import Document +from cycode.cli.utils.scan_batch import split_documents_into_batches + +_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]