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

Filter by extension

Filter by extension

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


Expand Down Expand Up @@ -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.
Expand Down
149 changes: 144 additions & 5 deletions cycode/cli/apps/ai_guardrails/ides/copilot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down Expand Up @@ -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'(?<!\S)@(?=("[^"\n]+"|\'[^\'\n]+\'|(?:\\ |\S)+))')
_MENTION_TRAILING_PUNCTUATION = '.,;:!?)]}'
# Copilot CLI replaces a pasted image with this placeholder, naming the file it saved
# in the temp directory.
_PASTED_IMAGE_PATTERN = re.compile(r'\[image:\s*([^\]\r\n]+?)\s*\]')

# 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_CHAT_DB_NAME = 'session.db'
_VSCODE_CHAT_SESSION_KEYS = ('defaultChatProviderData', 'agentHost.chatProviderData')


def _copilot_home() -> Path:
"""Resolve Copilot's user-scope home directory (honors ``$COPILOT_HOME``)."""
Expand All @@ -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:
Expand Down Expand Up @@ -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)
# <chat id>/attachments/<attachment id>/<file>
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'
Expand Down Expand Up @@ -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
Expand Down
65 changes: 47 additions & 18 deletions cycode/cli/apps/ai_guardrails/scan/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand All @@ -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.
Expand Down Expand Up @@ -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 ''
Expand All @@ -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

Expand Down Expand Up @@ -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(
Expand All @@ -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,)
)
7 changes: 7 additions & 0 deletions cycode/cli/apps/ai_guardrails/scan/payload.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
Loading
Loading