Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
16 changes: 12 additions & 4 deletions data-management/viewer/backend/src/api/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,15 +372,23 @@ 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
31 changes: 29 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,29 @@ 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 +169,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 +200,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
1 change: 1 addition & 0 deletions data-management/viewer/backend/src/api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,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"],
Expand Down
16 changes: 16 additions & 0 deletions data-management/viewer/backend/tests/test_auth_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,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