|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Simulate /floconsole/v1/authenticate token create + require_auth decode (KMS). |
| 4 | +
|
| 5 | +Usage: |
| 6 | + export GOOGLE_APPLICATION_CREDENTIALS=/path/to/key.json |
| 7 | + export GCP_PROJECT_ID=... GCP_LOCATION=... GCP_KMS_KEY_RING=... |
| 8 | + export GCP_KMS_CRYPTO_KEY=... GCP_KMS_CRYPTO_KEY_VERSION=... |
| 9 | + uv run python scripts/test_kms_auth_flow.py |
| 10 | +""" |
| 11 | + |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +import base64 |
| 15 | +import os |
| 16 | +import subprocess |
| 17 | +import sys |
| 18 | +import tempfile |
| 19 | +from uuid import uuid4 |
| 20 | + |
| 21 | +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../packages/flo_cloud')) |
| 22 | +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../apps/floconsole')) |
| 23 | + |
| 24 | +from flo_cloud.gcp.kms import GcpKMS |
| 25 | +from flo_cloud.kms import FloKmsService |
| 26 | +from floconsole.constants.auth import AUTH_ROLE_ID |
| 27 | +from floconsole.services.token_service import TokenAlgorithms, TokenService |
| 28 | + |
| 29 | +ISSUER = os.getenv('CONSOLE_JWT_ISSUER', 'https://floconsole.rootflo.ai') |
| 30 | +AUDIENCE = os.getenv('CONSOLE_JWT_AUDIENCE', 'https://floconsole.rootflo.ai') |
| 31 | +PREFIX = os.getenv('CONSOLE_TOKEN_PREFIX', 'fc_') |
| 32 | + |
| 33 | + |
| 34 | +def _dummy_pem_keys() -> tuple[str, str]: |
| 35 | + with tempfile.NamedTemporaryFile(suffix='.pem', delete=False) as priv: |
| 36 | + subprocess.run( |
| 37 | + ['openssl', 'genrsa', '-out', priv.name, '2048'], |
| 38 | + check=True, |
| 39 | + capture_output=True, |
| 40 | + ) |
| 41 | + priv_pem = open(priv.name, 'rb').read() |
| 42 | + pub_proc = subprocess.run( |
| 43 | + ['openssl', 'rsa', '-pubout'], |
| 44 | + input=priv_pem, |
| 45 | + capture_output=True, |
| 46 | + check=True, |
| 47 | + ) |
| 48 | + return base64.b64encode(priv_pem).decode(), base64.b64encode( |
| 49 | + pub_proc.stdout |
| 50 | + ).decode() |
| 51 | + |
| 52 | + |
| 53 | +def _simulate_require_auth(decoded: dict) -> str | None: |
| 54 | + """Mirror floconsole require_auth checks after decode_token.""" |
| 55 | + if 'session_id' not in decoded: |
| 56 | + return 'Invalid token: missing session_id' |
| 57 | + if 'role_id' not in decoded or decoded['role_id'] != AUTH_ROLE_ID: |
| 58 | + return 'Invalid token: Not the console user' |
| 59 | + return None |
| 60 | + |
| 61 | + |
| 62 | +def main() -> int: |
| 63 | + print('=== KMS auth flow test (create_token + decode_token) ===\n') |
| 64 | + |
| 65 | + for var in ( |
| 66 | + 'GCP_PROJECT_ID', |
| 67 | + 'GCP_LOCATION', |
| 68 | + 'GCP_KMS_KEY_RING', |
| 69 | + 'GCP_KMS_CRYPTO_KEY', |
| 70 | + 'GCP_KMS_CRYPTO_KEY_VERSION', |
| 71 | + 'GOOGLE_APPLICATION_CREDENTIALS', |
| 72 | + ): |
| 73 | + print(f' {var}={os.environ.get(var, "<not set>")}') |
| 74 | + |
| 75 | + print('\n--- Step 1: Init KMS (same as ApplicationContainer) ---') |
| 76 | + kms = FloKmsService(cloud_provider='gcp') |
| 77 | + gcp: GcpKMS = kms.kms_client # type: ignore[assignment] |
| 78 | + print(f' KMS key: {gcp.key_name}') |
| 79 | + print(f' jwt_algorithm(): {kms.jwt_algorithm()}') |
| 80 | + print(f' uses_pkcs1: {gcp._uses_pkcs1}') |
| 81 | + |
| 82 | + priv, pub = _dummy_pem_keys() |
| 83 | + token_service = TokenService( |
| 84 | + private_key=priv, |
| 85 | + public_key=pub, |
| 86 | + kms_service=kms, |
| 87 | + algorithm=TokenAlgorithms.PS256, |
| 88 | + app_env='production', |
| 89 | + token_prefix=PREFIX, |
| 90 | + issuer=ISSUER, |
| 91 | + audience=AUDIENCE, |
| 92 | + ) |
| 93 | + print('\n--- Step 2: TokenService (production / KMS) ---') |
| 94 | + print(f' is_dev={token_service.is_dev}') |
| 95 | + print(f' algorithm={token_service.algorithm}') |
| 96 | + |
| 97 | + session_id = str(uuid4()) |
| 98 | + user_id = str(uuid4()) |
| 99 | + print('\n--- Step 3: create_token (POST /authenticate) ---') |
| 100 | + token = token_service.create_token( |
| 101 | + sub='admin@rootflo.ai', |
| 102 | + user_id=user_id, |
| 103 | + role_id=AUTH_ROLE_ID, |
| 104 | + payload={'session_id': session_id}, |
| 105 | + ) |
| 106 | + print(f' token length={len(token)}') |
| 107 | + print(f' prefix ok={token.startswith(PREFIX)}') |
| 108 | + header_alg = __import__('json').loads( |
| 109 | + base64.urlsafe_b64decode(token[len(PREFIX) :].split('.')[0] + '==') |
| 110 | + )['alg'] |
| 111 | + print(f' JWT header alg={header_alg}') |
| 112 | + |
| 113 | + print('\n--- Step 4: decode_token (require_auth middleware) ---') |
| 114 | + try: |
| 115 | + decoded = token_service.decode_token(token) |
| 116 | + except ValueError as e: |
| 117 | + print(f' FAIL ValueError: {e}') |
| 118 | + return 1 |
| 119 | + except Exception as e: |
| 120 | + print(f' FAIL {type(e).__name__}: {e}') |
| 121 | + return 1 |
| 122 | + |
| 123 | + print(f' decoded session_id={decoded.get("session_id")}') |
| 124 | + print(f' decoded role_id={decoded.get("role_id")}') |
| 125 | + print(f' decoded iss={decoded.get("iss")}') |
| 126 | + |
| 127 | + err = _simulate_require_auth(decoded) |
| 128 | + if err: |
| 129 | + print('\n--- Step 5: require_auth ---') |
| 130 | + print(f' FAIL: {err}') |
| 131 | + return 1 |
| 132 | + |
| 133 | + print('\n--- Step 5: require_auth ---') |
| 134 | + print(' OK: token would be accepted') |
| 135 | + print('\n=== PASS: full KMS create + validate flow ===') |
| 136 | + return 0 |
| 137 | + |
| 138 | + |
| 139 | +if __name__ == '__main__': |
| 140 | + sys.exit(main()) |
0 commit comments