Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 19 additions & 8 deletions data-management/viewer/backend/src/api/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,15 +372,19 @@ def _build_provider() -> AuthProvider:
return ApiKeyProvider(key)

if provider_name == "azure_ad":
tenant_id = os.environ.get("DATAVIEWER_AZURE_TENANT_ID", "")
client_id = os.environ.get("DATAVIEWER_AZURE_CLIENT_ID", "")
tenant_id = os.environ.get("DATAVIEWER_AZURE_TENANT_ID", "").strip()
client_id = os.environ.get("DATAVIEWER_AZURE_CLIENT_ID", "").strip()
if not tenant_id or not client_id:
raise ValueError("DATAVIEWER_AZURE_TENANT_ID and DATAVIEWER_AZURE_CLIENT_ID are required for azure_ad")
jwks_uri = f"https://login.microsoftonline.com/{tenant_id}/discovery/v2.0/keys"
issuer = f"https://login.microsoftonline.com/{tenant_id}/v2.0"
return JwtProvider(jwks_uri=jwks_uri, audience=client_id, issuer=issuer, auth_method="azure_ad")

if provider_name == "auth0":
domain = os.environ.get("DATAVIEWER_AUTH0_DOMAIN", "")
audience = os.environ.get("DATAVIEWER_AUTH0_AUDIENCE", "")
domain = os.environ.get("DATAVIEWER_AUTH0_DOMAIN", "").strip()
audience = os.environ.get("DATAVIEWER_AUTH0_AUDIENCE", "").strip()
if not domain or not audience:
raise ValueError("DATAVIEWER_AUTH0_DOMAIN and DATAVIEWER_AUTH0_AUDIENCE are required for auth0")
jwks_uri = f"https://{domain}/.well-known/jwks.json"
issuer = f"https://{domain}/"
return JwtProvider(jwks_uri=jwks_uri, audience=audience, issuer=issuer, auth_method="auth0")
Expand Down Expand Up @@ -418,10 +422,17 @@ def reset_auth_provider() -> None:
_provider = None


def validate_hosted_auth_configuration() -> None:
"""Fail startup before storage or background workers for invalid hosted settings."""
if os.environ.get("DATAVIEWER_AUTH_PROVIDER", "apikey").lower() == "easy_auth":
_get_provider()
def validate_auth_configuration() -> None:
"""Build the selected provider at startup so invalid settings fail before serving.

Runs before storage or background workers start. Skipped only when local
development auth is disabled for a non-hosted provider, which is the same
case in which ``require_auth`` never constructs a provider.
"""
hosted = os.environ.get("DATAVIEWER_AUTH_PROVIDER", "apikey").lower() == "easy_auth"
if not hosted and os.environ.get("DATAVIEWER_AUTH_DISABLED", "false").lower() == "true":
return
_get_provider()


class HostedAuthMiddleware:
Expand Down
30 changes: 28 additions & 2 deletions data-management/viewer/backend/src/api/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,10 @@ class AppConfig:
"""Bind port for uvicorn."""

cors_origins: list[str] = field(default_factory=list)
"""Allowed CORS origins for the frontend."""
"""Allowed CORS origins for the frontend (literal matches only)."""

cors_origin_regex: str | None = None
"""Optional regex for wildcard CORS origins (e.g. Terraform ``https://*.domain``)."""

episode_cache_capacity: int = 32
"""Max episodes held in the LRU cache. 0 disables caching."""
Expand Down Expand Up @@ -116,6 +119,28 @@ class AppConfig:
"""Common ownership scope for workers sharing the same inference device."""


def _split_cors_origins(cors_raw: str) -> tuple[list[str], str | None]:
"""Split CORS_ORIGINS into literal origins and an optional wildcard regex.

Starlette's ``allow_origins`` matches literally, so values like
``https://*.example.com`` never match a real Origin header. Those entries
are converted to a regex for ``allow_origin_regex`` instead.
"""
literals: list[str] = []
regex_parts: list[str] = []
for origin in (o.strip() for o in cors_raw.split(",")):
if not origin:
continue
if "*" in origin:
# Escape then restore wildcards as ".*" so dots in the domain stay literal.
regex_parts.append(re.escape(origin).replace(r"\*", ".*"))
else:
literals.append(origin)
if not regex_parts:
return literals, None
return literals, "|".join(f"(?:{part})" for part in regex_parts)


def load_config(env_path: Path | None = None) -> AppConfig:
"""
Load application configuration from environment variables.
Expand Down Expand Up @@ -143,7 +168,7 @@ def load_config(env_path: Path | None = None) -> AppConfig:
backend_port = int(os.environ.get("BACKEND_PORT", "8000"))

cors_raw = os.environ.get("CORS_ORIGINS", _DEFAULT_CORS)
cors_origins = [o.strip() for o in cors_raw.split(",") if o.strip()]
cors_origins, cors_origin_regex = _split_cors_origins(cors_raw)

episode_cache_capacity = int(os.environ.get("EPISODE_CACHE_CAPACITY", "32"))
episode_cache_max_mb = int(os.environ.get("EPISODE_CACHE_MAX_MB", "100"))
Expand Down Expand Up @@ -174,6 +199,7 @@ def load_config(env_path: Path | None = None) -> AppConfig:
backend_host=backend_host,
backend_port=backend_port,
cors_origins=cors_origins,
cors_origin_regex=cors_origin_regex,
episode_cache_capacity=episode_cache_capacity,
episode_cache_max_mb=episode_cache_max_mb,
detection_models_dir=detection_models_dir,
Expand Down
5 changes: 3 additions & 2 deletions data-management/viewer/backend/src/api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
issue_media_session,
require_auth,
require_principal_context,
validate_hosted_auth_configuration,
validate_auth_configuration,
)
from .csrf import CSRF_COOKIE_NAME, generate_csrf_token, require_csrf_token
from .logging_config import configure_logging
Expand Down Expand Up @@ -99,7 +99,7 @@ def _validate_local_storage_writable(data_path: str) -> None:
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncGenerator[None]:
"""Validate local storage and clean up blob sync directories."""
validate_hosted_auth_configuration()
validate_auth_configuration()
if _config.storage_backend == "local":
await asyncio.to_thread(_validate_local_storage_writable, _config.data_path)

Expand Down Expand Up @@ -196,6 +196,7 @@ async def validation_exception_handler(request, exc: RequestValidationError) ->
app.add_middleware(
CORSMiddleware,
allow_origins=_config.cors_origins,
allow_origin_regex=_config.cors_origin_regex,
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
allow_headers=["Authorization", "Content-Type", "X-CSRF-Token", "X-API-Key", "X-Request-ID", "Idempotency-Key"],
Expand Down
73 changes: 73 additions & 0 deletions data-management/viewer/backend/tests/api/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -880,3 +880,76 @@ def test_hosted_startup_rejects_disabled_authentication(monkeypatch: pytest.Monk

with pytest.raises(ValueError, match="Hosted authentication cannot be disabled"), TestClient(app):
pass


@pytest.mark.parametrize(
("provider", "missing", "message"),
[
("azure_ad", ("DATAVIEWER_AZURE_TENANT_ID", "DATAVIEWER_AZURE_CLIENT_ID"), "DATAVIEWER_AZURE_TENANT_ID"),
("auth0", ("DATAVIEWER_AUTH0_DOMAIN", "DATAVIEWER_AUTH0_AUDIENCE"), "DATAVIEWER_AUTH0_DOMAIN"),
],
ids=["azure_ad", "auth0"],
)
def test_jwt_startup_rejects_missing_provider_settings(
monkeypatch: pytest.MonkeyPatch,
provider: str,
missing: Sequence[str],
message: str,
) -> None:
monkeypatch.setenv("DATAVIEWER_AUTH_DISABLED", "false")
monkeypatch.setenv("DATAVIEWER_AUTH_PROVIDER", provider)
for variable in missing:
monkeypatch.delenv(variable, raising=False)

with pytest.raises(ValueError, match=message), TestClient(app):
pass


def test_startup_rejects_unknown_auth_provider(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("DATAVIEWER_AUTH_DISABLED", "false")
monkeypatch.setenv("DATAVIEWER_AUTH_PROVIDER", "kerberos")

with pytest.raises(ValueError, match="Unsupported DATAVIEWER_AUTH_PROVIDER"), TestClient(app):
pass


@pytest.mark.parametrize(
("provider", "settings"),
[
(
"azure_ad",
{
"DATAVIEWER_AZURE_TENANT_ID": "00000000-0000-0000-0000-000000000001",
"DATAVIEWER_AZURE_CLIENT_ID": "00000000-0000-0000-0000-000000000002",
},
),
("auth0", {"DATAVIEWER_AUTH0_DOMAIN": "tenant.example.auth0.com", "DATAVIEWER_AUTH0_AUDIENCE": "dataviewer"}),
],
ids=["azure_ad", "auth0"],
)
def test_jwt_startup_constructs_provider_before_first_request(
monkeypatch: pytest.MonkeyPatch,
provider: str,
settings: dict[str, str],
) -> None:
from src.api import auth as auth_mod

monkeypatch.setenv("DATAVIEWER_AUTH_DISABLED", "false")
monkeypatch.setenv("DATAVIEWER_AUTH_PROVIDER", provider)
for variable, value in settings.items():
monkeypatch.setenv(variable, value)

with TestClient(app):
assert isinstance(auth_mod._provider, auth_mod.JwtProvider)


def test_startup_skips_provider_when_local_auth_disabled(monkeypatch: pytest.MonkeyPatch) -> None:
from src.api import auth as auth_mod

monkeypatch.setenv("DATAVIEWER_AUTH_DISABLED", "true")
monkeypatch.setenv("DATAVIEWER_AUTH_PROVIDER", "azure_ad")
monkeypatch.delenv("DATAVIEWER_AZURE_TENANT_ID", raising=False)
monkeypatch.delenv("DATAVIEWER_AZURE_CLIENT_ID", raising=False)

with TestClient(app):
assert auth_mod._provider is None
75 changes: 75 additions & 0 deletions data-management/viewer/backend/tests/api/test_cors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
"""CORS middleware behavior for literal and wildcard CORS_ORIGINS entries."""

from __future__ import annotations

import importlib
from collections.abc import Iterator

import pytest
from fastapi.testclient import TestClient

WILDCARD_ORIGINS = "http://localhost:5173,https://*.nicegrass-1a2b3c4d.eastus.azurecontainerapps.io"
FRONTEND_ORIGIN = "https://frontend.nicegrass-1a2b3c4d.eastus.azurecontainerapps.io"


def _reload_main() -> object:
import src.api.config as config_mod
import src.api.main as main_mod

config_mod._app_config = None
return importlib.reload(main_mod)


@pytest.fixture
def cors_client(monkeypatch: pytest.MonkeyPatch, tmp_path) -> Iterator[TestClient]:
"""Build the real app with wildcard CORS origins; main.py reads them at import time."""
monkeypatch.setenv("DATA_DIR", str(tmp_path))
monkeypatch.setenv("STORAGE_BACKEND", "local")
monkeypatch.setenv("DATAVIEWER_AUTH_DISABLED", "true")
monkeypatch.setenv("DATAVIEWER_AUTH_PROVIDER", "apikey")
monkeypatch.setenv("CORS_ORIGINS", WILDCARD_ORIGINS)
main_mod = _reload_main()
try:
yield TestClient(main_mod.app)
finally:
monkeypatch.undo()
_reload_main()


def _preflight(client: TestClient, origin: str):
return client.options(
"/api/datasets",
headers={"Origin": origin, "Access-Control-Request-Method": "GET"},
)


@pytest.mark.parametrize("origin", [FRONTEND_ORIGIN, "http://localhost:5173"], ids=["wildcard", "literal"])
def test_preflight_allows_configured_origin(cors_client: TestClient, origin: str) -> None:
response = _preflight(cors_client, origin)

assert response.status_code == 200
assert response.headers["access-control-allow-origin"] == origin
assert response.headers["access-control-allow-credentials"] == "true"


@pytest.mark.parametrize(
"origin",
[
"https://evil.example.com",
"https://frontend.nicegrass-1a2b3c4d.eastus.azurecontainerapps.io.evil.example.com",
"https://frontendXnicegrass-1a2b3c4d.eastus.azurecontainerapps.io",
],
ids=["other-domain", "suffix-appended", "dot-not-wildcard"],
)
def test_preflight_rejects_unconfigured_origin(cors_client: TestClient, origin: str) -> None:
response = _preflight(cors_client, origin)

assert response.status_code == 400
assert "access-control-allow-origin" not in response.headers


def test_simple_request_echoes_wildcard_origin(cors_client: TestClient) -> None:
response = cors_client.get("/health", headers={"Origin": FRONTEND_ORIGIN})

assert response.status_code == 200
assert response.headers["access-control-allow-origin"] == FRONTEND_ORIGIN
20 changes: 18 additions & 2 deletions data-management/viewer/backend/tests/test_auth_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,13 +285,13 @@ async def test_given_environment_limit_when_authenticating_then_enforces_overrid
def test_given_invalid_environment_limit_when_starting_hosted_auth_then_rejects_configuration(
self, setting: str, value: str, monkeypatch: pytest.MonkeyPatch
) -> None:
from src.api.auth import validate_hosted_auth_configuration
from src.api.auth import validate_auth_configuration

set_hosted_environment(monkeypatch)
monkeypatch.setenv(setting, value)

with pytest.raises(ValueError, match=f"{setting} must be a positive integer"):
validate_hosted_auth_configuration()
validate_auth_configuration()

@pytest.mark.asyncio
@pytest.mark.parametrize(("size", "accepted"), [(6144, True), (6145, False)], ids=["at-limit", "over-limit"])
Expand Down Expand Up @@ -508,6 +508,22 @@ async def test_easy_auth_selection(self, hosted_caller: HostedCaller) -> None:
assert exc_info.value.status_code == 401
assert exc_info.value.detail == "Caller authentication required"

async def test_azure_ad_missing_settings_fail_closed(self, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setenv("DATAVIEWER_AUTH_DISABLED", "false")
monkeypatch.setenv("DATAVIEWER_AUTH_PROVIDER", "azure_ad")
monkeypatch.delenv("DATAVIEWER_AZURE_TENANT_ID", raising=False)
monkeypatch.delenv("DATAVIEWER_AZURE_CLIENT_ID", raising=False)
with pytest.raises(ValueError, match="DATAVIEWER_AZURE_TENANT_ID"):
await require_auth(make_asgi_request("POST", "/api/x"))

async def test_auth0_missing_settings_fail_closed(self, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setenv("DATAVIEWER_AUTH_DISABLED", "false")
monkeypatch.setenv("DATAVIEWER_AUTH_PROVIDER", "auth0")
monkeypatch.delenv("DATAVIEWER_AUTH0_DOMAIN", raising=False)
monkeypatch.delenv("DATAVIEWER_AUTH0_AUDIENCE", raising=False)
with pytest.raises(ValueError, match="DATAVIEWER_AUTH0_DOMAIN"):
await require_auth(make_asgi_request("POST", "/api/x"))

async def test_azure_ad_selection(self, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setenv("DATAVIEWER_AUTH_DISABLED", "false")
monkeypatch.setenv("DATAVIEWER_AUTH_PROVIDER", "azure_ad")
Expand Down
18 changes: 18 additions & 0 deletions data-management/viewer/backend/tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,24 @@ def test_cors_origins_split_and_trimmed(self, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setenv("CORS_ORIGINS", "http://a.test , http://b.test ,, ")
cfg = load_config()
assert cfg.cors_origins == ["http://a.test", "http://b.test"]
assert cfg.cors_origin_regex is None

def test_cors_wildcard_origins_become_regex(self, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setenv(
"CORS_ORIGINS",
"http://localhost:5173,https://*.nicegrass-1a2b3c4d.eastus.azurecontainerapps.io",
)
cfg = load_config()
assert cfg.cors_origins == ["http://localhost:5173"]
assert cfg.cors_origin_regex is not None
assert "localhost" not in cfg.cors_origin_regex
import re

assert re.fullmatch(
cfg.cors_origin_regex,
"https://frontend.nicegrass-1a2b3c4d.eastus.azurecontainerapps.io",
)
assert re.fullmatch(cfg.cors_origin_regex, "https://evil.example.com") is None

def test_int_env_coercion(self, monkeypatch: pytest.MonkeyPatch):
monkeypatch.setenv("BACKEND_PORT", "9090")
Expand Down
Loading