ais-identity-fastapi 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.
- ais_identity_fastapi-0.1.0/LICENSE +204 -0
- ais_identity_fastapi-0.1.0/NOTICE +4 -0
- ais_identity_fastapi-0.1.0/PKG-INFO +142 -0
- ais_identity_fastapi-0.1.0/README.md +116 -0
- ais_identity_fastapi-0.1.0/pyproject.toml +51 -0
- ais_identity_fastapi-0.1.0/src/ais_identity_fastapi/__init__.py +27 -0
- ais_identity_fastapi-0.1.0/src/ais_identity_fastapi/compat.py +69 -0
- ais_identity_fastapi-0.1.0/src/ais_identity_fastapi/headers.py +148 -0
- ais_identity_fastapi-0.1.0/src/ais_identity_fastapi/identity.py +275 -0
- ais_identity_fastapi-0.1.0/src/ais_identity_fastapi/py.typed +0 -0
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
Copyright (c) 2026 Alpin Insight Solutions GmbH & Co. KG
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
Apache License
|
|
5
|
+
Version 2.0, January 2004
|
|
6
|
+
http://www.apache.org/licenses/
|
|
7
|
+
|
|
8
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
9
|
+
|
|
10
|
+
1. Definitions.
|
|
11
|
+
|
|
12
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
13
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
14
|
+
|
|
15
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
16
|
+
the copyright owner that is granting the License.
|
|
17
|
+
|
|
18
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
19
|
+
other entities that control, are controlled by, or are under common
|
|
20
|
+
control with that entity. For the purposes of this definition,
|
|
21
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
22
|
+
direction or management of such entity, whether by contract or
|
|
23
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
24
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
25
|
+
|
|
26
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
27
|
+
exercising permissions granted by this License.
|
|
28
|
+
|
|
29
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
30
|
+
including but not limited to software source code, documentation
|
|
31
|
+
source, and configuration files.
|
|
32
|
+
|
|
33
|
+
"Object" form shall mean any form resulting from mechanical
|
|
34
|
+
transformation or translation of a Source form, including but
|
|
35
|
+
not limited to compiled object code, generated documentation,
|
|
36
|
+
and conversions to other media types.
|
|
37
|
+
|
|
38
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
39
|
+
Object form, made available under the License, as indicated by a
|
|
40
|
+
copyright notice that is included in or attached to the work
|
|
41
|
+
(an example is provided in the Appendix below).
|
|
42
|
+
|
|
43
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
44
|
+
form, that is based on (or derived from) the Work and for which the
|
|
45
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
46
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
47
|
+
of this License, Derivative Works shall not include works that remain
|
|
48
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
49
|
+
the Work and Derivative Works thereof.
|
|
50
|
+
|
|
51
|
+
"Contribution" shall mean any work of authorship, including
|
|
52
|
+
the original version of the Work and any modifications or additions
|
|
53
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
54
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
55
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
56
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
57
|
+
means any form of electronic, verbal, or written communication sent
|
|
58
|
+
to the Licensor or its representatives, including but not limited to
|
|
59
|
+
communication on electronic mailing lists, source code control systems,
|
|
60
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
61
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
62
|
+
excluding communication that is conspicuously marked or otherwise
|
|
63
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
64
|
+
|
|
65
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
66
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
67
|
+
subsequently incorporated within the Work.
|
|
68
|
+
|
|
69
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
70
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
71
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
72
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
73
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
74
|
+
Work and such Derivative Works in Source or Object form.
|
|
75
|
+
|
|
76
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
77
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
78
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
79
|
+
(except as stated in this section) patent license to make, have made,
|
|
80
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
81
|
+
where such license applies only to those patent claims licensable
|
|
82
|
+
by such Contributor that are necessarily infringed by their
|
|
83
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
84
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
85
|
+
institute patent litigation against any entity (including a
|
|
86
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
87
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
88
|
+
or contributory patent infringement, then any patent licenses
|
|
89
|
+
granted to You under this License for that Work shall terminate
|
|
90
|
+
as of the date such litigation is filed.
|
|
91
|
+
|
|
92
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
93
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
94
|
+
modifications, and in Source or Object form, provided that You
|
|
95
|
+
meet the following conditions:
|
|
96
|
+
|
|
97
|
+
(a) You must give any other recipients of the Work or
|
|
98
|
+
Derivative Works a copy of this License; and
|
|
99
|
+
|
|
100
|
+
(b) You must cause any modified files to carry prominent notices
|
|
101
|
+
stating that You changed the files; and
|
|
102
|
+
|
|
103
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
104
|
+
that You distribute, all copyright, patent, trademark, and
|
|
105
|
+
attribution notices from the Source form of the Work,
|
|
106
|
+
excluding those notices that do not pertain to any part of
|
|
107
|
+
the Derivative Works; and
|
|
108
|
+
|
|
109
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
110
|
+
distribution, then any Derivative Works that You distribute must
|
|
111
|
+
include a readable copy of the attribution notices contained
|
|
112
|
+
within such NOTICE file, excluding those notices that do not
|
|
113
|
+
pertain to any part of the Derivative Works, in at least one
|
|
114
|
+
of the following places: within a NOTICE text file distributed
|
|
115
|
+
as part of the Derivative Works; within the Source form or
|
|
116
|
+
documentation, if provided along with the Derivative Works; or,
|
|
117
|
+
within a display generated by the Derivative Works, if and
|
|
118
|
+
wherever such third-party notices normally appear. The contents
|
|
119
|
+
of the NOTICE file are for informational purposes only and
|
|
120
|
+
do not modify the License. You may add Your own attribution
|
|
121
|
+
notices within Derivative Works that You distribute, alongside
|
|
122
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
123
|
+
that such additional attribution notices cannot be construed
|
|
124
|
+
as modifying the License.
|
|
125
|
+
|
|
126
|
+
You may add Your own copyright statement to Your modifications and
|
|
127
|
+
may provide additional or different license terms and conditions
|
|
128
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
129
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
130
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
131
|
+
the conditions stated in this License.
|
|
132
|
+
|
|
133
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
134
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
135
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
136
|
+
this License, without any additional terms or conditions.
|
|
137
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
138
|
+
the terms of any separate license agreement you may have executed
|
|
139
|
+
with Licensor regarding such Contributions.
|
|
140
|
+
|
|
141
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
142
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
143
|
+
except as required for reasonable and customary use in describing the
|
|
144
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
145
|
+
|
|
146
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
147
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
148
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
149
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
150
|
+
implied, including, without limitation, any warranties or conditions
|
|
151
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
152
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
153
|
+
appropriateness of using or redistributing the Work and assume any
|
|
154
|
+
risks associated with Your exercise of permissions under this License.
|
|
155
|
+
|
|
156
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
157
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
158
|
+
unless required by applicable law (such as deliberate and grossly
|
|
159
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
160
|
+
liable to You for damages, including any direct, indirect, special,
|
|
161
|
+
incidental, or consequential damages of any character arising as a
|
|
162
|
+
result of this License or out of the use or inability to use the
|
|
163
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
164
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
165
|
+
other commercial damages or losses), even if such Contributor
|
|
166
|
+
has been advised of the possibility of such damages.
|
|
167
|
+
|
|
168
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
169
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
170
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
171
|
+
or other liability obligations and/or rights consistent with this
|
|
172
|
+
License. However, in accepting such obligations, You may act only
|
|
173
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
174
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
175
|
+
defend, and hold each Contributor harmless for any liability
|
|
176
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
177
|
+
of your accepting any such warranty or additional liability.
|
|
178
|
+
|
|
179
|
+
END OF TERMS AND CONDITIONS
|
|
180
|
+
|
|
181
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
182
|
+
|
|
183
|
+
To apply the Apache License to your work, attach the following
|
|
184
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
185
|
+
replaced with your own identifying information. (Don't include
|
|
186
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
187
|
+
comment syntax for the file format. We also recommend that a
|
|
188
|
+
file or class name and description of purpose be included on the
|
|
189
|
+
same "printed page" as the copyright notice for easier
|
|
190
|
+
identification within third-party archives.
|
|
191
|
+
|
|
192
|
+
Copyright [yyyy] [name of copyright owner]
|
|
193
|
+
|
|
194
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
195
|
+
you may not use this file except in compliance with the License.
|
|
196
|
+
You may obtain a copy of the License at
|
|
197
|
+
|
|
198
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
199
|
+
|
|
200
|
+
Unless required by applicable law or agreed to in writing, software
|
|
201
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
202
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
203
|
+
See the License for the specific language governing permissions and
|
|
204
|
+
limitations under the License.
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: ais-identity-fastapi
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: FastAPI dependencies for Alpin Insight Identity Control Plane (ICp): bearer verification and access requirements over the ais-identity core.
|
|
5
|
+
Project-URL: Homepage, https://github.com/alpininsight/insight-identity-sdk
|
|
6
|
+
Project-URL: Documentation, https://github.com/alpininsight/insight-identity-sdk/tree/develop/packages/ais-identity-fastapi#readme
|
|
7
|
+
Project-URL: Issues, https://github.com/alpininsight/insight-identity-sdk/issues
|
|
8
|
+
Author: Alpin Insight Solutions GmbH & Co. KG
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
License-File: NOTICE
|
|
12
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
13
|
+
Classifier: Framework :: FastAPI
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Topic :: Security
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.12
|
|
23
|
+
Requires-Dist: ais-identity==0.1.0
|
|
24
|
+
Requires-Dist: fastapi<1,>=0.115
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# ais-identity-fastapi
|
|
28
|
+
|
|
29
|
+
Part of the Python SDK for **Alpin Insight Identity Control Plane (ICp)**.
|
|
30
|
+
|
|
31
|
+
FastAPI dependencies over the `ais-identity` core: bearer-token verification
|
|
32
|
+
and access requirements for resource servers and MCP backends.
|
|
33
|
+
|
|
34
|
+
Pre-release: not yet published to PyPI. See the
|
|
35
|
+
[repository README](https://github.com/alpininsight/insight-identity-sdk#readme).
|
|
36
|
+
|
|
37
|
+
## Usage
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
from typing import Annotated
|
|
41
|
+
|
|
42
|
+
from ais_identity import AccessContext
|
|
43
|
+
from ais_identity_fastapi import Identity
|
|
44
|
+
from fastapi import Depends, FastAPI
|
|
45
|
+
|
|
46
|
+
identity = Identity.from_issuer(
|
|
47
|
+
"https://id.example.com",
|
|
48
|
+
expected_audience="https://api.alpininsight.ai/api/v1/sources",
|
|
49
|
+
)
|
|
50
|
+
app = FastAPI()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@app.get("/reports")
|
|
54
|
+
def reports(
|
|
55
|
+
caller: Annotated[AccessContext, Depends(identity.require_access(any_scopes=["sources:read"]))],
|
|
56
|
+
): ...
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
`expected_audience` is the API's canonical resource URI: gateway host plus the
|
|
60
|
+
group's catalog `base_path`, compared exactly. Sources is
|
|
61
|
+
`https://api.alpininsight.ai/api/v1/sources` (development
|
|
62
|
+
`https://api.dev.alpininsight.ai/api/v1/sources`). Digitraffic marine is
|
|
63
|
+
`https://api.alpininsight.ai/api/v1/digitraffic/marine`. Sources and
|
|
64
|
+
source-control share that sources audience and are distinguished by scope.
|
|
65
|
+
The verifier accepts one string or a one-entry array and requires `client_id`.
|
|
66
|
+
Multiple audience entries are rejected, including duplicates.
|
|
67
|
+
|
|
68
|
+
Today, on provider `develop` (`de7c7c9`), every service-API token has `aud`
|
|
69
|
+
equal to `client_id`. `resource` binds only MCP scopes. The canonical URI as
|
|
70
|
+
`aud` is
|
|
71
|
+
[insight-oidc-provider#821](https://github.com/alpininsight/insight-oidc-provider/pull/821)
|
|
72
|
+
(still open, `f856b25`) and is not today's behavior. Configuring
|
|
73
|
+
`expected_audience` without `legacy_client_audiences` rejects every real
|
|
74
|
+
token today.
|
|
75
|
+
|
|
76
|
+
Pass `legacy_client_audiences` for those client ids
|
|
77
|
+
([insight-oidc-provider#819](https://github.com/alpininsight/insight-oidc-provider/issues/819)).
|
|
78
|
+
A match also requires `sub == client_id` and `principal_type` `service-client`
|
|
79
|
+
([`MACHINE_PRINCIPAL_TYPE`](https://github.com/alpininsight/insight-oidc-provider/blob/de7c7c9f112dbe9ad648b8132e6da731179608d9/src/oidc_core/access_tokens.py#L59),
|
|
80
|
+
only on
|
|
81
|
+
[`client_credentials`](https://github.com/alpininsight/insight-oidc-provider/blob/de7c7c9f112dbe9ad648b8132e6da731179608d9/src/oidc_core/access_tokens.py#L229-L242)).
|
|
82
|
+
A missing claim is never a service client. `workload` from the SPIRE token
|
|
83
|
+
exchange, off by default
|
|
84
|
+
([`spire_federation.py` L251-L257](https://github.com/alpininsight/insight-oidc-provider/blob/de7c7c9f112dbe9ad648b8132e6da731179608d9/src/oidc_core/spire_federation.py#L251-L257)),
|
|
85
|
+
is rejected on purpose even when `aud` equals `client_id`. A non-empty list
|
|
86
|
+
emits `PendingDeprecationWarning`, because every resource server needs the
|
|
87
|
+
list today. After #821 is deployed that warning becomes `DeprecationWarning`.
|
|
88
|
+
Empty the list only then. The parameter stays, so dropping the fallback later
|
|
89
|
+
is not a breaking change. There is no slug audience.
|
|
90
|
+
`audience=` is deprecated and cannot be combined with `expected_audience`.
|
|
91
|
+
|
|
92
|
+
`require_access` verifies the bearer token, then decides with the core:
|
|
93
|
+
|
|
94
|
+
| Outcome | Response |
|
|
95
|
+
|---|---|
|
|
96
|
+
| no credentials | 401, `WWW-Authenticate: Bearer` |
|
|
97
|
+
| invalid token | 401, `Bearer error="invalid_token", error_description="<code>"` |
|
|
98
|
+
| missing scope | 403, `Bearer error="insufficient_scope"` |
|
|
99
|
+
| any other denial | 403 with the reason code |
|
|
100
|
+
| provider unreachable (JWKS) | 503 |
|
|
101
|
+
|
|
102
|
+
Scopes are read from every scope claim by default; a tenant is required unless
|
|
103
|
+
`require_tenant=False`. `node="path:unit"` with `node_action` asks the provider
|
|
104
|
+
about the organization unit named by a path parameter. `write=True` applies the
|
|
105
|
+
write rule. `Depends(identity.context)` returns the context without deciding.
|
|
106
|
+
|
|
107
|
+
Dependencies are synchronous on purpose: FastAPI runs them in its thread pool,
|
|
108
|
+
so a JWKS fetch never blocks the event loop.
|
|
109
|
+
|
|
110
|
+
## Gateway headers: opt-in, with a trust check
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
from ais_identity_fastapi import GatewayHeaders, Identity
|
|
114
|
+
|
|
115
|
+
identity = Identity(
|
|
116
|
+
verifier=...,
|
|
117
|
+
gateway_headers=GatewayHeaders(
|
|
118
|
+
trusted_peer_ids=[
|
|
119
|
+
"spiffe://cluster.local/ns/istio-system/sa/istio-ingressgateway-service-account"
|
|
120
|
+
],
|
|
121
|
+
),
|
|
122
|
+
)
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Headers are read only when the request comes from a configured gateway:
|
|
126
|
+
`trusted_networks` (TCP peer address) and/or `trusted_peer_ids` (SPIFFE ID from
|
|
127
|
+
the `x-forwarded-client-cert` header an Envoy sidecar sets under Istio mTLS).
|
|
128
|
+
Every configured check must pass. A bearer token always wins and never falls
|
|
129
|
+
back to headers. `GatewayHeaders()` without a trust check raises.
|
|
130
|
+
|
|
131
|
+
## Rollouts
|
|
132
|
+
|
|
133
|
+
`Enforcement.REPORT_ONLY` logs every denial as an `ais_identity.access_decision`
|
|
134
|
+
event and lets the request continue.
|
|
135
|
+
|
|
136
|
+
## Migrating from insight_service_runtime.authz
|
|
137
|
+
|
|
138
|
+
`ais_identity_fastapi.compat.require_access(identity, any_of_scopes=..., write=..., mode=...)`
|
|
139
|
+
keeps the legacy meaning: any-of scopes from every scope source, a tenant
|
|
140
|
+
required, `warn` as report-only, and write violations reported as denials.
|
|
141
|
+
`LEGACY_SERVICE_RUNTIME_HEADERS` lists the headers the runtime reads today. The
|
|
142
|
+
deliberate change: headers count only from a trusted gateway.
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# ais-identity-fastapi
|
|
2
|
+
|
|
3
|
+
Part of the Python SDK for **Alpin Insight Identity Control Plane (ICp)**.
|
|
4
|
+
|
|
5
|
+
FastAPI dependencies over the `ais-identity` core: bearer-token verification
|
|
6
|
+
and access requirements for resource servers and MCP backends.
|
|
7
|
+
|
|
8
|
+
Pre-release: not yet published to PyPI. See the
|
|
9
|
+
[repository README](https://github.com/alpininsight/insight-identity-sdk#readme).
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from typing import Annotated
|
|
15
|
+
|
|
16
|
+
from ais_identity import AccessContext
|
|
17
|
+
from ais_identity_fastapi import Identity
|
|
18
|
+
from fastapi import Depends, FastAPI
|
|
19
|
+
|
|
20
|
+
identity = Identity.from_issuer(
|
|
21
|
+
"https://id.example.com",
|
|
22
|
+
expected_audience="https://api.alpininsight.ai/api/v1/sources",
|
|
23
|
+
)
|
|
24
|
+
app = FastAPI()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@app.get("/reports")
|
|
28
|
+
def reports(
|
|
29
|
+
caller: Annotated[AccessContext, Depends(identity.require_access(any_scopes=["sources:read"]))],
|
|
30
|
+
): ...
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
`expected_audience` is the API's canonical resource URI: gateway host plus the
|
|
34
|
+
group's catalog `base_path`, compared exactly. Sources is
|
|
35
|
+
`https://api.alpininsight.ai/api/v1/sources` (development
|
|
36
|
+
`https://api.dev.alpininsight.ai/api/v1/sources`). Digitraffic marine is
|
|
37
|
+
`https://api.alpininsight.ai/api/v1/digitraffic/marine`. Sources and
|
|
38
|
+
source-control share that sources audience and are distinguished by scope.
|
|
39
|
+
The verifier accepts one string or a one-entry array and requires `client_id`.
|
|
40
|
+
Multiple audience entries are rejected, including duplicates.
|
|
41
|
+
|
|
42
|
+
Today, on provider `develop` (`de7c7c9`), every service-API token has `aud`
|
|
43
|
+
equal to `client_id`. `resource` binds only MCP scopes. The canonical URI as
|
|
44
|
+
`aud` is
|
|
45
|
+
[insight-oidc-provider#821](https://github.com/alpininsight/insight-oidc-provider/pull/821)
|
|
46
|
+
(still open, `f856b25`) and is not today's behavior. Configuring
|
|
47
|
+
`expected_audience` without `legacy_client_audiences` rejects every real
|
|
48
|
+
token today.
|
|
49
|
+
|
|
50
|
+
Pass `legacy_client_audiences` for those client ids
|
|
51
|
+
([insight-oidc-provider#819](https://github.com/alpininsight/insight-oidc-provider/issues/819)).
|
|
52
|
+
A match also requires `sub == client_id` and `principal_type` `service-client`
|
|
53
|
+
([`MACHINE_PRINCIPAL_TYPE`](https://github.com/alpininsight/insight-oidc-provider/blob/de7c7c9f112dbe9ad648b8132e6da731179608d9/src/oidc_core/access_tokens.py#L59),
|
|
54
|
+
only on
|
|
55
|
+
[`client_credentials`](https://github.com/alpininsight/insight-oidc-provider/blob/de7c7c9f112dbe9ad648b8132e6da731179608d9/src/oidc_core/access_tokens.py#L229-L242)).
|
|
56
|
+
A missing claim is never a service client. `workload` from the SPIRE token
|
|
57
|
+
exchange, off by default
|
|
58
|
+
([`spire_federation.py` L251-L257](https://github.com/alpininsight/insight-oidc-provider/blob/de7c7c9f112dbe9ad648b8132e6da731179608d9/src/oidc_core/spire_federation.py#L251-L257)),
|
|
59
|
+
is rejected on purpose even when `aud` equals `client_id`. A non-empty list
|
|
60
|
+
emits `PendingDeprecationWarning`, because every resource server needs the
|
|
61
|
+
list today. After #821 is deployed that warning becomes `DeprecationWarning`.
|
|
62
|
+
Empty the list only then. The parameter stays, so dropping the fallback later
|
|
63
|
+
is not a breaking change. There is no slug audience.
|
|
64
|
+
`audience=` is deprecated and cannot be combined with `expected_audience`.
|
|
65
|
+
|
|
66
|
+
`require_access` verifies the bearer token, then decides with the core:
|
|
67
|
+
|
|
68
|
+
| Outcome | Response |
|
|
69
|
+
|---|---|
|
|
70
|
+
| no credentials | 401, `WWW-Authenticate: Bearer` |
|
|
71
|
+
| invalid token | 401, `Bearer error="invalid_token", error_description="<code>"` |
|
|
72
|
+
| missing scope | 403, `Bearer error="insufficient_scope"` |
|
|
73
|
+
| any other denial | 403 with the reason code |
|
|
74
|
+
| provider unreachable (JWKS) | 503 |
|
|
75
|
+
|
|
76
|
+
Scopes are read from every scope claim by default; a tenant is required unless
|
|
77
|
+
`require_tenant=False`. `node="path:unit"` with `node_action` asks the provider
|
|
78
|
+
about the organization unit named by a path parameter. `write=True` applies the
|
|
79
|
+
write rule. `Depends(identity.context)` returns the context without deciding.
|
|
80
|
+
|
|
81
|
+
Dependencies are synchronous on purpose: FastAPI runs them in its thread pool,
|
|
82
|
+
so a JWKS fetch never blocks the event loop.
|
|
83
|
+
|
|
84
|
+
## Gateway headers: opt-in, with a trust check
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
from ais_identity_fastapi import GatewayHeaders, Identity
|
|
88
|
+
|
|
89
|
+
identity = Identity(
|
|
90
|
+
verifier=...,
|
|
91
|
+
gateway_headers=GatewayHeaders(
|
|
92
|
+
trusted_peer_ids=[
|
|
93
|
+
"spiffe://cluster.local/ns/istio-system/sa/istio-ingressgateway-service-account"
|
|
94
|
+
],
|
|
95
|
+
),
|
|
96
|
+
)
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Headers are read only when the request comes from a configured gateway:
|
|
100
|
+
`trusted_networks` (TCP peer address) and/or `trusted_peer_ids` (SPIFFE ID from
|
|
101
|
+
the `x-forwarded-client-cert` header an Envoy sidecar sets under Istio mTLS).
|
|
102
|
+
Every configured check must pass. A bearer token always wins and never falls
|
|
103
|
+
back to headers. `GatewayHeaders()` without a trust check raises.
|
|
104
|
+
|
|
105
|
+
## Rollouts
|
|
106
|
+
|
|
107
|
+
`Enforcement.REPORT_ONLY` logs every denial as an `ais_identity.access_decision`
|
|
108
|
+
event and lets the request continue.
|
|
109
|
+
|
|
110
|
+
## Migrating from insight_service_runtime.authz
|
|
111
|
+
|
|
112
|
+
`ais_identity_fastapi.compat.require_access(identity, any_of_scopes=..., write=..., mode=...)`
|
|
113
|
+
keeps the legacy meaning: any-of scopes from every scope source, a tenant
|
|
114
|
+
required, `warn` as report-only, and write violations reported as denials.
|
|
115
|
+
`LEGACY_SERVICE_RUNTIME_HEADERS` lists the headers the runtime reads today. The
|
|
116
|
+
deliberate change: headers count only from a trusted gateway.
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27.0", "hatch-vcs>=0.5"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ais-identity-fastapi"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "FastAPI dependencies for Alpin Insight Identity Control Plane (ICp): bearer verification and access requirements over the ais-identity core."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.12"
|
|
11
|
+
# PEP 639: a short License-Expression on PyPI instead of the full text.
|
|
12
|
+
license = "Apache-2.0"
|
|
13
|
+
license-files = ["LICENSE", "NOTICE"]
|
|
14
|
+
authors = [
|
|
15
|
+
{ name = "Alpin Insight Solutions GmbH & Co. KG" },
|
|
16
|
+
]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Development Status :: 2 - Pre-Alpha",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"Operating System :: OS Independent",
|
|
21
|
+
"Programming Language :: Python :: 3",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"Programming Language :: Python :: 3.13",
|
|
24
|
+
"Programming Language :: Python :: 3.14",
|
|
25
|
+
"Topic :: Security",
|
|
26
|
+
"Typing :: Typed",
|
|
27
|
+
"Framework :: FastAPI",
|
|
28
|
+
]
|
|
29
|
+
dependencies = [
|
|
30
|
+
"ais-identity==0.1.0",
|
|
31
|
+
"fastapi>=0.115,<1",
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
[project.urls]
|
|
35
|
+
Homepage = "https://github.com/alpininsight/insight-identity-sdk"
|
|
36
|
+
Documentation = "https://github.com/alpininsight/insight-identity-sdk/tree/develop/packages/ais-identity-fastapi#readme"
|
|
37
|
+
Issues = "https://github.com/alpininsight/insight-identity-sdk/issues"
|
|
38
|
+
|
|
39
|
+
[tool.hatch.version]
|
|
40
|
+
source = "vcs"
|
|
41
|
+
|
|
42
|
+
[tool.hatch.version.raw-options]
|
|
43
|
+
# One repository version for all packages: tags live at the workspace root.
|
|
44
|
+
root = "../.."
|
|
45
|
+
fallback_version = "0.1.0.dev0"
|
|
46
|
+
|
|
47
|
+
[tool.hatch.build.targets.wheel]
|
|
48
|
+
packages = ["src/ais_identity_fastapi"]
|
|
49
|
+
|
|
50
|
+
[tool.hatch.build.targets.sdist]
|
|
51
|
+
include = ["/src", "/pyproject.toml", "/README.md", "/LICENSE", "/NOTICE"]
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""FastAPI dependencies for Alpin Insight Identity Control Plane (ICp).
|
|
2
|
+
|
|
3
|
+
``Identity.from_issuer(issuer, expected_audience=...)`` verifies bearer tokens.
|
|
4
|
+
``audience=`` is the deprecated overlap check.
|
|
5
|
+
``Depends(identity.require_access(any_scopes=[...]))`` decides with the
|
|
6
|
+
``ais-identity`` core. Gateway headers are accepted only through an explicit
|
|
7
|
+
:class:`GatewayHeaders` with a trust check.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
11
|
+
|
|
12
|
+
from ais_identity_fastapi.headers import LEGACY_SERVICE_RUNTIME_HEADERS, GatewayHeaders
|
|
13
|
+
from ais_identity_fastapi.identity import Enforcement, Identity, resolve_node
|
|
14
|
+
|
|
15
|
+
try:
|
|
16
|
+
__version__ = version("ais-identity-fastapi")
|
|
17
|
+
except PackageNotFoundError: # pragma: no cover - source checkout without an install
|
|
18
|
+
__version__ = "0.0.0"
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"LEGACY_SERVICE_RUNTIME_HEADERS",
|
|
22
|
+
"Enforcement",
|
|
23
|
+
"GatewayHeaders",
|
|
24
|
+
"Identity",
|
|
25
|
+
"__version__",
|
|
26
|
+
"resolve_node",
|
|
27
|
+
]
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Building blocks for the ``insight_service_runtime.authz`` compatibility layer.
|
|
2
|
+
|
|
3
|
+
``require_access(any_of_scopes=..., write=..., mode=...)`` keeps its meaning:
|
|
4
|
+
scopes are any-of from every scope source, a tenant is required, and in
|
|
5
|
+
``warn`` mode every violation is logged while the request continues. That
|
|
6
|
+
rollout behaviour is :attr:`Enforcement.REPORT_ONLY`; the write rule itself
|
|
7
|
+
must then enforce, so that its violations are reported as denials.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from collections.abc import Callable, Iterable
|
|
13
|
+
|
|
14
|
+
from starlette.requests import Request
|
|
15
|
+
|
|
16
|
+
from ais_identity.context import AccessContext
|
|
17
|
+
from ais_identity.write_policy import WriteMode, WritePolicy
|
|
18
|
+
from ais_identity_fastapi.identity import Enforcement, Identity
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def enforcement_from_mode(mode: str | None) -> Enforcement:
|
|
22
|
+
"""``SERVICE_AUTHZ_MODE`` semantics: only ``enforce`` enforces."""
|
|
23
|
+
|
|
24
|
+
return (
|
|
25
|
+
Enforcement.ENFORCE
|
|
26
|
+
if (mode or "").strip().lower() == "enforce"
|
|
27
|
+
else Enforcement.REPORT_ONLY
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def service_runtime_identity(identity: Identity) -> Identity:
|
|
32
|
+
"""The same identity with the write rule enforcing, as ``evaluate()`` reported it."""
|
|
33
|
+
|
|
34
|
+
return Identity(
|
|
35
|
+
verifier=identity.verifier,
|
|
36
|
+
gateway_headers=identity.gateway_headers,
|
|
37
|
+
write_policy=WritePolicy(mode=WriteMode.ENFORCE),
|
|
38
|
+
node_evaluator=identity.node_evaluator,
|
|
39
|
+
enforcement=identity.enforcement,
|
|
40
|
+
realm=identity.realm,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def require_access(
|
|
45
|
+
identity: Identity,
|
|
46
|
+
*,
|
|
47
|
+
any_of_scopes: Iterable[str] = (),
|
|
48
|
+
write: bool = False,
|
|
49
|
+
require_tenant: bool = True,
|
|
50
|
+
mode: str | None = None,
|
|
51
|
+
operation: str = "",
|
|
52
|
+
) -> Callable[[Request], AccessContext]:
|
|
53
|
+
"""``insight_service_runtime.authz.require_access`` over an :class:`Identity`.
|
|
54
|
+
|
|
55
|
+
The caller resolves ``mode`` (services reads ``SERVICE_AUTHZ_MODE``); the
|
|
56
|
+
SDK reads no environment.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
return service_runtime_identity(identity).require_access(
|
|
60
|
+
any_scopes=tuple(any_of_scopes),
|
|
61
|
+
scope_claim=None,
|
|
62
|
+
write=write,
|
|
63
|
+
require_tenant=require_tenant,
|
|
64
|
+
operation=operation,
|
|
65
|
+
enforcement=enforcement_from_mode(mode),
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
__all__ = ["enforcement_from_mode", "require_access", "service_runtime_identity"]
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""Gateway-projected identity headers, trusted only from a known gateway.
|
|
2
|
+
|
|
3
|
+
This mode exists for services behind a gateway that verified the token and
|
|
4
|
+
projects its facts as headers. It is an explicit opt-in: ``GatewayHeaders``
|
|
5
|
+
refuses to exist without a trust check, because a mesh-internal caller can set
|
|
6
|
+
any header it likes (insight-oidc-provider ADR 0001: Istio does not see
|
|
7
|
+
mesh-internal calls).
|
|
8
|
+
|
|
9
|
+
Two checks, and every configured one must pass:
|
|
10
|
+
|
|
11
|
+
- ``trusted_networks``: the TCP peer address is in one of these networks.
|
|
12
|
+
- ``trusted_peer_ids``: the SPIFFE ID of the immediate peer, read from the
|
|
13
|
+
``x-forwarded-client-cert`` header that an Envoy sidecar sets (and strips
|
|
14
|
+
from incoming requests) under Istio mTLS. Use it only behind such a sidecar.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import ipaddress
|
|
20
|
+
from collections.abc import Iterable
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from starlette.requests import Request
|
|
25
|
+
|
|
26
|
+
XFCC_HEADER = "x-forwarded-client-cert"
|
|
27
|
+
|
|
28
|
+
#: The headers insight_service_runtime.authz reads today, generic fallbacks included.
|
|
29
|
+
LEGACY_SERVICE_RUNTIME_HEADERS: dict[str, tuple[str, ...]] = {
|
|
30
|
+
"subject_headers": ("x-alpin-subject", "x-forwarded-user", "x-authenticated-user"),
|
|
31
|
+
"tenant_headers": ("x-alpin-tenant-id", "x-tenant-id", "x-forwarded-tenant"),
|
|
32
|
+
"scope_headers": ("x-alpin-scopes", "x-forwarded-scopes", "scope"),
|
|
33
|
+
"principal_headers": ("x-alpin-principal-type",),
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
# Gateway projections spell a human principal in several ways; the provider never does.
|
|
37
|
+
_HUMAN_SPELLINGS = frozenset({"", "human", "user"})
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _split_outside_quotes(text: str, separator: str) -> list[str]:
|
|
41
|
+
parts, current, quoted, escaped = [], [], False, False
|
|
42
|
+
for char in text:
|
|
43
|
+
if escaped:
|
|
44
|
+
current.append(char)
|
|
45
|
+
escaped = False
|
|
46
|
+
elif char == "\\":
|
|
47
|
+
current.append(char)
|
|
48
|
+
escaped = True
|
|
49
|
+
elif char == '"':
|
|
50
|
+
current.append(char)
|
|
51
|
+
quoted = not quoted
|
|
52
|
+
elif char == separator and not quoted:
|
|
53
|
+
parts.append("".join(current))
|
|
54
|
+
current = []
|
|
55
|
+
else:
|
|
56
|
+
current.append(char)
|
|
57
|
+
parts.append("".join(current))
|
|
58
|
+
return parts
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def xfcc_peer_ids(value: str) -> tuple[str, ...]:
|
|
62
|
+
"""SPIFFE IDs (``URI=``) of the nearest hop in an ``x-forwarded-client-cert`` value."""
|
|
63
|
+
|
|
64
|
+
elements = [element for element in _split_outside_quotes(value, ",") if element.strip()]
|
|
65
|
+
if not elements:
|
|
66
|
+
return ()
|
|
67
|
+
ids = []
|
|
68
|
+
for pair in _split_outside_quotes(elements[-1], ";"):
|
|
69
|
+
key, _, raw = pair.partition("=")
|
|
70
|
+
if key.strip().lower() == "uri":
|
|
71
|
+
ids.append(raw.strip().strip('"'))
|
|
72
|
+
return tuple(ids)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(frozen=True)
|
|
76
|
+
class GatewayHeaders:
|
|
77
|
+
trusted_networks: tuple[str, ...] = ()
|
|
78
|
+
trusted_peer_ids: tuple[str, ...] = ()
|
|
79
|
+
subject_headers: tuple[str, ...] = ("x-alpin-subject",)
|
|
80
|
+
tenant_headers: tuple[str, ...] = ("x-alpin-tenant-id",)
|
|
81
|
+
scope_headers: tuple[str, ...] = ("x-alpin-scopes",)
|
|
82
|
+
principal_headers: tuple[str, ...] = ("x-alpin-principal-type",)
|
|
83
|
+
_networks: tuple[Any, ...] = field(init=False, repr=False, compare=False, default=())
|
|
84
|
+
|
|
85
|
+
def __post_init__(self) -> None:
|
|
86
|
+
for name in ("trusted_networks", "trusted_peer_ids"):
|
|
87
|
+
value = getattr(self, name)
|
|
88
|
+
if isinstance(value, str):
|
|
89
|
+
raise TypeError(f"GatewayHeaders.{name} takes a list, not a string.")
|
|
90
|
+
object.__setattr__(self, name, tuple(item.strip() for item in value if item.strip()))
|
|
91
|
+
if not self.trusted_networks and not self.trusted_peer_ids:
|
|
92
|
+
raise ValueError(
|
|
93
|
+
"GatewayHeaders needs trusted_networks or trusted_peer_ids: "
|
|
94
|
+
"identity headers are trusted only from a known gateway."
|
|
95
|
+
)
|
|
96
|
+
networks = tuple(ipaddress.ip_network(item, strict=False) for item in self.trusted_networks)
|
|
97
|
+
object.__setattr__(self, "_networks", networks)
|
|
98
|
+
|
|
99
|
+
def trusted(self, request: Request) -> bool:
|
|
100
|
+
if self._networks:
|
|
101
|
+
try:
|
|
102
|
+
peer = ipaddress.ip_address(request.client.host if request.client else "")
|
|
103
|
+
except ValueError:
|
|
104
|
+
return False
|
|
105
|
+
if not any(peer in network for network in self._networks):
|
|
106
|
+
return False
|
|
107
|
+
if self.trusted_peer_ids:
|
|
108
|
+
peers = xfcc_peer_ids(request.headers.get(XFCC_HEADER, ""))
|
|
109
|
+
if not any(peer in self.trusted_peer_ids for peer in peers):
|
|
110
|
+
return False
|
|
111
|
+
return True
|
|
112
|
+
|
|
113
|
+
def present(self, request: Request) -> bool:
|
|
114
|
+
"""Whether the request carries any identity header at all."""
|
|
115
|
+
|
|
116
|
+
names = self.subject_headers + self.tenant_headers + self.scope_headers
|
|
117
|
+
return any(request.headers.get(name, "").strip() for name in names)
|
|
118
|
+
|
|
119
|
+
def claims(self, request: Request) -> dict[str, Any] | None:
|
|
120
|
+
"""Claims in contract shape, or ``None`` for an unknown principal type."""
|
|
121
|
+
|
|
122
|
+
def first(names: Iterable[str]) -> str:
|
|
123
|
+
for name in names:
|
|
124
|
+
value = request.headers.get(name, "").strip()
|
|
125
|
+
if value:
|
|
126
|
+
return value
|
|
127
|
+
return ""
|
|
128
|
+
|
|
129
|
+
scopes: set[str] = set()
|
|
130
|
+
for name in self.scope_headers:
|
|
131
|
+
scopes.update(part for part in request.headers.get(name, "").replace(",", " ").split())
|
|
132
|
+
|
|
133
|
+
principal = first(self.principal_headers).lower()
|
|
134
|
+
claims: dict[str, Any] = {
|
|
135
|
+
"sub": first(self.subject_headers),
|
|
136
|
+
"scope": " ".join(sorted(scopes)),
|
|
137
|
+
}
|
|
138
|
+
tenant = first(self.tenant_headers)
|
|
139
|
+
if tenant:
|
|
140
|
+
claims["tenant_id"] = tenant
|
|
141
|
+
if principal in ("service-client", "workload"):
|
|
142
|
+
claims["principal_type"] = principal
|
|
143
|
+
elif principal not in _HUMAN_SPELLINGS:
|
|
144
|
+
return None
|
|
145
|
+
return claims
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
__all__ = ["LEGACY_SERVICE_RUNTIME_HEADERS", "XFCC_HEADER", "GatewayHeaders", "xfcc_peer_ids"]
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
"""FastAPI dependencies: who is calling, and may they do this.
|
|
2
|
+
|
|
3
|
+
``Identity`` resolves the caller from a bearer token (verified by
|
|
4
|
+
:class:`ais_identity.TokenVerifier`) or, only when configured, from trusted
|
|
5
|
+
gateway headers. ``require_access`` returns a dependency that decides with
|
|
6
|
+
:func:`ais_identity.decide` and answers 401, 403 or 503.
|
|
7
|
+
|
|
8
|
+
Dependencies are synchronous on purpose: FastAPI runs them in its thread pool,
|
|
9
|
+
so a JWKS fetch never blocks the event loop.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import logging
|
|
15
|
+
from collections.abc import Callable, Iterable
|
|
16
|
+
from dataclasses import replace
|
|
17
|
+
from enum import StrEnum
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from fastapi import HTTPException
|
|
21
|
+
from starlette.requests import Request
|
|
22
|
+
|
|
23
|
+
from ais_identity.context import AccessContext
|
|
24
|
+
from ais_identity.discovery import Discovery
|
|
25
|
+
from ais_identity.errors import DiscoveryError, TokenVerificationError, UnknownPrincipalTypeError
|
|
26
|
+
from ais_identity.events import emit_decision_event
|
|
27
|
+
from ais_identity.nodes import NodeEvaluator
|
|
28
|
+
from ais_identity.requirements import Decision, DenyReason, Requirement, decide
|
|
29
|
+
from ais_identity.verification import TokenVerifier
|
|
30
|
+
from ais_identity.write_policy import WritePolicy
|
|
31
|
+
from ais_identity_fastapi.headers import GatewayHeaders
|
|
32
|
+
|
|
33
|
+
logger = logging.getLogger("ais_identity_fastapi")
|
|
34
|
+
|
|
35
|
+
BEARER_SOURCE = "bearer"
|
|
36
|
+
GATEWAY_HEADERS_SOURCE = "gateway_headers"
|
|
37
|
+
_NODE_CACHE_ATTR = "ais_identity_node_decisions"
|
|
38
|
+
|
|
39
|
+
NodeSpec = str | Callable[[Request], str | None] | None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Enforcement(StrEnum):
|
|
43
|
+
#: Denials answer 401/403.
|
|
44
|
+
ENFORCE = "enforce"
|
|
45
|
+
#: Denials are logged and the request continues, for rollouts.
|
|
46
|
+
REPORT_ONLY = "report-only"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def resolve_node(node: NodeSpec, request: Request) -> str | None:
|
|
50
|
+
"""An org-unit id or path, ``"path:<name>"`` for a path parameter, or a callable."""
|
|
51
|
+
|
|
52
|
+
if node is None:
|
|
53
|
+
return None
|
|
54
|
+
if callable(node):
|
|
55
|
+
value = node(request)
|
|
56
|
+
return str(value).strip() if value else None
|
|
57
|
+
text = str(node).strip()
|
|
58
|
+
if text.startswith("path:"):
|
|
59
|
+
value = request.path_params.get(text.removeprefix("path:"))
|
|
60
|
+
return str(value).strip() if value else None
|
|
61
|
+
return text or None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class Identity:
|
|
65
|
+
def __init__(
|
|
66
|
+
self,
|
|
67
|
+
*,
|
|
68
|
+
verifier: TokenVerifier | None = None,
|
|
69
|
+
gateway_headers: GatewayHeaders | None = None,
|
|
70
|
+
write_policy: WritePolicy | None = None,
|
|
71
|
+
node_evaluator: Any | None = None,
|
|
72
|
+
enforcement: Enforcement = Enforcement.ENFORCE,
|
|
73
|
+
realm: str | None = None,
|
|
74
|
+
) -> None:
|
|
75
|
+
"""``node_evaluator`` is a :class:`ais_identity.NodeEvaluationClient` or compatible."""
|
|
76
|
+
|
|
77
|
+
if verifier is None and gateway_headers is None:
|
|
78
|
+
raise ValueError("Identity needs a TokenVerifier, GatewayHeaders, or both.")
|
|
79
|
+
self.verifier = verifier
|
|
80
|
+
self.gateway_headers = gateway_headers
|
|
81
|
+
self.write_policy = write_policy or WritePolicy()
|
|
82
|
+
self.node_evaluator = node_evaluator
|
|
83
|
+
self.enforcement = enforcement
|
|
84
|
+
self.realm = realm
|
|
85
|
+
|
|
86
|
+
@classmethod
|
|
87
|
+
def from_issuer(
|
|
88
|
+
cls,
|
|
89
|
+
issuer: str,
|
|
90
|
+
*,
|
|
91
|
+
audience: str | Iterable[str] | None = None,
|
|
92
|
+
expected_audience: str | None = None,
|
|
93
|
+
legacy_client_audiences: Iterable[str] = (),
|
|
94
|
+
allowed_clients: Iterable[str] = (),
|
|
95
|
+
**kwargs: Any,
|
|
96
|
+
) -> Identity:
|
|
97
|
+
"""Verify bearer tokens for ``issuer``.
|
|
98
|
+
|
|
99
|
+
``audience`` is deprecated and accepts any overlap. ``expected_audience``
|
|
100
|
+
is one canonical https resource URI, compared exactly. ``aud`` must be
|
|
101
|
+
that string or a singleton array containing it, and ``client_id`` is
|
|
102
|
+
required. The verified claim shape is preserved. ``legacy_client_audiences``
|
|
103
|
+
are transitional client ids (insight-oidc-provider#819) and require
|
|
104
|
+
``expected_audience``, ``client_id`` equal to the sole audience and ``sub``, and
|
|
105
|
+
``principal_type`` ``service-client`` (``MACHINE_PRINCIPAL_TYPE``,
|
|
106
|
+
only on ``client_credentials``:
|
|
107
|
+
https://github.com/alpininsight/insight-oidc-provider/blob/de7c7c9f112dbe9ad648b8132e6da731179608d9/src/oidc_core/access_tokens.py#L59
|
|
108
|
+
and
|
|
109
|
+
https://github.com/alpininsight/insight-oidc-provider/blob/de7c7c9f112dbe9ad648b8132e6da731179608d9/src/oidc_core/access_tokens.py#L229-L242).
|
|
110
|
+
A missing claim is never a service client. ``workload`` from the SPIRE
|
|
111
|
+
token exchange is rejected on purpose
|
|
112
|
+
(https://github.com/alpininsight/insight-oidc-provider/blob/de7c7c9f112dbe9ad648b8132e6da731179608d9/src/oidc_core/spire_federation.py#L251-L257).
|
|
113
|
+
A non-empty list emits
|
|
114
|
+
``PendingDeprecationWarning``. On provider ``develop`` (``de7c7c9``)
|
|
115
|
+
every service-API token has ``aud`` equal to ``client_id``, so omitting
|
|
116
|
+
the list rejects every real token. The canonical URI as ``aud`` is
|
|
117
|
+
insight-oidc-provider#821 (still open). Empty the list only after that
|
|
118
|
+
deploy, when the warning becomes ``DeprecationWarning``.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
return cls(
|
|
122
|
+
verifier=TokenVerifier(
|
|
123
|
+
Discovery(issuer),
|
|
124
|
+
audience=audience,
|
|
125
|
+
expected_audience=expected_audience,
|
|
126
|
+
legacy_client_audiences=legacy_client_audiences,
|
|
127
|
+
allowed_clients=allowed_clients,
|
|
128
|
+
),
|
|
129
|
+
**kwargs,
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
def resolve(self, request: Request) -> tuple[AccessContext, str | None]:
|
|
133
|
+
"""The caller's context and, when it is anonymous, why."""
|
|
134
|
+
|
|
135
|
+
anonymous = AccessContext.anonymous()
|
|
136
|
+
scheme, _, credentials = request.headers.get("authorization", "").partition(" ")
|
|
137
|
+
if scheme:
|
|
138
|
+
if scheme.lower() != "bearer" or not credentials.strip():
|
|
139
|
+
return anonymous, "authorization_unsupported"
|
|
140
|
+
if self.verifier is None:
|
|
141
|
+
return anonymous, "bearer_not_accepted"
|
|
142
|
+
try:
|
|
143
|
+
claims = self.verifier.verify(credentials.strip())
|
|
144
|
+
return AccessContext.from_claims(claims, source=BEARER_SOURCE), None
|
|
145
|
+
except TokenVerificationError as exc:
|
|
146
|
+
return anonymous, exc.code
|
|
147
|
+
except DiscoveryError:
|
|
148
|
+
return anonymous, "discovery_unavailable"
|
|
149
|
+
except UnknownPrincipalTypeError:
|
|
150
|
+
return anonymous, "principal_type_unknown"
|
|
151
|
+
|
|
152
|
+
headers = self.gateway_headers
|
|
153
|
+
if headers is not None and headers.present(request):
|
|
154
|
+
if not headers.trusted(request):
|
|
155
|
+
return anonymous, "gateway_untrusted"
|
|
156
|
+
claims = headers.claims(request)
|
|
157
|
+
if claims is None:
|
|
158
|
+
return anonymous, "principal_type_unknown"
|
|
159
|
+
return AccessContext.from_claims(claims, source=GATEWAY_HEADERS_SOURCE), None
|
|
160
|
+
return anonymous, "credentials_missing"
|
|
161
|
+
|
|
162
|
+
def context(self, request: Request) -> AccessContext:
|
|
163
|
+
"""Dependency for handlers that check access themselves; never raises."""
|
|
164
|
+
|
|
165
|
+
return self.resolve(request)[0]
|
|
166
|
+
|
|
167
|
+
def _evaluator_for(self, request: Request) -> NodeEvaluator | None:
|
|
168
|
+
client = self.node_evaluator
|
|
169
|
+
if client is None:
|
|
170
|
+
return None
|
|
171
|
+
caches = getattr(request.state, _NODE_CACHE_ATTR, None)
|
|
172
|
+
if not isinstance(caches, dict):
|
|
173
|
+
caches = {}
|
|
174
|
+
setattr(request.state, _NODE_CACHE_ATTR, caches)
|
|
175
|
+
# A decision belongs to this Identity and evaluator, not every dependency on the request.
|
|
176
|
+
entry = caches.get(self)
|
|
177
|
+
if entry is None or entry[0] is not client:
|
|
178
|
+
entry = (client, {})
|
|
179
|
+
caches[self] = entry
|
|
180
|
+
cache = entry[1]
|
|
181
|
+
return lambda query: client.evaluate(query, cache=cache)
|
|
182
|
+
|
|
183
|
+
def require_access(
|
|
184
|
+
self,
|
|
185
|
+
*,
|
|
186
|
+
all_scopes: Iterable[str] = (),
|
|
187
|
+
any_scopes: Iterable[str] = (),
|
|
188
|
+
global_roles: Iterable[str] = (),
|
|
189
|
+
tenant_roles: Iterable[str] = (),
|
|
190
|
+
capabilities: Iterable[str] = (),
|
|
191
|
+
scope_claim: str | None = None,
|
|
192
|
+
capability_claim: str = "gateway_roles",
|
|
193
|
+
node: NodeSpec = None,
|
|
194
|
+
node_action: str | None = None,
|
|
195
|
+
resource_type: str = "view",
|
|
196
|
+
write: bool = False,
|
|
197
|
+
require_tenant: bool = True,
|
|
198
|
+
operation: str = "",
|
|
199
|
+
enforcement: Enforcement | None = None,
|
|
200
|
+
) -> Callable[[Request], AccessContext]:
|
|
201
|
+
"""A dependency: ``Depends(identity.require_access(any_scopes=["sources:read"]))``.
|
|
202
|
+
|
|
203
|
+
Scopes are read from every scope claim by default (``scope_claim=None``),
|
|
204
|
+
as a resource server receives them; pass a claim name to narrow it.
|
|
205
|
+
"""
|
|
206
|
+
|
|
207
|
+
base = Requirement(
|
|
208
|
+
global_roles=tuple(global_roles),
|
|
209
|
+
tenant_roles=tuple(tenant_roles),
|
|
210
|
+
all_scopes=tuple(all_scopes),
|
|
211
|
+
any_scopes=tuple(any_scopes),
|
|
212
|
+
capabilities=tuple(capabilities),
|
|
213
|
+
scope_claim=scope_claim,
|
|
214
|
+
capability_claim=capability_claim,
|
|
215
|
+
node_action=node_action,
|
|
216
|
+
resource_type=resource_type,
|
|
217
|
+
write=write,
|
|
218
|
+
require_tenant=require_tenant,
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
def dependency(request: Request) -> AccessContext:
|
|
222
|
+
context, failure = self.resolve(request)
|
|
223
|
+
requirement = (
|
|
224
|
+
base if node is None else replace(base, node=resolve_node(node, request) or "")
|
|
225
|
+
)
|
|
226
|
+
decision = decide(
|
|
227
|
+
context,
|
|
228
|
+
requirement,
|
|
229
|
+
node_evaluator=self._evaluator_for(request) if requirement.node else None,
|
|
230
|
+
write_policy=self.write_policy,
|
|
231
|
+
)
|
|
232
|
+
emit_decision_event(
|
|
233
|
+
decision,
|
|
234
|
+
context,
|
|
235
|
+
requirement,
|
|
236
|
+
operation=operation or f"{request.method} {request.url.path}",
|
|
237
|
+
)
|
|
238
|
+
if failure and failure != "credentials_missing":
|
|
239
|
+
logger.warning("caller credentials rejected (%s)", failure)
|
|
240
|
+
if decision.allowed or (enforcement or self.enforcement) is Enforcement.REPORT_ONLY:
|
|
241
|
+
return context
|
|
242
|
+
raise self._error(decision, failure)
|
|
243
|
+
|
|
244
|
+
return dependency
|
|
245
|
+
|
|
246
|
+
def _challenge(self, **params: str) -> str:
|
|
247
|
+
items = {"realm": self.realm} if self.realm else {}
|
|
248
|
+
items.update(params)
|
|
249
|
+
rendered = ", ".join(f'{key}="{value}"' for key, value in items.items())
|
|
250
|
+
return f"Bearer {rendered}".strip()
|
|
251
|
+
|
|
252
|
+
def _error(self, decision: Decision, failure: str | None) -> HTTPException:
|
|
253
|
+
if failure == "discovery_unavailable":
|
|
254
|
+
return HTTPException(status_code=503, detail="Identity provider unavailable.")
|
|
255
|
+
detail = f"Access denied: {decision.reason}."
|
|
256
|
+
if decision.status_code == 401:
|
|
257
|
+
invalid = failure not in (None, "credentials_missing")
|
|
258
|
+
challenge = (
|
|
259
|
+
self._challenge(error="invalid_token", error_description=failure or "")
|
|
260
|
+
if invalid
|
|
261
|
+
else self._challenge()
|
|
262
|
+
)
|
|
263
|
+
return HTTPException(
|
|
264
|
+
status_code=401, detail=detail, headers={"WWW-Authenticate": challenge}
|
|
265
|
+
)
|
|
266
|
+
if decision.reason is DenyReason.MISSING_SCOPE:
|
|
267
|
+
return HTTPException(
|
|
268
|
+
status_code=403,
|
|
269
|
+
detail=detail,
|
|
270
|
+
headers={"WWW-Authenticate": self._challenge(error="insufficient_scope")},
|
|
271
|
+
)
|
|
272
|
+
return HTTPException(status_code=403, detail=detail)
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
__all__ = ["Enforcement", "Identity", "NodeSpec", "resolve_node"]
|
|
File without changes
|