|
| 1 | +import base64 |
1 | 2 | import json |
| 3 | +import secrets |
2 | 4 | import time |
3 | 5 | from base64 import b64encode |
4 | 6 |
|
@@ -29,7 +31,6 @@ def rsa_keys(): |
29 | 31 | encryption_algorithm=NoEncryption(), |
30 | 32 | ) |
31 | 33 | public_key = private_key.public_key() |
32 | | - |
33 | 34 | return { |
34 | 35 | "private_key": private_key, |
35 | 36 | "private_pem": private_pem, |
@@ -209,3 +210,37 @@ def _mock_keycloak_introspect_token(user): |
209 | 210 | ) |
210 | 211 |
|
211 | 212 | return _mock_keycloak_introspect_token |
| 213 | + |
| 214 | + |
| 215 | +@pytest.fixture |
| 216 | +def mock_keycloak_certs(settings, rsa_keys, mock_keycloak_api): |
| 217 | + keycloak_settings = settings.auth.model_dump()["keycloak"] |
| 218 | + api_url = keycloak_settings["api_url"] |
| 219 | + realm_name = keycloak_settings["client_id"] |
| 220 | + realm_url = f"{api_url}/realms/{realm_name}" |
| 221 | + certs_url = f"{realm_url}/protocol/openid-connect/certs" |
| 222 | + |
| 223 | + def encode_number_base64(n: int): |
| 224 | + return base64.b64encode(n.to_bytes((n.bit_length() + 7) // 8, byteorder="big")).decode("utf-8") |
| 225 | + |
| 226 | + # return public key in Keycloak JWK format |
| 227 | + # https://github.com/marcospereirampj/python-keycloak/pull/704/changes |
| 228 | + public_key = rsa_keys["public_key"] |
| 229 | + payload = { |
| 230 | + "keys": [ |
| 231 | + { |
| 232 | + "kid": secrets.token_hex(16), |
| 233 | + "kty": "RSA", |
| 234 | + "alg": "RS256", |
| 235 | + "use": "sig", |
| 236 | + "n": encode_number_base64(public_key.public_numbers().n), |
| 237 | + "e": encode_number_base64(public_key.public_numbers().e), |
| 238 | + }, |
| 239 | + ] |
| 240 | + } |
| 241 | + |
| 242 | + mock_keycloak_api.get(certs_url).respond( |
| 243 | + json=payload, |
| 244 | + status_code=200, |
| 245 | + content_type="application/json", |
| 246 | + ) |
0 commit comments