pypispdx 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.
pypispdx-0.1.0/LICENSE ADDED
@@ -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,140 @@
1
+ Metadata-Version: 2.4
2
+ Name: pypispdx
3
+ Version: 0.1.0
4
+ Summary: An SCA tool for creating an SPDX SBOM for a https://pypi.org/ package
5
+ Author-email: Marc-Etienne Vargenau <marc-etienne.vargenau@nokia.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/nokia/pypispdx
8
+ Project-URL: Issues, https://github.com/nokia/pypispdx/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: requests>=2.32.4
15
+ Requires-Dist: spdx-license-list>=3.27
16
+ Requires-Dist: spdx-tools>=0.8.3
17
+ Dynamic: license-file
18
+
19
+ # pypispdx
20
+
21
+ An SCA tool for creating an SPDX SBOM for a https://pypi.org/ package.
22
+
23
+ # Usage
24
+
25
+ ```
26
+ usage: pypispdx [-h] [--json | --rdf | --xml | --yaml] [--debug] package
27
+ ```
28
+
29
+ where “package” is a Python package avalable on https://pypi.org/
30
+
31
+ ```
32
+ options:
33
+ -h, --help Shows this help message and exits.
34
+ --debug Enable debug output, including detailed messages and full tracebacks.
35
+ --json Output the result in SPDX JSON format.
36
+ --rdf Output the result in SPDX RDF format.
37
+ --xml Output the result in SPDX XML format.
38
+ --yaml Output the result in SPDX YAML format.
39
+ ```
40
+
41
+ It will create an SPDX 2.3 SBOM for the latest available release of the package,
42
+ including all transitive dependencies.
43
+
44
+ By default, the output will be in tag:value format. The other formats, JSON, RDF,
45
+ XML and YAML are available by using the corresponding command-line option.
46
+
47
+ The SBOM filename will be ```package-version.spdx``` (plus the corresponding
48
+ suffix for the other formats), where the package name will be in lower case,
49
+ with underscores and dots replaced by dash.
50
+
51
+ Running again the command will give a different result if a newer version of the package or its
52
+ transitive dependencies are available.
53
+
54
+ Running the command with different versions of Python might give different results
55
+ as different versions of transitive dependencies might be selected.
56
+
57
+ ## Content of the SBOM
58
+
59
+ The Creator Organization will be taken from the ORGANIZATION environment variable.
60
+ If not set, it will be “UNKNOWN”.
61
+
62
+ The DocumentNamespace will be ```https://pypi.org/spdx/```package-version
63
+
64
+ For each package, the ```PackageSupplier``` will be “Organization: https://pypi.org”.
65
+
66
+ The ```PackageDownloadLocation``` will be a “.tar.gz” file if available.
67
+ If not available, it will be NOASSERTION.
68
+
69
+ If available, the ```PackageChecksum``` will be provided in both SHA256 and MD5.
70
+
71
+ The ```PackageLicenseConcluded``` and ```PackageLicenseDeclared``` will be given if available on PyPI.
72
+ If not, it will be NOASSERTION. See more details below.
73
+
74
+ The ```PackageCopyrightText``` will always be NOASSERTION.
75
+
76
+ The [PURL](https://github.com/package-url/purl-spec/) (Package URL) will be provided
77
+ in the ```ExternalRef``` field.
78
+
79
+ ## Licenses
80
+
81
+ First, the licenses will be searched in “license_expression” as specified in
82
+ [PEP 639](https://peps.python.org/pep-0639/).
83
+
84
+ If not available, the licenses will be searched in “license”
85
+
86
+ If no “license_expression” and no “license” they will be searched in “classifiers”
87
+
88
+ If the classifier is ambiguous, for example:
89
+ ```
90
+ License :: OSI Approved :: GNU General Public License (GPL)
91
+ ```
92
+ a ```LicenseRef-``` is created with that text.
93
+
94
+ When the license is specified with a ```LicenseRef-```, the text of the license
95
+ is retreived from the license file and put in the SBOM.
96
+
97
+ See for example [infinity-grid](https://pypi.org/project/infinity-grid/).
98
+
99
+ ## About PURL specification
100
+
101
+ The name is case insensitive and lowercased.
102
+
103
+ Underscore “_” is replaced with dash “-”.
104
+
105
+ Dot “.” is replaced with dash “-”.
106
+
107
+ ## Compliance
108
+
109
+ The SBOM is valid SPDX 2.3.
110
+
111
+ It is compliant with the [OpenChain Telco SBOM Guide](https://github.com/OpenChain-Project/Telco-WG/blob/main/OpenChain-Telco-SBOM-Guide_EN.md).
112
+
113
+ You can check it with the [openchain-telco-sbom-validator](https://pypi.org/project/openchain-telco-sbom-validator/).
114
+
115
+ ## When an SBOM cannot be created
116
+
117
+ ### Versions incompatibility
118
+
119
+ Running ```pypispdx``` with Python 3.14
120
+ ```
121
+ pypispdx google-ads-reports
122
+ Creating SPDX SBOM for PyPI package google-ads-reports
123
+ ERROR: Ignored the following versions that require a different python version:
124
+ 1.0 Requires-Python >=3.9,<3.13;
125
+ 1.0.1 Requires-Python >=3.9,<3.13;
126
+ 1.1.0 Requires-Python >=3.9,<3.13;
127
+ 1.2.0 Requires-Python >=3.9,<3.13;
128
+ 1.2.1 Requires-Python >=3.10,<3.13;
129
+ 1.2.2 Requires-Python >=3.10,<3.13;
130
+ 1.2.3 Requires-Python >=3.10,<3.13;
131
+ 1.3.0 Requires-Python >=3.10,<3.13;
132
+ 2.0.0 Requires-Python >=3.12,<3.13;
133
+ 2.0.1 Requires-Python >=3.12,<3.13;
134
+ 2.0.2 Requires-Python >=3.11,<3.14
135
+ ERROR: Could not find a version that satisfies the requirement google-ads-reports (from versions: none)
136
+ ERROR: No matching distribution found for google-ads-reports
137
+ Cannot create SBOM for google-ads-reports
138
+ ```
139
+
140
+ The SBOM cannot be created as ```google-ads-reports``` cannot currently be installed with Python 3.14.
@@ -0,0 +1,122 @@
1
+ # pypispdx
2
+
3
+ An SCA tool for creating an SPDX SBOM for a https://pypi.org/ package.
4
+
5
+ # Usage
6
+
7
+ ```
8
+ usage: pypispdx [-h] [--json | --rdf | --xml | --yaml] [--debug] package
9
+ ```
10
+
11
+ where “package” is a Python package avalable on https://pypi.org/
12
+
13
+ ```
14
+ options:
15
+ -h, --help Shows this help message and exits.
16
+ --debug Enable debug output, including detailed messages and full tracebacks.
17
+ --json Output the result in SPDX JSON format.
18
+ --rdf Output the result in SPDX RDF format.
19
+ --xml Output the result in SPDX XML format.
20
+ --yaml Output the result in SPDX YAML format.
21
+ ```
22
+
23
+ It will create an SPDX 2.3 SBOM for the latest available release of the package,
24
+ including all transitive dependencies.
25
+
26
+ By default, the output will be in tag:value format. The other formats, JSON, RDF,
27
+ XML and YAML are available by using the corresponding command-line option.
28
+
29
+ The SBOM filename will be ```package-version.spdx``` (plus the corresponding
30
+ suffix for the other formats), where the package name will be in lower case,
31
+ with underscores and dots replaced by dash.
32
+
33
+ Running again the command will give a different result if a newer version of the package or its
34
+ transitive dependencies are available.
35
+
36
+ Running the command with different versions of Python might give different results
37
+ as different versions of transitive dependencies might be selected.
38
+
39
+ ## Content of the SBOM
40
+
41
+ The Creator Organization will be taken from the ORGANIZATION environment variable.
42
+ If not set, it will be “UNKNOWN”.
43
+
44
+ The DocumentNamespace will be ```https://pypi.org/spdx/```package-version
45
+
46
+ For each package, the ```PackageSupplier``` will be “Organization: https://pypi.org”.
47
+
48
+ The ```PackageDownloadLocation``` will be a “.tar.gz” file if available.
49
+ If not available, it will be NOASSERTION.
50
+
51
+ If available, the ```PackageChecksum``` will be provided in both SHA256 and MD5.
52
+
53
+ The ```PackageLicenseConcluded``` and ```PackageLicenseDeclared``` will be given if available on PyPI.
54
+ If not, it will be NOASSERTION. See more details below.
55
+
56
+ The ```PackageCopyrightText``` will always be NOASSERTION.
57
+
58
+ The [PURL](https://github.com/package-url/purl-spec/) (Package URL) will be provided
59
+ in the ```ExternalRef``` field.
60
+
61
+ ## Licenses
62
+
63
+ First, the licenses will be searched in “license_expression” as specified in
64
+ [PEP 639](https://peps.python.org/pep-0639/).
65
+
66
+ If not available, the licenses will be searched in “license”
67
+
68
+ If no “license_expression” and no “license” they will be searched in “classifiers”
69
+
70
+ If the classifier is ambiguous, for example:
71
+ ```
72
+ License :: OSI Approved :: GNU General Public License (GPL)
73
+ ```
74
+ a ```LicenseRef-``` is created with that text.
75
+
76
+ When the license is specified with a ```LicenseRef-```, the text of the license
77
+ is retreived from the license file and put in the SBOM.
78
+
79
+ See for example [infinity-grid](https://pypi.org/project/infinity-grid/).
80
+
81
+ ## About PURL specification
82
+
83
+ The name is case insensitive and lowercased.
84
+
85
+ Underscore “_” is replaced with dash “-”.
86
+
87
+ Dot “.” is replaced with dash “-”.
88
+
89
+ ## Compliance
90
+
91
+ The SBOM is valid SPDX 2.3.
92
+
93
+ It is compliant with the [OpenChain Telco SBOM Guide](https://github.com/OpenChain-Project/Telco-WG/blob/main/OpenChain-Telco-SBOM-Guide_EN.md).
94
+
95
+ You can check it with the [openchain-telco-sbom-validator](https://pypi.org/project/openchain-telco-sbom-validator/).
96
+
97
+ ## When an SBOM cannot be created
98
+
99
+ ### Versions incompatibility
100
+
101
+ Running ```pypispdx``` with Python 3.14
102
+ ```
103
+ pypispdx google-ads-reports
104
+ Creating SPDX SBOM for PyPI package google-ads-reports
105
+ ERROR: Ignored the following versions that require a different python version:
106
+ 1.0 Requires-Python >=3.9,<3.13;
107
+ 1.0.1 Requires-Python >=3.9,<3.13;
108
+ 1.1.0 Requires-Python >=3.9,<3.13;
109
+ 1.2.0 Requires-Python >=3.9,<3.13;
110
+ 1.2.1 Requires-Python >=3.10,<3.13;
111
+ 1.2.2 Requires-Python >=3.10,<3.13;
112
+ 1.2.3 Requires-Python >=3.10,<3.13;
113
+ 1.3.0 Requires-Python >=3.10,<3.13;
114
+ 2.0.0 Requires-Python >=3.12,<3.13;
115
+ 2.0.1 Requires-Python >=3.12,<3.13;
116
+ 2.0.2 Requires-Python >=3.11,<3.14
117
+ ERROR: Could not find a version that satisfies the requirement google-ads-reports (from versions: none)
118
+ ERROR: No matching distribution found for google-ads-reports
119
+ Cannot create SBOM for google-ads-reports
120
+ ```
121
+
122
+ The SBOM cannot be created as ```google-ads-reports``` cannot currently be installed with Python 3.14.
@@ -0,0 +1,27 @@
1
+ [project]
2
+ name = "pypispdx"
3
+ version = "0.1.0"
4
+ authors = [
5
+ { name="Marc-Etienne Vargenau", email="marc-etienne.vargenau@nokia.com" },
6
+ ]
7
+ description = "An SCA tool for creating an SPDX SBOM for a https://pypi.org/ package"
8
+ readme = "README.md"
9
+ requires-python = ">=3.10"
10
+ dependencies = [
11
+ "requests>=2.32.4",
12
+ "spdx-license-list>=3.27",
13
+ "spdx-tools>=0.8.3",
14
+ ]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Operating System :: OS Independent",
18
+ ]
19
+ license = "Apache-2.0"
20
+ license-files = ["LICENSE"]
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/nokia/pypispdx"
24
+ Issues = "https://github.com/nokia/pypispdx/issues"
25
+
26
+ [project.scripts]
27
+ pypispdx = "pypispdx.pypispdx:main"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,566 @@
1
+ #!/bin/python3
2
+
3
+ # © 2025 Nokia
4
+ # Author: Marc-Etienne Vargenau
5
+ # Licensed under the Apache License 2.0
6
+ # SPDX-License-Identifier: Apache-2.0
7
+
8
+ """Module creating an SPDX SBOM for a pypi.org package."""
9
+
10
+ import sys
11
+ import os
12
+ import platform
13
+ import datetime
14
+ import re
15
+ import json
16
+ import urllib.request
17
+ import tarfile
18
+ import subprocess
19
+ import argparse
20
+ import traceback # Import traceback for detailed error logging
21
+ import requests
22
+ import spdx_license_list
23
+ from spdx_tools.spdx.parser.parse_anything import parse_file
24
+ from spdx_tools.spdx.writer.write_anything import write_file
25
+
26
+ # --- Constants for improved readability and maintainability ---
27
+ SPDX_VERSION = "SPDX-2.3"
28
+ DATA_LICENSE = "CC0-1.0"
29
+ SPDX_DOCUMENT_REF = "SPDXRef-DOCUMENT"
30
+ CREATOR_TOOL = "pypispdx - 0.1.0"
31
+ LICENSE_LIST_VERSION = "3.27"
32
+ CISA_SBOM_TYPE = "Analyzed"
33
+ PACKAGE_SUPPLIER = "Organization: https://pypi.org"
34
+ FILES_ANALYZED = "false"
35
+ PACKAGE_COPYRIGHT_TEXT = "NOASSERTION"
36
+ PURL_EXTERNAL_REF_TYPE = "PACKAGE-MANAGER purl pkg:pypi/"
37
+
38
+ # Mapping for common OSI-approved licenses from classifiers
39
+ CLASSIFIER_LICENSE_MAP = {
40
+ "License :: Aladdin Free Public License (AFPL)": "Aladdin",
41
+ "License :: Nokia Open Source License (NOKOS)": "Nokia",
42
+ "License :: OSI Approved :: Apache Software License": "Apache-2.0",
43
+ "License :: OSI Approved :: Attribution Assurance License": "AAL",
44
+ "License :: OSI Approved :: Boost Software License 1.0 (BSL-1.0)": "BSL-1.0",
45
+ "License :: OSI Approved :: CEA CNRS Inria Logiciel Libre License, version 2.1 (CeCILL-2.1)": "CECILL-2.1",
46
+ "License :: OSI Approved :: Common Public License": "CPL-1.0",
47
+ "License :: OSI Approved :: European Union Public Licence 1.0 (EUPL 1.0)": "EUPL-1.0",
48
+ "License :: OSI Approved :: European Union Public Licence 1.1 (EUPL 1.1)": "EUPL-1.1",
49
+ "License :: OSI Approved :: GNU Affero General Public License v3": "AGPL-3.0-only",
50
+ "License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)": "AGPL-3.0-or-later",
51
+ "License :: OSI Approved :: GNU General Public License v2 (GPLv2)": "GPL-2.0-only",
52
+ "License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)": "GPL-2.0-or-later",
53
+ "License :: OSI Approved :: GNU General Public License v3 (GPLv3)": "GPL-3.0-only",
54
+ "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)": "GPL-3.0-or-later",
55
+ "License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+)": "LGPL-2.0-or-later",
56
+ "License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)": "LGPL-3.0-only",
57
+ "License :: OSI Approved :: GNU Lesser General Public License v3 or later (LGPLv3+)": "LGPL-3.0-or-later",
58
+ "License :: OSI Approved :: IBM Public License": "IPL-1.0",
59
+ "License :: OSI Approved :: Intel Open Source License": "Intel",
60
+ "License :: OSI Approved :: ISC License (ISCL)": "ISC",
61
+ "License :: OSI Approved :: MIT License": "MIT",
62
+ "License :: OSI Approved :: Motosoto License": "Motosoto",
63
+ "License :: OSI Approved :: Mozilla Public License 1.0 (MPL)": "MPL-1.0",
64
+ "License :: OSI Approved :: Mozilla Public License 1.1 (MPL 1.1)": "MPL-1.1",
65
+ "License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)": "MPL-2.0",
66
+ "License :: OSI Approved :: Nethack General Public License": "NGPL",
67
+ "License :: OSI Approved :: Nokia Open Source License": "Nokia",
68
+ "License :: OSI Approved :: Open Group Test Suite License": "OGTSL",
69
+ "License :: OSI Approved :: Python License (CNRI Python License)": "CNRI-Python",
70
+ "License :: OSI Approved :: Python Software Foundation License": "PSF-2.0",
71
+ "License :: OSI Approved :: Ricoh Source Code Public License": "RSCPL",
72
+ "License :: OSI Approved :: Sleepycat License": "Sleepycat",
73
+ "License :: OSI Approved :: Sun Public License": "SPL-1.0",
74
+ "License :: OSI Approved :: The Unlicense (Unlicense)": "Unlicense",
75
+ "License :: OSI Approved :: University of Illinois/NCSA Open Source License": "NCSA",
76
+ "License :: OSI Approved :: Vovida Software License 1.0": "VSL-1.0",
77
+ "License :: OSI Approved :: W3C License": "W3C-20150513",
78
+ "License :: OSI Approved :: X.Net License": "Xnet",
79
+ }
80
+
81
+ # Deprecated license identifiers mapping
82
+ DEPRECATED_LICENSES_MAP = {
83
+ "GPL-2.0": "GPL-2.0-only",
84
+ "GPL-2.0+": "GPL-2.0-or-later",
85
+ "LGPL-2.0": "LGPL-2.0-only",
86
+ "LGPL-2.0+": "LGPL-2.0-or-later",
87
+ "LGPL-2.1": "LGPL-2.1-only",
88
+ "LGPL-2.1+": "LGPL-2.1-or-later",
89
+ }
90
+
91
+ class PyPISPDXError(Exception):
92
+ """Custom exception for PyPI SPDX generation errors."""
93
+ pass
94
+
95
+ def dash_name(input_string: str) -> str:
96
+ """
97
+ Replaces underscore and dot characters in a string with dashes,
98
+ and converts uppercase letters to lowercase.
99
+
100
+ Parameter:
101
+ - input_string (str): The string to process.
102
+
103
+ Returns:
104
+ - str: The processed string.
105
+ """
106
+ return input_string.strip().replace("_", "-").replace(".", "-").lower()
107
+
108
+ def get_package_info(package_name: str, debug_mode: bool) -> dict | None:
109
+ """
110
+ Fetches information about a package from PyPI.
111
+
112
+ Parameter:
113
+ - package_name (str): The name of the package to fetch information about.
114
+ - debug_mode (bool): If True, print debug information.
115
+
116
+ Returns:
117
+ - dict: A dictionary containing the package information, or None if not found or an error occurs.
118
+ """
119
+ dashed_package_name = dash_name(package_name)
120
+ url = f"https://pypi.org/pypi/{dashed_package_name}/json"
121
+ if debug_mode:
122
+ print(f"DEBUG: Fetching package info from: {url}", file=sys.stderr)
123
+ try:
124
+ response = requests.get(url, timeout=10) # Added timeout for robustness
125
+ if debug_mode:
126
+ print(f"DEBUG: Response status for {package_name}: {response.status_code}", file=sys.stderr)
127
+ response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)
128
+ return response.json()
129
+ except requests.exceptions.RequestException as e:
130
+ print(f"Error fetching package info for {package_name}: {e}", file=sys.stderr)
131
+ if debug_mode:
132
+ traceback.print_exc(file=sys.stderr)
133
+ return None
134
+
135
+ def print_spdx_header(package_name: str, package_version: str, sbom_file_object) -> None:
136
+ """
137
+ Prints the SPDX header to the SBOM file.
138
+
139
+ Parameters:
140
+ - package_name (str): The name of the main package.
141
+ - package_version (str): The version of the main package.
142
+ - sbom_file_object (io.TextIOWrapper): The SBOM file object where to write.
143
+ """
144
+ dashed_package_name = dash_name(package_name)
145
+
146
+ sbom_file_object.write(f"SPDXVersion: {SPDX_VERSION}\n")
147
+ sbom_file_object.write(f"DataLicense: {DATA_LICENSE}\n")
148
+ sbom_file_object.write(f"SPDXID: {SPDX_DOCUMENT_REF}\n")
149
+ sbom_file_object.write(f"DocumentName: {dashed_package_name}-{package_version}\n")
150
+
151
+ sbom_file_object.write(f"DocumentNamespace: https://pypi.org/spdx/{dashed_package_name}-{package_version}\n\n")
152
+
153
+ sbom_file_object.write("## Creation Information\n\n")
154
+ sbom_file_object.write(f"LicenseListVersion: {LICENSE_LIST_VERSION}\n")
155
+
156
+ organization = os.getenv("ORGANIZATION", "UNKNOWN")
157
+ sbom_file_object.write(f"Creator: Organization: {organization}\n")
158
+ sbom_file_object.write(f"Creator: Tool: {CREATOR_TOOL}\n")
159
+
160
+ # Use datetime.UTC if available (Python 3.11+), otherwise use datetime.timezone.utc
161
+ utc_tz = getattr(datetime, 'UTC', datetime.timezone.utc)
162
+ sbom_file_object.write(f"Created: {datetime.datetime.now(utc_tz).strftime('%Y-%m-%dT%H:%M:%SZ')}\n")
163
+ sbom_file_object.write("CreatorComment: <text>")
164
+ sbom_file_object.write(f"CISA SBOM type: {CISA_SBOM_TYPE}\n")
165
+ sbom_file_object.write(f"This SBOM was created with Python version {platform.python_version()}")
166
+ sbom_file_object.write("</text>\n\n")
167
+
168
+ def _get_spdx_license_from_classifiers(classifiers: list, unknown_licenses_list: list, debug_mode: bool) -> str | None:
169
+ """
170
+ Determines the SPDX license identifier(s) from PyPI classifiers.
171
+
172
+ Parameters:
173
+ - classifiers (list): List of classifier strings from PyPI.
174
+ - unknown_licenses_list (list): A list to append details of unknown licenses.
175
+ - debug_mode (bool): If True, print debug information.
176
+
177
+ Returns:
178
+ - str | None: The SPDX license expression, or None if no license could be determined.
179
+ """
180
+ licenses = set()
181
+ for classifier in classifiers:
182
+ if classifier in CLASSIFIER_LICENSE_MAP:
183
+ licenses.add(CLASSIFIER_LICENSE_MAP[classifier])
184
+ if debug_mode:
185
+ print(f"DEBUG: Classifier '{classifier}' mapped to SPDX '{CLASSIFIER_LICENSE_MAP[classifier]}'", file=sys.stderr)
186
+ elif classifier.startswith("License ::") and classifier != "License :: OSI Approved":
187
+ # Generate a unique LicenseRef for unknown licenses
188
+ licenseref_base = re.sub(r'[^a-zA-Z0-9]', '-', classifier)
189
+ licenseref = "LicenseRef-unknown-" + re.sub('-+', '-', licenseref_base).strip('-')
190
+ licenses.add(licenseref)
191
+ unknown = {"id": licenseref, "text": classifier}
192
+ if unknown not in unknown_licenses_list:
193
+ unknown_licenses_list.append(unknown)
194
+ if debug_mode:
195
+ print(f"DEBUG: Classifier '{classifier}' identified as unknown, assigned LicenseRef '{licenseref}'", file=sys.stderr)
196
+
197
+ if len(licenses) == 1:
198
+ return list(licenses)[0]
199
+ elif len(licenses) >= 2:
200
+ return " AND ".join(sorted(licenses))
201
+ return None
202
+
203
+ def print_package(package_name: str, package_version: str, sbom_file_object,
204
+ custom_licenses_list: list, unknown_licenses_list: list, debug_mode: bool) -> None:
205
+ """
206
+ Prints the SPDX package information to the SBOM file.
207
+
208
+ Parameters:
209
+ - package_name (str): The name of the package.
210
+ - package_version (str): The version of the package.
211
+ - sbom_file_object (io.TextIOWrapper): The SBOM file object where to write.
212
+ - custom_licenses_list (list): A list to store custom license details.
213
+ - unknown_licenses_list (list): A list to store unknown license details.
214
+ - debug_mode (bool): If True, print debug information.
215
+ """
216
+ dashed_package_name = dash_name(package_name)
217
+ if debug_mode:
218
+ print(f"DEBUG: Processing package: {package_name} (version: {package_version})", file=sys.stderr)
219
+ package_info = get_package_info(dashed_package_name, debug_mode)
220
+
221
+ if not package_info:
222
+ raise PyPISPDXError(f"Package '{package_name}' cannot be found in https://pypi.org/")
223
+
224
+ info = package_info["info"]
225
+
226
+ sbom_file_object.write(f"##### Package: {dashed_package_name}\n\n")
227
+ sbom_file_object.write(f"PackageName: {dashed_package_name}\n")
228
+ sbom_file_object.write(f"SPDXID: SPDXRef-{dashed_package_name}\n")
229
+ sbom_file_object.write(f"PackageVersion: {package_version}\n")
230
+ sbom_file_object.write(f"PackageSupplier: {PACKAGE_SUPPLIER}\n")
231
+
232
+ download_location = "NOASSERTION"
233
+ sha256 = ""
234
+ md5 = ""
235
+
236
+ # Find the .tar.gz distribution for the specific version
237
+ releases = package_info.get("releases", {})
238
+ if package_version in releases:
239
+ if debug_mode:
240
+ print(f"DEBUG: Looking for tar.gz for {package_name}@{package_version} in releases.", file=sys.stderr)
241
+ for release_file in releases[package_version]:
242
+ filename = release_file.get("filename", "").lower()
243
+ if filename.endswith(".tar.gz"):
244
+ # Ensure we pick the correct tar.gz for the package name
245
+ # e.g., 'mypackage-1.0.tar.gz' for 'mypackage'
246
+ filename = filename.removesuffix("-" + package_version + ".tar.gz")
247
+ filename = filename.replace(".", "-")
248
+ underscored_package_name = package_name.replace("-", "_").replace(".", "_").lower()
249
+ if filename in (underscored_package_name, dashed_package_name, package_name):
250
+ download_location = release_file.get("url", "NOASSERTION")
251
+ digests = release_file.get("digests", {})
252
+ sha256 = digests.get("sha256", "")
253
+ md5 = digests.get("md5", "")
254
+ if debug_mode:
255
+ print(f"DEBUG: Found tar.gz: {filename}, URL: {download_location}", file=sys.stderr)
256
+ break # Found the relevant tar.gz, exit loop
257
+ else:
258
+ if debug_mode:
259
+ print(f"DEBUG: No releases found for {package_name}@{package_version}.", file=sys.stderr)
260
+
261
+
262
+ sbom_file_object.write(f"PackageDownloadLocation: {download_location}\n")
263
+ sbom_file_object.write(f"FilesAnalyzed: {FILES_ANALYZED}\n")
264
+
265
+ if sha256:
266
+ sbom_file_object.write(f"PackageChecksum: SHA256: {sha256}\n")
267
+ if md5:
268
+ sbom_file_object.write(f"PackageChecksum: MD5: {md5}\n")
269
+
270
+ spdx_license = info.get("license_expression")
271
+ if debug_mode:
272
+ print(f"DEBUG: Initial license_expression for {package_name}: {spdx_license}", file=sys.stderr)
273
+
274
+ # If no license_expression, try 'license' field
275
+ if not spdx_license:
276
+ license_field = info.get("license")
277
+ if license_field:
278
+ if debug_mode:
279
+ print(f"DEBUG: No license_expression, checking 'license' field: {license_field}", file=sys.stderr)
280
+ if license_field in spdx_license_list.LICENSES:
281
+ spdx_license = DEPRECATED_LICENSES_MAP.get(license_field, license_field)
282
+ if debug_mode:
283
+ print(f"DEBUG: 'license' field is valid SPDX: {spdx_license}", file=sys.stderr)
284
+ else:
285
+ if debug_mode:
286
+ print(f"DEBUG: 'license' field '{license_field}' is not a known SPDX ID.", file=sys.stderr)
287
+ # If 'license' field is not a known SPDX ID, treat as NOASSERTION for now
288
+ # and check classifiers next.
289
+ pass
290
+
291
+ # Check for custom licenses (LicenseRef- with no spaces)
292
+ if spdx_license and spdx_license.startswith("LicenseRef-") and " " not in spdx_license:
293
+ license_files = info.get("license_files", [])
294
+ if len(license_files) == 1:
295
+ custom = {"id": spdx_license, "file": license_files[0], "download_location": download_location}
296
+ custom_licenses_list.append(custom)
297
+ if debug_mode:
298
+ print(f"DEBUG: Identified custom license: {spdx_license} from file {license_files[0]}", file=sys.stderr)
299
+
300
+ # If still no license, try classifiers
301
+ if not spdx_license or spdx_license == "NOASSERTION": # Check for explicit NOASSERTION from previous step
302
+ if debug_mode:
303
+ print(f"DEBUG: No license found yet, checking classifiers for {package_name}.", file=sys.stderr)
304
+ classifiers = info.get("classifiers", [])
305
+ classifier_spdx_license = _get_spdx_license_from_classifiers(classifiers, unknown_licenses_list, debug_mode)
306
+ if classifier_spdx_license:
307
+ spdx_license = classifier_spdx_license
308
+ if debug_mode:
309
+ print(f"DEBUG: License determined from classifiers: {spdx_license}", file=sys.stderr)
310
+ else:
311
+ spdx_license = "NOASSERTION" # Default if nothing found
312
+ if debug_mode:
313
+ print(f"DEBUG: No license could be determined for {package_name}, setting to NOASSERTION.", file=sys.stderr)
314
+
315
+ sbom_file_object.write(f"PackageLicenseConcluded: {spdx_license}\n")
316
+ sbom_file_object.write(f"PackageLicenseDeclared: {spdx_license}\n")
317
+ sbom_file_object.write(f"PackageCopyrightText: {PACKAGE_COPYRIGHT_TEXT}\n")
318
+ sbom_file_object.write(f"ExternalRef: {PURL_EXTERNAL_REF_TYPE}{dashed_package_name}@{package_version}\n\n")
319
+
320
+ def _process_custom_license_file(custom_license_entry: dict, sbom_file_object, debug_mode: bool) -> None:
321
+ """
322
+ Downloads, extracts, and writes the text of a custom license to the SBOM.
323
+
324
+ Parameters:
325
+ - custom_license_entry (dict): Dictionary containing 'id', 'file', and 'download_location'.
326
+ - sbom_file_object (io.TextIOWrapper): The SBOM file object where to write.
327
+ - debug_mode (bool): If True, print debug information.
328
+ """
329
+ license_id = custom_license_entry["id"]
330
+ download_url = custom_license_entry["download_location"]
331
+ license_file_in_archive = custom_license_entry["file"]
332
+
333
+ if debug_mode:
334
+ print(f"DEBUG: Processing custom license '{license_id}' from '{download_url}'", file=sys.stderr)
335
+
336
+ sbom_file_object.write(f"LicenseID: {license_id}\n")
337
+ license_name = license_id.replace('LicenseRef-', '')
338
+ sbom_file_object.write(f"LicenseName: {license_name}\n")
339
+
340
+ if download_url == "NOASSERTION":
341
+ sbom_file_object.write("ExtractedText: <text>License file not available for download.</text>\n")
342
+ if debug_mode:
343
+ print(f"DEBUG: Custom license '{license_id}' has NOASSERTION download location.", file=sys.stderr)
344
+ return
345
+
346
+ tar_filename = os.path.basename(download_url)
347
+ temp_dir = f"temp_license_extract_{os.getpid()}" # Use PID for unique temp dir
348
+
349
+ try:
350
+ os.makedirs(temp_dir, exist_ok=True)
351
+ temp_tar_path = os.path.join(temp_dir, tar_filename)
352
+
353
+ if debug_mode:
354
+ print(f"DEBUG: Downloading custom license from {download_url} to {temp_tar_path}", file=sys.stderr)
355
+ urllib.request.urlretrieve(download_url, temp_tar_path)
356
+
357
+ with tarfile.open(temp_tar_path, "r:gz") as tar:
358
+ # Extract only the specific license file to avoid extracting everything
359
+ # Find the member that matches the license file path
360
+ members = [m for m in tar.getmembers() if m.name.endswith(license_file_in_archive)]
361
+ if not members:
362
+ raise PyPISPDXError(f"License file '{license_file_in_archive}' not found in archive '{tar_filename}'")
363
+
364
+ # Extract the first matching member
365
+ extracted_member_name = members[0].name
366
+ if debug_mode:
367
+ print(f"DEBUG: Extracting '{extracted_member_name}' from '{tar_filename}'", file=sys.stderr)
368
+ tar.extract(members[0], path=temp_dir)
369
+ extracted_file_path = os.path.join(temp_dir, extracted_member_name)
370
+
371
+ with open(extracted_file_path, "rb") as lic_f:
372
+ lic_text = lic_f.read().decode("utf-8", errors='replace') # Use 'replace' for encoding errors
373
+
374
+ sbom_file_object.write("ExtractedText: <text>")
375
+ sbom_file_object.write(lic_text)
376
+ sbom_file_object.write("</text>\n")
377
+
378
+ except (urllib.error.URLError, tarfile.ReadError, IOError, PyPISPDXError) as e:
379
+ print(f"Warning: Could not process custom license '{license_id}' from '{download_url}': {e}", file=sys.stderr)
380
+ if debug_mode:
381
+ traceback.print_exc(file=sys.stderr)
382
+ sbom_file_object.write(f"ExtractedText: <text>Error retrieving or extracting license text: {e}</text>\n")
383
+ finally:
384
+ # Clean up temporary files and directory
385
+ if os.path.exists(temp_dir):
386
+ if debug_mode:
387
+ print(f"DEBUG: Cleaning up temporary directory: {temp_dir}", file=sys.stderr)
388
+ for root, dirs, files in os.walk(temp_dir, topdown=False):
389
+ for name in files:
390
+ os.remove(os.path.join(root, name))
391
+ for name in dirs:
392
+ os.rmdir(os.path.join(root, name))
393
+ os.rmdir(temp_dir)
394
+
395
+ def main():
396
+ """
397
+ Main function to generate an SPDX SBOM for a PyPI package and its dependencies.
398
+ """
399
+ parser = argparse.ArgumentParser(
400
+ description="Create an SPDX SBOM for a pypi.org package and its dependencies."
401
+ )
402
+ parser.add_argument(
403
+ "package_name",
404
+ help="The name of the PyPI package to create an SBOM for."
405
+ )
406
+ parser.add_argument(
407
+ "--debug",
408
+ action="store_true",
409
+ help="Enable debug output, including detailed messages and full tracebacks."
410
+ )
411
+ spdxformat = parser.add_mutually_exclusive_group()
412
+ spdxformat.add_argument(
413
+ "--json",
414
+ action="store_true",
415
+ help="Output the result in SPDX JSON format."
416
+ )
417
+ spdxformat.add_argument(
418
+ "--rdf",
419
+ action="store_true",
420
+ help="Output the result in SPDX RDF format."
421
+ )
422
+ spdxformat.add_argument(
423
+ "--xml",
424
+ action="store_true",
425
+ help="Output the result in SPDX XML format."
426
+ )
427
+ spdxformat.add_argument(
428
+ "--yaml",
429
+ action="store_true",
430
+ help="Output the result in SPDX YAML format."
431
+ )
432
+ args = parser.parse_args()
433
+
434
+ main_package_name = args.package_name
435
+ debug_mode = args.debug
436
+
437
+ if debug_mode:
438
+ print("DEBUG: Debug mode is enabled.", file=sys.stderr)
439
+ print(f"Creating SPDX SBOM for PyPI package {main_package_name}")
440
+
441
+ sbom_filename = "" # Initialize for cleanup in case of early error
442
+ try:
443
+ main_package_info = get_package_info(main_package_name, debug_mode)
444
+ if not main_package_info:
445
+ raise PyPISPDXError(f"Main package '{main_package_name}' cannot be found in https://pypi.org/")
446
+
447
+ main_info = main_package_info["info"]
448
+ main_version = main_info["version"]
449
+ main_package_dashed = dash_name(main_package_name)
450
+
451
+ sbom_filename = f"{main_package_dashed}-{main_version}.spdx"
452
+ custom_licenses = []
453
+ unknown_licenses = []
454
+
455
+ with open(sbom_filename, "w", encoding="utf-8") as sbom:
456
+ print_spdx_header(main_package_name, main_version, sbom)
457
+ print_package(main_package_name, main_version, sbom, custom_licenses, unknown_licenses, debug_mode)
458
+
459
+ # Use subprocess.run for better control over external commands
460
+ temp_json_report = f"{main_package_dashed}_pip_report.json"
461
+ pip_command = [
462
+ sys.executable, "-m", "pip", "install",
463
+ "--dry-run", "--ignore-installed",
464
+ main_package_name,
465
+ "--report", temp_json_report
466
+ ]
467
+ if debug_mode:
468
+ print(f"DEBUG: Running pip command to get dependencies: {' '.join(pip_command)}", file=sys.stderr)
469
+ try:
470
+ result = subprocess.run(pip_command, check=True, capture_output=True, text=True)
471
+ if debug_mode:
472
+ print(f"DEBUG: pip stdout:\n{result.stdout}", file=sys.stderr)
473
+ print(f"DEBUG: pip stderr:\n{result.stderr}", file=sys.stderr)
474
+ except subprocess.CalledProcessError as e:
475
+ print(f"Error running pip: {e.stderr}", file=sys.stderr)
476
+ if debug_mode:
477
+ traceback.print_exc(file=sys.stderr)
478
+ raise PyPISPDXError(f"Failed to get dependencies for {main_package_name}.")
479
+
480
+ if not os.path.isfile(temp_json_report):
481
+ raise PyPISPDXError(f"Pip report file '{temp_json_report}' was not created.")
482
+
483
+ with open(temp_json_report, encoding="utf-8") as json_data_file:
484
+ pip_report_data = json.load(json_data_file)
485
+ os.remove(temp_json_report)
486
+ if debug_mode:
487
+ print(f"DEBUG: Pip report file '{temp_json_report}' processed and removed.", file=sys.stderr)
488
+
489
+ dependencies = []
490
+ for dependency_entry in pip_report_data.get("install", []):
491
+ metadata = dependency_entry.get("metadata", {})
492
+ name = metadata.get("name")
493
+ version = metadata.get("version")
494
+ if name and version:
495
+ dependencies.append({"name": name, "version": version})
496
+ if debug_mode:
497
+ print(f"DEBUG: Found {len(dependencies)} dependencies.", file=sys.stderr)
498
+
499
+ # Sort dependencies for consistent SBOM output
500
+ dependencies = sorted(dependencies, key=lambda x: dash_name(x['name']))
501
+
502
+ for dep in dependencies:
503
+ dep_name_dashed = dash_name(dep["name"])
504
+ if dep_name_dashed != main_package_dashed: # Avoid re-printing the main package
505
+ print_package(dep["name"], dep["version"], sbom, custom_licenses, unknown_licenses, debug_mode)
506
+
507
+ sbom.write("##### Relationships\n\n")
508
+ sbom.write(f"Relationship: {SPDX_DOCUMENT_REF} DESCRIBES SPDXRef-{main_package_dashed}\n")
509
+
510
+ for dep in dependencies:
511
+ dep_name_dashed = dash_name(dep["name"])
512
+ if dep_name_dashed != main_package_dashed:
513
+ sbom.write(f"Relationship: SPDXRef-{main_package_dashed} CONTAINS SPDXRef-{dep_name_dashed}\n")
514
+
515
+ # Print custom and unknown licenses if any were found
516
+ if custom_licenses or unknown_licenses:
517
+ sbom.write("\n##### Custom licenses\n\n")
518
+
519
+ for cust_license in custom_licenses:
520
+ _process_custom_license_file(cust_license, sbom, debug_mode)
521
+
522
+ for unk_license in unknown_licenses:
523
+ if debug_mode:
524
+ print(f"DEBUG: Adding unknown license: {unk_license['id']}", file=sys.stderr)
525
+ sbom.write(f"LicenseID: {unk_license['id']}\n")
526
+ license_name = unk_license['id'].replace('LicenseRef-', '')
527
+ sbom.write(f"LicenseName: {license_name}\n")
528
+ sbom.write(f"ExtractedText: <text>{unk_license['text']}</text>\n")
529
+
530
+ # Convert to JSON, RDF, XML or YAML format if needed
531
+ if args.json:
532
+ new_sbom_filename = sbom_filename + ".json"
533
+ elif args.rdf:
534
+ new_sbom_filename = sbom_filename + ".rdf"
535
+ elif args.xml:
536
+ new_sbom_filename = sbom_filename + ".xml"
537
+ elif args.yaml:
538
+ new_sbom_filename = sbom_filename + ".yaml"
539
+ else:
540
+ print(f"SBOM successfully created: {sbom_filename}")
541
+ sys.exit(0)
542
+
543
+ document = parse_file(sbom_filename)
544
+ write_file(document, new_sbom_filename)
545
+ os.remove(sbom_filename)
546
+ print(f"SBOM successfully created: {new_sbom_filename}")
547
+ sys.exit(0)
548
+
549
+ except PyPISPDXError as e:
550
+ print(f"Error: {e}", file=sys.stderr)
551
+ if debug_mode:
552
+ traceback.print_exc(file=sys.stderr) # Print full traceback in debug mode
553
+ # Clean up partially created SBOM file if an error occurred
554
+ if os.path.exists(sbom_filename):
555
+ os.remove(sbom_filename)
556
+ sys.exit(1)
557
+ except Exception as e:
558
+ print(f"An unexpected error occurred: {e}", file=sys.stderr)
559
+ if debug_mode:
560
+ traceback.print_exc(file=sys.stderr) # Print full traceback in debug mode
561
+ if os.path.exists(sbom_filename):
562
+ os.remove(sbom_filename)
563
+ sys.exit(1)
564
+
565
+ if __name__ == "__main__":
566
+ main()
@@ -0,0 +1,140 @@
1
+ Metadata-Version: 2.4
2
+ Name: pypispdx
3
+ Version: 0.1.0
4
+ Summary: An SCA tool for creating an SPDX SBOM for a https://pypi.org/ package
5
+ Author-email: Marc-Etienne Vargenau <marc-etienne.vargenau@nokia.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/nokia/pypispdx
8
+ Project-URL: Issues, https://github.com/nokia/pypispdx/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: requests>=2.32.4
15
+ Requires-Dist: spdx-license-list>=3.27
16
+ Requires-Dist: spdx-tools>=0.8.3
17
+ Dynamic: license-file
18
+
19
+ # pypispdx
20
+
21
+ An SCA tool for creating an SPDX SBOM for a https://pypi.org/ package.
22
+
23
+ # Usage
24
+
25
+ ```
26
+ usage: pypispdx [-h] [--json | --rdf | --xml | --yaml] [--debug] package
27
+ ```
28
+
29
+ where “package” is a Python package avalable on https://pypi.org/
30
+
31
+ ```
32
+ options:
33
+ -h, --help Shows this help message and exits.
34
+ --debug Enable debug output, including detailed messages and full tracebacks.
35
+ --json Output the result in SPDX JSON format.
36
+ --rdf Output the result in SPDX RDF format.
37
+ --xml Output the result in SPDX XML format.
38
+ --yaml Output the result in SPDX YAML format.
39
+ ```
40
+
41
+ It will create an SPDX 2.3 SBOM for the latest available release of the package,
42
+ including all transitive dependencies.
43
+
44
+ By default, the output will be in tag:value format. The other formats, JSON, RDF,
45
+ XML and YAML are available by using the corresponding command-line option.
46
+
47
+ The SBOM filename will be ```package-version.spdx``` (plus the corresponding
48
+ suffix for the other formats), where the package name will be in lower case,
49
+ with underscores and dots replaced by dash.
50
+
51
+ Running again the command will give a different result if a newer version of the package or its
52
+ transitive dependencies are available.
53
+
54
+ Running the command with different versions of Python might give different results
55
+ as different versions of transitive dependencies might be selected.
56
+
57
+ ## Content of the SBOM
58
+
59
+ The Creator Organization will be taken from the ORGANIZATION environment variable.
60
+ If not set, it will be “UNKNOWN”.
61
+
62
+ The DocumentNamespace will be ```https://pypi.org/spdx/```package-version
63
+
64
+ For each package, the ```PackageSupplier``` will be “Organization: https://pypi.org”.
65
+
66
+ The ```PackageDownloadLocation``` will be a “.tar.gz” file if available.
67
+ If not available, it will be NOASSERTION.
68
+
69
+ If available, the ```PackageChecksum``` will be provided in both SHA256 and MD5.
70
+
71
+ The ```PackageLicenseConcluded``` and ```PackageLicenseDeclared``` will be given if available on PyPI.
72
+ If not, it will be NOASSERTION. See more details below.
73
+
74
+ The ```PackageCopyrightText``` will always be NOASSERTION.
75
+
76
+ The [PURL](https://github.com/package-url/purl-spec/) (Package URL) will be provided
77
+ in the ```ExternalRef``` field.
78
+
79
+ ## Licenses
80
+
81
+ First, the licenses will be searched in “license_expression” as specified in
82
+ [PEP 639](https://peps.python.org/pep-0639/).
83
+
84
+ If not available, the licenses will be searched in “license”
85
+
86
+ If no “license_expression” and no “license” they will be searched in “classifiers”
87
+
88
+ If the classifier is ambiguous, for example:
89
+ ```
90
+ License :: OSI Approved :: GNU General Public License (GPL)
91
+ ```
92
+ a ```LicenseRef-``` is created with that text.
93
+
94
+ When the license is specified with a ```LicenseRef-```, the text of the license
95
+ is retreived from the license file and put in the SBOM.
96
+
97
+ See for example [infinity-grid](https://pypi.org/project/infinity-grid/).
98
+
99
+ ## About PURL specification
100
+
101
+ The name is case insensitive and lowercased.
102
+
103
+ Underscore “_” is replaced with dash “-”.
104
+
105
+ Dot “.” is replaced with dash “-”.
106
+
107
+ ## Compliance
108
+
109
+ The SBOM is valid SPDX 2.3.
110
+
111
+ It is compliant with the [OpenChain Telco SBOM Guide](https://github.com/OpenChain-Project/Telco-WG/blob/main/OpenChain-Telco-SBOM-Guide_EN.md).
112
+
113
+ You can check it with the [openchain-telco-sbom-validator](https://pypi.org/project/openchain-telco-sbom-validator/).
114
+
115
+ ## When an SBOM cannot be created
116
+
117
+ ### Versions incompatibility
118
+
119
+ Running ```pypispdx``` with Python 3.14
120
+ ```
121
+ pypispdx google-ads-reports
122
+ Creating SPDX SBOM for PyPI package google-ads-reports
123
+ ERROR: Ignored the following versions that require a different python version:
124
+ 1.0 Requires-Python >=3.9,<3.13;
125
+ 1.0.1 Requires-Python >=3.9,<3.13;
126
+ 1.1.0 Requires-Python >=3.9,<3.13;
127
+ 1.2.0 Requires-Python >=3.9,<3.13;
128
+ 1.2.1 Requires-Python >=3.10,<3.13;
129
+ 1.2.2 Requires-Python >=3.10,<3.13;
130
+ 1.2.3 Requires-Python >=3.10,<3.13;
131
+ 1.3.0 Requires-Python >=3.10,<3.13;
132
+ 2.0.0 Requires-Python >=3.12,<3.13;
133
+ 2.0.1 Requires-Python >=3.12,<3.13;
134
+ 2.0.2 Requires-Python >=3.11,<3.14
135
+ ERROR: Could not find a version that satisfies the requirement google-ads-reports (from versions: none)
136
+ ERROR: No matching distribution found for google-ads-reports
137
+ Cannot create SBOM for google-ads-reports
138
+ ```
139
+
140
+ The SBOM cannot be created as ```google-ads-reports``` cannot currently be installed with Python 3.14.
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/pypispdx/pypispdx.py
5
+ src/pypispdx.egg-info/PKG-INFO
6
+ src/pypispdx.egg-info/SOURCES.txt
7
+ src/pypispdx.egg-info/dependency_links.txt
8
+ src/pypispdx.egg-info/entry_points.txt
9
+ src/pypispdx.egg-info/requires.txt
10
+ src/pypispdx.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pypispdx = pypispdx.pypispdx:main
@@ -0,0 +1,3 @@
1
+ requests>=2.32.4
2
+ spdx-license-list>=3.27
3
+ spdx-tools>=0.8.3
@@ -0,0 +1 @@
1
+ pypispdx