securebox-cli 0.1.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.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,109 @@
1
+ Metadata-Version: 2.1
2
+ Name: securebox-cli
3
+ Version: 0.1.0
4
+ Summary: SecureBox on your machine: secrets, code rules and dependencies before you push
5
+ Author: GTools
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://securebox.gtools.in
8
+ Keywords: security,sast,secrets,pre-commit,gitleaks,opengrep,trivy
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Operating System :: MacOS
14
+ Classifier: Operating System :: Microsoft :: Windows
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Security
18
+ Classifier: Topic :: Software Development :: Quality Assurance
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: httpx<1,>=0.27
23
+ Requires-Dist: pyyaml<7,>=6.0.1
24
+ Provides-Extra: dev
25
+ Requires-Dist: pytest==8.3.4; extra == "dev"
26
+ Requires-Dist: ruff==0.8.4; extra == "dev"
27
+ Requires-Dist: mypy==1.14.1; extra == "dev"
28
+ Requires-Dist: types-PyYAML==6.0.12.20241230; extra == "dev"
29
+
30
+ # securebox: SecureBox on your machine and in CI
31
+
32
+ Checks a repository for leaked secrets, insecure code patterns and vulnerable or malicious
33
+ dependencies with the same scanners and rules as SecureBox: before you commit, before you
34
+ push, or in a CI pipeline. Code never leaves your machine for `scan`.
35
+
36
+ ```sh
37
+ pipx install securebox-cli # or: pip install securebox-cli
38
+ securebox scan # the whole folder
39
+ securebox hook install # check staged changes before every commit
40
+ ```
41
+
42
+ ## Commands
43
+
44
+ | Command | What it does |
45
+ |---|---|
46
+ | `securebox scan [PATH]` | Secrets (Gitleaks), code rules (Opengrep) and dependencies (Trivy) of a folder. `--format json\|sarif --output FILE` for reports. |
47
+ | `securebox scan --staged` | Only what is about to be committed, exactly as staged (not what is in your editor): secrets on the lines the commit adds, code rules on staged files, dependencies when a manifest or lockfile changed. This is what the hook runs. |
48
+ | `securebox hook install` / `uninstall` | Adds or removes the repository's pre-commit hook. It will not replace another tool's hook or a linked hook, nor write into a shared `core.hooksPath` folder (use `--force`, or add `securebox scan --staged` to it yourself). Uninstall removes only the hook it wrote. Skip once with `git commit --no-verify`. |
49
+ | `securebox login` | Stores an organization API key (Organization → Settings → API Keys, scope `read`) in `~/.config/securebox/config.json`, readable by you only. The server URL must be `https://` (`http://` only for `localhost`). |
50
+ | `securebox link [PROJECT_ID]` | Ties the repository to its SecureBox project (`git config securebox.project`). |
51
+ | `securebox ci` | Starts a SecureBox code scan of the project's branch (as it is on the server, not this checkout; waits while another scan of the project runs) and fails on new findings at the project's level. Needs `SECUREBOX_API_KEY` (scopes `read`, `scans`) and `SECUREBOX_PROJECT`. |
52
+
53
+ Exit codes: `0` nothing blocking, `1` blocking findings, `2` the check could not run or did
54
+ not finish (a scanner failed, the report could not be written): never treated as a pass.
55
+
56
+ ## What is checked
57
+
58
+ `scan` checks a copy of the files git would commit: tracked files and new files that are not
59
+ git-ignored (a local `.env` you never commit is left out; outside a git repository, every
60
+ file). Scanner settings in the repository (`.semgrepignore`, `.trivyignore`, `trivy.yaml`,
61
+ `.gitleaks.toml`, `.gitleaksignore`) are not honoured, as on the SecureBox server: use
62
+ `.securebox.yml` to ignore paths or rules. Test files are left out of the code rules as on
63
+ the server. Symbolic links are not followed.
64
+
65
+ ## What blocks
66
+
67
+ Every secret, and findings at or above the failure level: `--fail-on`, else the linked
68
+ project's pull-request setting, else `high`.
69
+
70
+ ## With an API key
71
+
72
+ Without a key the CLI uses a small public starter set of rules. With a key and a linked
73
+ project it uses SecureBox's full rules, the project's own rules, and stays quiet about
74
+ findings your team closed in SecureBox as false positive or accepted risk (secrets excepted).
75
+ The repository's `.securebox.yml` ignores apply with or without a key.
76
+
77
+ ## Scanners
78
+
79
+ Gitleaks 8.30.1, Opengrep 2.0.0 and Trivy 0.74.0 are downloaded once into your cache folder
80
+ and checked against pinned SHA-256 digests before they run (`--use-path` uses copies you
81
+ installed); a cached copy is checked again before every run and fetched again if it changed.
82
+ Trivy downloads its vulnerability database on first use. Repository code is only read, never
83
+ run (git runs with the repository's fsmonitor, hooks, external diff and pager switched off),
84
+ and secret values never appear in the output (`--redact`). Rules from the server are cached
85
+ per version and used when SecureBox cannot be reached (`--offline` never calls it).
86
+
87
+ ## Other hook managers
88
+
89
+ ```yaml
90
+ # .pre-commit-config.yaml
91
+ repos:
92
+ - repo: local
93
+ hooks:
94
+ - id: securebox
95
+ name: SecureBox
96
+ entry: securebox scan --staged
97
+ language: system
98
+ pass_filenames: false
99
+ ```
100
+
101
+ ```json
102
+ // package.json (husky / lint-staged): .husky/pre-commit
103
+ securebox scan --staged
104
+ ```
105
+
106
+ ## Licence
107
+
108
+ Apache-2.0 (see `LICENSE`). The scanners it downloads keep their own licences: Gitleaks (MIT),
109
+ Opengrep (LGPL-2.1), Trivy (Apache-2.0).
@@ -0,0 +1,80 @@
1
+ # securebox: SecureBox on your machine and in CI
2
+
3
+ Checks a repository for leaked secrets, insecure code patterns and vulnerable or malicious
4
+ dependencies with the same scanners and rules as SecureBox: before you commit, before you
5
+ push, or in a CI pipeline. Code never leaves your machine for `scan`.
6
+
7
+ ```sh
8
+ pipx install securebox-cli # or: pip install securebox-cli
9
+ securebox scan # the whole folder
10
+ securebox hook install # check staged changes before every commit
11
+ ```
12
+
13
+ ## Commands
14
+
15
+ | Command | What it does |
16
+ |---|---|
17
+ | `securebox scan [PATH]` | Secrets (Gitleaks), code rules (Opengrep) and dependencies (Trivy) of a folder. `--format json\|sarif --output FILE` for reports. |
18
+ | `securebox scan --staged` | Only what is about to be committed, exactly as staged (not what is in your editor): secrets on the lines the commit adds, code rules on staged files, dependencies when a manifest or lockfile changed. This is what the hook runs. |
19
+ | `securebox hook install` / `uninstall` | Adds or removes the repository's pre-commit hook. It will not replace another tool's hook or a linked hook, nor write into a shared `core.hooksPath` folder (use `--force`, or add `securebox scan --staged` to it yourself). Uninstall removes only the hook it wrote. Skip once with `git commit --no-verify`. |
20
+ | `securebox login` | Stores an organization API key (Organization → Settings → API Keys, scope `read`) in `~/.config/securebox/config.json`, readable by you only. The server URL must be `https://` (`http://` only for `localhost`). |
21
+ | `securebox link [PROJECT_ID]` | Ties the repository to its SecureBox project (`git config securebox.project`). |
22
+ | `securebox ci` | Starts a SecureBox code scan of the project's branch (as it is on the server, not this checkout; waits while another scan of the project runs) and fails on new findings at the project's level. Needs `SECUREBOX_API_KEY` (scopes `read`, `scans`) and `SECUREBOX_PROJECT`. |
23
+
24
+ Exit codes: `0` nothing blocking, `1` blocking findings, `2` the check could not run or did
25
+ not finish (a scanner failed, the report could not be written): never treated as a pass.
26
+
27
+ ## What is checked
28
+
29
+ `scan` checks a copy of the files git would commit: tracked files and new files that are not
30
+ git-ignored (a local `.env` you never commit is left out; outside a git repository, every
31
+ file). Scanner settings in the repository (`.semgrepignore`, `.trivyignore`, `trivy.yaml`,
32
+ `.gitleaks.toml`, `.gitleaksignore`) are not honoured, as on the SecureBox server: use
33
+ `.securebox.yml` to ignore paths or rules. Test files are left out of the code rules as on
34
+ the server. Symbolic links are not followed.
35
+
36
+ ## What blocks
37
+
38
+ Every secret, and findings at or above the failure level: `--fail-on`, else the linked
39
+ project's pull-request setting, else `high`.
40
+
41
+ ## With an API key
42
+
43
+ Without a key the CLI uses a small public starter set of rules. With a key and a linked
44
+ project it uses SecureBox's full rules, the project's own rules, and stays quiet about
45
+ findings your team closed in SecureBox as false positive or accepted risk (secrets excepted).
46
+ The repository's `.securebox.yml` ignores apply with or without a key.
47
+
48
+ ## Scanners
49
+
50
+ Gitleaks 8.30.1, Opengrep 2.0.0 and Trivy 0.74.0 are downloaded once into your cache folder
51
+ and checked against pinned SHA-256 digests before they run (`--use-path` uses copies you
52
+ installed); a cached copy is checked again before every run and fetched again if it changed.
53
+ Trivy downloads its vulnerability database on first use. Repository code is only read, never
54
+ run (git runs with the repository's fsmonitor, hooks, external diff and pager switched off),
55
+ and secret values never appear in the output (`--redact`). Rules from the server are cached
56
+ per version and used when SecureBox cannot be reached (`--offline` never calls it).
57
+
58
+ ## Other hook managers
59
+
60
+ ```yaml
61
+ # .pre-commit-config.yaml
62
+ repos:
63
+ - repo: local
64
+ hooks:
65
+ - id: securebox
66
+ name: SecureBox
67
+ entry: securebox scan --staged
68
+ language: system
69
+ pass_filenames: false
70
+ ```
71
+
72
+ ```json
73
+ // package.json (husky / lint-staged): .husky/pre-commit
74
+ securebox scan --staged
75
+ ```
76
+
77
+ ## Licence
78
+
79
+ Apache-2.0 (see `LICENSE`). The scanners it downloads keep their own licences: Gitleaks (MIT),
80
+ Opengrep (LGPL-2.1), Trivy (Apache-2.0).
@@ -0,0 +1,59 @@
1
+ [build-system]
2
+ requires = ["setuptools==75.6.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "securebox-cli"
7
+ version = "0.1.0"
8
+ description = "SecureBox on your machine: secrets, code rules and dependencies before you push"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "Apache-2.0" }
12
+ authors = [{ name = "GTools" }]
13
+ keywords = ["security", "sast", "secrets", "pre-commit", "gitleaks", "opengrep", "trivy"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Environment :: Console",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: Apache Software License",
19
+ "Operating System :: MacOS",
20
+ "Operating System :: Microsoft :: Windows",
21
+ "Operating System :: POSIX :: Linux",
22
+ "Programming Language :: Python :: 3",
23
+ "Topic :: Security",
24
+ "Topic :: Software Development :: Quality Assurance",
25
+ ]
26
+ # Ranges, not exact pins: the package is installed next to other people's packages.
27
+ dependencies = [
28
+ "httpx>=0.27,<1",
29
+ "pyyaml>=6.0.1,<7",
30
+ ]
31
+
32
+ [project.urls]
33
+ Homepage = "https://securebox.gtools.in"
34
+
35
+ [project.optional-dependencies]
36
+ dev = ["pytest==8.3.4", "ruff==0.8.4", "mypy==1.14.1", "types-PyYAML==6.0.12.20241230"]
37
+
38
+ [project.scripts]
39
+ securebox = "securebox_cli.main:main"
40
+
41
+ [tool.setuptools.packages.find]
42
+ include = ["securebox_cli*"]
43
+
44
+ [tool.setuptools.package-data]
45
+ securebox_cli = ["rules/*.yml"]
46
+
47
+ [tool.ruff]
48
+ line-length = 100
49
+ target-version = "py310"
50
+
51
+ [tool.ruff.lint]
52
+ select = ["E", "F", "I", "B", "UP", "S", "SIM", "RUF"]
53
+ ignore = ["S603", "S607"]
54
+
55
+ [tool.ruff.lint.per-file-ignores]
56
+ "tests/*" = ["S101", "S105", "S106", "S108"]
57
+
58
+ [tool.mypy]
59
+ strict = true
@@ -0,0 +1,3 @@
1
+ """securebox: SecureBox's checks on your machine and in CI."""
2
+
3
+ __version__ = "0.1.0"
@@ -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)