mycelium-http-tools 0.3.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.
Files changed (50) hide show
  1. mycelium_http_tools-0.3.0/PKG-INFO +291 -0
  2. mycelium_http_tools-0.3.0/README.md +262 -0
  3. mycelium_http_tools-0.3.0/pyproject.toml +53 -0
  4. mycelium_http_tools-0.3.0/src/myc_http_tools/__init__.py +29 -0
  5. mycelium_http_tools-0.3.0/src/myc_http_tools/__main__.py +0 -0
  6. mycelium_http_tools-0.3.0/src/myc_http_tools/__version__.py +1 -0
  7. mycelium_http_tools-0.3.0/src/myc_http_tools/exceptions.py +97 -0
  8. mycelium_http_tools-0.3.0/src/myc_http_tools/fastapi/__init__.py +43 -0
  9. mycelium_http_tools-0.3.0/src/myc_http_tools/fastapi/enforce_profile_signature.py +125 -0
  10. mycelium_http_tools-0.3.0/src/myc_http_tools/fastapi/middleware.py +372 -0
  11. mycelium_http_tools-0.3.0/src/myc_http_tools/functions/__init__.py +23 -0
  12. mycelium_http_tools-0.3.0/src/myc_http_tools/functions/compress_and_encode_profile_to_base64.py +34 -0
  13. mycelium_http_tools-0.3.0/src/myc_http_tools/functions/decode_and_decompress_profile_from_base64.py +115 -0
  14. mycelium_http_tools-0.3.0/src/myc_http_tools/functions/verify_profile_signature.py +214 -0
  15. mycelium_http_tools-0.3.0/src/myc_http_tools/models/__init__.py +17 -0
  16. mycelium_http_tools-0.3.0/src/myc_http_tools/models/licensed_resources.py +198 -0
  17. mycelium_http_tools-0.3.0/src/myc_http_tools/models/owner.py +32 -0
  18. mycelium_http_tools-0.3.0/src/myc_http_tools/models/permission.py +19 -0
  19. mycelium_http_tools-0.3.0/src/myc_http_tools/models/profile.py +346 -0
  20. mycelium_http_tools-0.3.0/src/myc_http_tools/models/related_accounts.py +58 -0
  21. mycelium_http_tools-0.3.0/src/myc_http_tools/models/tenants_ownership.py +72 -0
  22. mycelium_http_tools-0.3.0/src/myc_http_tools/models/verbose_status.py +10 -0
  23. mycelium_http_tools-0.3.0/src/myc_http_tools/profile_jwks/__init__.py +35 -0
  24. mycelium_http_tools-0.3.0/src/myc_http_tools/profile_jwks/fetch_profile_jwks.py +150 -0
  25. mycelium_http_tools-0.3.0/src/myc_http_tools/profile_jwks/jwks_profile_signature_verifier.py +98 -0
  26. mycelium_http_tools-0.3.0/src/myc_http_tools/profile_jwks/profile_jwks_url.py +78 -0
  27. mycelium_http_tools-0.3.0/src/myc_http_tools/profile_jwks/profile_key_store.py +158 -0
  28. mycelium_http_tools-0.3.0/src/myc_http_tools/profile_jwks/read_jwks_cache_max_age.py +47 -0
  29. mycelium_http_tools-0.3.0/src/myc_http_tools/profile_jwks/read_signature_key_version.py +28 -0
  30. mycelium_http_tools-0.3.0/src/myc_http_tools/profile_jwks/trusted_profile_keys.py +126 -0
  31. mycelium_http_tools-0.3.0/src/myc_http_tools/profile_signature_config.py +243 -0
  32. mycelium_http_tools-0.3.0/src/myc_http_tools/profile_signature_verifier.py +37 -0
  33. mycelium_http_tools-0.3.0/src/myc_http_tools/settings.py +64 -0
  34. mycelium_http_tools-0.3.0/src/tests/__init__.py +0 -0
  35. mycelium_http_tools-0.3.0/src/tests/mock/__init__.py +0 -0
  36. mycelium_http_tools-0.3.0/src/tests/mock/cross_go_encoded.b64 +1 -0
  37. mycelium_http_tools-0.3.0/src/tests/mock/large-profile.json +1345 -0
  38. mycelium_http_tools-0.3.0/src/tests/mock/profile-signature/jwks-vectors.json +348 -0
  39. mycelium_http_tools-0.3.0/src/tests/mock/profile-signature/vectors.json +633 -0
  40. mycelium_http_tools-0.3.0/src/tests/test_contract_shared_fixture.py +105 -0
  41. mycelium_http_tools-0.3.0/src/tests/test_decode_and_decompress_profile.py +277 -0
  42. mycelium_http_tools-0.3.0/src/tests/test_licensed_resource.py +320 -0
  43. mycelium_http_tools-0.3.0/src/tests/test_licensed_resources.py +307 -0
  44. mycelium_http_tools-0.3.0/src/tests/test_permission.py +64 -0
  45. mycelium_http_tools-0.3.0/src/tests/test_profile.py +2110 -0
  46. mycelium_http_tools-0.3.0/src/tests/test_profile_contract.py +255 -0
  47. mycelium_http_tools-0.3.0/src/tests/test_profile_jwks.py +639 -0
  48. mycelium_http_tools-0.3.0/src/tests/test_profile_parity.py +246 -0
  49. mycelium_http_tools-0.3.0/src/tests/test_profile_signature.py +427 -0
  50. mycelium_http_tools-0.3.0/src/tests/test_profile_signature_fastapi.py +313 -0
@@ -0,0 +1,291 @@
1
+ Metadata-Version: 2.4
2
+ Name: mycelium-http-tools
3
+ Version: 0.3.0
4
+ Summary: A python library to integrate python APIs in Mycelium API Gateway
5
+ License: Apache 2.0
6
+ Author: Samuel Galvão Elias
7
+ Author-email: sgelias@outlook.com
8
+ Requires-Python: >=3.12,<4.0
9
+ Classifier: License :: Other/Proprietary License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.12
12
+ Classifier: Programming Language :: Python :: 3.13
13
+ Classifier: Programming Language :: Python :: 3.14
14
+ Classifier: Programming Language :: Python :: 3.15
15
+ Provides-Extra: dev
16
+ Provides-Extra: fastapi
17
+ Provides-Extra: signature
18
+ Requires-Dist: PyJWT[crypto] (>=2.15.1,<3.0.0) ; extra == "signature"
19
+ Requires-Dist: commitizen (>=4.9.1) ; extra == "dev"
20
+ Requires-Dist: fastapi[standard] (>=0.117.1,<1.0.0) ; extra == "fastapi"
21
+ Requires-Dist: mypy (>=2.3.0) ; extra == "dev"
22
+ Requires-Dist: pre-commit (>=4.3.0) ; extra == "dev"
23
+ Requires-Dist: pydantic (>=2.11.9,<3.0.0)
24
+ Requires-Dist: urllib3 (>=2.7.0,<3.0.0)
25
+ Requires-Dist: zstandard (>=0.25.0,<0.26.0) ; extra == "fastapi"
26
+ Requires-Dist: zstandard (>=0.25.0,<0.26.0) ; extra == "signature"
27
+ Description-Content-Type: text/markdown
28
+
29
+ # mycelium-sdk-py
30
+
31
+ Mycelium SDK for Python backends — decode the `x-mycelium-profile` header injected by the
32
+ Mycelium API Gateway and enforce tenant/account/role authorization with a fluent, typed API.
33
+ Published on PyPI as `mycelium-http-tools` (import as `myc_http_tools`).
34
+
35
+ Part of the Mycelium SDK family, alongside
36
+ [`mycelium-sdk-go`](https://github.com/LepistaBioinformatics/mycelium-sdk-go) (Go) and
37
+ [`mycelium-sdk-js`](https://github.com/LepistaBioinformatics/mycelium-sdk-js) (Node/TypeScript).
38
+ All three have full parity against the gateway's Rust `core::Profile` — the same method
39
+ surface (`permit_flags`/`deny_flags`, tenant-wide and admin helpers) and the same wire
40
+ contract (`perm` serialized as `"read"`/`"write"`).
41
+
42
+ ## Requirements
43
+
44
+ - Python **>= 3.12**
45
+ - The `fastapi` extra pulls in `zstandard` (required to decode/encode compressed profiles)
46
+ and `fastapi`; the `signature` extra also pulls in `zstandard`
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ # Core only (framework-agnostic)
52
+ pip install mycelium-http-tools
53
+
54
+ # With the FastAPI adapter (+ zstandard)
55
+ pip install mycelium-http-tools[fastapi]
56
+
57
+ # With profile signature verification (PyJWT[crypto] + zstandard)
58
+ pip install mycelium-http-tools[fastapi,signature]
59
+
60
+ # Development (all extras + tooling)
61
+ pip install mycelium-http-tools[dev,fastapi,signature]
62
+ ```
63
+
64
+ ## Core usage
65
+
66
+ ```python
67
+ from myc_http_tools.functions import decode_and_decompress_profile_from_base64
68
+
69
+ profile = decode_and_decompress_profile_from_base64(header_value)
70
+
71
+ related_accounts = (
72
+ profile
73
+ .with_read_access()
74
+ .on_tenant(tenant_id)
75
+ .with_roles(["admin"])
76
+ .on_account(account_id)
77
+ .get_related_account_or_error()
78
+ )
79
+ ```
80
+
81
+ Every filter method returns a copy — the original `Profile` is never mutated.
82
+
83
+ `decode_and_decompress_profile_from_base64` raises `ProfileDecodingError` on any failure
84
+ (empty input, invalid Base64, failed decompression, or invalid JSON). It is strict by
85
+ default; pass `strict=False` to fall back to treating the payload as uncompressed (useful
86
+ in development). To produce a header value (e.g. in tests), use the encode counterpart:
87
+
88
+ ```python
89
+ from myc_http_tools.functions import compress_and_encode_profile_to_base64
90
+
91
+ encoded = compress_and_encode_profile_to_base64(profile) # requires the zstandard extra
92
+ ```
93
+
94
+ ## FastAPI usage
95
+
96
+ Install with the `fastapi` extra, then choose one of three integration styles.
97
+
98
+ ### Dependency injection (recommended)
99
+
100
+ ```python
101
+ from fastapi import FastAPI, Depends
102
+ from myc_http_tools.models.profile import Profile
103
+ from myc_http_tools.fastapi import (
104
+ get_profile_from_header,
105
+ get_profile_from_header_required,
106
+ )
107
+
108
+ app = FastAPI()
109
+
110
+ # Optional profile (None if the header is missing in development)
111
+ @app.get("/whoami")
112
+ async def whoami(profile: Profile | None = Depends(get_profile_from_header)):
113
+ return {"accId": str(profile.acc_id) if profile else None}
114
+
115
+ # Required profile (raises if the header is missing/undecodable)
116
+ @app.get("/admin")
117
+ async def admin(profile: Profile = Depends(get_profile_from_header_required)):
118
+ profile.has_admin_privileges_or_error()
119
+ return {"accId": str(profile.acc_id)}
120
+ ```
121
+
122
+ ### Middleware
123
+
124
+ ```python
125
+ from fastapi import FastAPI, Request
126
+ from starlette.middleware.base import BaseHTTPMiddleware
127
+ from myc_http_tools.fastapi import profile_middleware
128
+
129
+ app = FastAPI()
130
+ app.add_middleware(BaseHTTPMiddleware, dispatch=profile_middleware)
131
+
132
+ @app.get("/whoami")
133
+ async def whoami(request: Request):
134
+ profile = request.state.profile # from the x-mycelium-profile header
135
+ return {"accId": str(profile.acc_id) if profile else None}
136
+ ```
137
+
138
+ ### Manual extraction
139
+
140
+ ```python
141
+ from fastapi import FastAPI, Request
142
+ from myc_http_tools.fastapi import get_profile_from_request
143
+
144
+ app = FastAPI()
145
+
146
+ @app.get("/whoami")
147
+ async def whoami(request: Request):
148
+ profile = get_profile_from_request(request)
149
+ return {"accId": str(profile.acc_id) if profile else None}
150
+ ```
151
+
152
+ The DI and middleware helpers are environment-gated: in development a missing/invalid
153
+ header resolves to `None`; in production a missing header responds `403` and an undecodable
154
+ header `401`. The environment is read from the `ENVIRONMENT` variable (default
155
+ `development`).
156
+
157
+ ## Profile signature verification (opt-in)
158
+
159
+ When the gateway is configured with `[core.profileSigning]`, it adds
160
+ `x-mycelium-profile-signature` to every request that carries
161
+ `x-mycelium-profile`: a compact JWS (`alg: EdDSA`, `kid: <key version>`) over
162
+ `{iat, ph, aud}`, where `ph` is the SHA-256 of the exact profile header and
163
+ `aud` the downstream service name. The gateway publishes its public keys as a
164
+ JWKS at `/.well-known/mycelium-profile-jwks.json`; this SDK downloads them,
165
+ caches them and verifies every signature locally.
166
+
167
+ > **Rollout order is mandatory.** Confirm the gateway in front of this service
168
+ > is already signing **before** setting `MYCELIUM_JWKS_URL` here. A service
169
+ > that verifies behind a gateway that does not sign rejects every request
170
+ > (403). To roll back, unset `MYCELIUM_JWKS_URL` here first, then disable
171
+ > signing in the gateway.
172
+
173
+ Enable it by installing the `signature` extra and pointing the SDK at the
174
+ gateway. `MYCELIUM_JWKS_URL` accepts either the complete JWKS endpoint or just
175
+ the gateway address (`mycelium.example.com`, `https://mycelium.example.com/prod`),
176
+ to which `/.well-known/mycelium-profile-jwks.json` is appended; `https://` is
177
+ assumed when no scheme is given:
178
+
179
+ ```bash
180
+ export MYCELIUM_JWKS_URL="https://gateway.internal/.well-known/mycelium-profile-jwks.json"
181
+ # Required with MYCELIUM_JWKS_URL: this service's name as registered in the gateway
182
+ export MYC_PROFILE_SIGNATURE_AUDIENCE=billing-api
183
+ # Optional: accepted clock skew, both directions (default 60 seconds, 1..300)
184
+ export MYC_PROFILE_SIGNATURE_TOLERANCE_SECONDS=60
185
+ # Local development only: accept an http:// JWKS URL (logs a warning)
186
+ # export MYCELIUM_JWKS_ALLOW_INSECURE_HTTP=true
187
+ ```
188
+
189
+ Configure at startup so a misconfigured service never starts.
190
+ `configure_profile_signature()` validates the settings; the JWKS is downloaded
191
+ on the **first signed request**, and requests fail closed (403) until it is
192
+ available. Requests only reach this service through the gateway, so the
193
+ gateway is up when that first request arrives: the service never depends on
194
+ the gateway to start (both can start in any order). Pass
195
+ `prefetch=True` to download the keys at startup instead (blocking, at most
196
+ 5 seconds; raises `ProfileJwksFetchError` when the gateway is unreachable).
197
+ Without `configure_profile_signature()` the settings are loaded on first use
198
+ and invalid settings make requests fail with 500:
199
+
200
+ ```python
201
+ from contextlib import asynccontextmanager
202
+ from fastapi import FastAPI
203
+ from myc_http_tools import configure_profile_signature
204
+
205
+ @asynccontextmanager
206
+ async def lifespan(app):
207
+ # raises ProfileSignatureConfigurationError (invalid settings);
208
+ # the keys are downloaded on the first signed request
209
+ configure_profile_signature()
210
+ yield
211
+
212
+ app = FastAPI(lifespan=lifespan)
213
+ ```
214
+
215
+ With `MYCELIUM_JWKS_URL` set, the four FastAPI entry points
216
+ (`get_profile_from_request`, `profile_middleware`,
217
+ `get_profile_from_header`, `get_profile_from_header_required`) verify before
218
+ decoding and answer **403** `Unable to verify Mycelium profile` on any
219
+ signature rejection, **in every `ENVIRONMENT`**: the development leniency never applies to
220
+ a failed signature. Duplicate profile/signature headers are rejected. Without
221
+ that variable nothing changes, except that a signed profile logs one warning
222
+ per process (`MYCELIUM_JWKS_URL` is not set, so nothing is verified). The
223
+ required header dependency preserves FastAPI 422 when the profile header is
224
+ absent. Internal/configuration errors return generic 500 and never run the
225
+ handler.
226
+
227
+ Key handling follows the gateway contract (`jwks-vectors.json`):
228
+
229
+ - the set is cached for the `max-age` sent by the gateway (bounded to
230
+ 1 minute..1 day, 12 hours when absent), then refreshed;
231
+ - a signature with an unknown `kid` triggers one refetch, at most every
232
+ 30 seconds, so gateway key rotation needs no change or restart here;
233
+ - until a first set is downloaded, a failed attempt is retried after
234
+ 5 seconds, so a service started before the gateway recovers quickly;
235
+ - if a refresh fails, the last valid set is kept and the failure is logged
236
+ (standard `logging`); one day (86400 seconds) after the set expired it
237
+ stops being trusted and requests fail closed until a refresh succeeds;
238
+ - while keys are cached, a request never waits for a refresh another request
239
+ already started: it verifies with the cached set;
240
+ - the fetch is bounded (5 seconds in total, 64 KiB, redirects never followed)
241
+ and a set with private material, another key type, a wrong key length or
242
+ a non-canonical/repeated `kid` is refused as a whole.
243
+
244
+ Any present but invalid setting (non-`https` URL without the development
245
+ switch, URL with credentials, missing audience, invalid tolerance, a value
246
+ other than `true`/`false` for the switch, missing `signature` extra) is a
247
+ configuration error, never "verification disabled". Tolerance must be an
248
+ integer between 1 and 300 (seconds), matching the other SDKs. The JWKS URL
249
+ comes only from configuration, never from a request.
250
+
251
+ Custom integrations can call the verifier directly; the raw decoder
252
+ `decode_and_decompress_profile_from_base64` does **not** verify anything:
253
+
254
+ ```python
255
+ from myc_http_tools import load_profile_signature_verifier_from_env
256
+
257
+ verifier = load_profile_signature_verifier_from_env() # once, at startup
258
+ if verifier is None:
259
+ raise RuntimeError("Profile verification must be configured for this service")
260
+ # optional: download the keys now (raises ProfileJwksFetchError);
261
+ # otherwise they are downloaded on the first verify_and_decode call
262
+ verifier.prefetch()
263
+ profile = verifier.verify_and_decode(profile_header, signature_header)
264
+ ```
265
+
266
+ `verify_and_decode` may block while keys are (re)fetched; call it from a
267
+ worker thread in async code.
268
+
269
+ Limits (by design): a captured valid pair can be replayed to the same service
270
+ during the tolerance window; only `x-mycelium-profile` is signed, so derive
271
+ identity from the profile, not from `x-mycelium-email`/`x-mycelium-role`
272
+ alone. Mount the middleware only where a profile is required: public or
273
+ health routes do not receive a profile from the gateway.
274
+
275
+ ## Error handling
276
+
277
+ All SDK errors extend `MyceliumError` (`message`, `code`, `exp_true`):
278
+
279
+ | Error | Code | Raised by |
280
+ |---|---|---|
281
+ | `ProfileSignatureError` | `MYC_PROFILE_SIGNATURE_INVALID` | `verify_profile_signature` / `verify_and_decode_profile` (carries a log-safe `reason`) |
282
+ | `ProfileSignatureConfigurationError` | `MYC_PROFILE_SIGNATURE_CONFIG_INVALID` | Invalid `MYCELIUM_JWKS_*` / `MYC_PROFILE_SIGNATURE_*` setting, or an unsafe JWKS |
283
+ | `ProfileJwksFetchError` | `MYC_PROFILE_JWKS_FETCH_FAILED` | The gateway JWKS could not be downloaded (`prefetch=True` at startup: abort) |
284
+ | `ProfileDecodingError` | `MYC00020` | `decode_and_decompress_profile_from_base64` on any decode failure |
285
+ | `InsufficientLicensesError` | `MYC00019` | `get_related_account_or_error()` when licensed resources are present but empty |
286
+ | `InsufficientPrivilegesError` | `MYC00019` | Any method requiring a privilege the profile lacks (carries `filtering_state`) |
287
+
288
+ ## License
289
+
290
+ Apache-2.0
291
+
@@ -0,0 +1,262 @@
1
+ # mycelium-sdk-py
2
+
3
+ Mycelium SDK for Python backends — decode the `x-mycelium-profile` header injected by the
4
+ Mycelium API Gateway and enforce tenant/account/role authorization with a fluent, typed API.
5
+ Published on PyPI as `mycelium-http-tools` (import as `myc_http_tools`).
6
+
7
+ Part of the Mycelium SDK family, alongside
8
+ [`mycelium-sdk-go`](https://github.com/LepistaBioinformatics/mycelium-sdk-go) (Go) and
9
+ [`mycelium-sdk-js`](https://github.com/LepistaBioinformatics/mycelium-sdk-js) (Node/TypeScript).
10
+ All three have full parity against the gateway's Rust `core::Profile` — the same method
11
+ surface (`permit_flags`/`deny_flags`, tenant-wide and admin helpers) and the same wire
12
+ contract (`perm` serialized as `"read"`/`"write"`).
13
+
14
+ ## Requirements
15
+
16
+ - Python **>= 3.12**
17
+ - The `fastapi` extra pulls in `zstandard` (required to decode/encode compressed profiles)
18
+ and `fastapi`; the `signature` extra also pulls in `zstandard`
19
+
20
+ ## Install
21
+
22
+ ```bash
23
+ # Core only (framework-agnostic)
24
+ pip install mycelium-http-tools
25
+
26
+ # With the FastAPI adapter (+ zstandard)
27
+ pip install mycelium-http-tools[fastapi]
28
+
29
+ # With profile signature verification (PyJWT[crypto] + zstandard)
30
+ pip install mycelium-http-tools[fastapi,signature]
31
+
32
+ # Development (all extras + tooling)
33
+ pip install mycelium-http-tools[dev,fastapi,signature]
34
+ ```
35
+
36
+ ## Core usage
37
+
38
+ ```python
39
+ from myc_http_tools.functions import decode_and_decompress_profile_from_base64
40
+
41
+ profile = decode_and_decompress_profile_from_base64(header_value)
42
+
43
+ related_accounts = (
44
+ profile
45
+ .with_read_access()
46
+ .on_tenant(tenant_id)
47
+ .with_roles(["admin"])
48
+ .on_account(account_id)
49
+ .get_related_account_or_error()
50
+ )
51
+ ```
52
+
53
+ Every filter method returns a copy — the original `Profile` is never mutated.
54
+
55
+ `decode_and_decompress_profile_from_base64` raises `ProfileDecodingError` on any failure
56
+ (empty input, invalid Base64, failed decompression, or invalid JSON). It is strict by
57
+ default; pass `strict=False` to fall back to treating the payload as uncompressed (useful
58
+ in development). To produce a header value (e.g. in tests), use the encode counterpart:
59
+
60
+ ```python
61
+ from myc_http_tools.functions import compress_and_encode_profile_to_base64
62
+
63
+ encoded = compress_and_encode_profile_to_base64(profile) # requires the zstandard extra
64
+ ```
65
+
66
+ ## FastAPI usage
67
+
68
+ Install with the `fastapi` extra, then choose one of three integration styles.
69
+
70
+ ### Dependency injection (recommended)
71
+
72
+ ```python
73
+ from fastapi import FastAPI, Depends
74
+ from myc_http_tools.models.profile import Profile
75
+ from myc_http_tools.fastapi import (
76
+ get_profile_from_header,
77
+ get_profile_from_header_required,
78
+ )
79
+
80
+ app = FastAPI()
81
+
82
+ # Optional profile (None if the header is missing in development)
83
+ @app.get("/whoami")
84
+ async def whoami(profile: Profile | None = Depends(get_profile_from_header)):
85
+ return {"accId": str(profile.acc_id) if profile else None}
86
+
87
+ # Required profile (raises if the header is missing/undecodable)
88
+ @app.get("/admin")
89
+ async def admin(profile: Profile = Depends(get_profile_from_header_required)):
90
+ profile.has_admin_privileges_or_error()
91
+ return {"accId": str(profile.acc_id)}
92
+ ```
93
+
94
+ ### Middleware
95
+
96
+ ```python
97
+ from fastapi import FastAPI, Request
98
+ from starlette.middleware.base import BaseHTTPMiddleware
99
+ from myc_http_tools.fastapi import profile_middleware
100
+
101
+ app = FastAPI()
102
+ app.add_middleware(BaseHTTPMiddleware, dispatch=profile_middleware)
103
+
104
+ @app.get("/whoami")
105
+ async def whoami(request: Request):
106
+ profile = request.state.profile # from the x-mycelium-profile header
107
+ return {"accId": str(profile.acc_id) if profile else None}
108
+ ```
109
+
110
+ ### Manual extraction
111
+
112
+ ```python
113
+ from fastapi import FastAPI, Request
114
+ from myc_http_tools.fastapi import get_profile_from_request
115
+
116
+ app = FastAPI()
117
+
118
+ @app.get("/whoami")
119
+ async def whoami(request: Request):
120
+ profile = get_profile_from_request(request)
121
+ return {"accId": str(profile.acc_id) if profile else None}
122
+ ```
123
+
124
+ The DI and middleware helpers are environment-gated: in development a missing/invalid
125
+ header resolves to `None`; in production a missing header responds `403` and an undecodable
126
+ header `401`. The environment is read from the `ENVIRONMENT` variable (default
127
+ `development`).
128
+
129
+ ## Profile signature verification (opt-in)
130
+
131
+ When the gateway is configured with `[core.profileSigning]`, it adds
132
+ `x-mycelium-profile-signature` to every request that carries
133
+ `x-mycelium-profile`: a compact JWS (`alg: EdDSA`, `kid: <key version>`) over
134
+ `{iat, ph, aud}`, where `ph` is the SHA-256 of the exact profile header and
135
+ `aud` the downstream service name. The gateway publishes its public keys as a
136
+ JWKS at `/.well-known/mycelium-profile-jwks.json`; this SDK downloads them,
137
+ caches them and verifies every signature locally.
138
+
139
+ > **Rollout order is mandatory.** Confirm the gateway in front of this service
140
+ > is already signing **before** setting `MYCELIUM_JWKS_URL` here. A service
141
+ > that verifies behind a gateway that does not sign rejects every request
142
+ > (403). To roll back, unset `MYCELIUM_JWKS_URL` here first, then disable
143
+ > signing in the gateway.
144
+
145
+ Enable it by installing the `signature` extra and pointing the SDK at the
146
+ gateway. `MYCELIUM_JWKS_URL` accepts either the complete JWKS endpoint or just
147
+ the gateway address (`mycelium.example.com`, `https://mycelium.example.com/prod`),
148
+ to which `/.well-known/mycelium-profile-jwks.json` is appended; `https://` is
149
+ assumed when no scheme is given:
150
+
151
+ ```bash
152
+ export MYCELIUM_JWKS_URL="https://gateway.internal/.well-known/mycelium-profile-jwks.json"
153
+ # Required with MYCELIUM_JWKS_URL: this service's name as registered in the gateway
154
+ export MYC_PROFILE_SIGNATURE_AUDIENCE=billing-api
155
+ # Optional: accepted clock skew, both directions (default 60 seconds, 1..300)
156
+ export MYC_PROFILE_SIGNATURE_TOLERANCE_SECONDS=60
157
+ # Local development only: accept an http:// JWKS URL (logs a warning)
158
+ # export MYCELIUM_JWKS_ALLOW_INSECURE_HTTP=true
159
+ ```
160
+
161
+ Configure at startup so a misconfigured service never starts.
162
+ `configure_profile_signature()` validates the settings; the JWKS is downloaded
163
+ on the **first signed request**, and requests fail closed (403) until it is
164
+ available. Requests only reach this service through the gateway, so the
165
+ gateway is up when that first request arrives: the service never depends on
166
+ the gateway to start (both can start in any order). Pass
167
+ `prefetch=True` to download the keys at startup instead (blocking, at most
168
+ 5 seconds; raises `ProfileJwksFetchError` when the gateway is unreachable).
169
+ Without `configure_profile_signature()` the settings are loaded on first use
170
+ and invalid settings make requests fail with 500:
171
+
172
+ ```python
173
+ from contextlib import asynccontextmanager
174
+ from fastapi import FastAPI
175
+ from myc_http_tools import configure_profile_signature
176
+
177
+ @asynccontextmanager
178
+ async def lifespan(app):
179
+ # raises ProfileSignatureConfigurationError (invalid settings);
180
+ # the keys are downloaded on the first signed request
181
+ configure_profile_signature()
182
+ yield
183
+
184
+ app = FastAPI(lifespan=lifespan)
185
+ ```
186
+
187
+ With `MYCELIUM_JWKS_URL` set, the four FastAPI entry points
188
+ (`get_profile_from_request`, `profile_middleware`,
189
+ `get_profile_from_header`, `get_profile_from_header_required`) verify before
190
+ decoding and answer **403** `Unable to verify Mycelium profile` on any
191
+ signature rejection, **in every `ENVIRONMENT`**: the development leniency never applies to
192
+ a failed signature. Duplicate profile/signature headers are rejected. Without
193
+ that variable nothing changes, except that a signed profile logs one warning
194
+ per process (`MYCELIUM_JWKS_URL` is not set, so nothing is verified). The
195
+ required header dependency preserves FastAPI 422 when the profile header is
196
+ absent. Internal/configuration errors return generic 500 and never run the
197
+ handler.
198
+
199
+ Key handling follows the gateway contract (`jwks-vectors.json`):
200
+
201
+ - the set is cached for the `max-age` sent by the gateway (bounded to
202
+ 1 minute..1 day, 12 hours when absent), then refreshed;
203
+ - a signature with an unknown `kid` triggers one refetch, at most every
204
+ 30 seconds, so gateway key rotation needs no change or restart here;
205
+ - until a first set is downloaded, a failed attempt is retried after
206
+ 5 seconds, so a service started before the gateway recovers quickly;
207
+ - if a refresh fails, the last valid set is kept and the failure is logged
208
+ (standard `logging`); one day (86400 seconds) after the set expired it
209
+ stops being trusted and requests fail closed until a refresh succeeds;
210
+ - while keys are cached, a request never waits for a refresh another request
211
+ already started: it verifies with the cached set;
212
+ - the fetch is bounded (5 seconds in total, 64 KiB, redirects never followed)
213
+ and a set with private material, another key type, a wrong key length or
214
+ a non-canonical/repeated `kid` is refused as a whole.
215
+
216
+ Any present but invalid setting (non-`https` URL without the development
217
+ switch, URL with credentials, missing audience, invalid tolerance, a value
218
+ other than `true`/`false` for the switch, missing `signature` extra) is a
219
+ configuration error, never "verification disabled". Tolerance must be an
220
+ integer between 1 and 300 (seconds), matching the other SDKs. The JWKS URL
221
+ comes only from configuration, never from a request.
222
+
223
+ Custom integrations can call the verifier directly; the raw decoder
224
+ `decode_and_decompress_profile_from_base64` does **not** verify anything:
225
+
226
+ ```python
227
+ from myc_http_tools import load_profile_signature_verifier_from_env
228
+
229
+ verifier = load_profile_signature_verifier_from_env() # once, at startup
230
+ if verifier is None:
231
+ raise RuntimeError("Profile verification must be configured for this service")
232
+ # optional: download the keys now (raises ProfileJwksFetchError);
233
+ # otherwise they are downloaded on the first verify_and_decode call
234
+ verifier.prefetch()
235
+ profile = verifier.verify_and_decode(profile_header, signature_header)
236
+ ```
237
+
238
+ `verify_and_decode` may block while keys are (re)fetched; call it from a
239
+ worker thread in async code.
240
+
241
+ Limits (by design): a captured valid pair can be replayed to the same service
242
+ during the tolerance window; only `x-mycelium-profile` is signed, so derive
243
+ identity from the profile, not from `x-mycelium-email`/`x-mycelium-role`
244
+ alone. Mount the middleware only where a profile is required: public or
245
+ health routes do not receive a profile from the gateway.
246
+
247
+ ## Error handling
248
+
249
+ All SDK errors extend `MyceliumError` (`message`, `code`, `exp_true`):
250
+
251
+ | Error | Code | Raised by |
252
+ |---|---|---|
253
+ | `ProfileSignatureError` | `MYC_PROFILE_SIGNATURE_INVALID` | `verify_profile_signature` / `verify_and_decode_profile` (carries a log-safe `reason`) |
254
+ | `ProfileSignatureConfigurationError` | `MYC_PROFILE_SIGNATURE_CONFIG_INVALID` | Invalid `MYCELIUM_JWKS_*` / `MYC_PROFILE_SIGNATURE_*` setting, or an unsafe JWKS |
255
+ | `ProfileJwksFetchError` | `MYC_PROFILE_JWKS_FETCH_FAILED` | The gateway JWKS could not be downloaded (`prefetch=True` at startup: abort) |
256
+ | `ProfileDecodingError` | `MYC00020` | `decode_and_decompress_profile_from_base64` on any decode failure |
257
+ | `InsufficientLicensesError` | `MYC00019` | `get_related_account_or_error()` when licensed resources are present but empty |
258
+ | `InsufficientPrivilegesError` | `MYC00019` | Any method requiring a privilege the profile lacks (carries `filtering_state`) |
259
+
260
+ ## License
261
+
262
+ Apache-2.0
@@ -0,0 +1,53 @@
1
+ [project]
2
+ name = "mycelium-http-tools"
3
+ version = "0.3.0"
4
+ description = "A python library to integrate python APIs in Mycelium API Gateway"
5
+ authors = [{ name = "Samuel Galvão Elias", email = "sgelias@outlook.com" }]
6
+ license = { text = "Apache 2.0" }
7
+ readme = "README.md"
8
+ requires-python = ">=3.12,<4.0"
9
+
10
+ dependencies = ["pydantic (>=2.11.9,<3.0.0)", "urllib3 (>=2.7.0,<3.0.0)"]
11
+
12
+ [tool.poetry]
13
+ packages = [
14
+ { include = "myc_http_tools", from = "src" },
15
+ { include = "tests", from = "src" },
16
+ ]
17
+
18
+ [project.optional-dependencies]
19
+ dev = ["mypy>=2.3.0", "pre-commit>=4.3.0", "commitizen>=4.9.1"]
20
+ fastapi = [
21
+ "fastapi[standard] (>=0.117.1,<1.0.0)",
22
+ "zstandard (>=0.25.0,<0.26.0)",
23
+ ]
24
+ # Downstream profile signature verification (opt-in via
25
+ # MYCELIUM_JWKS_URL). PyJWT[crypto] pulls `cryptography` for Ed25519;
26
+ # zstandard decodes the verified profile.
27
+ signature = [
28
+ "PyJWT[crypto] (>=2.15.1,<3.0.0)",
29
+ "zstandard (>=0.25.0,<0.26.0)",
30
+ ]
31
+
32
+ [tool.setuptools.packages.find]
33
+ where = ["src"]
34
+
35
+ [tool.setuptools.package-dir]
36
+ "" = "src"
37
+
38
+ [tool.pytest.ini_options]
39
+ testpaths = ["src/tests"]
40
+ python_files = ["test_*.py"]
41
+ python_classes = ["Test*"]
42
+ python_functions = ["test_*"]
43
+
44
+
45
+ [build-system]
46
+ requires = ["poetry-core>=2.0.0,<3.0.0"]
47
+ build-backend = "poetry.core.masonry.api"
48
+
49
+ [tool.poetry.group.dev.dependencies]
50
+ commitizen = "^4.9.1"
51
+ mypy = "^2.3.0"
52
+ pre-commit = "^4.3.0"
53
+ pytest = "^9.0.3"
@@ -0,0 +1,29 @@
1
+ """Mycelium HTTP Tools - A Python library to integrate Python APIs in Mycelium API Gateway."""
2
+
3
+ from .exceptions import (
4
+ InsufficientLicensesError,
5
+ InsufficientPrivilegesError,
6
+ MyceliumError,
7
+ ProfileJwksFetchError,
8
+ ProfileSignatureConfigurationError,
9
+ ProfileSignatureError,
10
+ )
11
+ from .profile_jwks import JwksProfileSignatureVerifier
12
+ from .profile_signature_config import (
13
+ configure_profile_signature,
14
+ load_profile_signature_verifier_from_env,
15
+ )
16
+ from .profile_signature_verifier import ProfileSignatureVerifier
17
+
18
+ __all__ = [
19
+ "MyceliumError",
20
+ "InsufficientLicensesError",
21
+ "InsufficientPrivilegesError",
22
+ "JwksProfileSignatureVerifier",
23
+ "ProfileJwksFetchError",
24
+ "ProfileSignatureConfigurationError",
25
+ "ProfileSignatureError",
26
+ "ProfileSignatureVerifier",
27
+ "configure_profile_signature",
28
+ "load_profile_signature_verifier_from_env",
29
+ ]
@@ -0,0 +1 @@
1
+ version = "0.3.0"