This commit is contained in:
1 parent
08a6d7bd1d
commit
b3d27ff37e
5 files changed
+165
-114
No files matched your search
@@ -55,6 +55,7 @@ not a bug.
|
||||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
import os
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
||||
@@ -95,13 +96,12 @@ ERR_AUTHGUARD_UNAVAILABLE = "Unable to reach the authentication service. Please
|
||||
ERR_SECRET_NOT_SET = "SECRET environment variable is not set."
|
||||
|
||||
# _LOCAL_PROFILE is the fixed placeholder identity every handler reports when
|
||||
# auth is disabled (get_client(request) returns None, i.e. AUTHGUARD_URL was
|
||||
# never configured). Role is superadmin so can_manage_users reports true,
|
||||
# consistent with "nothing gated": the frontend's own admin-only UI sections
|
||||
# become visible too, even though the underlying admin endpoints have
|
||||
# nothing to manage.
|
||||
# authentication is disabled, either because AUTHGUARD_URL is disabled or
|
||||
# because ProjectConfigurator has turned off this project's login requirement.
|
||||
# Role is superadmin so all application routes see the same Admin identity even
|
||||
# though no credentials were supplied.
|
||||
_LOCAL_PROFILE = PublicUser(
|
||||
id=0, username="local", email="", role=ROLE_SUPERADMIN, totp_enabled=False
|
||||
id=0, username="Admin", email="", role=ROLE_SUPERADMIN, totp_enabled=False
|
||||
)
|
||||
|
||||
|
||||
@@ -244,6 +244,7 @@ def build_auth_router(
|
||||
secure_cookie: bool = False,
|
||||
cookie_name: str = DEFAULT_COOKIE_NAME,
|
||||
configuration_error: str | None = None,
|
||||
internal_secret: str | None = None,
|
||||
) -> APIRouter:
|
||||
"""Builds a ready-to-mount APIRouter implementing the full standardized
|
||||
AuthGuard-proxy surface (no prefix baked in - mount it at "/api/auth",
|
||||
@@ -251,6 +252,10 @@ def build_auth_router(
|
||||
`get_client`/`get_store` contract."""
|
||||
|
||||
router = APIRouter()
|
||||
login_required_override: bool | None = None
|
||||
configured_internal_secret = (
|
||||
os.environ.get("SECRET", "") if internal_secret is None else internal_secret
|
||||
).strip()
|
||||
|
||||
def _ensure_configured() -> None:
|
||||
if configuration_error:
|
||||
@@ -300,12 +305,18 @@ def build_auth_router(
|
||||
raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED)
|
||||
return profile, token
|
||||
|
||||
async def _login_required(store: ProxyStore) -> bool:
|
||||
if login_required_override is not None:
|
||||
return login_required_override
|
||||
return await store.login_required()
|
||||
|
||||
async def require_session(
|
||||
request: Request,
|
||||
store: ProxyStore = Depends(get_store), # noqa: B008
|
||||
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
|
||||
) -> PublicUser:
|
||||
"""FastAPI dependency gating a route behind a valid session."""
|
||||
if not _enabled(client):
|
||||
if not _enabled(client) or not await _login_required(store):
|
||||
return _LOCAL_PROFILE
|
||||
assert client is not None
|
||||
profile, _ = await _current_profile_or_401(request, client)
|
||||
@@ -313,13 +324,14 @@ def build_auth_router(
|
||||
|
||||
async def _require_user_manager(
|
||||
request: Request,
|
||||
store: ProxyStore = Depends(get_store), # noqa: B008
|
||||
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
|
||||
) -> str:
|
||||
"""Returns the caller's session token, or "" in auth-disabled mode
|
||||
(each handler decides its own auth-disabled response). Authorization
|
||||
(can_manage_users, "protect the superadmin") is enforced by
|
||||
AuthGuard itself from the forwarded token."""
|
||||
if not _enabled(client):
|
||||
if not _enabled(client) or not await _login_required(store):
|
||||
return ""
|
||||
token = _session_token(request)
|
||||
if not token:
|
||||
@@ -335,9 +347,11 @@ def build_auth_router(
|
||||
client: Optional[AuthClient] = Depends(get_client), # noqa: B008
|
||||
) -> dict[str, Any]:
|
||||
_ensure_configured()
|
||||
login_required = await store.login_required()
|
||||
login_required = await _login_required(store)
|
||||
if not _enabled(client):
|
||||
return {"user": _user_payload(_LOCAL_PROFILE), "authRequired": login_required}
|
||||
return {"user": _user_payload(_LOCAL_PROFILE), "authRequired": False}
|
||||
if not login_required:
|
||||
return {"user": _user_payload(_LOCAL_PROFILE), "authRequired": False}
|
||||
assert client is not None
|
||||
try:
|
||||
profile, _ = await _current_profile(request, client)
|
||||
@@ -355,6 +369,8 @@ def build_auth_router(
|
||||
) -> dict[str, bool]:
|
||||
if not _enabled(client):
|
||||
return {"adminNeeded": False}
|
||||
if not await _login_required(store):
|
||||
return {"adminNeeded": False}
|
||||
assert client is not None
|
||||
if await store.is_setup_claimed():
|
||||
return {"adminNeeded": False}
|
||||
@@ -375,10 +391,18 @@ def build_auth_router(
|
||||
return {
|
||||
"setupRequired": False,
|
||||
"authenticated": True,
|
||||
"authRequired": True,
|
||||
"authRequired": False,
|
||||
"user": _user_payload(_LOCAL_PROFILE),
|
||||
}
|
||||
assert client is not None
|
||||
login_required = await _login_required(store)
|
||||
if not login_required:
|
||||
return {
|
||||
"setupRequired": False,
|
||||
"authenticated": True,
|
||||
"authRequired": False,
|
||||
"user": _user_payload(_LOCAL_PROFILE),
|
||||
}
|
||||
claimed = await store.is_setup_claimed()
|
||||
setup_required = False
|
||||
if not claimed:
|
||||
@@ -390,7 +414,6 @@ def build_auth_router(
|
||||
profile, _ = await _current_profile(request, client)
|
||||
except AuthClientError as exc:
|
||||
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
|
||||
login_required = await store.login_required()
|
||||
return {
|
||||
"setupRequired": setup_required,
|
||||
"authenticated": profile is not None,
|
||||
@@ -532,14 +555,29 @@ def build_auth_router(
|
||||
|
||||
@router.get("/access")
|
||||
async def access_settings(store: ProxyStore = Depends(get_store)) -> dict[str, bool]: # noqa: B008
|
||||
return {"loginRequired": await store.login_required()}
|
||||
return {"loginRequired": await _login_required(store)}
|
||||
|
||||
@router.put("/access")
|
||||
async def update_access_settings(
|
||||
req: UpdateAccessRequest,
|
||||
store: ProxyStore = Depends(get_store), # noqa: B008
|
||||
) -> dict[str, bool]:
|
||||
nonlocal login_required_override
|
||||
await store.set_login_required(req.loginRequired)
|
||||
login_required_override = req.loginRequired
|
||||
return {"loginRequired": req.loginRequired}
|
||||
|
||||
@router.put("/access/internal")
|
||||
async def update_access_settings_internal(
|
||||
req: UpdateAccessRequest,
|
||||
request: Request,
|
||||
store: ProxyStore = Depends(get_store), # noqa: B008
|
||||
) -> dict[str, bool]:
|
||||
nonlocal login_required_override
|
||||
if not configured_internal_secret or request.headers.get("X-Internal-Auth") != configured_internal_secret:
|
||||
raise HTTPException(status_code=401, detail="internal service authentication required")
|
||||
await store.set_login_required(req.loginRequired)
|
||||
login_required_override = req.loginRequired
|
||||
return {"loginRequired": req.loginRequired}
|
||||
|
||||
# --- admin user management ----------------------------------------------
|
||||
|
||||
@@ -33,7 +33,12 @@ class _FakeStore(ap.ProxyStore):
|
||||
self.claimed = False
|
||||
|
||||
|
||||
def _build_app(store: ap.ProxyStore, client: AuthClient | None = None) -> FastAPI:
|
||||
def _build_app(
|
||||
store: ap.ProxyStore,
|
||||
client: AuthClient | None = None,
|
||||
*,
|
||||
internal_secret: str | None = None,
|
||||
) -> FastAPI:
|
||||
def get_client(request: Request) -> AuthClient | None:
|
||||
return client
|
||||
|
||||
@@ -41,7 +46,10 @@ def _build_app(store: ap.ProxyStore, client: AuthClient | None = None) -> FastAP
|
||||
return store
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(ap.build_auth_router(get_client, get_store), prefix="/api/auth")
|
||||
app.include_router(
|
||||
ap.build_auth_router(get_client, get_store, internal_secret=internal_secret),
|
||||
prefix="/api/auth",
|
||||
)
|
||||
return app
|
||||
|
||||
|
||||
@@ -68,7 +76,7 @@ class AuthDisabledModeTests(unittest.TestCase):
|
||||
|
||||
def test_me_reports_local_superadmin(self) -> None:
|
||||
body = self.client.get("/api/auth/me").json()
|
||||
self.assertEqual(body["user"]["username"], "local")
|
||||
self.assertEqual(body["user"]["username"], "Admin")
|
||||
|
||||
def test_setup_succeeds_as_a_no_op(self) -> None:
|
||||
response = self.client.post(
|
||||
@@ -113,6 +121,22 @@ class AccessSettingsTests(unittest.TestCase):
|
||||
self.assertEqual(response.json(), {"loginRequired": False})
|
||||
self.assertEqual(client.get("/api/auth/access").json(), {"loginRequired": False})
|
||||
|
||||
def test_internal_update_disables_login_and_uses_admin_identity(self) -> None:
|
||||
store = _FakeStore(login_required=True)
|
||||
client = TestClient(_build_app(store, _FakeClient(setup_required=False), internal_secret="secret"))
|
||||
|
||||
response = client.put(
|
||||
"/api/auth/access/internal",
|
||||
headers={"X-Internal-Auth": "secret"},
|
||||
json={"loginRequired": False},
|
||||
)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json(), {"loginRequired": False})
|
||||
|
||||
body = client.get("/api/auth/me").json()
|
||||
self.assertFalse(body["authRequired"])
|
||||
self.assertEqual(body["user"]["username"], "Admin")
|
||||
|
||||
|
||||
class _FakeClient(AuthClient):
|
||||
"""Overrides just the methods build_auth_router calls, bypassing real
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
import {
|
||||
PRIMARY_COLOR_PALETTE,
|
||||
initPrimaryColor,
|
||||
primaryColorByName,
|
||||
setPrimaryColor,
|
||||
storedPrimaryColor,
|
||||
} from '../primary-color.svelte'
|
||||
@@ -32,38 +31,17 @@
|
||||
|
||||
<div class="sc-primary-color">
|
||||
<span class="sc-label">{label}</span>
|
||||
<div class="sc-primary-color-options" role="radiogroup" aria-label={label}>
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={selected === ''}
|
||||
aria-label="Default"
|
||||
title="Default"
|
||||
class:sc-primary-color-selected={selected === ''}
|
||||
onclick={() => choose('')}
|
||||
>
|
||||
<span class="sc-primary-color-default">—</span>
|
||||
</button>
|
||||
<select
|
||||
class="sc-input"
|
||||
aria-label={label}
|
||||
value={selected}
|
||||
onchange={(event) => choose(event.currentTarget.value)}
|
||||
>
|
||||
<option value="">Default</option>
|
||||
{#each PRIMARY_COLOR_PALETTE as color (color.name)}
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={selected === color.name}
|
||||
aria-label={color.name}
|
||||
title={color.name}
|
||||
class:sc-primary-color-selected={selected === color.name}
|
||||
style={'--sc-picker-color:' + color.light}
|
||||
onclick={() => choose(color.name)}
|
||||
>
|
||||
<span></span>
|
||||
</button>
|
||||
<option value={color.name}>{color.name}</option>
|
||||
{/each}
|
||||
</div>
|
||||
{#if selected}
|
||||
<span class="sc-primary-color-name">{primaryColorByName(selected)?.name}</span>
|
||||
{:else}
|
||||
<span class="sc-primary-color-name">Default</span>
|
||||
{/if}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
@@ -71,45 +49,4 @@
|
||||
display: grid;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.sc-primary-color-options {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
|
||||
.sc-primary-color-options button {
|
||||
display: grid;
|
||||
width: 1.75rem;
|
||||
height: 1.75rem;
|
||||
place-items: center;
|
||||
padding: 0;
|
||||
border: 1px solid var(--sc-border);
|
||||
border-radius: 9999px;
|
||||
background: var(--sc-surface);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.sc-primary-color-options button > span {
|
||||
width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
border-radius: 9999px;
|
||||
background: var(--sc-picker-color);
|
||||
}
|
||||
|
||||
.sc-primary-color-options button:focus-visible,
|
||||
.sc-primary-color-options button.sc-primary-color-selected {
|
||||
outline: 2px solid var(--sc-ring);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.sc-primary-color-default {
|
||||
color: var(--sc-muted-fg);
|
||||
background: transparent !important;
|
||||
}
|
||||
|
||||
.sc-primary-color-name {
|
||||
color: var(--sc-muted-fg);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
</style>
|
||||
Reference in new issue
Block a user