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,6 @@
1
+ """patchops_cli — PatchOps Guard command-line interface."""
2
+ from __future__ import annotations
3
+
4
+ __version__ = "0.2.0"
5
+
6
+ __all__ = ["__version__"]
@@ -0,0 +1,9 @@
1
+ """Allow `python -m patchops_cli ...` to run the same app as the ``patchops`` script."""
2
+ from __future__ import annotations
3
+
4
+ import sys
5
+
6
+ from patchops_cli.main import main
7
+
8
+ if __name__ == "__main__":
9
+ sys.exit(main())
patchops_cli/client.py ADDED
@@ -0,0 +1,336 @@
1
+ """HTTP client for the PatchOps CLI.
2
+
3
+ Thin wrapper around the published ``patchguard`` SDK. The SDK already
4
+ covers findings/health/benchmark; here we add the endpoints the CLI
5
+ needs (auth/me, scan/*, repairs, sbom) without forking the SDK.
6
+
7
+ Every method re-raises ``patchguard.PatchopsError`` so the top-level
8
+ Typer app can render a single error line.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ import httpx
17
+
18
+ from patchops_cli.config import Config
19
+
20
+
21
+ class APIError(Exception):
22
+ """HTTP error surfaced to the command layer.
23
+
24
+ ``status == 0`` means the request never reached the server (DNS,
25
+ timeout, TLS, etc.). Keep the status attribute — commands inspect
26
+ it to decide between exit code 1 (network) and 2 (auth).
27
+ """
28
+
29
+ def __init__(self, status: int, message: str, detail: Any = None) -> None:
30
+ super().__init__(message)
31
+ self.status = status
32
+ self.message = message
33
+ self.detail = detail
34
+
35
+
36
+ def _normalize_base(base_url: str) -> str:
37
+ """Return the API root. Strips trailing slash, appends ``/api`` when
38
+ pointing at the public website (nginx strips ``/api`` before hitting
39
+ uvicorn). Direct-to-backend URLs (``localhost``, ``127.0.0.1``) skip
40
+ the prefix because the backend already serves routes at the root.
41
+ """
42
+ normalized = base_url.rstrip("/")
43
+ lowered = normalized.lower()
44
+ is_direct_backend = "://localhost" in lowered or "://127.0.0.1" in lowered
45
+ if is_direct_backend:
46
+ return normalized
47
+ if not normalized.endswith("/api"):
48
+ normalized += "/api"
49
+ return normalized
50
+
51
+
52
+ class PatchOpsCLIClient:
53
+ """Minimal HTTP client scoped to what the CLI needs.
54
+
55
+ Uses ``httpx.Client`` synchronously — the CLI blocks on every call,
56
+ so an async client would just add ceremony. The SDK (patchguard)
57
+ is reused when it already covers a route; raw _request is used for
58
+ newer endpoints not yet in the SDK.
59
+ """
60
+
61
+ def __init__(self, cfg: Config, *, timeout: float = 30.0) -> None:
62
+ self.cfg = cfg
63
+ headers: dict[str, str] = {
64
+ "User-Agent": "patchops-cli",
65
+ "Accept": "application/json",
66
+ }
67
+ if cfg.api_key:
68
+ headers["Authorization"] = f"Bearer {cfg.api_key}"
69
+ self._http = httpx.Client(
70
+ base_url=_normalize_base(cfg.base_url),
71
+ headers=headers,
72
+ timeout=timeout,
73
+ follow_redirects=True,
74
+ )
75
+
76
+ def close(self) -> None:
77
+ self._http.close()
78
+
79
+ def __enter__(self) -> PatchOpsCLIClient:
80
+ return self
81
+
82
+ def __exit__(self, *a: Any) -> None:
83
+ self.close()
84
+
85
+ # ---------------------------------------------------------------- low level
86
+
87
+ def request(
88
+ self,
89
+ method: str,
90
+ path: str,
91
+ *,
92
+ params: dict[str, Any] | None = None,
93
+ json_body: Any | None = None,
94
+ files: dict[str, Any] | None = None,
95
+ data: dict[str, Any] | None = None,
96
+ ) -> Any:
97
+ try:
98
+ resp = self._http.request(
99
+ method, path, params=params, json=json_body, files=files, data=data
100
+ )
101
+ except httpx.TimeoutException as exc:
102
+ raise APIError(0, f"timeout talking to {self.cfg.base_url}: {exc}") from exc
103
+ except httpx.HTTPError as exc:
104
+ raise APIError(0, f"network error: {exc}") from exc
105
+ if resp.status_code >= 400:
106
+ try:
107
+ detail = resp.json()
108
+ except Exception:
109
+ detail = resp.text
110
+ # Normalise FastAPI's {"detail": "..."} shape
111
+ if isinstance(detail, dict) and "detail" in detail:
112
+ msg = str(detail.get("detail"))
113
+ else:
114
+ msg = str(detail)[:300]
115
+ raise APIError(resp.status_code, msg, detail=detail)
116
+ ctype = resp.headers.get("content-type", "")
117
+ if ctype.startswith("application/json"):
118
+ return resp.json()
119
+ return resp.text
120
+
121
+ # ---------------------------------------------------------------- auth
122
+
123
+ def me(self) -> dict[str, Any]:
124
+ """GET /auth/me — verifies the key and returns user+org."""
125
+ return self.request("GET", "/auth/me")
126
+
127
+ def health(self) -> dict[str, Any]:
128
+ return self.request("GET", "/health")
129
+
130
+ # ---------------------------------------------------------------- scans
131
+
132
+ def scan_website(self, url: str) -> dict[str, Any]:
133
+ return self.request("POST", "/scan/website", json_body={"url": url})
134
+
135
+ def scan_docker(self, image: str) -> dict[str, Any]:
136
+ return self.request("POST", "/scan/docker", json_body={"image": image})
137
+
138
+ def scan_manifest(self, path: Path) -> dict[str, Any]:
139
+ with path.open("rb") as fh:
140
+ files = {"file": (path.name, fh, "application/octet-stream")}
141
+ return self.request("POST", "/scan/manifest", files=files)
142
+
143
+ def scan_auto(
144
+ self, query: str, *, lang: str | None = None,
145
+ ) -> dict[str, Any]:
146
+ body: dict[str, Any] = {"query": query}
147
+ if lang:
148
+ body["lang"] = lang
149
+ return self.request("POST", "/scan/auto", json_body=body)
150
+
151
+ def scan_package(
152
+ self, ecosystem: str, name: str, version: str | None = None
153
+ ) -> dict[str, Any]:
154
+ params: dict[str, Any] = {"ecosystem": ecosystem, "name": name}
155
+ if version:
156
+ params["version"] = version
157
+ return self.request("GET", "/scan/package", params=params)
158
+
159
+ # ---------------------------------------------------------------- findings
160
+
161
+ def findings_list(
162
+ self,
163
+ *,
164
+ status: str | None = None,
165
+ severity: str | None = None,
166
+ limit: int = 100,
167
+ offset: int = 0,
168
+ ) -> dict[str, Any]:
169
+ params: dict[str, Any] = {"limit": limit, "offset": offset}
170
+ if status:
171
+ params["status"] = status
172
+ if severity:
173
+ params["severity"] = severity
174
+ return self.request("GET", "/findings/unified", params=params)
175
+
176
+ def finding_get(self, finding_id: str) -> dict[str, Any]:
177
+ return self.request("GET", f"/findings/{finding_id}")
178
+
179
+ # ---------------------------------------------------------------- repairs
180
+
181
+ def repair_start(self, finding_id: str) -> dict[str, Any]:
182
+ return self.request("POST", f"/findings/{finding_id}/repair")
183
+
184
+ def repair_status(self, job_id: str) -> dict[str, Any]:
185
+ return self.request("GET", f"/repairs/{job_id}")
186
+
187
+ def repair_list(
188
+ self, *, status: str | None = None, limit: int = 50
189
+ ) -> dict[str, Any]:
190
+ params: dict[str, Any] = {"limit": limit}
191
+ if status:
192
+ params["status_filter"] = status
193
+ return self.request("GET", "/repairs", params=params)
194
+
195
+ # ---------------------------------------------------------------- sbom
196
+
197
+ # ───────────────────────── locked engines ─────────────────────────
198
+ # 4 production engines exposed by the CLI:
199
+ # 1. URL Scan Flash 1.0 → POST /v6/scan/url
200
+ # 2. Repo Scan Flash 1.4 → POST /v6/scan (default flags)
201
+ # 3. Repo Scan Deep 1.4 → POST /v6/scan (--stage-e + plan=pro)
202
+ # 4. AI Repair 1.0 → existing repair_* + quick-repair surfaces
203
+
204
+ def free_scan_start(self, host: str) -> dict[str, Any]:
205
+ """Free Scan — 135 deterministic checks across 17 categories.
206
+
207
+ Public, no auth, IP rate-limited. Returns ``{scan_id, status, ...}``.
208
+ """
209
+ return self.request(
210
+ "POST", "/free-scan/start", json_body={"host": host},
211
+ )
212
+
213
+ def free_scan_get(self, scan_id: str) -> dict[str, Any]:
214
+ """Poll Free Scan status. Returns ``{status, findings, score, ...}``."""
215
+ return self.request("GET", f"/free-scan/{scan_id}")
216
+
217
+ def free_scan_badge(self, scan_id: str) -> str:
218
+ """Download Free Scan SVG badge (returns raw SVG text)."""
219
+ return self.request("GET", f"/free-scan/{scan_id}/badge.svg")
220
+
221
+ def url_scan_pro(
222
+ self,
223
+ url: str,
224
+ *,
225
+ wait: bool = True,
226
+ poll_interval_sec: float = 3.0,
227
+ max_wait_sec: float = 900.0,
228
+ ) -> dict[str, Any]:
229
+ """URL Scan Flash 1.0 — live-site Pro pentest (84 checks + AI chain).
230
+
231
+ Phase 1 (2026-05-10) made ``POST /v6/scan/url`` async — it now
232
+ returns ``{scan_id, status: "pending", target_url}`` immediately
233
+ and the heavy work runs on the RQ worker. Callers must poll
234
+ ``GET /v6/scan/url/{scan_id}`` until ``status`` is terminal
235
+ (``complete`` / ``error`` / ``orphaned``).
236
+
237
+ With ``wait=True`` (default), this method does the POST + poll
238
+ loop and returns the GET payload with ``result_json`` flattened
239
+ up so legacy callers still see ``url_84_failed`` / ``dns`` /
240
+ ``llm_scan`` at the top level.
241
+
242
+ With ``wait=False``, returns the immediate POST response
243
+ ``{scan_id, status, target_url}`` and the caller is responsible
244
+ for polling.
245
+ """
246
+ import time
247
+
248
+ post_resp = self.request(
249
+ "POST", "/v6/scan/url", json_body={"url": url},
250
+ )
251
+ scan_id = post_resp.get("scan_id") if isinstance(post_resp, dict) else None
252
+ if not wait or not scan_id:
253
+ return post_resp
254
+
255
+ deadline = time.time() + max_wait_sec
256
+ while time.time() < deadline:
257
+ time.sleep(poll_interval_sec)
258
+ resp = self.url_scan_get(scan_id)
259
+ status = resp.get("status") if isinstance(resp, dict) else None
260
+ if status in ("complete", "error", "orphaned"):
261
+ # Flatten result_json up so old callers (url-scan run
262
+ # formatters) still see url_84_failed / dns / llm_scan
263
+ # at the top level of the dict.
264
+ result_json = resp.get("result_json") or {}
265
+ if not isinstance(result_json, dict):
266
+ result_json = {}
267
+ flattened = {**result_json, **resp}
268
+ # Drop result_json after flattening to avoid double-nesting
269
+ # noise in JSON output.
270
+ flattened.pop("result_json", None)
271
+ return flattened
272
+ raise APIError(
273
+ 408,
274
+ f"url-scan timeout after {max_wait_sec}s (scan_id={scan_id})",
275
+ )
276
+
277
+ def url_scan_get(self, scan_id: str) -> dict[str, Any]:
278
+ """Poll URL Scan status. Returns ``{status, scan_id, ...}``."""
279
+ return self.request("GET", f"/v6/scan/url/{scan_id}")
280
+
281
+ def repo_scan(
282
+ self,
283
+ repo_path: str,
284
+ *,
285
+ tier: str = "quick", # "quick" | "deep"
286
+ plan: str = "",
287
+ ) -> dict[str, Any]:
288
+ """Repo Scan Flash 1.4 (quick) or Deep 1.4 (deep cascade)."""
289
+ body: dict[str, Any] = {
290
+ "repo_path": repo_path,
291
+ "plan": plan or ("pro" if tier == "deep" else ""),
292
+ "enable_layer1": True,
293
+ "enable_layer2": True,
294
+ "enable_layer3": True,
295
+ "enable_stage_e": tier == "deep", # heavy MRVA only on deep
296
+ "enable_stage_f": True,
297
+ "enable_stage_g": True,
298
+ }
299
+ return self.request("POST", "/v6/scan", json_body=body)
300
+
301
+ def quick_repair_patch_download(self, finding_id: str) -> str:
302
+ """Download verified .diff for a finding (App-less UX)."""
303
+ return self.request(
304
+ "GET", f"/quick-repair/finding/{finding_id}/patch.diff",
305
+ )
306
+
307
+ def quick_repair_create_pr(self, finding_id: str) -> dict[str, Any]:
308
+ """Promote a stored patch into a real pull/merge request (GitHub, GitLab or Bitbucket)."""
309
+ return self.request(
310
+ "POST", f"/quick-repair/finding/{finding_id}/create-pr",
311
+ )
312
+
313
+ # ─────────────────────────── auxiliary ───────────────────────────
314
+
315
+ def sbom_upload(
316
+ self, path: Path, *, fmt: str = "cyclonedx"
317
+ ) -> dict[str, Any]:
318
+ # Server accepts SBOM in /scan/sbom (guest-accessible) or the
319
+ # authenticated /repos/{repo_id}/sbom. For a CLI upload without
320
+ # a repo_id we use the public scan ingest, which already runs
321
+ # OSV matching against the uploaded components.
322
+ with path.open("rb") as fh:
323
+ files = {"file": (path.name, fh, "application/octet-stream")}
324
+ return self.request("POST", "/scan/sbom", files=files)
325
+
326
+
327
+ def write_json(data: Any, dest: Path | None) -> None:
328
+ """Serialise ``data`` as JSON and write to ``dest`` or stdout."""
329
+ text = json.dumps(data, indent=2, ensure_ascii=False, default=str)
330
+ if dest is None:
331
+ print(text)
332
+ else:
333
+ dest.write_text(text + "\n", encoding="utf-8")
334
+
335
+
336
+ __all__ = ["APIError", "PatchOpsCLIClient", "write_json"]
@@ -0,0 +1 @@
1
+ """Typer subcommand modules for the PatchOps CLI."""
@@ -0,0 +1,100 @@
1
+ """`patchops auth ...` — login, logout, status."""
2
+ from __future__ import annotations
3
+
4
+ import typer
5
+ from rich.console import Console
6
+
7
+ from patchops_cli import config as cfg_mod
8
+ from patchops_cli.client import APIError, PatchOpsCLIClient
9
+ from patchops_cli.utils.errors import EXIT_ERROR, EXIT_USAGE, fail
10
+
11
+ app = typer.Typer(help="Authenticate with the PatchOps Guard API.")
12
+
13
+
14
+ @app.command("login")
15
+ def login(
16
+ api_key: str | None = typer.Option(
17
+ None, "--api-key", help="API key (pk_live_... or pk_test_...)."
18
+ ),
19
+ base_url: str = typer.Option(
20
+ cfg_mod.DEFAULT_BASE_URL, "--base-url", help="API base URL."
21
+ ),
22
+ ) -> None:
23
+ """Store credentials and verify them against the API.
24
+
25
+ Prompts for the key interactively when ``--api-key`` is omitted. The
26
+ key is validated by calling ``/auth/me`` — a bad key exits 1 and
27
+ nothing is written to disk.
28
+ """
29
+ if api_key is None:
30
+ api_key = typer.prompt("API key", hide_input=True)
31
+ api_key = api_key.strip()
32
+ if not api_key:
33
+ raise fail("API key cannot be empty", exit_code=EXIT_USAGE)
34
+
35
+ candidate = cfg_mod.Config(base_url=base_url, api_key=api_key)
36
+
37
+ try:
38
+ with PatchOpsCLIClient(candidate, timeout=15.0) as client:
39
+ me = client.me()
40
+ except APIError as exc:
41
+ if exc.status == 401:
42
+ raise fail("invalid API key (401 unauthorized)")
43
+ if exc.status == 0:
44
+ raise fail(f"could not reach {base_url}: {exc.message}")
45
+ raise fail(f"auth failed ({exc.status}): {exc.message}")
46
+
47
+ user = me.get("user") or {}
48
+ org = me.get("org") or {}
49
+ candidate.user_email = user.get("email")
50
+ candidate.plan = org.get("plan")
51
+
52
+ path = cfg_mod.save(candidate)
53
+ console = Console()
54
+ console.print("[green]Logged in.[/green]")
55
+ console.print(f" user : {user.get('email', '?')}")
56
+ console.print(f" org : {org.get('name', '?')} ({org.get('plan', '?')})")
57
+ console.print(f" file : {path}")
58
+
59
+
60
+ @app.command("logout")
61
+ def logout() -> None:
62
+ """Remove the local credentials file."""
63
+ removed = cfg_mod.clear()
64
+ console = Console()
65
+ if removed:
66
+ console.print("[green]Logged out.[/green]")
67
+ else:
68
+ console.print("Not logged in — nothing to remove.")
69
+
70
+
71
+ @app.command("status")
72
+ def status() -> None:
73
+ """Show current authentication state."""
74
+ cfg = cfg_mod.load()
75
+ console = Console()
76
+ if not cfg.is_authenticated():
77
+ console.print("[yellow]Not logged in.[/yellow]")
78
+ console.print("Run: patchops auth login --api-key pk_live_...")
79
+ raise typer.Exit(code=EXIT_ERROR)
80
+
81
+ # Revalidate so we surface a revoked key as not-logged-in.
82
+ try:
83
+ with PatchOpsCLIClient(cfg, timeout=10.0) as client:
84
+ me = client.me()
85
+ except APIError as exc:
86
+ console.print(
87
+ f"[red]Credentials present but server rejected them ({exc.status}).[/red]"
88
+ )
89
+ console.print(f"File: {cfg_mod.config_path()}")
90
+ raise typer.Exit(code=EXIT_ERROR) from None
91
+
92
+ user = me.get("user") or {}
93
+ org = me.get("org") or {}
94
+ console.print(f"[green]Logged in[/green] as {user.get('email', '?')}")
95
+ console.print(f" org : {org.get('name', '?')} ({org.get('plan', '?')})")
96
+ console.print(f" url : {cfg.base_url}")
97
+ console.print(f" file : {cfg_mod.config_path()}")
98
+
99
+
100
+ __all__ = ["app"]
@@ -0,0 +1,111 @@
1
+ """`patchops findings ...` — list + details."""
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.formatters.sarif import findings_to_sarif, write_sarif_output
13
+ from patchops_cli.formatters.table import render_findings_table
14
+ from patchops_cli.utils.errors import EXIT_USAGE, fail
15
+
16
+ app = typer.Typer(help="Inspect findings stored on the server.")
17
+
18
+
19
+ class _Format(str, Enum):
20
+ json = "json"
21
+ table = "table"
22
+ sarif = "sarif"
23
+
24
+
25
+ class _Status(str, Enum):
26
+ open = "open"
27
+ fixed = "fixed"
28
+ ignored = "ignored"
29
+
30
+
31
+ class _Severity(str, Enum):
32
+ low = "low"
33
+ medium = "medium"
34
+ high = "high"
35
+ critical = "critical"
36
+
37
+
38
+ def _tool_version() -> str:
39
+ try:
40
+ from patchops_cli import __version__
41
+
42
+ return __version__
43
+ except Exception:
44
+ return "0.0.0"
45
+
46
+
47
+ def _client() -> PatchOpsCLIClient:
48
+ cfg = cfg_mod.load()
49
+ if not cfg.is_authenticated():
50
+ raise fail(
51
+ "not authenticated — run `patchops auth login` first", exit_code=EXIT_USAGE
52
+ )
53
+ return PatchOpsCLIClient(cfg)
54
+
55
+
56
+ @app.command("list")
57
+ def list_findings(
58
+ status: _Status | None = typer.Option(None, "--status"),
59
+ severity: _Severity | None = typer.Option(None, "--severity"),
60
+ limit: int = typer.Option(100, "--limit", min=1, max=500),
61
+ fmt: _Format = typer.Option(_Format.table, "--format"),
62
+ output: Path | None = typer.Option(None, "--output"),
63
+ ) -> None:
64
+ """List open findings (default: 100 most recent)."""
65
+ try:
66
+ with _client() as client:
67
+ data = client.findings_list(
68
+ status=status.value if status else None,
69
+ severity=severity.value if severity else None,
70
+ limit=limit,
71
+ )
72
+ except APIError as exc:
73
+ raise fail(f"could not list findings ({exc.status}): {exc.message}")
74
+
75
+ items = data.get("items") or []
76
+ if fmt is _Format.json:
77
+ write_json_output(data, output)
78
+ elif fmt is _Format.sarif:
79
+ write_sarif_output(
80
+ findings_to_sarif(items, _tool_version()), output
81
+ )
82
+ else:
83
+ if output is not None:
84
+ write_json_output(data, output)
85
+ render_findings_table(items, title=f"Findings (total={data.get('total', 0)})")
86
+
87
+
88
+ @app.command("get")
89
+ def get_finding(
90
+ finding_id: str = typer.Argument(..., help="Finding UUID."),
91
+ fmt: _Format = typer.Option(_Format.json, "--format"),
92
+ output: Path | None = typer.Option(None, "--output"),
93
+ ) -> None:
94
+ """Fetch a single finding by ID."""
95
+ try:
96
+ with _client() as client:
97
+ data = client.finding_get(finding_id)
98
+ except APIError as exc:
99
+ raise fail(f"could not fetch finding ({exc.status}): {exc.message}")
100
+
101
+ if fmt is _Format.sarif:
102
+ write_sarif_output(
103
+ findings_to_sarif([data], _tool_version()), output
104
+ )
105
+ elif fmt is _Format.table:
106
+ render_findings_table([data], title=f"Finding {finding_id}")
107
+ else:
108
+ write_json_output(data, output)
109
+
110
+
111
+ __all__ = ["app"]