Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Fix API auth failure handling
rcourtman649516cab429
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 0cda77e136..87fa5c191d 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -882,6 +882,11 @@ development-only admin bypass path. Lifecycle-adjacent setup or first-sessionflows may still run in non-release developer mode with `ALLOW_ADMIN_BYPASS`,but release binaries must compile that env override out instead of carrying aruntime branch that can be reopened after deployment.+That same shared auth dependency now also assumes direct auth probes fail+explicitly without overwriting narrower route-owned failures. Lifecycle-adjacent+setup-token, recovery, and install helpers may depend on shared auth wrappers,+but missing setup-token or API-token-only failures must preserve their specific+response instead of being flattened into a second generic auth body.Agent lifecycle owns the install/register/update continuity surfaces, but itdoes not own unified-resource history or control-plane timeline persistence.@@ -1478,6 +1483,10 @@ That same auth failure contract must also fail specifically on the canonicalsetup-token requirement: missing `authToken` input on `/api/auto-register` maynot collapse back to a generic authentication message once the route isgoverned as setup-token-only.+Shared router auth bypass for that setup-token route remains a handler-ownership+mechanism only: lifecycle-adjacent routes may bypass global auth so they can+return their route-specific setup-token failure, not so unauthenticated callers+can fall through to a successful lifecycle mutation.That same canonical request contract must also keep field-validation failuresspecific: mismatched `tokenId`/`tokenValue` input may not collapse intogeneric missing-field output, and other missing canonical fields must returndiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex d341f189ff..dfe63c0f26 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -301,6 +301,9 @@ the canonical monitored-system blocked payload.configured, anonymous fallback and bootstrap quick setup may run only on direct loopback, recovery tokens must bindto the generating client IP, and recovery may mint only a browser-bound localhost session rather than a sharedfilesystem toggle that disables auth for every loopback client.+ Direct `CheckAuth` callers must also fail explicitly: a non-loopback or missing-credential request may not fall+ through as a silent `200`, and middleware wrappers must use shared response capture so route-specific auth errors+ remain single-written rather than being replaced by a second generic auth body.The same shared auth boundary also owns release-build admin bypass gating.`internal/api/auth.go` may keep `ALLOW_ADMIN_BYPASS` for non-releasedevelopment workflows, but release builds must compile that env override@@ -729,12 +732,13 @@ only after canonical IDs have been resolved or a safe row-name fallback hasbeen chosen. API-adjacent browser callers must not reinterpret missing IDs orpreview arrays as authoritative empty success.Monitored-system commercial admission is now also part of that owned live-contract. Add and update routes must project prospective candidates or-previewed source records through the canonical monitored-system resolver-before persistence, and `/api/license/entitlements` must expose-`current_available` when an active monitored-system cap cannot resolve current-usage so callers can fail closed without misreading unavailable usage as a-real zero.+contract only when a hosted, MSP, or private policy installs an active cap.+Self-hosted Community/Relay/Pro core monitoring remains uncapped; any active+cap path must still project prospective candidates or previewed source records+through the canonical monitored-system resolver before persistence, and+`/api/license/entitlements` must expose `current_available` when that cap+cannot resolve current usage so callers can fail closed without misreading+unavailable usage as a real zero.That same `current_available` truth now includes supplemental-provider startupreadiness. API contracts must not serialize a live monitored-system count fromthe first store-backed read-state when provider-owned inventories such as@@ -1004,6 +1008,10 @@ browser/runtime value. The older `max_monitored_systems` label may be acceptedonly as a backward-compatible alias during request or callback normalization,but Pulse and the license server must not emit it as the primary self-hostedpurchase intent once the uncapped self-hosted model is canonical.+Compatibility-only Pro capabilities and legacy monitored-system aliases must+not become marketed upgrade reasons in the free-tier entitlement payload; the+payload should describe paid surfaces that are actually being sold rather than+recreating the retired monitored-infrastructure paywall.opener is available, the callback must still return the current tab to theowned billing route automatically instead of leaving the operator on a deadsuccess page.@@ -3177,6 +3185,10 @@ panicking on optional side effects. `/api/config/import` may be exercised fromproof or setup contexts that do not yet have every long-lived runtime managerwired, but the contract must still leave the imported configuration readablethrough the canonical API surface.+`/api/config/export` and `/api/config/import` are therefore router auth-bypass+entries only so their handlers can own stricter route-local auth and+public-network checks; global middleware must not preempt those handlers or+mask their public-network `403` outcomes with a generic auth failure.That same shared infrastructure-settings API contract now also owns theconnected-infrastructure distinction between machine-managed andplatform-connections-managed reporting. `frontend-modern/src/types/api.ts`,diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex 8599cdbd92..021268bbc7 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -155,6 +155,10 @@ regression protection.validate request-body setup tokens, but the router-level public-path check muststay O(1) and must not front-run persistence loads, monitor refresh, or otherteardown/register side effects before the canonical handler owns the request.+ `/api/config/export` and `/api/config/import` follow the same hot-path rule:+ router auth bypass exists only to let their handlers make route-local auth and+ public-network decisions, and the bypass check must remain a constant-time+ path comparison rather than a persistence-backed authorization probe.Agent-version signaling follows that same hot-path rule. Shared helpers usedby `/api/agent/version` and adjacent settings payloads may read the cachedprocess version once, but they must not add per-request release lookups,diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.mdindex b23da43dac..98ea24e2c4 100644--- a/docs/release-control/v6/internal/subsystems/security-privacy.md+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md@@ -302,6 +302,11 @@ persistence: `recovery_tokens.go` may mint raw recovery secrets for immediateoperator use, but persisted `recovery_tokens.json` state must store only tokenhashes and treat any legacy plaintext-token file as a one-time migration inputthat is rewritten immediately into hashed canonical persistence on load.+Direct auth probes on that same boundary must fail closed with an explicit+response: public-network or missing-credential calls into shared `CheckAuth`+must emit the canonical auth-required error, while middleware-owned paths use+shared response capture so setup, recovery, and API-token-specific handlers can+preserve their stricter single response.That same recovery trust boundary also governs live use of those secrets:recovery tokens must bind to the generating client IP, may authorize only adirect-loopback browser recovery session, and must not reopen authenticationdiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex fddbc47648..6152a1e761 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -117,6 +117,12 @@ querying, and the operator-facing storage health presentation layer.direct-loopback only, keep recovery-token validation bound to thegenerating client IP, and mint or clear browser recovery sessions insteadof toggling a shared `.auth_recovery` file for every localhost caller.+ Shared auth probes and router bypasses on that adjacent API boundary must+ preserve route ownership: missing credentials must return an explicit auth+ response, route-specific setup/recovery errors must not be overwritten by a+ second generic auth body, and `/api/config/export` or `/api/config/import`+ bypass entries must still leave public-network and credential decisions to+ their route-local handlers.That same adjacent API boundary also owns monitored-system admission previewtransport for provider-backed setup context. `/api/truenas/connections/preview`,`/api/truenas/connections/{id}/preview`, `/api/vmware/connections/preview`,diff --git a/internal/api/ai_handlers_patrol_test.go b/internal/api/ai_handlers_patrol_test.goindex 34d2361a27..ec5ed74285 100644--- a/internal/api/ai_handlers_patrol_test.go+++ b/internal/api/ai_handlers_patrol_test.go@@ -24,7 +24,7 @@ func TestAISettingsHandler_PatrolInterval_SpecificCheck(t *testing.T) {body, _ := json.Marshal(AISettingsUpdateRequest{PatrolIntervalMinutes: ptr(15),})- req := httptest.NewRequest(http.MethodPut, "/api/settings/ai", bytes.NewReader(body))+ req := newLoopbackRequest(http.MethodPut, "/api/settings/ai", bytes.NewReader(body))rec := httptest.NewRecorder()handler.HandleUpdateAISettings(rec, req)@@ -46,7 +46,7 @@ func TestAISettingsHandler_PatrolInterval_SpecificCheck(t *testing.T) {// Step 2: Verify persistence by fetching settings again{- req := httptest.NewRequest(http.MethodGet, "/api/settings/ai", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/settings/ai", nil)rec := httptest.NewRecorder()handler.HandleGetAISettings(rec, req)@@ -78,7 +78,7 @@ func TestAISettingsHandler_PatrolEnabled_ResponseReflectsToggleImmediately(t *tebody, _ := json.Marshal(AISettingsUpdateRequest{PatrolEnabled: ptr(false),})- req := httptest.NewRequest(http.MethodPut, "/api/settings/ai", bytes.NewReader(body))+ req := newLoopbackRequest(http.MethodPut, "/api/settings/ai", bytes.NewReader(body))rec := httptest.NewRecorder()handler.HandleUpdateAISettings(rec, req)if rec.Code != http.StatusOK {@@ -98,7 +98,7 @@ func TestAISettingsHandler_PatrolEnabled_ResponseReflectsToggleImmediately(t *tebody, _ := json.Marshal(AISettingsUpdateRequest{PatrolEnabled: ptr(true),})- req := httptest.NewRequest(http.MethodPut, "/api/settings/ai", bytes.NewReader(body))+ req := newLoopbackRequest(http.MethodPut, "/api/settings/ai", bytes.NewReader(body))rec := httptest.NewRecorder()handler.HandleUpdateAISettings(rec, req)if rec.Code != http.StatusOK {@@ -130,7 +130,7 @@ func TestAISettingsHandler_PatrolTriggerSettings_SplitAndLegacyCompatibility(t *PatrolAlertTriggersEnabled: ptr(false),PatrolAnomalyTriggersEnabled: ptr(true),})- req := httptest.NewRequest(http.MethodPut, "/api/settings/ai", bytes.NewReader(body))+ req := newLoopbackRequest(http.MethodPut, "/api/settings/ai", bytes.NewReader(body))rec := httptest.NewRecorder()handler.HandleUpdateAISettings(rec, req)if rec.Code != http.StatusOK {@@ -156,7 +156,7 @@ func TestAISettingsHandler_PatrolTriggerSettings_SplitAndLegacyCompatibility(t *body, _ := json.Marshal(AISettingsUpdateRequest{PatrolEventTriggersEnabled: ptr(false),})- req := httptest.NewRequest(http.MethodPut, "/api/settings/ai", bytes.NewReader(body))+ req := newLoopbackRequest(http.MethodPut, "/api/settings/ai", bytes.NewReader(body))rec := httptest.NewRecorder()handler.HandleUpdateAISettings(rec, req)if rec.Code != http.StatusOK {diff --git a/internal/api/ai_handlers_test.go b/internal/api/ai_handlers_test.goindex 5cd408050b..f13d303bbe 100644--- a/internal/api/ai_handlers_test.go+++ b/internal/api/ai_handlers_test.go@@ -102,7 +102,7 @@ func TestAISettingsHandler_GetAndUpdateSettings_RoundTrip(t *testing.T) {// GET should return defaults if no config has been saved yet.{- req := httptest.NewRequest(http.MethodGet, "/api/settings/ai", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/settings/ai", nil)rec := httptest.NewRecorder()handler.HandleGetAISettings(rec, req)@@ -134,7 +134,7 @@ func TestAISettingsHandler_GetAndUpdateSettings_RoundTrip(t *testing.T) {OllamaUsername: ptr("unai"),OllamaPassword: ptr("secret"),})- req := httptest.NewRequest(http.MethodPut, "/api/settings/ai", bytes.NewReader(body))+ req := newLoopbackRequest(http.MethodPut, "/api/settings/ai", bytes.NewReader(body))rec := httptest.NewRecorder()handler.HandleUpdateAISettings(rec, req)@@ -165,7 +165,7 @@ func TestAISettingsHandler_GetAndUpdateSettings_RoundTrip(t *testing.T) {// GET again should reflect persisted updates.{- req := httptest.NewRequest(http.MethodGet, "/api/settings/ai", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/settings/ai", nil)rec := httptest.NewRecorder()handler.HandleGetAISettings(rec, req)@@ -260,7 +260,7 @@ func TestAISettingsHandler_GetHostedSettings_AutoBootstrapsQuickstart(t *testinghandler := NewAISettingsHandler(mtp, nil, nil)handler.defaultConfig = &config.Config{DataPath: tmp}- req := httptest.NewRequest(http.MethodGet, "/api/settings/ai", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/settings/ai", nil)rec := httptest.NewRecorder()handler.HandleGetAISettings(rec, req)@@ -300,7 +300,7 @@ func TestAISettingsHandler_GetHostedTenantSettings_InheritsDefaultHostedBillingShandler := NewAISettingsHandler(mtp, nil, nil)handler.defaultConfig = &config.Config{DataPath: tmp}- req := httptest.NewRequest(http.MethodGet, "/api/settings/ai", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/settings/ai", nil)req = req.WithContext(context.WithValue(req.Context(), OrgIDContextKey, "t-tenant"))rec := httptest.NewRecorder()handler.HandleGetAISettings(rec, req)@@ -339,7 +339,7 @@ func TestAISettingsHandler_GetSettings_NormalizesLegacyQuickstartAliases(t *testhandler := NewAISettingsHandler(mtp, nil, nil)handler.defaultConfig = &config.Config{DataPath: tmp}- req := httptest.NewRequest(http.MethodGet, "/api/settings/ai", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/settings/ai", nil)rec := httptest.NewRecorder()handler.HandleGetAISettings(rec, req)@@ -365,7 +365,7 @@ func TestAISettingsHandler_GetSettings_QuickstartActivationRequiredSurface(t *tefunc() *config.AIConfig { return &config.AIConfig{Enabled: true} },))- req := httptest.NewRequest(http.MethodGet, "/api/settings/ai", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/settings/ai", nil)rec := httptest.NewRecorder()handler.HandleGetAISettings(rec, req)@@ -470,7 +470,7 @@ func TestAISettingsHandler_UpdateSettings_ResolvesProviderModelWhenOmitted(t *teEnabled: ptr(true),OllamaBaseURL: ptr(ollama.URL),})- req := httptest.NewRequest(http.MethodPut, "/api/settings/ai/update", bytes.NewReader(body))+ req := newLoopbackRequest(http.MethodPut, "/api/settings/ai/update", bytes.NewReader(body))rec := httptest.NewRecorder()handler.HandleUpdateAISettings(rec, req)@@ -503,7 +503,7 @@ func TestAISettingsHandler_UpdateSettings_OpenRouterKeySetAndClear(t *testing.T)OpenRouterAPIKey: ptr(" sk-or-test-key "),Model: ptr("openrouter:openai/gpt-4o-mini"),})- req := httptest.NewRequest(http.MethodPut, "/api/settings/ai/update", bytes.NewReader(body))+ req := newLoopbackRequest(http.MethodPut, "/api/settings/ai/update", bytes.NewReader(body))rec := httptest.NewRecorder()handler.HandleUpdateAISettings(rec, req)@@ -525,7 +525,7 @@ func TestAISettingsHandler_UpdateSettings_OpenRouterKeySetAndClear(t *testing.T)body, _ := json.Marshal(AISettingsUpdateRequest{ClearOpenRouterKey: ptr(true),})- req := httptest.NewRequest(http.MethodPut, "/api/settings/ai/update", bytes.NewReader(body))+ req := newLoopbackRequest(http.MethodPut, "/api/settings/ai/update", bytes.NewReader(body))rec := httptest.NewRecorder()handler.HandleUpdateAISettings(rec, req)@@ -575,7 +575,7 @@ func TestAISettingsHandler_ListModels_Ollama(t *testing.T) {handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodGet, "/api/ai/models", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/models", nil)rec := httptest.NewRecorder()handler.HandleListModels(rec, req)@@ -644,7 +644,7 @@ func TestAISettingsHandler_Execute_Ollama(t *testing.T) {handler := newTestAISettingsHandler(cfg, persistence, nil)body, _ := json.Marshal(AIExecuteRequest{Prompt: "hi"})- req := httptest.NewRequest(http.MethodPost, "/api/ai/execute", bytes.NewReader(body))+ req := newLoopbackRequest(http.MethodPost, "/api/ai/execute", bytes.NewReader(body))req = req.WithContext(context.Background())rec := httptest.NewRecorder()handler.HandleExecute(rec, req)@@ -692,7 +692,7 @@ func TestHandleExecute_RejectsLegacyHostTargetType(t *testing.T) {handler := newTestAISettingsHandler(cfg, persistence, nil)body := []byte(`{"prompt":"hi","target_type":"host","target_id":"agent-1"}`)- req := httptest.NewRequest(http.MethodPost, "/api/ai/execute", bytes.NewReader(body))+ req := newLoopbackRequest(http.MethodPost, "/api/ai/execute", bytes.NewReader(body))rec := httptest.NewRecorder()handler.HandleExecute(rec, req)@@ -711,7 +711,7 @@ func TestHandleExecuteStream_RejectsLegacyHostTargetType(t *testing.T) {handler := newTestAISettingsHandler(cfg, persistence, nil)body := []byte(`{"prompt":"hi","target_type":"host","target_id":"agent-1"}`)- req := httptest.NewRequest(http.MethodPost, "/api/ai/execute/stream", bytes.NewReader(body))+ req := newLoopbackRequest(http.MethodPost, "/api/ai/execute/stream", bytes.NewReader(body))rec := httptest.NewRecorder()handler.HandleExecuteStream(rec, req)@@ -846,7 +846,7 @@ func TestAISettingsHandler_TestConnection_Ollama(t *testing.T) {handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodPost, "/api/ai/test", nil)+ req := newLoopbackRequest(http.MethodPost, "/api/ai/test", nil)rec := httptest.NewRecorder()handler.HandleTestAIConnection(rec, req)@@ -909,7 +909,7 @@ func TestAISettingsHandler_TestProvider_Ollama(t *testing.T) {handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodPost, "/api/ai/test/ollama", nil)+ req := newLoopbackRequest(http.MethodPost, "/api/ai/test/ollama", nil)rec := httptest.NewRecorder()handler.HandleTestProvider(rec, req)@@ -944,7 +944,7 @@ func TestAISettingsHandler_TestConnection_MethodNotAllowed(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodGet, "/api/ai/test", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/test", nil)rec := httptest.NewRecorder()handler.HandleTestAIConnection(rec, req)@@ -974,7 +974,7 @@ func TestAISettingsHandler_TestConnection_Failure(t *testing.T) {handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodPost, "/api/ai/test", nil)+ req := newLoopbackRequest(http.MethodPost, "/api/ai/test", nil)rec := httptest.NewRecorder()handler.HandleTestAIConnection(rec, req)@@ -1000,7 +1000,7 @@ func TestAISettingsHandler_TestConnection_NoConfig(t *testing.T) {// Don't save any AI config — service will have no configured providerhandler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodPost, "/api/ai/test", nil)+ req := newLoopbackRequest(http.MethodPost, "/api/ai/test", nil)rec := httptest.NewRecorder()handler.HandleTestAIConnection(rec, req)@@ -1028,7 +1028,7 @@ func TestAISettingsHandler_TestProvider_MethodNotAllowed(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodGet, "/api/ai/test/ollama", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/test/ollama", nil)rec := httptest.NewRecorder()handler.HandleTestProvider(rec, req)@@ -1053,7 +1053,7 @@ func TestAISettingsHandler_TestProvider_NotConfigured(t *testing.T) {handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodPost, "/api/ai/test/openai", nil)+ req := newLoopbackRequest(http.MethodPost, "/api/ai/test/openai", nil)rec := httptest.NewRecorder()handler.HandleTestProvider(rec, req)@@ -1082,7 +1082,7 @@ func TestAISettingsHandler_TestProvider_NoAIConfig(t *testing.T) {// for the default (empty) config.handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodPost, "/api/ai/test/ollama", nil)+ req := newLoopbackRequest(http.MethodPost, "/api/ai/test/ollama", nil)rec := httptest.NewRecorder()handler.HandleTestProvider(rec, req)@@ -1122,7 +1122,7 @@ func TestAISettingsHandler_TestProvider_ConnectionFailure(t *testing.T) {handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodPost, "/api/ai/test/ollama", nil)+ req := newLoopbackRequest(http.MethodPost, "/api/ai/test/ollama", nil)rec := httptest.NewRecorder()handler.HandleTestProvider(rec, req)@@ -1151,7 +1151,7 @@ func TestHandleGetAICostSummary_MethodNotAllowed(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodPost, "/api/ai/cost/summary", nil)+ req := newLoopbackRequest(http.MethodPost, "/api/ai/cost/summary", nil)rec := httptest.NewRecorder()handler.HandleGetAICostSummary(rec, req)@@ -1168,7 +1168,7 @@ func TestHandleGetAICostSummary_NoAIService(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodGet, "/api/ai/cost/summary", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/cost/summary", nil)rec := httptest.NewRecorder()handler.HandleGetAICostSummary(rec, req)@@ -1196,7 +1196,7 @@ func TestHandleGetAICostSummary_CustomDays(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodGet, "/api/ai/cost/summary?days=7", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/cost/summary?days=7", nil)rec := httptest.NewRecorder()handler.HandleGetAICostSummary(rec, req)@@ -1224,7 +1224,7 @@ func TestHandleGetAICostSummary_MaxDays(t *testing.T) {handler := newTestAISettingsHandler(cfg, persistence, nil)// Test that days > 365 is capped at 365- req := httptest.NewRequest(http.MethodGet, "/api/ai/cost/summary?days=1000", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/cost/summary?days=1000", nil)rec := httptest.NewRecorder()handler.HandleGetAICostSummary(rec, req)@@ -1251,7 +1251,7 @@ func TestHandleGetAICostSummary_NegativeDays(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodGet, "/api/ai/cost/summary?days=-5", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/cost/summary?days=-5", nil)rec := httptest.NewRecorder()handler.HandleGetAICostSummary(rec, req)@@ -1278,7 +1278,7 @@ func TestHandleGetAICostSummary_ZeroDays(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodGet, "/api/ai/cost/summary?days=0", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/cost/summary?days=0", nil)rec := httptest.NewRecorder()handler.HandleGetAICostSummary(rec, req)@@ -1305,7 +1305,7 @@ func TestHandleGetAICostSummary_NonNumericDays(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodGet, "/api/ai/cost/summary?days=abc", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/cost/summary?days=abc", nil)rec := httptest.NewRecorder()handler.HandleGetAICostSummary(rec, req)@@ -1332,7 +1332,7 @@ func TestHandleGetAICostSummary_ResponseShape(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodGet, "/api/ai/cost/summary", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/cost/summary", nil)rec := httptest.NewRecorder()handler.HandleGetAICostSummary(rec, req)@@ -1387,7 +1387,7 @@ func TestHandleGetAICostSummary_NoService_InvalidDays(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- req := httptest.NewRequest(http.MethodGet, "/api/ai/cost/summary"+tt.query, nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/cost/summary"+tt.query, nil)rec := httptest.NewRecorder()handler.HandleGetAICostSummary(rec, req)@@ -1415,7 +1415,7 @@ func TestHandleGetAICostSummary_NoService_ResponseShape(t *testing.T) {// nil persistence → nil defaultAIService → exercises no-service stubhandler := newTestAISettingsHandler(cfg, nil, nil)- req := httptest.NewRequest(http.MethodGet, "/api/ai/cost/summary", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/cost/summary", nil)rec := httptest.NewRecorder()handler.HandleGetAICostSummary(rec, req)@@ -1479,7 +1479,7 @@ func TestHandleResetAICostHistory_MethodNotAllowed(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodGet, "/api/ai/cost/reset", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/cost/reset", nil)rec := httptest.NewRecorder()handler.HandleResetAICostHistory(rec, req)@@ -1496,7 +1496,7 @@ func TestHandleResetAICostHistory_Success(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodPost, "/api/ai/cost/reset", nil)+ req := newLoopbackRequest(http.MethodPost, "/api/ai/cost/reset", nil)rec := httptest.NewRecorder()handler.HandleResetAICostHistory(rec, req)@@ -1527,7 +1527,7 @@ func TestHandleExportAICostHistory_MethodNotAllowed(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodPost, "/api/ai/cost/export", nil)+ req := newLoopbackRequest(http.MethodPost, "/api/ai/cost/export", nil)rec := httptest.NewRecorder()handler.HandleExportAICostHistory(rec, req)@@ -1548,7 +1548,7 @@ func TestHandleGetSuppressionRules_MethodNotAllowed(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodPost, "/api/ai/patrol/suppressions", nil)+ req := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/suppressions", nil)rec := httptest.NewRecorder()handler.HandleGetSuppressionRules(rec, req)@@ -1569,7 +1569,7 @@ func TestHandleAddSuppressionRule_MethodNotAllowed(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodGet, "/api/ai/patrol/suppressions", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/patrol/suppressions", nil)rec := httptest.NewRecorder()handler.HandleAddSuppressionRule(rec, req)@@ -1590,7 +1590,7 @@ func TestHandleDeleteSuppressionRule_MethodNotAllowed(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodGet, "/api/ai/patrol/suppressions/rule-123", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/patrol/suppressions/rule-123", nil)rec := httptest.NewRecorder()handler.HandleDeleteSuppressionRule(rec, req)@@ -1611,7 +1611,7 @@ func TestHandleGetDismissedFindings_MethodNotAllowed(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodPost, "/api/ai/patrol/dismissed", nil)+ req := newLoopbackRequest(http.MethodPost, "/api/ai/patrol/dismissed", nil)rec := httptest.NewRecorder()handler.HandleGetDismissedFindings(rec, req)@@ -1637,7 +1637,7 @@ func TestHandleDebugContext_MethodNotAllowed(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodPost, "/api/ai/debug/context", nil)+ req := newLoopbackRequest(http.MethodPost, "/api/ai/debug/context", nil)rec := httptest.NewRecorder()handler.HandleDebugContext(rec, req)@@ -1658,7 +1658,7 @@ func TestHandleGetConnectedAgents_MethodNotAllowed(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodPost, "/api/ai/agents", nil)+ req := newLoopbackRequest(http.MethodPost, "/api/ai/agents", nil)rec := httptest.NewRecorder()handler.HandleGetConnectedAgents(rec, req)@@ -1676,7 +1676,7 @@ func TestHandleGetConnectedAgents_NoAgentServer(t *testing.T) {// handler created with nil agentServerhandler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodGet, "/api/ai/agents", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/agents", nil)rec := httptest.NewRecorder()handler.HandleGetConnectedAgents(rec, req)@@ -1711,7 +1711,7 @@ func TestHandleRunCommand_MethodNotAllowed(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodGet, "/api/ai/run-command", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/run-command", nil)rec := httptest.NewRecorder()handler.HandleRunCommand(rec, req)@@ -1728,7 +1728,7 @@ func TestHandleRunCommand_InvalidBody(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodPost, "/api/ai/run-command", bytes.NewReader([]byte(`{invalid json}`)))+ req := newLoopbackRequest(http.MethodPost, "/api/ai/run-command", bytes.NewReader([]byte(`{invalid json}`)))req.RemoteAddr = "127.0.0.1:12345"rec := httptest.NewRecorder()handler.HandleRunCommand(rec, req)@@ -1984,7 +1984,7 @@ func TestHandleAnalyzeKubernetesCluster_MethodNotAllowed(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodGet, "/api/ai/kubernetes/analyze", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/kubernetes/analyze", nil)rec := httptest.NewRecorder()handler.HandleAnalyzeKubernetesCluster(rec, req)@@ -2001,7 +2001,7 @@ func TestHandleAnalyzeKubernetesCluster_InvalidBody(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodPost, "/api/ai/kubernetes/analyze", bytes.NewReader([]byte(`{invalid json}`)))+ req := newLoopbackRequest(http.MethodPost, "/api/ai/kubernetes/analyze", bytes.NewReader([]byte(`{invalid json}`)))rec := httptest.NewRecorder()handler.HandleAnalyzeKubernetesCluster(rec, req)@@ -2022,7 +2022,7 @@ func TestHandleInvestigateAlert_MethodNotAllowed(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodGet, "/api/ai/investigate", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/investigate", nil)rec := httptest.NewRecorder()handler.HandleInvestigateAlert(rec, req)@@ -2039,7 +2039,7 @@ func TestHandleInvestigateAlert_InvalidBody(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodPost, "/api/ai/investigate", bytes.NewReader([]byte(`{invalid json}`)))+ req := newLoopbackRequest(http.MethodPost, "/api/ai/investigate", bytes.NewReader([]byte(`{invalid json}`)))rec := httptest.NewRecorder()handler.HandleInvestigateAlert(rec, req)@@ -2057,7 +2057,7 @@ func TestHandleInvestigateAlert_MissingAlertIdentifier(t *testing.T) {handler := newTestAISettingsHandler(cfg, persistence, nil)body := []byte(`{}`)- req := httptest.NewRequest(http.MethodPost, "/api/ai/investigate", bytes.NewReader(body))+ req := newLoopbackRequest(http.MethodPost, "/api/ai/investigate", bytes.NewReader(body))rec := httptest.NewRecorder()handler.HandleInvestigateAlert(rec, req)@@ -2077,7 +2077,7 @@ func TestHandleInvestigateAlert_RejectsLegacyHostResourceType(t *testing.T) {handler := newTestAISettingsHandler(cfg, persistence, nil)body := []byte(`{"alertIdentifier":"alert-1","resource_id":"agent-1","resource_name":"node-1","resource_type":"host","alert_type":"cpu","level":"warning","message":"high cpu"}`)- req := httptest.NewRequest(http.MethodPost, "/api/ai/investigate", bytes.NewReader(body))+ req := newLoopbackRequest(http.MethodPost, "/api/ai/investigate", bytes.NewReader(body))rec := httptest.NewRecorder()handler.HandleInvestigateAlert(rec, req)@@ -2097,7 +2097,7 @@ func TestHandleInvestigateAlert_AcceptsCanonicalAlertIdentifier(t *testing.T) {handler := newTestAISettingsHandler(cfg, persistence, nil)body := []byte(`{"alertIdentifier":"instance:node:100::metric/cpu","resource_id":"agent-1","resource_name":"node-1","resource_type":"host","alert_type":"cpu","level":"warning","message":"high cpu"}`)- req := httptest.NewRequest(http.MethodPost, "/api/ai/investigate", bytes.NewReader(body))+ req := newLoopbackRequest(http.MethodPost, "/api/ai/investigate", bytes.NewReader(body))rec := httptest.NewRecorder()handler.HandleInvestigateAlert(rec, req)@@ -2238,7 +2238,7 @@ func TestAISettingsHandler_Approvals(t *testing.T) {})t.Run("HandleGetApproval", func(t *testing.T) {- req := httptest.NewRequest(http.MethodGet, "/api/ai/approvals/"+appID, nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/approvals/"+appID, nil)rec := httptest.NewRecorder()handler.HandleGetApproval(rec, req)@@ -2250,7 +2250,7 @@ func TestAISettingsHandler_Approvals(t *testing.T) {})t.Run("HandleListApprovals", func(t *testing.T) {- req := httptest.NewRequest(http.MethodGet, "/api/ai/approvals", nil)+ req := newLoopbackRequest(http.MethodGet, "/api/ai/approvals", nil)rec := httptest.NewRecorder()handler.HandleListApprovals(rec, req)@@ -2267,7 +2267,7 @@ func TestAISettingsHandler_Approvals(t *testing.T) {})t.Run("HandleApproveCommand", func(t *testing.T) {- req := httptest.NewRequest(http.MethodPost, "/api/ai/approvals/"+appID+"/approve", nil)+ req := newLoopbackRequest(http.MethodPost, "/api/ai/approvals/"+appID+"/approve", nil)rec := httptest.NewRecorder()handler.HandleApproveCommand(rec, req)@@ -2285,7 +2285,7 @@ func TestAISettingsHandler_Approvals(t *testing.T) {})body, _ := json.Marshal(map[string]string{"reason": "too dangerous"})- req := httptest.NewRequest(http.MethodPost, "/api/ai/approvals/"+appID2+"/deny", bytes.NewReader(body))+ req := newLoopbackRequest(http.MethodPost, "/api/ai/approvals/"+appID2+"/deny", bytes.NewReader(body))rec := httptest.NewRecorder()handler.HandleDenyCommand(rec, req)@@ -2303,7 +2303,7 @@ func TestAISettingsHandler_Approvals(t *testing.T) {Status: approval.StatusPending,})- req := httptest.NewRequest(http.MethodPost, "/api/ai/approvals/"+appID3+"/approve", nil)+ req := newLoopbackRequest(http.MethodPost, "/api/ai/approvals/"+appID3+"/approve", nil)record := config.APITokenRecord{ID: "relay-mobile-approve", Scopes: []string{config.ScopeRelayMobileAccess}}attachAPITokenRecord(req, &record)rec := httptest.NewRecorder()@@ -2323,7 +2323,7 @@ func TestAISettingsHandler_Approvals(t *testing.T) {})body, _ := json.Marshal(map[string]string{"reason": "not now"})- req := httptest.NewRequest(http.MethodPost, "/api/ai/approvals/"+appID4+"/deny", bytes.NewReader(body))+ req := newLoopbackRequest(http.MethodPost, "/api/ai/approvals/"+appID4+"/deny", bytes.NewReader(body))record := config.APITokenRecord{ID: "relay-mobile-deny", Scopes: []string{config.ScopeRelayMobileAccess}}attachAPITokenRecord(req, &record)rec := httptest.NewRecorder()@@ -2363,7 +2363,7 @@ func TestAISettingsHandler_Approvals_RejectCrossOrgAccess(t *testing.T) {Command: "ls -la",}))- getReq := withOrg(httptest.NewRequest(http.MethodGet, "/api/ai/approvals/cross-org-get", nil), "org-b")+ getReq := withOrg(newLoopbackRequest(http.MethodGet, "/api/ai/approvals/cross-org-get", nil), "org-b")getRec := httptest.NewRecorder()handler.HandleGetApproval(getRec, getReq)require.Equal(t, http.StatusNotFound, getRec.Code)@@ -2374,7 +2374,7 @@ func TestAISettingsHandler_Approvals_RejectCrossOrgAccess(t *testing.T) {Command: "uptime",}))- approveReq := withOrg(httptest.NewRequest(http.MethodPost, "/api/ai/approvals/cross-org-approve/approve", nil), "org-b")+ approveReq := withOrg(newLoopbackRequest(http.MethodPost, "/api/ai/approvals/cross-org-approve/approve", nil), "org-b")approveRec := httptest.NewRecorder()handler.HandleApproveCommand(approveRec, approveReq)require.Equal(t, http.StatusNotFound, approveRec.Code)@@ -2389,7 +2389,7 @@ func TestAISettingsHandler_Approvals_RejectCrossOrgAccess(t *testing.T) {}))denyReq := withOrg(- httptest.NewRequest(http.MethodPost, "/api/ai/approvals/cross-org-deny/deny", bytes.NewReader([]byte(`{"reason":"no"}`))),+ newLoopbackRequest(http.MethodPost, "/api/ai/approvals/cross-org-deny/deny", bytes.NewReader([]byte(`{"reason":"no"}`))),"org-b",)denyRec := httptest.NewRecorder()diff --git a/internal/api/auth.go b/internal/api/auth.goindex 48064b4c55..20f020426f 100644--- a/internal/api/auth.go+++ b/internal/api/auth.go@@ -553,8 +553,52 @@ func CheckProxyAuth(cfg *config.Config, r *http.Request) (bool, string, bool) {return true, username, isAdmin}-// CheckAuth checks both basic auth and API token+type responseCapture struct {+ http.ResponseWriter+ wrote bool+}++func (rc *responseCapture) WriteHeader(statusCode int) {+ if !rc.wrote {+ rc.wrote = true+ rc.ResponseWriter.WriteHeader(statusCode)+ }+}++func (rc *responseCapture) Write(b []byte) (int, error) {+ rc.wrote = true+ return rc.ResponseWriter.Write(b)+}++func wantsJSONAuthResponse(r *http.Request) bool {+ if r == nil {+ return false+ }+ if r.URL != nil && strings.HasPrefix(r.URL.Path, "/api/") {+ return true+ }+ return strings.Contains(r.Header.Get("Accept"), "application/json")+}++func writeAuthenticationRequired(w http.ResponseWriter, r *http.Request) {+ if w == nil {+ return+ }+ if wantsJSONAuthResponse(r) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusUnauthorized)+ _, _ = w.Write([]byte(`{"error":"Authentication required"}`))+ return+ }+ http.Error(w, "Unauthorized", http.StatusUnauthorized)+}++// CheckAuth checks both basic auth and API token.func CheckAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request) bool {+ return checkAuth(cfg, w, r, true)+}++func checkAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request, writeDefaultFailure bool) bool {// Dev mode bypass for all auth (disabled by default)if adminBypassEnabled() {if w != nil {@@ -895,6 +939,9 @@ func CheckAuth(cfg *config.Config, w http.ResponseWriter, r *http.Request) bool}}+ if writeDefaultFailure {+ writeAuthenticationRequired(w, r)+ }return false}@@ -910,7 +957,8 @@ func RequireAuth(cfg *config.Config, handler http.HandlerFunc) http.HandlerFuncreturn}- if CheckAuth(cfg, w, r) {+ authWriter := &responseCapture{ResponseWriter: w}+ if checkAuth(cfg, authWriter, r, false) {handler(w, r)return}@@ -922,15 +970,10 @@ func RequireAuth(cfg *config.Config, handler http.HandlerFunc) http.HandlerFuncStr("method", r.Method).Msg("Unauthorized access attempt")- // Never send WWW-Authenticate header - we want to use our custom login page- // The frontend will detect 401 responses and show the login component- // Return JSON error for API requests, plain text for others- if strings.HasPrefix(r.URL.Path, "/api/") || strings.Contains(r.Header.Get("Accept"), "application/json") {- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(http.StatusUnauthorized)- w.Write([]byte(`{"error":"Authentication required"}`))- } else {- http.Error(w, "Unauthorized", http.StatusUnauthorized)+ if !authWriter.wrote {+ // Never send WWW-Authenticate header - we want to use our custom login page.+ // The frontend will detect 401 responses and show the login component.+ writeAuthenticationRequired(w, r)}}}@@ -950,7 +993,8 @@ func RequireAdmin(cfg *config.Config, handler http.HandlerFunc) http.HandlerFunc}// First check if user is authenticated- if !CheckAuth(cfg, w, r) {+ authWriter := &responseCapture{ResponseWriter: w}+ if !checkAuth(cfg, authWriter, r, false) {// Log the failed attemptlog.Warn().Str("ip", r.RemoteAddr).@@ -958,13 +1002,8 @@ func RequireAdmin(cfg *config.Config, handler http.HandlerFunc) http.HandlerFuncStr("method", r.Method).Msg("Unauthorized access attempt")- // Return authentication error- if strings.HasPrefix(r.URL.Path, "/api/") || strings.Contains(r.Header.Get("Accept"), "application/json") {- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(http.StatusUnauthorized)- w.Write([]byte(`{"error":"Authentication required"}`))- } else {- http.Error(w, "Unauthorized", http.StatusUnauthorized)+ if !authWriter.wrote {+ writeAuthenticationRequired(w, r)}return}@@ -1008,13 +1047,16 @@ func RequireAdmin(cfg *config.Config, handler http.HandlerFunc) http.HandlerFuncfunc RequirePermission(cfg *config.Config, authorizer auth.Authorizer, action, resource string, next http.HandlerFunc) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {// First check if user is authenticated (using RequireAdmin logic as base)- if !CheckAuth(cfg, w, r) {- if strings.HasPrefix(r.URL.Path, "/api/") || strings.Contains(r.Header.Get("Accept"), "application/json") {- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(http.StatusUnauthorized)- w.Write([]byte(`{"error":"authentication_required","message":"Authentication required"}`))- } else {- http.Error(w, "Unauthorized", http.StatusUnauthorized)+ authWriter := &responseCapture{ResponseWriter: w}+ if !checkAuth(cfg, authWriter, r, false) {+ if !authWriter.wrote {+ if wantsJSONAuthResponse(r) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(http.StatusUnauthorized)+ w.Write([]byte(`{"error":"authentication_required","message":"Authentication required"}`))+ } else {+ http.Error(w, "Unauthorized", http.StatusUnauthorized)+ }}return}diff --git a/internal/api/auth_helpers_test.go b/internal/api/auth_helpers_test.goindex c34c95f215..0d64a29733 100644--- a/internal/api/auth_helpers_test.go+++ b/internal/api/auth_helpers_test.go@@ -4,6 +4,7 @@ import ("crypto/tls""net/http""net/http/httptest"+ "strings""testing""time"@@ -1036,4 +1037,10 @@ func TestCheckAuth_NoAuthConfiguredRejectsRemote(t *testing.T) {if CheckAuth(cfg, w, req) {t.Fatal("CheckAuth should reject remote access before auth is configured")}+ if w.Code != http.StatusUnauthorized {+ t.Fatalf("expected explicit unauthorized response, got %d: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "Authentication required") {+ t.Fatalf("expected authentication-required body, got %q", w.Body.String())+ }}diff --git a/internal/api/cloud_org_admin_auth.go b/internal/api/cloud_org_admin_auth.goindex 64395ece61..7adde78a2f 100644--- a/internal/api/cloud_org_admin_auth.go+++ b/internal/api/cloud_org_admin_auth.go@@ -25,13 +25,10 @@ func RequirePlatformAdmin(cfg *config.Config, handler http.HandlerFunc) http.Hanreturn}- if !CheckAuth(cfg, w, r) {- if strings.HasPrefix(r.URL.Path, "/api/") || strings.Contains(r.Header.Get("Accept"), "application/json") {- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(http.StatusUnauthorized)- _, _ = w.Write([]byte(`{"error":"Authentication required"}`))- } else {- http.Error(w, "Unauthorized", http.StatusUnauthorized)+ authWriter := &responseCapture{ResponseWriter: w}+ if !checkAuth(cfg, authWriter, r, false) {+ if !authWriter.wrote {+ writeAuthenticationRequired(w, r)}return}@@ -90,14 +87,11 @@ func RequireOrgOwnerOrPlatformAdmin(cfg *config.Config, orgs OrgPersistenceProvi// Authenticate first. We intentionally do not reuse RequireAdmin because// RequireAdmin treats *all* authenticated non-proxy users as "admin".- if !CheckAuth(cfg, w, r) {+ authWriter := &responseCapture{ResponseWriter: w}+ if !checkAuth(cfg, authWriter, r, false) {// Match RequireAdmin's behavior for API routes.- if strings.HasPrefix(r.URL.Path, "/api/") || strings.Contains(r.Header.Get("Accept"), "application/json") {- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(http.StatusUnauthorized)- _, _ = w.Write([]byte(`{"error":"Authentication required"}`))- } else {- http.Error(w, "Unauthorized", http.StatusUnauthorized)+ if !authWriter.wrote {+ writeAuthenticationRequired(w, r)}return}diff --git a/internal/api/config_handlers_update_test.go b/internal/api/config_handlers_update_test.goindex cd284eaced..923101fff3 100644--- a/internal/api/config_handlers_update_test.go+++ b/internal/api/config_handlers_update_test.go@@ -171,7 +171,7 @@ func TestHandleUpdateNode(t *testing.T) {}}-func TestHandleUpdateNode_BlocksProjectedNetNewSystemAtLimit(t *testing.T) {+func TestHandleUpdateNode_AllowsProjectedNetNewSystemWithoutPaidLimit(t *testing.T) {setMaxMonitoredSystemsLicenseForTests(t, 1)cfg := &config.Config{@@ -236,10 +236,10 @@ func TestHandleUpdateNode_BlocksProjectedNetNewSystemAtLimit(t *testing.T) {handler.HandleUpdateNode(rec, req)- if rec.Code != http.StatusPaymentRequired {- t.Fatalf("expected 402 when update would add a new monitored system, got %d: %s", rec.Code, rec.Body.String())+ if rec.Code != http.StatusOK {+ t.Fatalf("expected update to remain allowed without monitored-system paid limits, got %d: %s", rec.Code, rec.Body.String())}- if got := cfg.PVEInstances[0].Host; got != "https://tower.local:8006" {- t.Fatalf("expected blocked update to preserve original host, got %q", got)+ if got := cfg.PVEInstances[0].Host; got != "https://backup.local:8006" {+ t.Fatalf("expected update to apply new host without paid limit enforcement, got %q", got)}}diff --git a/internal/api/connections_grouping_test.go b/internal/api/connections_grouping_test.goindex 0ab7a0d285..ee86a860c0 100644--- a/internal/api/connections_grouping_test.go+++ b/internal/api/connections_grouping_test.go@@ -141,6 +141,11 @@ func TestBuildConnectionSystems_ClusterMemberAgentsAttachToOwningProxmoxSystem(tLinkedNodeID: "node-delly",},},+ Identity: unified.ResourceIdentity{+ MachineID: "machine-delly",+ Hostnames: []string{"delly"},+ IPAddresses: []string{"192.168.0.10"},+ },},{SourceID: "node-minipc",@@ -171,6 +176,11 @@ func TestBuildConnectionSystems_ClusterMemberAgentsAttachToOwningProxmoxSystem(tLinkedNodeID: "node-minipc",},},+ Identity: unified.ResourceIdentity{+ MachineID: "machine-minipc",+ Hostnames: []string{"minipc"},+ IPAddresses: []string{"192.168.0.11"},+ },},})setTestUnexportedField(t, monitor, "resourceStore", monitoring.ResourceStoreInterface(adapter))diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 42872cc05a..85c08cc282 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -304,7 +304,7 @@ func TestContract_AISettingsUpdateQuickstartBootstrapJSONSnapshot(t *testing.T)},))- req := httptest.NewRequest(http.MethodPut, "/api/settings/ai/update", strings.NewReader(`{+ req := newLoopbackRequest(http.MethodPut, "/api/settings/ai/update", strings.NewReader(`{"enabled": true}`))req.Header.Set("Content-Type", "application/json")@@ -376,7 +376,7 @@ func TestContract_AISettingsUpdateProviderResolutionJSONSnapshot(t *testing.T) {persistence := config.NewConfigPersistence(tmp)handler := newTestAISettingsHandler(cfg, persistence, nil)- req := httptest.NewRequest(http.MethodPut, "/api/settings/ai/update", strings.NewReader(fmt.Sprintf(`{+ req := newLoopbackRequest(http.MethodPut, "/api/settings/ai/update", strings.NewReader(fmt.Sprintf(`{"enabled": true,"ollama_base_url": %q}`, ollama.URL)))diff --git a/internal/api/entitlement_handlers_test.go b/internal/api/entitlement_handlers_test.goindex 68af458188..983c478066 100644--- a/internal/api/entitlement_handlers_test.go+++ b/internal/api/entitlement_handlers_test.go@@ -65,10 +65,11 @@ func TestBuildEntitlementPayload_FreeTier(t *testing.T) {payload := buildEntitlementPayload(status, "")- // Upgrade reasons should cover every Pro feature not in Free.- proMinusFree := countProMinusFreeFeatures()- if len(payload.UpgradeReasons) != proMinusFree {- t.Fatalf("expected %d upgrade reasons for free tier, got %d", proMinusFree, len(payload.UpgradeReasons))+ // Upgrade reasons should cover marketed upgrade surfaces, not every+ // compatibility-only capability that may exist in the Pro feature set.+ wantReasons := pkglicensing.GenerateUpgradeReasons(status.Features)+ if len(payload.UpgradeReasons) != len(wantReasons) {+ t.Fatalf("expected %d upgrade reasons for free tier, got %d", len(wantReasons), len(payload.UpgradeReasons))}for _, reason := range payload.UpgradeReasons {if reason.ActionURL == "" {diff --git a/internal/api/monitored_system_limit_enforcement_test.go b/internal/api/monitored_system_limit_enforcement_test.goindex 7bb9d57a7d..cbc6d5c35f 100644--- a/internal/api/monitored_system_limit_enforcement_test.go+++ b/internal/api/monitored_system_limit_enforcement_test.go@@ -287,8 +287,9 @@ func TestMonitoredSystemAdmissionSurfacesStayBehindSharedLimitGate(t *testing.T){file: "config_handlers_update_test.go",snippets: []string{- "TestHandleUpdateNode_BlocksProjectedNetNewSystemAtLimit",- "http.StatusPaymentRequired",+ "TestHandleUpdateNode_AllowsProjectedNetNewSystemWithoutPaidLimit",+ "without paid limit enforcement",+ "http.StatusOK",},},},@@ -308,9 +309,6 @@ func TestMonitoredSystemAdmissionSurfacesStayBehindSharedLimitGate(t *testing.T)requiredCounts: map[string]int{"enforceMonitoredSystemLimitForConfigRegistration(": 2,},- requiredOrderings: [][2]string{- {"enforceMonitoredSystemLimitForConfigRegistration(", "PVEInstances = append"},- },}},proofs: []proofContract{{file: "config_handlers_auto_register_test.go",diff --git a/internal/api/rbac_test.go b/internal/api/rbac_test.goindex dd4a956adb..6952f83929 100644--- a/internal/api/rbac_test.go+++ b/internal/api/rbac_test.go@@ -47,7 +47,7 @@ func TestRequirePermission(t *testing.T) {w.WriteHeader(http.StatusOK)})- req := httptest.NewRequest("GET", "/api/test", nil)+ req := newLoopbackRequest("GET", "/api/test", nil)// Mock authentication bypass or setup// Since CheckAuth is internal, we might need a way to mock it or set up what it expects.// For this test, let's assume CheckAuth passes if no auth is configured.@@ -70,7 +70,7 @@ func TestRequirePermission(t *testing.T) {w.WriteHeader(http.StatusOK)})- req := httptest.NewRequest("POST", "/api/test", nil)+ req := newLoopbackRequest("POST", "/api/test", nil)rr := httptest.NewRecorder()handler.ServeHTTP(rr, req)@@ -94,7 +94,7 @@ func TestRequirePermission(t *testing.T) {})// req with no auth -> CheckAuth sets "anonymous"- req := httptest.NewRequest("GET", "/api/test", nil)+ req := newLoopbackRequest("GET", "/api/test", nil)rr := httptest.NewRecorder()handler.ServeHTTP(rr, req)diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.goindex c471784fc0..ae4446c10c 100644--- a/internal/api/route_inventory_test.go+++ b/internal/api/route_inventory_test.go@@ -266,6 +266,7 @@ var publicRouteAllowlist = []string{"/api/security/status","/api/security/validate-bootstrap-token","/api/security/quick-setup",+ "/api/security/recovery","/api/login","/api/public/signup","/api/public/magic-link/request",@@ -274,6 +275,8 @@ var publicRouteAllowlist = []string{"/api/ai/oauth/callback","/api/webhooks/stripe","/api/setup-script",+ "/api/config/export",+ "/api/config/import","/api/system/verify-temperature-ssh","/api/system/ssh-config","/api/auto-register",@@ -486,7 +489,9 @@ var allRouteAllowlist = []string{"DELETE /api/org-invitations/{id}","GET /api/orgs/{id}/shares","GET /api/orgs/{id}/shares/incoming",+ "POST /api/orgs/{id}/shares/incoming/{shareId}/accept","POST /api/orgs/{id}/shares",+ "DELETE /api/orgs/{id}/shares/incoming/{shareId}","DELETE /api/orgs/{id}/shares/{shareId}","GET /api/audit","GET /api/audit/",diff --git a/internal/api/router.go b/internal/api/router.goindex 91866861b4..a1235121f4 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -953,19 +953,16 @@ func (r *Router) handleVerifyTemperatureSSH(w http.ResponseWriter, req *http.Req}// Require authentication- if !CheckAuth(r.config, w, req) {+ authWriter := &responseCapture{ResponseWriter: w}+ if !checkAuth(r.config, authWriter, req, false) {log.Warn().Str("ip", req.RemoteAddr).Str("path", req.URL.Path).Str("method", req.Method).Msg("Unauthorized access attempt (verify-temperature-ssh)")- if strings.HasPrefix(req.URL.Path, "/api/") || strings.Contains(req.Header.Get("Accept"), "application/json") {- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(http.StatusUnauthorized)- w.Write([]byte(`{"error":"Authentication required"}`))- } else {- http.Error(w, "Unauthorized", http.StatusUnauthorized)+ if !authWriter.wrote {+ writeAuthenticationRequired(w, req)}return}@@ -1004,19 +1001,16 @@ func (r *Router) handleSSHConfig(w http.ResponseWriter, req *http.Request) {}// Require authentication- if !CheckAuth(r.config, w, req) {+ authWriter := &responseCapture{ResponseWriter: w}+ if !checkAuth(r.config, authWriter, req, false) {log.Warn().Str("ip", req.RemoteAddr).Str("path", req.URL.Path).Str("method", req.Method).Msg("Unauthorized access attempt (ssh-config)")- if strings.HasPrefix(req.URL.Path, "/api/") || strings.Contains(req.Header.Get("Accept"), "application/json") {- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(http.StatusUnauthorized)- w.Write([]byte(`{"error":"Authentication required"}`))- } else {- http.Error(w, "Unauthorized", http.StatusUnauthorized)+ if !authWriter.wrote {+ writeAuthenticationRequired(w, req)}return}@@ -3568,6 +3562,10 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {isPublic = true}}+ if normalizedPath == "/api/config/export" || normalizedPath == "/api/config/import" {+ // These handlers apply stricter route-local auth and public-network checks.+ isPublic = true+ }// Auto-register endpoint needs to be public (validates tokens internally)// BUT the tokens must be generated by authenticated users via setup-script-url@@ -3587,21 +3585,19 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {}// Check auth for protected routes (only if auth is needed)- if needsAuth && !isPublic && !CheckAuth(r.config, w, req) {- // Never send WWW-Authenticate - use custom login page- // For API requests, return JSON- if strings.HasPrefix(req.URL.Path, "/api/") || strings.Contains(req.Header.Get("Accept"), "application/json") {- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(http.StatusUnauthorized)- w.Write([]byte(`{"error":"Authentication required"}`))- } else {- http.Error(w, "Authentication required", http.StatusUnauthorized)+ if needsAuth && !isPublic {+ authWriter := &responseCapture{ResponseWriter: w}+ if !checkAuth(r.config, authWriter, req, false) {+ if !authWriter.wrote {+ // Never send WWW-Authenticate - use custom login page.+ writeAuthenticationRequired(w, req)+ }+ log.Warn().+ Str("ip", req.RemoteAddr).+ Str("path", req.URL.Path).+ Msg("Unauthorized access attempt")+ return}- log.Warn().- Str("ip", req.RemoteAddr).- Str("path", req.URL.Path).- Msg("Unauthorized access attempt")- return}}// Check CSRF for state-changing requests.@@ -4787,9 +4783,12 @@ func (r *Router) handleState(w http.ResponseWriter, req *http.Request) {}// Use standard auth check (supports both basic auth and API tokens) unless auth is disabled- if !CheckAuth(r.config, w, req) {- writeErrorResponse(w, http.StatusUnauthorized, "unauthorized",- "Authentication required", nil)+ authWriter := &responseCapture{ResponseWriter: w}+ if !checkAuth(r.config, authWriter, req, false) {+ if !authWriter.wrote {+ writeErrorResponse(w, http.StatusUnauthorized, "unauthorized",+ "Authentication required", nil)+ }return}diff --git a/internal/api/router_auth_bypass_inventory_test.go b/internal/api/router_auth_bypass_inventory_test.goindex c4e3e00bc1..606d6a817d 100644--- a/internal/api/router_auth_bypass_inventory_test.go+++ b/internal/api/router_auth_bypass_inventory_test.go@@ -75,6 +75,8 @@ func parseAuthBypassPaths(t *testing.T) []string {var authBypassAllowlist = []string{"/api/auto-register","/api/auto-unregister",+ "/api/config/export",+ "/api/config/import","/api/setup-script","/api/system/ssh-config","/api/system/verify-temperature-ssh",diff --git a/internal/api/router_public_paths_inventory_test.go b/internal/api/router_public_paths_inventory_test.goindex 452a126e07..3496cd0a82 100644--- a/internal/api/router_public_paths_inventory_test.go+++ b/internal/api/router_public_paths_inventory_test.go@@ -107,6 +107,7 @@ var publicPathsDynamicAllowlist = []string{}var publicPathsAllowlist = []string{"/api/health","/api/security/status",+ "/api/security/recovery","/api/security/validate-bootstrap-token","/api/security/quick-setup","/api/version",diff --git a/internal/api/router_routes_ai_execute_test.go b/internal/api/router_routes_ai_execute_test.goindex 0d1ec1a92a..57de16153f 100644--- a/internal/api/router_routes_ai_execute_test.go+++ b/internal/api/router_routes_ai_execute_test.go@@ -113,7 +113,7 @@ func TestRouteExecute_NoAuth(t *testing.T) {router.Handler().ServeHTTP(rec, req)assert.Equal(t, http.StatusUnauthorized, rec.Code, "unauthenticated request should return 401")- assert.Contains(t, rec.Body.String(), "Authentication required", "body should indicate authentication is needed")+ assert.Contains(t, rec.Body.String(), "API token required", "body should indicate token authentication is needed")}// TestRouteExecute_WrongScope verifies that a token without the ai:executediff --git a/internal/api/router_routes_debug_test.go b/internal/api/router_routes_debug_test.goindex a06390c209..84a0ea3032 100644--- a/internal/api/router_routes_debug_test.go+++ b/internal/api/router_routes_debug_test.go@@ -59,7 +59,7 @@ func TestPprofEndpoints_AdminAccessSucceeds(t *testing.T) {r.registerDebugRoutes()// /debug/pprof/ (index) should return 200 when no auth is configured- req := httptest.NewRequest(http.MethodGet, "/debug/pprof/", nil)+ req := newLoopbackRequest(http.MethodGet, "/debug/pprof/", nil)rec := httptest.NewRecorder()r.mux.ServeHTTP(rec, req)@@ -77,7 +77,7 @@ func TestPprofEndpoints_SymbolPost(t *testing.T) {}r.registerDebugRoutes()- req := httptest.NewRequest(http.MethodPost, "/debug/pprof/symbol", nil)+ req := newLoopbackRequest(http.MethodPost, "/debug/pprof/symbol", nil)rec := httptest.NewRecorder()r.mux.ServeHTTP(rec, req)@@ -95,7 +95,7 @@ func TestPprofEndpoints_HeapProfile(t *testing.T) {}r.registerDebugRoutes()- req := httptest.NewRequest(http.MethodGet, "/debug/pprof/heap", nil)+ req := newLoopbackRequest(http.MethodGet, "/debug/pprof/heap", nil)rec := httptest.NewRecorder()r.mux.ServeHTTP(rec, req)@@ -118,7 +118,7 @@ func TestPprofEndpoints_RoutingPrefix(t *testing.T) {}r.registerDebugRoutes()- req := httptest.NewRequest(http.MethodGet, "/debug/pprof/goroutine?debug=1", nil)+ req := newLoopbackRequest(http.MethodGet, "/debug/pprof/goroutine?debug=1", nil)rec := httptest.NewRecorder()r.mux.ServeHTTP(rec, req)diff --git a/internal/api/security_regression_test.go b/internal/api/security_regression_test.goindex 5c4c4b21ab..4368ebfba0 100644--- a/internal/api/security_regression_test.go+++ b/internal/api/security_regression_test.go@@ -1757,6 +1757,36 @@ func TestSystemSettingsUpdateRequiresSettingsWriteScope(t *testing.T) {}}+func TestSystemSettingsUpdatePreservesAPIOnlyAuthError(t *testing.T) {+ rawToken := "system-settings-api-only-token-123.12345678"+ record := newTokenRecord(t, rawToken, []string{config.ScopeSettingsWrite}, nil)+ cfg := newTestConfigWithTokens(t, record)+ handler := NewSystemSettingsHandler(+ cfg,+ config.NewConfigPersistence(cfg.DataPath),+ nil,+ nil,+ nil,+ func() {},+ func() error { return nil },+ )++ req := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(`{}`))+ rec := httptest.NewRecorder()+ handler.HandleUpdateSystemSettings(rec, req)++ if rec.Code != http.StatusUnauthorized {+ t.Fatalf("expected 401 for missing API token, got %d", rec.Code)+ }+ body := rec.Body.String()+ if !strings.Contains(body, "API token required") {+ t.Fatalf("expected API-token-specific auth response, got %q", body)+ }+ if strings.Contains(body, `"unauthorized"`) {+ t.Fatalf("expected route to preserve API-token-specific auth response, got generic body %q", body)+ }+}+func TestMockModeReadRequiresSettingsReadScope(t *testing.T) {rawToken := "mock-mode-read-token-123.12345678"record := newTokenRecord(t, rawToken, []string{config.ScopeMonitoringRead}, nil)diff --git a/internal/api/security_setup_fix.go b/internal/api/security_setup_fix.goindex 37a93435e3..cfcbf9d2af 100644--- a/internal/api/security_setup_fix.go+++ b/internal/api/security_setup_fix.go@@ -118,23 +118,6 @@ func ensureSettingsWriteScope(cfg *config.Config, w http.ResponseWriter, req *ht}// handleQuickSecuritySetupFixed is the fixed version of the Quick Security Setup-type responseCapture struct {- http.ResponseWriter- wrote bool-}--func (rc *responseCapture) WriteHeader(statusCode int) {- if !rc.wrote {- rc.wrote = true- }- rc.ResponseWriter.WriteHeader(statusCode)-}--func (rc *responseCapture) Write(b []byte) (int, error) {- rc.wrote = true- return rc.ResponseWriter.Write(b)-}-func handleQuickSecuritySetupFixed(r *Router) http.HandlerFunc {return func(w http.ResponseWriter, req *http.Request) {if req.Method != http.MethodPost {@@ -196,7 +179,7 @@ func handleQuickSecuritySetupFixed(r *Router) http.HandlerFunc {// Only require authentication if credentials are already configured.if !authorized && authConfigured {wrapped := &responseCapture{ResponseWriter: w}- if CheckAuth(r.config, wrapped, req) {+ if checkAuth(r.config, wrapped, req, false) {// If proxy auth is configured, require admin role for changes.if r.config.ProxyAuthSecret != "" {if valid, username, isAdmin := CheckProxyAuth(r.config, req); valid && !isAdmin {diff --git a/internal/api/security_setup_fix_additional_test.go b/internal/api/security_setup_fix_additional_test.goindex 4d79b25a75..7eaf7abde2 100644--- a/internal/api/security_setup_fix_additional_test.go+++ b/internal/api/security_setup_fix_additional_test.go@@ -54,10 +54,9 @@ func TestHandleRegenerateAPIToken_DoesNotRequireEnvFile(t *testing.T) {router := &Router{config: cfg}handler := http.HandlerFunc(router.HandleRegenerateAPIToken)- authLimiter.Reset("198.51.100.9")+ authLimiter.Reset("127.0.0.1")- req := httptest.NewRequest(http.MethodPost, "/api/security/regenerate-token", nil)- req.RemoteAddr = "198.51.100.9:54321"+ req := newLoopbackRequest(http.MethodPost, "/api/security/regenerate-token", nil)rec := httptest.NewRecorder()handler.ServeHTTP(rec, req)@@ -82,10 +81,9 @@ func TestHandleValidateAPIToken_InvalidJSON(t *testing.T) {router := &Router{config: &config.Config{}}handler := http.HandlerFunc(router.HandleValidateAPIToken)- authLimiter.Reset("198.51.100.10")+ authLimiter.Reset("127.0.0.1")- req := httptest.NewRequest(http.MethodPost, "/api/security/validate-token", strings.NewReader("not-json"))- req.RemoteAddr = "198.51.100.10:54321"+ req := newLoopbackRequest(http.MethodPost, "/api/security/validate-token", strings.NewReader("not-json"))rec := httptest.NewRecorder()handler.ServeHTTP(rec, req)@@ -99,10 +97,9 @@ func TestHandleValidateAPIToken_MissingToken(t *testing.T) {router := &Router{config: &config.Config{}}handler := http.HandlerFunc(router.HandleValidateAPIToken)- authLimiter.Reset("198.51.100.11")+ authLimiter.Reset("127.0.0.1")- req := httptest.NewRequest(http.MethodPost, "/api/security/validate-token", strings.NewReader(`{"token":""}`))- req.RemoteAddr = "198.51.100.11:54321"+ req := newLoopbackRequest(http.MethodPost, "/api/security/validate-token", strings.NewReader(`{"token":""}`))rec := httptest.NewRecorder()handler.ServeHTTP(rec, req)@@ -124,10 +121,9 @@ func TestHandleValidateAPIToken_NoTokensConfigured(t *testing.T) {router := &Router{config: &config.Config{}}handler := http.HandlerFunc(router.HandleValidateAPIToken)- authLimiter.Reset("198.51.100.12")+ authLimiter.Reset("127.0.0.1")- req := httptest.NewRequest(http.MethodPost, "/api/security/validate-token", strings.NewReader(`{"token":"abc"}`))- req.RemoteAddr = "198.51.100.12:54321"+ req := newLoopbackRequest(http.MethodPost, "/api/security/validate-token", strings.NewReader(`{"token":"abc"}`))rec := httptest.NewRecorder()handler.ServeHTTP(rec, req)diff --git a/internal/api/security_test.go b/internal/api/security_test.goindex f5544aef34..01914528de 100644--- a/internal/api/security_test.go+++ b/internal/api/security_test.go@@ -1551,7 +1551,7 @@ func TestRequireAdmin_NoAuthConfiguredAllowsAccess(t *testing.T) {})w := httptest.NewRecorder()- req := httptest.NewRequest("GET", "/api/admin/test", nil)+ req := newLoopbackRequest("GET", "/api/admin/test", nil)handler(w, req)if !handlerCalled {@@ -2030,7 +2030,7 @@ func TestRequireAuth_NoAuthConfiguredAllowsAccess(t *testing.T) {})w := httptest.NewRecorder()- req := httptest.NewRequest("GET", "/api/test", nil)+ req := newLoopbackRequest("GET", "/api/test", nil)handler(w, req)if !handlerCalled {diff --git a/internal/api/stripe_webhook_handlers_additional_test.go b/internal/api/stripe_webhook_handlers_additional_test.goindex 8cdf0784b5..e9df00f5aa 100644--- a/internal/api/stripe_webhook_handlers_additional_test.go+++ b/internal/api/stripe_webhook_handlers_additional_test.go@@ -215,8 +215,8 @@ func TestStripeWebhook_SubscriptionUpdated_RecognizesGrandfatheredRecurringPriceif state.SubscriptionState != entitlements.SubStateActive {t.Fatalf("subscription_state=%q, want %q", state.SubscriptionState, entitlements.SubStateActive)}- if got := state.Limits["max_monitored_systems"]; got != 10 {- t.Fatalf("limits[max_monitored_systems]=%d, want %d", got, 10)+ if got, ok := state.Limits["max_monitored_systems"]; ok && got != 0 {+ t.Fatalf("limits[max_monitored_systems]=%d, want uncapped/absent", got)}}diff --git a/internal/api/system_settings.go b/internal/api/system_settings.goindex ac38c535a6..2c60b89d77 100644--- a/internal/api/system_settings.go+++ b/internal/api/system_settings.go@@ -159,11 +159,11 @@ func (h *SystemSettingsHandler) SetConfig(cfg *config.Config) {func (h *SystemSettingsHandler) ensureWriteAccess(w http.ResponseWriter, r *http.Request) bool {// Require authentication- if !CheckAuth(h.config, w, r) {- // CheckAuth handles explicit failures (rate limits, invalid tokens)- // but returns false silently for missing credentials.- // We ensure a 401 is returned nicely even if we risk a double-write warning in rare cases.- writeErrorResponse(w, http.StatusUnauthorized, "unauthorized", "Unauthorized", nil)+ authWriter := &responseCapture{ResponseWriter: w}+ if !checkAuth(h.config, authWriter, r, false) {+ if !authWriter.wrote {+ writeErrorResponse(w, http.StatusUnauthorized, "unauthorized", "Unauthorized", nil)+ }return false}diff --git a/internal/api/system_settings_temperature_test.go b/internal/api/system_settings_temperature_test.goindex 34b2c20b5f..84da5ee146 100644--- a/internal/api/system_settings_temperature_test.go+++ b/internal/api/system_settings_temperature_test.go@@ -18,7 +18,7 @@ func TestHandleUpdateSystemSettingsAllowsTempsWithoutTransport(t *testing.T) {persistence := config.NewConfigPersistence(tempDir)handler := newTestSystemSettingsHandler(cfg, persistence, nil, nil, nil)- req := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", bytes.NewBufferString(`{"temperatureMonitoringEnabled":true}`))+ req := newLoopbackRequest(http.MethodPost, "/api/system/settings/update", bytes.NewBufferString(`{"temperatureMonitoringEnabled":true}`))rec := httptest.NewRecorder()handler.HandleUpdateSystemSettings(rec, req)@@ -41,7 +41,7 @@ func TestHandleUpdateSystemSettingsRejectsInvalidPVEPollingInterval(t *testing.Tpersistence := config.NewConfigPersistence(tempDir)handler := newTestSystemSettingsHandler(cfg, persistence, nil, nil, nil)- req := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(`{"pvePollingInterval":5}`))+ req := newLoopbackRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(`{"pvePollingInterval":5}`))rec := httptest.NewRecorder()handler.HandleUpdateSystemSettings(rec, req)@@ -65,7 +65,7 @@ func TestHandleUpdateSystemSettingsUpdatesPVEPollingInterval(t *testing.T) {return nil})- req := httptest.NewRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(`{"pvePollingInterval":30}`))+ req := newLoopbackRequest(http.MethodPost, "/api/system/settings/update", strings.NewReader(`{"pvePollingInterval":30}`))rec := httptest.NewRecorder()handler.HandleUpdateSystemSettings(rec, req)