Files
new-api/common/session_cookie.go
T
CaIon 56dbaab1d4 feat(session): support opt-in Secure session cookies
- add SESSION_COOKIE_SECURE / SESSION_COOKIE_TRUSTED_URL env vars with
  startup validation: enabling Secure requires at least one trusted
  HTTPS entry URL
- wire common.SessionCookieSecure into the session cookie store instead
  of a hardcoded Secure=false
- print a startup warning when Secure session cookies are disabled
- document the new settings in .env.example and docker-compose files

Secure stays off by default because many deployments front new-api with
plain-HTTP reverse proxies, where a hardcoded Secure default would break
logins entirely; enabling it safely depends on the deployment's TLS
setup, so it ships as an opt-in deployment-hardening flag.
2026-07-05 13:53:16 +08:00

51 lines
1.4 KiB
Go

package common
import (
"fmt"
"net/url"
"os"
"strings"
)
func InitSessionCookieSettings() error {
secureRaw := strings.TrimSpace(os.Getenv("SESSION_COOKIE_SECURE"))
trustedURLsRaw := strings.TrimSpace(os.Getenv("SESSION_COOKIE_TRUSTED_URL"))
SessionCookieSecure = false
SessionCookieTrustedURLs = nil
if secureRaw == "" || strings.EqualFold(secureRaw, "false") {
if trustedURLsRaw != "" {
return fmt.Errorf("SESSION_COOKIE_TRUSTED_URL requires SESSION_COOKIE_SECURE=true")
}
return nil
}
if !strings.EqualFold(secureRaw, "true") {
return fmt.Errorf("SESSION_COOKIE_SECURE must be true or false")
}
if trustedURLsRaw == "" {
return fmt.Errorf("SESSION_COOKIE_SECURE=true requires SESSION_COOKIE_TRUSTED_URL")
}
trustedURLs := strings.Split(trustedURLsRaw, ",")
for _, trustedURL := range trustedURLs {
trustedURL = strings.TrimSpace(trustedURL)
if trustedURL == "" {
return fmt.Errorf("SESSION_COOKIE_TRUSTED_URL contains an empty URL")
}
parsedURL, err := url.Parse(trustedURL)
if err != nil {
return fmt.Errorf("invalid SESSION_COOKIE_TRUSTED_URL: %w", err)
}
if parsedURL.Scheme != "https" || parsedURL.Host == "" {
return fmt.Errorf("SESSION_COOKIE_TRUSTED_URL must contain only https URLs with hosts")
}
SessionCookieTrustedURLs = append(SessionCookieTrustedURLs, trustedURL)
}
SessionCookieSecure = true
return nil
}