Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(auth): derive cookie Secure flag from FRONTEND_ORIGIN scheme (#1390)

Bohan Jiang824d94384858
diff --git a/.env.example b/.env.example
index 23918ca5c7..c0ecc835c4 100644
--- a/.env.example
+++ b/.env.example
@@ -56,6 +56,13 @@ CLOUDFRONT_KEY_PAIR_ID=
CLOUDFRONT_PRIVATE_KEY_SECRET=multica/cloudfront-signing-key
CLOUDFRONT_PRIVATE_KEY=
CLOUDFRONT_DOMAIN=
+# COOKIE_DOMAIN — optional Domain attribute on session + CloudFront cookies.
+# Leave empty for single-host deployments (localhost, LAN IP, or a single
+# hostname) — session cookies become host-only, which is what the browser
+# wants. Only set it when the frontend and backend sit on different
+# subdomains of one registered domain (e.g. ".example.com"). Do NOT set it
+# to an IP address: RFC 6265 forbids IP literals in the cookie Domain
+# attribute and browsers silently drop such cookies.
COOKIE_DOMAIN=
# Local file storage (fallback when S3_BUCKET is not set)
diff --git a/SELF_HOSTING_ADVANCED.md b/SELF_HOSTING_ADVANCED.md
index 7d8f7bae07..b4b4bf4ebd 100644
--- a/SELF_HOSTING_ADVANCED.md
+++ b/SELF_HOSTING_ADVANCED.md
@@ -53,7 +53,14 @@ For file uploads and attachments, configure S3 and CloudFront:
| `CLOUDFRONT_DOMAIN` | CloudFront distribution domain |
| `CLOUDFRONT_KEY_PAIR_ID` | CloudFront key pair ID for signed URLs |
| `CLOUDFRONT_PRIVATE_KEY` | CloudFront private key (PEM format) |
-| `COOKIE_DOMAIN` | Domain for CloudFront auth cookies |
+
+### Cookies
+
+| Variable | Description |
+|----------|-------------|
+| `COOKIE_DOMAIN` | Optional `Domain` attribute for session + CloudFront cookies. **Leave empty** for single-host deployments (localhost, LAN IP, or a single hostname). Only set it when the frontend and backend sit on different subdomains of one registered domain (e.g. `.example.com`). **Do not use an IP literal** — RFC 6265 forbids IP addresses in the cookie `Domain` attribute and browsers will drop such `Set-Cookie` headers. |
+
+The `Secure` flag on session cookies is derived automatically from the scheme of `FRONTEND_ORIGIN`: HTTPS origins get `Secure` cookies; plain-HTTP origins (LAN / private-network self-host) get non-secure cookies so the browser can actually store them.
### Server
diff --git a/apps/docs/content/docs/getting-started/self-hosting.mdx b/apps/docs/content/docs/getting-started/self-hosting.mdx
index 462614cc5c..227571c81e 100644
--- a/apps/docs/content/docs/getting-started/self-hosting.mdx
+++ b/apps/docs/content/docs/getting-started/self-hosting.mdx
@@ -202,7 +202,14 @@ For file uploads and attachments, configure S3 and CloudFront:
| `CLOUDFRONT_DOMAIN` | CloudFront distribution domain |
| `CLOUDFRONT_KEY_PAIR_ID` | CloudFront key pair ID for signed URLs |
| `CLOUDFRONT_PRIVATE_KEY` | CloudFront private key (PEM format) |
-| `COOKIE_DOMAIN` | Domain for CloudFront auth cookies |
+
+### Cookies
+
+| Variable | Description |
+|----------|-------------|
+| `COOKIE_DOMAIN` | Optional `Domain` attribute for session + CloudFront cookies. **Leave empty** for single-host deployments (localhost, LAN IP, or a single hostname). Only set it when the frontend and backend sit on different subdomains of one registered domain (e.g. `.example.com`). **Do not use an IP literal** — RFC 6265 forbids IP addresses in the cookie `Domain` attribute and browsers will drop such `Set-Cookie` headers. |
+
+The `Secure` flag on session cookies is derived automatically from the scheme of `FRONTEND_ORIGIN`: HTTPS origins get `Secure` cookies; plain-HTTP origins (LAN / private-network self-host) get non-secure cookies so the browser can actually store them.
### Server
diff --git a/server/internal/auth/cookie.go b/server/internal/auth/cookie.go
index 6846466135..5f3330535b 100644
--- a/server/internal/auth/cookie.go
+++ b/server/internal/auth/cookie.go
@@ -5,25 +5,61 @@ import (
"crypto/rand"
"crypto/sha256"
"encoding/hex"
+ "log/slog"
+ "net"
"net/http"
+ "net/url"
"os"
"strings"
+ "sync"
"time"
)
const (
- AuthCookieName = "multica_auth"
- CSRFCookieName = "multica_csrf"
+ AuthCookieName = "multica_auth"
+ CSRFCookieName = "multica_csrf"
authCookieMaxAge = 30 * 24 * 60 * 60 // 30 days in seconds
)
+var ipCookieDomainWarnOnce sync.Once
+
+// cookieDomain returns the trimmed COOKIE_DOMAIN env value, or "" if it looks
+// like an IP address. RFC 6265 §4.1.2.3 forbids IP literals in the cookie
+// Domain attribute, so browsers silently drop Set-Cookie headers that carry
+// one. An IP value here is almost always a misconfiguration.
func cookieDomain() string {
- return strings.TrimSpace(os.Getenv("COOKIE_DOMAIN"))
+ raw := strings.TrimSpace(os.Getenv("COOKIE_DOMAIN"))
+ if raw == "" {
+ return ""
+ }
+ // A leading dot ("." for subdomain matching) is legal syntax but doesn't
+ // change whether the remainder is an IP literal.
+ if ip := net.ParseIP(strings.TrimPrefix(raw, ".")); ip != nil {
+ ipCookieDomainWarnOnce.Do(func() {
+ slog.Warn(
+ "COOKIE_DOMAIN looks like an IP address; ignoring. RFC 6265 forbids IP literals in the cookie Domain attribute, so browsers would drop the Set-Cookie. Leave COOKIE_DOMAIN empty for single-host deployments, or use a real domain.",
+ "value", raw,
+ )
+ })
+ return ""
+ }
+ return raw
}
+// isSecureCookie reports whether session cookies should carry the Secure flag.
+// Derived from the scheme of FRONTEND_ORIGIN — browsers silently drop Secure
+// cookies received on a plain-HTTP page, so the flag has to track the actual
+// user-facing scheme rather than a coarser environment name.
func isSecureCookie() bool {
- env := os.Getenv("APP_ENV")
- return env == "production" || env == "staging"
+ raw := strings.TrimSpace(os.Getenv("FRONTEND_ORIGIN"))
+ if raw == "" {
+ return false
+ }
+ u, err := url.Parse(raw)
+ if err != nil {
+ return false
+ }
+ return strings.EqualFold(u.Scheme, "https")
}
// generateCSRFToken creates a CSRF token bound to the auth token via HMAC.
diff --git a/server/internal/auth/cookie_test.go b/server/internal/auth/cookie_test.go
new file mode 100644
index 0000000000..40ec49a28d
--- /dev/null
+++ b/server/internal/auth/cookie_test.go
@@ -0,0 +1,101 @@
+package auth
+
+import (
+ "net/http/httptest"
+ "testing"
+)
+
+func TestIsSecureCookie(t *testing.T) {
+ cases := []struct {
+ name string
+ frontendOrigin string
+ want bool
+ }{
+ {"https origin → Secure", "https://app.example.com", true},
+ {"https with port", "https://app.example.com:8443", true},
+ {"http origin → not Secure", "http://192.168.5.5:13000", false},
+ {"http localhost → not Secure", "http://localhost:3000", false},
+ {"empty → not Secure", "", false},
+ {"malformed → not Secure", "::not-a-url", false},
+ {"uppercase scheme still matches", "HTTPS://app.example.com", true},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Setenv("FRONTEND_ORIGIN", tc.frontendOrigin)
+ if got := isSecureCookie(); got != tc.want {
+ t.Errorf("isSecureCookie() = %v, want %v (FRONTEND_ORIGIN=%q)", got, tc.want, tc.frontendOrigin)
+ }
+ })
+ }
+}
+
+func TestCookieDomain(t *testing.T) {
+ cases := []struct {
+ name string
+ env string
+ want string
+ }{
+ {"empty", "", ""},
+ {"whitespace only", " ", ""},
+ {"real domain", ".example.com", ".example.com"},
+ {"bare domain", "example.com", "example.com"},
+ {"IPv4 rejected", "192.168.5.5", ""},
+ {"IPv4 with leading dot rejected", ".192.168.5.5", ""},
+ {"IPv6 rejected", "::1", ""},
+ {"IPv6 bracketed is not a valid IP literal → passthrough", "[::1]", "[::1]"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Setenv("COOKIE_DOMAIN", tc.env)
+ if got := cookieDomain(); got != tc.want {
+ t.Errorf("cookieDomain() = %q, want %q (COOKIE_DOMAIN=%q)", got, tc.want, tc.env)
+ }
+ })
+ }
+}
+
+// TestSetAuthCookies_HTTPSelfHost covers the exact misconfiguration that
+// shipped to users on LAN self-host: COOKIE_DOMAIN=<ip> + HTTP FRONTEND_ORIGIN.
+// The cookie must land with no Domain attribute and Secure=false so browsers
+// actually store it.
+func TestSetAuthCookies_HTTPSelfHost(t *testing.T) {
+ t.Setenv("FRONTEND_ORIGIN", "http://192.168.5.5:13000")
+ t.Setenv("COOKIE_DOMAIN", "192.168.5.5")
+
+ rec := httptest.NewRecorder()
+ if err := SetAuthCookies(rec, "test-token"); err != nil {
+ t.Fatalf("SetAuthCookies: %v", err)
+ }
+
+ cookies := rec.Result().Cookies()
+ if len(cookies) != 2 {
+ t.Fatalf("expected 2 cookies (auth + csrf), got %d", len(cookies))
+ }
+ for _, c := range cookies {
+ if c.Secure {
+ t.Errorf("cookie %q has Secure=true on HTTP origin; browser would reject it", c.Name)
+ }
+ if c.Domain != "" {
+ t.Errorf("cookie %q has Domain=%q; IP-address Domain would be rejected by the browser (RFC 6265)", c.Name, c.Domain)
+ }
+ }
+}
+
+func TestSetAuthCookies_HTTPSProduction(t *testing.T) {
+ t.Setenv("FRONTEND_ORIGIN", "https://app.example.com")
+ t.Setenv("COOKIE_DOMAIN", "app.example.com")
+
+ rec := httptest.NewRecorder()
+ if err := SetAuthCookies(rec, "test-token"); err != nil {
+ t.Fatalf("SetAuthCookies: %v", err)
+ }
+
+ for _, c := range rec.Result().Cookies() {
+ if !c.Secure {
+ t.Errorf("cookie %q missing Secure flag on HTTPS origin", c.Name)
+ }
+ if c.Domain != "app.example.com" {
+ t.Errorf("cookie %q Domain = %q, want %q", c.Name, c.Domain, "app.example.com")
+ }
+ }
+}