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,147 @@
1
+ """MCP 설정 감사의 서버 분석 — 명시적으로 켰을 때만, 비밀값은 가린 뒤 (ISSUE-042, 2026-11-23).
2
+
3
+ 예전엔 로컬 분석 엔진(backend 코드)을 import 하지 못하면 **묻지 않고** 설정 원문 전체를
4
+ `PATCHOPS_BASE_URL`(기본 patchguard.ai)로 보냈다. MCP 설정의 env·headers·args 에는 API 키·DB 접속
5
+ 정보가 들어 있는 경우가 많다. 이제는:
6
+
7
+ - 서버 분석은 `--remote` 또는 `PATCHOPS_MCP_REMOTE=1` 일 때만.
8
+ - 보내기 전에 로컬에서 가린다 — 이름이 비밀처럼 보이는 env·header 값, `--token xxx`·`--api-key=xxx`
9
+ 같은 인자 값, 긴 토큰 모양 문자열, URL 의 사용자 정보·비밀 query 값.
10
+ 서버 규칙은 "비밀 이름의 env 에 값이 박혀 있는지(`${…}` 참조가 아닌지)" 를 보므로, 값은
11
+ `<redacted>` 로 바꾸고 `${…}` 참조는 그대로 둬서 판정은 같다.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import copy
16
+ import json
17
+ import os
18
+ import re
19
+ from typing import Any
20
+ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
21
+
22
+ REMOTE_ENV = "PATCHOPS_MCP_REMOTE"
23
+ REDACTED = "<redacted>"
24
+
25
+ _SECRET_NAME = re.compile(r"(?i)(token|api[_\-]?key|secret|passw(or)?d|pwd|credential|auth|bearer|cookie|session|private[_\-]?key|dsn|connection[_\-]?string)")
26
+ _SECRET_FLAG = re.compile(r"(?i)^--?[a-z0-9_\-]*(token|api[_\-]?key|secret|passw(or)?d|pwd|credential|auth|bearer|key)[a-z0-9_\-]*$")
27
+ _TOKEN_SHAPE = re.compile(r"^[A-Za-z0-9_\-\.+/=]{24,}$")
28
+ _KNOWN_PREFIX = re.compile(r"^(sk-|sk_|pk_live|rk_live|ghp_|gho_|ghs_|github_pat_|glpat-|xox[abpr]-|AKIA|AIza|eyJ)")
29
+
30
+
31
+ def remote_enabled(flag: bool = False) -> bool:
32
+ return flag or os.environ.get(REMOTE_ENV, "").strip().lower() in ("1", "true", "yes")
33
+
34
+
35
+ def _redact_value(v: str) -> str:
36
+ if not v or v.startswith("${"):
37
+ return v # 참조는 비밀값이 아니고, 서버 판정에도 필요
38
+ return REDACTED
39
+
40
+
41
+ def _looks_like_secret(s: str) -> bool:
42
+ if "://" in s or s.startswith(("/", "./", "../", "~")) or "\\" in s:
43
+ return False
44
+ return bool(_KNOWN_PREFIX.match(s) or _TOKEN_SHAPE.match(s) and re.search(r"\d", s) and re.search(r"[A-Za-z]", s))
45
+
46
+
47
+ def _redact_url(u: str) -> str:
48
+ try:
49
+ parts = urlsplit(u)
50
+ except ValueError:
51
+ return u
52
+ if not parts.scheme or not parts.netloc:
53
+ return u
54
+ netloc = parts.netloc
55
+ if "@" in netloc:
56
+ netloc = f"{REDACTED}@{netloc.rsplit('@', 1)[1]}"
57
+ query = parts.query
58
+ if query:
59
+ pairs = [(k, REDACTED if (_SECRET_NAME.search(k) or _looks_like_secret(v)) else v)
60
+ for k, v in parse_qsl(query, keep_blank_values=True)]
61
+ query = urlencode(pairs, safe="<>")
62
+ return urlunsplit((parts.scheme, netloc, parts.path, query, parts.fragment))
63
+
64
+
65
+ def _redact_args(args: list[Any]) -> list[Any]:
66
+ out: list[Any] = []
67
+ hide_next = False
68
+ for a in args:
69
+ if not isinstance(a, str):
70
+ out.append(a)
71
+ hide_next = False
72
+ continue
73
+ if hide_next:
74
+ out.append(_redact_value(a))
75
+ hide_next = False
76
+ continue
77
+ if a.startswith("-") and "=" in a:
78
+ flag, _, val = a.partition("=")
79
+ out.append(f"{flag}={_redact_value(val)}" if _SECRET_FLAG.match(flag) else f"{flag}={_redact_str(val)}")
80
+ continue
81
+ if _SECRET_FLAG.match(a):
82
+ out.append(a)
83
+ hide_next = True
84
+ continue
85
+ out.append(_redact_str(a))
86
+ return out
87
+
88
+
89
+ def _redact_str(s: str) -> str:
90
+ if "://" in s:
91
+ return _redact_url(s)
92
+ if _looks_like_secret(s):
93
+ return REDACTED
94
+ return s
95
+
96
+
97
+ def _redact_mapping(d: dict[str, Any], *, all_secret_names: bool) -> dict[str, Any]:
98
+ out: dict[str, Any] = {}
99
+ for k, v in d.items():
100
+ if isinstance(v, str):
101
+ out[k] = _redact_value(v) if (all_secret_names and _SECRET_NAME.search(str(k))) else _redact_str(v)
102
+ else:
103
+ out[k] = v
104
+ return out
105
+
106
+
107
+ def redact_mcp_config(cfg: dict[str, Any]) -> dict[str, Any]:
108
+ """서버로 보낼 사본 — 원본은 바꾸지 않는다."""
109
+ red = copy.deepcopy(cfg)
110
+ servers = red.get("mcpServers")
111
+ if not isinstance(servers, dict):
112
+ return red
113
+ for spec in servers.values():
114
+ if not isinstance(spec, dict):
115
+ continue
116
+ for key in ("env", "headers"):
117
+ if isinstance(spec.get(key), dict):
118
+ spec[key] = _redact_mapping(spec[key], all_secret_names=True)
119
+ if isinstance(spec.get("args"), list):
120
+ spec["args"] = _redact_args(spec["args"])
121
+ for key in ("url", "serverUrl", "endpoint"):
122
+ if isinstance(spec.get(key), str):
123
+ spec[key] = _redact_url(spec[key])
124
+ if isinstance(spec.get("command"), str):
125
+ spec["command"] = _redact_str(spec["command"]) if "://" in spec["command"] else spec["command"]
126
+ return red
127
+
128
+
129
+ LOCAL_ENGINE_MISSING = (
130
+ "로컬 분석 엔진이 없어 감사하지 않았어요. 서버에서 분석하려면 --remote (또는 PATCHOPS_MCP_REMOTE=1) — "
131
+ "비밀값은 가린 뒤 보냅니다. / Local engine unavailable; re-run with --remote to analyze on the server "
132
+ "(secret values are masked before upload)."
133
+ )
134
+
135
+
136
+ def audit_remote(cfg: dict[str, Any], *, timeout: float = 60.0) -> dict[str, Any]:
137
+ import httpx
138
+
139
+ base = os.environ.get("PATCHOPS_BASE_URL", "https://patchguard.ai").rstrip("/")
140
+ with httpx.Client(timeout=timeout) as client:
141
+ r = client.post(
142
+ f"{base}/api/mcp-audit/scan",
143
+ content=json.dumps(redact_mcp_config(cfg)).encode("utf-8"),
144
+ headers={"Content-Type": "application/json"},
145
+ )
146
+ r.raise_for_status()
147
+ return r.json()
@@ -0,0 +1 @@
1
+ """Shared utilities for the PatchOps CLI."""
@@ -0,0 +1,75 @@
1
+ """Exit codes and error helpers for the CLI.
2
+
3
+ Exit code contract:
4
+ 0 — success
5
+ 1 — general/runtime error (network, API, IO)
6
+ 2 — usage error (bad arguments, missing auth)
7
+ 10 — severity threshold hit (``--fail-on-severity low``)
8
+ 11 — severity threshold hit (medium)
9
+ 12 — severity threshold hit (high)
10
+ 13 — severity threshold hit (critical)
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import sys
15
+
16
+ import typer
17
+
18
+ EXIT_OK = 0
19
+ EXIT_ERROR = 1
20
+ EXIT_USAGE = 2
21
+
22
+ SEVERITY_EXIT_CODES: dict[str, int] = {
23
+ "low": 10,
24
+ "medium": 11,
25
+ "high": 12,
26
+ "critical": 13,
27
+ }
28
+
29
+ SEVERITY_ORDER: dict[str, int] = {
30
+ "low": 1,
31
+ "medium": 2,
32
+ "high": 3,
33
+ "critical": 4,
34
+ }
35
+
36
+
37
+ class CLIError(RuntimeError):
38
+ """Raised for expected runtime failures. Rendered as a single line."""
39
+
40
+ def __init__(self, message: str, *, exit_code: int = EXIT_ERROR) -> None:
41
+ super().__init__(message)
42
+ self.exit_code = exit_code
43
+
44
+
45
+ def fail(message: str, *, exit_code: int = EXIT_ERROR) -> "typer.Exit":
46
+ """Print `error: <message>` to stderr and return a typer.Exit.
47
+
48
+ Callers should ``raise fail(...)`` so that Typer unwinds cleanly.
49
+ """
50
+ print(f"error: {message}", file=sys.stderr)
51
+ return typer.Exit(code=exit_code)
52
+
53
+
54
+ def severity_exit_code(severity: str) -> int:
55
+ return SEVERITY_EXIT_CODES.get(severity.lower(), EXIT_ERROR)
56
+
57
+
58
+ def meets_threshold(found: str, threshold: str) -> bool:
59
+ """Return True if ``found`` is at least as severe as ``threshold``."""
60
+ return SEVERITY_ORDER.get(found.lower(), 0) >= SEVERITY_ORDER.get(
61
+ threshold.lower(), 0
62
+ )
63
+
64
+
65
+ __all__ = [
66
+ "CLIError",
67
+ "EXIT_ERROR",
68
+ "EXIT_OK",
69
+ "EXIT_USAGE",
70
+ "SEVERITY_EXIT_CODES",
71
+ "SEVERITY_ORDER",
72
+ "fail",
73
+ "meets_threshold",
74
+ "severity_exit_code",
75
+ ]
@@ -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,31 @@
1
+ patchops_cli/__init__.py,sha256=VaNk-cvrizorXRkPpSh6ZVnMUEEUO-CgZyDhtiszrDo,153
2
+ patchops_cli/__main__.py,sha256=All8fsgPmLy_-YgGjeMLUh330apiRx_DDRDgWwW8-PM,230
3
+ patchops_cli/client.py,sha256=prqdlznW8lvUlLAmJf2iD4q0zjhF1ROhB-v46YewVXk,13250
4
+ patchops_cli/config.py,sha256=-DzHj-A9qW4IELsFQCVUQWLcVra39f_oS-kX5ow7aGM,5953
5
+ patchops_cli/legacy.py,sha256=buFkbyO1lTxFVcGx_UnBjbRuzwt_c23J8fY9NknaaaM,5135
6
+ patchops_cli/main.py,sha256=47bIE9kh-NxOLoFmlKaBPtrkmRkGEoU3UqsNQS-a8mo,3453
7
+ patchops_cli/mcp_remote.py,sha256=KL1WsCJUDqaxNdmhfE_7DSr-5762WWQnf19pjDbiyGM,5766
8
+ patchops_cli/commands/__init__.py,sha256=n5YTR0PubVHGe6u8Dgmxafb4_e49WOduU3ykkJAN7WA,54
9
+ patchops_cli/commands/auth.py,sha256=5OAoqxExrI1lszufSToXqlZfCKnaitXb2jPn4KvNgMI,3464
10
+ patchops_cli/commands/findings.py,sha256=0HdEUUbE1lATgde99-8BbMBkHpXGVbMFgAhOWnnWkfg,3337
11
+ patchops_cli/commands/free_scan.py,sha256=PPJKZLPO9h822Lo_wzCJjN1dEWwADhQu0zbJJUp-LDA,5658
12
+ patchops_cli/commands/mcp_audit.py,sha256=5yYnaMzOt3JTcJSAQqSoqVT5lQUA-4DFLk1SpNU_sI4,9033
13
+ patchops_cli/commands/mcp_watch.py,sha256=uMbXvYXcltzJeB3wJX25KgWlIGciGkDasZUdhidJwyc,8465
14
+ patchops_cli/commands/repair.py,sha256=7OYgVpl4zD-8vcbERV7BD9hT9c1t2gZxovfWkeBoJxY,8202
15
+ patchops_cli/commands/repo_scan.py,sha256=Pwow8QkQQ-6goxlI-yyWEtukwjPKmaFyLY3w4CIjeTA,4598
16
+ patchops_cli/commands/sbom.py,sha256=oG4t1L5ccgz2NcZtGzhrlIS5hZz0y2MGCAv5UKse6NA,11263
17
+ patchops_cli/commands/scan.py,sha256=lqYyo5nh5dpvmRv9QOLgpC_T2HLpJonI5r-3Qpxxp2U,17087
18
+ patchops_cli/commands/url_scan.py,sha256=F8M-JJPO6UhYvHfbcUCJqvkaOzewtXdvmlyYo91Ppgs,3562
19
+ patchops_cli/commands/v6.py,sha256=26aSLCKsgli2JuTpoJdChjBOuiVb1F7r9OCFoCMhDjY,5219
20
+ patchops_cli/formatters/__init__.py,sha256=VHhDiK3ioXEJSaYrKDwh5QPHs3UH_TlI7Xhnvik6Lcg,467
21
+ patchops_cli/formatters/json_fmt.py,sha256=KqINmWna95T0YL8qgoOXEfxdSjnjhGCqFdRLQOLkD_s,657
22
+ patchops_cli/formatters/sarif.py,sha256=3dwjsB5XTZIZP2iqUhMoD4WXfLf4PCAHUXm8T7XOM_Y,8148
23
+ patchops_cli/formatters/table.py,sha256=DXo5VZsiVJ23JAaz4ir16pQLgVNgIdANUjm9h98fANM,9555
24
+ patchops_cli/formatters/tree.py,sha256=Nu84ys4TH5-_QOAH446Hvlkdue1-QQTFcvJFXbP5vmw,6373
25
+ patchops_cli/utils/__init__.py,sha256=5bDLJZ_SkHa69sjDwLIWb_cZM5DY7Ce61LioGDih80E,46
26
+ patchops_cli/utils/errors.py,sha256=eBlWisEpforcgA0jjHP_aADMOyTsVGvsRE_xGHC8SGU,1873
27
+ patchops_guard-0.2.0.dist-info/METADATA,sha256=jebfgZUZAL0gJm32fxsuAk_04r5JOYz3oLu4oDXqsVw,3686
28
+ patchops_guard-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
29
+ patchops_guard-0.2.0.dist-info/entry_points.txt,sha256=A5_dSLovNChNOteiGc3l5_8mfJY2PnbbEcDUIUWIqA4,52
30
+ patchops_guard-0.2.0.dist-info/top_level.txt,sha256=4-RyWUgDaQFKHdfNolj4UvxfAWuN1w1VuAEsxnodIO0,13
31
+ patchops_guard-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ patchops = patchops_cli.main:main
@@ -0,0 +1 @@
1
+ patchops_cli