|
3 | 3 | import re |
4 | 4 | from typing import Any, Dict, List, Sequence, Set |
5 | 5 |
|
6 | | -from ggshield.verticals.ai.agents import Claude, Copilot, Cursor |
| 6 | +from notifypy import Notify |
7 | 7 |
|
8 | | -from .models import Agent, EventType, HookPayload, Tool |
| 8 | +from ggshield.core.filter import censor_match |
| 9 | +from ggshield.core.scan import ScannerProtocol |
| 10 | +from ggshield.core.scan import SecretProtocol as Secret |
| 11 | +from ggshield.core.scanner_ui import create_message_only_scanner_ui |
| 12 | +from ggshield.core.text_utils import pluralize, translate_validity |
| 13 | + |
| 14 | +from .agents import Claude, Copilot, Cursor |
| 15 | +from .models import Agent, EventType, HookPayload, HookResult, Tool |
9 | 16 |
|
10 | 17 |
|
11 | 18 | HOOK_NAME_TO_EVENT_TYPE = { |
@@ -163,3 +170,168 @@ def _parse_user_prompt( |
163 | 170 | ) |
164 | 171 | ) |
165 | 172 | return payloads |
| 173 | + |
| 174 | + |
| 175 | +class AIHookScanner: |
| 176 | + """AI hook scanner. |
| 177 | +
|
| 178 | + It is called with the payload of a hook event. |
| 179 | + Note that instead of having a base class with common method and a subclass per supported AI tool, |
| 180 | + we instead have a single class which detects which protocol to use. |
| 181 | + This is because some tools sloppily support hooks from others. For instance, |
| 182 | + Cursor will call hooks defined in the Claude Code format, but send payload in its own format. |
| 183 | + So we can't assume which tool will call us based on the command line/hook configuration only. |
| 184 | +
|
| 185 | + Raises: |
| 186 | + ValueError: If the input is not valid. |
| 187 | + """ |
| 188 | + |
| 189 | + def __init__(self, scanner: ScannerProtocol): |
| 190 | + self.scanner = scanner |
| 191 | + |
| 192 | + def scan(self, content: str) -> int: |
| 193 | + """Scan the content, print the result and return the exit code.""" |
| 194 | + |
| 195 | + payloads = parse_hook_input(content) |
| 196 | + result = self._scan_payloads(payloads) |
| 197 | + payload = result.payload |
| 198 | + |
| 199 | + # Special case: in post-tool use, the action is already done: at least notify the user |
| 200 | + if result.block and payload.event_type == EventType.POST_TOOL_USE: |
| 201 | + self._send_secret_notification( |
| 202 | + result.nbr_secrets, |
| 203 | + payload.tool or Tool.OTHER, |
| 204 | + payload.agent.display_name, |
| 205 | + ) |
| 206 | + |
| 207 | + return payload.agent.output_result(result) |
| 208 | + |
| 209 | + def _scan_payloads(self, payloads: List[HookPayload]) -> HookResult: |
| 210 | + """Scan payloads for secrets using the SecretScanner. |
| 211 | +
|
| 212 | + Returns: |
| 213 | + The result of the first blocking payload, or a non-blocking result. |
| 214 | + Raises a ValueError if the list is empty (we must have at least one to emit a result). |
| 215 | + """ |
| 216 | + if not payloads: |
| 217 | + raise ValueError("Error: no payloads to scan") |
| 218 | + for payload in payloads: |
| 219 | + result = self._scan_content(payload) |
| 220 | + if result.block: |
| 221 | + return result |
| 222 | + return HookResult.allow(payloads[0]) |
| 223 | + |
| 224 | + def _scan_content( |
| 225 | + self, |
| 226 | + payload: HookPayload, |
| 227 | + ) -> HookResult: |
| 228 | + """Scan content for secrets using the SecretScanner.""" |
| 229 | + # Short path: if there is no content, no need to do an API call |
| 230 | + if payload.empty: |
| 231 | + return HookResult.allow(payload) |
| 232 | + |
| 233 | + with create_message_only_scanner_ui() as scanner_ui: |
| 234 | + results = self.scanner.scan([payload.scannable], scanner_ui=scanner_ui) |
| 235 | + # Collect all secrets from results |
| 236 | + secrets: List[Secret] = [] |
| 237 | + for result in results.results: |
| 238 | + secrets.extend(result.secrets) |
| 239 | + |
| 240 | + if not secrets: |
| 241 | + return HookResult.allow(payload) |
| 242 | + |
| 243 | + message = self._message_from_secrets( |
| 244 | + secrets, |
| 245 | + payload, |
| 246 | + escape_markdown=True, |
| 247 | + ) |
| 248 | + return HookResult( |
| 249 | + block=True, |
| 250 | + message=message, |
| 251 | + nbr_secrets=len(secrets), |
| 252 | + payload=payload, |
| 253 | + ) |
| 254 | + |
| 255 | + @staticmethod |
| 256 | + def _message_from_secrets( |
| 257 | + secrets: List[Secret], |
| 258 | + payload: HookPayload, |
| 259 | + escape_markdown: bool = False, |
| 260 | + ) -> str: |
| 261 | + """ |
| 262 | + Format detected secrets into a user-friendly message. |
| 263 | +
|
| 264 | + Args: |
| 265 | + secrets: List of detected secrets |
| 266 | + payload: Text to display after the secrets output |
| 267 | + escape_markdown: If True, escape asterisks to prevent markdown interpretation |
| 268 | +
|
| 269 | + Returns: |
| 270 | + Formatted message describing the detected secrets |
| 271 | + """ |
| 272 | + count = len(secrets) |
| 273 | + header = f"**🚨 Detected {count} {pluralize('secret', count)} 🚨**" |
| 274 | + |
| 275 | + secret_lines = [] |
| 276 | + for secret in secrets: |
| 277 | + validity = translate_validity(secret.validity).lower() |
| 278 | + if validity == "valid": |
| 279 | + validity = f"**{validity}**" |
| 280 | + match_str = ", ".join(censor_match(m) for m in secret.matches) |
| 281 | + if escape_markdown: |
| 282 | + match_str = match_str.replace("*", "•") |
| 283 | + secret_lines.append( |
| 284 | + f" - {secret.detector_display_name} ({validity}): {match_str}" |
| 285 | + ) |
| 286 | + |
| 287 | + if payload.tool == Tool.BASH: |
| 288 | + if payload.event_type == EventType.POST_TOOL_USE: |
| 289 | + message = "Secrets detected in the command output." |
| 290 | + else: |
| 291 | + message = ( |
| 292 | + "Please remove the secrets from the command before executing it. " |
| 293 | + "Consider using environment variables or a secrets manager instead." |
| 294 | + ) |
| 295 | + elif payload.tool == Tool.READ: |
| 296 | + message = f"Please remove the secrets from {payload.identifier} before reading it." |
| 297 | + elif payload.event_type == EventType.USER_PROMPT: |
| 298 | + message = "Please remove the secrets from your prompt before submitting." |
| 299 | + else: |
| 300 | + message = ( |
| 301 | + "Please remove the secrets from the tool input before executing. " |
| 302 | + "Consider using environment variables or a secrets manager instead." |
| 303 | + ) |
| 304 | + |
| 305 | + secrets_block = "\n".join(secret_lines) |
| 306 | + return f"{header}\n{secrets_block}\n\n{message}" |
| 307 | + |
| 308 | + @staticmethod |
| 309 | + def _send_secret_notification( |
| 310 | + nbr_secrets: int, tool: Tool, agent_name: str |
| 311 | + ) -> None: |
| 312 | + """ |
| 313 | + Send desktop notification when secrets are detected. |
| 314 | +
|
| 315 | + Args: |
| 316 | + nbr_secrets: Number of detected secrets |
| 317 | + tool: Tool used to detect the secrets |
| 318 | + agent_name: Name of the agent that detected the secrets |
| 319 | + """ |
| 320 | + source = "using a tool" |
| 321 | + if tool == Tool.READ: |
| 322 | + source = "reading a file" |
| 323 | + elif tool == Tool.BASH: |
| 324 | + source = "running a command" |
| 325 | + notification = Notify() |
| 326 | + notification.title = "ggshield - Secrets Detected" |
| 327 | + notification.message = ( |
| 328 | + f"{agent_name} got access to {nbr_secrets}" |
| 329 | + f" {pluralize('secret', nbr_secrets)} by {source}" |
| 330 | + ) |
| 331 | + notification.application_name = "ggshield" |
| 332 | + try: |
| 333 | + notification.send() |
| 334 | + except Exception: |
| 335 | + # This is best effort, we don't want to propagate an error |
| 336 | + # if the notification fails. |
| 337 | + pass |
0 commit comments