csa-secid 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,5 @@
1
+ dist/
2
+ *.egg-info/
3
+ __pycache__/
4
+ *.pyc
5
+ build/
@@ -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.
@@ -0,0 +1,120 @@
1
+ Metadata-Version: 2.5
2
+ Name: csa-secid
3
+ Version: 0.1.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,95 @@
1
+ # secid
2
+
3
+ Resolve security identifiers to URLs using the [SecID](https://secid.cloudsecurityalliance.org) API.
4
+
5
+ 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).
6
+
7
+ **Zero dependencies.** Python 3.9+ stdlib only.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pip install csa-secid
13
+ ```
14
+
15
+ ## CLI
16
+
17
+ ```bash
18
+ # Resolve a CVE to its URL
19
+ secid "secid:advisory/mitre.org/cve#CVE-2021-44228"
20
+
21
+ # JSON output
22
+ secid --json "secid:advisory/mitre.org/cve#CVE-2021-44228"
23
+
24
+ # Cross-source search (find CVE across all advisory sources)
25
+ secid "secid:advisory/CVE-2021-44228"
26
+ ```
27
+
28
+ ## Library
29
+
30
+ ```python
31
+ from secid_client import SecIDClient
32
+
33
+ client = SecIDClient()
34
+
35
+ # Get the best URL for a security identifier
36
+ url = client.best_url("secid:advisory/mitre.org/cve#CVE-2021-44228")
37
+ print(url) # https://www.cve.org/CVERecord?id=CVE-2021-44228
38
+
39
+ # Full response with status, results, and guidance
40
+ response = client.resolve("secid:advisory/mitre.org/cve#CVE-2021-44228")
41
+ print(response.status) # "found"
42
+ print(response.best_url) # highest-weight URL
43
+ print(response.was_corrected) # True if input was auto-corrected
44
+ print(response.resolution_results) # all URL results, sorted by weight
45
+ print(response.registry_results) # browsing/discovery data
46
+
47
+ # Cross-source search
48
+ response = client.lookup("advisory", "CVE-2021-44228")
49
+
50
+ # Capability lookup (product security features)
51
+ response = client.resolve("secid:capability/amazon.com/aws/s3#default-encryption")
52
+
53
+ # Disclosure lookup (who to report vulnerabilities to)
54
+ response = client.resolve("secid:disclosure/redhat.com/cna")
55
+
56
+ # Look up a scoring methodology
57
+ response = client.resolve("secid:methodology/first.org/cvss@4.0")
58
+ ```
59
+
60
+ ## SecID Format
61
+
62
+ ```
63
+ secid:type/namespace/name[@version]#subpath
64
+ ```
65
+
66
+ | Type | Identifies |
67
+ |------|-----------|
68
+ | `advisory` | Vulnerability publications (CVE, GHSA, vendor advisories) |
69
+ | `weakness` | Abstract flaw patterns (CWE, OWASP Top 10) |
70
+ | `ttp` | Adversary techniques (ATT&CK, CAPEC) |
71
+ | `control` | Security requirements (NIST CSF, ISO 27001) |
72
+ | `capability` | Product security features and capabilities |
73
+ | `methodology` | Formal processes for producing security analysis |
74
+ | `disclosure` | Vulnerability disclosure programs and reporting channels |
75
+ | `regulation` | Laws (GDPR, HIPAA) |
76
+ | `entity` | Organizations, products, services |
77
+ | `reference` | Documents, research (arXiv, DOI, RFC) |
78
+
79
+ ## API
80
+
81
+ One endpoint: `GET /api/v1/resolve?secid={encoded_secid}`
82
+
83
+ The `#` character must be encoded as `%23` — the client handles this automatically.
84
+
85
+ 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.
86
+
87
+ ## Links
88
+
89
+ - [SecID Registry & Spec](https://github.com/CloudSecurityAlliance/SecID)
90
+ - [SecID API + MCP Server](https://secid.cloudsecurityalliance.org)
91
+ - [Cloud Security Alliance](https://cloudsecurityalliance.org)
92
+
93
+ ## License
94
+
95
+ Apache 2.0
@@ -0,0 +1,44 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"] # PEP 639 license expression support
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ # PyPI has a flat namespace, so the distribution name carries the csa- prefix.
7
+ # The import module (secid_client) and the CLI command (secid) stay simple.
8
+ name = "csa-secid"
9
+ dynamic = ["version"] # read from __version__ in secid_client.py
10
+ description = "Resolve security identifiers to URLs using the SecID API"
11
+ readme = "README.md"
12
+ license = "Apache-2.0"
13
+ requires-python = ">=3.9"
14
+ authors = [
15
+ { name = "Cloud Security Alliance", email = "research@cloudsecurityalliance.org" },
16
+ ]
17
+ keywords = ["security", "cve", "vulnerability", "secid", "cybersecurity"]
18
+ classifiers = [
19
+ "Development Status :: 3 - Alpha",
20
+ "Intended Audience :: Developers",
21
+ "Intended Audience :: Information Technology",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3.9",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Programming Language :: Python :: 3.13",
28
+ "Topic :: Security",
29
+ ]
30
+
31
+ [project.scripts]
32
+ secid = "secid_client:main"
33
+
34
+ [project.urls]
35
+ Homepage = "https://github.com/CloudSecurityAlliance/SecID"
36
+ Repository = "https://github.com/CloudSecurityAlliance/SecID-Client-SDK"
37
+ Documentation = "https://secid.cloudsecurityalliance.org"
38
+ Issues = "https://github.com/CloudSecurityAlliance/SecID-Client-SDK/issues"
39
+
40
+ [tool.hatch.version]
41
+ path = "secid_client.py"
42
+
43
+ [tool.hatch.build.targets.wheel]
44
+ only-include = ["secid_client.py"]
@@ -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__ = "0.1.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()
@@ -0,0 +1,487 @@
1
+ """Fixture-driven tests for the Python SecID client.
2
+
3
+ Reads ../tests/fixtures.json and runs each test case against a local mock server.
4
+ No external dependencies — uses stdlib http.server + pytest (or unittest).
5
+
6
+ Run: pytest python/test_secid_client.py -v
7
+ """
8
+
9
+ import json
10
+ import os
11
+ import threading
12
+ import time
13
+ from http.server import HTTPServer, BaseHTTPRequestHandler
14
+ from pathlib import Path
15
+
16
+ import pytest
17
+
18
+ from secid_client import SecIDClient
19
+
20
+ FIXTURES_PATH = Path(__file__).resolve().parent.parent / "tests" / "fixtures.json"
21
+
22
+
23
+ def load_fixtures():
24
+ with open(FIXTURES_PATH) as f:
25
+ return json.load(f)["tests"]
26
+
27
+
28
+ FIXTURES = load_fixtures()
29
+
30
+
31
+ def fixture_ids():
32
+ return [t["name"] for t in FIXTURES]
33
+
34
+
35
+ # ---------------------------------------------------------------------------
36
+ # Mock HTTP server
37
+ # ---------------------------------------------------------------------------
38
+
39
+ class MockHandler(BaseHTTPRequestHandler):
40
+ """Serves canned responses from fixture data. Records request URLs."""
41
+
42
+ response_body = b"{}"
43
+ response_status = 200
44
+ response_content_type = "application/json"
45
+ recorded_urls = []
46
+ hang = False
47
+ oversized_bytes = 0
48
+
49
+ def do_GET(self):
50
+ MockHandler.recorded_urls.append(self.path)
51
+
52
+ if MockHandler.hang:
53
+ # Sleep long enough that the client should time out
54
+ time.sleep(10)
55
+ return
56
+
57
+ if MockHandler.oversized_bytes > 0:
58
+ self.send_response(200)
59
+ self.send_header("Content-Type", "application/json")
60
+ self.end_headers()
61
+ self.wfile.write(b"x" * MockHandler.oversized_bytes)
62
+ return
63
+
64
+ self.send_response(MockHandler.response_status)
65
+ self.send_header("Content-Type", MockHandler.response_content_type)
66
+ self.end_headers()
67
+ self.wfile.write(MockHandler.response_body)
68
+
69
+ def log_message(self, format, *args):
70
+ pass # Suppress request logging
71
+
72
+
73
+ def start_mock_server():
74
+ server = HTTPServer(("127.0.0.1", 0), MockHandler)
75
+ port = server.server_address[1]
76
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
77
+ thread.start()
78
+ return server, port
79
+
80
+
81
+ def configure_mock(mock_response):
82
+ """Configure MockHandler class vars from fixture mock_response."""
83
+ MockHandler.recorded_urls = []
84
+ MockHandler.hang = False
85
+ MockHandler.oversized_bytes = 0
86
+ MockHandler.response_status = 200
87
+ MockHandler.response_content_type = "application/json"
88
+ MockHandler.response_body = b"{}"
89
+
90
+ behavior = mock_response.get("behavior")
91
+ if behavior == "timeout":
92
+ MockHandler.hang = True
93
+ return
94
+ if behavior == "oversized_body":
95
+ MockHandler.oversized_bytes = mock_response["body_size_bytes"]
96
+ return
97
+ if behavior == "connection_refused":
98
+ return # Handled specially in the test
99
+
100
+ if "raw_body" in mock_response:
101
+ MockHandler.response_body = mock_response["raw_body"].encode()
102
+ MockHandler.response_content_type = mock_response.get("content_type", "text/html")
103
+ elif "body" in mock_response:
104
+ MockHandler.response_body = json.dumps(mock_response["body"]).encode()
105
+
106
+ MockHandler.response_status = mock_response.get("http_status", 200)
107
+
108
+
109
+ # ---------------------------------------------------------------------------
110
+ # Server fixture (shared across the module)
111
+ # ---------------------------------------------------------------------------
112
+
113
+ _server = None
114
+ _port = None
115
+
116
+
117
+ @pytest.fixture(scope="module")
118
+ def mock_server():
119
+ global _server, _port
120
+ if _server is None:
121
+ _server, _port = start_mock_server()
122
+ yield _port
123
+ _server.shutdown()
124
+
125
+
126
+ # ---------------------------------------------------------------------------
127
+ # Tests
128
+ # ---------------------------------------------------------------------------
129
+
130
+ def standard_tests():
131
+ """Return fixture entries that use a normal mock server (not connection_refused)."""
132
+ return [t for t in FIXTURES if t["mock_response"].get("behavior") != "connection_refused"]
133
+
134
+
135
+ def connection_refused_tests():
136
+ """Return fixture entries that need no server (connection refused)."""
137
+ return [t for t in FIXTURES if t["mock_response"].get("behavior") == "connection_refused"]
138
+
139
+
140
+ def _invoke_response(client: SecIDClient, inp: dict):
141
+ method = inp.get("method", "resolve")
142
+ if method == "lookup":
143
+ args = inp["args"]
144
+ return client.lookup(args["type"], args["identifier"])
145
+ if method == "resolve":
146
+ return client.resolve(inp["secid"])
147
+ raise ValueError(f"Unsupported fixture method: {method}")
148
+
149
+
150
+ def _assert_request_url(expected: dict):
151
+ if "request_url_contains" in expected:
152
+ assert len(MockHandler.recorded_urls) > 0, "No request recorded"
153
+ url = MockHandler.recorded_urls[-1]
154
+ assert expected["request_url_contains"] in url, (
155
+ f"Request URL should contain '{expected['request_url_contains']}', got: {url}"
156
+ )
157
+
158
+ if "request_url_not_contains" in expected:
159
+ assert len(MockHandler.recorded_urls) > 0, "No request recorded"
160
+ url = MockHandler.recorded_urls[-1]
161
+ assert expected["request_url_not_contains"] not in url, (
162
+ f"Request URL should NOT contain '{expected['request_url_not_contains']}', got: {url}"
163
+ )
164
+
165
+
166
+ @pytest.mark.parametrize(
167
+ "fixture",
168
+ standard_tests(),
169
+ ids=[t["name"] for t in standard_tests()],
170
+ )
171
+ def test_fixture(fixture, mock_server):
172
+ port = mock_server
173
+ configure_mock(fixture["mock_response"])
174
+ expected = fixture["expected"]
175
+ inp = fixture["input"]
176
+
177
+ # Use short timeout for timeout tests
178
+ is_timeout = fixture["mock_response"].get("behavior") == "timeout"
179
+ timeout = 2 if is_timeout else 10
180
+
181
+ client = SecIDClient(base_url=f"http://127.0.0.1:{port}", timeout=timeout)
182
+
183
+ if inp.get("method") == "best_url":
184
+ url = client.best_url(inp["secid"])
185
+ if expected.get("raises_error"):
186
+ assert url is None, f"best_url: expected None on error, got {url}"
187
+ return
188
+ assert url == expected.get("best_url"), (
189
+ f"best_url: expected {expected.get('best_url')}, got {url}"
190
+ )
191
+ _assert_request_url(expected)
192
+ return
193
+
194
+ if expected.get("raises_error"):
195
+ # The Python client never raises: every failure is status="error".
196
+ resp = _invoke_response(client, inp)
197
+ assert resp.status == "error", f"Expected error status, got status={resp.status}"
198
+ if "error_contains" in expected:
199
+ assert resp.message and expected["error_contains"].lower() in resp.message.lower(), (
200
+ f"Expected '{expected['error_contains']}' in message: {resp.message}"
201
+ )
202
+ return
203
+
204
+ # Normal test: call resolve/lookup and check expected fields
205
+ resp = _invoke_response(client, inp)
206
+
207
+ if "status" in expected:
208
+ assert resp.status == expected["status"], (
209
+ f"status: expected {expected['status']}, got {resp.status}"
210
+ )
211
+
212
+ if "best_url" in expected:
213
+ if expected["best_url"] is None:
214
+ assert resp.best_url is None, f"best_url: expected None, got {resp.best_url}"
215
+ else:
216
+ assert resp.best_url == expected["best_url"], (
217
+ f"best_url: expected {expected['best_url']}, got {resp.best_url}"
218
+ )
219
+
220
+ if "was_corrected" in expected:
221
+ assert resp.was_corrected == expected["was_corrected"], (
222
+ f"was_corrected: expected {expected['was_corrected']}, got {resp.was_corrected}"
223
+ )
224
+
225
+ if "resolution_result_count" in expected:
226
+ actual = len(resp.resolution_results)
227
+ assert actual == expected["resolution_result_count"], (
228
+ f"resolution_result_count: expected {expected['resolution_result_count']}, got {actual}"
229
+ )
230
+
231
+ if "registry_result_count" in expected:
232
+ actual = len(resp.registry_results)
233
+ assert actual == expected["registry_result_count"], (
234
+ f"registry_result_count: expected {expected['registry_result_count']}, got {actual}"
235
+ )
236
+
237
+ if "message" in expected:
238
+ if expected["message"] is None:
239
+ assert resp.message is None, f"message: expected None, got {resp.message}"
240
+ else:
241
+ assert resp.message == expected["message"], (
242
+ f"message: expected {expected['message']}, got {resp.message}"
243
+ )
244
+
245
+ if "first_resolution_result" in expected:
246
+ assert len(resp.resolution_results) > 0, "Expected at least one resolution result"
247
+ first = resp.resolution_results[0]
248
+ for field_name, want in expected["first_resolution_result"].items():
249
+ actual = first.get(field_name)
250
+ assert actual == want, (
251
+ f"first_resolution_result.{field_name}: expected {want!r}, got {actual!r}"
252
+ )
253
+
254
+ # Encoding assertions: check the URL the client actually sent
255
+ _assert_request_url(expected)
256
+
257
+
258
+ @pytest.mark.parametrize(
259
+ "fixture",
260
+ connection_refused_tests(),
261
+ ids=[t["name"] for t in connection_refused_tests()],
262
+ )
263
+ def test_connection_refused(fixture):
264
+ # Point client at a port where nothing is listening
265
+ client = SecIDClient(base_url="http://127.0.0.1:1", timeout=2)
266
+ inp = fixture["input"]
267
+ if inp.get("method") == "best_url":
268
+ assert client.best_url(inp["secid"]) is None
269
+ return
270
+ resp = _invoke_response(client, inp)
271
+ assert resp.status == "error"
272
+
273
+
274
+ # ── Untrusted-response hardening (audit findings F-08, F-10-02) ──
275
+
276
+ from secid_client import SecIDResponse, _validate_url, _sanitize_terminal # noqa: E402
277
+
278
+
279
+ def test_validate_url_scheme_allowlist():
280
+ assert _validate_url("https://www.cve.org/CVERecord?id=CVE-2021-44228")
281
+ assert _validate_url("http://example.com/x")
282
+ for bad in ("javascript:alert(1)", "data:text/html,x", "file:///etc/passwd",
283
+ "vbscript:msgbox(1)", "//evil.example/x", "/relative", "", None):
284
+ assert _validate_url(bad) is None, f"{bad!r} must be rejected"
285
+
286
+
287
+ def test_best_url_rejects_hostile_scheme():
288
+ # A hostile resolver returns a javascript: URL as the highest-weight result.
289
+ r = SecIDResponse(secid_query="x", status="found",
290
+ results=[{"weight": 100, "url": "javascript:fetch('//evil')"}])
291
+ assert r.best_url is None
292
+ # A valid https result is returned unchanged.
293
+ r2 = SecIDResponse(secid_query="x", status="found",
294
+ results=[{"weight": 100, "url": "https://example.com/ok"}])
295
+ assert r2.best_url == "https://example.com/ok"
296
+
297
+
298
+ def test_sanitize_terminal_strips_control_chars():
299
+ assert _sanitize_terminal("https://x/\x1b[2Jfake") == "https://x/[2Jfake"
300
+ assert _sanitize_terminal("plain text") == "plain text"
301
+
302
+
303
+ def test_sanitize_terminal_accepts_non_strings():
304
+ assert _sanitize_terminal(123) == "123"
305
+ assert _sanitize_terminal(None) == ""
306
+ assert isinstance(_sanitize_terminal({"a": 1}), str)
307
+
308
+
309
+ # ── Hostile resolver responses (audit finding H2) ──
310
+ #
311
+ # The resolver is untrusted. None of these may raise; each must come back as
312
+ # a SecIDResponse whose helpers work.
313
+
314
+ import socketserver # noqa: E402
315
+
316
+
317
+ class _RawHandler(BaseHTTPRequestHandler):
318
+ status = 200
319
+ body = b""
320
+ delay = 0.0
321
+ truncate = False
322
+
323
+ def do_GET(self):
324
+ if _RawHandler.delay:
325
+ # Send headers promptly, then stall mid-body: a read timeout,
326
+ # not a connect timeout.
327
+ self.send_response(200)
328
+ self.send_header("Content-Type", "application/json")
329
+ self.send_header("Content-Length", "100")
330
+ self.end_headers()
331
+ self.wfile.write(b'{"status":')
332
+ self.wfile.flush()
333
+ time.sleep(_RawHandler.delay)
334
+ return
335
+ self.send_response(_RawHandler.status)
336
+ self.send_header("Content-Type", "application/json")
337
+ if _RawHandler.truncate:
338
+ self.send_header("Content-Length", str(len(_RawHandler.body) + 50))
339
+ self.end_headers()
340
+ self.wfile.write(_RawHandler.body)
341
+
342
+ def log_message(self, format, *args):
343
+ pass
344
+
345
+
346
+ class _ThreadedServer(socketserver.ThreadingMixIn, HTTPServer):
347
+ daemon_threads = True
348
+
349
+
350
+ @pytest.fixture(scope="module")
351
+ def raw_server():
352
+ server = _ThreadedServer(("127.0.0.1", 0), _RawHandler)
353
+ threading.Thread(target=server.serve_forever, daemon=True).start()
354
+ yield f"http://127.0.0.1:{server.server_address[1]}"
355
+ server.shutdown()
356
+
357
+
358
+ def _serve(body, status=200, delay=0.0, truncate=False):
359
+ _RawHandler.body = body if isinstance(body, bytes) else json.dumps(body).encode()
360
+ _RawHandler.status = status
361
+ _RawHandler.delay = delay
362
+ _RawHandler.truncate = truncate
363
+
364
+
365
+ def _exercise(resp):
366
+ """Touch every helper; none may raise on a hostile response."""
367
+ resp.best_url, resp.was_corrected, resp.resolution_results, resp.registry_results
368
+ return resp
369
+
370
+
371
+ @pytest.mark.parametrize("body", [
372
+ b"null", b"[]", b"42", b'"found"', b"true", b"", b" ",
373
+ ], ids=["null", "array", "number", "string", "bool", "empty", "whitespace"])
374
+ def test_non_object_body_is_error(raw_server, body):
375
+ _serve(body)
376
+ resp = _exercise(SecIDClient(raw_server, timeout=5).resolve("secid:x/y/z"))
377
+ assert resp.status == "error"
378
+ assert resp.results == []
379
+
380
+
381
+ def test_wrongly_typed_envelope_fields(raw_server):
382
+ _serve({"secid_query": 7, "status": ["found"], "results": {"a": 1}, "message": 5})
383
+ resp = _exercise(SecIDClient(raw_server, timeout=5).resolve("secid:x/y/z"))
384
+ assert resp.secid_query == "secid:x/y/z"
385
+ assert resp.status == "error"
386
+ assert resp.results == []
387
+ assert resp.message is None
388
+
389
+
390
+ def test_non_dict_results_and_mixed_weights(raw_server):
391
+ _serve({"status": "found", "results": [
392
+ 17, "junk", None, [1, 2],
393
+ {"secid": "a", "weight": None, "url": "https://a.example/"},
394
+ {"secid": "b", "weight": "90", "url": "https://b.example/"},
395
+ {"secid": "c", "weight": True, "url": "https://c.example/"},
396
+ {"secid": "d", "weight": 87.5, "url": "https://d.example/"},
397
+ {"secid": "e", "weight": 90, "url": "https://e.example/"},
398
+ {"secid": "f", "weight": 99, "url": 12345},
399
+ {"secid": "g", "data": {"k": "v"}},
400
+ ]})
401
+ resp = _exercise(SecIDClient(raw_server, timeout=5).resolve("secid:x/y/z"))
402
+ assert resp.status == "found"
403
+ assert len(resp.results) == 7 # the four non-objects are dropped
404
+ assert [r["secid"] for r in resp.resolution_results] == ["e", "d"]
405
+ assert resp.best_url == "https://e.example/"
406
+ assert len(resp.registry_results) == 1
407
+
408
+
409
+ def test_non_utf8_body(raw_server):
410
+ _serve(b"\xff\xfe\xfa not utf-8")
411
+ assert SecIDClient(raw_server, timeout=5).resolve("secid:x/y/z").status == "error"
412
+
413
+
414
+ def test_non_utf8_error_body(raw_server):
415
+ _serve(b"\xff\xfe\xfa not utf-8", status=502)
416
+ resp = SecIDClient(raw_server, timeout=5).resolve("secid:x/y/z")
417
+ assert resp.status == "error"
418
+ assert resp.message.startswith("HTTP 502")
419
+
420
+
421
+ def test_error_status_with_null_json_body(raw_server):
422
+ _serve(b"null", status=500)
423
+ resp = SecIDClient(raw_server, timeout=5).resolve("secid:x/y/z")
424
+ assert resp.status == "error"
425
+ assert resp.message.startswith("HTTP 500")
426
+
427
+
428
+ def test_truncated_body(raw_server):
429
+ _serve(b'{"status": "fo', truncate=True)
430
+ assert SecIDClient(raw_server, timeout=5).resolve("secid:x/y/z").status == "error"
431
+
432
+
433
+ def test_read_timeout_mid_body(raw_server):
434
+ _serve(b"", delay=3)
435
+ resp = SecIDClient(raw_server, timeout=1).resolve("secid:x/y/z")
436
+ assert resp.status == "error"
437
+ assert "timeout" in resp.message.lower()
438
+
439
+
440
+ def test_deeply_nested_json(raw_server):
441
+ _serve(b"[" * 100000 + b"]" * 100000)
442
+ assert SecIDClient(raw_server, timeout=5).resolve("secid:x/y/z").status == "error"
443
+
444
+
445
+ @pytest.mark.parametrize("base_url", ["not a url", "ftp://example.com", ""])
446
+ def test_unusable_base_url(base_url):
447
+ resp = SecIDClient(base_url, timeout=2).resolve("secid:x/y/z")
448
+ assert resp.status == "error"
449
+
450
+
451
+ def test_cli_survives_hostile_values(monkeypatch, capsys):
452
+ import secid_client
453
+
454
+ hostile = SecIDResponse(secid_query="q", status="corrected", results=[
455
+ {"secid": 42, "weight": 100, "url": "https://ok.example/"},
456
+ ])
457
+ monkeypatch.setattr(secid_client.SecIDClient, "resolve", lambda self, s: hostile)
458
+ monkeypatch.setattr(secid_client.sys, "argv", ["secid", "secid:x/y/z"])
459
+ secid_client.main()
460
+ out = capsys.readouterr()
461
+ assert out.out.strip() == "https://ok.example/"
462
+ assert "corrected to: 42" in out.err
463
+
464
+
465
+ def test_unpaired_surrogate_secid():
466
+ resp = SecIDClient("http://127.0.0.1:1", timeout=2).resolve("secid:x/y/\ud800")
467
+ assert resp.status == "error"
468
+ assert "Unicode" in resp.message
469
+
470
+
471
+ def test_user_agent_carries_version(mock_server):
472
+ import secid_client
473
+
474
+ configure_mock({"http_status": 200, "body": {"status": "found", "results": []}})
475
+ captured = {}
476
+ orig = MockHandler.do_GET
477
+
478
+ def spy(self):
479
+ captured["ua"] = self.headers.get("User-Agent")
480
+ orig(self)
481
+
482
+ MockHandler.do_GET = spy
483
+ try:
484
+ SecIDClient(base_url=f"http://127.0.0.1:{mock_server}", timeout=5).resolve("secid:x/y/z")
485
+ finally:
486
+ MockHandler.do_GET = orig
487
+ assert captured["ua"] == f"secid-python-client/{secid_client.__version__}"