|
| 1 | +# Copyright (c) The OGX Contributors. |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# This source code is licensed under the terms described in the LICENSE file in |
| 5 | +# the root directory of this source tree. |
| 6 | + |
| 7 | +import pytest |
| 8 | +from fastapi import FastAPI |
| 9 | +from fastapi.testclient import TestClient |
| 10 | + |
| 11 | +from ogx.core.datatypes import ( |
| 12 | + AuthenticationConfig, |
| 13 | + LocalApiKeyAuthConfig, |
| 14 | + StackConfig, |
| 15 | + TenancyConfig, |
| 16 | +) |
| 17 | +from ogx.core.server.auth import AuthenticationMiddleware |
| 18 | +from ogx.core.server.auth_providers import LocalApiKeyAuthProvider, TokenValidationError |
| 19 | +from ogx.core.server.server import validate_auth_security |
| 20 | + |
| 21 | +KEY1 = "ogk_abc123" |
| 22 | +KEY2 = "ogk_def456" |
| 23 | +INVALID_KEY = "ogk_invalid" |
| 24 | + |
| 25 | +_CONFIG = LocalApiKeyAuthConfig(api_keys=[KEY1, KEY2]) |
| 26 | + |
| 27 | + |
| 28 | +async def test_valid_token_returns_user_with_attributes(): |
| 29 | + provider = LocalApiKeyAuthProvider(_CONFIG) |
| 30 | + user = await provider.validate_token(KEY1) |
| 31 | + assert user.principal == KEY1 |
| 32 | + assert user.attributes == {"roles": ["admin", "owner"], "teams": [KEY1]} |
| 33 | + |
| 34 | + |
| 35 | +async def test_invalid_token_raises(): |
| 36 | + provider = LocalApiKeyAuthProvider(_CONFIG) |
| 37 | + with pytest.raises(TokenValidationError, match="Invalid or missing API key"): |
| 38 | + await provider.validate_token(INVALID_KEY) |
| 39 | + |
| 40 | + |
| 41 | +async def test_all_keys_work(): |
| 42 | + provider = LocalApiKeyAuthProvider(_CONFIG) |
| 43 | + u1 = await provider.validate_token(KEY1) |
| 44 | + u2 = await provider.validate_token(KEY2) |
| 45 | + assert u1.attributes["roles"] == ["admin", "owner"] |
| 46 | + assert u2.attributes["roles"] == ["admin", "owner"] |
| 47 | + |
| 48 | + |
| 49 | +async def test_attributes_are_immutable(): |
| 50 | + provider = LocalApiKeyAuthProvider(_CONFIG) |
| 51 | + user = await provider.validate_token(KEY1) |
| 52 | + # mutating the returned dict should not affect future validations |
| 53 | + user.attributes.pop("roles") |
| 54 | + user2 = await provider.validate_token(KEY1) |
| 55 | + assert user2.attributes == {"roles": ["admin", "owner"], "teams": [KEY1]} |
| 56 | + |
| 57 | + |
| 58 | +# --- Authentication middleware integration tests --- |
| 59 | + |
| 60 | + |
| 61 | +@pytest.fixture |
| 62 | +def local_api_key_app(): |
| 63 | + app = FastAPI() |
| 64 | + |
| 65 | + auth_config = AuthenticationConfig( |
| 66 | + provider_config=LocalApiKeyAuthConfig( |
| 67 | + type="local_api_key", |
| 68 | + api_keys=["test-api-key-12345", "secondary-key-67890", "third-key-abcde"], |
| 69 | + ), |
| 70 | + ) |
| 71 | + |
| 72 | + app.add_middleware( |
| 73 | + AuthenticationMiddleware, |
| 74 | + auth_config=auth_config, |
| 75 | + ) |
| 76 | + |
| 77 | + @app.get("/test") |
| 78 | + def test_endpoint(): |
| 79 | + return {"message": "Authentication successful"} |
| 80 | + |
| 81 | + return app |
| 82 | + |
| 83 | + |
| 84 | +@pytest.fixture |
| 85 | +def local_api_key_client(local_api_key_app): |
| 86 | + return TestClient(local_api_key_app) |
| 87 | + |
| 88 | + |
| 89 | +def test_authenticated_endpoint_without_token(local_api_key_client): |
| 90 | + """Test accessing protected endpoint without token""" |
| 91 | + response = local_api_key_client.get("/test") |
| 92 | + assert response.status_code == 401 |
| 93 | + assert "Authentication required" in response.json()["error"]["message"] |
| 94 | + |
| 95 | + |
| 96 | +def test_authenticated_endpoint_with_invalid_bearer_format(local_api_key_client): |
| 97 | + """Test accessing protected endpoint with invalid bearer format""" |
| 98 | + response = local_api_key_client.get("/test", headers={"Authorization": "InvalidFormat token123"}) |
| 99 | + assert response.status_code == 401 |
| 100 | + assert "Invalid Authorization header format" in response.json()["error"]["message"] |
| 101 | + |
| 102 | + |
| 103 | +def test_authenticated_endpoint_with_invalid_api_key(local_api_key_client): |
| 104 | + """Test accessing protected endpoint with wrong API key""" |
| 105 | + response = local_api_key_client.get("/test", headers={"Authorization": "Bearer wrong-key"}) |
| 106 | + assert response.status_code == 401 |
| 107 | + assert "Invalid or missing API key" in response.json()["error"]["message"] |
| 108 | + |
| 109 | + |
| 110 | +def test_authenticated_endpoint_with_valid_api_key(local_api_key_client): |
| 111 | + """Test accessing protected endpoint with correct API key""" |
| 112 | + response = local_api_key_client.get( |
| 113 | + "/test", |
| 114 | + headers={"Authorization": "Bearer test-api-key-12345"}, |
| 115 | + ) |
| 116 | + assert response.status_code == 200 |
| 117 | + assert response.json()["message"] == "Authentication successful" |
| 118 | + |
| 119 | + |
| 120 | +def test_authenticated_endpoint_with_valid_api_key_secondary(local_api_key_client): |
| 121 | + """Test accessing protected endpoint with secondary API key""" |
| 122 | + response = local_api_key_client.get( |
| 123 | + "/test", |
| 124 | + headers={"Authorization": "Bearer secondary-key-67890"}, |
| 125 | + ) |
| 126 | + assert response.status_code == 200 |
| 127 | + assert response.json()["message"] == "Authentication successful" |
| 128 | + |
| 129 | + |
| 130 | +def test_authenticated_endpoint_empty_bearer_token(local_api_key_client): |
| 131 | + """Test accessing protected endpoint with empty bearer token""" |
| 132 | + response = local_api_key_client.get( |
| 133 | + "/test", |
| 134 | + headers={"Authorization": "Bearer "}, |
| 135 | + ) |
| 136 | + assert response.status_code == 401 |
| 137 | + assert "Invalid or missing API key" in response.json()["error"]["message"] |
| 138 | + |
| 139 | + |
| 140 | +# --- Startup validation --- |
| 141 | + |
| 142 | + |
| 143 | +class TestLocalApiKeyTenancyValidation: |
| 144 | + def _make_config(self, tenancy_mode, default_tenant_id=None): |
| 145 | + return StackConfig( |
| 146 | + version=2, |
| 147 | + distro_name="test", |
| 148 | + providers={}, |
| 149 | + server={ |
| 150 | + "insecure": True, |
| 151 | + "auth": AuthenticationConfig( |
| 152 | + provider_config=LocalApiKeyAuthConfig( |
| 153 | + api_keys=["ogk_test123"], |
| 154 | + ), |
| 155 | + ), |
| 156 | + "tenancy": TenancyConfig(mode=tenancy_mode, default_tenant_id=default_tenant_id), |
| 157 | + }, |
| 158 | + ) |
| 159 | + |
| 160 | + def test_multi_tenancy_errors(self): |
| 161 | + config = self._make_config("multi") |
| 162 | + with pytest.raises(SystemExit, match="local_api_key.*multi"): |
| 163 | + validate_auth_security(config) |
| 164 | + |
| 165 | + def test_single_tenancy_passes(self): |
| 166 | + config = self._make_config("single", default_tenant_id="acme-corp") |
| 167 | + validate_auth_security(config) |
| 168 | + |
| 169 | + def test_disabled_tenancy_passes(self): |
| 170 | + config = self._make_config("disabled") |
| 171 | + validate_auth_security(config) |
0 commit comments