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.
- patchops_cli/__init__.py +6 -0
- patchops_cli/__main__.py +9 -0
- patchops_cli/client.py +336 -0
- patchops_cli/commands/__init__.py +1 -0
- patchops_cli/commands/auth.py +100 -0
- patchops_cli/commands/findings.py +111 -0
- patchops_cli/commands/free_scan.py +167 -0
- patchops_cli/commands/mcp_audit.py +271 -0
- patchops_cli/commands/mcp_watch.py +248 -0
- patchops_cli/commands/repair.py +229 -0
- patchops_cli/commands/repo_scan.py +127 -0
- patchops_cli/commands/sbom.py +339 -0
- patchops_cli/commands/scan.py +461 -0
- patchops_cli/commands/url_scan.py +111 -0
- patchops_cli/commands/v6.py +138 -0
- patchops_cli/config.py +181 -0
- patchops_cli/formatters/__init__.py +16 -0
- patchops_cli/formatters/json_fmt.py +22 -0
- patchops_cli/formatters/sarif.py +252 -0
- patchops_cli/formatters/table.py +269 -0
- patchops_cli/formatters/tree.py +167 -0
- patchops_cli/legacy.py +150 -0
- patchops_cli/main.py +110 -0
- patchops_cli/mcp_remote.py +147 -0
- patchops_cli/utils/__init__.py +1 -0
- patchops_cli/utils/errors.py +75 -0
- patchops_guard-0.2.0.dist-info/METADATA +130 -0
- patchops_guard-0.2.0.dist-info/RECORD +31 -0
- patchops_guard-0.2.0.dist-info/WHEEL +5 -0
- patchops_guard-0.2.0.dist-info/entry_points.txt +2 -0
- patchops_guard-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""`patchops v6 ...` — Scanner v6 (4-Layer · 35 modules) CLI commands."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from enum import Enum
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import typer
|
|
8
|
+
|
|
9
|
+
from patchops_cli import config as cfg_mod
|
|
10
|
+
from patchops_cli.client import APIError, PatchOpsCLIClient
|
|
11
|
+
from patchops_cli.formatters.json_fmt import write_json_output
|
|
12
|
+
from patchops_cli.utils.errors import EXIT_USAGE, fail
|
|
13
|
+
|
|
14
|
+
app = typer.Typer(help="Scanner v6 — 4-Layer pipeline (35 modules).")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _client() -> PatchOpsCLIClient:
|
|
18
|
+
"""Build CLI client — health/benchmark 는 public 이라 auth 필요 없음."""
|
|
19
|
+
cfg = cfg_mod.load()
|
|
20
|
+
return PatchOpsCLIClient(cfg)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class _Fmt(str, Enum):
|
|
24
|
+
json = "json"
|
|
25
|
+
table = "table"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@app.command("health")
|
|
29
|
+
def health(
|
|
30
|
+
fmt: _Fmt = typer.Option(_Fmt.table, "--format", "-f"),
|
|
31
|
+
) -> None:
|
|
32
|
+
"""GET /api/v6/health — 35 모듈 상태 + 도구 가용성."""
|
|
33
|
+
client = _client()
|
|
34
|
+
try:
|
|
35
|
+
data = client.request("GET", "/v6/health")
|
|
36
|
+
except APIError as e:
|
|
37
|
+
fail(f"health failed: {e}", code=EXIT_USAGE)
|
|
38
|
+
return
|
|
39
|
+
|
|
40
|
+
if fmt == _Fmt.json:
|
|
41
|
+
write_json_output(data)
|
|
42
|
+
return
|
|
43
|
+
|
|
44
|
+
total = data.get("modules_total", 0)
|
|
45
|
+
ok = data.get("modules_importable", 0)
|
|
46
|
+
failed = data.get("failed_imports", []) or []
|
|
47
|
+
tools = data.get("tools", {}) or {}
|
|
48
|
+
tools_ok = sum(1 for v in tools.values() if v)
|
|
49
|
+
typer.echo(f"Modules: {ok}/{total} importable")
|
|
50
|
+
typer.echo(f"Tools: {tools_ok}/{len(tools)} installed")
|
|
51
|
+
if failed:
|
|
52
|
+
typer.secho(f"Failed: {', '.join(failed[:3])}", fg="red")
|
|
53
|
+
missing = [k for k, v in tools.items() if not v]
|
|
54
|
+
if missing:
|
|
55
|
+
typer.echo(f"Missing tools: {', '.join(missing[:5])}")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@app.command("scan")
|
|
59
|
+
def scan(
|
|
60
|
+
repo_path: Path = typer.Argument(..., exists=True, file_okay=False),
|
|
61
|
+
fmt: _Fmt = typer.Option(_Fmt.table, "--format", "-f"),
|
|
62
|
+
layer1: bool = typer.Option(True, "--layer1/--no-layer1"),
|
|
63
|
+
layer2: bool = typer.Option(True, "--layer2/--no-layer2"),
|
|
64
|
+
layer3: bool = typer.Option(True, "--layer3/--no-layer3"),
|
|
65
|
+
stage_e: bool = typer.Option(False, "--stage-e", help="heavy (MRVA/fuzz)"),
|
|
66
|
+
stage_f: bool = typer.Option(True, "--stage-f/--no-stage-f"),
|
|
67
|
+
stage_g: bool = typer.Option(True, "--stage-g/--no-stage-g"),
|
|
68
|
+
plan: str = typer.Option("", "--plan", help="(ignored by the server — /v6/scan always uses the stub LLM)"),
|
|
69
|
+
) -> None:
|
|
70
|
+
"""POST /api/v6/scan — full orchestrator on local repo.
|
|
71
|
+
|
|
72
|
+
Guest 1회 맛보기 + authenticated 무제한. 경로는 서버에 도달 가능해야.
|
|
73
|
+
"""
|
|
74
|
+
client = _client()
|
|
75
|
+
body = {
|
|
76
|
+
"repo_path": str(repo_path.absolute()),
|
|
77
|
+
"plan": plan,
|
|
78
|
+
"enable_layer1": layer1,
|
|
79
|
+
"enable_layer2": layer2,
|
|
80
|
+
"enable_layer3": layer3,
|
|
81
|
+
"enable_stage_e": stage_e,
|
|
82
|
+
"enable_stage_f": stage_f,
|
|
83
|
+
"enable_stage_g": stage_g,
|
|
84
|
+
}
|
|
85
|
+
try:
|
|
86
|
+
data = client.request("POST", "/v6/scan", json_body=body)
|
|
87
|
+
except APIError as e:
|
|
88
|
+
fail(f"scan failed: {e}", code=EXIT_USAGE)
|
|
89
|
+
return
|
|
90
|
+
|
|
91
|
+
if fmt == _Fmt.json:
|
|
92
|
+
write_json_output(data)
|
|
93
|
+
return
|
|
94
|
+
|
|
95
|
+
typer.echo(f"Layer 1 findings: {data.get('layer1_total', 0)}")
|
|
96
|
+
typer.echo(f"Layer 2 anti-pattern: {data.get('layer2_anti_pattern_count', 0)}")
|
|
97
|
+
typer.echo(f"Layer 2 git archeology:{data.get('layer2_git_arch_variants', 0)}")
|
|
98
|
+
typer.echo(f"Layer 3 variant hits: {data.get('layer3_variant_hits', 0)}")
|
|
99
|
+
typer.echo(f"Stage E MRVA: {data.get('stage_e_mrva_hits', 0)}")
|
|
100
|
+
typer.echo(f"Stage F findings: {len(data.get('stage_f_findings', []) or [])}")
|
|
101
|
+
typer.echo(f"Stage G toxic combos: {data.get('stage_g_toxic_combinations', 0)}")
|
|
102
|
+
typer.echo(f"Differential hits: {data.get('stage_g_differential_hits', 0)}")
|
|
103
|
+
routing = data.get("stage_g_routing_decisions", {}) or {}
|
|
104
|
+
if routing:
|
|
105
|
+
typer.echo(f"Routing: {dict(routing)}")
|
|
106
|
+
budget = data.get("budget", {}) or {}
|
|
107
|
+
if budget.get("allow_real_llm"):
|
|
108
|
+
typer.secho(
|
|
109
|
+
f"Real LLM active ({budget.get('remaining_cents', 0)}¢ remaining)",
|
|
110
|
+
fg="green",
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
@app.command("benchmark")
|
|
115
|
+
def benchmark(fmt: _Fmt = typer.Option(_Fmt.table, "--format", "-f")) -> None:
|
|
116
|
+
"""GET /api/v6/benchmark — public multi-fixture head-to-head."""
|
|
117
|
+
client = _client()
|
|
118
|
+
try:
|
|
119
|
+
data = client.request("GET", "/v6/benchmark")
|
|
120
|
+
except APIError as e:
|
|
121
|
+
fail(f"benchmark failed: {e}", code=EXIT_USAGE)
|
|
122
|
+
return
|
|
123
|
+
|
|
124
|
+
if fmt == _Fmt.json:
|
|
125
|
+
write_json_output(data)
|
|
126
|
+
return
|
|
127
|
+
|
|
128
|
+
if data.get("status") != "ok":
|
|
129
|
+
typer.echo(data.get("message", "not ok"))
|
|
130
|
+
return
|
|
131
|
+
|
|
132
|
+
agg = data.get("aggregate", {}) or {}
|
|
133
|
+
typer.echo(f"Fixtures scanned: {data.get('fixtures_scanned', 0)}")
|
|
134
|
+
typer.echo(f"v6 total: {agg.get('v6', 0)}")
|
|
135
|
+
typer.echo(f"semgrep: {agg.get('semgrep', 0)}")
|
|
136
|
+
typer.echo(f"trivy: {agg.get('trivy', 0)}")
|
|
137
|
+
typer.echo(f"v6 vs semgrep: +{agg.get('v6_beats_semgrep_by', 0)}")
|
|
138
|
+
typer.echo(f"v6 vs trivy: +{agg.get('v6_beats_trivy_by', 0)}")
|
patchops_cli/config.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""Config file persistence for the PatchOps CLI.
|
|
2
|
+
|
|
3
|
+
Stores the API key and base URL in a TOML file with permissions 0600:
|
|
4
|
+
|
|
5
|
+
- Linux / macOS: ``~/.config/patchops/config.toml``
|
|
6
|
+
- Windows: ``%APPDATA%\\patchops\\config.toml``
|
|
7
|
+
|
|
8
|
+
Environment variables still win — ``PATCHOPS_API_KEY`` and
|
|
9
|
+
``PATCHOPS_BASE_URL`` override the file when both are present. This
|
|
10
|
+
matches the behaviour of every other developer CLI (aws, gh, heroku)
|
|
11
|
+
and keeps CI runners usable without a login step.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
import stat
|
|
17
|
+
import sys
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
try:
|
|
23
|
+
import tomllib # Python 3.11+
|
|
24
|
+
except ModuleNotFoundError: # pragma: no cover — 3.10 fallback
|
|
25
|
+
import tomli as tomllib # type: ignore[import-not-found,no-redef]
|
|
26
|
+
|
|
27
|
+
import tomli_w
|
|
28
|
+
|
|
29
|
+
DEFAULT_BASE_URL = "https://patchguard.ai"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class Config:
|
|
34
|
+
"""Everything the CLI needs to talk to the backend."""
|
|
35
|
+
|
|
36
|
+
base_url: str = DEFAULT_BASE_URL
|
|
37
|
+
api_key: str | None = None
|
|
38
|
+
user_email: str | None = None
|
|
39
|
+
plan: str | None = None
|
|
40
|
+
|
|
41
|
+
def is_authenticated(self) -> bool:
|
|
42
|
+
return bool(self.api_key)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _is_windows() -> bool:
|
|
46
|
+
return sys.platform.startswith("win")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def config_dir() -> Path:
|
|
50
|
+
"""Platform-appropriate config directory.
|
|
51
|
+
|
|
52
|
+
Honours ``PATCHOPS_CONFIG_DIR`` so tests can point at a tmpdir without
|
|
53
|
+
race conditions.
|
|
54
|
+
"""
|
|
55
|
+
override = os.environ.get("PATCHOPS_CONFIG_DIR")
|
|
56
|
+
if override:
|
|
57
|
+
return Path(override)
|
|
58
|
+
if _is_windows():
|
|
59
|
+
base = os.environ.get("APPDATA") or str(Path.home() / "AppData" / "Roaming")
|
|
60
|
+
return Path(base) / "patchops"
|
|
61
|
+
xdg = os.environ.get("XDG_CONFIG_HOME")
|
|
62
|
+
if xdg:
|
|
63
|
+
return Path(xdg) / "patchops"
|
|
64
|
+
return Path.home() / ".config" / "patchops"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def config_path() -> Path:
|
|
68
|
+
return config_dir() / "config.toml"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def load() -> Config:
|
|
72
|
+
"""Read config from disk. Env vars override the file where set."""
|
|
73
|
+
data: dict[str, Any] = {}
|
|
74
|
+
path = config_path()
|
|
75
|
+
if path.exists():
|
|
76
|
+
try:
|
|
77
|
+
with path.open("rb") as fh:
|
|
78
|
+
data = tomllib.load(fh)
|
|
79
|
+
except (OSError, tomllib.TOMLDecodeError):
|
|
80
|
+
data = {}
|
|
81
|
+
|
|
82
|
+
cfg = Config(
|
|
83
|
+
base_url=str(data.get("base_url") or DEFAULT_BASE_URL),
|
|
84
|
+
api_key=data.get("api_key"),
|
|
85
|
+
user_email=data.get("user_email"),
|
|
86
|
+
plan=data.get("plan"),
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
env_key = os.environ.get("PATCHOPS_API_KEY")
|
|
90
|
+
env_url = os.environ.get("PATCHOPS_BASE_URL")
|
|
91
|
+
if env_key:
|
|
92
|
+
cfg.api_key = env_key
|
|
93
|
+
if env_url:
|
|
94
|
+
cfg.base_url = env_url
|
|
95
|
+
return cfg
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def save(cfg: Config) -> Path:
|
|
99
|
+
"""Persist config (API key) so only the current user can read it.
|
|
100
|
+
|
|
101
|
+
ISSUE-042 (2026-11-23): 예전엔 일반 umask 로 파일을 만든 **뒤** chmod 하고 실패도 무시했다.
|
|
102
|
+
- POSIX: 폴더 0700, 같은 폴더의 임시 파일을 처음부터 0600 으로 만들고(O_EXCL) 쓴 뒤 원자적으로 교체.
|
|
103
|
+
권한을 확보하지 못하면 저장 실패(OSError)로 끝낸다 — 키가 다른 사용자에게 읽히는 구간이 없다.
|
|
104
|
+
- Windows: 상속 ACL 은 PC 마다 다르다(다른 그룹에 수정 권한이 상속된 경우도 있음). 임시 파일에서 상속을 끊고
|
|
105
|
+
현재 사용자·SYSTEM 만 남긴 뒤(icacls) 내용을 쓰고 원자적으로 교체. icacls 실패도 저장 실패.
|
|
106
|
+
"""
|
|
107
|
+
path = config_path()
|
|
108
|
+
posix = not _is_windows()
|
|
109
|
+
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
110
|
+
if posix:
|
|
111
|
+
os.chmod(path.parent, stat.S_IRWXU)
|
|
112
|
+
payload: dict[str, Any] = {"base_url": cfg.base_url}
|
|
113
|
+
if cfg.api_key:
|
|
114
|
+
payload["api_key"] = cfg.api_key
|
|
115
|
+
if cfg.user_email:
|
|
116
|
+
payload["user_email"] = cfg.user_email
|
|
117
|
+
if cfg.plan:
|
|
118
|
+
payload["plan"] = cfg.plan
|
|
119
|
+
|
|
120
|
+
tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
|
|
121
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0)
|
|
122
|
+
fd = os.open(tmp, flags, 0o600)
|
|
123
|
+
try:
|
|
124
|
+
if posix:
|
|
125
|
+
os.fchmod(fd, stat.S_IRUSR | stat.S_IWUSR) # umask 와 무관하게 0600
|
|
126
|
+
else:
|
|
127
|
+
_restrict_windows_acl(tmp)
|
|
128
|
+
with os.fdopen(fd, "wb") as fh:
|
|
129
|
+
tomli_w.dump(payload, fh)
|
|
130
|
+
fh.flush()
|
|
131
|
+
os.fsync(fh.fileno())
|
|
132
|
+
os.replace(tmp, path)
|
|
133
|
+
except BaseException:
|
|
134
|
+
try:
|
|
135
|
+
tmp.unlink()
|
|
136
|
+
except OSError:
|
|
137
|
+
pass
|
|
138
|
+
raise
|
|
139
|
+
if posix and stat.S_IMODE(path.stat().st_mode) & (stat.S_IRWXG | stat.S_IRWXO):
|
|
140
|
+
raise OSError(f"could not restrict permissions on {path}")
|
|
141
|
+
return path
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _restrict_windows_acl(path: Path) -> None:
|
|
145
|
+
"""상속을 끊고 현재 사용자(전체)·SYSTEM 만 남긴다. 실패하면 OSError."""
|
|
146
|
+
import subprocess
|
|
147
|
+
|
|
148
|
+
user = os.environ.get("USERNAME")
|
|
149
|
+
domain = os.environ.get("USERDOMAIN")
|
|
150
|
+
if not user:
|
|
151
|
+
raise OSError("cannot determine the current Windows user for the config ACL")
|
|
152
|
+
principal = f"{domain}\\{user}" if domain else user
|
|
153
|
+
result = subprocess.run(
|
|
154
|
+
["icacls", str(path), "/inheritance:r", "/grant:r", f"{principal}:(F)", "*S-1-5-18:(F)"],
|
|
155
|
+
capture_output=True, text=True, encoding="oem", errors="replace", timeout=30,
|
|
156
|
+
)
|
|
157
|
+
if result.returncode != 0:
|
|
158
|
+
raise OSError(f"could not restrict the ACL on {path}: {(result.stderr or result.stdout).strip()[:200]}")
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def clear() -> bool:
|
|
162
|
+
"""Delete the config file. Returns True if a file was removed."""
|
|
163
|
+
path = config_path()
|
|
164
|
+
if path.exists():
|
|
165
|
+
try:
|
|
166
|
+
path.unlink()
|
|
167
|
+
return True
|
|
168
|
+
except OSError:
|
|
169
|
+
return False
|
|
170
|
+
return False
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
__all__ = [
|
|
174
|
+
"DEFAULT_BASE_URL",
|
|
175
|
+
"Config",
|
|
176
|
+
"clear",
|
|
177
|
+
"config_dir",
|
|
178
|
+
"config_path",
|
|
179
|
+
"load",
|
|
180
|
+
"save",
|
|
181
|
+
]
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Output formatters shared by every CLI command."""
|
|
2
|
+
from patchops_cli.formatters.json_fmt import write_json_output
|
|
3
|
+
from patchops_cli.formatters.sarif import write_sarif_output
|
|
4
|
+
from patchops_cli.formatters.table import (
|
|
5
|
+
render_findings_table,
|
|
6
|
+
render_manifest_scan,
|
|
7
|
+
render_website_scan,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"render_findings_table",
|
|
12
|
+
"render_manifest_scan",
|
|
13
|
+
"render_website_scan",
|
|
14
|
+
"write_json_output",
|
|
15
|
+
"write_sarif_output",
|
|
16
|
+
]
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""JSON output formatter — stable, machine-readable."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def write_json_output(data: Any, output: Path | None) -> None:
|
|
10
|
+
"""Write ``data`` as pretty JSON to ``output`` or stdout.
|
|
11
|
+
|
|
12
|
+
The ``default=str`` covers datetime/UUID leaking from API responses.
|
|
13
|
+
"""
|
|
14
|
+
text = json.dumps(data, indent=2, ensure_ascii=False, default=str)
|
|
15
|
+
if output is None:
|
|
16
|
+
print(text)
|
|
17
|
+
else:
|
|
18
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
19
|
+
output.write_text(text + "\n", encoding="utf-8")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
__all__ = ["write_json_output"]
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
"""SARIF 2.1.0 output formatter.
|
|
2
|
+
|
|
3
|
+
Only the subset of SARIF used by GitHub Code Scanning / GitLab SAST
|
|
4
|
+
dashboards is emitted. Covers:
|
|
5
|
+
|
|
6
|
+
- website scan findings (libraries + CVEs, TLS issues, headers)
|
|
7
|
+
- manifest scan findings (vulnerable package @ version)
|
|
8
|
+
- docker scan findings (Trivy output)
|
|
9
|
+
|
|
10
|
+
Anything the server gives us that does not map cleanly is dropped —
|
|
11
|
+
better to emit a valid-but-thin SARIF document than a rich invalid one.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
SARIF_VERSION = "2.1.0"
|
|
20
|
+
SARIF_SCHEMA = (
|
|
21
|
+
"https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/"
|
|
22
|
+
"Schemata/sarif-schema-2.1.0.json"
|
|
23
|
+
)
|
|
24
|
+
TOOL_NAME = "PatchOps Guard CLI"
|
|
25
|
+
TOOL_URI = "https://patchguard.ai"
|
|
26
|
+
|
|
27
|
+
_SARIF_LEVELS = {
|
|
28
|
+
"critical": "error",
|
|
29
|
+
"high": "error",
|
|
30
|
+
"medium": "warning",
|
|
31
|
+
"low": "note",
|
|
32
|
+
"unknown": "none",
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _level(severity: str | None) -> str:
|
|
37
|
+
return _SARIF_LEVELS.get((severity or "unknown").lower(), "none")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _result(
|
|
41
|
+
*,
|
|
42
|
+
rule_id: str,
|
|
43
|
+
message: str,
|
|
44
|
+
level: str,
|
|
45
|
+
uri: str | None = None,
|
|
46
|
+
) -> dict[str, Any]:
|
|
47
|
+
res: dict[str, Any] = {
|
|
48
|
+
"ruleId": rule_id,
|
|
49
|
+
"level": level,
|
|
50
|
+
"message": {"text": message},
|
|
51
|
+
}
|
|
52
|
+
if uri:
|
|
53
|
+
res["locations"] = [
|
|
54
|
+
{
|
|
55
|
+
"physicalLocation": {
|
|
56
|
+
"artifactLocation": {"uri": uri},
|
|
57
|
+
"region": {"startLine": 1},
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
]
|
|
61
|
+
return res
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _rule(rule_id: str, name: str, description: str) -> dict[str, Any]:
|
|
65
|
+
return {
|
|
66
|
+
"id": rule_id,
|
|
67
|
+
"name": name,
|
|
68
|
+
"shortDescription": {"text": name},
|
|
69
|
+
"fullDescription": {"text": description or name},
|
|
70
|
+
"defaultConfiguration": {"level": "warning"},
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _skeleton(tool_version: str) -> dict[str, Any]:
|
|
75
|
+
return {
|
|
76
|
+
"version": SARIF_VERSION,
|
|
77
|
+
"$schema": SARIF_SCHEMA,
|
|
78
|
+
"runs": [
|
|
79
|
+
{
|
|
80
|
+
"tool": {
|
|
81
|
+
"driver": {
|
|
82
|
+
"name": TOOL_NAME,
|
|
83
|
+
"informationUri": TOOL_URI,
|
|
84
|
+
"version": tool_version,
|
|
85
|
+
"rules": [],
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
"results": [],
|
|
89
|
+
}
|
|
90
|
+
],
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _add_rule_once(rules: list[dict[str, Any]], rule: dict[str, Any]) -> None:
|
|
95
|
+
if not any(r["id"] == rule["id"] for r in rules):
|
|
96
|
+
rules.append(rule)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def website_to_sarif(data: dict[str, Any], tool_version: str) -> dict[str, Any]:
|
|
100
|
+
doc = _skeleton(tool_version)
|
|
101
|
+
run = doc["runs"][0]
|
|
102
|
+
rules: list[dict[str, Any]] = run["tool"]["driver"]["rules"]
|
|
103
|
+
results: list[dict[str, Any]] = run["results"]
|
|
104
|
+
uri = data.get("url", "")
|
|
105
|
+
|
|
106
|
+
for lib in data.get("libraries") or []:
|
|
107
|
+
name = lib.get("name", "?")
|
|
108
|
+
version = lib.get("version") or "?"
|
|
109
|
+
for cve in lib.get("cves") or []:
|
|
110
|
+
rid = cve.get("id") or f"LIB/{name}"
|
|
111
|
+
_add_rule_once(
|
|
112
|
+
rules,
|
|
113
|
+
_rule(
|
|
114
|
+
rid,
|
|
115
|
+
rid,
|
|
116
|
+
f"Vulnerable library {name}@{version} (CVE {rid})",
|
|
117
|
+
),
|
|
118
|
+
)
|
|
119
|
+
results.append(
|
|
120
|
+
_result(
|
|
121
|
+
rule_id=rid,
|
|
122
|
+
message=f"{name}@{version} — {cve.get('summary') or rid}",
|
|
123
|
+
level=_level(cve.get("severity")),
|
|
124
|
+
uri=uri,
|
|
125
|
+
)
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
for sec in data.get("secrets_found") or []:
|
|
129
|
+
rid = sec.get("type") or "SECRET/UNKNOWN"
|
|
130
|
+
_add_rule_once(
|
|
131
|
+
rules, _rule(rid, rid, "Exposed secret in web response")
|
|
132
|
+
)
|
|
133
|
+
results.append(
|
|
134
|
+
_result(
|
|
135
|
+
rule_id=rid,
|
|
136
|
+
message=sec.get("value", "")[:200] or "secret exposed",
|
|
137
|
+
level="error",
|
|
138
|
+
uri=uri,
|
|
139
|
+
)
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
# URL Scan Flash(v6) — 84 점검 실패 + AI 공격 단계 (2026-11-24: 예전엔 빠져 SARIF 가 비었다)
|
|
143
|
+
uri = uri or data.get("target_url", "")
|
|
144
|
+
for chk in data.get("url_84_failed") or []:
|
|
145
|
+
rid = f"URL84/{chk.get('id') or chk.get('name') or 'check'}"
|
|
146
|
+
_add_rule_once(rules, _rule(rid, str(chk.get("name") or rid), str(chk.get("finding") or "")))
|
|
147
|
+
results.append(_result(rule_id=rid, message=str(chk.get("finding") or chk.get("name") or rid)[:300],
|
|
148
|
+
level=_level(chk.get("severity")), uri=uri))
|
|
149
|
+
for i, step in enumerate((data.get("llm_scan") or {}).get("steps") or []):
|
|
150
|
+
rid = f"URLAI/{step.get('phase') or 'step'}-{i + 1}"
|
|
151
|
+
_add_rule_once(rules, _rule(rid, str(step.get("headline") or rid), str(step.get("narration") or "")[:500]))
|
|
152
|
+
results.append(_result(rule_id=rid, message=str(step.get("headline") or rid)[:300],
|
|
153
|
+
level=_level(step.get("severity")), uri=uri))
|
|
154
|
+
return doc
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def manifest_to_sarif(data: dict[str, Any], tool_version: str) -> dict[str, Any]:
|
|
158
|
+
doc = _skeleton(tool_version)
|
|
159
|
+
run = doc["runs"][0]
|
|
160
|
+
rules: list[dict[str, Any]] = run["tool"]["driver"]["rules"]
|
|
161
|
+
results: list[dict[str, Any]] = run["results"]
|
|
162
|
+
uri = data.get("filename") or "manifest"
|
|
163
|
+
|
|
164
|
+
for pkg in data.get("top_vulnerable") or []:
|
|
165
|
+
name = pkg.get("name", "?")
|
|
166
|
+
version = pkg.get("version") or "?"
|
|
167
|
+
for cve in pkg.get("cves") or []:
|
|
168
|
+
rid = cve.get("id") or f"PKG/{name}"
|
|
169
|
+
_add_rule_once(
|
|
170
|
+
rules,
|
|
171
|
+
_rule(
|
|
172
|
+
rid,
|
|
173
|
+
rid,
|
|
174
|
+
f"{name}@{version} has known vulnerability {rid}",
|
|
175
|
+
),
|
|
176
|
+
)
|
|
177
|
+
results.append(
|
|
178
|
+
_result(
|
|
179
|
+
rule_id=rid,
|
|
180
|
+
message=(
|
|
181
|
+
f"{name}@{version} — "
|
|
182
|
+
f"{cve.get('summary') or rid}"
|
|
183
|
+
),
|
|
184
|
+
level=_level(cve.get("severity")),
|
|
185
|
+
uri=uri,
|
|
186
|
+
)
|
|
187
|
+
)
|
|
188
|
+
return doc
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def docker_to_sarif(data: dict[str, Any], tool_version: str) -> dict[str, Any]:
|
|
192
|
+
doc = _skeleton(tool_version)
|
|
193
|
+
run = doc["runs"][0]
|
|
194
|
+
rules: list[dict[str, Any]] = run["tool"]["driver"]["rules"]
|
|
195
|
+
results: list[dict[str, Any]] = run["results"]
|
|
196
|
+
uri = data.get("image", "docker-image")
|
|
197
|
+
|
|
198
|
+
for v in data.get("vulns") or []:
|
|
199
|
+
rid = v.get("id") or "TRIVY/UNKNOWN"
|
|
200
|
+
_add_rule_once(
|
|
201
|
+
rules,
|
|
202
|
+
_rule(rid, rid, v.get("message") or rid),
|
|
203
|
+
)
|
|
204
|
+
results.append(
|
|
205
|
+
_result(
|
|
206
|
+
rule_id=rid,
|
|
207
|
+
message=v.get("message") or rid,
|
|
208
|
+
level=_level(v.get("severity")),
|
|
209
|
+
uri=uri,
|
|
210
|
+
)
|
|
211
|
+
)
|
|
212
|
+
return doc
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def findings_to_sarif(items: list[dict[str, Any]], tool_version: str) -> dict[str, Any]:
|
|
216
|
+
doc = _skeleton(tool_version)
|
|
217
|
+
run = doc["runs"][0]
|
|
218
|
+
rules: list[dict[str, Any]] = run["tool"]["driver"]["rules"]
|
|
219
|
+
results: list[dict[str, Any]] = run["results"]
|
|
220
|
+
|
|
221
|
+
for item in items:
|
|
222
|
+
rid = item.get("fingerprint") or item.get("id") or "FINDING"
|
|
223
|
+
title = item.get("title") or rid
|
|
224
|
+
_add_rule_once(rules, _rule(rid, title, title))
|
|
225
|
+
results.append(
|
|
226
|
+
_result(
|
|
227
|
+
rule_id=rid,
|
|
228
|
+
message=title,
|
|
229
|
+
level=_level(item.get("severity")),
|
|
230
|
+
)
|
|
231
|
+
)
|
|
232
|
+
return doc
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def write_sarif_output(
|
|
236
|
+
sarif_doc: dict[str, Any], output: Path | None
|
|
237
|
+
) -> None:
|
|
238
|
+
text = json.dumps(sarif_doc, indent=2, ensure_ascii=False, default=str)
|
|
239
|
+
if output is None:
|
|
240
|
+
print(text)
|
|
241
|
+
else:
|
|
242
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
243
|
+
output.write_text(text + "\n", encoding="utf-8")
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
__all__ = [
|
|
247
|
+
"docker_to_sarif",
|
|
248
|
+
"findings_to_sarif",
|
|
249
|
+
"manifest_to_sarif",
|
|
250
|
+
"website_to_sarif",
|
|
251
|
+
"write_sarif_output",
|
|
252
|
+
]
|