Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

fix(api): log routine authorization refusals at debug, warn on the rate

rcourtman14a82e768439
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 29d487778e..31ef1eed45 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -5986,3 +5986,15 @@ Pinned by the capability cases in `useTrueNASSettingsPanelState.test.tsx` and
`useVMwareSettingsPanelState.test.tsx` (skipped when withheld, loads once when
the accessor flips) and by the discovery source pin in
`InfrastructureOperationsModel.test.tsx`.
+
+### API-layer refusal logging moved to debug
+
+`internal/api/` is a canonical reference in this contract's Extension Points, so
+this records the change made in `internal/api/auth.go`,
+`internal/api/middleware.go` and `internal/api/auth_denial_signal.go`: routine
+authorization refusals log at debug, and only an abnormal rate from one caller
+warns. Agent registration, capability, and lifecycle routes keep their existing
+status codes and payloads unchanged — an agent presenting insufficient
+credentials is refused exactly as before, it simply no longer emits a warn line
+per attempt. The security-privacy and api-contracts entries hold the
+authoritative description and proof.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 2b76fb7566..9901a5381c 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -9026,3 +9026,25 @@ halves: the served value for a `settings:read` token versus a
`monitoring:read` token, and that the routes agree with whichever value was
served. `TestSettingsCapabilitiesMatchRouteEnforcementWithoutRBAC` keeps the
withheld case honest against live 403s.
+
+### The API layer warns on faults, not on refusals
+
+`internal/api/middleware.go` logged every response `>= 400` at warn. That put an
+unauthenticated bootstrap request, an RBAC refusal, and a probe for an endpoint
+this build does not serve on the same footing as a handler panic, so a correctly
+configured instance could not produce a quiet log. The middleware now warns only
+on `5xx` — the class this build owns — and records `4xx` at debug.
+
+The auth wrappers in `internal/api/auth.go` (`RequireAuth`, `RequireAdmin`,
+`RequirePermission`) previously added a second warn line per refusal. They now
+route through `logAuthDenial` in `internal/api/auth_denial_signal.go`, which
+logs the refusal at debug and escalates once per window when one caller crosses
+a probing threshold. The security-privacy contract holds the authoritative
+description of that escalation.
+
+No route, status code, payload, or header changes: the same callers receive the
+same responses. `TestContract_AuthorizationRefusalKeepsStatusWhileLoggingAtDebug`
+pins that pairing directly — a scoped API token and a non-admin proxy session
+both still get 403, no warn line is emitted, and the refusal still leaves a
+debug-level trace — so a future attempt to quiet the log by relaxing enforcement
+fails the contract instead of passing it.
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 1c4dc689d8..97c07e3f1f 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -1980,3 +1980,40 @@ re-fetches the server version itself and runs the existing download, checksum,
and self-test pipeline before swapping binaries, so a stale or spoofed ack
version can at most trigger one extra validated check
(`TestRunLoopRunsCheckOnNudge`).
+
+### Routine authorization refusals log at debug; the rate is what warns
+
+`RequireAuth`, `RequireAdmin` and `RequirePermission` used to emit `log.Warn()`
+for every refusal — an unauthenticated caller before login, a non-admin on an
+admin route, an RBAC denial — and `internal/api/middleware.go` independently
+warned on *every* 4xx. A single refusal therefore produced two warn lines, and a
+correctly configured instance could not produce a quiet log. #1601's rc.9
+reporter read that stream as an RBAC regression.
+
+Refusals now route through `logAuthDenial`
+(`internal/api/auth_denial_signal.go`), which records the refusal at debug and
+counts it per caller. Attribution prefers the authenticated username so a
+principal is still tracked across rotating source addresses, falling back to
+`GetClientIP`. When one caller crosses `authDenialWarnThreshold` refusals inside
+`authDenialWindow`, exactly one warn is emitted for that window
+(`"Repeated authorization denials from one caller; possible endpoint probing"`),
+which is the shape that actually distinguishes probing from a UI mounting a
+surface its session cannot read. The tracked set is bounded by
+`authDenialMaxTracked` with oldest-window eviction so spoofed forwarded-for
+values cannot grow it without bound.
+
+The middleware now warns only on 5xx — a fault this build owns — and logs 4xx at
+debug.
+
+**Enforcement is unchanged.** Every route returns the same status to the same
+callers; only the log level and the escalation moved. Verified live on a
+proxy-auth instance: `/api/connections`, `/api/updates/status` and
+`/api/system/settings` still return 403 to a viewer and 200 to an admin, while
+an idle non-admin browser session produced zero warn lines across 90 seconds
+where it previously produced roughly one per refusal plus a paired
+`"Request failed"`.
+
+Pinned by `auth_denial_signal_test.go`: below-threshold refusals stay at debug,
+the escalation fires exactly once per window, a closed window re-arms it, a
+username aggregates across addresses, separate callers keep separate budgets,
+and the tracked set stays bounded.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 8726546fa1..690b8dd3a5 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -5064,3 +5064,12 @@ served by `GET /api/security/status` now carries `infrastructureRead`, derived
from `canAccessAdminSurface(config.ScopeSettingsRead)`. No recovery or storage
route, payload, or persisted shape changes. The api-contracts entry holds the
authoritative description and its proof.
+
+### API-layer refusal logging moved to debug
+
+`internal/api/` is a canonical reference in this contract's Extension Points.
+Routine authorization refusals raised by `internal/api/auth.go` and
+`internal/api/middleware.go` now log at debug, with a rate-based escalation in
+`internal/api/auth_denial_signal.go`. No recovery or storage route, payload, or
+persisted shape changes. The security-privacy and api-contracts entries hold the
+authoritative description and proof.
diff --git a/internal/api/auth.go b/internal/api/auth.go
index 711f25218b..60af743557 100644
--- a/internal/api/auth.go
+++ b/internal/api/auth.go
@@ -1024,12 +1024,9 @@ func RequireAuth(cfg *config.Config, handler http.HandlerFunc) http.HandlerFunc
return
}
- // Log the failed attempt
- log.Warn().
- Str("ip", r.RemoteAddr).
- Str("path", r.URL.Path).
- Str("method", r.Method).
- Msg("Unauthorized access attempt")
+ // An unauthenticated caller on a protected route is the expected outcome
+ // before login, not a fault. See logAuthDenial for the escalation rule.
+ logAuthDenial(r, "", "Unauthorized access attempt", nil)
if !authWriter.wrote {
// Never send WWW-Authenticate header - we want to use our custom login page.
@@ -1056,12 +1053,7 @@ func RequireAdmin(cfg *config.Config, handler http.HandlerFunc) http.HandlerFunc
// First check if user is authenticated
authWriter := &responseCapture{ResponseWriter: w}
if !checkAuth(cfg, authWriter, r, false) {
- // Log the failed attempt
- log.Warn().
- Str("ip", r.RemoteAddr).
- Str("path", r.URL.Path).
- Str("method", r.Method).
- Msg("Unauthorized access attempt")
+ logAuthDenial(r, "", "Unauthorized access attempt", nil)
if !authWriter.wrote {
writeAuthenticationRequired(w, r)
@@ -1073,13 +1065,10 @@ func RequireAdmin(cfg *config.Config, handler http.HandlerFunc) http.HandlerFunc
if cfg.ProxyAuthSecret != "" {
if valid, username, isAdmin := CheckProxyAuth(cfg, r); valid {
if !isAdmin {
- // User is authenticated but not an admin
- log.Warn().
- Str("ip", r.RemoteAddr).
- Str("path", r.URL.Path).
- Str("method", r.Method).
- Str("username", username).
- Msg("Non-admin user attempted to access admin endpoint")
+ // Authenticated, just not an admin. Every settings surface a
+ // non-admin UI still mounts lands here, so this must not warn
+ // per request; the rate escalation carries the security signal.
+ logAuthDenial(r, username, "Non-admin user attempted to access admin endpoint", nil)
// Return forbidden error
if strings.HasPrefix(r.URL.Path, "/api/") || strings.Contains(r.Header.Get("Accept"), "application/json") {
@@ -1134,13 +1123,9 @@ func RequirePermission(cfg *config.Config, authorizer auth.Authorizer, action, r
_, isDefaultAuth := authorizer.(*internalauth.DefaultAuthorizer)
if isDefaultAuth {
// No RBAC: non-admin proxy users are rejected
- log.Warn().
- Str("ip", r.RemoteAddr).
- Str("path", r.URL.Path).
- Str("action", action).
- Str("resource", resource).
- Str("username", username).
- Msg("Non-admin proxy user attempted to access permissioned endpoint (no RBAC active)")
+ logAuthDenial(r, username,
+ "Non-admin proxy user attempted to access permissioned endpoint (no RBAC active)",
+ map[string]string{"action": action, "resource": resource})
if strings.HasPrefix(r.URL.Path, "/api/") || strings.Contains(r.Header.Get("Accept"), "application/json") {
w.Header().Set("Content-Type", "application/json")
@@ -1202,13 +1187,8 @@ func RequirePermission(cfg *config.Config, authorizer auth.Authorizer, action, r
}
if !allowed {
- log.Warn().
- Str("user", username).
- Str("ip", r.RemoteAddr).
- Str("path", r.URL.Path).
- Str("action", action).
- Str("resource", resource).
- Msg("Forbidden access attempt (RBAC)")
+ logAuthDenial(r, username, "Forbidden access attempt (RBAC)",
+ map[string]string{"action": action, "resource": resource})
if strings.HasPrefix(r.URL.Path, "/api/") || strings.Contains(r.Header.Get("Accept"), "application/json") {
w.Header().Set("Content-Type", "application/json")
diff --git a/internal/api/auth_denial_signal.go b/internal/api/auth_denial_signal.go
new file mode 100644
index 0000000000..d150b91659
--- /dev/null
+++ b/internal/api/auth_denial_signal.go
@@ -0,0 +1,160 @@
+package api
+
+import (
+ "net/http"
+ "sort"
+ "sync"
+ "time"
+
+ "github.com/rs/zerolog/log"
+)
+
+// Routine authorization outcomes — an unauthenticated caller reaching a
+// protected route, or an authenticated non-admin reaching an admin one — are
+// the access control working as designed, not faults. Logging each one at warn
+// level meant a healthy instance could not produce a quiet log: a single idle
+// non-admin browser tab emitted a steady stream of "Non-admin user attempted to
+// access admin endpoint" lines, which #1601's rc.9 reporter read as an RBAC
+// regression.
+//
+// Individually these are debug-level facts. The thing actually worth warning an
+// operator about is an abnormal *rate* of refusals from one caller, which is
+// what credential stuffing and endpoint probing look like. So denials are
+// counted per caller per window and escalated once when they cross the
+// threshold, instead of every refusal shouting on its own.
+const (
+ authDenialWindow = time.Minute
+ authDenialWarnThreshold = 20
+ // Cap on tracked callers. A flood of spoofed forwarded-for values must not
+ // grow this map without bound; once full, untracked callers still log at
+ // debug level, they just do not contribute to the escalation signal.
+ authDenialMaxTracked = 4096
+)
+
+type authDenialCounter struct {
+ windowStart time.Time
+ count int
+ warned bool
+}
+
+var (
+ authDenialMu sync.Mutex
+ authDenials = make(map[string]*authDenialCounter)
+ // Test seam: the tracker is time-based, and tests must not sleep for a
+ // minute to exercise window rollover.
+ authDenialNow = time.Now
+)
+
+// authDenialKey identifies the caller a refusal is attributed to. A known
+// username survives IP rotation, so it is preferred; otherwise fall back to the
+// client IP.
+func authDenialKey(r *http.Request, identity string) string {
+ if identity != "" {
+ return "user:" + identity
+ }
+ if r == nil {
+ return "ip:unknown"
+ }
+ return "ip:" + GetClientIP(r)
+}
+
+// recordAuthDenial counts one refusal and reports whether this is the call that
+// pushed the caller over the probing threshold. It returns true at most once per
+// caller per window, so the escalation itself cannot become the new log spam.
+func recordAuthDenial(key string) (crossed bool, count int) {
+ now := authDenialNow()
+
+ authDenialMu.Lock()
+ defer authDenialMu.Unlock()
+
+ entry, ok := authDenials[key]
+ if !ok || now.Sub(entry.windowStart) >= authDenialWindow {
+ if !ok {
+ pruneAuthDenialsLocked(now)
+ entry = &authDenialCounter{}
+ authDenials[key] = entry
+ }
+ entry.windowStart = now
+ entry.count = 0
+ entry.warned = false
+ }
+
+ entry.count++
+ if entry.count >= authDenialWarnThreshold && !entry.warned {
+ entry.warned = true
+ return true, entry.count
+ }
+ return false, entry.count
+}
+
+// pruneAuthDenialsLocked drops counters whose window has closed. Callers must
+// hold authDenialMu.
+func pruneAuthDenialsLocked(now time.Time) {
+ for key, entry := range authDenials {
+ if now.Sub(entry.windowStart) >= authDenialWindow {
+ delete(authDenials, key)
+ }
+ }
+ if len(authDenials) < authDenialMaxTracked {
+ return
+ }
+ // Still over the cap with every window live: evict the oldest windows so a
+ // spoofed-key flood cannot pin newer callers out of the map.
+ keys := make([]string, 0, len(authDenials))
+ for key := range authDenials {
+ keys = append(keys, key)
+ }
+ sort.Slice(keys, func(i, j int) bool {
+ return authDenials[keys[i]].windowStart.Before(authDenials[keys[j]].windowStart)
+ })
+ for _, key := range keys[:len(authDenials)-authDenialMaxTracked/2] {
+ delete(authDenials, key)
+ }
+}
+
+// logAuthDenial records an expected authorization refusal. The refusal itself
+// goes to debug; only a caller crossing the probing threshold warns.
+func logAuthDenial(r *http.Request, identity, message string, fields map[string]string) {
+ event := log.Debug()
+ if r != nil {
+ event = event.
+ Str("ip", r.RemoteAddr).
+ Str("path", r.URL.Path).
+ Str("method", r.Method)
+ }
+ if identity != "" {
+ event = event.Str("username", identity)
+ }
+ for _, name := range sortedFieldNames(fields) {
+ event = event.Str(name, fields[name])
+ }
+ event.Msg(message)
+
+ crossed, count := recordAuthDenial(authDenialKey(r, identity))
+ if !crossed {
+ return
+ }
+
+ warn := log.Warn().
+ Int("denials", count).
+ Dur("window", authDenialWindow)
+ if r != nil {
+ warn = warn.Str("ip", GetClientIP(r)).Str("path", r.URL.Path)
+ }
+ if identity != "" {
+ warn = warn.Str("username", identity)
+ }
+ warn.Msg("Repeated authorization denials from one caller; possible endpoint probing")
+}
+
+func sortedFieldNames(fields map[string]string) []string {
+ if len(fields) == 0 {
+ return nil
+ }
+ names := make([]string, 0, len(fields))
+ for name := range fields {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+ return names
+}
diff --git a/internal/api/auth_denial_signal_test.go b/internal/api/auth_denial_signal_test.go
new file mode 100644
index 0000000000..4117406e47
--- /dev/null
+++ b/internal/api/auth_denial_signal_test.go
@@ -0,0 +1,158 @@
+package api
+
+import (
+ "bytes"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rs/zerolog"
+ "github.com/rs/zerolog/log"
+)
+
+// captureAuthDenialLogs swaps the global logger for a buffer at debug level and
+// resets the denial tracker, so each case starts from a known window.
+func captureAuthDenialLogs(t *testing.T) *bytes.Buffer {
+ t.Helper()
+
+ var buf bytes.Buffer
+ prevLogger := log.Logger
+ prevLevel := zerolog.GlobalLevel()
+ log.Logger = zerolog.New(&buf).Level(zerolog.DebugLevel)
+ zerolog.SetGlobalLevel(zerolog.DebugLevel)
+
+ authDenialMu.Lock()
+ authDenials = make(map[string]*authDenialCounter)
+ authDenialMu.Unlock()
+
+ prevNow := authDenialNow
+ t.Cleanup(func() {
+ log.Logger = prevLogger
+ zerolog.SetGlobalLevel(prevLevel)
+ authDenialNow = prevNow
+ authDenialMu.Lock()
+ authDenials = make(map[string]*authDenialCounter)
+ authDenialMu.Unlock()
+ })
+
+ return &buf
+}
+
+func countLevel(output, level string) int {
+ return strings.Count(output, `"level":"`+level+`"`)
+}
+
+// A non-admin browsing a UI that still mounts an admin-only surface produces a
+// steady trickle of refusals. Warning on each is what made #1601's rc.9 reporter
+// read a working RBAC gate as a break, so ordinary refusals must stay at debug.
+func TestAuthDenialBelowThresholdStaysDebug(t *testing.T) {
+ buf := captureAuthDenialLogs(t)
+ req := httptest.NewRequest("GET", "/api/connections", nil)
+
+ for i := 0; i < authDenialWarnThreshold-1; i++ {
+ logAuthDenial(req, "viewer", "Non-admin user attempted to access admin endpoint", nil)
+ }
+
+ output := buf.String()
+ if got := countLevel(output, "debug"); got != authDenialWarnThreshold-1 {
+ t.Fatalf("debug lines = %d, want %d", got, authDenialWarnThreshold-1)
+ }
+ if got := countLevel(output, "warn"); got != 0 {
+ t.Fatalf("warn lines = %d, want 0 below the probing threshold", got)
+ }
+}
+
+// The signal worth an operator's attention is the rate, not the individual
+// refusal — and the escalation must not itself become the new spam.
+func TestAuthDenialEscalatesOncePerWindow(t *testing.T) {
+ buf := captureAuthDenialLogs(t)
+ req := httptest.NewRequest("GET", "/api/connections", nil)
+
+ for i := 0; i < authDenialWarnThreshold*3; i++ {
+ logAuthDenial(req, "viewer", "Non-admin user attempted to access admin endpoint", nil)
+ }
+
+ output := buf.String()
+ if got := countLevel(output, "warn"); got != 1 {
+ t.Fatalf("warn lines = %d, want exactly 1 for a single window", got)
+ }
+ if !strings.Contains(output, "possible endpoint probing") {
+ t.Fatalf("escalation missing from output: %q", output)
+ }
+}
+
+func TestAuthDenialWindowRolloverRearmsEscalation(t *testing.T) {
+ buf := captureAuthDenialLogs(t)
+ req := httptest.NewRequest("GET", "/api/connections", nil)
+
+ base := time.Unix(1_700_000_000, 0)
+ authDenialNow = func() time.Time { return base }
+ for i := 0; i < authDenialWarnThreshold; i++ {
+ logAuthDenial(req, "viewer", "denied", nil)
+ }
+ if got := countLevel(buf.String(), "warn"); got != 1 {
+ t.Fatalf("first window warn lines = %d, want 1", got)
+ }
+
+ // A caller that goes quiet and starts probing again later is a fresh signal,
+ // not a permanently silenced one.
+ authDenialNow = func() time.Time { return base.Add(authDenialWindow + time.Second) }
+ for i := 0; i < authDenialWarnThreshold; i++ {
+ logAuthDenial(req, "viewer", "denied", nil)
+ }
+ if got := countLevel(buf.String(), "warn"); got != 2 {
+ t.Fatalf("warn lines after rollover = %d, want 2", got)
+ }
+}
+
+// Attribution follows the identity when there is one, so a probing account is
+// still caught after rotating source addresses.
+func TestAuthDenialTracksIdentityAcrossAddresses(t *testing.T) {
+ buf := captureAuthDenialLogs(t)
+
+ for i := 0; i < authDenialWarnThreshold; i++ {
+ req := httptest.NewRequest("GET", "/api/connections", nil)
+ req.RemoteAddr = "10.0.0." + string(rune('1'+i%9)) + ":5000"
+ logAuthDenial(req, "viewer", "denied", nil)
+ }
+
+ if got := countLevel(buf.String(), "warn"); got != 1 {
+ t.Fatalf("warn lines = %d, want 1 — identity should aggregate across addresses", got)
+ }
+}
+
+// Separate callers must not pool into one another's budget, or one busy client
+// would silence the signal for everybody else.
+func TestAuthDenialSeparatesCallers(t *testing.T) {
+ buf := captureAuthDenialLogs(t)
+ req := httptest.NewRequest("GET", "/api/connections", nil)
+
+ for i := 0; i < authDenialWarnThreshold-1; i++ {
+ logAuthDenial(req, "viewer-a", "denied", nil)
+ logAuthDenial(req, "viewer-b", "denied", nil)
+ }
+
+ if got := countLevel(buf.String(), "warn"); got != 0 {
+ t.Fatalf("warn lines = %d, want 0 — neither caller crossed the threshold", got)
+ }
+}
+
+func TestAuthDenialPruneKeepsTrackedSetBounded(t *testing.T) {
+ captureAuthDenialLogs(t)
+
+ base := time.Unix(1_700_000_000, 0)
+ authDenialNow = func() time.Time { return base }
+ for i := 0; i < authDenialMaxTracked+64; i++ {
+ req := httptest.NewRequest("GET", "/api/connections", nil)
+ logAuthDenial(req, "spoofed-"+strings.Repeat("x", i%7)+string(rune(i)), "denied", nil)
+ }
+
+ authDenialMu.Lock()
+ tracked := len(authDenials)
+ authDenialMu.Unlock()
+
+ if tracked > authDenialMaxTracked {
+ t.Fatalf("tracked callers = %d, want <= %d", tracked, authDenialMaxTracked)
+ }
+}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 497c82a940..cfca47cc78 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -61,6 +61,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"
"github.com/rcourtman/pulse-go-rewrite/pkg/reporting"
"github.com/rs/zerolog"
+ "github.com/rs/zerolog/log"
tmock "github.com/stretchr/testify/mock"
)
@@ -22646,3 +22647,81 @@ func TestContract_CheckoutStartSourceAttributionReachesHandoffNeverPortal(t *tes
})
}
}
+
+// The refusal itself is the contract; its log severity is not. This pins both
+// halves of the 2026-08-07 logging change together, because the tempting way to
+// quiet a noisy log is to stop refusing — a "fix" that would be a security
+// regression rather than an observability one.
+func TestContract_AuthorizationRefusalKeepsStatusWhileLoggingAtDebug(t *testing.T) {
+ rawToken := "contract-refusal-severity.12345678"
+ record := newTokenRecord(t, rawToken, []string{config.ScopeMonitoringRead}, nil)
+ cfg := newTestConfigWithTokens(t, record)
+ // Exercise the proxy-auth non-admin branch too: that is the exact line
+ // #1601's rc.9 reporter saw repeating.
+ cfg.ProxyAuthSecret = "contract-proxy-secret"
+ cfg.ProxyAuthUserHeader = "X-Remote-User"
+ cfg.ProxyAuthRoleHeader = "X-Remote-Role"
+ cfg.ProxyAuthAdminRole = "admin"
+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")
+
+ // Capture only the request phase — router construction emits unrelated
+ // startup warnings that have nothing to do with authorization.
+ var logBuf bytes.Buffer
+ prevLogger := log.Logger
+ prevLevel := zerolog.GlobalLevel()
+ log.Logger = zerolog.New(&logBuf).Level(zerolog.DebugLevel)
+ zerolog.SetGlobalLevel(zerolog.DebugLevel)
+
+ authDenialMu.Lock()
+ authDenials = make(map[string]*authDenialCounter)
+ authDenialMu.Unlock()
+
+ t.Cleanup(func() {
+ log.Logger = prevLogger
+ zerolog.SetGlobalLevel(prevLevel)
+ authDenialMu.Lock()
+ authDenials = make(map[string]*authDenialCounter)
+ authDenialMu.Unlock()
+ })
+
+ cases := []struct {
+ name string
+ path string
+ prepare func(*http.Request)
+ }{
+ {
+ name: "scoped api token",
+ path: "/api/connections",
+ prepare: func(r *http.Request) { r.Header.Set("X-API-Token", rawToken) },
+ },
+ {
+ name: "non-admin proxy session",
+ path: "/api/system/settings",
+ prepare: func(r *http.Request) {
+ r.Header.Set("X-Proxy-Secret", "contract-proxy-secret")
+ r.Header.Set("X-Remote-User", "viewer")
+ r.Header.Set("X-Remote-Role", "viewer")
+ },
+ },
+ }
+
+ for _, tc := range cases {
+ req := httptest.NewRequest(http.MethodGet, tc.path, nil)
+ tc.prepare(req)
+ rec := httptest.NewRecorder()
+ router.Handler().ServeHTTP(rec, req)
+ if rec.Code != http.StatusForbidden {
+ t.Fatalf("%s: GET %s = %d, want 403 — the refusal must survive the logging change",
+ tc.name, tc.path, rec.Code)
+ }
+ }
+
+ output := logBuf.String()
+ if strings.Contains(output, `"level":"warn"`) {
+ t.Fatalf("ordinary refusals emitted a warn line, which is the noise this change removed:\n%s", output)
+ }
+ // The refusal must still be recorded somewhere an operator can find it.
+ if !strings.Contains(output, `"status":403`) {
+ t.Fatalf("refusal left no debug-level trace at all:\n%s", output)
+ }
+}
diff --git a/internal/api/middleware.go b/internal/api/middleware.go
index e415fae831..0dc0d0cbca 100644
--- a/internal/api/middleware.go
+++ b/internal/api/middleware.go
@@ -94,9 +94,18 @@ func ErrorHandler(next http.Handler) http.Handler {
// Call the next handler
next.ServeHTTP(rw, r)
- // Log errors (4xx and 5xx)
+ // A 5xx is ours to explain, so it warns. A 4xx is the client being told
+ // no — an unauthenticated bootstrap request, an RBAC refusal, a probe for
+ // an endpoint this build does not serve — and warning on each one meant a
+ // correctly behaving instance could never produce a quiet log. Those go to
+ // debug; logAuthDenial carries the escalation for refusals that arrive at
+ // a rate worth an operator's attention.
if rw.statusCode >= 400 {
- log.Warn().
+ event := log.Debug()
+ if rw.statusCode >= 500 {
+ event = log.Warn()
+ }
+ event.
Str("path", r.URL.Path).
Str("method", r.Method).
Int("status", rw.statusCode).