High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix(auth): make dashboard cookie Secure flag configurable
pigd0g47581a86c148
diff --git a/docs/guides/security.md b/docs/guides/security.mdindex fcfe2798..ab83c325 100644--- a/docs/guides/security.md+++ b/docs/guides/security.md@@ -96,6 +96,19 @@ The browser dashboard uses a different flow:3. sensitive dashboard actions can require token re-entry for short-livedelevation+By default, PinchTab auto-detects whether the dashboard session cookie should+use the `Secure` flag. For reverse-proxied HTTPS this stays enabled. If you+intentionally access the dashboard over plain HTTP on a trusted LAN, you can+explicitly disable it:++```json+{+ "server": {+ "cookieSecure": false+ }+}+```+Why this matters:- without a token, any process that can reach the server can call the APIdiff --git a/internal/authn/cookie.go b/internal/authn/cookie.goindex f557c26d..57d2faa7 100644--- a/internal/authn/cookie.go+++ b/internal/authn/cookie.go@@ -11,7 +11,7 @@ import (// SetSessionCookie stores the opaque dashboard session id in an HttpOnly// same-site cookie so browser APIs can authenticate without exposing the// underlying bearer token to JavaScript.-func SetSessionCookie(w http.ResponseWriter, r *http.Request, sessionID string, maxLifetime time.Duration, trustProxy bool) {+func SetSessionCookie(w http.ResponseWriter, r *http.Request, sessionID string, maxLifetime time.Duration, trustProxy bool, cookieSecure *bool) {if maxLifetime <= 0 {maxLifetime = DefaultSessionMaxLifetime}@@ -20,7 +20,7 @@ func SetSessionCookie(w http.ResponseWriter, r *http.Request, sessionID string,Value: url.QueryEscape(strings.TrimSpace(sessionID)),Path: "/",HttpOnly: true,- Secure: sessionCookieSecure(r, trustProxy),+ Secure: sessionCookieSecure(r, trustProxy, cookieSecure),SameSite: http.SameSiteStrictMode,MaxAge: int(maxLifetime.Seconds()),Expires: time.Now().Add(maxLifetime),@@ -28,20 +28,23 @@ func SetSessionCookie(w http.ResponseWriter, r *http.Request, sessionID string,}// ClearSessionCookie expires the dashboard auth cookie.-func ClearSessionCookie(w http.ResponseWriter, r *http.Request, trustProxy bool) {+func ClearSessionCookie(w http.ResponseWriter, r *http.Request, trustProxy bool, cookieSecure *bool) {http.SetCookie(w, &http.Cookie{Name: CookieName,Value: "",Path: "/",HttpOnly: true,- Secure: sessionCookieSecure(r, trustProxy),+ Secure: sessionCookieSecure(r, trustProxy, cookieSecure),SameSite: http.SameSiteStrictMode,MaxAge: -1,Expires: time.Unix(0, 0),})}-func sessionCookieSecure(r *http.Request, trustProxy bool) bool {+func sessionCookieSecure(r *http.Request, trustProxy bool, cookieSecure *bool) bool {+ if cookieSecure != nil {+ return *cookieSecure+ }if requestScheme(r, trustProxy) == "https" {return true}diff --git a/internal/authn/cookie_test.go b/internal/authn/cookie_test.gonew file mode 100644index 00000000..748c4d42--- /dev/null+++ b/internal/authn/cookie_test.go@@ -0,0 +1,47 @@+package authn++import (+ "net/http/httptest"+ "testing"+)++func TestSessionCookieSecure_AutoDetect(t *testing.T) {+ t.Run("https is secure", func(t *testing.T) {+ req := httptest.NewRequest("GET", "https://example.com/dashboard", nil)+ if !sessionCookieSecure(req, false, nil) {+ t.Fatal("expected https request to set Secure cookie")+ }+ })++ t.Run("localhost over http is not secure", func(t *testing.T) {+ req := httptest.NewRequest("GET", "http://localhost:9867/dashboard", nil)+ if sessionCookieSecure(req, false, nil) {+ t.Fatal("expected localhost http request to clear Secure cookie")+ }+ })++ t.Run("lan host over http remains secure for backward compatibility", func(t *testing.T) {+ req := httptest.NewRequest("GET", "http://192.168.1.50:9867/dashboard", nil)+ if !sessionCookieSecure(req, false, nil) {+ t.Fatal("expected lan http request to keep Secure cookie in auto-detect mode")+ }+ })+}++func TestSessionCookieSecure_ConfigOverride(t *testing.T) {+ t.Run("explicit false disables secure flag", func(t *testing.T) {+ force := false+ req := httptest.NewRequest("GET", "https://example.com/dashboard", nil)+ if sessionCookieSecure(req, false, &force) {+ t.Fatal("expected explicit false to disable Secure cookie")+ }+ })++ t.Run("explicit true enables secure flag", func(t *testing.T) {+ force := true+ req := httptest.NewRequest("GET", "http://localhost:9867/dashboard", nil)+ if !sessionCookieSecure(req, false, &force) {+ t.Fatal("expected explicit true to enable Secure cookie")+ }+ })+}diff --git a/internal/config/config_file.go b/internal/config/config_file.goindex 7b7749f6..408dc909 100644--- a/internal/config/config_file.go+++ b/internal/config/config_file.go@@ -132,6 +132,7 @@ type serverConfigJSON struct {Engine string `json:"engine"`NetworkBufferSize *int `json:"networkBufferSize,omitempty"`TrustProxyHeaders *bool `json:"trustProxyHeaders,omitempty"`+ CookieSecure *bool `json:"cookieSecure,omitempty"`}type browserConfigJSON struct {@@ -262,6 +263,7 @@ func (fc FileConfig) MarshalJSON() ([]byte, error) {Engine: fc.Server.Engine,NetworkBufferSize: fc.Server.NetworkBufferSize,TrustProxyHeaders: fc.Server.TrustProxyHeaders,+ CookieSecure: fc.Server.CookieSecure,},Browser: browserConfigJSON{ChromeVersion: fc.Browser.ChromeVersion,@@ -415,6 +417,7 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {Engine: cfg.Engine,NetworkBufferSize: netBufSize,TrustProxyHeaders: &cfg.TrustProxyHeaders,+ CookieSecure: cfg.CookieSecure,},Browser: BrowserConfig{ChromeVersion: cfg.ChromeVersion,diff --git a/internal/config/config_file_test.go b/internal/config/config_file_test.goindex ecbb5276..b7a68ce9 100644--- a/internal/config/config_file_test.go+++ b/internal/config/config_file_test.go@@ -13,6 +13,9 @@ func TestDefaultFileConfig(t *testing.T) {if fc.Server.Bind != "127.0.0.1" {t.Errorf("DefaultFileConfig.Server.Bind = %v, want 127.0.0.1", fc.Server.Bind)}+ if fc.Server.CookieSecure != nil {+ t.Errorf("DefaultFileConfig.Server.CookieSecure = %v, want nil for auto-detect", formatBoolPtr(fc.Server.CookieSecure))+ }if fc.InstanceDefaults.Mode != "headless" {t.Errorf("DefaultFileConfig.InstanceDefaults.Mode = %v, want headless", fc.InstanceDefaults.Mode)}diff --git a/internal/config/config_load.go b/internal/config/config_load.goindex f9c22122..36547de1 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -19,6 +19,7 @@ func Load() *RuntimeConfig {InstancePortEnd: 9968,Token: os.Getenv("PINCHTAB_TOKEN"),StateDir: userConfigDir(),+ CookieSecure: nil,// Security defaultsAllowEvaluate: false,@@ -197,6 +198,7 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {if fc.Server.TrustProxyHeaders != nil {cfg.TrustProxyHeaders = *fc.Server.TrustProxyHeaders}+ cfg.CookieSecure = fc.Server.CookieSecure// Securityif fc.Security.AllowEvaluate != nil {cfg.AllowEvaluate = *fc.Security.AllowEvaluatediff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.goindex 362dc720..4bc09fa3 100644--- a/internal/config/config_load_test.go+++ b/internal/config/config_load_test.go@@ -62,6 +62,9 @@ func TestLoadConfigDefaults(t *testing.T) {if cfg.TrustProxyHeaders {t.Errorf("default TrustProxyHeaders = %v, want false", cfg.TrustProxyHeaders)}+ if cfg.CookieSecure != nil {+ t.Errorf("default CookieSecure = %v, want nil for auto-detect", *cfg.CookieSecure)+ }if len(cfg.DownloadAllowedDomains) != 0 {t.Errorf("default DownloadAllowedDomains = %v, want empty list", cfg.DownloadAllowedDomains)}@@ -477,6 +480,33 @@ func TestApplyFileConfigToRuntime_TrustProxyHeaders(t *testing.T) {}}+func TestApplyFileConfigToRuntime_CookieSecure(t *testing.T) {+ cfg := &RuntimeConfig{}+ if cfg.CookieSecure != nil {+ t.Fatal("expected default CookieSecure to be nil")+ }++ enabled := true+ fc := &FileConfig{Server: ServerConfig{CookieSecure: &enabled}}+ applyFileConfig(cfg, fc)+ if cfg.CookieSecure == nil || !*cfg.CookieSecure {+ t.Fatal("expected CookieSecure to be true after apply")+ }++ disabled := false+ fc2 := &FileConfig{Server: ServerConfig{CookieSecure: &disabled}}+ applyFileConfig(cfg, fc2)+ if cfg.CookieSecure == nil || *cfg.CookieSecure {+ t.Fatal("expected CookieSecure to be false after apply with false")+ }++ fc3 := &FileConfig{}+ applyFileConfig(cfg, fc3)+ if cfg.CookieSecure != nil {+ t.Fatal("expected CookieSecure to reset to nil when omitted")+ }+}+func TestApplyFileConfigToRuntime_SanitizesChromeExtraFlags(t *testing.T) {cfg := &RuntimeConfig{}fc := &FileConfig{diff --git a/internal/config/config_types.go b/internal/config/config_types.goindex 8abfc03b..37b982e5 100644--- a/internal/config/config_types.go+++ b/internal/config/config_types.go@@ -12,7 +12,8 @@ type RuntimeConfig struct {InstancePortEnd int // Ending port for instances (default 9968)Token stringStateDir string- TrustProxyHeaders bool // Only trust X-Forwarded-*/Forwarded headers when behind a trusted reverse proxy+ TrustProxyHeaders bool // Only trust X-Forwarded-*/Forwarded headers when behind a trusted reverse proxy+ CookieSecure *bool // Nil = auto-detect based on request scheme/host for backward compatibility// Security settingsAllowEvaluate bool@@ -150,6 +151,7 @@ type ServerConfig struct {Engine string `json:"engine,omitempty"`NetworkBufferSize *int `json:"networkBufferSize,omitempty"`TrustProxyHeaders *bool `json:"trustProxyHeaders,omitempty"`+ CookieSecure *bool `json:"cookieSecure,omitempty"`}type BrowserConfig struct {diff --git a/internal/config/editor_get.go b/internal/config/editor_get.goindex ddbeeb08..f4f50635 100644--- a/internal/config/editor_get.go+++ b/internal/config/editor_get.go@@ -48,6 +48,8 @@ func getServerField(s *ServerConfig, field string) (string, error) {return s.StateDir, nilcase "trustProxyHeaders":return formatBoolPtr(s.TrustProxyHeaders), nil+ case "cookieSecure":+ return formatBoolPtr(s.CookieSecure), nildefault:return "", fmt.Errorf("unknown field server.%s", field)}diff --git a/internal/config/editor_get_test.go b/internal/config/editor_get_test.goindex b552b514..1590ec19 100644--- a/internal/config/editor_get_test.go+++ b/internal/config/editor_get_test.go@@ -14,6 +14,7 @@ func TestGetConfigValue_RoundTrip(t *testing.T) {{"server.bind", "0.0.0.0", "0.0.0.0"},{"server.token", "s3cr3t", "s3cr3t"},{"server.stateDir", "/tmp/state", "/tmp/state"},+ {"server.cookieSecure", "false", "false"},{"browser.version", "120.0", "120.0"},{"browser.binary", "/usr/bin/chrome", "/usr/bin/chrome"},{"instanceDefaults.mode", "headed", "headed"},@@ -101,6 +102,7 @@ func TestGetConfigValue_NilPointerReturnsEmpty(t *testing.T) {"multiInstance.instancePortStart","multiInstance.instancePortEnd","security.attach.enabled",+ "server.cookieSecure",}for _, path := range ptrs {t.Run(path, func(t *testing.T) {diff --git a/internal/config/editor_set.go b/internal/config/editor_set.goindex 4b765d78..d825838a 100644--- a/internal/config/editor_set.go+++ b/internal/config/editor_set.go@@ -51,6 +51,12 @@ func setServerField(s *ServerConfig, field, value string) error {return fmt.Errorf("server.trustProxyHeaders must be true or false: %w", err)}s.TrustProxyHeaders = &b+ case "cookieSecure":+ b, err := parseBool(value)+ if err != nil {+ return fmt.Errorf("server.cookieSecure must be true or false: %w", err)+ }+ s.CookieSecure = &bdefault:return fmt.Errorf("unknown field server.%s", field)}diff --git a/internal/config/editor_set_test.go b/internal/config/editor_set_test.goindex 0c1dad7d..a051eb37 100644--- a/internal/config/editor_set_test.go+++ b/internal/config/editor_set_test.go@@ -13,6 +13,7 @@ func TestSetConfigValue_ServerFields(t *testing.T) {{"server.bind", "0.0.0.0", func(fc *FileConfig) bool { return fc.Server.Bind == "0.0.0.0" }, false},{"server.token", "secret", func(fc *FileConfig) bool { return fc.Server.Token == "secret" }, false},{"server.stateDir", "/tmp/state", func(fc *FileConfig) bool { return fc.Server.StateDir == "/tmp/state" }, false},+ {"server.cookieSecure", "false", func(fc *FileConfig) bool { return fc.Server.CookieSecure != nil && *fc.Server.CookieSecure == false }, false},{"server.unknown", "value", nil, true},}diff --git a/internal/dashboard/auth_api.go b/internal/dashboard/auth_api.goindex 7ab226b2..b66ea78e 100644--- a/internal/dashboard/auth_api.go+++ b/internal/dashboard/auth_api.go@@ -84,7 +84,7 @@ func (a *AuthAPI) HandleLogin(w http.ResponseWriter, r *http.Request) {if a.loginLimiter != nil {a.loginLimiter.RecordFailure(clientIP)}- authn.ClearSessionCookie(w, r, a.runtime != nil && a.runtime.TrustProxyHeaders)+ authn.ClearSessionCookie(w, r, a.runtime != nil && a.runtime.TrustProxyHeaders, cookieSecureSetting(a.runtime))authn.AuditWarn(r, "auth.login_failed", "reason", "bad_token")w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)httpx.ErrorCode(w, http.StatusUnauthorized, "bad_token", "unauthorized", false, nil)@@ -107,7 +107,7 @@ func (a *AuthAPI) HandleLogin(w http.ResponseWriter, r *http.Request) {httpx.Error(w, http.StatusInternalServerError, err)return}- authn.SetSessionCookie(w, r, sessionID, a.sessions.MaxLifetime(), a.runtime != nil && a.runtime.TrustProxyHeaders)+ authn.SetSessionCookie(w, r, sessionID, a.sessions.MaxLifetime(), a.runtime != nil && a.runtime.TrustProxyHeaders, cookieSecureSetting(a.runtime))authn.AuditLog(r, "auth.session_created","sessionIdleSec", int(authn.DefaultSessionIdleTimeout.Seconds()),"sessionMaxLifetimeSec", int(a.sessions.MaxLifetime().Seconds()),@@ -122,7 +122,7 @@ func (a *AuthAPI) HandleLogout(w http.ResponseWriter, r *http.Request) {authn.AuditLog(r, "auth.session_revoked", "reason", "logout")}}- authn.ClearSessionCookie(w, r, a.runtime != nil && a.runtime.TrustProxyHeaders)+ authn.ClearSessionCookie(w, r, a.runtime != nil && a.runtime.TrustProxyHeaders, cookieSecureSetting(a.runtime))httpx.JSON(w, http.StatusOK, map[string]string{"status": "ok"})}@@ -165,7 +165,7 @@ func (a *AuthAPI) HandleElevate(w http.ResponseWriter, r *http.Request) {return}if !a.sessions.Elevate(creds.Value, token) {- authn.ClearSessionCookie(w, r, a.runtime != nil && a.runtime.TrustProxyHeaders)+ authn.ClearSessionCookie(w, r, a.runtime != nil && a.runtime.TrustProxyHeaders, cookieSecureSetting(a.runtime))w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)httpx.ErrorCode(w, http.StatusUnauthorized, "bad_token", "unauthorized", false, nil)return@@ -178,6 +178,13 @@ func (a *AuthAPI) HandleElevate(w http.ResponseWriter, r *http.Request) {})}+func cookieSecureSetting(cfg *config.RuntimeConfig) *bool {+ if cfg == nil {+ return nil+ }+ return cfg.CookieSecure+}+func secondsCeil(d time.Duration) int {if d <= 0 {return 1diff --git a/internal/dashboard/auth_api_test.go b/internal/dashboard/auth_api_test.goindex c2087745..738a0f93 100644--- a/internal/dashboard/auth_api_test.go+++ b/internal/dashboard/auth_api_test.go@@ -100,6 +100,32 @@ func TestAuthAPIHandleLogin_TrustedProxyHTTPSUsesSecureCookie(t *testing.T) {}}+func TestAuthAPIHandleLogin_CookieSecureFalseOverridesHTTPS(t *testing.T) {+ sessions := authn.NewSessionManager(authn.SessionConfig{})+ forceInsecure := false+ api := NewAuthAPI(&config.RuntimeConfig{+ Token: "secret-token",+ CookieSecure: &forceInsecure,+ }, sessions)++ req := httptest.NewRequest("POST", "https://pinchtab.example/api/auth/login", strings.NewReader(`{"token":"secret-token"}`))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()++ api.HandleLogin(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)+ }+ cookies := w.Result().Cookies()+ if len(cookies) != 1 {+ t.Fatalf("cookies = %d, want 1", len(cookies))+ }+ if cookies[0].Secure {+ t.Fatal("expected explicit cookieSecure=false to disable Secure even on https request")+ }+}+func TestAuthAPIHandleLoginRejectsBadToken(t *testing.T) {api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, authn.NewSessionManager(authn.SessionConfig{}))diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.goindex fabd5143..1b3a66e6 100644--- a/internal/handlers/middleware.go+++ b/internal/handlers/middleware.go@@ -90,7 +90,7 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *authn.Sessicreds := authn.CredentialsFromRequest(r)if creds.Value == "" {- authn.ClearSessionCookie(w, r, cfg != nil && cfg.TrustProxyHeaders)+ authn.ClearSessionCookie(w, r, cfg != nil && cfg.TrustProxyHeaders, cookieSecureSetting(cfg))w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="missing_token"`)httpx.ErrorCode(w, 401, "missing_token", "unauthorized", false, nil)return@@ -99,7 +99,7 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *authn.Sessiswitch creds.Method {case authn.MethodHeader:if subtle.ConstantTimeCompare([]byte(creds.Value), []byte(token)) != 1 {- authn.ClearSessionCookie(w, r, cfg != nil && cfg.TrustProxyHeaders)+ authn.ClearSessionCookie(w, r, cfg != nil && cfg.TrustProxyHeaders, cookieSecureSetting(cfg))w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)httpx.ErrorCode(w, 401, "bad_token", "unauthorized", false, nil)return@@ -112,7 +112,7 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *authn.Sessireturn}if sessions == nil || !sessions.Validate(creds.Value, token) {- authn.ClearSessionCookie(w, r, cfg != nil && cfg.TrustProxyHeaders)+ authn.ClearSessionCookie(w, r, cfg != nil && cfg.TrustProxyHeaders, cookieSecureSetting(cfg))w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)httpx.ErrorCode(w, 401, "bad_token", "unauthorized", false, nil)return@@ -129,7 +129,7 @@ func AuthMiddlewareWithSessions(cfg *config.RuntimeConfig, sessions *authn.Sessireturn}default:- authn.ClearSessionCookie(w, r, cfg != nil && cfg.TrustProxyHeaders)+ authn.ClearSessionCookie(w, r, cfg != nil && cfg.TrustProxyHeaders, cookieSecureSetting(cfg))w.Header().Set("WWW-Authenticate", `Bearer realm="pinchtab", error="bad_token"`)httpx.ErrorCode(w, 401, "bad_token", "unauthorized", false, nil)return@@ -291,6 +291,13 @@ func isWebSocketUpgrade(r *http.Request) bool {return strings.Contains(strings.ToLower(r.Header.Get("Connection")), "upgrade")}+func cookieSecureSetting(cfg *config.RuntimeConfig) *bool {+ if cfg == nil {+ return nil+ }+ return cfg.CookieSecure+}+func requestScheme(r *http.Request, trustProxy bool) string {if r == nil {return "http"