securebox-cli 0.1.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.
securebox_cli/main.py ADDED
@@ -0,0 +1,403 @@
1
+ """securebox: SecureBox's checks on your machine and in CI.
2
+
3
+ securebox scan [PATH] secrets, code rules and dependencies of a folder
4
+ securebox scan --staged only what is about to be committed (the pre-commit check)
5
+ securebox hook install run the staged check before every commit
6
+ securebox login store an organization API key (full rules, team decisions)
7
+ securebox link [PROJECT_ID] tie this repository to its SecureBox project
8
+ securebox ci start a SecureBox scan and fail on new serious findings
9
+
10
+ Exit codes: 0 nothing blocking, 1 blocking findings, 2 the check could not run.
11
+ """
12
+
13
+ import argparse
14
+ import contextlib
15
+ import getpass
16
+ import os
17
+ import re
18
+ import shutil
19
+ import subprocess
20
+ import sys
21
+ import tempfile
22
+ import time
23
+ from importlib import resources
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ from securebox_cli import __version__, config, hook, output, snapshot, tools
28
+ from securebox_cli.api import Api, ApiError
29
+ from securebox_cli.api import project_id as checked_id
30
+ from securebox_cli.scan import RANK, blocking, scan
31
+
32
+ FAIL_LEVELS = ("critical", "high", "medium", "low", "never")
33
+ RULES_VERSION = re.compile(r"^[0-9a-f]{8,64}$")
34
+ RULES_FILE = re.compile(r"^[A-Za-z0-9_-]{1,64}\.yml$")
35
+ MAX_RULE_FILES = 50
36
+ MAX_RULES_BYTES = 8 * 1024 * 1024
37
+ POLL_SECONDS = 10
38
+
39
+
40
+ def _err(message: str) -> None:
41
+ print(f"securebox: {output._plain(message)}", file=sys.stderr)
42
+
43
+
44
+ def _repo(path: Path) -> Path:
45
+ return snapshot.repo_root(path) or path
46
+
47
+
48
+ def _starter() -> Path:
49
+ return Path(str(resources.files("securebox_cli") / "rules" / "starter.yml"))
50
+
51
+
52
+ def _rule_set(folder: Path) -> list[Path]:
53
+ files = [f for f in sorted(folder.glob("*.yml")) if RULES_FILE.match(f.name) and f.is_file()]
54
+ return [f for f in files if not f.is_symlink()]
55
+
56
+
57
+ def _store_rules(cached: Path, data: Any) -> Path:
58
+ """Writes the server's rule files into cache/rules/own-<version> (new folders only, moved
59
+ into place whole). Anything malformed is refused: no name or version from the server is
60
+ ever used as a path as it is."""
61
+ if not isinstance(data, dict) or not isinstance(data.get("files"), list):
62
+ raise ValueError("unexpected answer")
63
+ version = str(data.get("version", ""))
64
+ if not RULES_VERSION.match(version):
65
+ raise ValueError("unexpected rules version")
66
+ files: dict[str, str] = {}
67
+ for item in data["files"][: MAX_RULE_FILES + 1]:
68
+ name, content = (item.get("name"), item.get("content")) if isinstance(item, dict) else (
69
+ None, None) # fmt: skip
70
+ if not isinstance(name, str) or not RULES_FILE.match(name) or not isinstance(content, str):
71
+ raise ValueError("unexpected rule file")
72
+ files[name] = content
73
+ if not files or len(files) > MAX_RULE_FILES or sum(map(len, files.values())) > MAX_RULES_BYTES:
74
+ raise ValueError("unexpected rule files")
75
+ folder = cached / f"own-{version}"
76
+ if not _rule_set(folder):
77
+ cached.mkdir(parents=True, exist_ok=True)
78
+ building = Path(tempfile.mkdtemp(prefix=".own-", dir=cached))
79
+ try:
80
+ for name, content in files.items():
81
+ (building / name).write_text(content, encoding="utf-8")
82
+ if folder.exists():
83
+ shutil.rmtree(folder, ignore_errors=True) # an incomplete earlier copy
84
+ os.replace(building, folder)
85
+ except OSError:
86
+ shutil.rmtree(building, ignore_errors=True)
87
+ if not _rule_set(folder): # another run may have put the same version in place
88
+ raise
89
+ tools._place(cached / "latest", folder.name.encode(), executable=False)
90
+ return folder
91
+
92
+
93
+ def _rules(api: Api | None, offline: bool) -> tuple[list[Path], str]:
94
+ """SecureBox's rules: the full set for a key (cached per version), else the starter set."""
95
+ cached = tools.cache_dir() / "rules"
96
+ if api is not None and not offline:
97
+ try:
98
+ folder = _store_rules(cached, api.rules())
99
+ return _rule_set(folder), "SecureBox rules"
100
+ except (ApiError, OSError, ValueError) as exc:
101
+ _err(f"could not fetch the rules ({exc}); using the last copy")
102
+ if api is not None:
103
+ with contextlib.suppress(OSError, UnicodeDecodeError):
104
+ name = (cached / "latest").read_text().strip()
105
+ if name.startswith("own-") and RULES_VERSION.match(name[4:]):
106
+ files = _rule_set(cached / name)
107
+ if files:
108
+ return files, "SecureBox rules (cached)"
109
+ return [_starter()], "starter rules"
110
+
111
+
112
+ def _fail_level(*choices: object) -> str:
113
+ for choice in choices:
114
+ if isinstance(choice, str) and choice in FAIL_LEVELS:
115
+ return choice
116
+ return "high"
117
+
118
+
119
+ def _settings(path: Path) -> config.Settings | None:
120
+ try:
121
+ return config.load(path)
122
+ except config.ConfigError as exc:
123
+ _err(str(exc))
124
+ return None
125
+
126
+
127
+ def cmd_scan(args: argparse.Namespace) -> int:
128
+ target = Path(args.path).resolve()
129
+ if not target.is_dir():
130
+ _err(f"{args.path} is not a folder")
131
+ return 2
132
+ settings = _settings(_repo(target))
133
+ if settings is None:
134
+ return 2
135
+ api = Api(settings.url, settings.api_key) if settings.api_key else None
136
+ rule_files, rules_label = _rules(api, args.offline)
137
+ project: dict[str, Any] | None = None
138
+ if api is not None and settings.project and not args.offline:
139
+ try:
140
+ project = api.project(settings.project)
141
+ except ApiError as exc:
142
+ _err(f"could not read the linked project ({exc}); scanning without its settings")
143
+ suppressed: set[str] = set()
144
+ fail_on = _fail_level(args.fail_on, (project or {}).get("fail_on"))
145
+ quiet = args.format != "text" or args.staged
146
+ progress = (lambda m: None) if quiet else (lambda m: print(m, file=sys.stderr))
147
+ if not quiet:
148
+ linked = f" · project {output._plain(project.get('name'))}" if project else ""
149
+ print(f"securebox {__version__} · {rules_label}{linked}", file=sys.stderr)
150
+ # The project's own rules go to a file of this run only (two runs never share one).
151
+ with tempfile.TemporaryDirectory(prefix="securebox-rules-") as tmp:
152
+ extra: list[Path] = []
153
+ if project:
154
+ items = project.get("suppressed")
155
+ suppressed = {str(f) for f in items} if isinstance(items, list) else set()
156
+ custom = project.get("custom_rules")
157
+ if isinstance(custom, str) and custom.strip():
158
+ extra.append(Path(tmp) / "custom.yml")
159
+ extra[0].write_text(custom, encoding="utf-8")
160
+ result = scan(target, rule_files + extra, staged=args.staged, use_path=args.use_path,
161
+ suppressed=suppressed, progress=progress) # fmt: skip
162
+ stop = blocking(result, fail_on)
163
+ text = None
164
+ if args.format == "json":
165
+ text = output.as_json(result, stop)
166
+ elif args.format == "sarif":
167
+ text = output.as_sarif(result)
168
+ if text is not None:
169
+ if args.output:
170
+ try:
171
+ Path(args.output).write_text(text, encoding="utf-8")
172
+ except OSError as exc:
173
+ _err(f"could not write {args.output}: {exc.strerror or exc}")
174
+ return 2
175
+ else:
176
+ print(text)
177
+ elif not args.staged or result.findings or result.errors:
178
+ output.text(result, stop)
179
+ if result.errors:
180
+ # A check that did not finish is never a pass: the commit or build stops (exit 2).
181
+ failed = ", ".join(result.errors)
182
+ _err(f"{failed} did not finish, so this is not a complete check"
183
+ + (" (skip once with `git commit --no-verify`)" if args.staged else "")) # fmt: skip
184
+ return 2
185
+ if args.staged and stop:
186
+ print("Commit stopped by SecureBox. Fix the findings above, or skip this check once "
187
+ "with `git commit --no-verify`.", file=sys.stderr) # fmt: skip
188
+ return 1 if stop else 0
189
+
190
+
191
+ def cmd_login(args: argparse.Namespace) -> int:
192
+ try:
193
+ url = config.check_url(args.url or os.environ.get("SECUREBOX_URL") or config.DEFAULT_URL)
194
+ except config.ConfigError as exc:
195
+ _err(str(exc))
196
+ return 2
197
+ key = (
198
+ args.key
199
+ or os.environ.get("SECUREBOX_API_KEY")
200
+ or getpass.getpass("Organization API key (Organization → Settings → API Keys): ")
201
+ )
202
+ key = key.strip()
203
+ if not re.fullmatch(r"sbk_[A-Za-z0-9_-]{20,100}", key):
204
+ _err("that does not look like a SecureBox API key (sbk_…)")
205
+ return 2
206
+ try:
207
+ projects = Api(url, key).projects()
208
+ except ApiError as exc:
209
+ _err(str(exc))
210
+ return 2
211
+ path = config.save(url, key)
212
+ print(f"Saved to {path} (readable by you only). The key reaches {len(projects)} projects.")
213
+ print("Link this repository with `securebox link` to use its project's rules and decisions.")
214
+ return 0
215
+
216
+
217
+ def cmd_link(args: argparse.Namespace) -> int:
218
+ repo = snapshot.repo_root(Path.cwd())
219
+ if repo is None:
220
+ _err("run this inside a git repository")
221
+ return 2
222
+ settings = _settings(repo)
223
+ if settings is None:
224
+ return 2
225
+ if not settings.api_key:
226
+ _err("run `securebox login` first")
227
+ return 2
228
+ api = Api(settings.url, settings.api_key)
229
+ try:
230
+ if not args.project:
231
+ for p in api.projects():
232
+ print(f"{output._plain(p.get('id'))} {output._plain(p.get('name'))}")
233
+ print("Run `securebox link <project id>`.")
234
+ return 0
235
+ project_id = checked_id(args.project)
236
+ project = api.project(project_id)
237
+ except ApiError as exc:
238
+ _err(str(exc))
239
+ return 2
240
+ config.git_config(repo, "securebox.project", project_id)
241
+ print(f"Linked {output._plain(repo.name)} to {output._plain(project.get('name'))}.")
242
+ return 0
243
+
244
+
245
+ def cmd_hook(args: argparse.Namespace) -> int:
246
+ repo = snapshot.repo_root(Path.cwd())
247
+ if repo is None:
248
+ _err("run this inside a git repository")
249
+ return 2
250
+ try:
251
+ if args.action == "install":
252
+ path = hook.install(repo, force=args.force)
253
+ print(f"Installed {path}: staged changes are checked before every commit.")
254
+ if shutil.which("securebox") is None:
255
+ print("Note: `securebox` is not on PATH in this shell; the hook needs it there "
256
+ "(commits stop with a message until it is).") # fmt: skip
257
+ else:
258
+ print("Removed the hook." if hook.uninstall(repo) else "No SecureBox hook found.")
259
+ except hook.HookError as exc:
260
+ _err(str(exc))
261
+ return 2
262
+ return 0
263
+
264
+
265
+ def _local_commit(repo: Path | None) -> str | None:
266
+ for name in ("GITHUB_SHA", "CI_COMMIT_SHA", "BITBUCKET_COMMIT", "BUILD_SOURCEVERSION"):
267
+ value = os.environ.get(name, "")
268
+ if re.fullmatch(r"[0-9a-f]{40}", value):
269
+ return value
270
+ if repo is None:
271
+ return None
272
+ try:
273
+ head = snapshot.git(repo, "rev-parse", "HEAD").decode().strip()
274
+ except (snapshot.SnapshotError, OSError, subprocess.TimeoutExpired, UnicodeDecodeError):
275
+ return None
276
+ return head if re.fullmatch(r"[0-9a-f]{40}", head) else None
277
+
278
+
279
+ def _start(api: Api, project_id: str, deadline: float) -> dict[str, Any]:
280
+ """Starts the scan; while another code scan of the project runs (say one started by the
281
+ push), waits for it and starts again."""
282
+ while True:
283
+ try:
284
+ return api.start_scan(project_id)
285
+ except ApiError as exc:
286
+ if exc.status not in (409, 429) or time.monotonic() > deadline:
287
+ raise
288
+ print("Another scan of this project is running; waiting for it…", file=sys.stderr)
289
+ time.sleep(POLL_SECONDS * 3)
290
+
291
+
292
+ def cmd_ci(args: argparse.Namespace) -> int:
293
+ repo = snapshot.repo_root(Path.cwd())
294
+ settings = _settings(repo or Path.cwd())
295
+ if settings is None:
296
+ return 2
297
+ project_ref = args.project or settings.project
298
+ if not settings.api_key or not project_ref:
299
+ _err("needs SECUREBOX_API_KEY and a project (--project, SECUREBOX_PROJECT or `link`)")
300
+ return 2
301
+ api = Api(settings.url, settings.api_key)
302
+ deadline = time.monotonic() + args.timeout
303
+ try:
304
+ project_id = checked_id(project_ref)
305
+ project = api.project(project_id)
306
+ fail_on = _fail_level(args.fail_on, project.get("fail_on"))
307
+ started = _start(api, project_id, deadline)
308
+ scan_id = str(started.get("id"))
309
+ print(f"Scan {output._plain(scan_id)} started on SecureBox: "
310
+ f"{output._plain(started.get('securebox_url', ''))}") # fmt: skip
311
+ state = started
312
+ while state.get("status") in ("queued", "running"):
313
+ if time.monotonic() > deadline:
314
+ _err("the scan did not finish in time (raise --timeout)")
315
+ return 2
316
+ time.sleep(POLL_SECONDS)
317
+ state = api.scan(scan_id)
318
+ if state.get("status") != "completed":
319
+ _err(f"the scan {state.get('status')}: {state.get('error_message') or ''}")
320
+ return 2
321
+ levels = [s for s in RANK if fail_on != "never" and RANK[s] <= RANK.get(fail_on, -1)]
322
+ query = {"scan_id": scan_id, "change": "new", "status": "open",
323
+ "severity": levels, "page_size": 100} # fmt: skip
324
+ new = api.findings(query) if levels else {"items": [], "total": 0}
325
+ except ApiError as exc:
326
+ _err(str(exc))
327
+ return 2
328
+ # SecureBox scans the project's branch as it is on the server, not this checkout.
329
+ scanned = str(state.get("commit_sha") or "")
330
+ local = _local_commit(repo)
331
+ branch = output._plain(state.get("branch") or "the project's branch")
332
+ if local and scanned and local != scanned:
333
+ print(f"Note: SecureBox scanned {branch} at {scanned[:7]}, not this checkout "
334
+ f"({local[:7]}): `ci` checks the project's branch (use `securebox scan` for this "
335
+ "checkout).", file=sys.stderr) # fmt: skip
336
+ items = new.get("items") or []
337
+ total_value = new.get("total")
338
+ total = total_value if isinstance(total_value, int) else len(items)
339
+ for item in items:
340
+ where = item.get("file_path") or item.get("url") or ""
341
+ print(f"✖ {output._plain(item.get('severity')).upper():<8} "
342
+ f"{output._plain(item.get('title'))} {output._plain(where)}") # fmt: skip
343
+ more = f" (first {len(items)} shown)" if total > len(items) else ""
344
+ print(f"{total} new findings at {fail_on} or above{more}.")
345
+ return 1 if total else 0
346
+
347
+
348
+ def parser() -> argparse.ArgumentParser:
349
+ top = argparse.ArgumentParser(prog="securebox", description=__doc__,
350
+ formatter_class=argparse.RawDescriptionHelpFormatter) # fmt: skip
351
+ top.add_argument("--version", action="version", version=f"securebox {__version__}")
352
+ sub = top.add_subparsers(dest="command", required=True)
353
+
354
+ s = sub.add_parser("scan", help="check a folder, or only the staged changes")
355
+ s.add_argument("path", nargs="?", default=".")
356
+ s.add_argument("--staged", action="store_true", help="only what is about to be committed")
357
+ s.add_argument("--format", choices=("text", "json", "sarif"), default="text")
358
+ s.add_argument("--output", help="write the json/sarif report to this file")
359
+ s.add_argument(
360
+ "--fail-on",
361
+ choices=FAIL_LEVELS,
362
+ help="lowest severity that fails (default: the project's, else high)",
363
+ )
364
+ s.add_argument(
365
+ "--use-path",
366
+ action="store_true",
367
+ help="use gitleaks/opengrep/trivy on PATH instead of downloading them",
368
+ )
369
+ s.add_argument("--offline", action="store_true", help="no calls to SecureBox")
370
+ s.set_defaults(func=cmd_scan)
371
+
372
+ lg = sub.add_parser("login", help="store an organization API key")
373
+ lg.add_argument("--url", help=f"SecureBox API URL (default {config.DEFAULT_URL})")
374
+ lg.add_argument("--key", help="the API key (prompted for if left out)")
375
+ lg.set_defaults(func=cmd_login)
376
+
377
+ ln = sub.add_parser("link", help="tie this repository to its SecureBox project")
378
+ ln.add_argument("project", nargs="?")
379
+ ln.set_defaults(func=cmd_link)
380
+
381
+ h = sub.add_parser("hook", help="install or remove the pre-commit hook")
382
+ h.add_argument("action", choices=("install", "uninstall"))
383
+ h.add_argument("--force", action="store_true", help="replace another tool's hook")
384
+ h.set_defaults(func=cmd_hook)
385
+
386
+ c = sub.add_parser("ci", help="start a SecureBox scan and fail on new serious findings")
387
+ c.add_argument("--project")
388
+ c.add_argument("--fail-on", choices=FAIL_LEVELS)
389
+ c.add_argument("--timeout", type=int, default=1800, help="seconds to wait (default 1800)")
390
+ c.set_defaults(func=cmd_ci)
391
+ return top
392
+
393
+
394
+ def main(argv: list[str] | None = None) -> int:
395
+ args = parser().parse_args(argv)
396
+ try:
397
+ return int(args.func(args))
398
+ except KeyboardInterrupt:
399
+ return 130
400
+
401
+
402
+ if __name__ == "__main__":
403
+ sys.exit(main())
@@ -0,0 +1,87 @@
1
+ """Results as text for people, JSON for scripts, or SARIF for code-scanning tools."""
2
+
3
+ import json
4
+ import sys
5
+ from typing import Any, TextIO
6
+ from urllib.parse import quote
7
+
8
+ from securebox_cli import __version__
9
+ from securebox_cli.scan import Finding, Result
10
+
11
+ COLORS = {"critical": "\033[31;1m", "high": "\033[31m", "medium": "\033[33m",
12
+ "low": "\033[34m", "info": "\033[90m"} # fmt: skip
13
+ RESET = "\033[0m"
14
+ SEVERITY_NAMES = ("critical", "high", "medium", "low", "info")
15
+ SARIF_LEVEL = {"critical": "error", "high": "error", "medium": "warning", "low": "note",
16
+ "info": "note"} # fmt: skip
17
+
18
+
19
+ def _plain(text: str | None) -> str:
20
+ """Repository text without control characters (no terminal escape tricks)."""
21
+ return "".join(ch if ch.isprintable() else "?" for ch in (text or ""))
22
+
23
+
24
+ def text(result: Result, blocking: list[Finding], out: TextIO | None = None,
25
+ color: bool | None = None) -> None: # fmt: skip
26
+ out = out or sys.stdout # looked up per call: redirections after import still apply
27
+ color = out.isatty() if color is None else color
28
+ for f in result.findings:
29
+ sev = f.severity.upper()
30
+ sev = f"{COLORS.get(f.severity, '')}{sev}{RESET}" if color else sev
31
+ where = _plain(f.path) + (f":{f.line}" if f.line else "") if f.path else ""
32
+ mark = "✖" if f in blocking else "•"
33
+ print(f"{mark} {sev:<8} {_plain(f.title)}", file=out)
34
+ detail = f"{f.tool} · {_plain(f.rule_id)}"
35
+ if f.fixed_version:
36
+ detail += f" · fixed in {_plain(f.fixed_version)}"
37
+ print(f" {where} ({detail})" if where else f" ({detail})", file=out)
38
+ for name, error in result.errors.items():
39
+ print(f"! {name} did not finish: {_plain(error)}", file=out)
40
+ for warning in result.warnings[:20]:
41
+ print(f"! {_plain(warning)}", file=out)
42
+ per = {s: sum(1 for f in result.findings if f.severity == s) for s in SEVERITY_NAMES}
43
+ counts = ", ".join(f"{n} {s}" for s, n in per.items() if n)
44
+ summary = f"{len(result.findings)} findings" + (f" ({counts})" if counts else "")
45
+ extra = []
46
+ if result.suppressed:
47
+ extra.append(f"{result.suppressed} closed in SecureBox as false positive or accepted risk")
48
+ if result.ignored:
49
+ extra.append(f"{result.ignored} ignored by .securebox.yml")
50
+ print(f"\n{summary}" + (f"; {'; '.join(extra)}" if extra else "") + ".", file=out)
51
+ if blocking:
52
+ secrets = sum(1 for f in blocking if f.category == "secret")
53
+ print(f"{len(blocking)} blocking" + (f" ({secrets} secrets: never commit them; remove "
54
+ "them and rotate)" if secrets else "") + ".", file=out) # fmt: skip
55
+
56
+
57
+ def as_json(result: Result, blocking: list[Finding]) -> str:
58
+ data = result.as_dict() | {"blocking": len(blocking), "version": __version__}
59
+ return json.dumps(data, indent=2)
60
+
61
+
62
+ def as_sarif(result: Result) -> str:
63
+ runs: dict[str, dict[str, Any]] = {}
64
+ for f in result.findings:
65
+ run = runs.setdefault(f.tool, {
66
+ "tool": {"driver": {"name": f"SecureBox CLI ({f.tool})", "version": __version__,
67
+ "rules": []}},
68
+ "results": [],
69
+ }) # fmt: skip
70
+ rules = run["tool"]["driver"]["rules"]
71
+ if not any(r["id"] == f.rule_id for r in rules):
72
+ rules.append({"id": f.rule_id, "shortDescription": {"text": f.title[:200]}})
73
+ location: dict[str, Any] = {"artifactLocation": {"uri": quote(f.path or ".", safe="/")}}
74
+ if f.line:
75
+ location["region"] = {"startLine": f.line}
76
+ item: dict[str, Any] = {
77
+ "ruleId": f.rule_id, "level": SARIF_LEVEL.get(f.severity, "warning"),
78
+ "message": {"text": f.title}, "locations": [{"physicalLocation": location}],
79
+ "properties": {"severity": f.severity},
80
+ } # fmt: skip
81
+ if f.fingerprint:
82
+ item["partialFingerprints"] = {"securebox/v1": f.fingerprint}
83
+ run["results"].append(item)
84
+ return json.dumps({
85
+ "$schema": "https://json.schemastore.org/sarif-2.1.0.json", "version": "2.1.0",
86
+ "runs": list(runs.values()),
87
+ }, indent=2) # fmt: skip