feat: honor project login requirement in shared auth

This commit is contained in:
Gabriel20xx committed 2026-09-17 00:14:56 +02:00
1 parent 78067cc890
commit 51eef30971
4 files changed
+223 -43

No files matched your search

+98 -23
View File
@@ -116,7 +116,7 @@
// ------------------------------------------- // -------------------------------------------
// Passing Disabled() to New/NewWithStore turns authentication off entirely // Passing Disabled() to New/NewWithStore turns authentication off entirely
// for a Service: Service.authGuard is nil (Service.enabled() reports false), // for a Service: Service.authGuard is nil (Service.enabled() reports false),
// CurrentUser always resolves to localProfile (a fixed placeholder // CurrentUser always resolves to adminProfile (a fixed placeholder
// superadmin identity), so every request is treated as already authenticated // superadmin identity), so every request is treated as already authenticated
// regardless of the `auth_required` setting - there is no login screen and // regardless of the `auth_required` setting - there is no login screen and
// nothing gated. This is an explicit mode for local development or a // nothing gated. This is an explicit mode for local development or a
@@ -172,6 +172,7 @@ import (
"os" "os"
"strconv" "strconv"
"strings" "strings"
"sync"
"time" "time"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
@@ -233,12 +234,12 @@ const (
proxyMaxEmailLength = 254 proxyMaxEmailLength = 254
) )
// localProfile is the fixed placeholder identity CurrentUser/Signup/Login // adminProfile is the fixed placeholder identity used when authentication is
// report when auth is disabled (Disabled()). Role is superadmin so // disabled, either explicitly through Disabled() or through a project's
// CanManageUsers reports true, consistent with "nothing gated": the // ProjectConfigurator "Require Login" toggle. Role is superadmin so all
// frontend's own admin-only UI sections become visible too, even though the // application routes see the same administrator identity even though no
// underlying admin endpoints have nothing to manage. // credentials were supplied.
var localProfile = ProxyUser{ID: 0, Username: "local", Email: "", Role: string(RoleSuperAdmin), CanManageUsers: true} var adminProfile = ProxyUser{ID: 0, Username: "Admin", Email: "", Role: string(RoleSuperAdmin), CanManageUsers: true}
// ProxyStore is the small piece of local, project-owned persistence a // ProxyStore is the small piece of local, project-owned persistence a
// Service needs beyond AuthGuard itself: the independent "require login" // Service needs beyond AuthGuard itself: the independent "require login"
@@ -276,6 +277,12 @@ type Service struct {
// real base URL. // real base URL.
authGuard *authclient.Client authGuard *authclient.Client
configurationError error configurationError error
// loginRequiredOverride is populated by the internal ProjectConfigurator
// endpoint. Some legacy consumers intentionally use a no-op ProxyStore for
// this setting because they historically had no local toggle; the live
// override lets those services still honor the central setting immediately.
loginRequiredMu sync.RWMutex
loginRequiredOverride *bool
} }
// ServiceOption configures optional New/NewWithStore construction behavior. // ServiceOption configures optional New/NewWithStore construction behavior.
@@ -499,7 +506,15 @@ func (s *Service) CurrentUser(r *http.Request) (*ProxyUser, error) {
return nil, s.configurationError return nil, s.configurationError
} }
if !s.enabled() { if !s.enabled() {
user := localProfile user := adminProfile
return &user, nil
}
loginRequired, err := s.LoginRequired(r.Context())
if err != nil {
return nil, err
}
if !loginRequired {
user := adminProfile
return &user, nil return &user, nil
} }
profile, err := s.currentProfile(r.Context(), s.sessionToken(r)) profile, err := s.currentProfile(r.Context(), s.sessionToken(r))
@@ -537,9 +552,10 @@ func (s *Service) Require(next http.Handler) http.Handler {
} }
// RequireIfLoginRequired protects actions when the application has login // RequireIfLoginRequired protects actions when the application has login
// enabled, while allowing explicitly public installations to use actions that // enabled. When login is disabled, CurrentUser supplies the synthetic Admin
// do not need a user identity. This toggle is independent of AuthGuard - see // superadmin identity, so handlers can use the same authenticated code path
// the package doc comment's second paragraph. // without requiring credentials. This toggle is independent of AuthGuard -
// see the package doc comment's second paragraph.
func (s *Service) RequireIfLoginRequired(next http.Handler) http.Handler { func (s *Service) RequireIfLoginRequired(next http.Handler) http.Handler {
return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if UserFromContext(r.Context()) != nil { if UserFromContext(r.Context()) != nil {
@@ -572,8 +588,9 @@ func (s *Service) RequireAdmin(next http.Handler) http.Handler {
} }
// RequireAdminIfLoginRequired keeps administrative actions protected for // RequireAdminIfLoginRequired keeps administrative actions protected for
// authenticated users, while allowing explicitly public installations to use // authenticated users. When login is disabled, CurrentUser supplies the
// configuration endpoints that do not require a user identity. // synthetic Admin superadmin identity so configuration endpoints remain
// available without credentials.
func (s *Service) RequireAdminIfLoginRequired(next http.Handler) http.Handler { func (s *Service) RequireAdminIfLoginRequired(next http.Handler) http.Handler {
return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := UserFromContext(r.Context()) user := UserFromContext(r.Context())
@@ -713,6 +730,15 @@ func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) {
writeProxyJSON(w, http.StatusOK, map[string]bool{"adminNeeded": false}) writeProxyJSON(w, http.StatusOK, map[string]bool{"adminNeeded": false})
return return
} }
loginRequired, err := s.LoginRequired(r.Context())
if err != nil {
writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
if !loginRequired {
writeProxyJSON(w, http.StatusOK, map[string]bool{"adminNeeded": false})
return
}
claimed, err := s.isSetupClaimed(r.Context()) claimed, err := s.isSetupClaimed(r.Context())
if err != nil { if err != nil {
writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable") writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable")
@@ -731,6 +757,15 @@ func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) {
} }
func (s *Service) LoginRequired(ctx context.Context) (bool, error) { func (s *Service) LoginRequired(ctx context.Context) (bool, error) {
s.loginRequiredMu.RLock()
override := s.loginRequiredOverride
s.loginRequiredMu.RUnlock()
if override != nil {
return *override, nil
}
if s.store == nil {
return true, nil
}
return s.store.LoginRequired(ctx) return s.store.LoginRequired(ctx)
} }
@@ -764,7 +799,40 @@ func (s *Service) UpdateAccessSettings(w http.ResponseWriter, r *http.Request) {
// central "Require Login" toggle (ConfigWorkspace.svelte's loginControls) apply here without an // central "Require Login" toggle (ConfigWorkspace.svelte's loginControls) apply here without an
// admin session of its own. // admin session of its own.
func (s *Service) SetLoginRequired(ctx context.Context, required bool) error { func (s *Service) SetLoginRequired(ctx context.Context, required bool) error {
return s.store.SetLoginRequired(ctx, required) if s.store != nil {
if err := s.store.SetLoginRequired(ctx, required); err != nil {
return err
}
}
s.loginRequiredMu.Lock()
s.loginRequiredOverride = &required
s.loginRequiredMu.Unlock()
return nil
}
// SetLoginRequiredInternal returns the X-Internal-Auth-gated handler used by
// ProjectConfigurator to apply its per-project "Require Login" setting. It
// lives on the shared service so projects outside the core-service family can
// expose the same propagation endpoint without duplicating its JSON handling.
func (s *Service) SetLoginRequiredInternal(secret string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.TrimSpace(secret) == "" || r.Header.Get("X-Internal-Auth") != secret {
writeProxyError(w, http.StatusUnauthorized, "internal service authentication required")
return
}
var input struct {
LoginRequired *bool `json:"loginRequired"`
}
if err := decodeProxyJSON(r, &input); err != nil || input.LoginRequired == nil {
writeProxyError(w, http.StatusBadRequest, "loginRequired must be a boolean")
return
}
if err := s.SetLoginRequired(r.Context(), *input.LoginRequired); err != nil {
writeProxyError(w, http.StatusInternalServerError, "access setting could not be saved")
return
}
writeProxyJSON(w, http.StatusOK, map[string]bool{"loginRequired": *input.LoginRequired})
})
} }
func (s *Service) Status(w http.ResponseWriter, r *http.Request) { func (s *Service) Status(w http.ResponseWriter, r *http.Request) {
@@ -773,8 +841,20 @@ func (s *Service) Status(w http.ResponseWriter, r *http.Request) {
return return
} }
if !s.enabled() { if !s.enabled() {
user := localProfile user := adminProfile
writeProxyJSON(w, http.StatusOK, map[string]any{"setupRequired": false, "authenticated": true, "authRequired": true, "user": &user}) writeProxyJSON(w, http.StatusOK, map[string]any{"setupRequired": false, "authenticated": true, "authRequired": false, "user": &user})
return
}
loginRequired, err := s.LoginRequired(r.Context())
if err != nil {
writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
if !loginRequired {
user := adminProfile
writeProxyJSON(w, http.StatusOK, map[string]any{
"setupRequired": false, "authenticated": true, "authRequired": false, "user": &user,
})
return return
} }
claimed, err := s.isSetupClaimed(r.Context()) claimed, err := s.isSetupClaimed(r.Context())
@@ -795,11 +875,6 @@ func (s *Service) Status(w http.ResponseWriter, r *http.Request) {
writeProxyError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) writeProxyError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error())
return return
} }
loginRequired, err := s.LoginRequired(r.Context())
if err != nil {
writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
writeProxyJSON(w, http.StatusOK, map[string]any{ writeProxyJSON(w, http.StatusOK, map[string]any{
"setupRequired": setupRequired, "authenticated": user != nil, "authRequired": loginRequired, "user": user, "setupRequired": setupRequired, "authenticated": user != nil, "authRequired": loginRequired, "user": user,
}) })
@@ -938,7 +1013,7 @@ func (s *Service) ManagedDeleteUser(w http.ResponseWriter, r *http.Request) {
// why this needs a small local claim flag instead of a count-based check. // why this needs a small local claim flag instead of a count-based check.
func (s *Service) Signup(w http.ResponseWriter, r *http.Request) { func (s *Service) Signup(w http.ResponseWriter, r *http.Request) {
if !s.enabled() { if !s.enabled() {
user := localProfile user := adminProfile
writeProxyJSON(w, http.StatusCreated, map[string]any{"user": &user}) writeProxyJSON(w, http.StatusCreated, map[string]any{"user": &user})
return return
} }
@@ -1017,7 +1092,7 @@ func (s *Service) Signup(w http.ResponseWriter, r *http.Request) {
func (s *Service) Login(w http.ResponseWriter, r *http.Request) { func (s *Service) Login(w http.ResponseWriter, r *http.Request) {
if !s.enabled() { if !s.enabled() {
user := localProfile user := adminProfile
writeProxyJSON(w, http.StatusOK, map[string]any{"user": &user}) writeProxyJSON(w, http.StatusOK, map[string]any{"user": &user})
return return
} }
+47 -4
View File
@@ -14,7 +14,7 @@ type fakeProxyStore struct {
setupClaimed bool setupClaimed bool
} }
func (s *fakeProxyStore) LoginRequired(context.Context) (bool, error) { return s.loginRequired, nil } func (s *fakeProxyStore) LoginRequired(context.Context) (bool, error) { return s.loginRequired, nil }
func (s *fakeProxyStore) SetLoginRequired(_ context.Context, v bool) error { func (s *fakeProxyStore) SetLoginRequired(_ context.Context, v bool) error {
s.loginRequired = v s.loginRequired = v
return nil return nil
@@ -32,6 +32,10 @@ func (s *fakeProxyStore) UnclaimSetup(context.Context) error {
return nil return nil
} }
type noOpLoginProxyStore struct{ fakeProxyStore }
func (s *noOpLoginProxyStore) SetLoginRequired(context.Context, bool) error { return nil }
// TestPendingModeStillGatesRequests locks in the fix that made an empty // TestPendingModeStillGatesRequests locks in the fix that made an empty
// authGuardURL at construction mean "pending" (auth still enabled, calls // authGuardURL at construction mean "pending" (auth still enabled, calls
// fail closed until a real URL arrives via SetAuthGuardBaseURL) instead of // fail closed until a real URL arrives via SetAuthGuardBaseURL) instead of
@@ -39,7 +43,7 @@ func (s *fakeProxyStore) UnclaimSetup(context.Context) error {
// made AUTHGUARD_URL a de-facto requirement even though ProjectConfigurator // made AUTHGUARD_URL a de-facto requirement even though ProjectConfigurator
// can push it live after startup. // can push it live after startup.
func TestPendingModeStillGatesRequests(t *testing.T) { func TestPendingModeStillGatesRequests(t *testing.T) {
service := NewWithStore(&fakeProxyStore{}, "session", false, "", "testproject") service := NewWithStore(&fakeProxyStore{loginRequired: true}, "session", false, "", "testproject")
if !service.enabled() { if !service.enabled() {
t.Fatal("Service with no authGuardURL and no Disabled() option should still be enabled (pending), not disabled") t.Fatal("Service with no authGuardURL and no Disabled() option should still be enabled (pending), not disabled")
} }
@@ -60,8 +64,47 @@ func TestDisabledOptionSkipsGating(t *testing.T) {
} }
req := httptest.NewRequest(http.MethodGet, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
user, err := service.CurrentUser(req) user, err := service.CurrentUser(req)
if err != nil || user == nil || user.Username != "local" { if err != nil || user == nil || user.Username != "Admin" || !IsAdmin(user) {
t.Fatalf("Disabled() Service should resolve the fixed local superadmin profile, got user=%+v err=%v", user, err) t.Fatalf("Disabled() Service should resolve the fixed Admin superadmin profile, got user=%+v err=%v", user, err)
}
}
func TestLoginDisabledUsesAdminIdentityWithoutCredentials(t *testing.T) {
store := &fakeProxyStore{loginRequired: false}
service := NewWithStore(store, "session", false, "", "testproject")
req := httptest.NewRequest(http.MethodGet, "/", nil)
user, err := service.CurrentUser(req)
if err != nil || user == nil || user.Username != "Admin" || !IsAdmin(user) {
t.Fatalf("login-disabled Service should resolve the Admin identity, got user=%+v err=%v", user, err)
}
called := false
handler := service.RequireAdminIfLoginRequired(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
contextUser := UserFromContext(r.Context())
if contextUser == nil || contextUser.Username != "Admin" || !IsAdmin(contextUser) {
t.Errorf("middleware context user = %+v, want Admin superadmin", contextUser)
}
w.WriteHeader(http.StatusNoContent)
}))
response := httptest.NewRecorder()
handler.ServeHTTP(response, req)
if response.Code != http.StatusNoContent || !called {
t.Fatalf("login-disabled admin middleware status = %d/called=%v, want %d/true", response.Code, called, http.StatusNoContent)
}
}
func TestInternalLoginOverrideWorksWithNoOpStore(t *testing.T) {
store := &noOpLoginProxyStore{fakeProxyStore: fakeProxyStore{loginRequired: true}}
service := NewWithStore(store, "session", false, "", "testproject")
if err := service.SetLoginRequired(context.Background(), false); err != nil {
t.Fatalf("SetLoginRequired() error = %v", err)
}
user, err := service.CurrentUser(httptest.NewRequest(http.MethodGet, "/", nil))
if err != nil || user == nil || user.Username != "Admin" {
t.Fatalf("no-op store override resolved user=%+v err=%v, want Admin", user, err)
} }
} }
@@ -55,6 +55,7 @@ not a bug.
from __future__ import annotations from __future__ import annotations
import abc import abc
import os
from typing import Any, Callable, Optional from typing import Any, Callable, Optional
from fastapi import APIRouter, Depends, HTTPException, Request, Response 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." ERR_SECRET_NOT_SET = "SECRET environment variable is not set."
# _LOCAL_PROFILE is the fixed placeholder identity every handler reports when # _LOCAL_PROFILE is the fixed placeholder identity every handler reports when
# auth is disabled (get_client(request) returns None, i.e. AUTHGUARD_URL was # authentication is disabled, either because AUTHGUARD_URL is disabled or
# never configured). Role is superadmin so can_manage_users reports true, # because ProjectConfigurator has turned off this project's login requirement.
# consistent with "nothing gated": the frontend's own admin-only UI sections # Role is superadmin so all application routes see the same Admin identity even
# become visible too, even though the underlying admin endpoints have # though no credentials were supplied.
# nothing to manage.
_LOCAL_PROFILE = PublicUser( _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, secure_cookie: bool = False,
cookie_name: str = DEFAULT_COOKIE_NAME, cookie_name: str = DEFAULT_COOKIE_NAME,
configuration_error: str | None = None, configuration_error: str | None = None,
internal_secret: str | None = None,
) -> APIRouter: ) -> APIRouter:
"""Builds a ready-to-mount APIRouter implementing the full standardized """Builds a ready-to-mount APIRouter implementing the full standardized
AuthGuard-proxy surface (no prefix baked in - mount it at "/api/auth", 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.""" `get_client`/`get_store` contract."""
router = APIRouter() 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: def _ensure_configured() -> None:
if configuration_error: if configuration_error:
@@ -300,12 +305,18 @@ def build_auth_router(
raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED) raise HTTPException(status_code=401, detail=ERR_AUTH_REQUIRED)
return profile, token 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( async def require_session(
request: Request, request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> PublicUser: ) -> PublicUser:
"""FastAPI dependency gating a route behind a valid session.""" """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 return _LOCAL_PROFILE
assert client is not None assert client is not None
profile, _ = await _current_profile_or_401(request, client) profile, _ = await _current_profile_or_401(request, client)
@@ -313,13 +324,14 @@ def build_auth_router(
async def _require_user_manager( async def _require_user_manager(
request: Request, request: Request,
store: ProxyStore = Depends(get_store), # noqa: B008
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> str: ) -> str:
"""Returns the caller's session token, or "" in auth-disabled mode """Returns the caller's session token, or "" in auth-disabled mode
(each handler decides its own auth-disabled response). Authorization (each handler decides its own auth-disabled response). Authorization
(can_manage_users, "protect the superadmin") is enforced by (can_manage_users, "protect the superadmin") is enforced by
AuthGuard itself from the forwarded token.""" AuthGuard itself from the forwarded token."""
if not _enabled(client): if not _enabled(client) or not await _login_required(store):
return "" return ""
token = _session_token(request) token = _session_token(request)
if not token: if not token:
@@ -335,9 +347,11 @@ def build_auth_router(
client: Optional[AuthClient] = Depends(get_client), # noqa: B008 client: Optional[AuthClient] = Depends(get_client), # noqa: B008
) -> dict[str, Any]: ) -> dict[str, Any]:
_ensure_configured() _ensure_configured()
login_required = await store.login_required() login_required = await _login_required(store)
if not _enabled(client): 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 assert client is not None
try: try:
profile, _ = await _current_profile(request, client) profile, _ = await _current_profile(request, client)
@@ -355,6 +369,8 @@ def build_auth_router(
) -> dict[str, bool]: ) -> dict[str, bool]:
if not _enabled(client): if not _enabled(client):
return {"adminNeeded": False} return {"adminNeeded": False}
if not await _login_required(store):
return {"adminNeeded": False}
assert client is not None assert client is not None
if await store.is_setup_claimed(): if await store.is_setup_claimed():
return {"adminNeeded": False} return {"adminNeeded": False}
@@ -375,10 +391,18 @@ def build_auth_router(
return { return {
"setupRequired": False, "setupRequired": False,
"authenticated": True, "authenticated": True,
"authRequired": True, "authRequired": False,
"user": _user_payload(_LOCAL_PROFILE), "user": _user_payload(_LOCAL_PROFILE),
} }
assert client is not None 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() claimed = await store.is_setup_claimed()
setup_required = False setup_required = False
if not claimed: if not claimed:
@@ -390,7 +414,6 @@ def build_auth_router(
profile, _ = await _current_profile(request, client) profile, _ = await _current_profile(request, client)
except AuthClientError as exc: except AuthClientError as exc:
raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc raise HTTPException(status_code=500, detail=ERR_AUTHGUARD_UNAVAILABLE) from exc
login_required = await store.login_required()
return { return {
"setupRequired": setup_required, "setupRequired": setup_required,
"authenticated": profile is not None, "authenticated": profile is not None,
@@ -532,14 +555,29 @@ def build_auth_router(
@router.get("/access") @router.get("/access")
async def access_settings(store: ProxyStore = Depends(get_store)) -> dict[str, bool]: # noqa: B008 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") @router.put("/access")
async def update_access_settings( async def update_access_settings(
req: UpdateAccessRequest, req: UpdateAccessRequest,
store: ProxyStore = Depends(get_store), # noqa: B008 store: ProxyStore = Depends(get_store), # noqa: B008
) -> dict[str, bool]: ) -> dict[str, bool]:
nonlocal login_required_override
await store.set_login_required(req.loginRequired) 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} return {"loginRequired": req.loginRequired}
# --- admin user management ---------------------------------------------- # --- admin user management ----------------------------------------------
@@ -33,7 +33,12 @@ class _FakeStore(ap.ProxyStore):
self.claimed = False 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: def get_client(request: Request) -> AuthClient | None:
return client return client
@@ -41,7 +46,10 @@ def _build_app(store: ap.ProxyStore, client: AuthClient | None = None) -> FastAP
return store return store
app = FastAPI() 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 return app
@@ -68,7 +76,7 @@ class AuthDisabledModeTests(unittest.TestCase):
def test_me_reports_local_superadmin(self) -> None: def test_me_reports_local_superadmin(self) -> None:
body = self.client.get("/api/auth/me").json() 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: def test_setup_succeeds_as_a_no_op(self) -> None:
response = self.client.post( response = self.client.post(
@@ -113,6 +121,22 @@ class AccessSettingsTests(unittest.TestCase):
self.assertEqual(response.json(), {"loginRequired": False}) self.assertEqual(response.json(), {"loginRequired": False})
self.assertEqual(client.get("/api/auth/access").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): class _FakeClient(AuthClient):
"""Overrides just the methods build_auth_router calls, bypassing real """Overrides just the methods build_auth_router calls, bypassing real