cycode 3.27.1.dev11__py3-none-any.whl → 3.27.2.dev1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cycode/__init__.py +1 -1
- cycode/cli/apps/ai_guardrails/ides/base.py +13 -0
- cycode/cli/apps/ai_guardrails/ides/copilot.py +144 -5
- cycode/cli/apps/ai_guardrails/scan/handlers.py +47 -18
- cycode/cli/apps/ai_guardrails/scan/payload.py +7 -0
- cycode/cli/apps/ai_guardrails/scan/prompt_images.py +184 -0
- cycode/cli/apps/ai_guardrails/scan/scan_command.py +15 -0
- cycode/cli/apps/ai_guardrails/scan/utils.py +15 -7
- cycode/cli/files_collector/models/in_memory_zip.py +4 -5
- cycode/cli/files_collector/sca/maven/restore_gradle_dependencies.py +68 -13
- cycode/cli/models.py +13 -2
- cycode/cli/utils/scan_batch.py +2 -1
- {cycode-3.27.1.dev11.dist-info → cycode-3.27.2.dev1.dist-info}/METADATA +2 -1
- {cycode-3.27.1.dev11.dist-info → cycode-3.27.2.dev1.dist-info}/RECORD +17 -16
- {cycode-3.27.1.dev11.dist-info → cycode-3.27.2.dev1.dist-info}/WHEEL +0 -0
- {cycode-3.27.1.dev11.dist-info → cycode-3.27.2.dev1.dist-info}/entry_points.txt +0 -0
- {cycode-3.27.1.dev11.dist-info → cycode-3.27.2.dev1.dist-info}/licenses/LICENCE +0 -0
cycode/__init__.py
CHANGED
|
@@ -5,4 +5,4 @@ import time as _time
|
|
|
5
5
|
# end-to-end scan duration from the moment the user actually triggered it.
|
|
6
6
|
_BOOT_WALL: float = _time.time()
|
|
7
7
|
|
|
8
|
-
__version__ = '3.27.
|
|
8
|
+
__version__ = '3.27.2.dev1' # DON'T TOUCH. Placeholder. Will be filled automatically on poetry build from Git Tag
|
|
@@ -21,6 +21,7 @@ from pathlib import Path
|
|
|
21
21
|
from typing import ClassVar
|
|
22
22
|
|
|
23
23
|
from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload
|
|
24
|
+
from cycode.cli.apps.ai_guardrails.scan.prompt_images import PromptImage
|
|
24
25
|
from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType
|
|
25
26
|
|
|
26
27
|
|
|
@@ -159,6 +160,18 @@ class IDE(ABC):
|
|
|
159
160
|
def parse_hook_payload(self, raw_payload: dict) -> AIHookPayload:
|
|
160
161
|
"""Normalize a raw stdin payload into the canonical ``AIHookPayload``."""
|
|
161
162
|
|
|
163
|
+
def collect_prompt_images(self, raw_payload: dict) -> list[PromptImage]:
|
|
164
|
+
"""Return the images attached to a prompt, read once, to scan along with its text.
|
|
165
|
+
|
|
166
|
+
``scan_command`` calls it for every prompt event, only in the process that runs the scan
|
|
167
|
+
(never in a parent about to detach): collecting may move per-session state forward, so a
|
|
168
|
+
second call for the same prompt finds nothing. The server decides whether to scan them.
|
|
169
|
+
|
|
170
|
+
Default: ``[]`` (attachments are out of the hook's reach). Override for IDEs that leave
|
|
171
|
+
them on disk.
|
|
172
|
+
"""
|
|
173
|
+
return []
|
|
174
|
+
|
|
162
175
|
@abstractmethod
|
|
163
176
|
def build_hook_response(self, decision: HookDecision) -> dict:
|
|
164
177
|
"""Translate a canonical ``HookDecision`` into the IDE-specific JSON.
|
|
@@ -19,13 +19,21 @@ runtime uses ``Read``/``path`` and ``<server>-<tool>`` — so both are accepted.
|
|
|
19
19
|
Copilot hooks have no matchers, so ``PreToolUse`` fires for every tool; tools we
|
|
20
20
|
don't scan pass through as raw event names, which match no handler and allow
|
|
21
21
|
immediately.
|
|
22
|
+
|
|
23
|
+
A ``UserPromptSubmit`` payload carries the prompt text only, never its attachments,
|
|
24
|
+
but by the time the hook runs Copilot has saved every attached image to disk; see
|
|
25
|
+
``Copilot.collect_prompt_images`` for where each runtime puts them.
|
|
22
26
|
"""
|
|
23
27
|
|
|
24
28
|
import json
|
|
25
29
|
import os
|
|
26
30
|
import platform
|
|
27
31
|
import re
|
|
32
|
+
import sqlite3
|
|
33
|
+
import tempfile
|
|
34
|
+
import time
|
|
28
35
|
from collections.abc import Iterable
|
|
36
|
+
from contextlib import closing
|
|
29
37
|
from pathlib import Path
|
|
30
38
|
from typing import ClassVar
|
|
31
39
|
from urllib.parse import urlparse
|
|
@@ -40,6 +48,13 @@ from cycode.cli.apps.ai_guardrails.ides._plugin_utils import (
|
|
|
40
48
|
from cycode.cli.apps.ai_guardrails.ides._skill_utils import walk_plugin_skills, walk_skill_dirs
|
|
41
49
|
from cycode.cli.apps.ai_guardrails.ides.base import IDE, DecisionAction, HookDecision
|
|
42
50
|
from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload
|
|
51
|
+
from cycode.cli.apps.ai_guardrails.scan.prompt_images import (
|
|
52
|
+
PromptImage,
|
|
53
|
+
get_prompt_mark,
|
|
54
|
+
modified_between,
|
|
55
|
+
save_prompt_mark,
|
|
56
|
+
select_prompt_images,
|
|
57
|
+
)
|
|
43
58
|
from cycode.cli.apps.ai_guardrails.scan.types import AiHookEventType
|
|
44
59
|
from cycode.logger import get_logger
|
|
45
60
|
|
|
@@ -97,6 +112,26 @@ _PLUGIN_MANIFEST_LOCATIONS = (
|
|
|
97
112
|
_SCAN_COMMAND = f'{CYCODE_SCAN_PROMPT_COMMAND} --ide copilot'
|
|
98
113
|
_SESSION_START_COMMAND = f'{CYCODE_SESSION_START_COMMAND} --ide copilot'
|
|
99
114
|
|
|
115
|
+
# Copilot CLI leaves an `@path` mention in the prompt as typed: quoted, with
|
|
116
|
+
# backslash-escaped spaces (a file dragged into a terminal), or plain up to the next
|
|
117
|
+
# whitespace. Never mid-word, so an email address is not a mention. A lookahead, so
|
|
118
|
+
# every `@` is read on its own: a quote left open must not swallow the mentions after
|
|
119
|
+
# it, and a quoted path never spans lines.
|
|
120
|
+
_MENTION_PATTERN = re.compile(r'(?<!\S)@(?=("[^"\n]+"|\'[^\'\n]+\'|(?:\\ |\S)+))')
|
|
121
|
+
_MENTION_TRAILING_PUNCTUATION = '.,;:!?)]}'
|
|
122
|
+
# Copilot CLI replaces a pasted image with this placeholder, naming the file it saved
|
|
123
|
+
# in the temp directory.
|
|
124
|
+
_PASTED_IMAGE_PATTERN = re.compile(r'\[image:\s*([^\]\r\n]+?)\s*\]')
|
|
125
|
+
|
|
126
|
+
# VS Code (stable and Insiders) agent sessions copy a prompt's attachments into the
|
|
127
|
+
# chat's session data when it is sent. That folder is named after VS Code's chat id, not
|
|
128
|
+
# the hook's session_id; the chat's session database records the agent runtime's session
|
|
129
|
+
# id, which is the hook's, under one of these keys.
|
|
130
|
+
_VSCODE_PRODUCT_NAMES = ('Code', 'Code - Insiders')
|
|
131
|
+
_VSCODE_ATTACHMENT_COPIES_GLOB = 'agentSessionData/*/attachments/*/*'
|
|
132
|
+
_VSCODE_CHAT_DB_NAME = 'session.db'
|
|
133
|
+
_VSCODE_CHAT_SESSION_KEYS = ('defaultChatProviderData', 'agentHost.chatProviderData')
|
|
134
|
+
|
|
100
135
|
|
|
101
136
|
def _copilot_home() -> Path:
|
|
102
137
|
"""Resolve Copilot's user-scope home directory (honors ``$COPILOT_HOME``)."""
|
|
@@ -118,13 +153,18 @@ def _vscode_agent_plugins_dir() -> Path:
|
|
|
118
153
|
return Path.home() / '.vscode' / 'agent-plugins'
|
|
119
154
|
|
|
120
155
|
|
|
121
|
-
def
|
|
122
|
-
"""Per-platform VS Code user
|
|
156
|
+
def _vscode_user_data_dir(product_name: str = 'Code') -> Path:
|
|
157
|
+
"""Per-platform VS Code user data directory; ``product_name`` is 'Code' or 'Code - Insiders'."""
|
|
123
158
|
if platform.system() == 'Darwin':
|
|
124
|
-
return Path.home() / 'Library' / 'Application Support' /
|
|
159
|
+
return Path.home() / 'Library' / 'Application Support' / product_name
|
|
125
160
|
if platform.system() == 'Windows':
|
|
126
|
-
return Path.home() / 'AppData' / 'Roaming' /
|
|
127
|
-
return Path.home() / '.config' /
|
|
161
|
+
return Path.home() / 'AppData' / 'Roaming' / product_name
|
|
162
|
+
return Path.home() / '.config' / product_name
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _vscode_user_dir() -> Path:
|
|
166
|
+
"""Per-platform VS Code user settings directory."""
|
|
167
|
+
return _vscode_user_data_dir() / 'User'
|
|
128
168
|
|
|
129
169
|
|
|
130
170
|
def _vscode_mcp_config_path() -> Path:
|
|
@@ -380,6 +420,80 @@ def split_mcp_tool_name(tool_name: str, server_names: Iterable[str]) -> tuple[st
|
|
|
380
420
|
return None, rest or None
|
|
381
421
|
|
|
382
422
|
|
|
423
|
+
# --- prompt images ------------------------------------------------------------------
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _mentioned_files(prompt: str, cwd: str | None) -> list[Path]:
|
|
427
|
+
"""Existing files named by `@` mentions, resolved against the hook's cwd."""
|
|
428
|
+
base = Path(cwd) if cwd else Path()
|
|
429
|
+
files = []
|
|
430
|
+
for match in _MENTION_PATTERN.finditer(prompt):
|
|
431
|
+
token = match.group(1)
|
|
432
|
+
if len(token) > 1 and token[0] == token[-1] and token[0] in '"\'':
|
|
433
|
+
spellings = [token[1:-1]]
|
|
434
|
+
else:
|
|
435
|
+
if os.sep == '/':
|
|
436
|
+
token = token.replace('\\ ', ' ')
|
|
437
|
+
# The mention may end a sentence ("look at @shot.png.")
|
|
438
|
+
spellings = [token, token.rstrip(_MENTION_TRAILING_PUNCTUATION)]
|
|
439
|
+
for spelling in spellings:
|
|
440
|
+
path = base / os.path.expanduser(spelling)
|
|
441
|
+
if os.path.isfile(path):
|
|
442
|
+
files.append(path)
|
|
443
|
+
break
|
|
444
|
+
return files
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _pasted_cli_images(prompt: str) -> list[Path]:
|
|
448
|
+
"""Images pasted into Copilot CLI, saved in the temp directory its placeholder names."""
|
|
449
|
+
temp_dir = Path(tempfile.gettempdir())
|
|
450
|
+
# The base name only: the placeholder is prompt text, so it must not lead outside the temp directory
|
|
451
|
+
return [temp_dir / os.path.basename(name) for name in _PASTED_IMAGE_PATTERN.findall(prompt)]
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def _vscode_chat_session_id(chat_dir: Path) -> str | None:
|
|
455
|
+
"""The agent runtime's session id that VS Code recorded for a chat, or None."""
|
|
456
|
+
db_path = chat_dir / _VSCODE_CHAT_DB_NAME
|
|
457
|
+
if not db_path.is_file():
|
|
458
|
+
return None
|
|
459
|
+
placeholders = ', '.join('?' * len(_VSCODE_CHAT_SESSION_KEYS))
|
|
460
|
+
query = f'SELECT value FROM session_metadata WHERE key IN ({placeholders})' # noqa: S608
|
|
461
|
+
try:
|
|
462
|
+
# Read-only: VS Code keeps writing to the file while the chat is open
|
|
463
|
+
with closing(sqlite3.connect(f'{db_path.resolve().as_uri()}?mode=ro', uri=True, timeout=1)) as connection:
|
|
464
|
+
values = [value for (value,) in connection.execute(query, _VSCODE_CHAT_SESSION_KEYS)]
|
|
465
|
+
except sqlite3.Error as e:
|
|
466
|
+
logger.debug('Failed to read a VS Code chat session database, %s', {'path': str(db_path)}, exc_info=e)
|
|
467
|
+
return None
|
|
468
|
+
for value in values:
|
|
469
|
+
try:
|
|
470
|
+
session_id = json.loads(value).get('sdkSessionId')
|
|
471
|
+
except (TypeError, ValueError, AttributeError):
|
|
472
|
+
continue
|
|
473
|
+
if isinstance(session_id, str) and session_id:
|
|
474
|
+
return session_id
|
|
475
|
+
return None
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def _vscode_saved_attachments(session_id: str | None, since: float, until: float) -> list[Path]:
|
|
479
|
+
"""Attachment files VS Code saved in ``[since, until)`` for this session's chat.
|
|
480
|
+
|
|
481
|
+
Other chats' attachments, in any window, never count. A prompt with no VS Code chat
|
|
482
|
+
of its own (Copilot CLI, or VS Code's local chat) gets none.
|
|
483
|
+
"""
|
|
484
|
+
if not session_id:
|
|
485
|
+
return []
|
|
486
|
+
copies: list[Path] = []
|
|
487
|
+
for product_name in _VSCODE_PRODUCT_NAMES:
|
|
488
|
+
copies.extend(_vscode_user_data_dir(product_name).glob(_VSCODE_ATTACHMENT_COPIES_GLOB))
|
|
489
|
+
recent = modified_between(copies, since, until)
|
|
490
|
+
# <chat id>/attachments/<attachment id>/<file>
|
|
491
|
+
chats_of_this_session = {
|
|
492
|
+
chat_dir for chat_dir in {path.parents[2] for path in recent} if _vscode_chat_session_id(chat_dir) == session_id
|
|
493
|
+
}
|
|
494
|
+
return [path for path in recent if path.parents[2] in chats_of_this_session]
|
|
495
|
+
|
|
496
|
+
|
|
383
497
|
class Copilot(IDE):
|
|
384
498
|
name: ClassVar[str] = 'copilot'
|
|
385
499
|
display_name: ClassVar[str] = 'GitHub Copilot'
|
|
@@ -450,6 +564,31 @@ class Copilot(IDE):
|
|
|
450
564
|
mcp_arguments=mcp_arguments,
|
|
451
565
|
)
|
|
452
566
|
|
|
567
|
+
def collect_prompt_images(self, raw_payload: dict) -> list[PromptImage]:
|
|
568
|
+
"""Images attached to a prompt, found where Copilot saved them before the hook ran.
|
|
569
|
+
|
|
570
|
+
Copilot CLI names its attachments in the prompt: an `@path` mention as typed, or
|
|
571
|
+
a pasted image's placeholder. VS Code names none, so its attachments are the files
|
|
572
|
+
it saved for this session's chat since the session's previous prompt (see
|
|
573
|
+
prompt_images).
|
|
574
|
+
"""
|
|
575
|
+
session_id = raw_payload.get('session_id')
|
|
576
|
+
prompt = raw_payload.get('prompt') or ''
|
|
577
|
+
now = time.time()
|
|
578
|
+
since = get_prompt_mark(session_id, now)
|
|
579
|
+
|
|
580
|
+
images = select_prompt_images(
|
|
581
|
+
[
|
|
582
|
+
*_mentioned_files(prompt, raw_payload.get('cwd')),
|
|
583
|
+
*_pasted_cli_images(prompt),
|
|
584
|
+
*_vscode_saved_attachments(session_id, since, now),
|
|
585
|
+
]
|
|
586
|
+
)
|
|
587
|
+
save_prompt_mark(session_id, now)
|
|
588
|
+
|
|
589
|
+
logger.debug('Collected prompt images, %s', {'images_count': len(images), 'since': since})
|
|
590
|
+
return images
|
|
591
|
+
|
|
453
592
|
def build_hook_response(self, decision: HookDecision) -> dict:
|
|
454
593
|
if decision.action == DecisionAction.ALLOW:
|
|
455
594
|
# Neutral allow: {} means "no objection", leaving VS Code's own
|
|
@@ -12,7 +12,7 @@ import json
|
|
|
12
12
|
import os
|
|
13
13
|
import sys
|
|
14
14
|
import threading
|
|
15
|
-
from collections.abc import Callable
|
|
15
|
+
from collections.abc import Callable, Sequence
|
|
16
16
|
from dataclasses import dataclass
|
|
17
17
|
from gettext import ngettext
|
|
18
18
|
from typing import TYPE_CHECKING, Any, NamedTuple
|
|
@@ -27,6 +27,7 @@ from cycode.cli.apps.ai_guardrails.ides.base import HookDecision
|
|
|
27
27
|
from cycode.cli.apps.ai_guardrails.scan.mcp_server_status import is_enforced, load_mcp_server_statuses
|
|
28
28
|
from cycode.cli.apps.ai_guardrails.scan.payload import AIHookPayload
|
|
29
29
|
from cycode.cli.apps.ai_guardrails.scan.policy import get_policy_value
|
|
30
|
+
from cycode.cli.apps.ai_guardrails.scan.prompt_images import PromptImage
|
|
30
31
|
from cycode.cli.apps.ai_guardrails.scan.types import (
|
|
31
32
|
SECRETS_BLOCK_REASON_BY_EVENT_TYPE,
|
|
32
33
|
AiHookEventType,
|
|
@@ -47,6 +48,8 @@ logger = get_logger('AI Guardrails')
|
|
|
47
48
|
|
|
48
49
|
HandlerFn = Callable[[typer.Context, AIHookPayload, dict], HookDecision]
|
|
49
50
|
|
|
51
|
+
_TEXT_DOCUMENT_NAME = 'prompt-content.txt'
|
|
52
|
+
|
|
50
53
|
|
|
51
54
|
def _ignore_commands(shas: tuple[str, ...]) -> list[str]:
|
|
52
55
|
"""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:
|
|
|
112
115
|
|
|
113
116
|
|
|
114
117
|
def handle_before_submit_prompt(ctx: typer.Context, payload: AIHookPayload, policy: dict) -> HookDecision:
|
|
115
|
-
"""Scan prompt text for secrets before it's sent to the AI model."""
|
|
118
|
+
"""Scan prompt text, and the images attached to it, for secrets before it's sent to the AI model."""
|
|
116
119
|
ai_client = ctx.obj['ai_security_client']
|
|
117
120
|
|
|
118
121
|
prompt = payload.prompt or ''
|
|
@@ -127,11 +130,7 @@ def handle_before_submit_prompt(ctx: typer.Context, payload: AIHookPayload, poli
|
|
|
127
130
|
|
|
128
131
|
try:
|
|
129
132
|
scan_outcome = _scan_text_for_secrets(
|
|
130
|
-
ctx,
|
|
131
|
-
clipped,
|
|
132
|
-
timeout_ms,
|
|
133
|
-
payload=payload,
|
|
134
|
-
event_type=AiHookEventType.PROMPT,
|
|
133
|
+
ctx, clipped, timeout_ms, payload=payload, event_type=AiHookEventType.PROMPT, images=payload.images
|
|
135
134
|
)
|
|
136
135
|
scan_id = scan_outcome.scan_id
|
|
137
136
|
|
|
@@ -538,22 +537,53 @@ def _perform_scan(
|
|
|
538
537
|
)
|
|
539
538
|
|
|
540
539
|
|
|
541
|
-
def
|
|
540
|
+
def _scan_documents_for_secrets(
|
|
542
541
|
ctx: typer.Context,
|
|
543
|
-
|
|
542
|
+
documents: list[Document],
|
|
544
543
|
timeout_ms: int,
|
|
545
544
|
payload: AIHookPayload,
|
|
546
545
|
event_type: AiHookEventType,
|
|
546
|
+
paths: tuple[str, ...] | None = None,
|
|
547
547
|
) -> ScanOutcome:
|
|
548
|
-
"""Scan
|
|
549
|
-
if not
|
|
548
|
+
"""Scan in-memory documents for secrets, all in one scan; no documents means no scan."""
|
|
549
|
+
if not documents:
|
|
550
550
|
return NO_SCAN
|
|
551
551
|
|
|
552
|
-
document = Document(path='prompt-content.txt', content=text, is_git_diff_format=False)
|
|
553
552
|
scan_ctx = _setup_scan_context(ctx)
|
|
554
553
|
timeout_seconds = timeout_ms / 1000.0
|
|
555
|
-
scan_parameters = build_ai_guardrails_scan_parameters(scan_ctx,
|
|
556
|
-
return _perform_scan(scan_ctx,
|
|
554
|
+
scan_parameters = build_ai_guardrails_scan_parameters(scan_ctx, paths, payload, event_type)
|
|
555
|
+
return _perform_scan(scan_ctx, documents, scan_parameters, timeout_seconds)
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def _image_documents(images: Sequence[PromptImage]) -> list[Document]:
|
|
559
|
+
"""One bytes document per attached image.
|
|
560
|
+
|
|
561
|
+
The entry name keeps an image extension because the server picks the files to scan by extension as well as
|
|
562
|
+
signature. The original path stays on the document, to name the image in the block message.
|
|
563
|
+
"""
|
|
564
|
+
return [
|
|
565
|
+
Document(
|
|
566
|
+
path=f'image-{index}-{image.file_name}',
|
|
567
|
+
content=image.content,
|
|
568
|
+
is_git_diff_format=False,
|
|
569
|
+
absolute_path=image.path,
|
|
570
|
+
)
|
|
571
|
+
for index, image in enumerate(images, start=1)
|
|
572
|
+
]
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def _scan_text_for_secrets(
|
|
576
|
+
ctx: typer.Context,
|
|
577
|
+
text: str,
|
|
578
|
+
timeout_ms: int,
|
|
579
|
+
payload: AIHookPayload,
|
|
580
|
+
event_type: AiHookEventType,
|
|
581
|
+
images: Sequence[PromptImage] = (),
|
|
582
|
+
) -> ScanOutcome:
|
|
583
|
+
"""Scan text, and the images attached with it, for secrets in one scan."""
|
|
584
|
+
documents = [Document(path=_TEXT_DOCUMENT_NAME, content=text, is_git_diff_format=False)] if text else []
|
|
585
|
+
documents.extend(_image_documents(images))
|
|
586
|
+
return _scan_documents_for_secrets(ctx, documents, timeout_ms, payload, event_type)
|
|
557
587
|
|
|
558
588
|
|
|
559
589
|
def _scan_path_for_secrets(
|
|
@@ -576,9 +606,8 @@ def _scan_path_for_secrets(
|
|
|
576
606
|
content = f.read(max_bytes)
|
|
577
607
|
|
|
578
608
|
timeout_ms = get_policy_value(policy, 'secrets', 'timeout_ms', default=30000)
|
|
579
|
-
timeout_seconds = timeout_ms / 1000.0
|
|
580
609
|
|
|
581
610
|
document = Document(path=os.path.basename(file_path), content=content, is_git_diff_format=False)
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
611
|
+
return _scan_documents_for_secrets(
|
|
612
|
+
ctx, [document], timeout_ms, payload, AiHookEventType.FILE_READ, paths=(file_path,)
|
|
613
|
+
)
|
|
@@ -7,6 +7,10 @@ respective IDE class.
|
|
|
7
7
|
|
|
8
8
|
import uuid
|
|
9
9
|
from dataclasses import dataclass, field
|
|
10
|
+
from typing import TYPE_CHECKING
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from cycode.cli.apps.ai_guardrails.scan.prompt_images import PromptImage
|
|
10
14
|
|
|
11
15
|
|
|
12
16
|
@dataclass
|
|
@@ -33,6 +37,9 @@ class AIHookPayload:
|
|
|
33
37
|
|
|
34
38
|
# Event-specific data
|
|
35
39
|
prompt: str | None = None # PROMPT events
|
|
40
|
+
# Images attached to the prompt, scanned with its text. Filled by scan_command (IDE.collect_prompt_images),
|
|
41
|
+
# not at parse time: collecting moves per-session state forward, so only the process that scans may do it.
|
|
42
|
+
images: list['PromptImage'] = field(default_factory=list)
|
|
36
43
|
file_path: str | None = None # FILE_READ events
|
|
37
44
|
mcp_server_name: str | None = None # MCP_EXECUTION events
|
|
38
45
|
mcp_tool_name: str | None = None
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""Images attached to an AI prompt, scanned for secrets along with its text.
|
|
2
|
+
|
|
3
|
+
Some IDEs (GitHub Copilot) save a prompt's attachments to disk before its hook runs, yet never name them in the
|
|
4
|
+
hook payload. The IDE integration finds the candidates (``IDE.collect_prompt_images``); this module holds what is
|
|
5
|
+
IDE-agnostic about them: the filters every candidate passes, and the per-session prompt marks that turn "files saved
|
|
6
|
+
for this prompt" into "files saved since the session's previous prompt".
|
|
7
|
+
|
|
8
|
+
A session's first prompt looks back a fixed time rather than to session start: VS Code fires SessionStart together
|
|
9
|
+
with the first prompt, after its attachments were already saved.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import stat
|
|
16
|
+
from collections.abc import Iterable
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from cycode.cli.consts import CYCODE_CONFIGURATION_DIRECTORY, FILE_MAX_SIZE_LIMIT_IN_BYTES
|
|
21
|
+
from cycode.cli.utils.path_utils import atomic_write_text, quarantine_corrupt_file
|
|
22
|
+
from cycode.logger import get_logger
|
|
23
|
+
|
|
24
|
+
logger = get_logger('AI Guardrails')
|
|
25
|
+
|
|
26
|
+
PROMPT_MARKS_FILE_NAME = 'ai-guardrails-prompt-marks.json'
|
|
27
|
+
|
|
28
|
+
# Each image adds to the scan's time, which the IDE's hook timeout bounds
|
|
29
|
+
MAX_PROMPT_IMAGES = 5
|
|
30
|
+
|
|
31
|
+
# Covers attachments saved a while before the prompt was sent
|
|
32
|
+
FIRST_PROMPT_LOOKBACK_SECONDS = 600
|
|
33
|
+
|
|
34
|
+
# A session idle this long loses its mark; if it comes back, its next prompt falls back to the lookback
|
|
35
|
+
_MARK_RETENTION_SECONDS = 7 * 24 * 60 * 60
|
|
36
|
+
|
|
37
|
+
# The image formats sent for scanning, by signature (a file's own extension can be wrong or missing), with the
|
|
38
|
+
# extensions that name each one
|
|
39
|
+
_IMAGE_FORMATS = (
|
|
40
|
+
(b'\x89PNG\r\n\x1a\n', ('.png',)),
|
|
41
|
+
(b'\xff\xd8\xff', ('.jpg', '.jpeg')),
|
|
42
|
+
)
|
|
43
|
+
_SIGNATURE_LENGTH = max(len(signature) for signature, _ in _IMAGE_FORMATS)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def get_prompt_marks_path() -> Path:
|
|
47
|
+
return Path.home() / CYCODE_CONFIGURATION_DIRECTORY / PROMPT_MARKS_FILE_NAME
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _load_marks() -> dict[str, float]:
|
|
51
|
+
"""``{session_id: timestamp}``; empty when the file is absent, or corrupt (then it is moved aside)."""
|
|
52
|
+
path = get_prompt_marks_path()
|
|
53
|
+
if not path.exists():
|
|
54
|
+
return {}
|
|
55
|
+
|
|
56
|
+
try:
|
|
57
|
+
with open(path, encoding='UTF-8') as file:
|
|
58
|
+
marks = json.load(file)
|
|
59
|
+
if not isinstance(marks, dict):
|
|
60
|
+
raise TypeError('prompt marks are not an object')
|
|
61
|
+
return {str(session_id): float(timestamp) for session_id, timestamp in marks.items()}
|
|
62
|
+
except Exception as e:
|
|
63
|
+
logger.warning('Prompt marks file is corrupt and will be moved aside', exc_info=e)
|
|
64
|
+
quarantine_corrupt_file(str(path))
|
|
65
|
+
return {}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def get_prompt_mark(session_id: str | None, now: float) -> float:
|
|
69
|
+
"""Where a prompt's attachments start: the session's previous prompt, or the first-prompt lookback."""
|
|
70
|
+
mark = _load_marks().get(session_id) if session_id else None
|
|
71
|
+
if mark is None:
|
|
72
|
+
return now - FIRST_PROMPT_LOOKBACK_SECONDS
|
|
73
|
+
# A mark from before the clock was set back must not hide every new file
|
|
74
|
+
return min(mark, now)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def save_prompt_mark(session_id: str | None, now: float) -> None:
|
|
78
|
+
"""Move the session's mark to ``now`` and drop the marks of long-idle sessions. Never raises.
|
|
79
|
+
|
|
80
|
+
Unlocked read-modify-write: two sessions prompting at the same moment may lose one update, which only sends that
|
|
81
|
+
session's next prompt back to the lookback. The atomic write keeps the file whole.
|
|
82
|
+
"""
|
|
83
|
+
if not session_id:
|
|
84
|
+
return
|
|
85
|
+
|
|
86
|
+
marks = _load_marks()
|
|
87
|
+
marks[session_id] = now
|
|
88
|
+
cutoff = now - _MARK_RETENTION_SECONDS
|
|
89
|
+
marks = {key: timestamp for key, timestamp in marks.items() if timestamp >= cutoff}
|
|
90
|
+
|
|
91
|
+
path = get_prompt_marks_path()
|
|
92
|
+
try:
|
|
93
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
94
|
+
atomic_write_text(str(path), json.dumps(marks))
|
|
95
|
+
except Exception as e:
|
|
96
|
+
logger.debug('Failed to save prompt marks', exc_info=e)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def modified_between(paths: Iterable[Path], since: float, until: float) -> list[Path]:
|
|
100
|
+
"""The paths last modified in ``[since, until)``, oldest first (the order they were attached in).
|
|
101
|
+
|
|
102
|
+
Half-open so that each file belongs to exactly one prompt: a file saved while this prompt's images are being
|
|
103
|
+
collected is left to the next prompt, whose window starts where this one ends.
|
|
104
|
+
"""
|
|
105
|
+
dated = []
|
|
106
|
+
for path in paths:
|
|
107
|
+
try:
|
|
108
|
+
modified_at = path.stat().st_mtime
|
|
109
|
+
except OSError:
|
|
110
|
+
continue
|
|
111
|
+
if since <= modified_at < until:
|
|
112
|
+
dated.append((modified_at, path))
|
|
113
|
+
return [path for _, path in sorted(dated, key=lambda item: item[0])]
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _image_extensions(content: bytes) -> tuple[str, ...]:
|
|
117
|
+
return next((extensions for signature, extensions in _IMAGE_FORMATS if content.startswith(signature)), ())
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def read_prompt_image(path: str | os.PathLike) -> bytes | None:
|
|
121
|
+
"""The bytes of a scannable image - a regular PNG or JPEG file within the size limit - or None.
|
|
122
|
+
|
|
123
|
+
Regular files only, checked before opening: an `@` mention can name a FIFO or a device, and reading one would
|
|
124
|
+
hang the hook. The signature is read first, so a mentioned source file is never read in full.
|
|
125
|
+
"""
|
|
126
|
+
try:
|
|
127
|
+
file_stat = os.stat(path)
|
|
128
|
+
if not stat.S_ISREG(file_stat.st_mode) or file_stat.st_size > FILE_MAX_SIZE_LIMIT_IN_BYTES:
|
|
129
|
+
return None
|
|
130
|
+
with open(path, 'rb') as file:
|
|
131
|
+
head = file.read(_SIGNATURE_LENGTH)
|
|
132
|
+
if not _image_extensions(head):
|
|
133
|
+
return None
|
|
134
|
+
# One byte past the limit tells a file that grew since the stat
|
|
135
|
+
content = head + file.read(FILE_MAX_SIZE_LIMIT_IN_BYTES + 1 - len(head))
|
|
136
|
+
except (OSError, ValueError) as e:
|
|
137
|
+
logger.debug('Failed to read a prompt image candidate, %s', {'path': str(path)}, exc_info=e)
|
|
138
|
+
return None
|
|
139
|
+
|
|
140
|
+
return content if len(content) <= FILE_MAX_SIZE_LIMIT_IN_BYTES else None
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
@dataclass(frozen=True)
|
|
144
|
+
class PromptImage:
|
|
145
|
+
"""An image attached to a prompt, read once when it is collected: where it was, and its bytes."""
|
|
146
|
+
|
|
147
|
+
path: str
|
|
148
|
+
content: bytes
|
|
149
|
+
|
|
150
|
+
@property
|
|
151
|
+
def file_name(self) -> str:
|
|
152
|
+
"""The file's name, plus the extension of its actual format when its own extension doesn't name it."""
|
|
153
|
+
name = os.path.basename(self.path)
|
|
154
|
+
extensions = _image_extensions(self.content)
|
|
155
|
+
if extensions and os.path.splitext(name)[1].lower() not in extensions:
|
|
156
|
+
name += extensions[0]
|
|
157
|
+
return name
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def select_prompt_images(candidates: Iterable[str | os.PathLike]) -> list[PromptImage]:
|
|
161
|
+
"""The candidates to scan, in order: scannable images (see read_prompt_image), each content once, at most
|
|
162
|
+
MAX_PROMPT_IMAGES.
|
|
163
|
+
|
|
164
|
+
Once per content because the same image can be attached twice, for example pasted and also mentioned by path.
|
|
165
|
+
"""
|
|
166
|
+
selected: list[PromptImage] = []
|
|
167
|
+
seen_digests: set[str] = set()
|
|
168
|
+
for candidate in candidates:
|
|
169
|
+
content = read_prompt_image(candidate)
|
|
170
|
+
if content is None:
|
|
171
|
+
continue
|
|
172
|
+
|
|
173
|
+
digest = hashlib.sha256(content).hexdigest()
|
|
174
|
+
if digest in seen_digests:
|
|
175
|
+
continue
|
|
176
|
+
|
|
177
|
+
if len(selected) == MAX_PROMPT_IMAGES:
|
|
178
|
+
logger.debug('More images than a prompt scans; skipping the rest, %s', {'max_images': MAX_PROMPT_IMAGES})
|
|
179
|
+
break
|
|
180
|
+
|
|
181
|
+
seen_digests.add(digest)
|
|
182
|
+
selected.append(PromptImage(path=str(candidate), content=content))
|
|
183
|
+
|
|
184
|
+
return selected
|
|
@@ -87,6 +87,15 @@ def _should_skip_payload(ide_integration: IDE, payload: dict | None) -> bool:
|
|
|
87
87
|
return False
|
|
88
88
|
|
|
89
89
|
|
|
90
|
+
def _collect_prompt_images(ide_integration: IDE, payload: dict) -> list[str]:
|
|
91
|
+
"""Best-effort: an image that can't be collected goes unscanned, but the prompt text is still scanned."""
|
|
92
|
+
try:
|
|
93
|
+
return ide_integration.collect_prompt_images(payload)
|
|
94
|
+
except Exception as e:
|
|
95
|
+
logger.debug('Failed to collect prompt images, scanning the text only', exc_info=e)
|
|
96
|
+
return []
|
|
97
|
+
|
|
98
|
+
|
|
90
99
|
def _initialize_clients(ctx: typer.Context) -> None:
|
|
91
100
|
"""Initialize API clients.
|
|
92
101
|
|
|
@@ -169,6 +178,12 @@ def scan_command(
|
|
|
169
178
|
try:
|
|
170
179
|
_initialize_clients(ctx)
|
|
171
180
|
|
|
181
|
+
if event_name == AiHookEventType.PROMPT:
|
|
182
|
+
# Always sent: the server decides whether to scan them.
|
|
183
|
+
# Here rather than in parse_hook_payload: collecting moves the session's prompt mark forward, so it
|
|
184
|
+
# runs once, after the detach decision - a parent that detached would leave its child nothing to find.
|
|
185
|
+
unified_payload.images = _collect_prompt_images(ide_integration, payload)
|
|
186
|
+
|
|
172
187
|
decision = handler(ctx, unified_payload, policy)
|
|
173
188
|
logger.debug('Hook handler completed', extra={'event_name': event_name, 'action': decision.action.value})
|
|
174
189
|
output_json(ide_integration.build_hook_response(decision))
|
|
@@ -17,7 +17,7 @@ from cycode.cli.cli_types import SeverityOption
|
|
|
17
17
|
from cycode.cli.utils.string_utils import obfuscate_text
|
|
18
18
|
|
|
19
19
|
if TYPE_CHECKING:
|
|
20
|
-
from cycode.cli.models import LocalScanResult
|
|
20
|
+
from cycode.cli.models import Document, LocalScanResult
|
|
21
21
|
from cycode.cyclient.models import Detection
|
|
22
22
|
|
|
23
23
|
# Keeps the hook message readable when a single file trips dozens of detections
|
|
@@ -101,17 +101,23 @@ def output_json(obj: dict) -> None:
|
|
|
101
101
|
print(json.dumps(obj), end='') # noqa: T201
|
|
102
102
|
|
|
103
103
|
|
|
104
|
-
def _describe_detection(detection: 'Detection',
|
|
104
|
+
def _describe_detection(detection: 'Detection', document: 'Document') -> str:
|
|
105
105
|
details = detection.detection_details
|
|
106
106
|
description = detection.type or detection.message
|
|
107
107
|
|
|
108
|
+
if isinstance(document.content, bytes):
|
|
109
|
+
# An attached image: its line and position point into text the server read out of it, which the developer
|
|
110
|
+
# never sees. Its name is what tells them which attachment to remove.
|
|
111
|
+
image_name = os.path.basename(document.absolute_path or document.path)
|
|
112
|
+
return f'{description} in image "{image_name}"'
|
|
113
|
+
|
|
108
114
|
line = details.get('line')
|
|
109
115
|
if isinstance(line, int) and line >= 0:
|
|
110
116
|
description += f' (line {line + 1})' # the scanner reports 0-based lines
|
|
111
117
|
|
|
112
118
|
start, length = details.get('start_position'), details.get('length')
|
|
113
119
|
if isinstance(start, int) and isinstance(length, int) and start >= 0 and length > 0:
|
|
114
|
-
value =
|
|
120
|
+
value = document.text_content[start : start + length]
|
|
115
121
|
if value:
|
|
116
122
|
description += f': {obfuscate_text(value)}'
|
|
117
123
|
|
|
@@ -126,14 +132,16 @@ def build_violation_summary(
|
|
|
126
132
|
The masked value and hash are safe to display; the value itself is not. Detections excluded by an existing
|
|
127
133
|
ignore rule are already gone from `document_detections`, so only what actually blocked is listed.
|
|
128
134
|
"""
|
|
129
|
-
# Keyed by value hash so a repeated value is listed once; detections without one key by their description
|
|
135
|
+
# Keyed by value hash so a repeated value is listed once; detections without one key by their description.
|
|
136
|
+
# Per document too: the same value in the prompt and in an attached image is two places to remove it from.
|
|
130
137
|
finding_by_key = {}
|
|
131
138
|
for local_scan_result in local_scan_results:
|
|
132
139
|
for document_detections in local_scan_result.document_detections:
|
|
140
|
+
document = document_detections.document
|
|
133
141
|
for detection in document_detections.detections:
|
|
134
|
-
description = _describe_detection(detection,
|
|
142
|
+
description = _describe_detection(detection, document)
|
|
135
143
|
sha = detection.detection_details.get('sha512')
|
|
136
|
-
finding_by_key.setdefault(sha or description, (sha, description))
|
|
144
|
+
finding_by_key.setdefault((document.path, sha or description), (sha, description))
|
|
137
145
|
|
|
138
146
|
listed = list(finding_by_key.values())[:max_lines]
|
|
139
147
|
lines = [_build_severity_line(local_scan_results)] + [f' - {description}' for _, description in listed]
|
|
@@ -141,7 +149,7 @@ def build_violation_summary(
|
|
|
141
149
|
if remaining:
|
|
142
150
|
lines.append(f' - ...and {remaining} more')
|
|
143
151
|
|
|
144
|
-
return '\n'.join(lines), tuple(sha for sha, _ in listed if sha)
|
|
152
|
+
return '\n'.join(lines), tuple(dict.fromkeys(sha for sha, _ in listed if sha))
|
|
145
153
|
|
|
146
154
|
|
|
147
155
|
def _build_severity_line(local_scan_results: list['LocalScanResult']) -> str:
|
|
@@ -47,17 +47,16 @@ class InMemoryZip:
|
|
|
47
47
|
self._files_count = 0
|
|
48
48
|
self._extension_statistics = defaultdict(int)
|
|
49
49
|
|
|
50
|
-
def append(self, filename: str, unique_id: str | None, content: str) -> None:
|
|
50
|
+
def append(self, filename: str, unique_id: str | None, content: str | bytes) -> None:
|
|
51
51
|
self._files_count += 1
|
|
52
52
|
self._extension_statistics[Path(filename).suffix] += 1
|
|
53
53
|
|
|
54
54
|
if unique_id:
|
|
55
55
|
filename = concat_unique_id(filename, unique_id)
|
|
56
56
|
|
|
57
|
-
#
|
|
58
|
-
# that cannot be encoded to UTF-8
|
|
59
|
-
|
|
60
|
-
content_bytes = content.encode('utf-8', errors='replace')
|
|
57
|
+
# Bytes (an image) go in unchanged. Text is encoded with 'replace' so surrogate characters
|
|
58
|
+
# that cannot be encoded to UTF-8 become '?' instead of failing the scan.
|
|
59
|
+
content_bytes = content if isinstance(content, bytes) else content.encode('utf-8', errors='replace')
|
|
61
60
|
self.zip.writestr(filename, content_bytes)
|
|
62
61
|
|
|
63
62
|
def close(self) -> None:
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import os
|
|
2
2
|
import platform
|
|
3
3
|
import re
|
|
4
|
+
from pathlib import Path
|
|
4
5
|
|
|
5
6
|
import typer
|
|
6
7
|
|
|
@@ -8,11 +9,17 @@ from cycode.cli.files_collector.sca.base_restore_dependencies import BaseRestore
|
|
|
8
9
|
from cycode.cli.models import Document
|
|
9
10
|
from cycode.cli.utils.path_utils import get_path_from_context
|
|
10
11
|
from cycode.cli.utils.shell_executor import shell
|
|
12
|
+
from cycode.logger import get_logger
|
|
13
|
+
|
|
14
|
+
logger = get_logger('Gradle Restore')
|
|
11
15
|
|
|
12
16
|
BUILD_GRADLE_FILE_NAME = 'build.gradle'
|
|
13
17
|
BUILD_GRADLE_KTS_FILE_NAME = 'build.gradle.kts'
|
|
14
18
|
BUILD_GRADLE_DEP_TREE_FILE_NAME = 'gradle-dependencies-generated.txt'
|
|
15
19
|
ALL_PROJECTS_REGEX = r"[+-]{3} Project '(.*?)'"
|
|
20
|
+
PROJECT_LOCATION_REGEX = r"^project '(.+?)' - (.+?)\s*$"
|
|
21
|
+
CURRENT_PROJECT_REGEX = r"^Project '(.+?)'\s*$"
|
|
22
|
+
ROOT_PROJECT_PATH = ':'
|
|
16
23
|
|
|
17
24
|
GRADLE_EXECUTABLE = 'gradle'
|
|
18
25
|
GRADLEW_FILE_NAME = 'gradlew'
|
|
@@ -27,6 +34,7 @@ class RestoreGradleDependencies(BaseRestoreDependencies):
|
|
|
27
34
|
self.gradle_executable = self._resolve_gradle_executable()
|
|
28
35
|
if projects is None:
|
|
29
36
|
projects = set()
|
|
37
|
+
self.project_locations: dict[Path, str] = {}
|
|
30
38
|
self.projects = self.get_all_projects() if self.is_gradle_sub_projects() else projects
|
|
31
39
|
|
|
32
40
|
def _resolve_gradle_executable(self) -> str:
|
|
@@ -45,11 +53,13 @@ class RestoreGradleDependencies(BaseRestoreDependencies):
|
|
|
45
53
|
return document.path.endswith(BUILD_GRADLE_FILE_NAME) or document.path.endswith(BUILD_GRADLE_KTS_FILE_NAME)
|
|
46
54
|
|
|
47
55
|
def get_commands(self, manifest_file_path: str) -> list[list[str]]:
|
|
48
|
-
|
|
49
|
-
self.get_commands_for_sub_projects(manifest_file_path)
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
56
|
+
if self.is_gradle_sub_projects():
|
|
57
|
+
return self.get_commands_for_sub_projects(manifest_file_path)
|
|
58
|
+
|
|
59
|
+
# Gradle finds the root settings file above it and selects the project whose projectDir
|
|
60
|
+
# is that directory.
|
|
61
|
+
manifest_dir = str(Path(manifest_file_path).parent)
|
|
62
|
+
return [[self.gradle_executable, '-p', manifest_dir, 'dependencies', '-q', '--console', 'plain']]
|
|
53
63
|
|
|
54
64
|
def get_lock_file_name(self) -> str:
|
|
55
65
|
return BUILD_GRADLE_DEP_TREE_FILE_NAME
|
|
@@ -61,21 +71,66 @@ class RestoreGradleDependencies(BaseRestoreDependencies):
|
|
|
61
71
|
return get_path_from_context(self.ctx) if self.is_gradle_sub_projects() else None
|
|
62
72
|
|
|
63
73
|
def get_all_projects(self) -> set[str]:
|
|
74
|
+
scan_root = get_path_from_context(self.ctx)
|
|
64
75
|
output = shell(
|
|
65
76
|
command=[self.gradle_executable, 'projects'],
|
|
66
77
|
timeout=self.command_timeout,
|
|
67
|
-
working_directory=
|
|
78
|
+
working_directory=scan_root,
|
|
68
79
|
)
|
|
69
80
|
if not output:
|
|
70
81
|
return set()
|
|
71
82
|
|
|
83
|
+
if scan_root:
|
|
84
|
+
self.project_locations = self._parse_project_locations(output, Path(scan_root))
|
|
85
|
+
|
|
72
86
|
return set(re.findall(ALL_PROJECTS_REGEX, output))
|
|
73
87
|
|
|
88
|
+
@staticmethod
|
|
89
|
+
def _parse_project_locations(output: str, scan_root: Path) -> dict[Path, str]:
|
|
90
|
+
"""Map each project directory to its Gradle project path, from the "Project locations" section."""
|
|
91
|
+
# A location starts with a separator ("/x/y"). Strip it, or pathlib treats it as an absolute path.
|
|
92
|
+
relative_dirs = {
|
|
93
|
+
project_path: Path(relative_dir.lstrip('/\\'))
|
|
94
|
+
for project_path, relative_dir in re.findall(PROJECT_LOCATION_REGEX, output, flags=re.MULTILINE)
|
|
95
|
+
}
|
|
96
|
+
if not relative_dirs:
|
|
97
|
+
return {}
|
|
98
|
+
|
|
99
|
+
build_root = RestoreGradleDependencies._find_build_root(output, scan_root, relative_dirs)
|
|
100
|
+
locations = {(build_root / relative_dir).resolve(): path for path, relative_dir in relative_dirs.items()}
|
|
101
|
+
locations[build_root] = ROOT_PROJECT_PATH
|
|
102
|
+
return locations
|
|
103
|
+
|
|
104
|
+
@staticmethod
|
|
105
|
+
def _find_build_root(output: str, scan_root: Path, relative_dirs: dict[str, Path]) -> Path:
|
|
106
|
+
build_root = scan_root.resolve()
|
|
107
|
+
current_project = re.search(CURRENT_PROJECT_REGEX, output, flags=re.MULTILINE)
|
|
108
|
+
if current_project and current_project.group(1) in relative_dirs:
|
|
109
|
+
for _ in relative_dirs[current_project.group(1)].parts:
|
|
110
|
+
build_root = build_root.parent
|
|
111
|
+
|
|
112
|
+
return build_root
|
|
113
|
+
|
|
114
|
+
def _get_sub_project_path(self, manifest_file_path: str) -> str | None:
|
|
115
|
+
manifest_dir = Path(manifest_file_path).parent
|
|
116
|
+
if self.project_locations:
|
|
117
|
+
return self.project_locations.get(manifest_dir.resolve())
|
|
118
|
+
|
|
119
|
+
scan_root = get_path_from_context(self.ctx)
|
|
120
|
+
if self.projects and scan_root and manifest_dir.resolve() == Path(scan_root).resolve():
|
|
121
|
+
return ROOT_PROJECT_PATH
|
|
122
|
+
|
|
123
|
+
project_path = f':{manifest_dir.name}'
|
|
124
|
+
return project_path if project_path in self.projects else None
|
|
125
|
+
|
|
74
126
|
def get_commands_for_sub_projects(self, manifest_file_path: str) -> list[list[str]]:
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
127
|
+
project_path = self._get_sub_project_path(manifest_file_path)
|
|
128
|
+
if project_path is None:
|
|
129
|
+
logger.debug(
|
|
130
|
+
'Manifest does not match a Gradle project, skipping restore, %s',
|
|
131
|
+
{'manifest_file_path': manifest_file_path},
|
|
132
|
+
)
|
|
133
|
+
return []
|
|
134
|
+
|
|
135
|
+
task = 'dependencies' if project_path == ROOT_PROJECT_PATH else f'{project_path}:dependencies'
|
|
136
|
+
return [[self.gradle_executable, task, '-q', '--console', 'plain']]
|
cycode/cli/models.py
CHANGED
|
@@ -8,19 +8,30 @@ class Document:
|
|
|
8
8
|
def __init__(
|
|
9
9
|
self,
|
|
10
10
|
path: str,
|
|
11
|
-
content: str,
|
|
11
|
+
content: str | bytes,
|
|
12
12
|
is_git_diff_format: bool = False,
|
|
13
13
|
unique_id: str | None = None,
|
|
14
14
|
absolute_path: str | None = None,
|
|
15
15
|
) -> None:
|
|
16
16
|
self.path = path
|
|
17
|
+
# bytes for binary content scanned as is (an image attached to an AI prompt); text otherwise
|
|
17
18
|
self.content = content
|
|
18
19
|
self.is_git_diff_format = is_git_diff_format
|
|
19
20
|
self.unique_id = unique_id
|
|
20
21
|
self.absolute_path = absolute_path
|
|
21
22
|
|
|
23
|
+
@property
|
|
24
|
+
def text_content(self) -> str:
|
|
25
|
+
"""The content as text; '' for binary content.
|
|
26
|
+
|
|
27
|
+
Positions the server reports for binary content don't point into anything stored locally, so there is no
|
|
28
|
+
line or value to cut out of it here.
|
|
29
|
+
"""
|
|
30
|
+
return self.content if isinstance(self.content, str) else ''
|
|
31
|
+
|
|
22
32
|
def __repr__(self) -> str:
|
|
23
|
-
|
|
33
|
+
content = f'<{len(self.content)} bytes>' if isinstance(self.content, bytes) else self.content
|
|
34
|
+
return f'path:{self.path}, content:{content}'
|
|
24
35
|
|
|
25
36
|
|
|
26
37
|
class DocumentDetections:
|
cycode/cli/utils/scan_batch.py
CHANGED
|
@@ -61,7 +61,8 @@ def split_documents_into_batches(
|
|
|
61
61
|
current_size = 0
|
|
62
62
|
current_batch = []
|
|
63
63
|
for document in documents:
|
|
64
|
-
|
|
64
|
+
content = document.content
|
|
65
|
+
document_size = len(content) if isinstance(content, bytes) else len(content.encode('UTF-8'))
|
|
65
66
|
|
|
66
67
|
exceeds_max_size = current_size + document_size > max_size
|
|
67
68
|
if exceeds_max_size:
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: cycode
|
|
3
|
-
Version: 3.27.
|
|
3
|
+
Version: 3.27.2.dev1
|
|
4
4
|
Summary: Boost security in your dev lifecycle via SAST, SCA, Secrets & IaC scanning.
|
|
5
5
|
License-Expression: MIT
|
|
6
6
|
License-File: LICENCE
|
|
@@ -800,6 +800,7 @@ prompts, files the agent reads, and MCP tool arguments are scanned for secrets b
|
|
|
800
800
|
|
|
801
801
|
Scanning happens server-side, so the scanned content leaves the machine: the prompt text, the contents of
|
|
802
802
|
files the agent reads, and MCP tool arguments are sent to your Cycode tenant to be checked for secrets.
|
|
803
|
+
For GitHub Copilot, PNG and JPEG images attached to a prompt are sent along with its text.
|
|
803
804
|
|
|
804
805
|
Each event is also reported with context about the developer and the machine, so a finding can be attributed
|
|
805
806
|
to the device and user it came from. Some of this is personal data:
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
cycode/__init__.py,sha256=
|
|
1
|
+
cycode/__init__.py,sha256=yabemqfBKwJhkH_AH0LZ4Raarpd51a0ZYt9x8_Edqww,396
|
|
2
2
|
cycode/__main__.py,sha256=Z3bD5yrA7yPvAChcADQrqCaZd0ChGI1gdiwALwbWJ6U,104
|
|
3
3
|
cycode/cli/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
4
|
cycode/cli/app.py,sha256=sI6wBHmfo7RchO9rnOXaQyUHRG9fm4r9aIduV4ZOD5c,10167
|
|
@@ -11,23 +11,24 @@ cycode/cli/apps/ai_guardrails/hooks_manager.py,sha256=HrfEHamt4x9MSTDZf6HZPqJSvC
|
|
|
11
11
|
cycode/cli/apps/ai_guardrails/ides/__init__.py,sha256=wUvkI0b0RvoLNaQcEjX3v4YgAzz8gKmUxpIkjvWlWIE,3240
|
|
12
12
|
cycode/cli/apps/ai_guardrails/ides/_plugin_utils.py,sha256=RGCtuxtsLnWvVZLxjqC09Brnrwq9CP1O9dyAIm2sQfs,4018
|
|
13
13
|
cycode/cli/apps/ai_guardrails/ides/_skill_utils.py,sha256=c4FeoJAJdRIKodTiXbWH7xymSfJ9IlzlilUvT17QH8E,3941
|
|
14
|
-
cycode/cli/apps/ai_guardrails/ides/base.py,sha256=
|
|
14
|
+
cycode/cli/apps/ai_guardrails/ides/base.py,sha256=m0IJGH4xoPhUQZCFRYlr3GYRueJfhs6_qr1wIJ7GDLg,9123
|
|
15
15
|
cycode/cli/apps/ai_guardrails/ides/claude_code.py,sha256=L9N3vmrCculGFfTTFpFBssjhTdmwFfmm7QM18JaVx6E,17590
|
|
16
16
|
cycode/cli/apps/ai_guardrails/ides/codex.py,sha256=NG9iD09HeBAI1MQtDHDPwGQm9FY_CjdIMHmCJgq2Pu0,13679
|
|
17
|
-
cycode/cli/apps/ai_guardrails/ides/copilot.py,sha256=
|
|
17
|
+
cycode/cli/apps/ai_guardrails/ides/copilot.py,sha256=rn473Bq96DMFgZUNX9gnscp8DUbsNO8Kz4y4O2tr7hE,28307
|
|
18
18
|
cycode/cli/apps/ai_guardrails/ides/cursor.py,sha256=Ulr_Jq1FivtZtp5tGanmZUZXmvRLC-hUuZzXrfYbXbU,7759
|
|
19
19
|
cycode/cli/apps/ai_guardrails/install_command.py,sha256=u0v4okEHeIMnXWhqcfqUePLVrh90Lc8NwOxeoJic1IU,4053
|
|
20
20
|
cycode/cli/apps/ai_guardrails/scan/__init__.py,sha256=qJc82XiQGiAuc1sYY8Ij_A-qXpxgLPuayQq8xWlouMA,48
|
|
21
21
|
cycode/cli/apps/ai_guardrails/scan/consts.py,sha256=8H8JXlgm65sYkgTXqsBInHhHe80UPjqY4vumZXB4GGM,1060
|
|
22
22
|
cycode/cli/apps/ai_guardrails/scan/detach.py,sha256=8BRgBq9Qi8nXEx6NKlE8scSRPkO30XCfsiI5PLvq6Gk,2700
|
|
23
23
|
cycode/cli/apps/ai_guardrails/scan/guardrail_config.py,sha256=cU5DqsPvt_dejkiDhbN7ve--1LlT-VuQvLv70kWUtJs,7911
|
|
24
|
-
cycode/cli/apps/ai_guardrails/scan/handlers.py,sha256=
|
|
24
|
+
cycode/cli/apps/ai_guardrails/scan/handlers.py,sha256=P_stqp2abf-nyhgM7Mn3Xfh2nxjBQfbzcOFPzIWNyTc,24140
|
|
25
25
|
cycode/cli/apps/ai_guardrails/scan/mcp_server_status.py,sha256=44wij2VtjsB7cffxEnEBqQ5RInmzLROwOC0VwtDRl4s,4355
|
|
26
|
-
cycode/cli/apps/ai_guardrails/scan/payload.py,sha256=
|
|
26
|
+
cycode/cli/apps/ai_guardrails/scan/payload.py,sha256=Ntwn6f71VsZxgztPoa4UN9pJvp9KnP4ctN1qobY7QaY,1881
|
|
27
27
|
cycode/cli/apps/ai_guardrails/scan/policy.py,sha256=nqLjWqNty-p4pk4mSCyy7EfqavUNCdP3nUSkKC7QRMY,4984
|
|
28
|
-
cycode/cli/apps/ai_guardrails/scan/
|
|
28
|
+
cycode/cli/apps/ai_guardrails/scan/prompt_images.py,sha256=JRRmiuSqWYkgsh38d1lCiL0pgbGIYYOafZ7R5YTDYwM,7405
|
|
29
|
+
cycode/cli/apps/ai_guardrails/scan/scan_command.py,sha256=zMqurztyEJMB_-93xlBDBzAWB91MXXnF-4KKVJs0RNk,9115
|
|
29
30
|
cycode/cli/apps/ai_guardrails/scan/types.py,sha256=6nh_40KSTuWabsaVqkZEl712m6lAI8k9OuhPo8KhJdw,1553
|
|
30
|
-
cycode/cli/apps/ai_guardrails/scan/utils.py,sha256=
|
|
31
|
+
cycode/cli/apps/ai_guardrails/scan/utils.py,sha256=YiiajYpaUHg9eBevY6oG7chU5u_rZTDrESR-gfLKIrc,6844
|
|
31
32
|
cycode/cli/apps/ai_guardrails/session_start_command.py,sha256=1TsTK_SY6dp-iILCIqzxVFV0oHFtyyrg6fDIOV96stQ,8313
|
|
32
33
|
cycode/cli/apps/ai_guardrails/status_command.py,sha256=OXWnGhFwt4zILbtGHWnB6Bh-Z3OhcgKDGQW6e-7QyHU,3190
|
|
33
34
|
cycode/cli/apps/ai_guardrails/uninstall_command.py,sha256=po-Uh-U5itNOPPAG7wAfBLEB85DvZX1VMUVS-pgHX64,2685
|
|
@@ -114,7 +115,7 @@ cycode/cli/files_collector/file_excluder.py,sha256=atua_L2qDbmhFXj4nB6rDqSn5--Mu
|
|
|
114
115
|
cycode/cli/files_collector/iac/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
115
116
|
cycode/cli/files_collector/iac/tf_content_generator.py,sha256=a65zA0Ejv_LSA5jac2omHck4IKoNS5MX6v6ltF2wo4E,2873
|
|
116
117
|
cycode/cli/files_collector/models/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
117
|
-
cycode/cli/files_collector/models/in_memory_zip.py,sha256=
|
|
118
|
+
cycode/cli/files_collector/models/in_memory_zip.py,sha256=Tm3ipKh2vHpSt2igEMqMY0aeLsyc2L1mgccyJLHL824,4396
|
|
118
119
|
cycode/cli/files_collector/path_documents.py,sha256=7oNLcFZFHC_3sO34iD9FaKdS6_0lCogAl-nh11ejT_w,5040
|
|
119
120
|
cycode/cli/files_collector/repository_documents.py,sha256=7v15zzgjQW2pVsE7Xsny4FiUGyjbrVvhwFn5SU2YyHo,834
|
|
120
121
|
cycode/cli/files_collector/sca/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
@@ -122,7 +123,7 @@ cycode/cli/files_collector/sca/base_restore_dependencies.py,sha256=8wMKoh15CYLcm
|
|
|
122
123
|
cycode/cli/files_collector/sca/go/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
123
124
|
cycode/cli/files_collector/sca/go/restore_go_dependencies.py,sha256=_i4UBfhQ97Z14OYxVj5iUuckMSiVtbw-vYCBOowIHKQ,1868
|
|
124
125
|
cycode/cli/files_collector/sca/maven/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
125
|
-
cycode/cli/files_collector/sca/maven/restore_gradle_dependencies.py,sha256=
|
|
126
|
+
cycode/cli/files_collector/sca/maven/restore_gradle_dependencies.py,sha256=Gf7KO3VTwVfmUgkhYFDjIT8bTUmA_KdHrvE5n729XmI,5848
|
|
126
127
|
cycode/cli/files_collector/sca/maven/restore_maven_dependencies.py,sha256=zaXirOpVDMiZRUVjQzrHoLBfUpeAdP3ol_whNBbXkCY,3966
|
|
127
128
|
cycode/cli/files_collector/sca/npm/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
128
129
|
cycode/cli/files_collector/sca/npm/restore_bun_dependencies.py,sha256=r5MdGsezSRNeBMhGwxF1sPUMGr27SrQQC72-W0Aokz8,4817
|
|
@@ -154,7 +155,7 @@ cycode/cli/files_collector/walk_ignore.py,sha256=nvOM6oDmT2SxSI4pU-bLlc9LwTgkfTd
|
|
|
154
155
|
cycode/cli/files_collector/zip_documents.py,sha256=AJI-K9-ub2nsvgvYhi5bm21sQL7gmB0bzJpmm6GFWhg,1821
|
|
155
156
|
cycode/cli/logger.py,sha256=mlaYEQGYd582fTCc3SC3cFMj0PKTB6EsaI12Q4VL1z8,65
|
|
156
157
|
cycode/cli/main.py,sha256=QTPqIZsJsNK_vun8---vP2jP4ljlNJ15xidNrQ-Y0Rc,316
|
|
157
|
-
cycode/cli/models.py,sha256=
|
|
158
|
+
cycode/cli/models.py,sha256=tYee-v5zmtp2Zg-GX314niwv-sQuRqUlUYyID9zAfP4,2404
|
|
158
159
|
cycode/cli/printers/__init__.py,sha256=ALwAXSZy2lNXWC3NfCIxf8K0F6eFrbZa9PLZwPINi5E,93
|
|
159
160
|
cycode/cli/printers/console_printer.py,sha256=kCSmfWwp8OBMBBRA-0lZu4mHt1GXAkHpljOsMZTInVQ,6107
|
|
160
161
|
cycode/cli/printers/json_printer.py,sha256=nOwVH10h-W5z9Xz6ZPSEj9DMDby9bzpZm-q1TvEgKEk,2434
|
|
@@ -192,7 +193,7 @@ cycode/cli/utils/ignore_utils.py,sha256=lP77cIvf1XiNp5nWbpvCGHIjw6UH6dKyhCdW6COD
|
|
|
192
193
|
cycode/cli/utils/jwt_utils.py,sha256=QzeUWgRCoIuUou6qqOlJUxiZGBOubq5OEbcfNr70NwQ,780
|
|
193
194
|
cycode/cli/utils/path_utils.py,sha256=rKnImKJQhwC4lGOQkeRYZaldvuIUvVGjYAgiiQV2b6I,6468
|
|
194
195
|
cycode/cli/utils/progress_bar.py,sha256=RC6x9tPFrfdu4fVU69r_rruSU1zDRVilUmJcNOULt2E,9509
|
|
195
|
-
cycode/cli/utils/scan_batch.py,sha256=
|
|
196
|
+
cycode/cli/utils/scan_batch.py,sha256=6mVGsIV94jxBC-ySQgziHUTdvmLPtT8TaN38XwpoFy8,5289
|
|
196
197
|
cycode/cli/utils/scan_utils.py,sha256=C9f3lE0_H34SXHfr7rG-8wo1SB0MRNLqbB98Vn0Ee1s,1246
|
|
197
198
|
cycode/cli/utils/shell_executor.py,sha256=vzdzDev3in2nsPRnDoOzbZFbQYvCqIkMfMhG4OuUs6A,1801
|
|
198
199
|
cycode/cli/utils/string_utils.py,sha256=KyPSAHDRPEGNCCcKTF0v99vad5z9djpVGc8nxpBqdYo,2445
|
|
@@ -224,8 +225,8 @@ cycode/cyclient/report_client.py,sha256=PaKEo6Q0GFVdpNC18vvR4uBoUX1MnllVmKkS72eA
|
|
|
224
225
|
cycode/cyclient/scan_client.py,sha256=ft80sGTsW-BW4bECuGdfLv0CrSdIkp_RLlGfwHVf_Fs,17325
|
|
225
226
|
cycode/cyclient/scan_config_base.py,sha256=mXsPZGYCtp85rv5GIige40yQZXuRcEKUW-VQJ0vgFzk,1201
|
|
226
227
|
cycode/logger.py,sha256=OHmfkf4dnyZgfixGqkWf3js3uysrOXU_4cS8TChtAzc,2079
|
|
227
|
-
cycode-3.27.
|
|
228
|
-
cycode-3.27.
|
|
229
|
-
cycode-3.27.
|
|
230
|
-
cycode-3.27.
|
|
231
|
-
cycode-3.27.
|
|
228
|
+
cycode-3.27.2.dev1.dist-info/METADATA,sha256=ufPksJ-IxEiUMREaKpBvnFQ9M3dizSdPlczg0FRnljs,97123
|
|
229
|
+
cycode-3.27.2.dev1.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
|
|
230
|
+
cycode-3.27.2.dev1.dist-info/entry_points.txt,sha256=iDcVJM8ByLElVgvBgtYxDjw1kT7O8Mo0LcWZIT5L3Ig,45
|
|
231
|
+
cycode-3.27.2.dev1.dist-info/licenses/LICENCE,sha256=2Wx4N6mD_4xB7-E3hPkZ3MPhpJy__k_I8MaCSO-PDRo,1068
|
|
232
|
+
cycode-3.27.2.dev1.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|