Skip to content

Modern Docker Management, Designed for Everyone

fix: make Arcane reverse-proxy aware to resolve connection issues (#2717)

Kyle Mendell7d72bb153975
diff --git a/.env.example b/.env.example
index 232f56126..62c65dec5 100644
--- a/.env.example
+++ b/.env.example
@@ -14,6 +14,12 @@ APP_URL=https://your-domain.com
# TLS_CERT_FILE=/path/to/fullchain.pem
# TLS_KEY_FILE=/path/to/privkey.pem
+# When running behind a reverse proxy (Caddy, Nginx, Traefik), set the CIDR
+# range(s) of the proxy so X-Forwarded-* headers are trusted for client IP
+# and TLS scheme detection. Auto-defaults to loopback ranges when LISTEN is
+# bound to 127.0.0.1 or ::1. Comma-separated, e.g.:
+# TRUSTED_PROXIES=127.0.0.0/8,::1/128
+
# Optional runtime UID/GID for published Docker images.
# When both are set, Arcane will run as that UID/GID and files it writes under
# /app/data will be owned by that user inside the container.
diff --git a/backend/api/buildables.go b/backend/api/buildables.go
index 5bffca36f..7992e356b 100644
--- a/backend/api/buildables.go
+++ b/backend/api/buildables.go
@@ -89,7 +89,7 @@ func registerAutoLoginRoutes(apiGroup *echo.Group, authService *services.AuthSer
}
maxAge += 60
- c.Response().Header().Set("Set-Cookie", cookie.BuildTokenCookieString(maxAge, tokenPair.AccessToken))
+ c.Response().Header().Set("Set-Cookie", cookie.BuildTokenCookieStringFor(maxAge, tokenPair.AccessToken, cookie.SecureCookieFromRequest(c.Request())))
return c.JSON(http.StatusOK, base.ApiResponse[auth.LoginResponse]{
Success: true,
Data: auth.LoginResponse{
diff --git a/backend/api/handlers/auth.go b/backend/api/handlers/auth.go
index 9993d7ec6..38907d3a1 100644
--- a/backend/api/handlers/auth.go
+++ b/backend/api/handlers/auth.go
@@ -33,12 +33,12 @@ type LoginInput struct {
}
type LoginOutput struct {
- SetCookie string `header:"Set-Cookie" doc:"Session cookie"`
+ SetCookie []string `header:"Set-Cookie" doc:"Session cookie"`
Body base.ApiResponse[auth.LoginResponse]
}
type LogoutOutput struct {
- SetCookie string `header:"Set-Cookie" doc:"Cleared session cookie"`
+ SetCookie []string `header:"Set-Cookie" doc:"Cleared session cookie"`
Body base.ApiResponse[base.MessageResponse]
}
@@ -48,7 +48,7 @@ type RefreshTokenInput struct {
}
type RefreshTokenOutput struct {
- SetCookie string `header:"Set-Cookie" doc:"Updated session cookie"`
+ SetCookie []string `header:"Set-Cookie" doc:"Updated session cookie"`
Body base.ApiResponse[auth.TokenRefreshResponse]
}
@@ -164,7 +164,7 @@ func (h *AuthHandler) Login(ctx context.Context, input *LoginInput) (*LoginOutpu
maxAge += 60
return &LoginOutput{
- SetCookie: cookie.BuildTokenCookieString(maxAge, tokenPair.AccessToken),
+ SetCookie: []string{cookie.BuildTokenCookieStringFor(maxAge, tokenPair.AccessToken, cookie.SecureCookieFromContext(ctx))},
Body: base.ApiResponse[auth.LoginResponse]{
Success: true,
Data: auth.LoginResponse{
@@ -191,7 +191,7 @@ func (h *AuthHandler) Logout(ctx context.Context, input *struct{}) (*LogoutOutpu
}
return &LogoutOutput{
- SetCookie: cookie.BuildClearTokenCookieString(),
+ SetCookie: cookie.BuildClearTokenCookieStringsFor(cookie.SecureCookieFromContext(ctx)),
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
@@ -250,7 +250,7 @@ func (h *AuthHandler) RefreshToken(ctx context.Context, input *RefreshTokenInput
maxAge += 60
return &RefreshTokenOutput{
- SetCookie: cookie.BuildTokenCookieString(maxAge, tokenPair.AccessToken),
+ SetCookie: []string{cookie.BuildTokenCookieStringFor(maxAge, tokenPair.AccessToken, cookie.SecureCookieFromContext(ctx))},
Body: base.ApiResponse[auth.TokenRefreshResponse]{
Success: true,
Data: auth.TokenRefreshResponse{
diff --git a/backend/api/handlers/oidc.go b/backend/api/handlers/oidc.go
index d508deba5..c98175eaf 100644
--- a/backend/api/handlers/oidc.go
+++ b/backend/api/handlers/oidc.go
@@ -296,7 +296,7 @@ func (h *OidcHandler) HandleOidcCallback(ctx context.Context, input *HandleOidcC
if mobileRedirectURI == "" {
maxAge := max(int(time.Until(tokenPair.ExpiresAt).Seconds()), 0)
maxAge += 60 // Add 60 seconds buffer for clock skew
- setCookies = append(setCookies, cookie.BuildTokenCookieString(maxAge, tokenPair.AccessToken))
+ setCookies = append(setCookies, cookie.BuildTokenCookieStringFor(maxAge, tokenPair.AccessToken, cookie.SecureCookieFromContext(ctx)))
}
return &HandleOidcCallbackOutput{
@@ -379,7 +379,7 @@ func (h *OidcHandler) ExchangeDeviceToken(ctx context.Context, input *ExchangeDe
maxAge := max(int(time.Until(tokenPair.ExpiresAt).Seconds()), 0)
maxAge += 60
- tokenCookie := cookie.BuildTokenCookieString(maxAge, tokenPair.AccessToken)
+ tokenCookie := cookie.BuildTokenCookieStringFor(maxAge, tokenPair.AccessToken, cookie.SecureCookieFromContext(ctx))
return &ExchangeDeviceTokenOutput{
SetCookie: []string{tokenCookie},
diff --git a/backend/api/middleware/auth.go b/backend/api/middleware/auth.go
index ed86a6ab8..0e8fb817f 100644
--- a/backend/api/middleware/auth.go
+++ b/backend/api/middleware/auth.go
@@ -298,7 +298,9 @@ func handleBearerAuthInternal(api huma.API, ctx huma.Context, authService *servi
return huma.WithContext(ctx, newCtx), true
}
if errors.Is(err, services.ErrTokenVersionMismatch) || common.IsSessionRevokedError(err) || common.IsTokenValidationError(err) {
- ctx.AppendHeader("Set-Cookie", cookie.BuildClearTokenCookieStringFor(ctx.TLS() != nil))
+ for _, cookieHeader := range cookie.BuildClearTokenCookieStringsFor(cookie.SecureCookieFromContext(ctx.Context())) {
+ ctx.AppendHeader("Set-Cookie", cookieHeader)
+ }
_ = huma.WriteErr(api, ctx, http.StatusUnauthorized, "Session expired. Please log in again.")
return nil, true
}
diff --git a/backend/internal/bootstrap/bootstrap.go b/backend/internal/bootstrap/bootstrap.go
index 4a06facf5..7c9f49241 100644
--- a/backend/internal/bootstrap/bootstrap.go
+++ b/backend/internal/bootstrap/bootstrap.go
@@ -465,6 +465,12 @@ func newHTTPServerInternal(listenAddr string, handler http.Handler, protocols *h
Handler: handler,
Protocols: protocols,
ReadHeaderTimeout: 5 * time.Second,
+ // IdleTimeout closes idle keep-alive connections so upstream pools
+ // (e.g. Caddy) don't accumulate stale entries. ReadTimeout and
+ // WriteTimeout are intentionally unset — WebSocket upgrades and
+ // streaming endpoints (deploy/pull/build progress) need long-lived
+ // connections.
+ IdleTimeout: 120 * time.Second,
}
if !useTLS {
return srv, nil
diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.go
index 3f0c540e5..20cf0b06b 100644
--- a/backend/internal/bootstrap/router_bootstrap.go
+++ b/backend/internal/bootstrap/router_bootstrap.go
@@ -120,32 +120,23 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services)
e.HideBanner = true
e.HidePort = true
- if cfg.TrustedProxies == "" {
+ trustedProxyNets := parseTrustedProxyCIDRsInternal(cfg.TrustedProxies)
+ if cfg.TrustedProxies != "" && len(trustedProxyNets) == 0 {
+ slog.Warn("TRUSTED_PROXIES set but no valid CIDRs found; falling back to direct IP extraction")
+ }
+ if len(trustedProxyNets) == 0 {
e.IPExtractor = echo.ExtractIPDirect()
} else {
- var opts []echo.TrustOption
- for _, cidr := range strings.Split(cfg.TrustedProxies, ",") {
- cidr = strings.TrimSpace(cidr)
- if cidr == "" {
- continue
- }
- _, ipnet, err := net.ParseCIDR(cidr)
- if err != nil {
- slog.Warn("invalid TRUSTED_PROXIES CIDR, ignoring", "cidr", cidr, "error", err)
- continue
- }
+ opts := make([]echo.TrustOption, 0, len(trustedProxyNets))
+ for _, ipnet := range trustedProxyNets {
opts = append(opts, echo.TrustIPRange(ipnet))
}
- if len(opts) == 0 {
- slog.Warn("TRUSTED_PROXIES set but no valid CIDRs found; falling back to direct IP extraction")
- e.IPExtractor = echo.ExtractIPDirect()
- } else {
- e.IPExtractor = echo.ExtractIPFromXFFHeader(opts...)
- }
+ e.IPExtractor = echo.ExtractIPFromXFFHeader(opts...)
}
e.Use(echomiddleware.Recover())
- e.Use(requestLoggerMiddlewareInternal()) //nolint:contextcheck
+ e.Use(requestLoggerMiddlewareInternal()) //nolint:contextcheck
+ e.Use(secureCookieContextMiddlewareInternal(trustedProxyNets)) //nolint:contextcheck
authMiddleware := middleware.NewAuthMiddleware(appServices.Auth, cfg).
WithApiKeyValidator(appServices.ApiKey).
@@ -259,6 +250,71 @@ func setupRouter(ctx context.Context, cfg *config.Config, appServices *Services)
return e, tunnelServer
}
+// parseTrustedProxyCIDRsInternal parses TRUSTED_PROXIES into a list of
+// validated networks. Invalid entries are logged and skipped.
+func parseTrustedProxyCIDRsInternal(raw string) []*net.IPNet {
+ if raw == "" {
+ return nil
+ }
+ var nets []*net.IPNet
+ for _, cidr := range strings.Split(raw, ",") {
+ cidr = strings.TrimSpace(cidr)
+ if cidr == "" {
+ continue
+ }
+ _, ipnet, err := net.ParseCIDR(cidr)
+ if err != nil {
+ slog.Warn("invalid TRUSTED_PROXIES CIDR, ignoring", "cidr", cidr, "error", err)
+ continue
+ }
+ nets = append(nets, ipnet)
+ }
+ return nets
+}
+
+// secureCookieContextMiddlewareInternal records whether the request should be
+// treated as HTTPS for cookie-emitting handlers. X-Forwarded-Proto is honored
+// ONLY when the direct TCP peer is in TRUSTED_PROXIES — an untrusted client
+// setting the header directly cannot trick the server into issuing Secure /
+// __Host- cookies over plain HTTP.
+func secureCookieContextMiddlewareInternal(trustedProxyNets []*net.IPNet) echo.MiddlewareFunc {
+ return func(next echo.HandlerFunc) echo.HandlerFunc {
+ return func(c echo.Context) error {
+ req := c.Request()
+ secure := req.TLS != nil
+ if !secure && len(trustedProxyNets) > 0 &&
+ strings.EqualFold(req.Header.Get("X-Forwarded-Proto"), "https") &&
+ remoteAddrInTrustedProxiesInternal(req.RemoteAddr, trustedProxyNets) {
+ secure = true
+ }
+ if secure {
+ c.SetRequest(req.WithContext(cookie.WithSecureCookieContext(req.Context(), true)))
+ }
+ return next(c)
+ }
+ }
+}
+
+// remoteAddrInTrustedProxiesInternal reports whether the direct TCP peer
+// address of the request falls within any of the configured trusted-proxy
+// networks. Unparseable remote addresses are treated as untrusted.
+func remoteAddrInTrustedProxiesInternal(remoteAddr string, nets []*net.IPNet) bool {
+ host, _, err := net.SplitHostPort(remoteAddr)
+ if err != nil {
+ host = remoteAddr
+ }
+ ip := net.ParseIP(host)
+ if ip == nil {
+ return false
+ }
+ for _, n := range nets {
+ if n.Contains(ip) {
+ return true
+ }
+ }
+ return false
+}
+
func registerPprofRoutesInternal(apiGroup *echo.Group, authMiddleware *middleware.AuthMiddleware) {
pprofGroup := apiGroup.Group("/debug/pprof", authMiddleware.WithAdminRequired().Add())
pprofGroup.GET("", echo.WrapHandler(http.HandlerFunc(pprof.Index)))
diff --git a/backend/internal/bootstrap/router_bootstrap_test.go b/backend/internal/bootstrap/router_bootstrap_test.go
new file mode 100644
index 000000000..9187494b3
--- /dev/null
+++ b/backend/internal/bootstrap/router_bootstrap_test.go
@@ -0,0 +1,61 @@
+package bootstrap
+
+import (
+ "net"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/getarcaneapp/arcane/backend/pkg/utils/cookie"
+ "github.com/labstack/echo/v4"
+ "github.com/stretchr/testify/assert"
+)
+
+func TestSecureCookieContextMiddleware_TrustGating(t *testing.T) {
+ _, loopback, err := net.ParseCIDR("127.0.0.0/8")
+ if err != nil {
+ t.Fatalf("parse cidr: %v", err)
+ }
+ trusted := []*net.IPNet{loopback}
+
+ runRequest := func(t *testing.T, nets []*net.IPNet, remoteAddr, forwardedProto string) bool {
+ t.Helper()
+ e := echo.New()
+ req := httptest.NewRequest("GET", "/", nil)
+ req.RemoteAddr = remoteAddr
+ if forwardedProto != "" {
+ req.Header.Set("X-Forwarded-Proto", forwardedProto)
+ }
+ rec := httptest.NewRecorder()
+ c := e.NewContext(req, rec)
+
+ var observed bool
+ handler := secureCookieContextMiddlewareInternal(nets)(func(c echo.Context) error {
+ observed = cookie.SecureCookieFromContext(c.Request().Context())
+ return nil
+ })
+ if err := handler(c); err != nil {
+ t.Fatalf("handler: %v", err)
+ }
+ return observed
+ }
+
+ t.Run("trusted proxy with X-Forwarded-Proto https sets secure", func(t *testing.T) {
+ assert.True(t, runRequest(t, trusted, "127.0.0.1:54321", "https"))
+ })
+
+ t.Run("untrusted client setting X-Forwarded-Proto https is ignored", func(t *testing.T) {
+ assert.False(t, runRequest(t, trusted, "203.0.113.10:54321", "https"))
+ })
+
+ t.Run("trusted proxy with X-Forwarded-Proto http stays insecure", func(t *testing.T) {
+ assert.False(t, runRequest(t, trusted, "127.0.0.1:54321", "http"))
+ })
+
+ t.Run("no trusted proxies configured ignores header even from loopback", func(t *testing.T) {
+ assert.False(t, runRequest(t, nil, "127.0.0.1:54321", "https"))
+ })
+
+ t.Run("unparseable remote addr is untrusted", func(t *testing.T) {
+ assert.False(t, runRequest(t, trusted, "garbage", "https"))
+ })
+}
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index caeb806ed..4893dc7a9 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -111,6 +111,7 @@ func Load() *Config {
loadFromEnv(cfg)
applyOptions(cfg)
applyAgentModeDefaults(cfg)
+ applyProxyDefaults(cfg)
// Set global file permissions
common.FilePerm = cfg.FilePerm
@@ -127,6 +128,32 @@ func applyAgentModeDefaults(cfg *Config) {
}
}
+// applyProxyDefaults auto-trusts loopback proxies when LISTEN binds to a
+// loopback address. This is the canonical convenience-script setup
+// (LISTEN=127.0.0.1 + local reverse proxy like Caddy/Nginx/Traefik); auto-
+// detecting it lets X-Forwarded-* headers work without operators having to
+// discover TRUSTED_PROXIES.
+func applyProxyDefaults(cfg *Config) {
+ if cfg.TrustedProxies != "" {
+ return
+ }
+ host := strings.Trim(strings.TrimSpace(cfg.Listen), "[]")
+ if host == "" {
+ return
+ }
+ // Require an explicit loopback IP literal. Hostnames like "localhost" are
+ // intentionally not auto-trusted: /etc/hosts can map them to non-loopback
+ // addresses, in which case auto-trusting would silently trust external
+ // X-Forwarded-* headers. Operators using a hostname must set
+ // TRUSTED_PROXIES explicitly.
+ ip := net.ParseIP(host)
+ if ip == nil || !ip.IsLoopback() {
+ return
+ }
+ cfg.TrustedProxies = "127.0.0.0/8,::1/128"
+ slog.Info("LISTEN bound to loopback; trusting loopback proxies for X-Forwarded headers", "listen", cfg.Listen, "trusted_proxies", cfg.TrustedProxies)
+}
+
// loadFromEnv uses reflection to load configuration from environment variables.
func loadFromEnv(cfg *Config) {
v := reflect.ValueOf(cfg).Elem()
diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go
index 0ec9ba31f..c2ac6870c 100644
--- a/backend/internal/config/config_test.go
+++ b/backend/internal/config/config_test.go
@@ -503,6 +503,38 @@ func TestSetFieldValueInternal_DurationUsesFieldTagDefault(t *testing.T) {
assert.Equal(t, 2*time.Hour, cfg.SessionTimeout)
}
+func TestConfig_ApplyProxyDefaults(t *testing.T) {
+ t.Run("loopback ipv4 auto-trusts", func(t *testing.T) {
+ cfg := &Config{Listen: "127.0.0.1"}
+ applyProxyDefaults(cfg)
+ assert.Equal(t, "127.0.0.0/8,::1/128", cfg.TrustedProxies)
+ })
+
+ t.Run("loopback ipv6 auto-trusts", func(t *testing.T) {
+ cfg := &Config{Listen: "::1"}
+ applyProxyDefaults(cfg)
+ assert.Equal(t, "127.0.0.0/8,::1/128", cfg.TrustedProxies)
+ })
+
+ t.Run("explicit value preserved", func(t *testing.T) {
+ cfg := &Config{Listen: "127.0.0.1", TrustedProxies: "10.0.0.0/8"}
+ applyProxyDefaults(cfg)
+ assert.Equal(t, "10.0.0.0/8", cfg.TrustedProxies)
+ })
+
+ t.Run("empty listen is no-op", func(t *testing.T) {
+ cfg := &Config{Listen: ""}
+ applyProxyDefaults(cfg)
+ assert.Equal(t, "", cfg.TrustedProxies)
+ })
+
+ t.Run("public bind is no-op", func(t *testing.T) {
+ cfg := &Config{Listen: "0.0.0.0"}
+ applyProxyDefaults(cfg)
+ assert.Equal(t, "", cfg.TrustedProxies)
+ })
+}
+
func TestConfig_TrustedProxies(t *testing.T) {
orig := os.Getenv("TRUSTED_PROXIES")
defer restoreEnv("TRUSTED_PROXIES", orig)
diff --git a/backend/pkg/libarcane/edge/ws_proxy.go b/backend/pkg/libarcane/edge/ws_proxy.go
index 0301562af..c38e5af9b 100644
--- a/backend/pkg/libarcane/edge/ws_proxy.go
+++ b/backend/pkg/libarcane/edge/ws_proxy.go
@@ -4,12 +4,25 @@ import (
"context"
"log/slog"
"net/http"
+ "time"
"github.com/google/uuid"
"github.com/gorilla/websocket"
"github.com/labstack/echo/v4"
)
+const (
+ // tunnelWSPongWait is the deadline for the next pong (or any read) on the
+ // browser-facing side of a proxied WebSocket. Reverse proxies (Caddy,
+ // Nginx, ...) silently drop idle TCP connections; without a heartbeat the
+ // master would hold a dead stream open until something else terminates it.
+ tunnelWSPongWait = 60 * time.Second
+ tunnelWSPingWriteWait = 1 * time.Second
+ tunnelWSDataWriteWait = 10 * time.Second
+)
+
+var tunnelWSPingPeriod = tunnelWSPongWait * 9 / 10
+
var wsUpgraderForProxy = websocket.Upgrader{
ReadBufferSize: 64 * 1024,
WriteBufferSize: 64 * 1024,
@@ -30,6 +43,12 @@ func ProxyWebSocketRequest(c echo.Context, tunnel *AgentTunnel, targetPath strin
}
defer func() { _ = clientWS.Close() }()
+ _ = clientWS.SetReadDeadline(time.Now().Add(tunnelWSPongWait))
+ clientWS.SetPongHandler(func(string) error {
+ _ = clientWS.SetReadDeadline(time.Now().Add(tunnelWSPongWait))
+ return nil
+ })
+
streamID := uuid.New().String()
streamCtx, cancel := context.WithCancel(ctx)
defer cancel()
@@ -65,7 +84,7 @@ func ProxyWebSocketRequest(c echo.Context, tunnel *AgentTunnel, targetPath strin
// Goroutine to read from client and send to agent
go forwardClientToAgent(ctx, streamCtx, clientWS, tunnel, streamID, clientDoneCh)
- forwardAgentToClient(ctx, streamCtx, clientWS, agentDataCh, streamID, clientDoneCh)
+ forwardAgentToClient(ctx, streamCtx, clientWS, tunnel, agentDataCh, streamID, clientDoneCh)
return nil
}
@@ -109,13 +128,23 @@ func forwardClientToAgent(ctx context.Context, streamCtx context.Context, client
}
}
-func forwardAgentToClient(ctx context.Context, streamCtx context.Context, clientWS *websocket.Conn, agentDataCh <-chan *TunnelMessage, streamID string, clientDoneCh <-chan struct{}) {
+func forwardAgentToClient(ctx context.Context, streamCtx context.Context, clientWS *websocket.Conn, tunnel *AgentTunnel, agentDataCh <-chan *TunnelMessage, streamID string, clientDoneCh <-chan struct{}) {
+ pingTicker := time.NewTicker(tunnelWSPingPeriod)
+ defer pingTicker.Stop()
+
for {
select {
case <-streamCtx.Done():
return
case <-clientDoneCh:
return
+ case <-pingTicker.C:
+ _ = clientWS.SetWriteDeadline(time.Now().Add(tunnelWSPingWriteWait))
+ if err := clientWS.WriteMessage(websocket.PingMessage, nil); err != nil {
+ slog.DebugContext(ctx, "Failed to ping client WebSocket", "stream_id", streamID, "error", err)
+ sendWebSocketClose(tunnel, streamID)
+ return
+ }
case msg, ok := <-agentDataCh:
if !ok {
return
@@ -166,6 +195,7 @@ func writeWebSocketData(clientWS *websocket.Conn, msg *TunnelMessage) error {
slog.Warn("Dropping WebSocket message with unsupported type", "messageType", msgType)
return nil
}
+ _ = clientWS.SetWriteDeadline(time.Now().Add(tunnelWSDataWriteWait))
return clientWS.WriteMessage(msgType, msg.Body)
}
diff --git a/backend/pkg/utils/cookie/cookie_util.go b/backend/pkg/utils/cookie/cookie_util.go
index cfbaaeab6..a08c49cec 100644
--- a/backend/pkg/utils/cookie/cookie_util.go
+++ b/backend/pkg/utils/cookie/cookie_util.go
@@ -1,6 +1,7 @@
package cookie
import (
+ "context"
"net/http"
)
@@ -10,28 +11,37 @@ var (
OidcStateCookieName = "oidc_state"
)
-func isSecureInternal(r *http.Request) bool {
- return r.TLS != nil
+type secureCookieContextKey struct{}
+
+// WithSecureCookieContext records the router's trusted secure-cookie decision.
+func WithSecureCookieContext(ctx context.Context, secure bool) context.Context {
+ return context.WithValue(ctx, secureCookieContextKey{}, secure)
+}
+
+// SecureCookieFromContext returns the secure-cookie decision that router
+// middleware derived from TLS or trusted proxy headers.
+func SecureCookieFromContext(ctx context.Context) bool {
+ secure, _ := ctx.Value(secureCookieContextKey{}).(bool)
+ return secure
}
-func tokenCookieNameInternal(r *http.Request) string {
- if isSecureInternal(r) {
- return TokenCookieName
+// SecureCookieFromRequest returns true when the request was made over TLS or
+// router middleware marked it as forwarded from HTTPS by a trusted proxy.
+func SecureCookieFromRequest(r *http.Request) bool {
+ if r.TLS != nil {
+ return true
}
- return InsecureTokenCookieName
+ return SecureCookieFromContext(r.Context())
+}
+
+func isSecureInternal(r *http.Request) bool {
+ return SecureCookieFromRequest(r)
}
func ClearTokenCookie(w http.ResponseWriter, r *http.Request) {
- name := tokenCookieNameInternal(r)
- http.SetCookie(w, &http.Cookie{ // #nosec G124: Secure mirrors the request's TLS state so the clear directive matches whichever cookie variant (__Host-token vs. token) was originally set.
- Name: name,
- Value: "",
- Path: "/",
- MaxAge: -1,
- HttpOnly: true,
- Secure: isSecureInternal(r),
- SameSite: http.SameSiteLaxMode,
- })
+ for _, cookieHeader := range BuildClearTokenCookieStringsFor(isSecureInternal(r)) {
+ w.Header().Add("Set-Cookie", cookieHeader)
+ }
}
func GetTokenCookie(r *http.Request) (string, error) {
@@ -45,46 +55,43 @@ func GetTokenCookie(r *http.Request) (string, error) {
return c.Value, nil
}
-// BuildTokenCookieString builds a Set-Cookie header string for Huma handlers.
-// Uses the insecure cookie name since we can't detect TLS from context.
-// For secure contexts, the middleware should handle the __Host- prefix.
-func BuildTokenCookieString(maxAgeInSeconds int, token string) string {
+// BuildTokenCookieStringFor builds a Set-Cookie header string matching the
+// current request security context. Callers must pass the trusted secure flag
+// from SecureCookieFromContext / SecureCookieFromRequest so the cookie name
+// (__Host-token vs. token) round-trips correctly behind HTTPS reverse proxies.
+func BuildTokenCookieStringFor(maxAgeInSeconds int, token string, secure bool) string {
if maxAgeInSeconds < 0 {
maxAgeInSeconds = 0
}
- cookie := &http.Cookie{ // #nosec G124: Huma handlers intentionally use the HTTP-compatible fallback token cookie here.
- Name: InsecureTokenCookieName,
+ cookieName := InsecureTokenCookieName
+ if secure {
+ cookieName = TokenCookieName
+ }
+ cookie := &http.Cookie{ // #nosec G124: Secure mirrors the trusted request context so the cookie can round-trip through HTTPS reverse proxies.
+ Name: cookieName,
Value: token,
Path: "/",
MaxAge: maxAgeInSeconds,
HttpOnly: true,
+ Secure: secure,
SameSite: http.SameSiteLaxMode,
}
return cookie.String()
}
-// BuildClearTokenCookieString builds a Set-Cookie header string to clear the token cookie.
-func BuildClearTokenCookieString() string {
- cookie := &http.Cookie{ // #nosec G124: clearing must target the same HTTP-compatible fallback token cookie.
- Name: InsecureTokenCookieName,
- Value: "",
- Path: "/",
- MaxAge: -1,
- HttpOnly: true,
- SameSite: http.SameSiteLaxMode,
+// BuildClearTokenCookieStringsFor builds Set-Cookie header strings to clear
+// token cookies matching the current request security context. Secure contexts
+// also clear the HTTP fallback cookie so stale sessions from older releases are
+// flushed instead of being re-presented forever.
+func BuildClearTokenCookieStringsFor(secure bool) []string {
+ headers := []string{buildClearTokenCookieStringInternal(InsecureTokenCookieName, false)}
+ if secure {
+ headers = append(headers, buildClearTokenCookieStringInternal(TokenCookieName, true))
}
- return cookie.String()
+ return headers
}
-// BuildClearTokenCookieStringFor builds a Set-Cookie header string to clear the
-// token cookie variant matching the connection's TLS state — `__Host-token` for
-// TLS, `token` otherwise — mirroring ClearTokenCookie for callers that have no
-// http.ResponseWriter (e.g. Huma middleware).
-func BuildClearTokenCookieStringFor(secure bool) string {
- name := InsecureTokenCookieName
- if secure {
- name = TokenCookieName
- }
+func buildClearTokenCookieStringInternal(name string, secure bool) string {
cookie := &http.Cookie{ // #nosec G124: Secure mirrors the caller-provided TLS state so the clear directive matches whichever cookie variant (__Host-token vs. token) was originally set.
Name: name,
Value: "",
diff --git a/backend/pkg/utils/cookie/cookie_util_test.go b/backend/pkg/utils/cookie/cookie_util_test.go
new file mode 100644
index 000000000..6ffa1cdc5
--- /dev/null
+++ b/backend/pkg/utils/cookie/cookie_util_test.go
@@ -0,0 +1,86 @@
+package cookie
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestIsSecureInternal(t *testing.T) {
+ t.Run("plain http returns false", func(t *testing.T) {
+ req := httptest.NewRequest("GET", "http://example.com/", nil)
+ assert.False(t, isSecureInternal(req))
+ })
+
+ t.Run("X-Forwarded-Proto https is not trusted directly", func(t *testing.T) {
+ req := httptest.NewRequest("GET", "http://example.com/", nil)
+ req.Header.Set("X-Forwarded-Proto", "https")
+ assert.False(t, isSecureInternal(req))
+ })
+
+ t.Run("secure cookie context returns true", func(t *testing.T) {
+ req := httptest.NewRequest("GET", "http://example.com/", nil)
+ req = req.WithContext(WithSecureCookieContext(context.Background(), true))
+ assert.True(t, isSecureInternal(req))
+ })
+}
+
+func TestBuildTokenCookieStringFor(t *testing.T) {
+ t.Run("secure uses host-prefixed secure cookie", func(t *testing.T) {
+ header := BuildTokenCookieStringFor(60, "abc", true)
+
+ cookies := readSetCookieHeadersInternal(t, header)
+ require.Len(t, cookies, 1)
+ assert.Equal(t, TokenCookieName, cookies[0].Name)
+ assert.True(t, cookies[0].Secure)
+ })
+
+ t.Run("insecure uses fallback cookie", func(t *testing.T) {
+ header := BuildTokenCookieStringFor(60, "abc", false)
+
+ cookies := readSetCookieHeadersInternal(t, header)
+ require.Len(t, cookies, 1)
+ assert.Equal(t, InsecureTokenCookieName, cookies[0].Name)
+ assert.False(t, cookies[0].Secure)
+ })
+}
+
+func TestBuildClearTokenCookieStringsFor(t *testing.T) {
+ t.Run("secure clears fallback and host-prefixed cookies", func(t *testing.T) {
+ headers := BuildClearTokenCookieStringsFor(true)
+
+ require.Len(t, headers, 2)
+ assert.Equal(t, InsecureTokenCookieName, readSetCookieHeadersInternal(t, headers[0])[0].Name)
+ secureCookie := readSetCookieHeadersInternal(t, headers[1])[0]
+ assert.Equal(t, TokenCookieName, secureCookie.Name)
+ assert.True(t, secureCookie.Secure)
+ })
+
+ t.Run("insecure clears only fallback cookie", func(t *testing.T) {
+ headers := BuildClearTokenCookieStringsFor(false)
+
+ require.Len(t, headers, 1)
+ clearCookie := readSetCookieHeadersInternal(t, headers[0])[0]
+ assert.Equal(t, InsecureTokenCookieName, clearCookie.Name)
+ assert.False(t, clearCookie.Secure)
+ })
+}
+
+func readSetCookieHeadersInternal(t *testing.T, headers ...string) []*http.Cookie {
+ t.Helper()
+
+ resp := &http.Response{
+ Header: http.Header{
+ "Set-Cookie": headers,
+ },
+ }
+ for _, header := range headers {
+ require.NotContains(t, strings.ToLower(header), "samesite=none")
+ }
+ return resp.Cookies()
+}