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.
@@ -0,0 +1,3 @@
1
+ """securebox: SecureBox's checks on your machine and in CI."""
2
+
3
+ __version__ = "0.1.0"
securebox_cli/api.py ADDED
@@ -0,0 +1,86 @@
1
+ """The SecureBox integration API (/v1) with an organization API key."""
2
+
3
+ import uuid
4
+ from typing import Any
5
+
6
+ import httpx
7
+
8
+ from securebox_cli import __version__
9
+
10
+
11
+ class ApiError(Exception):
12
+ """A failed call; the message is safe to show."""
13
+
14
+ def __init__(self, message: str, status: int | None = None) -> None:
15
+ super().__init__(message)
16
+ self.status = status
17
+
18
+
19
+ def _plain(text: object) -> str:
20
+ """Server text without control characters (no terminal escapes), one line, ≤300 chars."""
21
+ return "".join(c if c.isprintable() else " " for c in str(text))[:300]
22
+
23
+
24
+ def project_id(value: str) -> str:
25
+ """A project id is a UUID: never a path piece taken as is."""
26
+ try:
27
+ return str(uuid.UUID(value))
28
+ except ValueError as exc:
29
+ raise ApiError(
30
+ "A project id looks like 0b6f…-…: run `securebox link` to pick one."
31
+ ) from exc
32
+
33
+
34
+ project_id_ = project_id # the methods' parameter shadows the name
35
+
36
+
37
+ class Api:
38
+ def __init__(self, url: str, api_key: str, client: httpx.Client | None = None) -> None:
39
+ self.base = url.rstrip("/") + "/v1"
40
+ self.http = client or httpx.Client(timeout=30, follow_redirects=False)
41
+ self.headers = {"Authorization": f"Bearer {api_key}",
42
+ "User-Agent": f"securebox-cli/{__version__}"} # fmt: skip
43
+
44
+ def _call(self, method: str, path: str, **kwargs: Any) -> Any:
45
+ try:
46
+ response = self.http.request(method, self.base + path, headers=self.headers, **kwargs)
47
+ except httpx.HTTPError as exc:
48
+ raise ApiError(f"Could not reach SecureBox ({type(exc).__name__}).") from exc
49
+ if response.status_code == 401:
50
+ raise ApiError("SecureBox refused the API key (run `securebox login` again).", 401)
51
+ if response.status_code >= 400:
52
+ try:
53
+ body = response.json()
54
+ detail = body.get("detail") if isinstance(body, dict) else None
55
+ except ValueError:
56
+ detail = None
57
+ message = _plain(detail) if isinstance(detail, str) else "error"
58
+ raise ApiError(f"SecureBox answered {response.status_code}: {message}",
59
+ response.status_code) # fmt: skip
60
+ if 300 <= response.status_code < 400:
61
+ raise ApiError(f"SecureBox answered with a redirect ({response.status_code}): check "
62
+ "the URL (it should end in /api).", response.status_code) # fmt: skip
63
+ try:
64
+ return response.json() if response.content else None
65
+ except ValueError as exc:
66
+ raise ApiError("SecureBox's answer was not JSON: check the URL.") from exc
67
+
68
+ def rules(self) -> dict[str, Any]:
69
+ return dict(self._call("GET", "/cli/rules"))
70
+
71
+ def project(self, project_id: str) -> dict[str, Any]:
72
+ return dict(self._call("GET", f"/projects/{project_id_(project_id)}/cli"))
73
+
74
+ def projects(self) -> list[dict[str, Any]]:
75
+ data = self._call("GET", "/projects")
76
+ return list(data.get("items", data) if isinstance(data, dict) else data)
77
+
78
+ def start_scan(self, project_id: str) -> dict[str, Any]:
79
+ path = f"/projects/{project_id_(project_id)}/scans"
80
+ return dict(self._call("POST", path, json={"type": "sast"}))
81
+
82
+ def scan(self, scan_id: str) -> dict[str, Any]:
83
+ return dict(self._call("GET", f"/scans/{project_id_(scan_id)}"))
84
+
85
+ def findings(self, params: dict[str, Any]) -> dict[str, Any]:
86
+ return dict(self._call("GET", "/findings", params=params))
@@ -0,0 +1,85 @@
1
+ """Where the CLI keeps its settings: the server URL and the organization API key in the user's
2
+ config file (owner-only permissions), the linked project in the repository's git config
3
+ (`securebox.project`). SECUREBOX_URL / SECUREBOX_API_KEY / SECUREBOX_PROJECT win (CI)."""
4
+
5
+ import json
6
+ import os
7
+ import platform
8
+ import subprocess
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+ from urllib.parse import urlsplit
12
+
13
+ DEFAULT_URL = "https://securebox.gtools.in/api"
14
+
15
+
16
+ @dataclass
17
+ class Settings:
18
+ url: str
19
+ api_key: str | None
20
+ project: str | None
21
+
22
+
23
+ def config_file() -> Path:
24
+ if platform.system() == "Windows":
25
+ return Path(os.environ.get("APPDATA", Path.home())) / "securebox" / "config.json"
26
+ base = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
27
+ return Path(base) / "securebox" / "config.json"
28
+
29
+
30
+ def _stored() -> dict[str, str]:
31
+ try:
32
+ data = json.loads(config_file().read_text())
33
+ except (OSError, ValueError):
34
+ return {}
35
+ return (
36
+ {k: str(v) for k, v in data.items() if isinstance(v, str)} if isinstance(data, dict) else {}
37
+ )
38
+
39
+
40
+ class ConfigError(ValueError):
41
+ """A setting that cannot be used; the message is safe to show."""
42
+
43
+
44
+ def check_url(url: str) -> str:
45
+ """https only (the API key travels in a header), except a server on this machine."""
46
+ parts = urlsplit(url.strip())
47
+ local = parts.hostname in ("localhost", "127.0.0.1", "::1")
48
+ if parts.scheme != "https" and not (parts.scheme == "http" and local):
49
+ raise ConfigError("The SecureBox URL must start with https:// (the API key is sent).")
50
+ if not parts.hostname or parts.username or parts.password or parts.query or parts.fragment:
51
+ raise ConfigError("Use the SecureBox API URL, such as https://securebox.example/api.")
52
+ return url.strip().rstrip("/")
53
+
54
+
55
+ def save(url: str, api_key: str) -> Path:
56
+ path = config_file()
57
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
58
+ if os.name != "nt":
59
+ os.chmod(path.parent, 0o700)
60
+ flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0)
61
+ fd = os.open(path, flags, 0o600)
62
+ if os.name != "nt":
63
+ os.fchmod(fd, 0o600) # also when the file already existed with wider permissions
64
+ with os.fdopen(fd, "w") as handle:
65
+ json.dump({"url": url, "api_key": api_key}, handle)
66
+ return path
67
+
68
+
69
+ def git_config(repo: Path, key: str, value: str | None = None) -> str | None:
70
+ """Read (or, with value, set) a key of the repository's own git config."""
71
+ from securebox_cli.snapshot import git_env
72
+
73
+ args = ["git", "-C", str(repo), "config", "--local", key] + ([value] if value else [])
74
+ result = subprocess.run(args, capture_output=True, text=True, check=False, env=git_env())
75
+ if result.returncode != 0 or value is not None:
76
+ return None
77
+ return result.stdout.strip() or None
78
+
79
+
80
+ def load(repo: Path) -> Settings:
81
+ stored = _stored()
82
+ url = check_url(os.environ.get("SECUREBOX_URL") or stored.get("url") or DEFAULT_URL)
83
+ key = os.environ.get("SECUREBOX_API_KEY") or stored.get("api_key")
84
+ project = os.environ.get("SECUREBOX_PROJECT") or git_config(repo, "securebox.project")
85
+ return Settings(url=url.rstrip("/"), api_key=key, project=project)
securebox_cli/hook.py ADDED
@@ -0,0 +1,78 @@
1
+ """The pre-commit hook: `securebox scan --staged` before every commit."""
2
+
3
+ import stat
4
+ import subprocess
5
+ from pathlib import Path
6
+
7
+ from securebox_cli.snapshot import git_env
8
+
9
+ MARKER = "# securebox pre-commit hook"
10
+ HOOK = f"""#!/bin/sh
11
+ {MARKER}: checks the staged changes for secrets and serious issues.
12
+ # Skip once with: git commit --no-verify
13
+ if ! command -v securebox >/dev/null 2>&1; then
14
+ echo "SecureBox: the securebox command is not on PATH (pip install securebox-cli)," >&2
15
+ echo "so the staged changes were not checked. Skip once with: git commit --no-verify" >&2
16
+ exit 1
17
+ fi
18
+ exec securebox scan --staged
19
+ """
20
+
21
+
22
+ class HookError(Exception):
23
+ pass
24
+
25
+
26
+ def _git(repo: Path, *args: str) -> str:
27
+ out = subprocess.run(["git", "-C", str(repo), *args], capture_output=True, text=True,
28
+ check=False, env=git_env(hooks_path=True)) # fmt: skip
29
+ if out.returncode != 0:
30
+ raise HookError("Not a git repository.")
31
+ return out.stdout.strip()
32
+
33
+
34
+ def hooks_dir(repo: Path) -> Path:
35
+ path = Path(_git(repo, "rev-parse", "--git-path", "hooks"))
36
+ return path if path.is_absolute() else repo / path
37
+
38
+
39
+ def _shared(repo: Path, hooks: Path) -> bool:
40
+ """A hooks folder outside this repository's git folder (core.hooksPath, often global)."""
41
+ git_dir = Path(_git(repo, "rev-parse", "--absolute-git-dir")).resolve()
42
+ return not hooks.resolve().is_relative_to(git_dir) and not hooks.resolve().is_relative_to(
43
+ repo.resolve()
44
+ )
45
+
46
+
47
+ def install(repo: Path, force: bool = False) -> Path:
48
+ hooks = hooks_dir(repo)
49
+ target = hooks / "pre-commit"
50
+ if _shared(repo, hooks) and not force:
51
+ raise HookError(
52
+ f"Hooks for this repository come from {hooks} (core.hooksPath), which other "
53
+ "repositories may share. Add `securebox scan --staged` there yourself, or run with "
54
+ "--force to install into it."
55
+ )
56
+ if target.is_symlink():
57
+ if not force:
58
+ raise HookError(f"{target} is a link to another file; run with --force to replace "
59
+ "the link (its target is left as it is).") # fmt: skip
60
+ target.unlink()
61
+ elif target.exists() and target.read_text(errors="replace") != HOOK and not force:
62
+ raise HookError(
63
+ f"{target} already exists (another tool's hook). Add `securebox scan --staged` to it, "
64
+ "or run with --force to replace it."
65
+ )
66
+ target.parent.mkdir(parents=True, exist_ok=True)
67
+ target.write_text(HOOK)
68
+ target.chmod(target.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
69
+ return target
70
+
71
+
72
+ def uninstall(repo: Path) -> bool:
73
+ """Removes the hook only when it is exactly the one `install` wrote."""
74
+ target = hooks_dir(repo) / "pre-commit"
75
+ if not target.is_symlink() and target.is_file() and target.read_text(errors="replace") == HOOK:
76
+ target.unlink()
77
+ return True
78
+ return False
@@ -0,0 +1,141 @@
1
+ """The repository's .securebox.yml (`ignore.paths` and `ignore.rules`), matched exactly as
2
+ the SecureBox server does (backend app/services/repo_config.py). Secrets are never ignored."""
3
+
4
+ import fnmatch
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ import yaml
10
+
11
+
12
+ @dataclass
13
+ class Ignore:
14
+ paths: list[str] = field(default_factory=list)
15
+ rules: list[dict[str, Any]] = field(default_factory=list)
16
+ error: str | None = None
17
+
18
+
19
+ MAX_BYTES = 64 * 1024
20
+ MAX_ENTRIES = 200
21
+ TOOLS = {"semgrep", "gitleaks", "trivy", "zap", "nuclei", "access_review", "access_map",
22
+ "backend", "access_check", "malware"} # fmt: skip
23
+
24
+
25
+ class Invalid(ValueError):
26
+ pass
27
+
28
+
29
+ def _pattern(value: object, what: str) -> str:
30
+ if not isinstance(value, str) or not value.strip() or len(value.strip()) > 300:
31
+ raise Invalid(f"{what}: a pattern of 1 to 300 characters is needed.")
32
+ if value.strip().startswith("!"):
33
+ raise Invalid(f"'{value.strip()[:100]}': negated patterns (!) are not supported.")
34
+ return value.strip()
35
+
36
+
37
+ def _reason(value: object, required: bool) -> None:
38
+ if value is None and not required:
39
+ return
40
+ if not isinstance(value, str) or not value.strip() or len(value.strip()) > 500:
41
+ raise Invalid("Every ignored rule needs a reason (1 to 500 characters).")
42
+
43
+
44
+ def parse(text: str) -> Ignore:
45
+ """The server's rules (backend services/repo_config.py): a file it would refuse is refused
46
+ here too, so nothing is ignored locally that the server would still report."""
47
+ data = yaml.safe_load(text)
48
+ data = {} if data is None else data
49
+ if not isinstance(data, dict) or set(data) - {"version", "ignore"}:
50
+ raise Invalid("Only `version` and `ignore` are allowed at the top.")
51
+ if data.get("version", 1) != 1:
52
+ raise Invalid("`version` must be 1.")
53
+ section = data.get("ignore") or {}
54
+ if not isinstance(section, dict) or set(section) - {"paths", "rules"}:
55
+ raise Invalid("`ignore` holds only `paths` and `rules`.")
56
+ raw_paths, raw_rules = section.get("paths") or [], section.get("rules") or []
57
+ if not isinstance(raw_paths, list) or not isinstance(raw_rules, list):
58
+ raise Invalid("`paths` and `rules` must be lists.")
59
+ if len(raw_paths) > MAX_ENTRIES or len(raw_rules) > MAX_ENTRIES:
60
+ raise Invalid(f"At most {MAX_ENTRIES} paths and {MAX_ENTRIES} rules.")
61
+ paths = []
62
+ for entry in raw_paths:
63
+ if isinstance(entry, dict):
64
+ if set(entry) - {"path", "reason"}:
65
+ raise Invalid("A path entry holds only `path` and `reason`.")
66
+ _reason(entry.get("reason"), required=False)
67
+ paths.append(_pattern(entry.get("path"), "path"))
68
+ else:
69
+ paths.append(_pattern(entry, "path"))
70
+ rules = []
71
+ for entry in raw_rules:
72
+ if not isinstance(entry, dict) or set(entry) - {"rule", "tool", "paths", "reason"}:
73
+ raise Invalid("A rule entry holds only `rule`, `tool`, `paths` and `reason`.")
74
+ _reason(entry.get("reason"), required=True)
75
+ tool = entry.get("tool")
76
+ if tool is not None and tool not in TOOLS:
77
+ raise Invalid(f"Unknown tool: {str(tool)[:50]}")
78
+ scoped = entry.get("paths") or []
79
+ if not isinstance(scoped, list) or len(scoped) > 50:
80
+ raise Invalid("A rule's `paths` is a list of at most 50 patterns.")
81
+ rules.append({"rule": _pattern(entry.get("rule"), "rule"), "tool": tool,
82
+ "paths": [_pattern(p, "path") for p in scoped]}) # fmt: skip
83
+ return Ignore(paths=paths, rules=rules)
84
+
85
+
86
+ def load(repo: Path) -> Ignore:
87
+ root = repo.resolve()
88
+ for name in (".securebox.yml", ".securebox.yaml"):
89
+ path = root / name
90
+ if path.is_symlink() or not path.is_file():
91
+ continue
92
+ try:
93
+ raw = path.read_bytes()
94
+ if len(raw) > MAX_BYTES:
95
+ return Ignore(error=f"{name} is larger than 64 KB.")
96
+ return parse(raw.decode("utf-8"))
97
+ except (OSError, UnicodeDecodeError, yaml.YAMLError, Invalid) as exc:
98
+ detail = str(exc) if isinstance(exc, Invalid) else type(exc).__name__
99
+ return Ignore(error=f"{name} is invalid ({detail[:200]}).")
100
+ return Ignore()
101
+
102
+
103
+ def _segments_match(pattern: list[str], parts: list[str]) -> bool:
104
+ reach = [True] + [False] * len(parts)
105
+ for segment in pattern:
106
+ if segment == "**":
107
+ for j in range(1, len(parts) + 1):
108
+ reach[j] = reach[j] or reach[j - 1]
109
+ else:
110
+ reach = [False] + [
111
+ reach[j] and fnmatch.fnmatchcase(parts[j], segment) for j in range(len(parts))
112
+ ]
113
+ return reach[-1]
114
+
115
+
116
+ def path_matches(pattern: str, path: str) -> bool:
117
+ trimmed = pattern.strip().removeprefix("./")
118
+ anchored = "/" in trimmed.rstrip("/")
119
+ segments = [s for s in trimmed.split("/") if s not in ("", ".")]
120
+ if not segments:
121
+ return False
122
+ if not anchored:
123
+ segments.insert(0, "**")
124
+ segments.append("**")
125
+ parts = [p for p in path.removeprefix("./").split("/") if p]
126
+ return _segments_match(segments, parts)
127
+
128
+
129
+ def ignored(config: Ignore, tool: str, rule_id: str, path: str | None, secret: bool) -> bool:
130
+ if secret:
131
+ return False # a committed file must not hide a leaked secret
132
+ for rule in config.rules:
133
+ if rule.get("tool") and rule["tool"] != tool:
134
+ continue
135
+ if not fnmatch.fnmatchcase(rule_id, str(rule["rule"])):
136
+ continue
137
+ scoped = [str(p) for p in rule.get("paths") or []]
138
+ if scoped and not (path and any(path_matches(p, path) for p in scoped)):
139
+ continue
140
+ return True
141
+ return bool(path) and any(path_matches(p, path or "") for p in config.paths)