patchops-guard 0.2.0__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.
@@ -0,0 +1,461 @@
1
+ """`patchops scan ...` — manifest / website / docker / auto."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from enum import Enum
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import typer
10
+
11
+ from patchops_cli import config as cfg_mod
12
+ from patchops_cli.client import APIError, PatchOpsCLIClient
13
+ from patchops_cli.formatters.json_fmt import write_json_output
14
+ from patchops_cli.formatters.sarif import (
15
+ docker_to_sarif,
16
+ manifest_to_sarif,
17
+ website_to_sarif,
18
+ write_sarif_output,
19
+ )
20
+ from patchops_cli.formatters.table import (
21
+ render_auto_scan,
22
+ render_docker_scan,
23
+ render_manifest_scan,
24
+ render_website_scan,
25
+ )
26
+ from patchops_cli.formatters.tree import render_markdown, render_tree
27
+ from patchops_cli.utils.errors import (
28
+ EXIT_USAGE,
29
+ fail,
30
+ meets_threshold,
31
+ severity_exit_code,
32
+ )
33
+
34
+ app = typer.Typer(help="Scan a manifest file, website, or container image.")
35
+
36
+
37
+ class _Format(str, Enum):
38
+ json = "json"
39
+ table = "table"
40
+ sarif = "sarif"
41
+ tree = "tree"
42
+ markdown = "markdown"
43
+
44
+
45
+ class _Severity(str, Enum):
46
+ low = "low"
47
+ medium = "medium"
48
+ high = "high"
49
+ critical = "critical"
50
+
51
+
52
+ _LOCKFILE_NAMES = {
53
+ "package.json",
54
+ "package-lock.json",
55
+ "yarn.lock",
56
+ "requirements.txt",
57
+ "pipfile.lock",
58
+ "poetry.lock",
59
+ "pom.xml",
60
+ "go.mod",
61
+ "go.sum",
62
+ "gemfile.lock",
63
+ "cargo.lock",
64
+ "composer.lock",
65
+ "packages.lock.json",
66
+ "package.resolved",
67
+ "pubspec.lock",
68
+ }
69
+
70
+
71
+ def _tool_version() -> str:
72
+ try:
73
+ from patchops_cli import __version__
74
+
75
+ return __version__
76
+ except Exception:
77
+ return "0.0.0"
78
+
79
+
80
+ def _require_auth() -> PatchOpsCLIClient:
81
+ cfg = cfg_mod.load()
82
+ if not cfg.is_authenticated():
83
+ # Scans against the public endpoints don't strictly need auth,
84
+ # but anon scans carry the guest rate limit (3/day). Warn and
85
+ # continue — the server will 429 if the budget is gone.
86
+ pass
87
+ return PatchOpsCLIClient(cfg, timeout=120.0)
88
+
89
+
90
+ def _collect_website_severities(data: dict[str, Any]) -> list[str]:
91
+ out: list[str] = []
92
+ for lib in data.get("libraries") or []:
93
+ for cve in lib.get("cves") or []:
94
+ out.append((cve.get("severity") or "unknown").lower())
95
+ if data.get("secrets_found"):
96
+ out.append("high") # exposed secrets are always at least high
97
+ # 2026-11-24: URL Scan Flash(v6) 결과 — 84 점검 실패 + AI 공격 단계. 예전엔 옛 빠른 검사 형식만 봐서
98
+ # `url-scan run --fail-on-severity` 가 실제 결과와 무관하게 늘 통과했다 (CI 게이트가 조용히 꺼짐)
99
+ for chk in data.get("url_84_failed") or []:
100
+ out.append((chk.get("severity") or "unknown").lower())
101
+ for step in (data.get("llm_scan") or {}).get("steps") or []:
102
+ out.append((step.get("severity") or "unknown").lower())
103
+ return out
104
+
105
+
106
+ def _collect_manifest_severities(data: dict[str, Any]) -> list[str]:
107
+ out: list[str] = []
108
+ for pkg in data.get("top_vulnerable") or []:
109
+ for cve in pkg.get("cves") or []:
110
+ out.append((cve.get("severity") or "unknown").lower())
111
+ # 2026-11-25: 서버가 화면 목록 밖(상위 10개 이후) 패키지까지 포함한 최고 심각도를 준다.
112
+ # 예전엔 응답에 심각도가 없어 --fail-on-severity 가 늘 통과했다.
113
+ if data.get("max_severity"):
114
+ out.append(str(data["max_severity"]).lower())
115
+ return out
116
+
117
+
118
+ def _collect_docker_severities(data: dict[str, Any]) -> list[str]:
119
+ return [
120
+ (v.get("severity") or "unknown").lower()
121
+ for v in (data.get("vulns") or [])
122
+ ]
123
+
124
+
125
+ def _filter_by_severity(severities: list[str], filt: str | None) -> list[str]:
126
+ if not filt:
127
+ return severities
128
+ return [s for s in severities if meets_threshold(s, filt)]
129
+
130
+
131
+ def _handle_output_and_threshold(
132
+ data: dict[str, Any],
133
+ *,
134
+ fmt: _Format,
135
+ output: Path | None,
136
+ severities: list[str],
137
+ severity_filter: str | None,
138
+ fail_on: str | None,
139
+ render_table, # callable
140
+ to_sarif, # callable(data, version) -> dict
141
+ ) -> None:
142
+ severities = _filter_by_severity(severities, severity_filter)
143
+
144
+ if fmt is _Format.json:
145
+ write_json_output(data, output)
146
+ elif fmt is _Format.sarif:
147
+ doc = to_sarif(data, _tool_version())
148
+ write_sarif_output(doc, output)
149
+ else:
150
+ if output is not None:
151
+ # Table mode + --output writes the rich-less JSON dump of
152
+ # the same payload so the file is still machine-readable.
153
+ write_json_output(data, output)
154
+ render_table(data)
155
+
156
+ if fail_on:
157
+ worst = max(severities, default=None, key=lambda s: {
158
+ "critical": 4, "high": 3, "medium": 2, "low": 1
159
+ }.get(s, 0))
160
+ if worst and meets_threshold(worst, fail_on):
161
+ raise typer.Exit(code=severity_exit_code(worst))
162
+
163
+
164
+ # ----------------------------------------------------------------- subcommands
165
+
166
+
167
+ @app.command("manifest")
168
+ def scan_manifest(
169
+ path: Path = typer.Argument(
170
+ ..., exists=True, file_okay=True, dir_okay=False, readable=True,
171
+ help="Lockfile to scan (package-lock.json, requirements.txt, ...).",
172
+ ),
173
+ fmt: _Format = typer.Option(_Format.table, "--format", help="Output format."),
174
+ output: Path | None = typer.Option(None, "--output", help="Write result to file."),
175
+ severity: _Severity | None = typer.Option(
176
+ None, "--severity", help="Filter findings at or above this severity."
177
+ ),
178
+ fail_on: _Severity | None = typer.Option(
179
+ None, "--fail-on-severity", help="Exit non-zero if a finding meets this severity.",
180
+ ),
181
+ ) -> None:
182
+ """Scan a dependency lockfile for known CVEs."""
183
+ if path.name.lower() not in _LOCKFILE_NAMES and path.suffix.lower() not in {
184
+ ".json", ".txt", ".xml", ".mod", ".sum", ".lock", ".resolved"
185
+ }:
186
+ raise fail(
187
+ f"unsupported lockfile: {path.name}. "
188
+ "Supported: package-lock.json, requirements.txt, Pipfile.lock, "
189
+ "pom.xml, go.mod, Gemfile.lock, Cargo.lock, composer.lock.",
190
+ exit_code=EXIT_USAGE,
191
+ )
192
+ try:
193
+ with _require_auth() as client:
194
+ data = client.scan_manifest(path)
195
+ except APIError as exc:
196
+ raise fail(f"scan failed ({exc.status}): {exc.message}")
197
+
198
+ _handle_output_and_threshold(
199
+ data,
200
+ fmt=fmt,
201
+ output=output,
202
+ severities=_collect_manifest_severities(data),
203
+ severity_filter=severity.value if severity else None,
204
+ fail_on=fail_on.value if fail_on else None,
205
+ render_table=render_manifest_scan,
206
+ to_sarif=manifest_to_sarif,
207
+ )
208
+
209
+
210
+ _URL_RE = re.compile(r"^https?://", re.IGNORECASE)
211
+
212
+
213
+ @app.command("website")
214
+ def scan_website(
215
+ url: str = typer.Argument(..., help="URL to scan (https://example.com)."),
216
+ fmt: _Format = typer.Option(_Format.table, "--format"),
217
+ output: Path | None = typer.Option(None, "--output"),
218
+ severity: _Severity | None = typer.Option(None, "--severity"),
219
+ fail_on: _Severity | None = typer.Option(None, "--fail-on-severity"),
220
+ attack_chain: bool = typer.Option(
221
+ False,
222
+ "--attack-chain",
223
+ help="Print the attacker-perspective exploit chain after the summary.",
224
+ ),
225
+ ) -> None:
226
+ """Scan a live website (headers + JS bundles + TLS + secrets)."""
227
+ if not _URL_RE.match(url):
228
+ url = f"https://{url}"
229
+ try:
230
+ with _require_auth() as client:
231
+ data = client.scan_website(url)
232
+ except APIError as exc:
233
+ raise fail(f"scan failed ({exc.status}): {exc.message}")
234
+
235
+ _handle_output_and_threshold(
236
+ data,
237
+ fmt=fmt,
238
+ output=output,
239
+ severities=_collect_website_severities(data),
240
+ severity_filter=severity.value if severity else None,
241
+ fail_on=fail_on.value if fail_on else None,
242
+ render_table=render_website_scan,
243
+ to_sarif=website_to_sarif,
244
+ )
245
+
246
+ if attack_chain:
247
+ chain = (data.get("results") or {}).get("attack_chain") or {}
248
+ _render_attack_chain(chain)
249
+
250
+
251
+ def _render_attack_chain(chain: dict) -> None:
252
+ """Pretty-print an attacker-perspective exploit chain on stdout."""
253
+ if not chain or not chain.get("steps"):
254
+ typer.echo("")
255
+ typer.echo(typer.style(
256
+ "[attack-chain] no steps available (chain builder returned empty)",
257
+ fg=typer.colors.YELLOW,
258
+ ))
259
+ return
260
+ title = chain.get("title", "Attacker simulation")
261
+ sev = str(chain.get("severity", "info")).upper()
262
+ ttx = chain.get("time_to_exploit_minutes")
263
+ typer.echo("")
264
+ typer.echo(typer.style(f"═ {title} · {sev}", fg=typer.colors.MAGENTA, bold=True))
265
+ if ttx:
266
+ typer.echo(typer.style(
267
+ f" time to first probe: ~{ttx} min", fg=typer.colors.RED,
268
+ ))
269
+ phases = {"recon": "🔎 RECON", "probe": "🧪 PROBE", "exploit": "💥 EXPLOIT", "post": "🕳️ POST"}
270
+ for step in chain.get("steps", []):
271
+ phase = step.get("phase", "")
272
+ header = phases.get(phase, phase.upper())
273
+ blocked = step.get("blocked_by_patchguard")
274
+ head_style = {"fg": typer.colors.GREEN} if blocked else {"fg": typer.colors.WHITE, "bold": True}
275
+ typer.echo("")
276
+ typer.echo(typer.style(f" {header} · {step.get('headline','')}", **head_style))
277
+ if blocked:
278
+ typer.echo(typer.style(" ✓ BLOCKED by Patchguard", fg=typer.colors.GREEN))
279
+ narration = step.get("narration", "").strip()
280
+ if narration:
281
+ typer.echo(f" {narration}")
282
+ payload = step.get("payload")
283
+ if payload:
284
+ typer.echo(typer.style(f" payload: {payload}", fg=typer.colors.YELLOW))
285
+ snippet = step.get("snippet", "")
286
+ if snippet:
287
+ typer.echo(typer.style(" snippet:", fg=typer.colors.BLUE))
288
+ for line in snippet.splitlines():
289
+ typer.echo(f" {line}")
290
+ blast = step.get("blast_radius")
291
+ if blast:
292
+ typer.echo(typer.style(f" blast radius: {blast}", fg=typer.colors.RED))
293
+ note = chain.get("audience_note")
294
+ if note:
295
+ typer.echo("")
296
+ typer.echo(typer.style(f" {note}", fg=typer.colors.CYAN))
297
+
298
+
299
+ _DOCKER_RE = re.compile(
300
+ r"^[a-z0-9]+(?:[._\-/][a-z0-9]+)*(?::[a-zA-Z0-9._\-]+)?(?:@sha256:[a-f0-9]{64})?$"
301
+ )
302
+
303
+
304
+ @app.command("docker")
305
+ def scan_docker(
306
+ image: str = typer.Argument(..., help="Docker image (e.g. nginx:1.25)."),
307
+ fmt: _Format = typer.Option(_Format.table, "--format"),
308
+ output: Path | None = typer.Option(None, "--output"),
309
+ severity: _Severity | None = typer.Option(None, "--severity"),
310
+ fail_on: _Severity | None = typer.Option(None, "--fail-on-severity"),
311
+ ) -> None:
312
+ """Scan a Docker image with Trivy (critical + high by default)."""
313
+ if not _DOCKER_RE.match(image):
314
+ raise fail(f"invalid docker image name: {image}", exit_code=EXIT_USAGE)
315
+ try:
316
+ with _require_auth() as client:
317
+ data = client.scan_docker(image)
318
+ except APIError as exc:
319
+ raise fail(f"scan failed ({exc.status}): {exc.message}")
320
+
321
+ _handle_output_and_threshold(
322
+ data,
323
+ fmt=fmt,
324
+ output=output,
325
+ severities=_collect_docker_severities(data),
326
+ severity_filter=severity.value if severity else None,
327
+ fail_on=fail_on.value if fail_on else None,
328
+ render_table=render_docker_scan,
329
+ to_sarif=docker_to_sarif,
330
+ )
331
+
332
+
333
+ def _looks_like_url(target: str) -> bool:
334
+ return bool(_URL_RE.match(target)) or bool(
335
+ re.match(r"^[a-zA-Z0-9]([a-zA-Z0-9-]*\.)+[a-zA-Z]{2,}", target)
336
+ )
337
+
338
+
339
+ def _looks_like_docker(target: str) -> bool:
340
+ return bool(_DOCKER_RE.match(target)) and ":" in target and "/" not in target.split(":")[0]
341
+
342
+
343
+ @app.command("auto")
344
+ def scan_auto(
345
+ target: str = typer.Argument(..., help="URL, lockfile path, docker image, or package@version."),
346
+ fmt: _Format = typer.Option(_Format.table, "--format"),
347
+ output: Path | None = typer.Option(None, "--output"),
348
+ severity: _Severity | None = typer.Option(None, "--severity"),
349
+ fail_on: _Severity | None = typer.Option(None, "--fail-on-severity"),
350
+ show_all: bool = typer.Option(False, "--all", help="Show medium/low/info findings too (tree mode)."),
351
+ watch: int = typer.Option(0, "--watch", help="Re-scan every N seconds (0=off). For tree mode."),
352
+ lang: str = typer.Option(
353
+ "en", "--lang",
354
+ help="Report language: 'en' (default) or 'ko'.",
355
+ ),
356
+ ) -> None:
357
+ """Auto-detect scan type from a single argument.
358
+
359
+ Dispatch rules:
360
+ - path exists on disk → manifest scan
361
+ - ``http(s)://...`` or domain-like → website scan
362
+ - ``image:tag`` → docker scan
363
+ - everything else → backend /scan/auto resolver
364
+ """
365
+ path = Path(target)
366
+ # tree/markdown 포맷은 server-side /scan/auto 응답 구조 (results.v6.url_84.failed_top)
367
+ # 가 필요. dispatch 우회하고 항상 server-side auto 호출.
368
+ if fmt not in (_Format.tree, _Format.markdown):
369
+ if path.exists() and path.is_file():
370
+ scan_manifest(path=path, fmt=fmt, output=output, severity=severity, fail_on=fail_on)
371
+ return
372
+
373
+ if _looks_like_url(target):
374
+ scan_website(
375
+ url=target, fmt=fmt, output=output, severity=severity, fail_on=fail_on
376
+ )
377
+ return
378
+
379
+ if _looks_like_docker(target):
380
+ scan_docker(
381
+ image=target, fmt=fmt, output=output, severity=severity, fail_on=fail_on
382
+ )
383
+ return
384
+
385
+ # Fall back to server-side auto-detect.
386
+ def _do_one() -> dict[str, Any]:
387
+ try:
388
+ with _require_auth() as client_:
389
+ return client_.scan_auto(target, lang=lang)
390
+ except APIError as exc_:
391
+ raise fail(f"scan failed ({exc_.status}): {exc_.message}") from None
392
+
393
+ data = _do_one()
394
+
395
+ if fmt is _Format.json:
396
+ write_json_output(data, output)
397
+ elif fmt is _Format.sarif:
398
+ # Server auto results are heterogeneous — flatten to SARIF per type.
399
+ detected = data.get("detected_type")
400
+ inner = data.get("results") or {}
401
+ if detected == "docker":
402
+ write_sarif_output(docker_to_sarif(inner, _tool_version()), output)
403
+ elif detected == "website" or detected == "git":
404
+ write_sarif_output(website_to_sarif(inner, _tool_version()), output)
405
+ else:
406
+ write_sarif_output(manifest_to_sarif(inner, _tool_version()), output)
407
+ elif fmt is _Format.tree:
408
+ render_tree(data, all_findings=show_all)
409
+ # --watch: same target 다시 스캔 (사용자 fix 적용 후 검증용)
410
+ if watch and watch > 0:
411
+ import time as _t
412
+ try:
413
+ while True:
414
+ _t.sleep(max(watch, 30)) # 최소 30s (rate limit 보호)
415
+ new_data = _do_one()
416
+ typer.echo("")
417
+ typer.echo(typer.style(f"--- re-scan after {watch}s ---", fg=typer.colors.MAGENTA))
418
+ render_tree(new_data, all_findings=show_all)
419
+ data = new_data
420
+ except KeyboardInterrupt:
421
+ typer.echo("")
422
+ typer.echo("watch stopped.")
423
+ elif fmt is _Format.markdown:
424
+ render_markdown(data)
425
+ else:
426
+ if output is not None:
427
+ write_json_output(data, output)
428
+ render_auto_scan(data)
429
+
430
+ # Threshold handling for auto — same max-severity logic as children.
431
+ severities: list[str] = []
432
+ detected = data.get("detected_type")
433
+ inner = data.get("results") or {}
434
+ if detected == "website" or detected == "git":
435
+ severities = _collect_website_severities(inner)
436
+ # 200+ URL checks 의 by_severity / failed_top 도 포함 (PASS-4)
437
+ v6 = (inner.get("v6") or {})
438
+ u84 = v6.get("url_84") or {}
439
+ for f in (u84.get("failed_top") or []):
440
+ sev_ = (f.get("severity") or "unknown").lower()
441
+ if sev_ in {"critical", "high", "medium", "low"}:
442
+ severities.append(sev_)
443
+ elif detected == "package":
444
+ severities = [
445
+ (v.get("severity") or "unknown").lower()
446
+ for v in (inner.get("vulns") or [])
447
+ ]
448
+ elif detected == "docker":
449
+ severities = _collect_docker_severities(inner)
450
+
451
+ if fail_on:
452
+ filtered = _filter_by_severity(severities, fail_on.value)
453
+ if filtered:
454
+ worst = max(
455
+ filtered,
456
+ key=lambda s: {"critical": 4, "high": 3, "medium": 2, "low": 1}.get(s, 0),
457
+ )
458
+ raise typer.Exit(code=severity_exit_code(worst))
459
+
460
+
461
+ __all__ = ["app"]
@@ -0,0 +1,111 @@
1
+ """``patchops url-scan`` — URL Scan Flash 1.0 (Pro tier live pentest).
2
+
3
+ Wraps the production URL Scan engine. CI-friendly: SARIF / JSON output
4
+ plus a ``--fail-on-severity`` threshold for pipeline gating.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from pathlib import Path
9
+
10
+ import typer
11
+
12
+ from patchops_cli import config as cfg_mod
13
+ from patchops_cli.client import APIError, PatchOpsCLIClient
14
+ from patchops_cli.commands.scan import (
15
+ _Format,
16
+ _Severity,
17
+ _collect_website_severities,
18
+ _filter_by_severity,
19
+ _tool_version,
20
+ )
21
+ from patchops_cli.formatters.json_fmt import write_json_output
22
+ from patchops_cli.formatters.sarif import website_to_sarif, write_sarif_output
23
+ from patchops_cli.formatters.table import render_url_scan, render_website_scan
24
+ from patchops_cli.utils.errors import (
25
+ EXIT_USAGE,
26
+ fail,
27
+ meets_threshold,
28
+ severity_exit_code,
29
+ )
30
+
31
+ app = typer.Typer(
32
+ help="URL Scan Flash 1.0 — live-site Pro pentest "
33
+ "(headers / TLS / JS bundle / secrets / AI exploit chains).",
34
+ )
35
+
36
+
37
+ def _client() -> PatchOpsCLIClient:
38
+ cfg = cfg_mod.load()
39
+ return PatchOpsCLIClient(cfg)
40
+
41
+
42
+ @app.command("run")
43
+ def url_scan_run(
44
+ url: str = typer.Argument(..., help="Target URL (https://...)."),
45
+ fmt: _Format = typer.Option(
46
+ _Format.table, "--format", help="Output format.",
47
+ ),
48
+ output: Path | None = typer.Option(
49
+ None, "--output", help="Write result to file.",
50
+ ),
51
+ severity: _Severity | None = typer.Option(
52
+ None, "--severity",
53
+ help="Filter findings at or above this severity.",
54
+ ),
55
+ fail_on: _Severity | None = typer.Option(
56
+ None, "--fail-on-severity",
57
+ help="Exit non-zero if any finding meets this severity.",
58
+ ),
59
+ wait: bool = typer.Option(
60
+ True, "--wait/--no-wait",
61
+ help="Poll until the scan reaches a terminal status (default). "
62
+ "--no-wait returns the scan_id immediately so the caller "
63
+ "can poll on their own.",
64
+ ),
65
+ ) -> None:
66
+ """Run URL Scan Flash 1.0 against a live URL."""
67
+ if not (url.startswith("http://") or url.startswith("https://")):
68
+ url = f"https://{url}"
69
+
70
+ client = _client()
71
+ try:
72
+ data = client.url_scan_pro(url, wait=wait)
73
+ except APIError as exc:
74
+ raise fail(
75
+ f"url-scan failed ({exc.status}): {exc.message}",
76
+ exit_code=EXIT_USAGE,
77
+ )
78
+
79
+ if not wait:
80
+ # Async mode: server is still working. Just emit the POST
81
+ # response (scan_id + pending status) so CI callers can poll.
82
+ write_json_output(data, output)
83
+ return
84
+
85
+ severities = _filter_by_severity(
86
+ _collect_website_severities(data),
87
+ severity.value if severity else None,
88
+ )
89
+
90
+ if fmt is _Format.json:
91
+ write_json_output(data, output)
92
+ elif fmt is _Format.sarif:
93
+ doc = website_to_sarif(data, _tool_version())
94
+ write_sarif_output(doc, output)
95
+ else:
96
+ if output is not None:
97
+ write_json_output(data, output)
98
+ if "url_84_failed" in data or "llm_scan" in data:
99
+ render_url_scan(data)
100
+ else:
101
+ render_website_scan(data)
102
+
103
+ if fail_on:
104
+ worst = max(severities, default=None, key=lambda s: {
105
+ "critical": 4, "high": 3, "medium": 2, "low": 1
106
+ }.get(s, 0))
107
+ if worst and meets_threshold(worst, fail_on.value):
108
+ raise typer.Exit(code=severity_exit_code(worst))
109
+
110
+
111
+ __all__ = ["app"]