High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: the front door still holds the boot config, so three settings report saved and never apply (PIN-276)
Luigi Agostid6ea5b670829
diff --git a/internal/config/live.go b/internal/config/live.goindex e887e5dd..7922e35e 100644--- a/internal/config/live.go+++ b/internal/config/live.go@@ -6,6 +6,23 @@ import "sync/atomic"// goroutine which built it. Holders keep the Live, never the *RuntimeConfig it// currently answers, so a save publishes a NEW value instead of writing the// fields of an object other goroutines are already reading.+//+// That is also the rule for anything BUILT ONCE and served for the life of the+// process — an HTTP middleware chain above all. A component that captured the+// *RuntimeConfig it was constructed with used to see saves, because a save wrote+// that object's fields; now it would enforce boot values forever while the+// dashboard reports the save as applied. Take the Live and resolve it per+// request; a nil Live answers nil, which every reader already handles.+//+// Two fields are excluded from that rule on provable properties rather than on+// expectations, and they are named here so the next holder knows which side it is+// on. BackgroundMarker exists only on RuntimeConfig, so no config file can carry+// it and no save can change it. Token cannot be written through the dashboard at+// all — PUT /api/config refuses a token write outright (token_write_only) — and+// the whole Security section is separately declared restart-required. Both are+// resolved per request anyway now that the chain reads through the Live; that is+// a consequence of one contract for the chain, not a change in what either can+// do.type Live struct {current atomic.Pointer[RuntimeConfig]}diff --git a/internal/dashboard/agent_session_api_integration_test.go b/internal/dashboard/agent_session_api_integration_test.goindex cf813ae7..88f5e668 100644--- a/internal/dashboard/agent_session_api_integration_test.go+++ b/internal/dashboard/agent_session_api_integration_test.go@@ -36,8 +36,7 @@ func TestAgentSessionAPI_Me_UsesContextSessionAfterMiddlewareAuth(t *testing.T)dashboard.NewSessionAPI(store, nil).RegisterHandlers(mux)sessionID, token, _ := store.Create("agent-1", "my-session", "")- handler := handlers.AuthMiddlewareWithSessions(- &config.RuntimeConfig{Token: "dashboard-token"},+ handler := handlers.AuthMiddlewareWithSessions(config.NewLive(&config.RuntimeConfig{Token: "dashboard-token"}),nil,store,http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {@@ -68,8 +67,7 @@ func TestAgentSessionAPI_Revoke_UsesContextSessionAfterMiddlewareAuth(t *testingdashboard.NewSessionAPI(store, nil).RegisterHandlers(mux)sessionID, token, _ := store.Create("agent-1", "", "")- handler := handlers.AuthMiddlewareWithSessions(- &config.RuntimeConfig{Token: "dashboard-token"},+ handler := handlers.AuthMiddlewareWithSessions(config.NewLive(&config.RuntimeConfig{Token: "dashboard-token"}),nil,store,http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.goindex d5b0184d..bc13d1de 100644--- a/internal/handlers/middleware.go+++ b/internal/handlers/middleware.go@@ -82,8 +82,16 @@ func LoggingMiddleware(next http.Handler) http.Handler {})}-func SecurityHeadersMiddleware(cfg *config.RuntimeConfig, next http.Handler) http.Handler {+// SecurityHeadersMiddleware and every other middleware here take the publication+// point rather than a config, and resolve it PER REQUEST. A middleware is built+// once at startup and serves for the life of the process, so one that closed over+// the boot *RuntimeConfig would enforce boot values forever: a save publishes a+// new value and never writes the old object. That froze trustProxyHeaders,+// cookieSecure and sessions.dashboard.requireElevation while the dashboard+// reported the save applied.+func SecurityHeadersMiddleware(live *config.Live, next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ cfg := live.Get()w.Header().Set("X-Content-Type-Options", "nosniff")w.Header().Set("X-Frame-Options", "DENY")w.Header().Set("Content-Security-Policy", defaultCSP)@@ -95,12 +103,13 @@ func SecurityHeadersMiddleware(cfg *config.RuntimeConfig, next http.Handler) htt})}-func AuthMiddleware(cfg *config.RuntimeConfig, next http.Handler) http.Handler {- return AuthMiddlewareWithSessions(cfg, nil, nil, next)+func AuthMiddleware(live *config.Live, next http.Handler) http.Handler {+ return AuthMiddlewareWithSessions(live, nil, nil, next)}-func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *browsersession.Manager, agentSessions *session.Store, next http.Handler) http.Handler {+func AuthMiddlewareWithSessions(live *config.Live, sessions *browsersession.Manager, agentSessions *session.Store, next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ cfg := live.Get()if isPublicDashboardPath(r.URL.Path) || isPublicAuthPath(r.URL.Path) {next.ServeHTTP(w, r)return@@ -109,6 +118,10 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *browsersessnext.ServeHTTP(w, r)return}+ if cfg == nil {+ httpx.ErrorCode(w, http.StatusServiceUnavailable, "token_required", "server token is not configured", false, nil)+ return+ }token := strings.TrimSpace(cfg.Token)if token == "" {httpx.ErrorCode(w, http.StatusServiceUnavailable, "token_required", "server token is not configured", false, nil)diff --git a/internal/handlers/middleware_cors.go b/internal/handlers/middleware_cors.goindex aff3196b..a0fab506 100644--- a/internal/handlers/middleware_cors.go+++ b/internal/handlers/middleware_cors.go@@ -8,8 +8,9 @@ import ("github.com/pinchtab/pinchtab/internal/httpx")-func CorsMiddleware(cfg *config.RuntimeConfig, next http.Handler) http.Handler {+func CorsMiddleware(live *config.Live, next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ cfg := live.Get()allowedOrigin := corsAllowedOrigin(cfg, r)if allowedOrigin != "" {w.Header().Set("Access-Control-Allow-Origin", allowedOrigin)@@ -21,7 +22,7 @@ func CorsMiddleware(cfg *config.RuntimeConfig, next http.Handler) http.Handler {w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")if r.Method == "OPTIONS" {- if strings.TrimSpace(r.Header.Get("Origin")) != "" && allowedOrigin == "" && strings.TrimSpace(cfg.Token) != "" {+ if strings.TrimSpace(r.Header.Get("Origin")) != "" && allowedOrigin == "" && cfg != nil && strings.TrimSpace(cfg.Token) != "" {httpx.ErrorCode(w, 403, "cors_forbidden", "cross-origin requests are disabled when auth is enabled", false, nil)return}@@ -34,7 +35,7 @@ func CorsMiddleware(cfg *config.RuntimeConfig, next http.Handler) http.Handler {func corsAllowedOrigin(cfg *config.RuntimeConfig, r *http.Request) string {origin := strings.TrimSpace(r.Header.Get("Origin"))- if origin == "" {+ if origin == "" || cfg == nil {return ""}if strings.TrimSpace(cfg.Token) == "" {diff --git a/internal/handlers/middleware_owned_headers_test.go b/internal/handlers/middleware_owned_headers_test.goindex 3df9c257..28b79595 100644--- a/internal/handlers/middleware_owned_headers_test.go+++ b/internal/handlers/middleware_owned_headers_test.go@@ -40,7 +40,7 @@ func TestTheOwnedResponseHeaderSetIsExactlyWhatTheOuterChainSets(t *testing.T) {}for _, r := range []*http.Request{plain, secure} {for _, name := range headersSetByMiddleware(t, func(next http.Handler) http.Handler {- return SecurityHeadersMiddleware(cfg, next)+ return SecurityHeadersMiddleware(config.NewLive(cfg), next)}, r) {set[name] = true}@@ -68,7 +68,7 @@ func TestTheOuterChainSetsItsHeadersSingleValued(t *testing.T) {req := httptest.NewRequest("GET", "/tabs", nil)req.TLS = &tls.ConnectionState{}- handler := RequestIDMiddleware(SecurityHeadersMiddleware(&config.RuntimeConfig{}, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {})))+ handler := RequestIDMiddleware(SecurityHeadersMiddleware(config.NewLive(&config.RuntimeConfig{}), http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {})))handler.ServeHTTP(rec, req)for _, name := range httpx.OuterChainResponseHeaders() {diff --git a/internal/handlers/middleware_test.go b/internal/handlers/middleware_test.goindex 232914ae..c0f6b212 100644--- a/internal/handlers/middleware_test.go+++ b/internal/handlers/middleware_test.go@@ -44,7 +44,7 @@ func TestAuthMiddleware_NoToken(t *testing.T) {cfg := &config.RuntimeConfig{Token: ""}called := false- handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddleware(config.NewLive(cfg), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(200)}))@@ -100,7 +100,7 @@ func TestSecurityHeadersMiddleware_AddsHSTSForTLS(t *testing.T) {}func TestSecurityHeadersMiddleware_UsesTrustedForwardedProtoForHSTS(t *testing.T) {- handler := SecurityHeadersMiddleware(&config.RuntimeConfig{TrustProxyHeaders: true}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := SecurityHeadersMiddleware(config.NewLive(&config.RuntimeConfig{TrustProxyHeaders: true}), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {w.WriteHeader(http.StatusOK)}))@@ -118,7 +118,7 @@ func TestAuthMiddleware_ValidToken(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123"}called := false- handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddleware(config.NewLive(cfg), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(200)}))@@ -137,7 +137,7 @@ func TestAuthMiddleware_AllowsBackgroundHealthProbeMarker(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123", BackgroundMarker: "marker-123"}called := false- handler := StripInternalHeadersMiddleware(AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := StripInternalHeadersMiddleware(AuthMiddleware(config.NewLive(cfg), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(http.StatusOK)})))@@ -159,7 +159,7 @@ func TestAuthMiddleware_RejectsWrongBackgroundHealthProbeMarker(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123", BackgroundMarker: "marker-123"}called := false- handler := StripInternalHeadersMiddleware(AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := StripInternalHeadersMiddleware(AuthMiddleware(config.NewLive(cfg), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(http.StatusOK)})))@@ -181,7 +181,7 @@ func TestAuthMiddleware_InvalidToken(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123"}called := false- handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddleware(config.NewLive(cfg), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = true}))@@ -204,7 +204,7 @@ func TestAuthMiddleware_InvalidToken(t *testing.T) {func TestAuthMiddleware_MissingTokenHeader(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123"}- handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddleware(config.NewLive(cfg), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {w.WriteHeader(200)}))@@ -229,7 +229,7 @@ func TestAuthMiddleware_ValidCookie(t *testing.T) {}called := false- handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(200)}))@@ -256,7 +256,7 @@ func TestAuthMiddleware_CookieRestrictedEndpointRejected(t *testing.T) {t.Fatalf("Create() error = %v", err)}called := false- handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(200)}))@@ -283,7 +283,7 @@ func TestAuthMiddleware_CookieAllowsTabCloseEndpoint(t *testing.T) {}called := false- handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(http.StatusOK)}))@@ -311,7 +311,7 @@ func TestAuthMiddleware_CookieAllowsActionEndpoint(t *testing.T) {}called := false- handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(http.StatusOK)}))@@ -339,7 +339,7 @@ func TestAuthMiddleware_CookieAllowsInstanceStartEndpoint(t *testing.T) {}called := false- handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(http.StatusOK)}))@@ -367,7 +367,7 @@ func TestAuthMiddleware_CookieCrossOriginRejected(t *testing.T) {}called := false- handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(http.StatusOK)}))@@ -395,7 +395,7 @@ func TestAuthMiddleware_CookieRequestWithoutOriginOrRefererRejected(t *testing.T}called := false- handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(http.StatusOK)}))@@ -422,7 +422,7 @@ func TestAuthMiddleware_CookieSameOriginRefererAccepted(t *testing.T) {}called := false- handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(http.StatusOK)}))@@ -450,7 +450,7 @@ func TestAuthMiddleware_CookieIgnoresForwardedOriginHints(t *testing.T) {}called := false- handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(http.StatusOK)}))@@ -481,7 +481,7 @@ func TestAuthMiddleware_CookieWebSocketRequiresSameOrigin(t *testing.T) {}called := false- handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(http.StatusOK)}))@@ -533,7 +533,7 @@ func TestAuthMiddleware_CookieElevatedEndpointRequiresElevation(t *testing.T) {}called := false- handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(http.StatusOK)}))@@ -579,7 +579,7 @@ func TestAuthMiddleware_CookieConfigEndpointDoesNotRequireElevationByDefault(t *}called := false- handler := AuthMiddlewareWithSessions(cfg, sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), sessions, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(http.StatusOK)}))@@ -601,7 +601,7 @@ func TestAuthMiddleware_CookieConfigEndpointDoesNotRequireElevationByDefault(t *func TestAuthMiddleware_HeaderAllowsRestrictedEndpoint(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123"}called := false- handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddleware(config.NewLive(cfg), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(200)}))@@ -623,7 +623,7 @@ func TestAuthMiddleware_QueryTokenRejected(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123"}called := false- handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddleware(config.NewLive(cfg), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(200)}))@@ -643,7 +643,7 @@ func TestAuthMiddleware_QueryTokenRejected(t *testing.T) {func TestAuthMiddleware_PublicDashboardPathBypassesAuth(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123"}called := false- handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddleware(config.NewLive(cfg), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(200)}))@@ -663,7 +663,7 @@ func TestAuthMiddleware_PublicDashboardPathBypassesAuth(t *testing.T) {func TestAuthMiddleware_PublicDashboardSubpathBypassesAuth(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123"}called := false- handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddleware(config.NewLive(cfg), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(200)}))@@ -683,7 +683,7 @@ func TestAuthMiddleware_PublicDashboardSubpathBypassesAuth(t *testing.T) {func TestAuthMiddleware_PublicAuthPathBypassesAuth(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123"}called := false- handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddleware(config.NewLive(cfg), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(200)}))@@ -702,7 +702,7 @@ func TestAuthMiddleware_PublicAuthPathBypassesAuth(t *testing.T) {func TestAuthMiddleware_ProtectedAPIStillRequiresAuth(t *testing.T) {cfg := &config.RuntimeConfig{Token: "secret123"}- handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddleware(config.NewLive(cfg), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {w.WriteHeader(200)}))@@ -737,7 +737,7 @@ func TestAuthMiddleware_TableDriven(t *testing.T) {t.Run(tt.name, func(t *testing.T) {cfg := &config.RuntimeConfig{Token: tt.token}called := false- handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddleware(config.NewLive(cfg), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(200)}))@@ -763,7 +763,7 @@ func TestAuthMiddleware_TableDriven(t *testing.T) {}func TestCorsMiddleware(t *testing.T) {- handler := CorsMiddleware(&config.RuntimeConfig{}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := CorsMiddleware(config.NewLive(&config.RuntimeConfig{}), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {w.WriteHeader(200)}))@@ -791,7 +791,7 @@ func TestCorsMiddleware(t *testing.T) {}func TestCorsMiddleware_AuthEnabledAllowsOnlySameOrigin(t *testing.T) {- handler := CorsMiddleware(&config.RuntimeConfig{Token: "secret"}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := CorsMiddleware(config.NewLive(&config.RuntimeConfig{Token: "secret"}), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {w.WriteHeader(200)}))@@ -813,7 +813,7 @@ func TestCorsMiddleware_AuthEnabledAllowsOnlySameOrigin(t *testing.T) {}func TestCorsMiddleware_AuthEnabledRejectsCrossOriginPreflight(t *testing.T) {- handler := CorsMiddleware(&config.RuntimeConfig{Token: "secret"}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := CorsMiddleware(config.NewLive(&config.RuntimeConfig{Token: "secret"}), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {w.WriteHeader(200)}))@@ -1202,7 +1202,7 @@ func TestAuthMiddleware_SessionAuth(t *testing.T) {cfg := &config.RuntimeConfig{Token: "server-token"}called := false- handler := AuthMiddlewareWithSessions(cfg, nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(200)}))@@ -1226,7 +1226,7 @@ func TestAuthMiddleware_SessionAuthRejectsDashboardAdminRoute(t *testing.T) {cfg := &config.RuntimeConfig{Token: "server-token"}called := false- handler := AuthMiddlewareWithSessions(cfg, nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(http.StatusOK)}))@@ -1250,7 +1250,7 @@ func TestAuthMiddleware_SessionAuthWithoutGrantsAllowsNonAdminRoutes(t *testing.cfg := &config.RuntimeConfig{Token: "server-token"}called := false- handler := AuthMiddlewareWithSessions(cfg, nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(http.StatusOK)}))@@ -1274,7 +1274,7 @@ func TestAuthMiddleware_SessionAuthAllowsRevokeRouteToReachHandler(t *testing.T)cfg := &config.RuntimeConfig{Token: "server-token"}called := false- handler := AuthMiddlewareWithSessions(cfg, nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(http.StatusOK)}))@@ -1301,7 +1301,7 @@ func TestAuthMiddleware_SessionAuthHonorsBrowseGrant(t *testing.T) {cfg := &config.RuntimeConfig{Token: "server-token"}called := false- handler := AuthMiddlewareWithSessions(cfg, nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(http.StatusOK)}))@@ -1328,7 +1328,7 @@ func TestAuthMiddleware_SessionAuthRejectsRouteOutsideGrant(t *testing.T) {cfg := &config.RuntimeConfig{Token: "server-token"}called := false- handler := AuthMiddlewareWithSessions(cfg, nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truew.WriteHeader(http.StatusOK)}))@@ -1354,7 +1354,7 @@ func TestAuthMiddleware_ForbiddenSessionRequestDoesNotExtendIdleLifetime(t *test}cfg := &config.RuntimeConfig{Token: "server-token"}- handler := AuthMiddlewareWithSessions(cfg, nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {w.WriteHeader(http.StatusOK)}))@@ -1387,7 +1387,7 @@ func TestAuthMiddleware_SessionAuthEnrichesActivity(t *testing.T) {rec := &activityCaptureRecorder{}cfg := &config.RuntimeConfig{Token: "server-token"}- handler := activity.Middleware(rec, "server", AuthMiddlewareWithSessions(cfg, nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := activity.Middleware(rec, "server", AuthMiddlewareWithSessions(config.NewLive(cfg), nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {w.WriteHeader(http.StatusOK)})))@@ -1419,7 +1419,7 @@ func TestAuthMiddleware_SessionAttachesAuthenticatedSessionToContext(t *testing.gotSession *session.Session)cfg := &config.RuntimeConfig{Token: "server-token"}- handler := AuthMiddlewareWithSessions(cfg, nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = truegotSession, _ = session.FromRequest(r)w.WriteHeader(http.StatusOK)@@ -1448,7 +1448,7 @@ func TestAuthMiddleware_HeaderAuthDoesNotAttachAgentSessionToContext(t *testing.cfg := &config.RuntimeConfig{Token: "server-token"}var gotSession *session.Session- handler := AuthMiddlewareWithSessions(cfg, nil, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), nil, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {gotSession, _ = session.FromRequest(r)w.WriteHeader(http.StatusOK)}))@@ -1471,7 +1471,7 @@ func TestAuthMiddleware_SessionAuthInvalid(t *testing.T) {cfg := &config.RuntimeConfig{Token: "server-token"}called := false- handler := AuthMiddlewareWithSessions(cfg, nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), nil, store, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = true}))@@ -1491,7 +1491,7 @@ func TestAuthMiddleware_SessionAuthInvalid(t *testing.T) {func TestAuthMiddleware_SessionAuthDisabled(t *testing.T) {cfg := &config.RuntimeConfig{Token: "server-token"}called := false- handler := AuthMiddlewareWithSessions(cfg, nil, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ handler := AuthMiddlewareWithSessions(config.NewLive(cfg), nil, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {called = true}))diff --git a/internal/handlers/screencast_test.go b/internal/handlers/screencast_test.goindex a43fdabb..7d6aa67b 100644--- a/internal/handlers/screencast_test.go+++ b/internal/handlers/screencast_test.go@@ -16,7 +16,7 @@ func TestHandleScreencast_AuthRejectsNoToken(t *testing.T) {req := httptest.NewRequest("GET", "/screencast", nil)w := httptest.NewRecorder()- handler := AuthMiddleware(cfg, http.HandlerFunc(h.HandleScreencast))+ handler := AuthMiddleware(config.NewLive(cfg), http.HandlerFunc(h.HandleScreencast))handler.ServeHTTP(w, req)if w.Code != http.StatusUnauthorized {@@ -32,7 +32,7 @@ func TestHandleScreencast_AuthRejectsWrongToken(t *testing.T) {req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: "wrong-token"})req.Header.Set("Referer", "http://example.com/dashboard")w := httptest.NewRecorder()- handler := AuthMiddleware(cfg, http.HandlerFunc(h.HandleScreencast))+ handler := AuthMiddleware(config.NewLive(cfg), http.HandlerFunc(h.HandleScreencast))handler.ServeHTTP(w, req)if w.Code != http.StatusUnauthorized {@@ -47,7 +47,7 @@ func TestHandleScreencast_AuthRejectsWrongHeader(t *testing.T) {req := httptest.NewRequest("GET", "/screencast", nil)req.Header.Set("Authorization", "Bearer wrong-token")w := httptest.NewRecorder()- handler := AuthMiddleware(cfg, http.HandlerFunc(h.HandleScreencast))+ handler := AuthMiddleware(config.NewLive(cfg), http.HandlerFunc(h.HandleScreencast))handler.ServeHTTP(w, req)if w.Code != http.StatusUnauthorized {@@ -61,7 +61,7 @@ func TestHandleScreencast_NoTokenConfigRejectsRequest(t *testing.T) {req := httptest.NewRequest("GET", "/screencast", nil)w := httptest.NewRecorder()- handler := AuthMiddleware(cfg, http.HandlerFunc(h.HandleScreencast))+ handler := AuthMiddleware(config.NewLive(cfg), http.HandlerFunc(h.HandleScreencast))handler.ServeHTTP(w, req)if w.Code != http.StatusServiceUnavailable {diff --git a/internal/server/bridge.go b/internal/server/bridge.goindex 204a9f59..3e63e9c4 100644--- a/internal/server/bridge.go+++ b/internal/server/bridge.go@@ -83,6 +83,12 @@ func RunBridgeServer(cfg *config.RuntimeConfig, version string) {RegisterSessionsUnavailableInBridgeMode(mux)cli.LogSecurityWarnings(cfg)+ // A bridge process registers no ConfigAPI and no orchestrator, so nothing+ // here ever publishes a second value: this Live holds the boot config for the+ // life of the process by construction, not by accident. The middlewares still+ // resolve per request, which is what keeps one contract for both processes.+ live := config.NewLive(cfg)+server = &http.Server{Addr: listenAddr,Handler: handlers.TrustedInternalProxyStripMiddleware(os.Getenv("PINCHTAB_INTERNAL_TOKEN"))(@@ -90,8 +96,8 @@ func RunBridgeServer(cfg *config.RuntimeConfig, version string) {activity.Middleware(actStore,"bridge",- handlers.SecurityHeadersMiddleware(cfg,- handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.AuthMiddleware(cfg, mux))),+ handlers.SecurityHeadersMiddleware(live,+ handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.AuthMiddleware(live, mux))),),),),diff --git a/internal/server/bridge_test.go b/internal/server/bridge_test.goindex 187483ba..6c7954fd 100644--- a/internal/server/bridge_test.go+++ b/internal/server/bridge_test.go@@ -118,7 +118,7 @@ func TestBridgeHandlerChainAppliesRateLimit(t *testing.T) {activity.Middleware(nil,"bridge",- handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.AuthMiddleware(cfg, mux))),+ handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.AuthMiddleware(config.NewLive(cfg), mux))),),)diff --git a/internal/server/front_door_live_config_test.go b/internal/server/front_door_live_config_test.gonew file mode 100644index 00000000..326a3b70--- /dev/null+++ b/internal/server/front_door_live_config_test.go@@ -0,0 +1,196 @@+package server++import (+ "bytes"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/pinchtab/pinchtab/internal/authn"+ "github.com/pinchtab/pinchtab/internal/browsersession"+ "github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/pinchtab/internal/dashboard"+ "github.com/pinchtab/pinchtab/internal/orchestrator"+)++const frontDoorLiveToken = "front-door-live-token"++// frontDoor stands up RunDashboard's wiring: one publication point reaching the+// orchestrator, the config API and the front-door chain, over a real config file+// the save writes to. The chain is the real one — an isolated middleware already+// behaved correctly, which is why nothing caught the boot pointer.+type frontDoor struct {+ handler http.Handler+ api *dashboard.ConfigAPI+ sessions *browsersession.Manager+}++func newFrontDoor(t *testing.T, boot func(*config.FileConfig)) frontDoor {+ t.Helper()++ fc := config.DefaultFileConfig()+ fc.Server.Token = frontDoorLiveToken+ if boot != nil {+ boot(&fc)+ }+ data, err := json.MarshalIndent(fc, "", " ")+ if err != nil {+ t.Fatal(err)+ }+ configPath := filepath.Join(t.TempDir(), "config.json")+ t.Setenv("PINCHTAB_CONFIG", configPath)+ if err := os.WriteFile(configPath, data, 0o600); err != nil {+ t.Fatal(err)+ }++ cfg := config.Load()+ orch := orchestrator.NewOrchestrator(t.TempDir())+ orch.ApplyRuntimeConfig(cfg)+ live := orch.LiveConfig()++ sessions := browsersession.NewManager(dashboard.BrowserSessionConfig(cfg))+ api := dashboard.NewConfigAPI(live, orch, nil, orch, nil, "test", time.Now())+ api.SetSessionManager(sessions)++ mux := http.NewServeMux()+ mux.HandleFunc("/health", func(w http.ResponseWriter, _ *http.Request) {+ _, _ = w.Write([]byte(`{"status":"ok"}`))+ })+ api.RegisterHandlers(mux)++ return frontDoor{+ handler: FrontDoorHandler(live, nil, sessions, nil, mux),+ api: api,+ sessions: sessions,+ }+}++// save drives a real PUT /api/config through the config API, the same way the+// dashboard does, and asserts the server reported it as applied rather than as+// needing a restart — which is the claim this card says the front door broke.+func (f frontDoor) save(t *testing.T, mutate func(*config.FileConfig)) {+ t.Helper()++ current, _, err := config.LoadFileConfig()+ if err != nil || current == nil {+ t.Fatalf("load current config: %v", err)+ }+ payload := *current+ payload.Server.Token = ""+ mutate(&payload)+ body, err := json.Marshal(payload)+ if err != nil {+ t.Fatal(err)+ }++ w := httptest.NewRecorder()+ f.api.HandlePutConfig(w, httptest.NewRequest(http.MethodPut, "/api/config", bytes.NewReader(body)))+ if w.Code != http.StatusOK {+ t.Fatalf("save returned %d: %s", w.Code, w.Body.String())+ }++ var env struct {+ RestartRequired bool `json:"restartRequired"`+ RestartReasons []string `json:"restartReasons"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil {+ t.Fatalf("decode save envelope: %v", err)+ }+ if env.RestartRequired {+ t.Fatalf("the save reported restartRequired=true (%v); this card must not enlarge that list", env.RestartReasons)+ }+}++func proxiedPreflight() *http.Request {+ req := httptest.NewRequest(http.MethodOptions, "/health", nil)+ req.Header.Set("Origin", "https://proxy.example")+ req.Header.Set("X-Forwarded-Host", "proxy.example")+ req.Header.Set("X-Forwarded-Proto", "https")+ return req+}++// server.trustProxyHeaders decides whether X-Forwarded-* is believed for the+// cookie-origin and CORS same-origin checks. It sits in the Server section, which+// restartReasonsFor does not flag, so the save reports applied — and with the boot+// pointer captured in the chain it went on being enforced at its boot value for+// the life of the process, in either direction.+func TestSavingTrustProxyHeadersTakesEffectWithoutARestart(t *testing.T) {+ f := newFrontDoor(t, func(fc *config.FileConfig) {+ trust := false+ fc.Server.TrustProxyHeaders = &trust+ })++ before := httptest.NewRecorder()+ f.handler.ServeHTTP(before, proxiedPreflight())+ if before.Code != http.StatusForbidden {+ t.Fatalf("with trustProxyHeaders off the proxied origin should be refused, got %d: %s", before.Code, before.Body.String())+ }++ f.save(t, func(fc *config.FileConfig) {+ trust := true+ fc.Server.TrustProxyHeaders = &trust+ })++ after := httptest.NewRecorder()+ f.handler.ServeHTTP(after, proxiedPreflight())+ if after.Code != http.StatusNoContent {+ t.Fatalf("after the save the proxied origin is still refused (%d: %s); the chain is serving the boot config",+ after.Code, after.Body.String())+ }+ if got := after.Header().Get("Access-Control-Allow-Origin"); got != "https://proxy.example" {+ t.Errorf("Access-Control-Allow-Origin = %q, want the forwarded origin echoed back", got)+ }+}++// The field the card missed, and the reason the direction is what it is: an+// authorization control on PUT /api/config and POST /shutdown. An operator who+// turns elevation ON is told the save applied; with the boot pointer the front+// door went on not requiring it.+func TestSavingRequireElevationTakesEffectWithoutARestart(t *testing.T) {+ f := newFrontDoor(t, func(fc *config.FileConfig) {+ require := false+ fc.Sessions.Dashboard.RequireElevation = &require+ })++ sessionID, err := f.sessions.Create(frontDoorLiveToken)+ if err != nil {+ t.Fatal(err)+ }+ covered := func() *httptest.ResponseRecorder {+ req := httptest.NewRequest(http.MethodPut, "/api/config", bytes.NewReader([]byte(`{}`)))+ req.Header.Set("Origin", "http://example.com")+ req.Host = "example.com"+ req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})+ w := httptest.NewRecorder()+ f.handler.ServeHTTP(w, req)+ return w+ }++ if got := covered().Code; got == http.StatusForbidden {+ t.Fatalf("elevation was demanded before it was turned on (%d); the fixture does not start from the state this test needs", got)+ }++ f.save(t, func(fc *config.FileConfig) {+ require := true+ fc.Sessions.Dashboard.RequireElevation = &require+ })++ after := covered()+ if after.Code != http.StatusForbidden {+ t.Fatalf("after saving requireElevation=true the request was not challenged (%d: %s); the chain is serving the boot config",+ after.Code, after.Body.String())+ }+ var resp struct {+ Code string `json:"code"`+ }+ if err := json.Unmarshal(after.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode challenge: %v (body %s)", err, after.Body.String())+ }+ if resp.Code != "elevation_required" {+ t.Errorf("code = %q, want elevation_required — the refusal must name the control that produced it", resp.Code)+ }+}diff --git a/internal/server/front_door_metrics.go b/internal/server/front_door_metrics.goindex c1c9f402..99cfb82a 100644--- a/internal/server/front_door_metrics.go+++ b/internal/server/front_door_metrics.go@@ -12,13 +12,19 @@ import ("github.com/pinchtab/pinchtab/internal/session")-// FrontDoorHandler is the orchestrator front door's whole middleware chain. It is-// a named function rather than an expression inside RunDashboard because the-// counters live in the middleware and the rejections that were invisible happen+// FrontDoorHandler is the orchestrator front door's whole middleware chain. It+// takes the publication point rather than a config: the chain is built once and+// serves for the life of the process, so a captured *RuntimeConfig would freeze+// every setting it reads at its boot value while the dashboard reported saves as+// applied. It is the orchestrator's Live, shared with ConfigAPI and AuthAPI, so a+// save is visible to all four holders at once.+//+// It is a named function rather than an expression inside RunDashboard because+// the counters live in the middleware and the rejections that were invisible happen// ABOVE the mux: proving they are counted needs the real chain, and the isolated// middleware already behaved correctly, which is why nothing caught this.func FrontDoorHandler(- cfg *config.RuntimeConfig,+ live *config.Live,recorder activity.Recorder,sessions *browsersession.Manager,sessionStore *session.Store,@@ -29,8 +35,8 @@ func FrontDoorHandler(activity.Middleware(recorder,"server",- handlers.SecurityHeadersMiddleware(cfg,- handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.CorsMiddleware(cfg, handlers.AuthMiddlewareWithSessions(cfg, sessions, sessionStore, mux)))),+ handlers.SecurityHeadersMiddleware(live,+ handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.CorsMiddleware(live, handlers.AuthMiddlewareWithSessions(live, sessions, sessionStore, mux)))),),),),diff --git a/internal/server/front_door_metrics_test.go b/internal/server/front_door_metrics_test.goindex 03d877af..6a42bb06 100644--- a/internal/server/front_door_metrics_test.go+++ b/internal/server/front_door_metrics_test.go@@ -29,7 +29,7 @@ func frontDoorFixture(t *testing.T) http.Handler {mux.HandleFunc("GET /tabs", func(w http.ResponseWriter, r *http.Request) {_, _ = w.Write([]byte(`{"tabs":[]}`))})- return FrontDoorHandler(cfg, nil, nil, nil, mux)+ return FrontDoorHandler(config.NewLive(cfg), nil, nil, nil, mux)}func readFrontDoorMetrics(t *testing.T, handler http.Handler) map[string]any {diff --git a/internal/server/server.go b/internal/server/server.goindex 9c95fcfb..2df93555 100644--- a/internal/server/server.go+++ b/internal/server/server.go@@ -298,7 +298,7 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {})})- handler := FrontDoorHandler(cfg, liveActivity, sessions, sessionStore, mux)+ handler := FrontDoorHandler(live, liveActivity, sessions, sessionStore, mux)if cfg.VerboseBanner {cli.LogSecurityWarnings(cfg)}diff --git a/internal/server/timeouts_test.go b/internal/server/timeouts_test.goindex bede5720..237a2b2f 100644--- a/internal/server/timeouts_test.go+++ b/internal/server/timeouts_test.go@@ -39,7 +39,7 @@ func TestDashboardHandlerChainAppliesRateLimit(t *testing.T) {activity.Middleware(nil,"server",- handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.CorsMiddleware(cfg, handlers.AuthMiddlewareWithSessions(cfg, sessions, nil, mux)))),+ handlers.LoggingMiddleware(handlers.RateLimitMiddleware(handlers.CorsMiddleware(config.NewLive(cfg), handlers.AuthMiddlewareWithSessions(config.NewLive(cfg), sessions, nil, mux)))),),)