cms-hte-ial2-reader 0.0.2__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.
- cms_hte_ial2_reader-0.0.2.dist-info/METADATA +73 -0
- cms_hte_ial2_reader-0.0.2.dist-info/RECORD +13 -0
- cms_hte_ial2_reader-0.0.2.dist-info/WHEEL +5 -0
- cms_hte_ial2_reader-0.0.2.dist-info/licenses/LICENSE +215 -0
- cms_hte_ial2_reader-0.0.2.dist-info/licenses/NOTICE +10 -0
- cms_hte_ial2_reader-0.0.2.dist-info/top_level.txt +1 -0
- cmshteial2reader/__init__.py +23 -0
- cmshteial2reader/claims_model.py +211 -0
- cmshteial2reader/fhir_converter.py +267 -0
- cmshteial2reader/ial2_extractor.py +97 -0
- cmshteial2reader/multi_issuer_verifier.py +198 -0
- cmshteial2reader/py.typed +0 -0
- cmshteial2reader/token_verifier.py +205 -0
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cms-hte-ial2-reader
|
|
3
|
+
Version: 0.0.2
|
|
4
|
+
Summary: Reads IAL2 token, verifies digital signature and returns FHIR Patient resource
|
|
5
|
+
Author-email: Imran Qureshi <imran.qureshi@bwell.com>
|
|
6
|
+
Project-URL: Repository, https://github.com/icanbwell/cms-hte-ial2-reader
|
|
7
|
+
Classifier: Development Status :: 4 - Beta
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
License-File: NOTICE
|
|
15
|
+
Requires-Dist: pyjwt>=2.8.0
|
|
16
|
+
Requires-Dist: cryptography>=43.0.0
|
|
17
|
+
Requires-Dist: fhirschemapy>=0.0.11
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# cms-hte-ial2-reader
|
|
21
|
+
|
|
22
|
+
Reads IAL2 token, verifies digital signature and returns FHIR Patient resource
|
|
23
|
+
|
|
24
|
+
Accepts a signed JWT (ID Token) from a Credential Service Provider (CSP),
|
|
25
|
+
verifies the signature via JWKS, extracts demographics per the CSP payload
|
|
26
|
+
specification V7.1, and returns a FHIR R4 Patient resource.
|
|
27
|
+
|
|
28
|
+
## Usage
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from cmshteial2reader import IAL2Extractor, TokenVerifier
|
|
32
|
+
|
|
33
|
+
verifier = TokenVerifier(
|
|
34
|
+
jwks_uri="https://idp.example.com/.well-known/jwks.json",
|
|
35
|
+
audience="my-client-id",
|
|
36
|
+
)
|
|
37
|
+
extractor = IAL2Extractor(verifier=verifier)
|
|
38
|
+
patient = await extractor.extract(token_string)
|
|
39
|
+
# patient is a FHIR R4 Patient resource dict
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
To accept tokens from any issuer on an explicit allow list (rather than a
|
|
43
|
+
single pinned issuer), use `MultiIssuerTokenVerifier` in place of
|
|
44
|
+
`TokenVerifier`:
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
from cmshteial2reader import IAL2Extractor, MultiIssuerTokenVerifier
|
|
48
|
+
|
|
49
|
+
verifier = MultiIssuerTokenVerifier.from_env(audience="my-client-id")
|
|
50
|
+
extractor = IAL2Extractor(verifier=verifier)
|
|
51
|
+
patient = await extractor.extract(token_string)
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
`MultiIssuerTokenVerifier.from_env` reads its whitelist of trusted JWKS URLs
|
|
55
|
+
from the `IAL2_ALLOWED_JWKS_URLS` environment variable (comma-separated).
|
|
56
|
+
|
|
57
|
+
## Quickstart
|
|
58
|
+
- `make init` to set up the local dev environment.
|
|
59
|
+
- `make up` to start the Docker dev stack.
|
|
60
|
+
- `make tests` to run tests in the dev container.
|
|
61
|
+
|
|
62
|
+
## Common Tasks
|
|
63
|
+
- `make shell` to open a shell in the dev container.
|
|
64
|
+
- `make run-pre-commit` to run linting and formatting hooks.
|
|
65
|
+
- `make build` to build the package artifacts.
|
|
66
|
+
|
|
67
|
+
## Publishing
|
|
68
|
+
- Set a token: `export TWINE_PASSWORD=pypi-xxx`
|
|
69
|
+
- `make package` to publish to PyPI or `make testpackage` for TestPyPI.
|
|
70
|
+
|
|
71
|
+
## Project Metadata
|
|
72
|
+
- Repo: https://github.com/icanbwell/cms-hte-ial2-reader
|
|
73
|
+
- Author: Imran Qureshi <imran.qureshi@bwell.com>
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
cms_hte_ial2_reader-0.0.2.dist-info/licenses/LICENSE,sha256=8bqmh5rx8pyajtpI25opYOAsjey5tYgml_i-v1IzlHI,11928
|
|
2
|
+
cms_hte_ial2_reader-0.0.2.dist-info/licenses/NOTICE,sha256=xB4gR4vwAHrDAixnYEexN3a2j3jVR0KvCB2gRKovp7k,1289
|
|
3
|
+
cmshteial2reader/__init__.py,sha256=0hdBjWKIt12dc29P98_vC9IkZnWmvDtJvtH1YPRq6K4,787
|
|
4
|
+
cmshteial2reader/claims_model.py,sha256=PsrmcSECbgvh3ykVaA1gXE44Atzec4maQFW3DNoPNO0,7109
|
|
5
|
+
cmshteial2reader/fhir_converter.py,sha256=gPTLngLUt0_V1de0Ux3DhmGH_qblRUJf9eigAo2SRwY,8444
|
|
6
|
+
cmshteial2reader/ial2_extractor.py,sha256=1XprEVgK6Kb-J9F1HNS2qCTmf6bRD1bomMXxxeeVkX8,2962
|
|
7
|
+
cmshteial2reader/multi_issuer_verifier.py,sha256=ivFP7X9YoURVQswCx9JYGilXZXAjDjx10SGgZt7EPIs,7374
|
|
8
|
+
cmshteial2reader/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
cmshteial2reader/token_verifier.py,sha256=GqXdSmE6JDmpogb9Z7lZauWHIHnfjwV2WciEG8jKC_w,7299
|
|
10
|
+
cms_hte_ial2_reader-0.0.2.dist-info/METADATA,sha256=JMEsTtL03IPOg1w3nrFsMxquMoLBid6y0PG0MbGBhxg,2521
|
|
11
|
+
cms_hte_ial2_reader-0.0.2.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
12
|
+
cms_hte_ial2_reader-0.0.2.dist-info/top_level.txt,sha256=kZHQ9HpkkY1Ei3nv7TiSP_XPeMD-lz0FnXqIqFware0,17
|
|
13
|
+
cms_hte_ial2_reader-0.0.2.dist-info/RECORD,,
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
Copyright 2026 b.well Connected Health, Inc.
|
|
2
|
+
|
|
3
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
you may not use this file except in compliance with the License.
|
|
5
|
+
You may obtain a copy of the License at
|
|
6
|
+
|
|
7
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
See the License for the specific language governing permissions and
|
|
13
|
+
limitations under the License.
|
|
14
|
+
|
|
15
|
+
Apache License
|
|
16
|
+
Version 2.0, January 2004
|
|
17
|
+
http://www.apache.org/licenses/
|
|
18
|
+
|
|
19
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
20
|
+
|
|
21
|
+
1. Definitions.
|
|
22
|
+
|
|
23
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
24
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
25
|
+
|
|
26
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
27
|
+
the copyright owner that is granting the License.
|
|
28
|
+
|
|
29
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
30
|
+
other entities that control, are controlled by, or are under common
|
|
31
|
+
control with that entity. For the purposes of this definition,
|
|
32
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
33
|
+
direction or management of such entity, whether by contract or
|
|
34
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
35
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
36
|
+
|
|
37
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
38
|
+
exercising permissions granted by this License.
|
|
39
|
+
|
|
40
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
41
|
+
including but not limited to software source code, documentation
|
|
42
|
+
source, and configuration files.
|
|
43
|
+
|
|
44
|
+
"Object" form shall mean any form resulting from mechanical
|
|
45
|
+
transformation or translation of a Source form, including but
|
|
46
|
+
not limited to compiled object code, generated documentation,
|
|
47
|
+
and conversions to other media types.
|
|
48
|
+
|
|
49
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
50
|
+
Object form, made available under the License, as indicated by a
|
|
51
|
+
copyright notice that is included in or attached to the work
|
|
52
|
+
(an example is provided in the Appendix below).
|
|
53
|
+
|
|
54
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
55
|
+
form, that is based on (or derived from) the Work and for which the
|
|
56
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
57
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
58
|
+
of this License, Derivative Works shall not include works that remain
|
|
59
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
60
|
+
the Work and Derivative Works thereof.
|
|
61
|
+
|
|
62
|
+
"Contribution" shall mean any work of authorship, including
|
|
63
|
+
the original version of the Work and any modifications or additions
|
|
64
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
65
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
66
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
67
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
68
|
+
means any form of electronic, verbal, or written communication sent
|
|
69
|
+
to the Licensor or its representatives, including but not limited to
|
|
70
|
+
communication on electronic mailing lists, source code control systems,
|
|
71
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
72
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
73
|
+
excluding communication that is conspicuously marked or otherwise
|
|
74
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
75
|
+
|
|
76
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
77
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
78
|
+
subsequently incorporated within the Work.
|
|
79
|
+
|
|
80
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
81
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
82
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
83
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
84
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
85
|
+
Work and such Derivative Works in Source or Object form.
|
|
86
|
+
|
|
87
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
88
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
89
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
90
|
+
(except as stated in this section) patent license to make, have made,
|
|
91
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
92
|
+
where such license applies only to those patent claims licensable
|
|
93
|
+
by such Contributor that are necessarily infringed by their
|
|
94
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
95
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
96
|
+
institute patent litigation against any entity (including a
|
|
97
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
98
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
99
|
+
or contributory patent infringement, then any patent licenses
|
|
100
|
+
granted to You under this License for that Work shall terminate
|
|
101
|
+
as of the date such litigation is filed.
|
|
102
|
+
|
|
103
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
104
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
105
|
+
modifications, and in Source or Object form, provided that You
|
|
106
|
+
meet the following conditions:
|
|
107
|
+
|
|
108
|
+
(a) You must give any other recipients of the Work or
|
|
109
|
+
Derivative Works a copy of this License; and
|
|
110
|
+
|
|
111
|
+
(b) You must cause any modified files to carry prominent notices
|
|
112
|
+
stating that You changed the files; and
|
|
113
|
+
|
|
114
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
115
|
+
that You distribute, all copyright, patent, trademark, and
|
|
116
|
+
attribution notices from the Source form of the Work,
|
|
117
|
+
excluding those notices that do not pertain to any part of
|
|
118
|
+
the Derivative Works; and
|
|
119
|
+
|
|
120
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
121
|
+
distribution, then any Derivative Works that You distribute must
|
|
122
|
+
include a readable copy of the attribution notices contained
|
|
123
|
+
within such NOTICE file, excluding those notices that do not
|
|
124
|
+
pertain to any part of the Derivative Works, in at least one
|
|
125
|
+
of the following places: within a NOTICE text file distributed
|
|
126
|
+
as part of the Derivative Works; within the Source form or
|
|
127
|
+
documentation, if provided along with the Derivative Works; or,
|
|
128
|
+
within a display generated by the Derivative Works, if and
|
|
129
|
+
wherever such third-party notices normally appear. The contents
|
|
130
|
+
of the NOTICE file are for informational purposes only and
|
|
131
|
+
do not modify the License. You may add Your own attribution
|
|
132
|
+
notices within Derivative Works that You distribute, alongside
|
|
133
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
134
|
+
that such additional attribution notices cannot be construed
|
|
135
|
+
as modifying the License.
|
|
136
|
+
|
|
137
|
+
You may add Your own copyright statement to Your modifications and
|
|
138
|
+
may provide additional or different license terms and conditions
|
|
139
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
140
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
141
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
142
|
+
the conditions stated in this License.
|
|
143
|
+
|
|
144
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
145
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
146
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
147
|
+
this License, without any additional terms or conditions.
|
|
148
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
149
|
+
the terms of any separate license agreement you may have executed
|
|
150
|
+
with Licensor regarding such Contributions.
|
|
151
|
+
|
|
152
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
153
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
154
|
+
except as required for reasonable and customary use in describing the
|
|
155
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
156
|
+
|
|
157
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
158
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
159
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
160
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
161
|
+
implied, including, without limitation, any warranties or conditions
|
|
162
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
163
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
164
|
+
appropriateness of using or redistributing the Work and assume any
|
|
165
|
+
risks associated with Your exercise of permissions under this License.
|
|
166
|
+
|
|
167
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
168
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
169
|
+
unless required by applicable law (such as deliberate and grossly
|
|
170
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
171
|
+
liable to You for damages, including any direct, indirect, special,
|
|
172
|
+
incidental, or consequential damages of any character arising as a
|
|
173
|
+
result of this License or out of the use or inability to use the
|
|
174
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
175
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
176
|
+
other commercial damages or losses), even if such Contributor
|
|
177
|
+
has been advised of the possibility of such damages.
|
|
178
|
+
|
|
179
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
180
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
181
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
182
|
+
or other liability obligations and/or rights consistent with this
|
|
183
|
+
License. However, in accepting such obligations, You may act only
|
|
184
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
185
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
186
|
+
defend, and hold each Contributor harmless for any liability
|
|
187
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
188
|
+
of your accepting any such warranty or additional liability.
|
|
189
|
+
|
|
190
|
+
END OF TERMS AND CONDITIONS
|
|
191
|
+
|
|
192
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
193
|
+
|
|
194
|
+
To apply the Apache License to your work, attach the following
|
|
195
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
196
|
+
replaced with your own identifying information. (Don't include
|
|
197
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
198
|
+
comment syntax for the file format. We also recommend that a
|
|
199
|
+
file or class name and description of purpose be included on the
|
|
200
|
+
same "printed page" as the copyright notice for easier
|
|
201
|
+
identification within third-party archives.
|
|
202
|
+
|
|
203
|
+
Copyright [yyyy] [name of copyright owner]
|
|
204
|
+
|
|
205
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
206
|
+
you may not use this file except in compliance with the License.
|
|
207
|
+
You may obtain a copy of the License at
|
|
208
|
+
|
|
209
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
210
|
+
|
|
211
|
+
Unless required by applicable law or agreed to in writing, software
|
|
212
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
213
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
214
|
+
See the License for the specific language governing permissions and
|
|
215
|
+
limitations under the License.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
cms-hte-ial2-reader
|
|
2
|
+
Copyright 2026 b.well Connected Health, Inc.
|
|
3
|
+
|
|
4
|
+
This product includes software developed by b.well Connected Health, Inc. (https://www.bwell.com).
|
|
5
|
+
|
|
6
|
+
Portions of this software may incorporate third-party open source components; see THIRD-PARTY-NOTICES.md for a complete list of those components and their respective licenses.
|
|
7
|
+
|
|
8
|
+
b.well Connected Health, Inc. is not affiliated with, and this software is not endorsed or certified by, the Centers for Medicare & Medicaid Services (CMS) or HL7 International. This software verifies signed JWT ID Tokens issued by third-party Credential Service Providers (CSPs) at NIST 800-63-3 Identity Assurance Level 2 (IAL2) and extracts demographics per those CSPs' payload specifications into a FHIR R4 Patient resource; references to CMS, IAL2, JWT/JWKS, and FHIR are solely for interoperability description and do not imply endorsement by, or affiliation with, any CSP, NIST, or HL7 International.
|
|
9
|
+
|
|
10
|
+
This software may be subject to U.S. export control laws, including the Export Administration Regulations (EAR). You may not use, export, or re-export this software in violation of applicable export laws, or to any country, entity, or individual subject to U.S. sanctions or listed on a U.S. government restricted- or denied-party list.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cmshteial2reader
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""cmshteial2reader: Extract and verify IAL2 token demographics as FHIR Patient resources.
|
|
2
|
+
|
|
3
|
+
Accepts a signed JWT (ID Token) from a Credential Service Provider (CSP),
|
|
4
|
+
verifies the signature via JWKS, extracts demographics per the CSP payload
|
|
5
|
+
specification V7.1, and returns a FHIR R4 Patient resource.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from .claims_model import IAL2Address, IAL2Claims, IAL2LegalId
|
|
9
|
+
from .fhir_converter import IAL2ToFhirConverter
|
|
10
|
+
from .ial2_extractor import IAL2Extractor
|
|
11
|
+
from .multi_issuer_verifier import MultiIssuerTokenVerifier
|
|
12
|
+
from .token_verifier import TokenVerificationError, TokenVerifier
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"IAL2Address",
|
|
16
|
+
"IAL2Claims",
|
|
17
|
+
"IAL2Extractor",
|
|
18
|
+
"IAL2LegalId",
|
|
19
|
+
"IAL2ToFhirConverter",
|
|
20
|
+
"MultiIssuerTokenVerifier",
|
|
21
|
+
"TokenVerificationError",
|
|
22
|
+
"TokenVerifier",
|
|
23
|
+
]
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
"""Data models for IAL2 token claims per CSP Payload Specification V7.1.
|
|
2
|
+
|
|
3
|
+
Handles field-name aliases across CSPs (e.g. name_first vs given_name)
|
|
4
|
+
and normalizes them into a single canonical representation.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class IAL2Address:
|
|
15
|
+
"""A physical address extracted from an IAL2 token.
|
|
16
|
+
|
|
17
|
+
Attributes:
|
|
18
|
+
address_line1: Primary street address.
|
|
19
|
+
address_line2: Secondary address line (apt, suite, etc.).
|
|
20
|
+
city: City or locality.
|
|
21
|
+
state: State, province, or region.
|
|
22
|
+
postal_code: ZIP or postal code.
|
|
23
|
+
country: Country.
|
|
24
|
+
full_address: Composite formatted address string.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
address_line1: str | None = None
|
|
28
|
+
address_line2: str | None = None
|
|
29
|
+
city: str | None = None
|
|
30
|
+
state: str | None = None
|
|
31
|
+
postal_code: str | None = None
|
|
32
|
+
country: str | None = None
|
|
33
|
+
full_address: str | None = None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class IAL2LegalId:
|
|
38
|
+
"""A government-issued legal identity document.
|
|
39
|
+
|
|
40
|
+
Attributes:
|
|
41
|
+
issuer: Issuing authority (e.g. state DMV, federal government).
|
|
42
|
+
id_type: Type of document (e.g. drivers_license, passport).
|
|
43
|
+
identifier: The document number/identifier.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
issuer: str | None = None
|
|
47
|
+
id_type: str | None = None
|
|
48
|
+
identifier: str | None = None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class IAL2Claims:
|
|
53
|
+
"""Normalized demographic claims from an IAL2 token.
|
|
54
|
+
|
|
55
|
+
Fields follow the CSP Payload Specification V7.1 (Feb 2026).
|
|
56
|
+
Alias resolution (e.g. given_name -> name_first) happens in from_token_claims().
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
# OIDC standard claims
|
|
60
|
+
iss: str = ""
|
|
61
|
+
sub: str = ""
|
|
62
|
+
aud: str = ""
|
|
63
|
+
exp: int = 0
|
|
64
|
+
iat: int = 0
|
|
65
|
+
jti: str = ""
|
|
66
|
+
at_hash: str | None = None
|
|
67
|
+
auth_time: int | None = None
|
|
68
|
+
identity_assurance_level: str | None = None
|
|
69
|
+
|
|
70
|
+
# Core person attributes
|
|
71
|
+
name_first: str = ""
|
|
72
|
+
name_middle: str | None = None
|
|
73
|
+
name_last: str = ""
|
|
74
|
+
name_full: str | None = None
|
|
75
|
+
name_historical: list[str] | None = None
|
|
76
|
+
birth_date: str = ""
|
|
77
|
+
sex_legal: str | None = None
|
|
78
|
+
|
|
79
|
+
# Address information
|
|
80
|
+
address: IAL2Address | None = None
|
|
81
|
+
address_historical: list[IAL2Address] | None = None
|
|
82
|
+
|
|
83
|
+
# Contact information
|
|
84
|
+
email: str | None = None
|
|
85
|
+
phone_number: str | None = None
|
|
86
|
+
phone_number_historical: list[str] | None = None
|
|
87
|
+
|
|
88
|
+
# Legal identifiers
|
|
89
|
+
uuid: str | None = None
|
|
90
|
+
ssn_itin: str | None = None
|
|
91
|
+
ssn_itin_short: str | None = None
|
|
92
|
+
legal_id: IAL2LegalId | None = None
|
|
93
|
+
suffix: str | None = None
|
|
94
|
+
|
|
95
|
+
@classmethod
|
|
96
|
+
def from_token_claims(cls, claims: dict[str, Any]) -> IAL2Claims:
|
|
97
|
+
"""Create an IAL2Claims instance from raw JWT claims.
|
|
98
|
+
|
|
99
|
+
Resolves field-name aliases used by different CSPs:
|
|
100
|
+
- given_name -> name_first
|
|
101
|
+
- middle_name -> name_middle
|
|
102
|
+
- last_name -> name_last
|
|
103
|
+
- street_address -> address_line1
|
|
104
|
+
- locality -> city
|
|
105
|
+
- region -> state
|
|
106
|
+
- postal_code / code_postal -> postal_code
|
|
107
|
+
- formatted -> full_address
|
|
108
|
+
"""
|
|
109
|
+
address = _extract_address(claims)
|
|
110
|
+
historical_addresses = _extract_historical_addresses(
|
|
111
|
+
claims.get("address_historical")
|
|
112
|
+
)
|
|
113
|
+
legal_id = _extract_legal_id(claims)
|
|
114
|
+
|
|
115
|
+
return cls(
|
|
116
|
+
# OIDC standard
|
|
117
|
+
iss=claims.get("iss", ""),
|
|
118
|
+
sub=claims.get("sub", ""),
|
|
119
|
+
aud=claims.get("aud", ""),
|
|
120
|
+
exp=claims.get("exp", 0),
|
|
121
|
+
iat=claims.get("iat", 0),
|
|
122
|
+
jti=claims.get("jti", ""),
|
|
123
|
+
at_hash=claims.get("at_hash"),
|
|
124
|
+
auth_time=claims.get("auth_time"),
|
|
125
|
+
identity_assurance_level=claims.get("identity_assurance_level"),
|
|
126
|
+
# Core person
|
|
127
|
+
name_first=claims.get("name_first") or claims.get("given_name", ""),
|
|
128
|
+
name_middle=claims.get("name_middle") or claims.get("middle_name"),
|
|
129
|
+
name_last=claims.get("name_last") or claims.get("last_name", ""),
|
|
130
|
+
name_full=claims.get("name_full"),
|
|
131
|
+
name_historical=claims.get("name_historical"),
|
|
132
|
+
birth_date=claims.get("birth_date") or claims.get("date_birth", ""),
|
|
133
|
+
sex_legal=claims.get("sex_legal") or claims.get("gender"),
|
|
134
|
+
suffix=claims.get("suffix"),
|
|
135
|
+
# Address
|
|
136
|
+
address=address,
|
|
137
|
+
address_historical=historical_addresses,
|
|
138
|
+
# Contact
|
|
139
|
+
email=claims.get("email"),
|
|
140
|
+
phone_number=claims.get("phone_number"),
|
|
141
|
+
phone_number_historical=claims.get("phone_number_historical"),
|
|
142
|
+
# Legal identifiers
|
|
143
|
+
uuid=claims.get("UUID") or claims.get("uuid"),
|
|
144
|
+
ssn_itin=claims.get("ssn_itin"),
|
|
145
|
+
ssn_itin_short=claims.get("ssn_itin_short"),
|
|
146
|
+
legal_id=legal_id,
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _extract_address(claims: dict[str, Any]) -> IAL2Address | None:
|
|
151
|
+
"""Extract the primary address from claims, resolving aliases."""
|
|
152
|
+
line1 = claims.get("address_line1") or claims.get("street_address")
|
|
153
|
+
city = claims.get("city") or claims.get("locality")
|
|
154
|
+
state = claims.get("state") or claims.get("region")
|
|
155
|
+
postal = claims.get("postal_code") or claims.get("code_postal")
|
|
156
|
+
|
|
157
|
+
if not any([line1, city, state, postal]):
|
|
158
|
+
return None
|
|
159
|
+
|
|
160
|
+
return IAL2Address(
|
|
161
|
+
address_line1=line1,
|
|
162
|
+
address_line2=claims.get("address_line2"),
|
|
163
|
+
city=city,
|
|
164
|
+
state=state,
|
|
165
|
+
postal_code=postal,
|
|
166
|
+
country=claims.get("country"),
|
|
167
|
+
full_address=claims.get("full_address") or claims.get("formatted"),
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _extract_historical_addresses(
|
|
172
|
+
raw: Any,
|
|
173
|
+
) -> list[IAL2Address] | None:
|
|
174
|
+
"""Parse historical addresses from the claims payload."""
|
|
175
|
+
if not raw or not isinstance(raw, list):
|
|
176
|
+
return None
|
|
177
|
+
|
|
178
|
+
addresses: list[IAL2Address] = []
|
|
179
|
+
for entry in raw:
|
|
180
|
+
if not isinstance(entry, dict):
|
|
181
|
+
continue
|
|
182
|
+
|
|
183
|
+
addresses.append(
|
|
184
|
+
IAL2Address(
|
|
185
|
+
address_line1=entry.get("address_line1") or entry.get("street_address"),
|
|
186
|
+
address_line2=entry.get("address_line2"),
|
|
187
|
+
city=entry.get("city") or entry.get("locality"),
|
|
188
|
+
state=entry.get("state") or entry.get("region"),
|
|
189
|
+
postal_code=entry.get("postal_code") or entry.get("code_postal"),
|
|
190
|
+
country=entry.get("country"),
|
|
191
|
+
full_address=entry.get("full_address") or entry.get("formatted"),
|
|
192
|
+
)
|
|
193
|
+
)
|
|
194
|
+
return addresses if addresses else None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _extract_legal_id(claims: dict[str, Any]) -> IAL2LegalId | None:
|
|
198
|
+
"""Extract legal identity document info from claims."""
|
|
199
|
+
legal_id_raw = claims.get("legal_id") or claims.get("legal_id_issuer")
|
|
200
|
+
if not legal_id_raw:
|
|
201
|
+
return None
|
|
202
|
+
|
|
203
|
+
if isinstance(legal_id_raw, dict):
|
|
204
|
+
return IAL2LegalId(
|
|
205
|
+
issuer=legal_id_raw.get("issuer"),
|
|
206
|
+
id_type=legal_id_raw.get("type"),
|
|
207
|
+
identifier=legal_id_raw.get("identifier"),
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
# If it's a string, treat it as the issuer identifier
|
|
211
|
+
return IAL2LegalId(issuer=str(legal_id_raw))
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
"""Converts IAL2 demographic claims into a FHIR R4 Patient resource.
|
|
2
|
+
|
|
3
|
+
Produces a dict conforming to the FHIR R4 Patient resource structure
|
|
4
|
+
(https://hl7.org/fhir/R4/patient.html).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from fhirschemapy.R4B.patient import Patient
|
|
12
|
+
|
|
13
|
+
from .claims_model import IAL2Address, IAL2Claims
|
|
14
|
+
|
|
15
|
+
# Mapping from CSP sex_legal values to FHIR administrative gender codes
|
|
16
|
+
_SEX_TO_FHIR_GENDER: dict[str, str] = {
|
|
17
|
+
"male": "male",
|
|
18
|
+
"m": "male",
|
|
19
|
+
"female": "female",
|
|
20
|
+
"f": "female",
|
|
21
|
+
"other": "other",
|
|
22
|
+
"unknown": "unknown",
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
# https://terminology.hl7.org/CodeSystem-v2-0203.html
|
|
26
|
+
_IDENTIFIER_TYPE_CODING_SYSTEM = "http://terminology.hl7.org/CodeSystem/v2-0203"
|
|
27
|
+
_SSN_IDENTIFIER_SYSTEM = "http://hl7.org/fhir/sid/us-ssn"
|
|
28
|
+
|
|
29
|
+
# FHIR Identifier.type coding codes (from the v2-0203 code system above)
|
|
30
|
+
_IDENTIFIER_CODE_RESOURCE_IDENTIFIER = "RI"
|
|
31
|
+
_IDENTIFIER_CODE_SOCIAL_SECURITY_NUMBER = "SS"
|
|
32
|
+
_IDENTIFIER_CODE_DRIVERS_LICENSE_NUMBER = "DL"
|
|
33
|
+
|
|
34
|
+
# FHIR HumanName.use / Address.use / ContactPoint.use values
|
|
35
|
+
_USE_OFFICIAL = "official"
|
|
36
|
+
_USE_HOME = "home"
|
|
37
|
+
_USE_MOBILE = "mobile"
|
|
38
|
+
_USE_OLD = "old"
|
|
39
|
+
|
|
40
|
+
# FHIR ContactPoint.system values
|
|
41
|
+
_CONTACT_SYSTEM_EMAIL = "email"
|
|
42
|
+
_CONTACT_SYSTEM_PHONE = "phone"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class IAL2ToFhirConverter:
|
|
46
|
+
"""Converts IAL2Claims into a FHIR R4 Patient resource dictionary."""
|
|
47
|
+
|
|
48
|
+
def convert(self, claims: IAL2Claims) -> dict[str, Any]:
|
|
49
|
+
"""Convert IAL2 claims to a FHIR Patient resource.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
claims: The normalized IAL2 demographic claims.
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
A dictionary representing a FHIR R4 Patient resource, validated
|
|
56
|
+
through fhirschemapy.
|
|
57
|
+
|
|
58
|
+
Raises:
|
|
59
|
+
pydantic.ValidationError: If the built resource doesn't conform
|
|
60
|
+
to the FHIR R4 Patient schema.
|
|
61
|
+
"""
|
|
62
|
+
patient: dict[str, Any] = {
|
|
63
|
+
"resourceType": "Patient",
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
# Identifiers
|
|
67
|
+
identifiers = self._build_identifiers(claims)
|
|
68
|
+
if identifiers:
|
|
69
|
+
patient["identifier"] = identifiers
|
|
70
|
+
|
|
71
|
+
# Name
|
|
72
|
+
names = self._build_names(claims)
|
|
73
|
+
if names:
|
|
74
|
+
patient["name"] = names
|
|
75
|
+
|
|
76
|
+
# Birth date
|
|
77
|
+
if claims.birth_date:
|
|
78
|
+
patient["birthDate"] = claims.birth_date
|
|
79
|
+
|
|
80
|
+
# Gender
|
|
81
|
+
if claims.sex_legal:
|
|
82
|
+
gender = _SEX_TO_FHIR_GENDER.get(claims.sex_legal.lower(), "unknown")
|
|
83
|
+
patient["gender"] = gender
|
|
84
|
+
|
|
85
|
+
# Telecom (email, phone)
|
|
86
|
+
telecoms = self._build_telecoms(claims)
|
|
87
|
+
if telecoms:
|
|
88
|
+
patient["telecom"] = telecoms
|
|
89
|
+
|
|
90
|
+
# Address
|
|
91
|
+
addresses = self._build_addresses(claims)
|
|
92
|
+
if addresses:
|
|
93
|
+
patient["address"] = addresses
|
|
94
|
+
|
|
95
|
+
validated = Patient.model_validate(patient)
|
|
96
|
+
result: dict[str, Any] = validated.model_dump(exclude_none=True, by_alias=True)
|
|
97
|
+
return result
|
|
98
|
+
|
|
99
|
+
@staticmethod
|
|
100
|
+
def _build_identifiers(claims: IAL2Claims) -> list[dict[str, Any]]:
|
|
101
|
+
"""Build FHIR Identifier entries from claims."""
|
|
102
|
+
identifiers: list[dict[str, Any]] = []
|
|
103
|
+
|
|
104
|
+
if claims.uuid:
|
|
105
|
+
identifiers.append(
|
|
106
|
+
{
|
|
107
|
+
"system": claims.iss,
|
|
108
|
+
"value": claims.uuid,
|
|
109
|
+
"type": {
|
|
110
|
+
"coding": [
|
|
111
|
+
{
|
|
112
|
+
"system": _IDENTIFIER_TYPE_CODING_SYSTEM,
|
|
113
|
+
"code": _IDENTIFIER_CODE_RESOURCE_IDENTIFIER,
|
|
114
|
+
"display": "Resource identifier",
|
|
115
|
+
}
|
|
116
|
+
]
|
|
117
|
+
},
|
|
118
|
+
}
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
if claims.ssn_itin:
|
|
122
|
+
identifiers.append(
|
|
123
|
+
{
|
|
124
|
+
"system": _SSN_IDENTIFIER_SYSTEM,
|
|
125
|
+
"value": claims.ssn_itin,
|
|
126
|
+
"type": {
|
|
127
|
+
"coding": [
|
|
128
|
+
{
|
|
129
|
+
"system": _IDENTIFIER_TYPE_CODING_SYSTEM,
|
|
130
|
+
"code": _IDENTIFIER_CODE_SOCIAL_SECURITY_NUMBER,
|
|
131
|
+
"display": "Social Security number",
|
|
132
|
+
}
|
|
133
|
+
]
|
|
134
|
+
},
|
|
135
|
+
}
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
if claims.legal_id:
|
|
139
|
+
lid = claims.legal_id
|
|
140
|
+
identifier_entry: dict[str, Any] = {
|
|
141
|
+
"type": {
|
|
142
|
+
"coding": [
|
|
143
|
+
{
|
|
144
|
+
"system": _IDENTIFIER_TYPE_CODING_SYSTEM,
|
|
145
|
+
"code": _IDENTIFIER_CODE_DRIVERS_LICENSE_NUMBER,
|
|
146
|
+
"display": "Driver's license number",
|
|
147
|
+
}
|
|
148
|
+
]
|
|
149
|
+
},
|
|
150
|
+
}
|
|
151
|
+
if lid.identifier:
|
|
152
|
+
identifier_entry["value"] = lid.identifier
|
|
153
|
+
if lid.issuer:
|
|
154
|
+
identifier_entry["assigner"] = {"display": lid.issuer}
|
|
155
|
+
identifiers.append(identifier_entry)
|
|
156
|
+
|
|
157
|
+
return identifiers
|
|
158
|
+
|
|
159
|
+
@staticmethod
|
|
160
|
+
def _build_names(claims: IAL2Claims) -> list[dict[str, Any]]:
|
|
161
|
+
"""Build FHIR HumanName entries from claims."""
|
|
162
|
+
names: list[dict[str, Any]] = []
|
|
163
|
+
|
|
164
|
+
# Official / current name
|
|
165
|
+
official: dict[str, Any] = {"use": _USE_OFFICIAL}
|
|
166
|
+
if claims.name_last:
|
|
167
|
+
official["family"] = claims.name_last
|
|
168
|
+
given: list[str] = []
|
|
169
|
+
if claims.name_first:
|
|
170
|
+
given.append(claims.name_first)
|
|
171
|
+
if claims.name_middle:
|
|
172
|
+
given.append(claims.name_middle)
|
|
173
|
+
if given:
|
|
174
|
+
official["given"] = given
|
|
175
|
+
if claims.suffix:
|
|
176
|
+
official["suffix"] = [claims.suffix]
|
|
177
|
+
if claims.name_full:
|
|
178
|
+
official["text"] = claims.name_full
|
|
179
|
+
if official.get("family") or official.get("given"):
|
|
180
|
+
names.append(official)
|
|
181
|
+
|
|
182
|
+
# Historical names
|
|
183
|
+
if claims.name_historical:
|
|
184
|
+
for hist_name in claims.name_historical:
|
|
185
|
+
names.append(
|
|
186
|
+
{
|
|
187
|
+
"use": _USE_OLD,
|
|
188
|
+
"text": hist_name,
|
|
189
|
+
}
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
return names
|
|
193
|
+
|
|
194
|
+
@staticmethod
|
|
195
|
+
def _build_telecoms(claims: IAL2Claims) -> list[dict[str, Any]]:
|
|
196
|
+
"""Build FHIR ContactPoint entries from claims."""
|
|
197
|
+
telecoms: list[dict[str, Any]] = []
|
|
198
|
+
|
|
199
|
+
if claims.email:
|
|
200
|
+
telecoms.append(
|
|
201
|
+
{
|
|
202
|
+
"system": _CONTACT_SYSTEM_EMAIL,
|
|
203
|
+
"value": claims.email,
|
|
204
|
+
"use": _USE_HOME,
|
|
205
|
+
}
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
if claims.phone_number:
|
|
209
|
+
telecoms.append(
|
|
210
|
+
{
|
|
211
|
+
"system": _CONTACT_SYSTEM_PHONE,
|
|
212
|
+
"value": claims.phone_number,
|
|
213
|
+
"use": _USE_MOBILE,
|
|
214
|
+
}
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
if claims.phone_number_historical:
|
|
218
|
+
for phone in claims.phone_number_historical:
|
|
219
|
+
telecoms.append(
|
|
220
|
+
{
|
|
221
|
+
"system": _CONTACT_SYSTEM_PHONE,
|
|
222
|
+
"value": phone,
|
|
223
|
+
"use": _USE_OLD,
|
|
224
|
+
}
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
return telecoms
|
|
228
|
+
|
|
229
|
+
@staticmethod
|
|
230
|
+
def _build_addresses(claims: IAL2Claims) -> list[dict[str, Any]]:
|
|
231
|
+
"""Build FHIR Address entries from claims."""
|
|
232
|
+
addresses: list[dict[str, Any]] = []
|
|
233
|
+
|
|
234
|
+
if claims.address:
|
|
235
|
+
addresses.append(_address_to_fhir(claims.address, use=_USE_HOME))
|
|
236
|
+
|
|
237
|
+
if claims.address_historical:
|
|
238
|
+
for hist_addr in claims.address_historical:
|
|
239
|
+
addresses.append(_address_to_fhir(hist_addr, use=_USE_OLD))
|
|
240
|
+
|
|
241
|
+
return addresses
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _address_to_fhir(addr: IAL2Address, *, use: str) -> dict[str, Any]:
|
|
245
|
+
"""Convert an IAL2Address to a FHIR Address dict."""
|
|
246
|
+
fhir_addr: dict[str, Any] = {"use": use}
|
|
247
|
+
|
|
248
|
+
lines: list[str] = []
|
|
249
|
+
if addr.address_line1:
|
|
250
|
+
lines.append(addr.address_line1)
|
|
251
|
+
if addr.address_line2:
|
|
252
|
+
lines.append(addr.address_line2)
|
|
253
|
+
if lines:
|
|
254
|
+
fhir_addr["line"] = lines
|
|
255
|
+
|
|
256
|
+
if addr.city:
|
|
257
|
+
fhir_addr["city"] = addr.city
|
|
258
|
+
if addr.state:
|
|
259
|
+
fhir_addr["state"] = addr.state
|
|
260
|
+
if addr.postal_code:
|
|
261
|
+
fhir_addr["postalCode"] = addr.postal_code
|
|
262
|
+
if addr.country:
|
|
263
|
+
fhir_addr["country"] = addr.country
|
|
264
|
+
if addr.full_address:
|
|
265
|
+
fhir_addr["text"] = addr.full_address
|
|
266
|
+
|
|
267
|
+
return fhir_addr
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Main orchestrator for IAL2 token extraction.
|
|
2
|
+
|
|
3
|
+
Combines token verification and FHIR conversion into a single
|
|
4
|
+
entry point.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import logging
|
|
10
|
+
from typing import Any, Protocol
|
|
11
|
+
|
|
12
|
+
from .claims_model import IAL2Claims
|
|
13
|
+
from .fhir_converter import IAL2ToFhirConverter
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class TokenVerifierProtocol(Protocol):
|
|
19
|
+
"""Structural interface for anything IAL2Extractor can verify tokens with.
|
|
20
|
+
|
|
21
|
+
Both TokenVerifier (single issuer) and MultiIssuerTokenVerifier
|
|
22
|
+
(whitelisted issuers) satisfy this without inheritance.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
async def verify(self, token: str) -> dict[str, Any]: ...
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class IAL2Extractor:
|
|
29
|
+
"""Accepts an IAL2 JWT, verifies it, and returns a FHIR Patient resource.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
verifier: A TokenVerifier (single issuer) or MultiIssuerTokenVerifier
|
|
33
|
+
(whitelisted issuers) for signature validation.
|
|
34
|
+
converter: An IAL2ToFhirConverter instance. If None, a default
|
|
35
|
+
converter is created.
|
|
36
|
+
|
|
37
|
+
Example::
|
|
38
|
+
|
|
39
|
+
verifier = TokenVerifier(
|
|
40
|
+
jwks_uri="https://idp.example.com/.well-known/jwks.json",
|
|
41
|
+
audience="my-client-id",
|
|
42
|
+
)
|
|
43
|
+
extractor = IAL2Extractor(verifier=verifier)
|
|
44
|
+
patient = await extractor.extract(token_string)
|
|
45
|
+
# patient is a FHIR R4 Patient resource dict
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
*,
|
|
51
|
+
verifier: TokenVerifierProtocol,
|
|
52
|
+
converter: IAL2ToFhirConverter | None = None,
|
|
53
|
+
) -> None:
|
|
54
|
+
self._verifier = verifier
|
|
55
|
+
self._converter = converter or IAL2ToFhirConverter()
|
|
56
|
+
|
|
57
|
+
async def extract(self, token: str) -> dict[str, Any]:
|
|
58
|
+
"""Verify an IAL2 token and return a FHIR Patient resource.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
token: The encoded JWT string from the CSP.
|
|
62
|
+
|
|
63
|
+
Returns:
|
|
64
|
+
A FHIR R4 Patient resource as a dictionary.
|
|
65
|
+
|
|
66
|
+
Raises:
|
|
67
|
+
TokenVerificationError: If the token signature or claims
|
|
68
|
+
are invalid.
|
|
69
|
+
"""
|
|
70
|
+
logger.debug("Verifying IAL2 token")
|
|
71
|
+
raw_claims = await self._verifier.verify(token)
|
|
72
|
+
|
|
73
|
+
logger.debug("Extracting claims from verified token")
|
|
74
|
+
claims = IAL2Claims.from_token_claims(raw_claims)
|
|
75
|
+
|
|
76
|
+
logger.debug("Converting claims to FHIR Patient resource")
|
|
77
|
+
patient = self._converter.convert(claims)
|
|
78
|
+
|
|
79
|
+
return patient
|
|
80
|
+
|
|
81
|
+
async def extract_claims(self, token: str) -> IAL2Claims:
|
|
82
|
+
"""Verify an IAL2 token and return the normalized claims.
|
|
83
|
+
|
|
84
|
+
Useful when you need the structured claims without FHIR conversion.
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
token: The encoded JWT string from the CSP.
|
|
88
|
+
|
|
89
|
+
Returns:
|
|
90
|
+
An IAL2Claims dataclass with normalized demographics.
|
|
91
|
+
|
|
92
|
+
Raises:
|
|
93
|
+
TokenVerificationError: If the token signature or claims
|
|
94
|
+
are invalid.
|
|
95
|
+
"""
|
|
96
|
+
raw_claims = await self._verifier.verify(token)
|
|
97
|
+
return IAL2Claims.from_token_claims(raw_claims)
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""Multi-issuer JWT verification restricted to a whitelist of JWKS URLs.
|
|
2
|
+
|
|
3
|
+
Resolves an incoming token's issuer via OIDC discovery, then only proceeds
|
|
4
|
+
with signature verification if the discovered JWKS URL is on an explicit
|
|
5
|
+
allow list -- an unrecognized issuer is rejected before any signing key is
|
|
6
|
+
fetched.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import ipaddress
|
|
13
|
+
import os
|
|
14
|
+
import socket
|
|
15
|
+
from typing import Any
|
|
16
|
+
from urllib.parse import urlparse
|
|
17
|
+
|
|
18
|
+
import jwt
|
|
19
|
+
|
|
20
|
+
from .token_verifier import TokenVerificationError, TokenVerifier
|
|
21
|
+
|
|
22
|
+
_IpAddress = ipaddress.IPv4Address | ipaddress.IPv6Address
|
|
23
|
+
|
|
24
|
+
ALLOWED_JWKS_URLS_ENV_VAR = "IAL2_ALLOWED_JWKS_URLS"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class MultiIssuerTokenVerifier:
|
|
28
|
+
"""Verifies IAL2 JWTs from any issuer whose JWKS URL is whitelisted.
|
|
29
|
+
|
|
30
|
+
Unlike TokenVerifier, which is pinned to a single jwks_uri, this class
|
|
31
|
+
accepts tokens from multiple issuers by resolving each token's issuer
|
|
32
|
+
via OIDC discovery and checking the discovered JWKS URL against an
|
|
33
|
+
explicit allow list before trusting it.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
audience: Expected ``aud`` claim value, applied to every issuer.
|
|
37
|
+
allowed_jwks_uris: JWKS URLs this instance will trust.
|
|
38
|
+
algorithms: Allowed signing algorithms. Defaults to RS256.
|
|
39
|
+
|
|
40
|
+
Example::
|
|
41
|
+
|
|
42
|
+
verifier = MultiIssuerTokenVerifier.from_env(audience="my-client-id")
|
|
43
|
+
claims = await verifier.verify(token_string)
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
def __init__(
|
|
47
|
+
self,
|
|
48
|
+
*,
|
|
49
|
+
audience: str,
|
|
50
|
+
allowed_jwks_uris: list[str],
|
|
51
|
+
algorithms: list[str] | None = None,
|
|
52
|
+
) -> None:
|
|
53
|
+
self._audience = audience
|
|
54
|
+
self._allowed_jwks_uris = set(allowed_jwks_uris)
|
|
55
|
+
self._algorithms = algorithms
|
|
56
|
+
self._verifiers_by_issuer: dict[str, TokenVerifier] = {}
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
def from_env(
|
|
60
|
+
cls,
|
|
61
|
+
*,
|
|
62
|
+
audience: str,
|
|
63
|
+
env_var: str = ALLOWED_JWKS_URLS_ENV_VAR,
|
|
64
|
+
algorithms: list[str] | None = None,
|
|
65
|
+
) -> MultiIssuerTokenVerifier:
|
|
66
|
+
"""Build the verifier from a comma-separated env var of JWKS URLs.
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
audience: Expected ``aud`` claim value.
|
|
70
|
+
env_var: Name of the env var holding the whitelist.
|
|
71
|
+
algorithms: Allowed signing algorithms.
|
|
72
|
+
|
|
73
|
+
Raises:
|
|
74
|
+
ValueError: If the env var is unset or contains no URLs.
|
|
75
|
+
"""
|
|
76
|
+
raw = os.environ.get(env_var, "")
|
|
77
|
+
allowed = [url.strip() for url in raw.split(",") if url.strip()]
|
|
78
|
+
if not allowed:
|
|
79
|
+
raise ValueError(f"{env_var} is not set or contains no JWKS URLs")
|
|
80
|
+
return cls(audience=audience, allowed_jwks_uris=allowed, algorithms=algorithms)
|
|
81
|
+
|
|
82
|
+
async def verify(self, token: str) -> dict[str, Any]:
|
|
83
|
+
"""Verify a token from any whitelisted issuer.
|
|
84
|
+
|
|
85
|
+
Args:
|
|
86
|
+
token: The encoded JWT string.
|
|
87
|
+
|
|
88
|
+
Returns:
|
|
89
|
+
The decoded claims dictionary.
|
|
90
|
+
|
|
91
|
+
Raises:
|
|
92
|
+
TokenVerificationError: If the issuer's JWKS URL isn't
|
|
93
|
+
whitelisted, or the token fails verification.
|
|
94
|
+
"""
|
|
95
|
+
issuer = self._peek_issuer(token)
|
|
96
|
+
|
|
97
|
+
verifier = self._verifiers_by_issuer.get(issuer)
|
|
98
|
+
if verifier is None:
|
|
99
|
+
verifier = await self._build_verifier_for_issuer(issuer)
|
|
100
|
+
self._verifiers_by_issuer[issuer] = verifier
|
|
101
|
+
|
|
102
|
+
return await verifier.verify(token)
|
|
103
|
+
|
|
104
|
+
@staticmethod
|
|
105
|
+
def _peek_issuer(token: str) -> str:
|
|
106
|
+
"""Read the ``iss`` claim without verifying the signature.
|
|
107
|
+
|
|
108
|
+
This claim is untrusted at this point -- it is only used to select
|
|
109
|
+
which JWKS URL to check against the whitelist, never to make a
|
|
110
|
+
trust decision on its own. The real verification happens in
|
|
111
|
+
TokenVerifier.verify() once the whitelist check passes.
|
|
112
|
+
"""
|
|
113
|
+
try:
|
|
114
|
+
unverified = jwt.decode(token, options={"verify_signature": False})
|
|
115
|
+
except jwt.InvalidTokenError as e:
|
|
116
|
+
raise TokenVerificationError(f"Could not parse token: {e}") from e
|
|
117
|
+
|
|
118
|
+
issuer = unverified.get("iss")
|
|
119
|
+
if not issuer:
|
|
120
|
+
raise TokenVerificationError("Token is missing the 'iss' claim")
|
|
121
|
+
return str(issuer)
|
|
122
|
+
|
|
123
|
+
async def _build_verifier_for_issuer(self, issuer: str) -> TokenVerifier:
|
|
124
|
+
"""Discover the issuer's JWKS URL and check it against the whitelist."""
|
|
125
|
+
pinned_ip = await self._validate_issuer_url(issuer)
|
|
126
|
+
|
|
127
|
+
verifier = await TokenVerifier.from_oidc_discovery(
|
|
128
|
+
discovery_url=f"{issuer.rstrip('/')}/.well-known/openid-configuration",
|
|
129
|
+
audience=self._audience,
|
|
130
|
+
issuer=issuer,
|
|
131
|
+
algorithms=self._algorithms,
|
|
132
|
+
pinned_ip=pinned_ip,
|
|
133
|
+
)
|
|
134
|
+
if verifier.jwks_uri not in self._allowed_jwks_uris:
|
|
135
|
+
raise TokenVerificationError(
|
|
136
|
+
f"Issuer '{issuer}' resolved to JWKS URL "
|
|
137
|
+
f"'{verifier.jwks_uri}', which is not whitelisted"
|
|
138
|
+
)
|
|
139
|
+
return verifier
|
|
140
|
+
|
|
141
|
+
@staticmethod
|
|
142
|
+
async def _validate_issuer_url(issuer: str) -> str:
|
|
143
|
+
"""Reject issuer URLs that could be used for SSRF before any
|
|
144
|
+
discovery or JWKS request is made, and return the validated IP to
|
|
145
|
+
pin the actual discovery connection to.
|
|
146
|
+
|
|
147
|
+
The issuer claim is unverified at this point -- read via
|
|
148
|
+
_peek_issuer() before signature verification, purely to select a
|
|
149
|
+
JWKS URL. Without this check, an attacker could set 'iss' to an
|
|
150
|
+
internal service or cloud metadata endpoint and have this process
|
|
151
|
+
make a request to it during OIDC discovery. Returning the validated
|
|
152
|
+
IP (rather than just validating and discarding it) lets the caller
|
|
153
|
+
pin the actual connection to it, closing the DNS-rebinding window
|
|
154
|
+
between this check and the request.
|
|
155
|
+
"""
|
|
156
|
+
parsed = urlparse(issuer)
|
|
157
|
+
if parsed.scheme != "https":
|
|
158
|
+
raise TokenVerificationError(f"Issuer URL must use https, got: {issuer!r}")
|
|
159
|
+
|
|
160
|
+
hostname = parsed.hostname
|
|
161
|
+
if not hostname:
|
|
162
|
+
raise TokenVerificationError(f"Issuer URL is missing a host: {issuer!r}")
|
|
163
|
+
|
|
164
|
+
addresses = await MultiIssuerTokenVerifier._resolve_addresses(hostname)
|
|
165
|
+
for address in addresses:
|
|
166
|
+
if (
|
|
167
|
+
address.is_private
|
|
168
|
+
or address.is_loopback
|
|
169
|
+
or address.is_link_local
|
|
170
|
+
or address.is_multicast
|
|
171
|
+
or address.is_reserved
|
|
172
|
+
or address.is_unspecified
|
|
173
|
+
):
|
|
174
|
+
raise TokenVerificationError(
|
|
175
|
+
f"Issuer '{issuer}' resolves to a non-public address "
|
|
176
|
+
f"({address}); rejected"
|
|
177
|
+
)
|
|
178
|
+
return str(addresses[0])
|
|
179
|
+
|
|
180
|
+
@staticmethod
|
|
181
|
+
async def _resolve_addresses(hostname: str) -> list[_IpAddress]:
|
|
182
|
+
"""Resolve a hostname to the IP address(es) it points to.
|
|
183
|
+
|
|
184
|
+
Guards against DNS rebinding: a hostname that looks external in
|
|
185
|
+
text form can still resolve to an internal address.
|
|
186
|
+
"""
|
|
187
|
+
try:
|
|
188
|
+
return [ipaddress.ip_address(hostname)]
|
|
189
|
+
except ValueError:
|
|
190
|
+
pass
|
|
191
|
+
|
|
192
|
+
try:
|
|
193
|
+
infos = await asyncio.to_thread(socket.getaddrinfo, hostname, None)
|
|
194
|
+
except socket.gaierror as e:
|
|
195
|
+
raise TokenVerificationError(
|
|
196
|
+
f"Could not resolve issuer host '{hostname}': {e}"
|
|
197
|
+
) from e
|
|
198
|
+
return [ipaddress.ip_address(info[4][0]) for info in infos]
|
|
File without changes
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""JWT signature verification for IAL2 tokens using JWKS.
|
|
2
|
+
|
|
3
|
+
Fetches the CSP's public keys from their OIDC discovery endpoint
|
|
4
|
+
and verifies the token signature, expiration, and audience.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
import http.client
|
|
11
|
+
import json
|
|
12
|
+
import logging
|
|
13
|
+
import socket
|
|
14
|
+
import ssl
|
|
15
|
+
from typing import Any
|
|
16
|
+
from urllib.parse import urlparse
|
|
17
|
+
from urllib.request import urlopen
|
|
18
|
+
|
|
19
|
+
import jwt
|
|
20
|
+
from jwt import PyJWKClient
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class TokenVerificationError(Exception):
|
|
26
|
+
"""Raised when an IAL2 token fails signature or claims verification."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class _PinnedHTTPSConnection(http.client.HTTPSConnection):
|
|
30
|
+
"""An HTTPSConnection that dials a pre-resolved IP instead of
|
|
31
|
+
re-resolving its host via DNS, while still using that original host for
|
|
32
|
+
TLS SNI and certificate verification.
|
|
33
|
+
|
|
34
|
+
Used to close the DNS-rebinding TOCTOU window between validating a
|
|
35
|
+
hostname's resolved address and actually connecting to it: a plain
|
|
36
|
+
HTTPSConnection re-resolves the hostname at connect() time, so an
|
|
37
|
+
attacker controlling that hostname's DNS could serve a different
|
|
38
|
+
(internal) address than the one that was validated moments earlier.
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
# Declared here for mypy: real attributes set by HTTPSConnection.__init__
|
|
42
|
+
# (typeshed doesn't expose them, since they're conventionally private).
|
|
43
|
+
_context: ssl.SSLContext
|
|
44
|
+
source_address: tuple[str, int] | None
|
|
45
|
+
|
|
46
|
+
def __init__(self, host: str, pinned_ip: str, **kwargs: Any) -> None:
|
|
47
|
+
super().__init__(host, **kwargs)
|
|
48
|
+
self._pinned_ip = pinned_ip
|
|
49
|
+
|
|
50
|
+
def connect(self) -> None:
|
|
51
|
+
sock = socket.create_connection(
|
|
52
|
+
(self._pinned_ip, self.port), self.timeout, self.source_address
|
|
53
|
+
)
|
|
54
|
+
self.sock = self._context.wrap_socket(sock, server_hostname=self.host)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _fetch_json_pinned(
|
|
58
|
+
url: str, pinned_ip: str, *, timeout: float = 10.0
|
|
59
|
+
) -> dict[str, Any]:
|
|
60
|
+
"""Fetch and parse JSON from `url`, connecting to `pinned_ip` rather
|
|
61
|
+
than letting the request re-resolve the URL's hostname via DNS."""
|
|
62
|
+
parsed = urlparse(url)
|
|
63
|
+
conn = _PinnedHTTPSConnection(
|
|
64
|
+
parsed.hostname or "", pinned_ip, port=parsed.port, timeout=timeout
|
|
65
|
+
)
|
|
66
|
+
try:
|
|
67
|
+
conn.request("GET", parsed.path or "/", headers={"Accept": "application/json"})
|
|
68
|
+
response = conn.getresponse()
|
|
69
|
+
body = response.read()
|
|
70
|
+
finally:
|
|
71
|
+
conn.close()
|
|
72
|
+
result: dict[str, Any] = json.loads(body)
|
|
73
|
+
return result
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class TokenVerifier:
|
|
77
|
+
"""Verifies IAL2 JWT tokens against a CSP's JWKS endpoint.
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
jwks_uri: URL of the JWKS endpoint (e.g.
|
|
81
|
+
``https://idp.example.com/.well-known/jwks.json``).
|
|
82
|
+
audience: Expected ``aud`` claim value.
|
|
83
|
+
issuer: Expected ``iss`` claim value. If provided, the token's
|
|
84
|
+
issuer must match exactly.
|
|
85
|
+
algorithms: Allowed signing algorithms. Defaults to RS256.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
def __init__(
|
|
89
|
+
self,
|
|
90
|
+
*,
|
|
91
|
+
jwks_uri: str,
|
|
92
|
+
audience: str,
|
|
93
|
+
issuer: str | None = None,
|
|
94
|
+
algorithms: list[str] | None = None,
|
|
95
|
+
) -> None:
|
|
96
|
+
self._jwks_uri = jwks_uri
|
|
97
|
+
self._audience = audience
|
|
98
|
+
self._issuer = issuer
|
|
99
|
+
self._algorithms = algorithms or ["RS256"]
|
|
100
|
+
self._jwks_client = PyJWKClient(jwks_uri)
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def jwks_uri(self) -> str:
|
|
104
|
+
"""The JWKS endpoint this verifier fetches signing keys from."""
|
|
105
|
+
return self._jwks_uri
|
|
106
|
+
|
|
107
|
+
async def verify(self, token: str) -> dict[str, Any]:
|
|
108
|
+
"""Verify the token signature and standard claims.
|
|
109
|
+
|
|
110
|
+
Args:
|
|
111
|
+
token: The encoded JWT string.
|
|
112
|
+
|
|
113
|
+
Returns:
|
|
114
|
+
The decoded claims dictionary.
|
|
115
|
+
|
|
116
|
+
Raises:
|
|
117
|
+
TokenVerificationError: If the token is invalid, expired,
|
|
118
|
+
or fails audience/issuer checks.
|
|
119
|
+
"""
|
|
120
|
+
return await asyncio.to_thread(self._verify_sync, token)
|
|
121
|
+
|
|
122
|
+
def _verify_sync(self, token: str) -> dict[str, Any]:
|
|
123
|
+
"""Blocking body of verify() -- PyJWT/PyJWKClient have no async API,
|
|
124
|
+
so verify() offloads this to a thread instead of blocking the event
|
|
125
|
+
loop for the JWKS fetch (network I/O) this does internally."""
|
|
126
|
+
try:
|
|
127
|
+
signing_key = self._jwks_client.get_signing_key_from_jwt(token)
|
|
128
|
+
|
|
129
|
+
decoded: dict[str, Any] = jwt.decode(
|
|
130
|
+
token,
|
|
131
|
+
signing_key.key,
|
|
132
|
+
algorithms=self._algorithms,
|
|
133
|
+
audience=self._audience,
|
|
134
|
+
issuer=self._issuer,
|
|
135
|
+
options={
|
|
136
|
+
"require": ["exp", "iat", "iss", "sub", "aud", "jti"],
|
|
137
|
+
},
|
|
138
|
+
)
|
|
139
|
+
return decoded
|
|
140
|
+
|
|
141
|
+
except jwt.ExpiredSignatureError as e:
|
|
142
|
+
raise TokenVerificationError(f"Token has expired: {e}") from e
|
|
143
|
+
except jwt.InvalidAudienceError as e:
|
|
144
|
+
raise TokenVerificationError(f"Invalid audience: {e}") from e
|
|
145
|
+
except jwt.InvalidIssuerError as e:
|
|
146
|
+
raise TokenVerificationError(f"Invalid issuer: {e}") from e
|
|
147
|
+
except jwt.PyJWKClientError as e:
|
|
148
|
+
raise TokenVerificationError(
|
|
149
|
+
f"Failed to fetch signing key from JWKS: {e}"
|
|
150
|
+
) from e
|
|
151
|
+
except jwt.InvalidTokenError as e:
|
|
152
|
+
raise TokenVerificationError(f"Token verification failed: {e}") from e
|
|
153
|
+
|
|
154
|
+
@classmethod
|
|
155
|
+
async def from_oidc_discovery(
|
|
156
|
+
cls,
|
|
157
|
+
*,
|
|
158
|
+
discovery_url: str,
|
|
159
|
+
audience: str,
|
|
160
|
+
issuer: str | None = None,
|
|
161
|
+
algorithms: list[str] | None = None,
|
|
162
|
+
pinned_ip: str | None = None,
|
|
163
|
+
) -> TokenVerifier:
|
|
164
|
+
"""Create a verifier by fetching the JWKS URI from OIDC discovery.
|
|
165
|
+
|
|
166
|
+
Args:
|
|
167
|
+
discovery_url: The ``/.well-known/openid-configuration`` URL.
|
|
168
|
+
audience: Expected ``aud`` claim value.
|
|
169
|
+
issuer: Expected ``iss`` claim value.
|
|
170
|
+
algorithms: Allowed signing algorithms.
|
|
171
|
+
pinned_ip: If given, connect to this IP instead of letting the
|
|
172
|
+
discovery fetch resolve discovery_url's host via DNS. Used
|
|
173
|
+
by callers (e.g. MultiIssuerTokenVerifier) that have already
|
|
174
|
+
validated an untrusted host's resolved address and need the
|
|
175
|
+
actual connection pinned to it, closing the window between
|
|
176
|
+
that validation and the request.
|
|
177
|
+
|
|
178
|
+
Returns:
|
|
179
|
+
A configured TokenVerifier instance.
|
|
180
|
+
|
|
181
|
+
Raises:
|
|
182
|
+
TokenVerificationError: If discovery metadata cannot be fetched.
|
|
183
|
+
"""
|
|
184
|
+
|
|
185
|
+
def _fetch_metadata() -> dict[str, Any]:
|
|
186
|
+
if pinned_ip:
|
|
187
|
+
return _fetch_json_pinned(discovery_url, pinned_ip)
|
|
188
|
+
with urlopen(discovery_url) as response: # nosec B310
|
|
189
|
+
result: dict[str, Any] = json.loads(response.read())
|
|
190
|
+
return result
|
|
191
|
+
|
|
192
|
+
try:
|
|
193
|
+
metadata = await asyncio.to_thread(_fetch_metadata)
|
|
194
|
+
jwks_uri = metadata["jwks_uri"]
|
|
195
|
+
except Exception as e:
|
|
196
|
+
raise TokenVerificationError(
|
|
197
|
+
f"Failed to fetch OIDC discovery metadata from {discovery_url}: {e}"
|
|
198
|
+
) from e
|
|
199
|
+
|
|
200
|
+
return cls(
|
|
201
|
+
jwks_uri=jwks_uri,
|
|
202
|
+
audience=audience,
|
|
203
|
+
issuer=issuer or metadata.get("issuer"),
|
|
204
|
+
algorithms=algorithms,
|
|
205
|
+
)
|