openfix-cli 0.4.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.
openfix/cli.py ADDED
@@ -0,0 +1,211 @@
1
+ """openfix command line."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from . import __version__
11
+ from .console import paint
12
+ from .engine import Engine, Options
13
+ from .ingest import UnsupportedFormat, load_files
14
+ from .policy import EXAMPLE_POLICY, load_policy
15
+ from .providers import ProviderError, describe_providers
16
+ from .receipt import verify_receipt
17
+ from .sandbox import SandboxUnavailable
18
+
19
+
20
+ def _rel(p: Path) -> str:
21
+ try:
22
+ return str(p.resolve().relative_to(Path.cwd().resolve()))
23
+ except ValueError:
24
+ return str(p)
25
+
26
+
27
+ def _table(rows: list[list[str]], header: list[str]) -> str:
28
+ widths = [max(len(str(r[i])) for r in [header, *rows]) for i in range(len(header))]
29
+ fmt = " ".join(f"{{:<{w}}}" for w in widths)
30
+ out = [fmt.format(*header), fmt.format(*["-" * w for w in widths])]
31
+ out += [fmt.format(*[str(c) for c in r]) for r in rows]
32
+ return "\n".join(out)
33
+
34
+
35
+ def cmd_findings(a: argparse.Namespace) -> int:
36
+ findings = load_files(a.reports)
37
+ if a.json:
38
+ print(
39
+ json.dumps(
40
+ {"openfix": "findings/v1", "findings": [f.model_dump(mode="json", exclude={"raw"}) for f in findings]},
41
+ indent=2,
42
+ )
43
+ )
44
+ return 0
45
+ rows = [
46
+ [
47
+ f.id,
48
+ f.severity.value,
49
+ f.category.value,
50
+ f.tool,
51
+ f.rule_id[-48:],
52
+ (f.location.path + (f":{f.location.start_line}" if f.location.start_line else ""))
53
+ if f.location
54
+ else (f.package.name if f.package else ""),
55
+ ]
56
+ for f in findings
57
+ ]
58
+ print(_table(rows, ["id", "severity", "category", "tool", "rule", "where"]))
59
+ print(f"\n{len(findings)} finding(s)")
60
+ return 0
61
+
62
+
63
+ def cmd_plan(a: argparse.Namespace) -> int:
64
+ policy, path = load_policy(a.policy, a.repo)
65
+ findings = load_files(a.reports)
66
+ engine = Engine(Path(a.repo), policy, Options(), path, log=lambda _m: None)
67
+ rows = []
68
+ for f, d in engine.plan(findings):
69
+ rows.append([f.id, d.action.value, f.severity.value, f.short()[:70], d.rule[:48]])
70
+ print(
71
+ f"policy: {path or 'built-in defaults'} author: {policy.models.author}"
72
+ f" reviewer: {policy.models.reviewer or '-'} require: {', '.join(policy.verify.require)}\n"
73
+ )
74
+ print(_table(rows, ["id", "action", "severity", "finding", "rule"]))
75
+ counts: dict[str, int] = {}
76
+ for r in rows:
77
+ counts[r[1]] = counts.get(r[1], 0) + 1
78
+ print("\n" + ", ".join(f"{v} {k}" for k, v in sorted(counts.items())))
79
+ return 0
80
+
81
+
82
+ def cmd_fix(a: argparse.Namespace) -> int:
83
+ policy, path = load_policy(a.policy, a.repo)
84
+ if a.require:
85
+ policy.verify.require = [x.strip() for x in a.require.split(",") if x.strip()]
86
+ for r in policy.rules:
87
+ r.require = None
88
+ findings = load_files(a.reports)
89
+ if a.only:
90
+ wanted = {x.strip() for x in a.only.split(",")}
91
+ findings = [f for f in findings if f.id in wanted or f.rule_id in wanted]
92
+ if not findings:
93
+ print(f"No findings match --only {a.only}", file=sys.stderr)
94
+ return 2
95
+ opts = Options(
96
+ out=Path(a.out) if a.out else None,
97
+ author=a.model,
98
+ reviewer=a.reviewer,
99
+ sandbox=a.sandbox,
100
+ open_prs=a.open_prs,
101
+ base_branch=a.base,
102
+ sign=a.sign,
103
+ dry_run=a.dry_run,
104
+ keep_worktrees=a.keep_worktrees,
105
+ max_findings=a.max,
106
+ )
107
+ engine = Engine(Path(a.repo), policy, opts, path)
108
+ outcomes = engine.run(findings)
109
+ by: dict[str, int] = {}
110
+ for o in outcomes:
111
+ by[o.status] = by.get(o.status, 0) + 1
112
+ counts = ", ".join(f"{v} {k}" for k, v in sorted(by.items()))
113
+ spent = f"tokens {engine.spent_tokens:,} cost ${engine.spent_usd:.2f}"
114
+ print(f"\n{paint(counts, 'bold', stream=sys.stdout)} {spent} results {_rel(engine.out)}")
115
+ if a.fail_on_unfixed and any(o.status not in ("verified", "skipped") for o in outcomes):
116
+ return 1
117
+ return 0
118
+
119
+
120
+ def cmd_init(a: argparse.Namespace) -> int:
121
+ target = Path(a.path)
122
+ if target.exists() and not a.force:
123
+ print(f"{target} already exists (use --force to overwrite)", file=sys.stderr)
124
+ return 1
125
+ target.write_text(EXAMPLE_POLICY, encoding="utf-8")
126
+ print(f"wrote {target}")
127
+ return 0
128
+
129
+
130
+ def cmd_providers(_a: argparse.Namespace) -> int:
131
+ rows = [[r["provider"], r["example"], r["sdk"], r["credentials"]] for r in describe_providers()]
132
+ print(_table(rows, ["provider", "example --model", "sdk", "credentials"]))
133
+ return 0
134
+
135
+
136
+ def cmd_receipt_verify(a: argparse.Namespace) -> int:
137
+ rows = verify_receipt(Path(a.path), Path(a.repo) if a.repo else None)
138
+ for name, ok, detail in rows:
139
+ print(f"{'ok ' if ok else 'FAIL'} {name:<24} {detail}")
140
+ return 0 if all(ok for _, ok, _ in rows) else 1
141
+
142
+
143
+ def build_parser() -> argparse.ArgumentParser:
144
+ p = argparse.ArgumentParser(
145
+ prog="openfix", description="Model-agnostic security remediation. Every fix ships with proof."
146
+ )
147
+ p.add_argument("--version", action="version", version=f"openfix {__version__}")
148
+ sub = p.add_subparsers(dest="cmd", required=True)
149
+
150
+ s = sub.add_parser("findings", help="normalise scanner reports and list the findings")
151
+ s.add_argument("reports", nargs="+")
152
+ s.add_argument("--json", action="store_true", help="emit OpenFix findings JSON")
153
+ s.set_defaults(fn=cmd_findings)
154
+
155
+ s = sub.add_parser("plan", help="show what the policy will do with each finding (no model calls)")
156
+ s.add_argument("reports", nargs="+")
157
+ s.add_argument("--repo", default=".")
158
+ s.add_argument("--policy")
159
+ s.set_defaults(fn=cmd_plan)
160
+
161
+ s = sub.add_parser("fix", help="fix findings, verify each fix, write receipts, optionally open PRs")
162
+ s.add_argument("reports", nargs="+", help="SARIF / scanner JSON files")
163
+ s.add_argument("--repo", default=".", help="git repository the findings refer to (default: .)")
164
+ s.add_argument("--policy", help="policy file (default: openfix.yaml in the repo, else built-in)")
165
+ s.add_argument("--model", help="author model as provider:model, overrides policy (e.g. openai:gpt-5)")
166
+ s.add_argument("--reviewer", help="reviewer model as provider:model")
167
+ s.add_argument(
168
+ "--require", help="comma-separated required checks, overrides policy (rescan,tests,regression_test,review)"
169
+ )
170
+ s.add_argument("--only", help="comma-separated finding ids or rule ids")
171
+ s.add_argument("--max", type=int, help="attempt at most N findings")
172
+ s.add_argument("--sandbox", choices=["auto", "docker", "local"])
173
+ s.add_argument("--open-prs", action="store_true", help="open a draft PR for each verified autofix")
174
+ s.add_argument("--base", help="PR base branch (default: repository default branch)")
175
+ s.add_argument("--sign", action="store_true", help="sign receipts with cosign (Sigstore)")
176
+ s.add_argument("--out", help="output directory (default: .openfix/runs/<timestamp>)")
177
+ s.add_argument("--dry-run", action="store_true")
178
+ s.add_argument("--keep-worktrees", action="store_true", help=argparse.SUPPRESS)
179
+ s.add_argument("--fail-on-unfixed", action="store_true", help="exit 1 unless every attempted fix verified")
180
+ s.set_defaults(fn=cmd_fix)
181
+
182
+ s = sub.add_parser("init", help="write a starter openfix.yaml")
183
+ s.add_argument("path", nargs="?", default="openfix.yaml")
184
+ s.add_argument("--force", action="store_true")
185
+ s.set_defaults(fn=cmd_init)
186
+
187
+ s = sub.add_parser("providers", help="list supported model providers and credential status")
188
+ s.set_defaults(fn=cmd_providers)
189
+
190
+ s = sub.add_parser("receipt", help="work with fix receipts")
191
+ rs = s.add_subparsers(dest="receipt_cmd", required=True)
192
+ v = rs.add_parser("verify", help="check a receipt's digests and that its patch applies")
193
+ v.add_argument("path", help="receipt directory or receipt.json")
194
+ v.add_argument("--repo", help="repository to check the patch against")
195
+ v.set_defaults(fn=cmd_receipt_verify)
196
+ return p
197
+
198
+
199
+ def main(argv: list[str] | None = None) -> int:
200
+ args = build_parser().parse_args(argv)
201
+ try:
202
+ return int(args.fn(args) or 0)
203
+ except (UnsupportedFormat, ProviderError, SandboxUnavailable, FileNotFoundError, ValueError) as exc:
204
+ print(f"openfix: {exc}", file=sys.stderr)
205
+ return 2
206
+ except KeyboardInterrupt:
207
+ return 130
208
+
209
+
210
+ if __name__ == "__main__":
211
+ sys.exit(main())
openfix/console.py ADDED
@@ -0,0 +1,68 @@
1
+ """Terminal output: colour when writing to a terminal, plain text otherwise (and with NO_COLOR)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+ from typing import TextIO
8
+
9
+ from .findings import Finding
10
+
11
+ _CODES = {"bold": "1", "dim": "2", "red": "31", "green": "32", "yellow": "33", "magenta": "35"}
12
+ _TOOLS = {"snykcode": "Snyk Code", "snyk open source": "Snyk Open Source", "semgrep oss": "Semgrep"}
13
+ _SEVERITY = {"critical": "red", "high": "red", "medium": "yellow", "low": "dim", "info": "dim"}
14
+ _GLYPH = {"passed": ("✔", "green"), "failed": ("✘", "red")}
15
+ _STATUS = {"verified": "green", "skipped": "dim", "unverified": "yellow"}
16
+
17
+
18
+ def color_enabled(stream: TextIO) -> bool:
19
+ if os.environ.get("NO_COLOR"):
20
+ return False
21
+ if os.environ.get("FORCE_COLOR"):
22
+ return True
23
+ return bool(getattr(stream, "isatty", lambda: False)())
24
+
25
+
26
+ def paint(text: str, *styles: str, stream: TextIO | None = None) -> str:
27
+ if not styles or not color_enabled(stream or sys.stderr):
28
+ return text
29
+ return "\033[" + ";".join(_CODES[s] for s in styles) + "m" + text + "\033[0m"
30
+
31
+
32
+ def tool_label(tool: str) -> str:
33
+ return _TOOLS.get(tool.lower(), tool)
34
+
35
+
36
+ def finding_line(f: Finding) -> str:
37
+ """One line per finding: scanner, severity, what it is, where."""
38
+ what = f.display_title()
39
+ where = ""
40
+ if f.location:
41
+ where = f.location.path + (f":{f.location.start_line}" if f.location.start_line else "")
42
+ elif f.package:
43
+ where = f"{f.package.name}@{f.package.version or '?'}"
44
+ sev = f.severity.value
45
+ return " ".join(
46
+ x
47
+ for x in (
48
+ "→ " + paint(f"{tool_label(f.tool):<9}", "bold"),
49
+ paint(f"{sev:<6}", _SEVERITY.get(sev, "dim")),
50
+ what,
51
+ paint(where, "dim"),
52
+ )
53
+ if x
54
+ )
55
+
56
+
57
+ def result_line(status: str, detail: str, checks: list[tuple[str, str]], pr_url: str | None = None) -> str:
58
+ """The checks that ran, then the outcome; the detail is shown when the fix did not verify."""
59
+ parts = []
60
+ for name, st in checks:
61
+ glyph, color = _GLYPH.get(st, ("·", "dim"))
62
+ parts.append(paint(f"{glyph} {name.replace('_', ' ')}", color))
63
+ line = " " + " ".join(parts + [paint(f"→ {status}", "bold", _STATUS.get(status, "red"))])
64
+ if status != "verified" and detail:
65
+ line += "\n " + paint(detail, "dim")
66
+ if pr_url:
67
+ line += "\n " + paint("draft PR", "dim") + f" {pr_url}"
68
+ return line
openfix/deps.py ADDED
@@ -0,0 +1,112 @@
1
+ """Deterministic dependency upgrades. No model is involved when a direct dependency can simply be bumped.
2
+
3
+ Supported manifests: package.json (npm/yarn/pnpm), requirements*.txt (pip). Anything else - transitive
4
+ dependencies, other ecosystems, upgrades needing code changes - goes to the agent.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+
14
+ from .findings import Finding
15
+
16
+
17
+ def _vkey(v: str) -> tuple:
18
+ parts = re.split(r"[.\-+]", v.strip().lstrip("v=^~<>"))
19
+ key: list[tuple[int, int | str]] = []
20
+ for p in parts:
21
+ key.append((0, int(p)) if p.isdigit() else (1, p))
22
+ return tuple(key)
23
+
24
+
25
+ def choose_fixed_version(current: str | None, fixed: list[str]) -> str | None:
26
+ """Lowest fixed version above ``current``, preferring one in the same major version."""
27
+ cands = sorted({f.strip().lstrip("v=^~<>") for f in fixed if f and re.match(r"^[v=^~<>]*\d", f.strip())}, key=_vkey)
28
+ if not cands:
29
+ return None
30
+ if current:
31
+ cur = current.strip().lstrip("v=^~<>")
32
+ above = [c for c in cands if _vkey(c) > _vkey(cur)]
33
+ major = cur.split(".")[0]
34
+ same_major = [c for c in above if c.split(".")[0] == major]
35
+ picked = same_major or above
36
+ return picked[0] if picked else None
37
+ return cands[0]
38
+
39
+
40
+ @dataclass
41
+ class DepFix:
42
+ manifest: str
43
+ package: str
44
+ old: str
45
+ new: str
46
+ lockfile_note: str | None = None
47
+
48
+
49
+ def try_bump(work: Path, f: Finding) -> DepFix | None:
50
+ pkg = f.package
51
+ if not pkg or not pkg.name:
52
+ return None
53
+ target = choose_fixed_version(pkg.version, pkg.fixed_versions)
54
+ if not target:
55
+ return None
56
+ manifests = [pkg.manifest] if pkg.manifest else []
57
+ eco = (pkg.ecosystem or "").lower()
58
+ if not manifests:
59
+ manifests = ["package.json"] if eco in ("npm", "yarn", "pnpm", "node") else ["requirements.txt"]
60
+ for m in manifests:
61
+ path = work / m
62
+ if not path.is_file():
63
+ continue
64
+ if path.name == "package.json":
65
+ return _bump_npm(path, m, pkg.name, target, work)
66
+ if path.name.startswith("requirements") and path.suffix == ".txt":
67
+ return _bump_pip(path, m, pkg.name, target)
68
+ return None
69
+
70
+
71
+ def _bump_npm(path: Path, rel: str, name: str, target: str, work: Path) -> DepFix | None:
72
+ text = path.read_text(encoding="utf-8")
73
+ data = json.loads(text)
74
+ for section in ("dependencies", "devDependencies", "optionalDependencies", "peerDependencies"):
75
+ spec = (data.get(section) or {}).get(name)
76
+ if not isinstance(spec, str):
77
+ continue
78
+ m = re.match(r"^(\^|~|>=|=)?\s*v?(\d[\w.\-+]*)$", spec.strip())
79
+ if not m:
80
+ return None # ranges, tags, git URLs: leave to the agent
81
+ prefix = m.group(1) or ""
82
+ if _vkey(m.group(2)) >= _vkey(target):
83
+ return None
84
+ new_spec = f"{prefix}{target}"
85
+ # Edit textually so formatting and key order are preserved.
86
+ pattern = re.compile(r'("' + re.escape(name) + r'"\s*:\s*")' + re.escape(spec) + '"')
87
+ new_text, n = pattern.subn(r"\g<1>" + new_spec.replace("\\", "\\\\") + '"', text, count=1)
88
+ if n != 1:
89
+ return None
90
+ path.write_text(new_text, encoding="utf-8")
91
+ note = None
92
+ for lock in ("package-lock.json", "yarn.lock", "pnpm-lock.yaml"):
93
+ if (path.parent / lock).exists():
94
+ note = f"{lock} must be regenerated (e.g. npm install --package-lock-only)"
95
+ return DepFix(rel, name, spec, new_spec, note)
96
+ return None
97
+
98
+
99
+ def _bump_pip(path: Path, rel: str, name: str, target: str) -> DepFix | None:
100
+ lines = path.read_text(encoding="utf-8").splitlines(keepends=True)
101
+ norm = re.sub(r"[-_.]+", "-", name).lower()
102
+ for i, line in enumerate(lines):
103
+ m = re.match(r"^(\s*)([A-Za-z0-9_.\-]+)(\[[^\]]*\])?\s*(==|>=|~=)\s*([\w.\-+]+)(.*)$", line.rstrip("\n"))
104
+ if not m or re.sub(r"[-_.]+", "-", m.group(2)).lower() != norm:
105
+ continue
106
+ if _vkey(m.group(5)) >= _vkey(target):
107
+ return None
108
+ old = f"{m.group(4)}{m.group(5)}"
109
+ lines[i] = f"{m.group(1)}{m.group(2)}{m.group(3) or ''}{m.group(4)}{target}{m.group(6)}\n"
110
+ path.write_text("".join(lines), encoding="utf-8")
111
+ return DepFix(rel, name, old, f"{m.group(4)}{target}")
112
+ return None