patchops-guard 0.2.0__tar.gz

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.
Files changed (39) hide show
  1. patchops_guard-0.2.0/PKG-INFO +130 -0
  2. patchops_guard-0.2.0/README.md +97 -0
  3. patchops_guard-0.2.0/patchops_cli/__init__.py +6 -0
  4. patchops_guard-0.2.0/patchops_cli/__main__.py +9 -0
  5. patchops_guard-0.2.0/patchops_cli/client.py +336 -0
  6. patchops_guard-0.2.0/patchops_cli/commands/__init__.py +1 -0
  7. patchops_guard-0.2.0/patchops_cli/commands/auth.py +100 -0
  8. patchops_guard-0.2.0/patchops_cli/commands/findings.py +111 -0
  9. patchops_guard-0.2.0/patchops_cli/commands/free_scan.py +167 -0
  10. patchops_guard-0.2.0/patchops_cli/commands/mcp_audit.py +271 -0
  11. patchops_guard-0.2.0/patchops_cli/commands/mcp_watch.py +248 -0
  12. patchops_guard-0.2.0/patchops_cli/commands/repair.py +229 -0
  13. patchops_guard-0.2.0/patchops_cli/commands/repo_scan.py +127 -0
  14. patchops_guard-0.2.0/patchops_cli/commands/sbom.py +339 -0
  15. patchops_guard-0.2.0/patchops_cli/commands/scan.py +461 -0
  16. patchops_guard-0.2.0/patchops_cli/commands/url_scan.py +111 -0
  17. patchops_guard-0.2.0/patchops_cli/commands/v6.py +138 -0
  18. patchops_guard-0.2.0/patchops_cli/config.py +181 -0
  19. patchops_guard-0.2.0/patchops_cli/formatters/__init__.py +16 -0
  20. patchops_guard-0.2.0/patchops_cli/formatters/json_fmt.py +22 -0
  21. patchops_guard-0.2.0/patchops_cli/formatters/sarif.py +252 -0
  22. patchops_guard-0.2.0/patchops_cli/formatters/table.py +269 -0
  23. patchops_guard-0.2.0/patchops_cli/formatters/tree.py +167 -0
  24. patchops_guard-0.2.0/patchops_cli/legacy.py +150 -0
  25. patchops_guard-0.2.0/patchops_cli/main.py +110 -0
  26. patchops_guard-0.2.0/patchops_cli/mcp_remote.py +147 -0
  27. patchops_guard-0.2.0/patchops_cli/utils/__init__.py +1 -0
  28. patchops_guard-0.2.0/patchops_cli/utils/errors.py +75 -0
  29. patchops_guard-0.2.0/patchops_guard.egg-info/PKG-INFO +130 -0
  30. patchops_guard-0.2.0/patchops_guard.egg-info/SOURCES.txt +37 -0
  31. patchops_guard-0.2.0/patchops_guard.egg-info/dependency_links.txt +1 -0
  32. patchops_guard-0.2.0/patchops_guard.egg-info/entry_points.txt +2 -0
  33. patchops_guard-0.2.0/patchops_guard.egg-info/requires.txt +12 -0
  34. patchops_guard-0.2.0/patchops_guard.egg-info/top_level.txt +1 -0
  35. patchops_guard-0.2.0/pyproject.toml +51 -0
  36. patchops_guard-0.2.0/setup.cfg +4 -0
  37. patchops_guard-0.2.0/tests/test_cli.py +785 -0
  38. patchops_guard-0.2.0/tests/test_sensitive_config.py +168 -0
  39. patchops_guard-0.2.0/tests/test_url_scan_async.py +201 -0
@@ -0,0 +1,130 @@
1
+ Metadata-Version: 2.4
2
+ Name: patchops-guard
3
+ Version: 0.2.0
4
+ Summary: PatchOps Guard CLI — SBOM, scans, and AI fixes from your terminal.
5
+ Author: Superlabs
6
+ License: MIT
7
+ Project-URL: Homepage, https://patchguard.ai
8
+ Project-URL: Documentation, https://patchguard.ai/docs
9
+ Project-URL: Source, https://github.com/superlabs-x/patchops-guard
10
+ Keywords: cve,sbom,security,patchops,patchguard
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Security
21
+ Classifier: Topic :: Software Development :: Libraries
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ Requires-Dist: httpx>=0.25
25
+ Requires-Dist: typer>=0.12
26
+ Requires-Dist: rich>=13.0
27
+ Requires-Dist: tomli-w>=1.0
28
+ Requires-Dist: tomli>=2.0; python_version < "3.11"
29
+ Requires-Dist: patchguard-ai>=0.1.1
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest>=7; extra == "dev"
32
+ Requires-Dist: pytest-mock>=3; extra == "dev"
33
+
34
+ # patchops CLI
35
+
36
+ Official command-line interface for [PatchOps Guard](https://patchguard.ai) —
37
+ SBOM generation, CVE scanning, and AI-driven fix jobs without leaving your
38
+ terminal.
39
+
40
+ ## Install
41
+
42
+ ```bash
43
+ pip install patchops-guard
44
+ ```
45
+
46
+ Or install from source:
47
+
48
+ ```bash
49
+ git clone https://github.com/superlabs-x/patchops-guard
50
+ pip install -e cli/
51
+ ```
52
+
53
+ ## Authentication
54
+
55
+ ```bash
56
+ patchops auth login --api-key pk_live_...
57
+ patchops auth status
58
+ patchops auth logout
59
+ ```
60
+
61
+ Credentials are stored with permissions `0600` at:
62
+
63
+ - Linux / macOS: `~/.config/patchops/config.toml`
64
+ - Windows: `%APPDATA%\patchops\config.toml`
65
+
66
+ Environment variables take precedence:
67
+
68
+ - `PATCHOPS_API_KEY` — bearer token
69
+ - `PATCHOPS_BASE_URL` — API host (default `https://patchguard.ai`)
70
+
71
+ ## Scans
72
+
73
+ ```bash
74
+ # Auto-detect: URL, lockfile, or docker image
75
+ patchops scan auto package-lock.json
76
+ patchops scan auto https://example.com
77
+ patchops scan auto nginx:1.25
78
+
79
+ # Explicit commands
80
+ patchops scan manifest package-lock.json --format json --output scan.json
81
+ patchops scan website https://example.com --fail-on-severity high
82
+ patchops scan docker nginx:1.25 --format sarif --output scan.sarif
83
+ ```
84
+
85
+ Common flags:
86
+
87
+ - `--format json|table|sarif` — output shape (default `table`)
88
+ - `--output FILE` — write to file (stdout is default)
89
+ - `--severity critical|high|medium|low` — show only findings at or above
90
+ - `--fail-on-severity SEVERITY` — exit non-zero when met (CI-friendly)
91
+
92
+ ## Findings
93
+
94
+ ```bash
95
+ patchops findings list --status open --severity high
96
+ patchops findings get <finding-uuid>
97
+ ```
98
+
99
+ ## AI Repair
100
+
101
+ ```bash
102
+ patchops repair start <finding-uuid> --wait
103
+ patchops repair status <job-uuid>
104
+ patchops repair list --status completed
105
+ ```
106
+
107
+ ## SBOM
108
+
109
+ ```bash
110
+ # Emit CycloneDX 1.6 JSON from a lockfile
111
+ patchops sbom generate package-lock.json --output sbom.json
112
+
113
+ # Upload an SBOM for OSV vulnerability matching
114
+ patchops sbom upload sbom.json
115
+ ```
116
+
117
+ Supported lockfiles: `package-lock.json`, `package.json`, `requirements.txt`,
118
+ `Pipfile.lock`, `pom.xml`, `go.mod`, `Gemfile.lock`, `Cargo.lock`,
119
+ `composer.lock`.
120
+
121
+ ## Exit codes
122
+
123
+ - `0` — success
124
+ - `1` — general error (network, API, IO)
125
+ - `2` — usage error (bad argument, missing auth)
126
+ - `10-13` — `--fail-on-severity` threshold hit (low / medium / high / critical)
127
+
128
+ ## License
129
+
130
+ MIT
@@ -0,0 +1,97 @@
1
+ # patchops CLI
2
+
3
+ Official command-line interface for [PatchOps Guard](https://patchguard.ai) —
4
+ SBOM generation, CVE scanning, and AI-driven fix jobs without leaving your
5
+ terminal.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install patchops-guard
11
+ ```
12
+
13
+ Or install from source:
14
+
15
+ ```bash
16
+ git clone https://github.com/superlabs-x/patchops-guard
17
+ pip install -e cli/
18
+ ```
19
+
20
+ ## Authentication
21
+
22
+ ```bash
23
+ patchops auth login --api-key pk_live_...
24
+ patchops auth status
25
+ patchops auth logout
26
+ ```
27
+
28
+ Credentials are stored with permissions `0600` at:
29
+
30
+ - Linux / macOS: `~/.config/patchops/config.toml`
31
+ - Windows: `%APPDATA%\patchops\config.toml`
32
+
33
+ Environment variables take precedence:
34
+
35
+ - `PATCHOPS_API_KEY` — bearer token
36
+ - `PATCHOPS_BASE_URL` — API host (default `https://patchguard.ai`)
37
+
38
+ ## Scans
39
+
40
+ ```bash
41
+ # Auto-detect: URL, lockfile, or docker image
42
+ patchops scan auto package-lock.json
43
+ patchops scan auto https://example.com
44
+ patchops scan auto nginx:1.25
45
+
46
+ # Explicit commands
47
+ patchops scan manifest package-lock.json --format json --output scan.json
48
+ patchops scan website https://example.com --fail-on-severity high
49
+ patchops scan docker nginx:1.25 --format sarif --output scan.sarif
50
+ ```
51
+
52
+ Common flags:
53
+
54
+ - `--format json|table|sarif` — output shape (default `table`)
55
+ - `--output FILE` — write to file (stdout is default)
56
+ - `--severity critical|high|medium|low` — show only findings at or above
57
+ - `--fail-on-severity SEVERITY` — exit non-zero when met (CI-friendly)
58
+
59
+ ## Findings
60
+
61
+ ```bash
62
+ patchops findings list --status open --severity high
63
+ patchops findings get <finding-uuid>
64
+ ```
65
+
66
+ ## AI Repair
67
+
68
+ ```bash
69
+ patchops repair start <finding-uuid> --wait
70
+ patchops repair status <job-uuid>
71
+ patchops repair list --status completed
72
+ ```
73
+
74
+ ## SBOM
75
+
76
+ ```bash
77
+ # Emit CycloneDX 1.6 JSON from a lockfile
78
+ patchops sbom generate package-lock.json --output sbom.json
79
+
80
+ # Upload an SBOM for OSV vulnerability matching
81
+ patchops sbom upload sbom.json
82
+ ```
83
+
84
+ Supported lockfiles: `package-lock.json`, `package.json`, `requirements.txt`,
85
+ `Pipfile.lock`, `pom.xml`, `go.mod`, `Gemfile.lock`, `Cargo.lock`,
86
+ `composer.lock`.
87
+
88
+ ## Exit codes
89
+
90
+ - `0` — success
91
+ - `1` — general error (network, API, IO)
92
+ - `2` — usage error (bad argument, missing auth)
93
+ - `10-13` — `--fail-on-severity` threshold hit (low / medium / high / critical)
94
+
95
+ ## License
96
+
97
+ MIT
@@ -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())
@@ -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"]