csa-secid 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of csa-secid might be problematic. Click here for more details.

@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.5
2
+ Name: csa-secid
3
+ Version: 1.0.0
4
+ Summary: Resolve security identifiers to URLs using the SecID API
5
+ Project-URL: Homepage, https://github.com/CloudSecurityAlliance/SecID
6
+ Project-URL: Repository, https://github.com/CloudSecurityAlliance/SecID-Client-SDK
7
+ Project-URL: Documentation, https://secid.cloudsecurityalliance.org
8
+ Project-URL: Issues, https://github.com/CloudSecurityAlliance/SecID-Client-SDK/issues
9
+ Author-email: Cloud Security Alliance <research@cloudsecurityalliance.org>
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: cve,cybersecurity,secid,security,vulnerability
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Information Technology
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Security
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+
26
+ # secid
27
+
28
+ Resolve security identifiers to URLs using the [SecID](https://secid.cloudsecurityalliance.org) API.
29
+
30
+ SecID is a universal grammar for security knowledge — CVEs, CWEs, ATT&CK techniques, NIST controls, and more — maintained by the [Cloud Security Alliance](https://cloudsecurityalliance.org).
31
+
32
+ **Zero dependencies.** Python 3.9+ stdlib only.
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ pip install csa-secid
38
+ ```
39
+
40
+ ## CLI
41
+
42
+ ```bash
43
+ # Resolve a CVE to its URL
44
+ secid "secid:advisory/mitre.org/cve#CVE-2021-44228"
45
+
46
+ # JSON output
47
+ secid --json "secid:advisory/mitre.org/cve#CVE-2021-44228"
48
+
49
+ # Cross-source search (find CVE across all advisory sources)
50
+ secid "secid:advisory/CVE-2021-44228"
51
+ ```
52
+
53
+ ## Library
54
+
55
+ ```python
56
+ from secid_client import SecIDClient
57
+
58
+ client = SecIDClient()
59
+
60
+ # Get the best URL for a security identifier
61
+ url = client.best_url("secid:advisory/mitre.org/cve#CVE-2021-44228")
62
+ print(url) # https://www.cve.org/CVERecord?id=CVE-2021-44228
63
+
64
+ # Full response with status, results, and guidance
65
+ response = client.resolve("secid:advisory/mitre.org/cve#CVE-2021-44228")
66
+ print(response.status) # "found"
67
+ print(response.best_url) # highest-weight URL
68
+ print(response.was_corrected) # True if input was auto-corrected
69
+ print(response.resolution_results) # all URL results, sorted by weight
70
+ print(response.registry_results) # browsing/discovery data
71
+
72
+ # Cross-source search
73
+ response = client.lookup("advisory", "CVE-2021-44228")
74
+
75
+ # Capability lookup (product security features)
76
+ response = client.resolve("secid:capability/amazon.com/aws/s3#default-encryption")
77
+
78
+ # Disclosure lookup (who to report vulnerabilities to)
79
+ response = client.resolve("secid:disclosure/redhat.com/cna")
80
+
81
+ # Look up a scoring methodology
82
+ response = client.resolve("secid:methodology/first.org/cvss@4.0")
83
+ ```
84
+
85
+ ## SecID Format
86
+
87
+ ```
88
+ secid:type/namespace/name[@version]#subpath
89
+ ```
90
+
91
+ | Type | Identifies |
92
+ |------|-----------|
93
+ | `advisory` | Vulnerability publications (CVE, GHSA, vendor advisories) |
94
+ | `weakness` | Abstract flaw patterns (CWE, OWASP Top 10) |
95
+ | `ttp` | Adversary techniques (ATT&CK, CAPEC) |
96
+ | `control` | Security requirements (NIST CSF, ISO 27001) |
97
+ | `capability` | Product security features and capabilities |
98
+ | `methodology` | Formal processes for producing security analysis |
99
+ | `disclosure` | Vulnerability disclosure programs and reporting channels |
100
+ | `regulation` | Laws (GDPR, HIPAA) |
101
+ | `entity` | Organizations, products, services |
102
+ | `reference` | Documents, research (arXiv, DOI, RFC) |
103
+
104
+ ## API
105
+
106
+ One endpoint: `GET /api/v1/resolve?secid={encoded_secid}`
107
+
108
+ The `#` character must be encoded as `%23` — the client handles this automatically.
109
+
110
+ Resolution results may include optional format metadata fields: `content_type`, `parsability`, `schema`, `parsing_instructions`, and `auth`. These describe the data format at the resolved URL and are present only when the registry has documented them.
111
+
112
+ ## Links
113
+
114
+ - [SecID Registry & Spec](https://github.com/CloudSecurityAlliance/SecID)
115
+ - [SecID API + MCP Server](https://secid.cloudsecurityalliance.org)
116
+ - [Cloud Security Alliance](https://cloudsecurityalliance.org)
117
+
118
+ ## License
119
+
120
+ Apache 2.0
@@ -0,0 +1,6 @@
1
+ secid_client.py,sha256=gjEn5DNtSB-D4T7vDGejZqUzmxPK4u-nSVU6fczpYTg,12730
2
+ csa_secid-1.0.0.dist-info/METADATA,sha256=OWie_CpBvItF2WUY41oxhzpdwTK2td7KnZspEsyTBZQ,4297
3
+ csa_secid-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
4
+ csa_secid-1.0.0.dist-info/entry_points.txt,sha256=BJ8DmJx125mEDXPYIjyq1UGc6YD9Z7H-dhOgiNWBsGo,44
5
+ csa_secid-1.0.0.dist-info/licenses/LICENSE,sha256=OSoLCoapvXQ9xOe9678SB5utika4uwbOBV8U2TQxsVw,10774
6
+ csa_secid-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ secid = secid_client:main
@@ -0,0 +1,190 @@
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 the 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 the 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 any 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
+ Copyright 2025 Cloud Security Alliance
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
secid_client.py ADDED
@@ -0,0 +1,327 @@
1
+ #!/usr/bin/env python3
2
+ """SecID client — resolve security identifiers to URLs.
3
+
4
+ Single file, zero dependencies (stdlib only). Copy and use.
5
+
6
+ SecID is a universal grammar for security knowledge:
7
+ secid:type/namespace/name[@version]#subpath
8
+
9
+ API: GET https://secid.cloudsecurityalliance.org/api/v1/resolve?secid={encoded}
10
+
11
+ IMPORTANT: The # character in SecID strings must be encoded as %23 in the
12
+ URL query parameter. This is the #1 failure mode for new clients.
13
+
14
+ Usage as library:
15
+ from secid_client import SecIDClient
16
+ client = SecIDClient()
17
+ response = client.resolve("secid:advisory/mitre.org/cve#CVE-2021-44228")
18
+ print(response.best_url)
19
+
20
+ Usage as CLI:
21
+ secid "secid:advisory/mitre.org/cve#CVE-2021-44228"
22
+ secid --json "secid:advisory/mitre.org/cve#CVE-2021-44228"
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ # Single source of truth for the version: pyproject.toml reads it from here
28
+ # (hatch dynamic version) and the User-Agent is built from it.
29
+ __version__ = "1.0.0"
30
+
31
+ import http.client
32
+ import json
33
+ import math
34
+ import socket
35
+ import sys
36
+ import urllib.error
37
+ import urllib.parse
38
+ import urllib.request
39
+ from dataclasses import dataclass, field
40
+ from typing import Any
41
+
42
+ DEFAULT_BASE_URL = "https://secid.cloudsecurityalliance.org"
43
+ DEFAULT_TIMEOUT = 30 # seconds
44
+ MAX_RESPONSE_BYTES = 10 * 1024 * 1024 # 10 MB
45
+
46
+
47
+ @dataclass
48
+ class SecIDResponse:
49
+ """Response from the SecID resolve API.
50
+
51
+ Attributes:
52
+ secid_query: The query string echoed back (decoded form).
53
+ status: One of: found, corrected, related, not_found, error.
54
+ results: List of result dicts — either resolution or registry type.
55
+ Resolution results have: secid, weight, url, and optional
56
+ content_type, parsability ("structured"/"scraped"), schema
57
+ (SecID reference), parsing_instructions (SecID reference),
58
+ auth (free-text).
59
+ message: Guidance text on not_found/error, None otherwise.
60
+ """
61
+
62
+ secid_query: str
63
+ status: str
64
+ results: list[dict[str, Any]] = field(default_factory=list)
65
+ message: str | None = None
66
+
67
+ @property
68
+ def best_url(self) -> str | None:
69
+ """Highest-weight valid URL from resolution results, or None.
70
+
71
+ Only absolute http(s) URLs count (see _validate_url). If the top
72
+ result carries a hostile or malformed URL, the next valid one is
73
+ returned instead of None.
74
+ """
75
+ resolved = self.resolution_results
76
+ return resolved[0]["url"] if resolved else None
77
+
78
+ @property
79
+ def was_corrected(self) -> bool:
80
+ """True if the server corrected the input."""
81
+ return self.status == "corrected"
82
+
83
+ @property
84
+ def resolution_results(self) -> list[dict[str, Any]]:
85
+ """Only results with a numeric weight and a valid http(s) url, sorted
86
+ by weight descending. Entries with a missing, null, or non-numeric
87
+ weight, or a url that fails _validate_url (javascript:, data:,
88
+ relative, ...), are left out."""
89
+ return sorted(
90
+ [r for r in self.results
91
+ if isinstance(r, dict) and _is_weight(r.get("weight"))
92
+ and _validate_url(r.get("url")) is not None],
93
+ key=lambda r: r["weight"],
94
+ reverse=True,
95
+ )
96
+
97
+ @property
98
+ def registry_results(self) -> list[dict[str, Any]]:
99
+ """Only results with data (registry/browsing info)."""
100
+ return [r for r in self.results if isinstance(r, dict) and "data" in r]
101
+
102
+
103
+ def _is_weight(value: Any) -> bool:
104
+ """True for a finite int/float. bool is excluded (it is an int subclass)."""
105
+ return (isinstance(value, (int, float)) and not isinstance(value, bool)
106
+ and math.isfinite(value))
107
+
108
+
109
+ # The resolver response is untrusted (a hostile, federated, or MITM'd resolver
110
+ # is in scope). Only absolute http(s) URLs may be surfaced. The check is done
111
+ # by hand rather than with urlparse so that all three reference clients apply
112
+ # exactly the same rule; parsers disagree on inputs such as "http:evil",
113
+ # "http:///evil" and "http:\\evil" (a WHATWG parser accepts all three).
114
+ ALLOWED_URL_SCHEMES = frozenset({"https", "http"})
115
+
116
+
117
+ def _validate_url(url: Any) -> str | None:
118
+ """Return url only if it is an absolute http(s) URL with a host, else None.
119
+
120
+ Rules (identical in the Python, TypeScript and Go clients):
121
+ 1. a non-empty string with no ASCII control characters or spaces;
122
+ 2. begins with "http://" or "https://" (scheme case-insensitive);
123
+ 3. the authority (up to the first "/", "?", "#" or backslash), minus
124
+ any "userinfo@", is non-empty and does not start with ":".
125
+ """
126
+ if not isinstance(url, str) or not url:
127
+ return None
128
+ if any(ord(ch) <= 0x20 or ord(ch) == 0x7F for ch in url):
129
+ return None
130
+ scheme, sep, rest = url.partition("://")
131
+ if not sep or scheme.lower() not in ALLOWED_URL_SCHEMES:
132
+ return None
133
+ end = len(rest)
134
+ for delim in "/?#\\":
135
+ i = rest.find(delim)
136
+ if i != -1:
137
+ end = min(end, i)
138
+ host = rest[:end].rpartition("@")[2]
139
+ if not host or host.startswith(":"):
140
+ return None
141
+ return url
142
+
143
+
144
+ def _sanitize_terminal(text: Any) -> str:
145
+ """Strip C0/C1 control chars (incl. ESC) from server-controlled text before
146
+ printing to a terminal — prevents ANSI/escape-sequence injection.
147
+
148
+ Accepts any value: a hostile resolver can send a number or object where a
149
+ string is expected, and printing it must not crash the CLI."""
150
+ if not isinstance(text, str):
151
+ text = "" if text is None else str(text)
152
+ return "".join(
153
+ ch for ch in text
154
+ if not (ord(ch) < 0x20 or ord(ch) == 0x7F or 0x80 <= ord(ch) <= 0x9F)
155
+ )
156
+
157
+
158
+ _INVALID = object()
159
+
160
+ # socket.timeout is an alias of TimeoutError from 3.10; on 3.9 it is a
161
+ # separate OSError subclass.
162
+ _TIMEOUTS = (TimeoutError, socket.timeout)
163
+
164
+
165
+ def _parse_json(body: bytes) -> Any:
166
+ """Decode a response body as JSON, returning _INVALID on any failure."""
167
+ try:
168
+ return json.loads(body.decode("utf-8"))
169
+ except (ValueError, UnicodeDecodeError, RecursionError):
170
+ return _INVALID
171
+
172
+
173
+ def _envelope(data: dict[str, Any], secid: str) -> SecIDResponse:
174
+ """Build a SecIDResponse from an untrusted JSON object, type-checking each
175
+ field. Wrong-typed fields fall back to defaults; non-object results are
176
+ dropped so the result helpers never see them."""
177
+ query = data.get("secid_query")
178
+ status = data.get("status")
179
+ message = data.get("message")
180
+ results = data.get("results")
181
+ return SecIDResponse(
182
+ secid_query=query if isinstance(query, str) else secid,
183
+ status=status if isinstance(status, str) and status else "error",
184
+ results=[r for r in results if isinstance(r, dict)] if isinstance(results, list) else [],
185
+ message=message if isinstance(message, str) else None,
186
+ )
187
+
188
+
189
+ class SecIDClient:
190
+ """HTTP client for the SecID resolve API.
191
+
192
+ Args:
193
+ base_url: API base URL. Defaults to the public SecID service.
194
+ """
195
+
196
+ def __init__(self, base_url: str = DEFAULT_BASE_URL, timeout: int = DEFAULT_TIMEOUT) -> None:
197
+ self.base_url = base_url.rstrip("/")
198
+ self.timeout = timeout
199
+
200
+ def resolve(self, secid: str) -> SecIDResponse:
201
+ """Resolve a SecID string to URL(s).
202
+
203
+ The # character is automatically encoded as %23 in the query parameter.
204
+
205
+ Args:
206
+ secid: Full SecID string, e.g. "secid:advisory/mitre.org/cve#CVE-2021-44228"
207
+
208
+ Returns:
209
+ SecIDResponse with status, results, and optional message. Never
210
+ raises for network, HTTP, or response-format problems: those come
211
+ back as status="error" with an explanatory message.
212
+ """
213
+ def error(message: str) -> SecIDResponse:
214
+ return SecIDResponse(secid_query=secid, status="error", message=message)
215
+
216
+ try:
217
+ encoded = urllib.parse.quote(secid, safe="")
218
+ except UnicodeEncodeError: # a lone surrogate cannot be UTF-8 encoded
219
+ return error("SecID is not valid Unicode (unpaired surrogate)")
220
+ url = f"{self.base_url}/api/v1/resolve?secid={encoded}"
221
+
222
+ # Every failure mode becomes status="error"; resolve() never raises.
223
+ # OSError covers URLError, socket timeouts, and connection resets;
224
+ # HTTPException covers malformed HTTP (IncompleteRead, BadStatusLine);
225
+ # ValueError covers an unusable base_url ("unknown url type").
226
+ try:
227
+ req = urllib.request.Request(url, headers={
228
+ "Accept": "application/json",
229
+ "User-Agent": f"secid-python-client/{__version__}",
230
+ })
231
+ with urllib.request.urlopen(req, timeout=self.timeout) as resp:
232
+ body = resp.read(MAX_RESPONSE_BYTES + 1)
233
+ except urllib.error.HTTPError as e:
234
+ # Non-2xx: the resolver may still send a JSON envelope.
235
+ try:
236
+ body = e.read(MAX_RESPONSE_BYTES + 1)
237
+ except (OSError, http.client.HTTPException, ValueError) as read_err:
238
+ return error(f"HTTP {e.code}: error reading body: {read_err}")
239
+ data = _parse_json(body)
240
+ if not isinstance(data, dict):
241
+ text = body[:200].decode("utf-8", errors="replace")
242
+ return error(f"HTTP {e.code}: {text}")
243
+ return _envelope(data, secid)
244
+ except urllib.error.URLError as e:
245
+ if isinstance(e.reason, _TIMEOUTS):
246
+ return error(f"Request timeout after {self.timeout}s: {e.reason}")
247
+ return error(f"Connection error: {e.reason}")
248
+ except _TIMEOUTS as e:
249
+ # A timeout while waiting for or reading the response is raised
250
+ # bare, not wrapped in URLError.
251
+ return error(f"Request timeout after {self.timeout}s: {e}")
252
+ except (OSError, http.client.HTTPException) as e:
253
+ return error(f"Connection error: {e}")
254
+ except ValueError as e:
255
+ return error(f"Invalid request URL {url!r}: {e}")
256
+
257
+ if len(body) > MAX_RESPONSE_BYTES:
258
+ return error(f"Response exceeds {MAX_RESPONSE_BYTES} byte limit")
259
+ data = _parse_json(body)
260
+ if data is _INVALID:
261
+ return error("Invalid response (not JSON)")
262
+ if not isinstance(data, dict):
263
+ return error(f"Invalid response: expected a JSON object, got {type(data).__name__}")
264
+ return _envelope(data, secid)
265
+
266
+ def best_url(self, secid: str) -> str | None:
267
+ """Resolve a SecID and return the highest-weight URL, or None."""
268
+ return self.resolve(secid).best_url
269
+
270
+ def lookup(self, type: str, identifier: str) -> SecIDResponse:
271
+ """Cross-source search: find an identifier across all sources of a type.
272
+
273
+ Equivalent to resolve(f"secid:{type}/{identifier}").
274
+
275
+ Args:
276
+ type: SecID type (advisory, weakness, ttp, control, capability, methodology, disclosure, regulation, entity, reference).
277
+ identifier: The identifier to search for, e.g. "CVE-2021-44228".
278
+ """
279
+ return self.resolve(f"secid:{type}/{identifier}")
280
+
281
+
282
+ def main() -> None:
283
+ if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"):
284
+ print("Usage: secid [--json] <secid>")
285
+ print()
286
+ print("Examples:")
287
+ print(' secid "secid:advisory/mitre.org/cve#CVE-2021-44228"')
288
+ print(' secid --json "secid:advisory/mitre.org/cve#CVE-2021-44228"')
289
+ print(' secid "secid:advisory/CVE-2021-44228"')
290
+ sys.exit(0)
291
+
292
+ json_mode = "--json" in sys.argv
293
+ args = [a for a in sys.argv[1:] if a != "--json"]
294
+ if not args:
295
+ print("Error: no SecID provided", file=sys.stderr)
296
+ sys.exit(1)
297
+
298
+ client = SecIDClient()
299
+ response = client.resolve(args[0])
300
+
301
+ if json_mode:
302
+ print(json.dumps({
303
+ "secid_query": response.secid_query,
304
+ "status": response.status,
305
+ "results": response.results,
306
+ "message": response.message,
307
+ }, indent=2))
308
+ elif response.status in ("found", "corrected"):
309
+ url = response.best_url
310
+ if url:
311
+ if response.was_corrected:
312
+ print(f"(corrected to: {_sanitize_terminal(str(response.results[0].get('secid', '')))})", file=sys.stderr)
313
+ print(_sanitize_terminal(url))
314
+ else:
315
+ for r in response.registry_results:
316
+ print(json.dumps(r, indent=2))
317
+ elif response.status == "related":
318
+ for r in response.results:
319
+ print(json.dumps(r, indent=2))
320
+ else:
321
+ msg = response.message or "No results"
322
+ print(f"{response.status}: {_sanitize_terminal(msg)}", file=sys.stderr)
323
+ sys.exit(1)
324
+
325
+
326
+ if __name__ == "__main__":
327
+ main()