security-review-ci 2.0.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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.4
2
+ Name: security-review-ci
3
+ Version: 2.0.0
4
+ Summary: Pipeline and workstation client of the security-review-mcp controller: gate, SARIF, trends, code and dependency scans
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Documentation, https://cyr-ius.github.io/security-review-mcp/usage/gate/#pipeline-client-security-review-ci
7
+ Project-URL: Repository, https://github.com/cyr-ius/security-review-mcp
8
+ Project-URL: Issues, https://github.com/cyr-ius/security-review-mcp/issues
9
+ Requires-Python: >=3.14
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Dynamic: license-file
13
+
14
+ # security-review-ci
15
+
16
+ Client of the [security-review-mcp](https://github.com/cyr-ius/security-review-mcp) controller for pipelines and developer
17
+ workstations: deployment gate, SARIF export, trend report, code and dependency scans, through
18
+ the REST API with a `ci` token. It only uses the Python standard library.
19
+
20
+ ```bash
21
+ uv tool install security-review-ci # uv installs a Python when none is available
22
+ export SECREVIEW_CONTROLLER_URL=https://secreview.example.com
23
+ export SECREVIEW_TOKEN=<ci token>
24
+ security-review-ci scan-deps uv.lock --project my-project
25
+ ```
26
+
27
+ Documentation: https://cyr-ius.github.io/security-review-mcp/usage/gate/#pipeline-client-security-review-ci
@@ -0,0 +1,14 @@
1
+ # security-review-ci
2
+
3
+ Client of the [security-review-mcp](https://github.com/cyr-ius/security-review-mcp) controller for pipelines and developer
4
+ workstations: deployment gate, SARIF export, trend report, code and dependency scans, through
5
+ the REST API with a `ci` token. It only uses the Python standard library.
6
+
7
+ ```bash
8
+ uv tool install security-review-ci # uv installs a Python when none is available
9
+ export SECREVIEW_CONTROLLER_URL=https://secreview.example.com
10
+ export SECREVIEW_TOKEN=<ci token>
11
+ security-review-ci scan-deps uv.lock --project my-project
12
+ ```
13
+
14
+ Documentation: https://cyr-ius.github.io/security-review-mcp/usage/gate/#pipeline-client-security-review-ci
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "security-review-ci"
7
+ version = "2.0.0"
8
+ description = "Pipeline and workstation client of the security-review-mcp controller: gate, SARIF, trends, code and dependency scans"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.14"
13
+ dependencies = []
14
+
15
+ [project.urls]
16
+ Documentation = "https://cyr-ius.github.io/security-review-mcp/usage/gate/#pipeline-client-security-review-ci"
17
+ Repository = "https://github.com/cyr-ius/security-review-mcp"
18
+ Issues = "https://github.com/cyr-ius/security-review-mcp/issues"
19
+
20
+ [project.scripts]
21
+ security-review-ci = "security_review_ci:main"
22
+
23
+ [tool.setuptools]
24
+ py-modules = ["security_review_ci"]
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.4
2
+ Name: security-review-ci
3
+ Version: 2.0.0
4
+ Summary: Pipeline and workstation client of the security-review-mcp controller: gate, SARIF, trends, code and dependency scans
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Documentation, https://cyr-ius.github.io/security-review-mcp/usage/gate/#pipeline-client-security-review-ci
7
+ Project-URL: Repository, https://github.com/cyr-ius/security-review-mcp
8
+ Project-URL: Issues, https://github.com/cyr-ius/security-review-mcp/issues
9
+ Requires-Python: >=3.14
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Dynamic: license-file
13
+
14
+ # security-review-ci
15
+
16
+ Client of the [security-review-mcp](https://github.com/cyr-ius/security-review-mcp) controller for pipelines and developer
17
+ workstations: deployment gate, SARIF export, trend report, code and dependency scans, through
18
+ the REST API with a `ci` token. It only uses the Python standard library.
19
+
20
+ ```bash
21
+ uv tool install security-review-ci # uv installs a Python when none is available
22
+ export SECREVIEW_CONTROLLER_URL=https://secreview.example.com
23
+ export SECREVIEW_TOKEN=<ci token>
24
+ security-review-ci scan-deps uv.lock --project my-project
25
+ ```
26
+
27
+ Documentation: https://cyr-ius.github.io/security-review-mcp/usage/gate/#pipeline-client-security-review-ci
@@ -0,0 +1,9 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ security_review_ci.py
5
+ security_review_ci.egg-info/PKG-INFO
6
+ security_review_ci.egg-info/SOURCES.txt
7
+ security_review_ci.egg-info/dependency_links.txt
8
+ security_review_ci.egg-info/entry_points.txt
9
+ security_review_ci.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ security-review-ci = security_review_ci:main
@@ -0,0 +1 @@
1
+ security_review_ci
@@ -0,0 +1,804 @@
1
+ """Lightweight pipeline client of the controller (Jenkins, GitLab CI, GitHub Actions...).
2
+
3
+ ``security-review-ci`` runs the security gate, downloads the SARIF log, prints the trend of a
4
+ project and runs the code and dependency scans through the pipeline routes of the controller
5
+ REST API (``/api/v1/ci/``), with a ``ci`` token restricted to the projects the pipeline may see.
6
+ It is the only command line for these pipeline commands (the controller CLI does not run them)
7
+ and opens no database: no database driver, no SQLModel, no database URL in the pipeline.
8
+
9
+ ``scan-code`` lists the files of a directory (``git ls-files`` or a walk of the tree) and
10
+ ``scan-deps`` reads the dependency files given by the operator; both send the content to the
11
+ controller, which scans it with its rules or its advisory database and stores the report with
12
+ ``--save``. Symbolic links are never followed: the content leaves the build agent.
13
+
14
+ The module only uses the Python standard library and imports nothing from the package, so it
15
+ can also be copied alone to a build agent and run with ``python3 ci_client.py``. That is why it
16
+ reads its two variables (``SECREVIEW_CONTROLLER_URL``, ``SECREVIEW_TOKEN``) from the environment
17
+ itself instead of through ``config.Settings``, and ignores the ``.env`` file. The file listing
18
+ (``detect_language``...) is defined here and reused by ``codescan`` on the controller.
19
+
20
+ Exit codes are those of the other commands: 0 success (gate passed, scan below the threshold),
21
+ 1 blocked, 2 usage, connection or data error (written as JSON on stderr). The token is never
22
+ written anywhere.
23
+ """
24
+
25
+ import argparse
26
+ import fnmatch
27
+ import json
28
+ import os
29
+ import ssl
30
+ import subprocess
31
+ import sys
32
+ import urllib.error
33
+ import urllib.request
34
+ from collections.abc import Callable
35
+ from pathlib import Path, PurePosixPath
36
+ from urllib.parse import urlencode, urlsplit
37
+
38
+ EXIT_PASSED = 0
39
+ EXIT_BLOCKED = 1
40
+ EXIT_ERROR = 2
41
+
42
+ CI_PATH = "/api/v1/ci"
43
+ DEFAULT_TIMEOUT = 60.0
44
+ # Bound of an answer read from the controller (a SARIF log of a large project included)
45
+ MAX_RESPONSE_BYTES = 64 * 1024 * 1024
46
+ # Bound of a dependency file read by scan-deps (the controller applies its own limit)
47
+ MAX_DEPENDENCY_FILE_BYTES = 50 * 1024 * 1024
48
+ # Bound of the error messages taken from the controller
49
+ MAX_ERROR_CHARS = 500
50
+ # Plain HTTP is only accepted to these hosts (the token travels in the request)
51
+ LOOPBACK_HOSTS = ("127.0.0.1", "localhost", "::1")
52
+ SEVERITIES = ["info", "low", "medium", "high", "critical"]
53
+
54
+ URL_VARIABLE = "SECREVIEW_CONTROLLER_URL"
55
+ TOKEN_VARIABLE = "SECREVIEW_TOKEN"
56
+
57
+ # Explanation added to the refusals of the controller
58
+ _REFUSAL_HINTS = {
59
+ 401: f"missing or invalid token ({TOKEN_VARIABLE} or --token-stdin)",
60
+ 403: "the token may not use this pipeline route (gate, sarif, trend: role ci, reader, "
61
+ "triager or admin; scans: role ci or admin)",
62
+ 404: "unknown project or report, or outside the projects of the token",
63
+ 413: "request too large for the controller (SECREVIEW_MAX_SCAN_REQUEST_MB): exclude files",
64
+ 503: "authentication is not configured on the controller",
65
+ }
66
+
67
+ # Sends a request (method, URL, headers, JSON body or None) and returns (HTTP status, content
68
+ # type, body); tests replace it
69
+ Fetch = Callable[[str, str, dict[str, str], bytes | None], tuple[int, str, bytes]]
70
+
71
+
72
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
73
+ """Refuse redirects: the token must never be sent elsewhere (or over HTTP)."""
74
+
75
+ def redirect_request(self, req, fp, code, msg, headers, newurl): # noqa: ANN001, ANN201
76
+ """Return None so that urllib raises an HTTPError for the 3xx answer."""
77
+ return None
78
+
79
+
80
+ def controller_endpoint(controller_url: str, route: str, allow_http: bool = False) -> str:
81
+ """Return the URL of a pipeline route of a controller given by its base URL.
82
+
83
+ Plain HTTP is refused except on a loopback address or with ``allow_http``, and so are
84
+ credentials in the URL: the token is the only credential and goes in a header.
85
+ """
86
+ parts = urlsplit(controller_url.strip())
87
+ if parts.scheme not in ("http", "https") or not parts.hostname:
88
+ raise ValueError(
89
+ f"Invalid controller URL '{controller_url}' (expected https://host[:port])"
90
+ )
91
+ if parts.username or parts.password:
92
+ raise ValueError("The controller URL must not contain credentials")
93
+ if parts.scheme == "http" and parts.hostname not in LOOPBACK_HOSTS and not allow_http:
94
+ raise ValueError("Refusing to send the token over plain HTTP (see --allow-http)")
95
+ # The base URL may be given with the path of the web interface or of the API
96
+ path = parts.path.rstrip("/")
97
+ for suffix in ("/ui", "/api/v1", "/api"):
98
+ path = path.removesuffix(suffix)
99
+ return f"{parts.scheme}://{parts.netloc}{path}{CI_PATH}/{route}"
100
+
101
+
102
+ def urllib_fetch(cafile: str | None = None, timeout: float = DEFAULT_TIMEOUT) -> Fetch:
103
+ """Return a fetch function that verifies the certificate with ``cafile`` (default: the
104
+ system CA bundle), follows no redirect and reads at most MAX_RESPONSE_BYTES."""
105
+ context = ssl.create_default_context(cafile=cafile)
106
+ opener = urllib.request.build_opener(
107
+ _NoRedirect(), urllib.request.HTTPSHandler(context=context)
108
+ )
109
+
110
+ def fetch(
111
+ method: str, url: str, headers: dict[str, str], body: bytes | None
112
+ ) -> tuple[int, str, bytes]:
113
+ """Send a request and return its status, content type and bounded body."""
114
+ request = urllib.request.Request(url, data=body, headers=headers, method=method)
115
+ try:
116
+ with opener.open(request, timeout=timeout) as response:
117
+ return (
118
+ response.status,
119
+ response.headers.get("Content-Type", ""),
120
+ response.read(MAX_RESPONSE_BYTES + 1),
121
+ )
122
+ except urllib.error.HTTPError as exc:
123
+ with exc:
124
+ body = exc.read(MAX_RESPONSE_BYTES + 1)
125
+ return exc.code, exc.headers.get("Content-Type", "") if exc.headers else "", body
126
+ except (urllib.error.URLError, OSError) as exc:
127
+ # The message never holds the token: it is only in the request headers
128
+ reason = getattr(exc, "reason", exc)
129
+ raise ValueError(f"Cannot reach {url}: {reason}") from exc
130
+
131
+ return fetch
132
+
133
+
134
+ def _error_detail(body: bytes) -> str:
135
+ """Extract the error message of a FastAPI or middleware answer, bounded."""
136
+ try:
137
+ answer = json.loads(body)
138
+ except ValueError:
139
+ return ""
140
+ if not isinstance(answer, dict):
141
+ return ""
142
+ detail = answer.get("detail") or answer.get("error_description") or ""
143
+ if isinstance(detail, list):
144
+ # Pydantic validation errors
145
+ detail = "; ".join(str(item.get("msg", item)) for item in detail if isinstance(item, dict))
146
+ return str(detail)[:MAX_ERROR_CHARS]
147
+
148
+
149
+ def call(
150
+ controller_url: str,
151
+ route: str,
152
+ params: dict[str, str | int | bool | None],
153
+ token: str,
154
+ fetch: Fetch,
155
+ allow_http: bool = False,
156
+ payload: dict | None = None,
157
+ ) -> tuple[str, bytes]:
158
+ """Call a pipeline route and return the content type and body of a successful answer.
159
+
160
+ ``payload`` is sent as a JSON body with a POST request (the scans), otherwise the route is
161
+ read with a GET request.
162
+
163
+ Raises:
164
+ ValueError: Invalid URL, unreachable controller, refused request or oversized answer.
165
+ """
166
+ query = {
167
+ key: str(value).lower() if isinstance(value, bool) else value
168
+ for key, value in params.items()
169
+ if value is not None
170
+ }
171
+ url = controller_endpoint(controller_url, route, allow_http)
172
+ if query:
173
+ url = f"{url}?{urlencode(query)}"
174
+ headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"}
175
+ data = None
176
+ if payload is not None:
177
+ headers["Content-Type"] = "application/json"
178
+ data = json.dumps(payload).encode("utf-8")
179
+ status, content_type, body = fetch("GET" if data is None else "POST", url, headers, data)
180
+ if len(body) > MAX_RESPONSE_BYTES:
181
+ raise ValueError(f"Answer of {route} too large (> {MAX_RESPONSE_BYTES} bytes)")
182
+ if status != 200:
183
+ detail = _error_detail(body) or _REFUSAL_HINTS.get(status, "no detail")
184
+ raise ValueError(f"The controller refused the request ({status}): {detail}")
185
+ return content_type, body
186
+
187
+
188
+ def printable(text: str) -> str:
189
+ """Remove the control characters (terminal escapes) of a text answer, except new lines and
190
+ tabs: project names and titles come from the reports."""
191
+ return "".join(c for c in text if c in "\n\t" or (c.isprintable() and c != "\x7f"))
192
+
193
+
194
+ def _json(body: bytes, route: str) -> dict:
195
+ """Decode a JSON object answered by a pipeline route."""
196
+ try:
197
+ answer = json.loads(body)
198
+ except ValueError as exc:
199
+ raise ValueError(f"Unexpected answer of {route}: not JSON") from exc
200
+ if not isinstance(answer, dict):
201
+ raise ValueError(f"Unexpected answer of {route}: not a JSON object")
202
+ return answer
203
+
204
+
205
+ # ── File listing (scan-code, scan-deps) ──────────────────────────────────────
206
+
207
+ DEFAULT_MAX_FILE_BYTES = 1024 * 1024
208
+ _BINARY_SNIFF_BYTES = 8192
209
+
210
+ # Skipped when the tree is walked without git
211
+ SKIPPED_DIRS = frozenset(
212
+ {
213
+ ".git",
214
+ ".hg",
215
+ ".svn",
216
+ ".venv",
217
+ "venv",
218
+ "env",
219
+ "__pycache__",
220
+ ".mypy_cache",
221
+ ".pytest_cache",
222
+ ".ruff_cache",
223
+ ".tox",
224
+ "node_modules",
225
+ "bower_components",
226
+ ".angular",
227
+ "dist",
228
+ "build",
229
+ "target",
230
+ "out",
231
+ "coverage",
232
+ ".gradle",
233
+ "obj", # .NET intermediate output
234
+ ".vs",
235
+ ".idea",
236
+ }
237
+ )
238
+
239
+ # Generated files: huge and never hand-written
240
+ SKIPPED_NAMES = frozenset(
241
+ {"package-lock.json", "yarn.lock", "pnpm-lock.yaml", "poetry.lock", "Pipfile.lock", "uv.lock"}
242
+ )
243
+
244
+ _EXTENSIONS = {
245
+ ".py": "python",
246
+ ".pyw": "python",
247
+ ".java": "java",
248
+ ".ts": "typescript",
249
+ ".tsx": "typescript",
250
+ ".mts": "typescript",
251
+ ".cts": "typescript",
252
+ ".js": "javascript",
253
+ ".jsx": "javascript",
254
+ ".mjs": "javascript",
255
+ ".cjs": "javascript",
256
+ ".go": "go",
257
+ ".cs": "csharp",
258
+ ".csx": "csharp",
259
+ ".cshtml": "csharp", # Razor views (Html.Raw...)
260
+ ".razor": "csharp",
261
+ ".rs": "rust",
262
+ ".html": "angular", # Angular templates ([innerHTML], bypassSecurityTrust...)
263
+ ".yml": "yaml",
264
+ ".yaml": "yaml",
265
+ ".properties": "config",
266
+ ".ini": "config",
267
+ ".cfg": "config",
268
+ ".conf": "config",
269
+ ".toml": "config",
270
+ ".env": "config",
271
+ ".groovy": "jenkins",
272
+ ".jenkinsfile": "jenkins",
273
+ ".dockerfile": "docker",
274
+ }
275
+
276
+ # Files that steer an AI assistant: scanned for hidden characters and injected instructions
277
+ _AGENT_INSTRUCTION_NAMES = frozenset(
278
+ {
279
+ "agents.md",
280
+ "claude.md",
281
+ "gemini.md",
282
+ "copilot-instructions.md",
283
+ ".cursorrules",
284
+ ".windsurfrules",
285
+ ".clinerules",
286
+ }
287
+ )
288
+ _AGENT_INSTRUCTION_DIRS = frozenset({".claude", ".cursor", ".windsurf", ".clinerules"})
289
+
290
+
291
+ def detect_language(path: str) -> str | None:
292
+ """Return the scanner language of a file from its name, or None when it is not scanned."""
293
+ name = PurePosixPath(path).name
294
+ lower = name.lower()
295
+ if name in SKIPPED_NAMES or lower.endswith((".min.js", ".d.ts")):
296
+ return None
297
+ if lower in ("dockerfile", "containerfile") or lower.startswith(
298
+ ("dockerfile.", "containerfile.")
299
+ ):
300
+ return "docker"
301
+ if lower == "jenkinsfile" or lower.startswith("jenkinsfile."):
302
+ return "jenkins"
303
+ if lower == ".gitlab-ci.yml" or (
304
+ lower.endswith((".yml", ".yaml")) and ".gitlab-ci" in PurePosixPath(path).parts[:-1]
305
+ ):
306
+ return "gitlab-ci"
307
+ if lower == ".env" or lower.startswith(".env."):
308
+ return "config"
309
+ if (
310
+ lower in _AGENT_INSTRUCTION_NAMES
311
+ or lower.endswith((".mdc", ".instructions.md", ".prompt.md"))
312
+ or (lower.endswith(".md") and _AGENT_INSTRUCTION_DIRS & set(PurePosixPath(path).parts))
313
+ ):
314
+ return "agent-instructions"
315
+ return _EXTENSIONS.get(PurePosixPath(lower).suffix)
316
+
317
+
318
+ # The scanned repository's .git/config is untrusted: some keys make git run a command
319
+ # (core.fsmonitor). Options given with -c override the repository configuration.
320
+ _GIT_SAFE_OPTIONS = ("-c", "core.fsmonitor=false", "-c", "core.untrackedCache=false")
321
+
322
+
323
+ def _git_files(root: Path) -> list[str] | None:
324
+ """List tracked and untracked (not ignored) files with git, or None if git is unusable."""
325
+ try:
326
+ completed = subprocess.run(
327
+ ["git", *_GIT_SAFE_OPTIONS, "ls-files", "-z", "--cached", "--others"]
328
+ + ["--exclude-standard"],
329
+ cwd=root,
330
+ capture_output=True,
331
+ check=True,
332
+ timeout=60,
333
+ )
334
+ except OSError, subprocess.SubprocessError:
335
+ return None
336
+ names = completed.stdout.decode("utf-8", errors="replace").split("\0")
337
+ return sorted({name for name in names if name})
338
+
339
+
340
+ def _walk_files(root: Path) -> list[str]:
341
+ """List files under root, skipping dependency, build and VCS directories."""
342
+ found: list[str] = []
343
+ for current, dirs, files in os.walk(root):
344
+ dirs[:] = sorted(d for d in dirs if d not in SKIPPED_DIRS)
345
+ base = Path(current).relative_to(root)
346
+ found.extend((base / name).as_posix() for name in sorted(files))
347
+ return found
348
+
349
+
350
+ def list_files(root: Path, use_git: bool = True) -> tuple[list[str], str]:
351
+ """Return the relative paths of the files to consider and the listing method used."""
352
+ if use_git:
353
+ names = _git_files(root)
354
+ if names is not None:
355
+ return names, "git"
356
+ return _walk_files(root), "walk"
357
+
358
+
359
+ def _excluded(path: str, patterns: list[str]) -> bool:
360
+ """Tell whether a relative path matches one of the exclusion globs."""
361
+ return any(
362
+ fnmatch.fnmatch(path, pattern) or path.startswith(pattern.rstrip("/") + "/")
363
+ for pattern in patterns
364
+ )
365
+
366
+
367
+ def _read_source(path: Path, max_bytes: int) -> tuple[str | None, str | None]:
368
+ """Read a text file; return ``(content, None)`` or ``(None, reason it was skipped)``."""
369
+ if path.is_symlink():
370
+ return None, "symbolic link"
371
+ if not path.is_file():
372
+ return None, "not a regular file"
373
+ size = path.stat().st_size
374
+ if size > max_bytes:
375
+ return None, f"larger than {max_bytes} bytes"
376
+ data = path.read_bytes()
377
+ if b"\0" in data[:_BINARY_SNIFF_BYTES]:
378
+ return None, "binary file"
379
+ return data.decode("utf-8", errors="replace"), None
380
+
381
+
382
+ def collect_sources(
383
+ root: str | Path,
384
+ excludes: list[str] | None = None,
385
+ max_file_bytes: int = DEFAULT_MAX_FILE_BYTES,
386
+ use_git: bool = True,
387
+ ) -> dict:
388
+ """Read every supported file under ``root``, ready to be sent to the code scan route.
389
+
390
+ Args:
391
+ root: Directory to scan.
392
+ excludes: Glob patterns (relative to root) of files or directories to skip.
393
+ max_file_bytes: Files above this size are skipped and reported.
394
+ use_git: List files with ``git ls-files`` when possible.
395
+
396
+ Returns:
397
+ The listing method, the files read (relative path with forward slashes and content),
398
+ the files skipped with their reason (excluded ones are only counted) and the number of
399
+ files of an unsupported type.
400
+
401
+ Raises:
402
+ ValueError: If root is not a directory.
403
+ """
404
+ base = Path(root).resolve()
405
+ if not base.is_dir():
406
+ raise ValueError(f"Not a directory: {root}")
407
+ patterns = list(excludes or [])
408
+ names, method = list_files(base, use_git)
409
+ files: list[dict] = []
410
+ skipped: list[dict] = []
411
+ excluded = unsupported = 0
412
+ for name in names:
413
+ if detect_language(name) is None:
414
+ unsupported += 1
415
+ continue
416
+ if _excluded(name, patterns):
417
+ excluded += 1
418
+ continue
419
+ try:
420
+ content, reason = _read_source(base / name, max_file_bytes)
421
+ except OSError as exc:
422
+ content, reason = None, f"unreadable: {exc.strerror or exc}"
423
+ if content is None:
424
+ skipped.append({"file": name, "reason": reason})
425
+ else:
426
+ files.append({"path": name, "content": content})
427
+ return {
428
+ "listing": method,
429
+ "files": files,
430
+ "skipped": skipped,
431
+ "excluded": excluded,
432
+ "unsupported": unsupported,
433
+ }
434
+
435
+
436
+ def read_dependency_file(name: str) -> dict:
437
+ """Read a dependency file given by the operator (never through a symbolic link: the content
438
+ leaves the machine), bounded by MAX_DEPENDENCY_FILE_BYTES."""
439
+ path = Path(name)
440
+ if path.is_symlink():
441
+ raise ValueError(f"Refusing to read a symbolic link: {path}")
442
+ if not path.is_file():
443
+ raise ValueError(f"File not found: {path}")
444
+ if path.stat().st_size > MAX_DEPENDENCY_FILE_BYTES:
445
+ raise ValueError(f"File too large (> {MAX_DEPENDENCY_FILE_BYTES} bytes): {path}")
446
+ return {"path": path.name, "content": path.read_text(encoding="utf-8", errors="replace")}
447
+
448
+
449
+ # ── Output of the scans ──────────────────────────────────────────────────────
450
+
451
+
452
+ def _clean(value: object) -> str:
453
+ """Return ``value`` as text without control characters (terminal escape sequences): scan
454
+ results come from advisories, from file names or from a remote server."""
455
+ return "".join(c if c.isprintable() else "?" for c in str(value))
456
+
457
+
458
+ def print_code_text(result: dict, fail_on: str) -> None:
459
+ """Print a short human-readable summary of a code scan answered by the controller."""
460
+ for entry in result["files"]:
461
+ for match in entry["matches"]:
462
+ line = (
463
+ f"{entry['file']}:{match['line']} [{match['severity'].upper()}] "
464
+ f"{match['rule_id']} {match['title']}"
465
+ )
466
+ print(_clean(line))
467
+ for entry in result["skipped"]:
468
+ print(_clean(f"skipped: {entry['file']} ({entry['reason']})"), file=sys.stderr)
469
+ counts = ", ".join(f"{k}: {v}" for k, v in result["by_severity"].items() if v)
470
+ print(
471
+ _clean(
472
+ f"{result['files_scanned']} file(s) scanned ({result['lines_scanned']} lines, listed "
473
+ f"with {result['listing']}), {result['files_skipped']} skipped, "
474
+ f"{result['matches_count']} match(es){f' ({counts})' if counts else ''}, "
475
+ f"{result['suppressed_count']} suppressed"
476
+ )
477
+ )
478
+ blocked = result["blocking_findings"]
479
+ print(f"RESULT: {f'BLOCKED ({blocked} match(es) >= {fail_on})' if blocked else 'OK'}")
480
+
481
+
482
+ def print_deps_text(results: list[dict], blocked: int, fail_on: str) -> None:
483
+ """Print a short human-readable summary of dependency scans (also used by scan-deps)."""
484
+ for result in results:
485
+ kind = "lockfile" if result["is_lockfile"] else "manifest"
486
+ print(
487
+ _clean(
488
+ f"{result['file']} ({result['ecosystem']}, {kind}): {result['components_total']} "
489
+ f"component(s), vulnerability check: {result['vulnerability_check']}"
490
+ )
491
+ )
492
+ for vuln in result["vulnerabilities"]:
493
+ upgrade = vuln["recommended_upgrade"]
494
+ fix = f" -> upgrade to {upgrade}" if upgrade else ""
495
+ line = (
496
+ f"[{vuln['severity'].upper()}] {vuln['package']} {vuln['version']} "
497
+ f"{vuln['advisory_id']}{fix}"
498
+ )
499
+ print(f" {_clean(line)}")
500
+ for issue in result["hygiene"]:
501
+ line = f"[{issue['severity'].upper()}] {issue['rule_id']} {issue['message']}"
502
+ print(f" {_clean(line)}")
503
+ for note in result["notes"]:
504
+ print(f" note: {_clean(note)}")
505
+ verdict = f"BLOCKED ({blocked} finding(s) >= {fail_on})" if blocked else "OK"
506
+ print(f"RESULT: {verdict}")
507
+
508
+
509
+ def warn_unchecked(results: list[dict]) -> list[str]:
510
+ """Warn on stderr about the files whose vulnerability check did not run; return them."""
511
+ skipped = [r["file"] for r in results if r["vulnerability_check"] != "performed"]
512
+ if skipped:
513
+ print(
514
+ _clean(
515
+ f"warning: vulnerability check did not run for: {', '.join(skipped)} "
516
+ "(no advisory database for this ecosystem)"
517
+ ),
518
+ file=sys.stderr,
519
+ )
520
+ return skipped
521
+
522
+
523
+ def _write_output(text: str, output: str | None, message: str) -> None:
524
+ """Print ``text`` or write it to ``output`` (then print ``message`` on stderr)."""
525
+ if not output:
526
+ print(text)
527
+ return
528
+ Path(output).write_text(text + "\n", encoding="utf-8")
529
+ print(message, file=sys.stderr)
530
+
531
+
532
+ # ── Command line ─────────────────────────────────────────────────────────────
533
+
534
+
535
+ def _fail(message: str, **fields: object) -> int:
536
+ """Print an error as JSON on stderr and return the error exit code."""
537
+ print(json.dumps(fields | {"error": message}), file=sys.stderr)
538
+ return EXIT_ERROR
539
+
540
+
541
+ def _add_report_options(parser: argparse.ArgumentParser) -> None:
542
+ """Options of the scans that store their result as a report of the project."""
543
+ parser.add_argument(
544
+ "--fail-on",
545
+ choices=SEVERITIES,
546
+ default="high",
547
+ help="lowest blocking severity (default: high)",
548
+ )
549
+ parser.add_argument("--save", action="store_true", help="store the result as a report")
550
+ parser.add_argument("--repository", help="repository URL stored with the report")
551
+ parser.add_argument("--branch", help="branch stored with the report")
552
+ parser.add_argument("--commit", help="commit stored with the report")
553
+ parser.add_argument(
554
+ "--author", help="username of the developer, stored with the report (with --save)"
555
+ )
556
+ parser.add_argument(
557
+ "--skip-unconfigured",
558
+ action="store_true",
559
+ help=f"exit 0 with a warning when {URL_VARIABLE} is not set (shared commit hooks)",
560
+ )
561
+
562
+
563
+ def _parser() -> argparse.ArgumentParser:
564
+ """Build the parser of ``security-review-ci`` and its sub-commands."""
565
+ common = argparse.ArgumentParser(add_help=False)
566
+ common.add_argument(
567
+ "--url",
568
+ default=os.environ.get(URL_VARIABLE) or None,
569
+ help=f"controller URL, for example https://secreview.example.com (default: {URL_VARIABLE})",
570
+ )
571
+ common.add_argument("--project", required=True, help="project name used for the reports")
572
+ common.add_argument(
573
+ "--token-stdin",
574
+ action="store_true",
575
+ help=f"read the token on stdin (default: {TOKEN_VARIABLE})",
576
+ )
577
+ common.add_argument("--cafile", help="CA bundle used to verify the controller certificate")
578
+ common.add_argument(
579
+ "--allow-http",
580
+ action="store_true",
581
+ help="allow plain HTTP to a non-loopback controller (the token would travel in clear)",
582
+ )
583
+ common.add_argument(
584
+ "--timeout", type=float, default=DEFAULT_TIMEOUT, help="seconds (default: 60)"
585
+ )
586
+
587
+ parser = argparse.ArgumentParser(
588
+ prog="security-review-ci",
589
+ description="Pipeline client of the security-review controller: gate, SARIF export, "
590
+ "trend, code scan and dependency scan of a project through the REST API, with a ci "
591
+ "token restricted to its projects. No database access.",
592
+ )
593
+ commands = parser.add_subparsers(dest="command", required=True)
594
+ gate = commands.add_parser(
595
+ "gate", parents=[common], help="fail when open findings reach a severity threshold"
596
+ )
597
+ gate.add_argument(
598
+ "--fail-on",
599
+ choices=SEVERITIES,
600
+ default="high",
601
+ help="lowest blocking severity (default: high)",
602
+ )
603
+ gate.add_argument("--report-id", type=int, default=None, help="check a single report")
604
+ exporter = commands.add_parser(
605
+ "sarif", parents=[common], help="download the findings as a SARIF 2.1.0 log"
606
+ )
607
+ exporter.add_argument("--include-resolved", action="store_true")
608
+ exporter.add_argument("--output", "-o", help="file to write (default: standard output)")
609
+ trend = commands.add_parser("trend", parents=[common], help="print the trend of a project")
610
+ trend.add_argument("--days", type=int, default=90)
611
+ trend.add_argument("--granularity", choices=["day", "week", "month"], default="week")
612
+ trend.add_argument("--format", choices=["markdown", "json"], default="markdown")
613
+
614
+ code = commands.add_parser(
615
+ "scan-code",
616
+ parents=[common],
617
+ help="pattern-scan a whole codebase with the rules of the controller",
618
+ )
619
+ code.add_argument("path", nargs="?", default=".", help="directory to scan (default: .)")
620
+ code.add_argument(
621
+ "--exclude",
622
+ action="append",
623
+ default=[],
624
+ metavar="GLOB",
625
+ help="file or directory glob to skip, relative to the path; repeat the option",
626
+ )
627
+ code.add_argument(
628
+ "--max-file-bytes",
629
+ type=int,
630
+ default=DEFAULT_MAX_FILE_BYTES,
631
+ help="skip larger files (default: 1 MiB)",
632
+ )
633
+ code.add_argument(
634
+ "--no-git", action="store_true", help="walk the tree instead of using git ls-files"
635
+ )
636
+ code.add_argument("--format", choices=["text", "json", "sarif"], default="text")
637
+ code.add_argument("--output", "-o", help="file to write (default: standard output)")
638
+ _add_report_options(code)
639
+
640
+ deps = commands.add_parser(
641
+ "scan-deps",
642
+ parents=[common],
643
+ help="scan dependency manifests and lockfiles with the advisories of the controller",
644
+ )
645
+ deps.add_argument("files", nargs="+", help="manifests or lockfiles")
646
+ deps.add_argument("--format", choices=["text", "json"], default="text")
647
+ deps.add_argument(
648
+ "--require-database",
649
+ action="store_true",
650
+ help="exit 2 when the vulnerability check could not run (no advisory database)",
651
+ )
652
+ _add_report_options(deps)
653
+ return parser
654
+
655
+
656
+ def _read_token(from_stdin: bool) -> str:
657
+ """Return the token from stdin or from SECREVIEW_TOKEN (never from the command line, where
658
+ it would show in the process list and the job log)."""
659
+ token = sys.stdin.readline().strip() if from_stdin else os.environ.get(TOKEN_VARIABLE, "")
660
+ if not token.strip():
661
+ source = "stdin" if from_stdin else TOKEN_VARIABLE
662
+ raise ValueError(f"No token: {source} is empty")
663
+ return token.strip()
664
+
665
+
666
+ def _report_fields(args: argparse.Namespace) -> dict:
667
+ """Fields of a scan request shared by scan-code and scan-deps."""
668
+ return {
669
+ "project": args.project,
670
+ "fail_on": args.fail_on,
671
+ "save": args.save,
672
+ "repository": args.repository,
673
+ "branch": args.branch,
674
+ "commit_sha": args.commit,
675
+ "author": args.author,
676
+ }
677
+
678
+
679
+ def print_saved_line(result: dict, project: str) -> None:
680
+ """Print the id of the stored report, if any."""
681
+ saved = result.get("saved_report")
682
+ if saved:
683
+ print(_clean(f"Report #{saved['report_id']} saved for project {project}"))
684
+
685
+
686
+ def _scan_code(args: argparse.Namespace, send: Callable[[str, dict], bytes]) -> int:
687
+ """Run ``scan-code``: read the files, scan them on the controller, print the result."""
688
+ sources = collect_sources(args.path, args.exclude, args.max_file_bytes, not args.no_git)
689
+ payload = _report_fields(args) | {
690
+ "root": args.path,
691
+ "listing": sources["listing"],
692
+ "files": sources["files"],
693
+ "skipped": sources["skipped"],
694
+ "excluded": sources["excluded"],
695
+ "unsupported": sources["unsupported"],
696
+ "sarif": args.format == "sarif",
697
+ }
698
+ result = _json(send("scan/code", payload), "scan/code")
699
+ if not isinstance(result.get("blocked"), bool):
700
+ raise ValueError("Unexpected answer of scan/code: no 'blocked' field")
701
+ code = EXIT_BLOCKED if result["blocked"] else EXIT_PASSED
702
+ if args.format == "text":
703
+ print_code_text(result, args.fail_on)
704
+ print_saved_line(result, args.project)
705
+ return code
706
+ log = result.pop("sarif", None)
707
+ document = log if args.format == "sarif" else result
708
+ if not isinstance(document, dict):
709
+ raise ValueError("Unexpected answer of scan/code: no SARIF log")
710
+ message = f"{result['matches_count']} match(es) written to {args.output}"
711
+ _write_output(json.dumps(document, indent=2), args.output, message)
712
+ return code
713
+
714
+
715
+ def _scan_deps(args: argparse.Namespace, send: Callable[[str, dict], bytes]) -> int:
716
+ """Run ``scan-deps``: read the files, scan them on the controller, print the result."""
717
+ files = [read_dependency_file(name) for name in args.files]
718
+ payload = _report_fields(args) | {
719
+ "files": files,
720
+ "require_database": args.require_database,
721
+ }
722
+ result = _json(send("scan/deps", payload), "scan/deps")
723
+ if not isinstance(result.get("blocked"), bool) or not isinstance(result.get("files"), list):
724
+ raise ValueError("Unexpected answer of scan/deps: no 'blocked' or 'files' field")
725
+ warn_unchecked(result["files"])
726
+ if args.format == "json":
727
+ print(json.dumps(result, indent=2))
728
+ else:
729
+ print_deps_text(result["files"], result["blocking_findings"], args.fail_on)
730
+ print_saved_line(result, args.project)
731
+ return EXIT_BLOCKED if result["blocked"] else EXIT_PASSED
732
+
733
+
734
+ def main(argv: list[str] | None = None, fetch: Fetch | None = None) -> int:
735
+ """Run ``security-review-ci`` and return its exit code (``fetch``: tests)."""
736
+ argv = sys.argv[1:] if argv is None else argv
737
+ parser = _parser()
738
+ if not argv:
739
+ # No sub-command: show the help rather than a bare usage error, still failing the step.
740
+ parser.print_help()
741
+ return EXIT_ERROR
742
+ args = parser.parse_args(argv)
743
+ if not args.url and getattr(args, "skip_unconfigured", False):
744
+ print(f"warning: {args.command} skipped ({URL_VARIABLE} is not set)", file=sys.stderr)
745
+ return EXIT_PASSED
746
+ try:
747
+ if not args.url:
748
+ raise ValueError(f"No controller URL: give --url or set {URL_VARIABLE}")
749
+ token = _read_token(args.token_stdin)
750
+ fetch = fetch or urllib_fetch(args.cafile, args.timeout)
751
+
752
+ def send(route: str, payload: dict) -> bytes:
753
+ """POST a scan request to the controller and return the answer."""
754
+ return call(args.url, route, {}, token, fetch, args.allow_http, payload)[1]
755
+
756
+ if args.command == "scan-code":
757
+ return _scan_code(args, send)
758
+ if args.command == "scan-deps":
759
+ return _scan_deps(args, send)
760
+ if args.command == "gate":
761
+ params: dict[str, str | int | bool | None] = {
762
+ "project": args.project,
763
+ "fail_on": args.fail_on,
764
+ "report_id": args.report_id,
765
+ }
766
+ elif args.command == "sarif":
767
+ params = {"project": args.project, "include_resolved": args.include_resolved}
768
+ else:
769
+ params = {
770
+ "project": args.project,
771
+ "days": args.days,
772
+ "granularity": args.granularity,
773
+ "format": args.format,
774
+ }
775
+ _, body = call(args.url, args.command, params, token, fetch, args.allow_http)
776
+ if args.command == "gate":
777
+ result = _json(body, "gate")
778
+ if not isinstance(result.get("passed"), bool):
779
+ raise ValueError("Unexpected answer of gate: no 'passed' field")
780
+ print(json.dumps(result, indent=2))
781
+ return EXIT_PASSED if result["passed"] else EXIT_BLOCKED
782
+ if args.command == "sarif":
783
+ log = _json(body, "sarif")
784
+ runs = log.get("runs") or [{}]
785
+ count = len(runs[0].get("results") or []) if isinstance(runs[0], dict) else 0
786
+ message = f"{count} result(s) written to {args.output}"
787
+ _write_output(json.dumps(log, indent=2), args.output, message)
788
+ return EXIT_PASSED
789
+ text = printable(body.decode("utf-8", errors="replace"))
790
+ if args.format == "json":
791
+ text = json.dumps(_json(body, "trend"), indent=2) + "\n"
792
+ print(text, end="")
793
+ return EXIT_PASSED
794
+ except (ValueError, OSError, KeyError, TypeError) as exc:
795
+ detail = (
796
+ f"Unexpected answer of the controller: {exc!r}"
797
+ if isinstance(exc, (KeyError, TypeError))
798
+ else str(exc)
799
+ )
800
+ return _fail(detail, **({"passed": False} if args.command == "gate" else {}))
801
+
802
+
803
+ if __name__ == "__main__":
804
+ sys.exit(main())
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+