synapse-sbom 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,75 @@
1
+ # Environment files (contain secrets)
2
+ .env
3
+ .env.local
4
+ .env.*.local
5
+
6
+ # Terraform
7
+ *.tfstate
8
+ *.tfstate.*
9
+ *.tfplan
10
+ .terraform/
11
+ .terraform.lock.hcl
12
+
13
+ # Python
14
+ __pycache__/
15
+ *.py[cod]
16
+ *$py.class
17
+ .venv/
18
+ venv/
19
+ .pytest_cache/
20
+
21
+ # Node
22
+ node_modules/
23
+ .next/
24
+ out/
25
+
26
+ # IDE
27
+ .idea/
28
+ .vscode/
29
+ *.swp
30
+ *.swo
31
+
32
+ # macOS
33
+ .DS_Store
34
+ .AppleDouble
35
+ .LSOverride
36
+ ._*
37
+ .Spotlight-V100
38
+ .Trashes
39
+
40
+ # Thumbnails
41
+ Thumbs.db
42
+ ehthumbs.db
43
+
44
+ # Logs
45
+ *.log
46
+ logs/
47
+
48
+ # Build artifacts
49
+ dist/
50
+ build/
51
+
52
+ # Local development
53
+ *.local
54
+ *.old
55
+
56
+ # Backups
57
+ backups/
58
+
59
+ # Scraper credentials and cached data
60
+ external/*/data/
61
+ **/linkedin_cookies.json
62
+ **/telegram_session*
63
+
64
+ # Ephemeral local artifacts (never commit)
65
+ .playwright-mcp/
66
+ .mcp.json
67
+ /*.png
68
+ scripts/prod-dump-*.sql
69
+ **/*.xcuserstate
70
+ # Local release/evidence artifacts (kept on disk, out of VCS)
71
+ /synapse-commits-history.*
72
+ /synapse-files-list.*
73
+ /synapse-files-sha256.*
74
+ /synapse-release-manifest.*
75
+ /synapse-evidence.xlsx
@@ -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 2026 PeachStudio (https://peachstudio.be)
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,220 @@
1
+ Metadata-Version: 2.4
2
+ Name: synapse-sbom
3
+ Version: 0.1.0
4
+ Summary: SYNAPSE SBOM scanner for Python projects — generate a CycloneDX SBOM locally and submit it to SYNAPSE Software Component Analysis.
5
+ Project-URL: Homepage, https://github.com/vitorallo/synapse/tree/main/tools/sbom-scanner-py#readme
6
+ Project-URL: Repository, https://github.com/vitorallo/synapse
7
+ Project-URL: Issues, https://github.com/vitorallo/synapse/issues
8
+ Author-email: PeachStudio <me@vitorallo.com>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: cyclonedx,pypi,sbom,sca,supply-chain,synapse,vulnerability
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Security
18
+ Classifier: Topic :: Software Development :: Quality Assurance
19
+ Requires-Python: >=3.9
20
+ Description-Content-Type: text/markdown
21
+
22
+ # synapse-sbom (Python)
23
+
24
+ > Command: **`synapse-sbom`** · PyPI package: **`synapse-sbom`** · the
25
+ > Python twin of the npm [`@peachstudio/synapse-sbom`](https://www.npmjs.com/package/@peachstudio/synapse-sbom)
26
+
27
+ Generate a [CycloneDX 1.6](https://cyclonedx.org/) SBOM from your Python
28
+ project **locally** and submit it to **SYNAPSE Software Component
29
+ Analysis** (SCA). Vulnerable components are then **continuously
30
+ re-evaluated** as new advisories land — *scan once, monitored forever*.
31
+
32
+ - **Zero runtime dependencies** — Python ≥ 3.9, stdlib only.
33
+ - The SBOM is built on your machine; only the SBOM JSON leaves it.
34
+ - Same `/v1/sca/analyze` contract, **shared config & project identity**
35
+ with the npm scanner — a polyglot repo is the **same product**
36
+ whichever scanner runs.
37
+
38
+ ---
39
+
40
+ ## Quick start
41
+
42
+ ```bash
43
+ # 1. Create an API key in the SYNAPSE webapp:
44
+ # Settings → Security → API Keys → name it → Create → copy the syn_… key
45
+
46
+ # 2. Store it once (shared with the npm scanner: ~/.config/synapse-sbom/config.json, 0600):
47
+ uvx synapse-sbom login --key syn_xxxxxxxxxxxx
48
+ # (or: pipx run synapse-sbom login --key syn_xxx)
49
+
50
+ # 3. From your project root:
51
+ uvx synapse-sbom scan
52
+ ```
53
+
54
+ Install it instead of using `uvx`/`pipx run` if you prefer:
55
+
56
+ ```bash
57
+ uv tool install synapse-sbom # → `synapse-sbom` on PATH
58
+ pipx install synapse-sbom # same
59
+ pip install synapse-sbom # into the current environment
60
+ ```
61
+
62
+ `uvx synapse-sbom` / `pipx run synapse-sbom` is the `npx` analog — no
63
+ install needed.
64
+
65
+ ---
66
+
67
+ ## What it reads
68
+
69
+ To build the component list (first match wins — closest to the npm
70
+ tool's lockfile-first approach):
71
+
72
+ 1. **`poetry.lock`** or **`uv.lock`** (TOML; needs Python ≥ 3.11 for the
73
+ stdlib `tomllib`, otherwise skipped)
74
+ 2. **`requirements.txt`** (pinned `name==version` lines)
75
+ 3. else the **active environment** — every installed distribution via
76
+ `importlib.metadata` (zero-config, reliable; run it in your project's
77
+ venv)
78
+
79
+ Product name/version come from `pyproject.toml` `[project]` (or
80
+ `[tool.poetry]`), else the directory name. Components are emitted as
81
+ `pkg:pypi/<normalized-name>@<version>`. Anything the resolver doesn't
82
+ support server-side is reported `skipped`, never fatal.
83
+
84
+ ---
85
+
86
+ ## Authentication (API key)
87
+
88
+ 1. SYNAPSE webapp → **Settings → Security → API Keys** (Business or
89
+ Enterprise tier). Name it, **Create**, copy the `syn_…` key — it is
90
+ shown **once**.
91
+ 2. Give it to the scanner — precedence **flag → env → stored config**:
92
+
93
+ | Method | How | Best for |
94
+ |---|---|---|
95
+ | Flag | `--key syn_…` | one-off / overrides |
96
+ | Env | `SYNAPSE_API_KEY=syn_…` | CI (use a secret) |
97
+ | Stored | `synapse-sbom login --key syn_…` → `~/.config/synapse-sbom/config.json` (`0600`) | local dev |
98
+
99
+ The config file and the `.synapse-sbom.json` project marker are the
100
+ **same** as the npm scanner's — `login` once, use either tool. The key
101
+ is never written to the project, the SBOM, or `.synapse-sbom.json`.
102
+
103
+ ---
104
+
105
+ ## Command reference
106
+
107
+ Copy-paste, no install needed (`uvx`; or `pipx run`, or drop the prefix
108
+ if installed):
109
+
110
+ ```bash
111
+ # Authenticate once (shared 0600 config)
112
+ uvx synapse-sbom login --key syn_xxx --url https://api.synapse-intel.com
113
+ uvx synapse-sbom login # interactive hidden prompt
114
+
115
+ # Scan
116
+ uvx synapse-sbom scan # current project, submit
117
+ uvx synapse-sbom scan ./path/to/app # a specific project
118
+ uvx synapse-sbom scan --dry-run # print SBOM only, no upload, no side effects
119
+ uvx synapse-sbom scan --product my-svc # override display name
120
+ uvx synapse-sbom scan --project my-key # explicit stable project key
121
+
122
+ # Per-run auth/endpoint overrides (skip stored config)
123
+ uvx synapse-sbom scan --url https://api.synapse-intel.com --key syn_xxx
124
+ SYNAPSE_API_KEY=syn_xxx SYNAPSE_API_URL=https://api.synapse-intel.com \
125
+ uvx synapse-sbom scan
126
+
127
+ # Local SYNAPSE instead of prod
128
+ uvx synapse-sbom scan --url http://localhost:8085 --key syn_local
129
+
130
+ # Inspect resolved URL / masked key / config path
131
+ uvx synapse-sbom whoami
132
+
133
+ # Help
134
+ uvx synapse-sbom help
135
+ ```
136
+
137
+ | Flag | Env | Default | Meaning |
138
+ |---|---|---|---|
139
+ | `--key` | `SYNAPSE_API_KEY` | stored config | Bearer API key |
140
+ | `--url` | `SYNAPSE_API_URL` | `https://api.synapse-intel.com` | SCA API base URL |
141
+ | `--project` | `SYNAPSE_PROJECT` | git remote → generated | Stable project identity (survives renames/CI) |
142
+ | `--product` | — | `pyproject.toml` name | Display name only |
143
+ | `--dry-run` | — | off | Build SBOM, print to stdout, **don't** upload or write `.synapse-sbom.json` |
144
+ | — | `SYNAPSE_TIMEOUT_MS` | `1200000` (20 min) | Client request timeout |
145
+ | — | `SYNAPSE_SBOM_CONFIG_DIR` | `~/.config/synapse-sbom` | Config directory (shared with npm tool) |
146
+
147
+ **Resolution order** (key & URL): `flag` > `env` > stored config > default.
148
+
149
+ ---
150
+
151
+ ## Project identity (re-scans update the same product)
152
+
153
+ Same rules and **same `.synapse-sbom.json` format** as the npm tool, so
154
+ a project scanned by either resolves to one product:
155
+
156
+ 1. `--project` / `SYNAPSE_PROJECT`
157
+ 2. committed `.synapse-sbom.json` — `{ "projectId": "…" }`
158
+ 3. the git remote URL, normalized (`git:github.com/org/repo`)
159
+ 4. else a generated UUID written to `.synapse-sbom.json` — **commit it**.
160
+
161
+ Server identity is `(your account, project key)`; the product name is a
162
+ mutable label. `--dry-run` reports the key without writing the file.
163
+
164
+ ---
165
+
166
+ ## Use in CI
167
+
168
+ ```yaml
169
+ # .github/workflows/sca.yml
170
+ name: SBOM SCA
171
+ on: [push]
172
+ jobs:
173
+ scan:
174
+ runs-on: ubuntu-latest
175
+ steps:
176
+ - uses: actions/checkout@v4
177
+ - uses: actions/setup-python@v5
178
+ with: { python-version: "3.12" }
179
+ - run: pip install -r requirements.txt # so the env reflects deps
180
+ - run: uvx synapse-sbom scan
181
+ env:
182
+ SYNAPSE_API_KEY: ${{ secrets.SYNAPSE_API_KEY }}
183
+ ```
184
+
185
+ Commit `.synapse-sbom.json` so every run reports as the same product.
186
+ Exit `0` on success, `1` on any error (fail the build as you see fit).
187
+
188
+ ---
189
+
190
+ ## Security
191
+
192
+ The SBOM is built locally; only it (+ a Bearer key over HTTPS) leaves
193
+ your machine. The key is stored `0600`, never written to the project,
194
+ the SBOM, or `.synapse-sbom.json`, and never printed (the CLI **warns**
195
+ if you point `--url` at a plaintext `http://` non-local host;
196
+ `http://localhost` and `https://` are silent). Zero third-party
197
+ dependencies — no transitive supply-chain surface.
198
+
199
+ ---
200
+
201
+ ## Troubleshooting
202
+
203
+ | Symptom | Cause / fix |
204
+ |---|---|
205
+ | `(N components, from environment)` but you expected lockfile | No `poetry.lock`/`uv.lock`/`requirements.txt` found, or Python < 3.11 for TOML locks. Run in the project venv, or add a pinned `requirements.txt`. |
206
+ | `no API key …` | `login`, or pass `--key` / `SYNAPSE_API_KEY`. |
207
+ | `API 401` | Key invalid/revoked, or wrong `--url`. Check `synapse-sbom whoami`. |
208
+ | `API 403` | Your tier doesn't include SCA (Business/Enterprise), or API access not enabled in webapp settings. |
209
+ | `API 413` | SBOM exceeds the server component cap. |
210
+ | `timed out after …s` | Large project still resolving. Re-run later (results cache) or raise `SYNAPSE_TIMEOUT_MS`. |
211
+
212
+ ---
213
+
214
+ ## Family
215
+
216
+ `synapse-sbom` ships for **npm** (`@peachstudio/synapse-sbom`, published)
217
+ and **PyPI** (this package). A **Go** scanner will follow the same
218
+ contract — generate a CycloneDX 1.6 SBOM locally, submit to
219
+ `/v1/sca/analyze`. The SCA engine is ecosystem-agnostic, so a CycloneDX
220
+ file from any tool works today.
@@ -0,0 +1,199 @@
1
+ # synapse-sbom (Python)
2
+
3
+ > Command: **`synapse-sbom`** · PyPI package: **`synapse-sbom`** · the
4
+ > Python twin of the npm [`@peachstudio/synapse-sbom`](https://www.npmjs.com/package/@peachstudio/synapse-sbom)
5
+
6
+ Generate a [CycloneDX 1.6](https://cyclonedx.org/) SBOM from your Python
7
+ project **locally** and submit it to **SYNAPSE Software Component
8
+ Analysis** (SCA). Vulnerable components are then **continuously
9
+ re-evaluated** as new advisories land — *scan once, monitored forever*.
10
+
11
+ - **Zero runtime dependencies** — Python ≥ 3.9, stdlib only.
12
+ - The SBOM is built on your machine; only the SBOM JSON leaves it.
13
+ - Same `/v1/sca/analyze` contract, **shared config & project identity**
14
+ with the npm scanner — a polyglot repo is the **same product**
15
+ whichever scanner runs.
16
+
17
+ ---
18
+
19
+ ## Quick start
20
+
21
+ ```bash
22
+ # 1. Create an API key in the SYNAPSE webapp:
23
+ # Settings → Security → API Keys → name it → Create → copy the syn_… key
24
+
25
+ # 2. Store it once (shared with the npm scanner: ~/.config/synapse-sbom/config.json, 0600):
26
+ uvx synapse-sbom login --key syn_xxxxxxxxxxxx
27
+ # (or: pipx run synapse-sbom login --key syn_xxx)
28
+
29
+ # 3. From your project root:
30
+ uvx synapse-sbom scan
31
+ ```
32
+
33
+ Install it instead of using `uvx`/`pipx run` if you prefer:
34
+
35
+ ```bash
36
+ uv tool install synapse-sbom # → `synapse-sbom` on PATH
37
+ pipx install synapse-sbom # same
38
+ pip install synapse-sbom # into the current environment
39
+ ```
40
+
41
+ `uvx synapse-sbom` / `pipx run synapse-sbom` is the `npx` analog — no
42
+ install needed.
43
+
44
+ ---
45
+
46
+ ## What it reads
47
+
48
+ To build the component list (first match wins — closest to the npm
49
+ tool's lockfile-first approach):
50
+
51
+ 1. **`poetry.lock`** or **`uv.lock`** (TOML; needs Python ≥ 3.11 for the
52
+ stdlib `tomllib`, otherwise skipped)
53
+ 2. **`requirements.txt`** (pinned `name==version` lines)
54
+ 3. else the **active environment** — every installed distribution via
55
+ `importlib.metadata` (zero-config, reliable; run it in your project's
56
+ venv)
57
+
58
+ Product name/version come from `pyproject.toml` `[project]` (or
59
+ `[tool.poetry]`), else the directory name. Components are emitted as
60
+ `pkg:pypi/<normalized-name>@<version>`. Anything the resolver doesn't
61
+ support server-side is reported `skipped`, never fatal.
62
+
63
+ ---
64
+
65
+ ## Authentication (API key)
66
+
67
+ 1. SYNAPSE webapp → **Settings → Security → API Keys** (Business or
68
+ Enterprise tier). Name it, **Create**, copy the `syn_…` key — it is
69
+ shown **once**.
70
+ 2. Give it to the scanner — precedence **flag → env → stored config**:
71
+
72
+ | Method | How | Best for |
73
+ |---|---|---|
74
+ | Flag | `--key syn_…` | one-off / overrides |
75
+ | Env | `SYNAPSE_API_KEY=syn_…` | CI (use a secret) |
76
+ | Stored | `synapse-sbom login --key syn_…` → `~/.config/synapse-sbom/config.json` (`0600`) | local dev |
77
+
78
+ The config file and the `.synapse-sbom.json` project marker are the
79
+ **same** as the npm scanner's — `login` once, use either tool. The key
80
+ is never written to the project, the SBOM, or `.synapse-sbom.json`.
81
+
82
+ ---
83
+
84
+ ## Command reference
85
+
86
+ Copy-paste, no install needed (`uvx`; or `pipx run`, or drop the prefix
87
+ if installed):
88
+
89
+ ```bash
90
+ # Authenticate once (shared 0600 config)
91
+ uvx synapse-sbom login --key syn_xxx --url https://api.synapse-intel.com
92
+ uvx synapse-sbom login # interactive hidden prompt
93
+
94
+ # Scan
95
+ uvx synapse-sbom scan # current project, submit
96
+ uvx synapse-sbom scan ./path/to/app # a specific project
97
+ uvx synapse-sbom scan --dry-run # print SBOM only, no upload, no side effects
98
+ uvx synapse-sbom scan --product my-svc # override display name
99
+ uvx synapse-sbom scan --project my-key # explicit stable project key
100
+
101
+ # Per-run auth/endpoint overrides (skip stored config)
102
+ uvx synapse-sbom scan --url https://api.synapse-intel.com --key syn_xxx
103
+ SYNAPSE_API_KEY=syn_xxx SYNAPSE_API_URL=https://api.synapse-intel.com \
104
+ uvx synapse-sbom scan
105
+
106
+ # Local SYNAPSE instead of prod
107
+ uvx synapse-sbom scan --url http://localhost:8085 --key syn_local
108
+
109
+ # Inspect resolved URL / masked key / config path
110
+ uvx synapse-sbom whoami
111
+
112
+ # Help
113
+ uvx synapse-sbom help
114
+ ```
115
+
116
+ | Flag | Env | Default | Meaning |
117
+ |---|---|---|---|
118
+ | `--key` | `SYNAPSE_API_KEY` | stored config | Bearer API key |
119
+ | `--url` | `SYNAPSE_API_URL` | `https://api.synapse-intel.com` | SCA API base URL |
120
+ | `--project` | `SYNAPSE_PROJECT` | git remote → generated | Stable project identity (survives renames/CI) |
121
+ | `--product` | — | `pyproject.toml` name | Display name only |
122
+ | `--dry-run` | — | off | Build SBOM, print to stdout, **don't** upload or write `.synapse-sbom.json` |
123
+ | — | `SYNAPSE_TIMEOUT_MS` | `1200000` (20 min) | Client request timeout |
124
+ | — | `SYNAPSE_SBOM_CONFIG_DIR` | `~/.config/synapse-sbom` | Config directory (shared with npm tool) |
125
+
126
+ **Resolution order** (key & URL): `flag` > `env` > stored config > default.
127
+
128
+ ---
129
+
130
+ ## Project identity (re-scans update the same product)
131
+
132
+ Same rules and **same `.synapse-sbom.json` format** as the npm tool, so
133
+ a project scanned by either resolves to one product:
134
+
135
+ 1. `--project` / `SYNAPSE_PROJECT`
136
+ 2. committed `.synapse-sbom.json` — `{ "projectId": "…" }`
137
+ 3. the git remote URL, normalized (`git:github.com/org/repo`)
138
+ 4. else a generated UUID written to `.synapse-sbom.json` — **commit it**.
139
+
140
+ Server identity is `(your account, project key)`; the product name is a
141
+ mutable label. `--dry-run` reports the key without writing the file.
142
+
143
+ ---
144
+
145
+ ## Use in CI
146
+
147
+ ```yaml
148
+ # .github/workflows/sca.yml
149
+ name: SBOM SCA
150
+ on: [push]
151
+ jobs:
152
+ scan:
153
+ runs-on: ubuntu-latest
154
+ steps:
155
+ - uses: actions/checkout@v4
156
+ - uses: actions/setup-python@v5
157
+ with: { python-version: "3.12" }
158
+ - run: pip install -r requirements.txt # so the env reflects deps
159
+ - run: uvx synapse-sbom scan
160
+ env:
161
+ SYNAPSE_API_KEY: ${{ secrets.SYNAPSE_API_KEY }}
162
+ ```
163
+
164
+ Commit `.synapse-sbom.json` so every run reports as the same product.
165
+ Exit `0` on success, `1` on any error (fail the build as you see fit).
166
+
167
+ ---
168
+
169
+ ## Security
170
+
171
+ The SBOM is built locally; only it (+ a Bearer key over HTTPS) leaves
172
+ your machine. The key is stored `0600`, never written to the project,
173
+ the SBOM, or `.synapse-sbom.json`, and never printed (the CLI **warns**
174
+ if you point `--url` at a plaintext `http://` non-local host;
175
+ `http://localhost` and `https://` are silent). Zero third-party
176
+ dependencies — no transitive supply-chain surface.
177
+
178
+ ---
179
+
180
+ ## Troubleshooting
181
+
182
+ | Symptom | Cause / fix |
183
+ |---|---|
184
+ | `(N components, from environment)` but you expected lockfile | No `poetry.lock`/`uv.lock`/`requirements.txt` found, or Python < 3.11 for TOML locks. Run in the project venv, or add a pinned `requirements.txt`. |
185
+ | `no API key …` | `login`, or pass `--key` / `SYNAPSE_API_KEY`. |
186
+ | `API 401` | Key invalid/revoked, or wrong `--url`. Check `synapse-sbom whoami`. |
187
+ | `API 403` | Your tier doesn't include SCA (Business/Enterprise), or API access not enabled in webapp settings. |
188
+ | `API 413` | SBOM exceeds the server component cap. |
189
+ | `timed out after …s` | Large project still resolving. Re-run later (results cache) or raise `SYNAPSE_TIMEOUT_MS`. |
190
+
191
+ ---
192
+
193
+ ## Family
194
+
195
+ `synapse-sbom` ships for **npm** (`@peachstudio/synapse-sbom`, published)
196
+ and **PyPI** (this package). A **Go** scanner will follow the same
197
+ contract — generate a CycloneDX 1.6 SBOM locally, submit to
198
+ `/v1/sca/analyze`. The SCA engine is ecosystem-agnostic, so a CycloneDX
199
+ file from any tool works today.
@@ -0,0 +1,42 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "synapse-sbom"
7
+ version = "0.1.0"
8
+ description = "SYNAPSE SBOM scanner for Python projects — generate a CycloneDX SBOM locally and submit it to SYNAPSE Software Component Analysis."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "PeachStudio", email = "me@vitorallo.com" }]
14
+ keywords = ["sbom", "cyclonedx", "sca", "vulnerability", "supply-chain", "pypi", "synapse"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Environment :: Console",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: Apache Software License",
20
+ "Programming Language :: Python :: 3",
21
+ "Topic :: Security",
22
+ "Topic :: Software Development :: Quality Assurance",
23
+ ]
24
+ # Zero runtime dependencies — stdlib only (urllib, json, argparse,
25
+ # pathlib, subprocess, importlib.metadata, uuid). tomllib is used for
26
+ # poetry.lock/uv.lock when available (Python >= 3.11); gracefully
27
+ # skipped otherwise.
28
+ dependencies = []
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/vitorallo/synapse/tree/main/tools/sbom-scanner-py#readme"
32
+ Repository = "https://github.com/vitorallo/synapse"
33
+ Issues = "https://github.com/vitorallo/synapse/issues"
34
+
35
+ [project.scripts]
36
+ synapse-sbom = "synapse_sbom.cli:main"
37
+
38
+ [tool.hatch.build.targets.wheel]
39
+ packages = ["src/synapse_sbom"]
40
+
41
+ [tool.hatch.build.targets.sdist]
42
+ include = ["src/synapse_sbom", "README.md", "LICENSE", "pyproject.toml"]
@@ -0,0 +1,8 @@
1
+ """synapse-sbom — Python/PyPI SBOM scanner for SYNAPSE SCA.
2
+
3
+ Faithful twin of the npm @peachstudio/synapse-sbom CLI: same commands,
4
+ same /v1/sca/analyze contract, same project identity, same shared
5
+ config, same security posture. Zero runtime dependencies.
6
+ """
7
+
8
+ __version__ = "0.1.0"
@@ -0,0 +1,505 @@
1
+ """synapse-sbom (Python) — faithful twin of @peachstudio/synapse-sbom.
2
+
3
+ Generates a CycloneDX 1.6 SBOM from a Python project locally and submits
4
+ it to the SYNAPSE public SCA API (POST /v1/sca/analyze, Bearer API key).
5
+ Zero runtime dependencies (stdlib only). Shares config + project-identity
6
+ format with the npm scanner so a polyglot repo is the SAME product.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import re
14
+ import socket
15
+ import subprocess
16
+ import sys
17
+ import threading
18
+ import time
19
+ import urllib.error
20
+ import urllib.request
21
+ import uuid
22
+ from importlib import metadata as importlib_metadata
23
+ from pathlib import Path
24
+ from urllib.parse import urlparse
25
+
26
+ try: # poetry.lock / uv.lock parsing; gracefully skipped on <3.11
27
+ import tomllib
28
+ except ModuleNotFoundError: # pragma: no cover
29
+ tomllib = None # type: ignore[assignment]
30
+
31
+ from . import __version__
32
+
33
+ DEFAULT_API_URL = "https://api.synapse-intel.com"
34
+
35
+ # SHARED with the npm scanner (one `login` works for both).
36
+ CONFIG_DIR = Path(
37
+ os.environ.get("SYNAPSE_SBOM_CONFIG_DIR")
38
+ or (
39
+ Path(os.environ.get("XDG_CONFIG_HOME") or (Path.home() / ".config"))
40
+ / "synapse-sbom"
41
+ )
42
+ )
43
+ CONFIG_FILE = CONFIG_DIR / "config.json"
44
+ PROJECT_FILE = ".synapse-sbom.json"
45
+
46
+ USAGE = f"""synapse-sbom — generate & submit a Python SBOM to SYNAPSE
47
+
48
+ Usage:
49
+ synapse-sbom login [--key <API_KEY>] [--url <API_URL>]
50
+ synapse-sbom scan [path] [--dry-run] [--product <name>] [--project <key>] [--url <API_URL>]
51
+ synapse-sbom whoami
52
+
53
+ Resolution order for API key / URL: CLI flag > env
54
+ (SYNAPSE_API_KEY / SYNAPSE_API_URL) > stored config (~/.config/synapse-sbom).
55
+ Default API URL: {DEFAULT_API_URL}
56
+
57
+ Examples:
58
+ synapse-sbom login --key syn_xxx
59
+ synapse-sbom scan # scan ./ and submit
60
+ synapse-sbom scan ./my-app --dry-run
61
+ SYNAPSE_API_URL=http://localhost:8085 synapse-sbom scan"""
62
+
63
+
64
+ # ── arg parsing (mirrors the npm tool's tiny parser) ───────────────────
65
+ def parse_args(argv):
66
+ positional, flags = [], {}
67
+ i = 0
68
+ while i < len(argv):
69
+ a = argv[i]
70
+ if a.startswith("--"):
71
+ key = a[2:]
72
+ if key == "dry-run":
73
+ flags["dryRun"] = True
74
+ else:
75
+ i += 1
76
+ flags[key] = argv[i] if i < len(argv) else None
77
+ else:
78
+ positional.append(a)
79
+ i += 1
80
+ return positional, flags
81
+
82
+
83
+ # ── config store (0600) ────────────────────────────────────────────────
84
+ def read_config():
85
+ try:
86
+ return json.loads(CONFIG_FILE.read_text("utf-8"))
87
+ except Exception:
88
+ return {}
89
+
90
+
91
+ def write_config(cfg):
92
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True, mode=0o700)
93
+ # Create with 0600 directly (no world-readable window).
94
+ fd = os.open(str(CONFIG_FILE), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
95
+ with os.fdopen(fd, "w") as fh:
96
+ json.dump(cfg, fh, indent=2)
97
+ try:
98
+ os.chmod(CONFIG_FILE, 0o600)
99
+ except OSError:
100
+ pass
101
+
102
+
103
+ def resolve_auth(flags):
104
+ cfg = read_config()
105
+ api_key = (
106
+ flags.get("key") or os.environ.get("SYNAPSE_API_KEY") or cfg.get("apiKey") or ""
107
+ )
108
+ api_url = (
109
+ flags.get("url")
110
+ or os.environ.get("SYNAPSE_API_URL")
111
+ or cfg.get("apiUrl")
112
+ or DEFAULT_API_URL
113
+ ).rstrip("/")
114
+ return api_key, api_url
115
+
116
+
117
+ # Warn if the API key would be sent over plaintext HTTP to a non-local
118
+ # host (credential exposure). http://localhost is a legitimate local
119
+ # deployment; a remote http:// URL leaks the Bearer token in cleartext.
120
+ def warn_insecure_transport(api_url):
121
+ try:
122
+ u = urlparse(api_url)
123
+ except ValueError:
124
+ return
125
+ host = u.hostname or ""
126
+ is_local = (
127
+ host in ("localhost", "127.0.0.1", "::1") or host.endswith(".localhost")
128
+ )
129
+ if u.scheme == "http" and not is_local:
130
+ print(
131
+ f"⚠ WARNING: {api_url} is plaintext HTTP — your API key "
132
+ f"will be sent in cleartext to {host}. Use https:// unless this "
133
+ f"is a trusted private network you control.",
134
+ file=sys.stderr,
135
+ )
136
+
137
+
138
+ # ── CycloneDX 1.6 generation ───────────────────────────────────────────
139
+ def pypi_purl(name, version):
140
+ # PEP 503 normalized project name (OSV/PyPI ecosystem identity).
141
+ norm = re.sub(r"[-_.]+", "-", name).lower()
142
+ return f"pkg:pypi/{norm}@{version}"
143
+
144
+
145
+ def _read_toml(path):
146
+ if tomllib is None:
147
+ return None
148
+ try:
149
+ with open(path, "rb") as fh:
150
+ return tomllib.load(fh)
151
+ except Exception:
152
+ return None
153
+
154
+
155
+ def _project_meta(project_dir, override):
156
+ """Product name/version from pyproject.toml [project], else dir name."""
157
+ name, version = None, None
158
+ data = _read_toml(project_dir / "pyproject.toml")
159
+ if data:
160
+ proj = data.get("project") or {}
161
+ name = proj.get("name")
162
+ version = proj.get("version")
163
+ if not version and isinstance(data.get("tool", {}).get("poetry"), dict):
164
+ name = name or data["tool"]["poetry"].get("name")
165
+ version = data["tool"]["poetry"].get("version")
166
+ return (override or name or project_dir.resolve().name or "unnamed"), (
167
+ version or "0.0.0"
168
+ )
169
+
170
+
171
+ def _components_from_lockfiles(project_dir):
172
+ """poetry.lock / uv.lock (TOML) or requirements.txt (pinned)."""
173
+ comps = []
174
+ poetry = _read_toml(project_dir / "poetry.lock")
175
+ if poetry and isinstance(poetry.get("package"), list):
176
+ for pkg in poetry["package"]:
177
+ n, v = pkg.get("name"), pkg.get("version")
178
+ if n and v:
179
+ dev = pkg.get("category") == "dev"
180
+ comps.append((n, str(v), dev))
181
+ if comps:
182
+ return comps, "poetry.lock"
183
+ uvlock = _read_toml(project_dir / "uv.lock")
184
+ if uvlock and isinstance(uvlock.get("package"), list):
185
+ for pkg in uvlock["package"]:
186
+ n, v = pkg.get("name"), pkg.get("version")
187
+ if n and v:
188
+ comps.append((n, str(v), False))
189
+ if comps:
190
+ return comps, "uv.lock"
191
+ req = project_dir / "requirements.txt"
192
+ if req.exists():
193
+ for line in req.read_text("utf-8", "ignore").splitlines():
194
+ line = line.split("#", 1)[0].strip()
195
+ m = re.match(r"^([A-Za-z0-9][A-Za-z0-9._-]*)\s*==\s*([^\s;]+)", line)
196
+ if m:
197
+ comps.append((m.group(1), m.group(2), False))
198
+ if comps:
199
+ return comps, "requirements.txt"
200
+ return [], None
201
+
202
+
203
+ def _components_from_env():
204
+ """Resolved packages in the active environment (importlib.metadata)."""
205
+ comps = []
206
+ for dist in importlib_metadata.distributions():
207
+ try:
208
+ n = dist.metadata["Name"]
209
+ v = dist.version
210
+ except Exception:
211
+ continue
212
+ if n and v:
213
+ comps.append((n, str(v), False))
214
+ return comps
215
+
216
+
217
+ def build_sbom(project_dir, product_name_override):
218
+ product_name, product_version = _project_meta(project_dir, product_name_override)
219
+
220
+ raw, source = _components_from_lockfiles(project_dir)
221
+ if not raw:
222
+ raw = _components_from_env()
223
+ source = "environment"
224
+
225
+ seen, components = set(), []
226
+ for name, version, dev in raw:
227
+ key = f"{name}@{version}"
228
+ if key in seen:
229
+ continue
230
+ seen.add(key)
231
+ purl = pypi_purl(name, version)
232
+ components.append(
233
+ {
234
+ "type": "library",
235
+ "bom-ref": purl,
236
+ "name": name,
237
+ "version": version,
238
+ "purl": purl,
239
+ "scope": "optional" if dev else "required",
240
+ }
241
+ )
242
+
243
+ return (
244
+ {
245
+ "bomFormat": "CycloneDX",
246
+ "specVersion": "1.6",
247
+ "serialNumber": f"urn:uuid:{uuid.uuid4()}",
248
+ "version": 1,
249
+ "metadata": {
250
+ "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
251
+ "tools": [
252
+ {"vendor": "SYNAPSE", "name": "synapse-sbom", "version": __version__}
253
+ ],
254
+ "component": {
255
+ "type": "application",
256
+ "bom-ref": pypi_purl(product_name, product_version),
257
+ "name": product_name,
258
+ "version": product_version,
259
+ "purl": pypi_purl(product_name, product_version),
260
+ },
261
+ },
262
+ "components": components,
263
+ },
264
+ source or "environment",
265
+ )
266
+
267
+
268
+ # ── stable project identity (shared format with the npm tool) ──────────
269
+ def git_remote_key(dir_):
270
+ try:
271
+ url = (
272
+ subprocess.run(
273
+ ["git", "-C", str(dir_), "config", "--get", "remote.origin.url"],
274
+ stdout=subprocess.PIPE,
275
+ stderr=subprocess.DEVNULL,
276
+ stdin=subprocess.DEVNULL,
277
+ check=True,
278
+ )
279
+ .stdout.decode()
280
+ .strip()
281
+ )
282
+ except Exception:
283
+ return None
284
+ if not url:
285
+ return None
286
+ n = re.sub(r"^[a-z]+://", "", url, flags=re.I)
287
+ n = re.sub(r"^[^@/]+@", "", n)
288
+ n = n.replace(":", "/", 1)
289
+ n = re.sub(r"\.git$", "", n).lower().rstrip("/")
290
+ return f"git:{n}" if n else None
291
+
292
+
293
+ def resolve_project_key(dir_, flags, write):
294
+ explicit = flags.get("project") or os.environ.get("SYNAPSE_PROJECT")
295
+ if explicit:
296
+ return explicit.strip(), "flag/env"
297
+
298
+ pf = dir_ / PROJECT_FILE
299
+ try:
300
+ j = json.loads(pf.read_text("utf-8"))
301
+ if j and j.get("projectId"):
302
+ return str(j["projectId"]), PROJECT_FILE
303
+ except Exception:
304
+ pass
305
+
306
+ gk = git_remote_key(dir_)
307
+ if gk:
308
+ return gk, "git remote"
309
+
310
+ generated = str(uuid.uuid4())
311
+ if write:
312
+ pf.write_text(json.dumps({"projectId": generated}, indent=2) + "\n")
313
+ print(
314
+ f"No git remote — generated a project id and wrote {PROJECT_FILE}. "
315
+ f"Commit this file so every clone/CI scans as the same product.",
316
+ file=sys.stderr,
317
+ )
318
+ return generated, "generated"
319
+
320
+
321
+ # ── commands ───────────────────────────────────────────────────────────
322
+ def cmd_login(flags):
323
+ cfg = read_config()
324
+ api_key = flags.get("key")
325
+ if not api_key:
326
+ import getpass
327
+
328
+ api_key = getpass.getpass("SYNAPSE API key: ").strip()
329
+ if not api_key:
330
+ raise RuntimeError("an API key is required")
331
+ api_url = (flags.get("url") or cfg.get("apiUrl") or DEFAULT_API_URL).rstrip("/")
332
+ warn_insecure_transport(api_url)
333
+ cfg.update({"apiKey": api_key, "apiUrl": api_url})
334
+ write_config(cfg)
335
+ print(f"Saved to {CONFIG_FILE} (mode 600)")
336
+ print(f"API URL: {api_url}")
337
+
338
+
339
+ def cmd_whoami(flags):
340
+ api_key, api_url = resolve_auth(flags)
341
+ print(f"API URL : {api_url}")
342
+ masked = (
343
+ f"{api_key[:4]}…({len(api_key)} chars)" if api_key else "(none)"
344
+ )
345
+ print(f"API key : {masked}")
346
+ print(f"Config : {CONFIG_FILE}")
347
+
348
+
349
+ def _spinner(stop_evt, t0):
350
+ is_tty = sys.stderr.isatty()
351
+ frames = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
352
+ f = 0
353
+ while not stop_evt.wait(0.25 if is_tty else 30):
354
+ s = round(time.time() - t0)
355
+ if is_tty:
356
+ sys.stderr.write(f"\r{frames[f % len(frames)]} analyzing… {s}s")
357
+ sys.stderr.flush()
358
+ f += 1
359
+ else:
360
+ sys.stderr.write(f"… still analyzing ({s}s)\n")
361
+
362
+
363
+ def cmd_scan(positional, flags):
364
+ project_dir = Path(positional[0] if positional else ".").resolve()
365
+ sbom, source = build_sbom(project_dir, flags.get("product"))
366
+ project_key, key_source = resolve_project_key(
367
+ project_dir, flags, not flags.get("dryRun")
368
+ )
369
+ print(f"Project identity: {project_key} ({key_source})", file=sys.stderr)
370
+ print(
371
+ f"Generated CycloneDX SBOM: {sbom['metadata']['component']['name']}@"
372
+ f"{sbom['metadata']['component']['version']} "
373
+ f"({len(sbom['components'])} components, from {source})",
374
+ file=sys.stderr,
375
+ )
376
+
377
+ if flags.get("dryRun"):
378
+ sys.stdout.write(json.dumps(sbom, indent=2) + "\n")
379
+ return
380
+
381
+ api_key, api_url = resolve_auth(flags)
382
+ if not api_key:
383
+ raise RuntimeError(
384
+ 'no API key — run "synapse-sbom login" or set SYNAPSE_API_KEY'
385
+ )
386
+ warn_insecure_transport(api_url)
387
+
388
+ print(
389
+ f"Submitting {len(sbom['components'])} component(s) to {api_url} — "
390
+ f"resolving & enriching vulnerabilities server-side. Large projects "
391
+ f"can take a few minutes…",
392
+ file=sys.stderr,
393
+ )
394
+
395
+ env_timeout = os.environ.get("SYNAPSE_TIMEOUT_MS")
396
+ try:
397
+ timeout_ms = float(env_timeout) if env_timeout else 0
398
+ except ValueError:
399
+ timeout_ms = 0
400
+ timeout_s = (timeout_ms / 1000.0) if timeout_ms > 0 else 20 * 60
401
+
402
+ body = json.dumps(
403
+ {
404
+ "format": "cyclonedx",
405
+ "sbom": sbom,
406
+ "product": {"project_key": project_key},
407
+ }
408
+ ).encode()
409
+ req = urllib.request.Request(
410
+ f"{api_url}/v1/sca/analyze",
411
+ data=body,
412
+ method="POST",
413
+ headers={
414
+ "Content-Type": "application/json",
415
+ "Authorization": f"Bearer {api_key}",
416
+ },
417
+ )
418
+
419
+ t0 = time.time()
420
+ stop_evt = threading.Event()
421
+ ticker = threading.Thread(target=_spinner, args=(stop_evt, t0), daemon=True)
422
+ ticker.start()
423
+ try:
424
+ try:
425
+ resp = urllib.request.urlopen(req, timeout=timeout_s)
426
+ status, text = resp.status, resp.read().decode("utf-8", "replace")
427
+ except urllib.error.HTTPError as e: # non-2xx still has a body
428
+ status = e.code
429
+ text = e.read().decode("utf-8", "replace")
430
+ except (urllib.error.URLError, socket.timeout, TimeoutError) as e:
431
+ reason = getattr(e, "reason", e)
432
+ if isinstance(reason, (socket.timeout, TimeoutError)) or isinstance(
433
+ e, (socket.timeout, TimeoutError)
434
+ ):
435
+ raise RuntimeError(
436
+ f"timed out after {round(timeout_s)}s — the server is "
437
+ f"still analyzing; re-run later (results cache) or raise "
438
+ f"SYNAPSE_TIMEOUT_MS"
439
+ )
440
+ raise RuntimeError(f"could not reach {api_url}: {reason}")
441
+ finally:
442
+ stop_evt.set()
443
+ ticker.join(timeout=1)
444
+ if sys.stderr.isatty():
445
+ sys.stderr.write("\r\x1b[K")
446
+ sys.stderr.flush()
447
+
448
+ print(f"Done in {round(time.time() - t0)}s (HTTP {status})", file=sys.stderr)
449
+
450
+ try:
451
+ data = json.loads(text)
452
+ except ValueError:
453
+ data = {"detail": text}
454
+ if not (200 <= status < 300):
455
+ detail = data.get("detail") or data.get("message") or text or "request failed"
456
+ raise RuntimeError(f"API {status}: {detail}")
457
+
458
+ s = data.get("summary") or {}
459
+ print(f"Submitted to {api_url}")
460
+ product = data.get("product") or {}
461
+ print(f" product : {product.get('name')} ({data.get('product_id')})")
462
+ print(f" components : {s.get('components_total', '?')}")
463
+ print(f" vulnerable : {s.get('components_vulnerable', 0)}")
464
+ print(f" new CVEs : {len(data.get('new_cve_ids') or [])}")
465
+ skipped = data.get("skipped") or []
466
+ if skipped:
467
+ print(f" skipped : {len(skipped)} (unsupported ecosystem)")
468
+
469
+
470
+ def main(argv=None):
471
+ argv = list(sys.argv[1:] if argv is None else argv)
472
+ try:
473
+ positional, flags = parse_args(argv)
474
+ cmd = positional.pop(0) if positional else None
475
+
476
+ if not cmd or flags.get("help") is not None or cmd == "help":
477
+ print(USAGE)
478
+ return 0
479
+ if cmd == "login":
480
+ cmd_login(flags)
481
+ elif cmd == "whoami":
482
+ cmd_whoami(flags)
483
+ elif cmd == "scan":
484
+ cmd_scan(positional, flags)
485
+ else:
486
+ print(f"unknown command: {cmd}\n", file=sys.stderr)
487
+ print(USAGE)
488
+ return 1
489
+ return 0
490
+ except BrokenPipeError:
491
+ # stdout closed early (e.g. piped to `head`) — exit cleanly.
492
+ try:
493
+ sys.stdout.close()
494
+ except Exception:
495
+ pass
496
+ return 0
497
+ except KeyboardInterrupt:
498
+ return 130
499
+ except Exception as err: # noqa: BLE001 — single top-level reporter
500
+ print(f"synapse-sbom: {err}", file=sys.stderr)
501
+ return 1
502
+
503
+
504
+ if __name__ == "__main__":
505
+ sys.exit(main())