HH-547: allow cross-origin widget requests (#126)
* HH-547: allow cross-origin widget requests * fix(HH-547): align production preflight with wildcard CORS --------- Co-authored-by: Rogee <rogee@ipao.vip>
This commit is contained in:
@@ -1,9 +1,6 @@
|
||||
# GoChat production overrides. Secrets and public origins must come from the environment.
|
||||
# GoChat production overrides. Secrets must come from the environment.
|
||||
server:
|
||||
mode: "release"
|
||||
cors:
|
||||
allowed_origins: ["https://CHANGE_ME.example.com"]
|
||||
allow_credentials: true
|
||||
|
||||
database:
|
||||
dsn: "postgres://gochat:CHANGE_ME@postgres:5432/gochat_production?sslmode=disable"
|
||||
|
||||
@@ -10,14 +10,11 @@ server:
|
||||
max_header_bytes: 1048576
|
||||
trusted_proxies: [] # add explicit reverse-proxy IPs/CIDRs; XFF is ignored otherwise
|
||||
cors:
|
||||
allowed_origins: [] # empty = Allow-Origin:* in debug mode; production must list exact origins
|
||||
# Examples:
|
||||
# - "https://app.example.com"
|
||||
# - "*.example.com"
|
||||
allowed_origins: [] # retained for config compatibility; GoChat allows all origins
|
||||
allowed_methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]
|
||||
allowed_headers: ["Origin", "Content-Type", "Accept", "Authorization", "X-Account-ID", "access-token", "client", "uid", "token-type", "expiry"]
|
||||
allowed_headers: ["Origin", "Content-Type", "Accept", "Authorization", "X-Account-ID", "X-Auth-Token", "X-Widget-Token", "X-Identifier-Hash", "access-token", "client", "uid", "token-type", "expiry"]
|
||||
expose_headers: ["Content-Length", "access-token", "client", "uid", "token-type", "expiry"]
|
||||
allow_credentials: false # set to true only if you need cookies/auth headers
|
||||
allow_credentials: false # retained for config compatibility; wildcard CORS does not use credentials
|
||||
max_age: 86400 # preflight cache duration in seconds
|
||||
|
||||
database:
|
||||
|
||||
@@ -22,7 +22,7 @@ func validReleaseConfig() *Config {
|
||||
}
|
||||
}
|
||||
|
||||
func TestReleaseTransportAndCORSValidationFailsClosed(t *testing.T) {
|
||||
func TestReleaseTransportValidationFailsClosed(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*Config)
|
||||
@@ -30,9 +30,6 @@ func TestReleaseTransportAndCORSValidationFailsClosed(t *testing.T) {
|
||||
}{
|
||||
{"database TLS without identity verification", func(c *Config) { c.Database.DSN = "postgres://user:pass@db.acme.test/gochat?sslmode=require" }, "sslmode=disable, verify-full or verify-ca"},
|
||||
{"redis certificate not verified", func(c *Config) { c.Redis.DSN = "rediss://:redis-secret@redis.acme.test:6379?insecure_skip_verify=true" }, "cannot be disabled"},
|
||||
{"placeholder origin", func(c *Config) { c.Server.CORS.AllowedOrigins = []string{"https://example.com"} }, "not deployable"},
|
||||
{"non HTTPS origin", func(c *Config) { c.Server.CORS.AllowedOrigins = []string{"http://chat.acme.test"} }, "exact HTTPS origin"},
|
||||
{"wildcard origin", func(c *Config) { c.Server.CORS.AllowedOrigins = []string{"*.acme.test"} }, "exact HTTPS origin"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
|
||||
@@ -136,19 +136,6 @@ func Validate(cfg *Config) error {
|
||||
if redisURL.Scheme == "rediss" && strings.EqualFold(redisURL.Query().Get("insecure_skip_verify"), "true") {
|
||||
return fmt.Errorf("production Redis TLS certificate verification cannot be disabled")
|
||||
}
|
||||
if len(cfg.Server.CORS.AllowedOrigins) == 0 {
|
||||
return fmt.Errorf("production CORS requires at least one HTTPS origin")
|
||||
}
|
||||
for _, origin := range cfg.Server.CORS.AllowedOrigins {
|
||||
parsed, err := url.Parse(origin)
|
||||
lower := strings.ToLower(origin)
|
||||
if err != nil || parsed.Scheme != "https" || parsed.Host == "" || parsed.Path != "" || parsed.RawQuery != "" || parsed.Fragment != "" {
|
||||
return fmt.Errorf("production CORS origin must be an exact HTTPS origin: %q", origin)
|
||||
}
|
||||
if strings.Contains(origin, "*") || strings.Contains(lower, "localhost") || strings.Contains(lower, "example.") || strings.Contains(lower, "yourdomain") || containsPlaceholder(origin) {
|
||||
return fmt.Errorf("production CORS origin is not deployable: %q", origin)
|
||||
}
|
||||
}
|
||||
if cfg.JWT.AccessExpiryMinutes <= 0 || cfg.JWT.AccessExpiryMinutes > 15 {
|
||||
return fmt.Errorf("production JWT access_expiry_minutes must be between 1 and 15")
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ type CORSConfig struct {
|
||||
|
||||
// Default CORS values for production.
|
||||
var defaultCORSMethods = []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"}
|
||||
var defaultCORSHeaders = []string{"Origin", "Content-Type", "Accept", "Authorization", "X-Account-ID", "access-token", "client", "uid", "token-type", "expiry"}
|
||||
var defaultCORSHeaders = []string{"Origin", "Content-Type", "Accept", "Authorization", "X-Account-ID", "X-Auth-Token", "X-Widget-Token", "X-Identifier-Hash", "access-token", "client", "uid", "token-type", "expiry"}
|
||||
var defaultCORSExposeHeaders = []string{"Content-Length", "access-token", "client", "uid", "token-type", "expiry"}
|
||||
var defaultCORSMaxAge = 86400 // 24 hours
|
||||
|
||||
@@ -170,16 +170,13 @@ func extractHost(origin string) string {
|
||||
return u.Hostname()
|
||||
}
|
||||
|
||||
// CORSConfigFromAppConfig creates a middleware CORSConfig from the application config.
|
||||
// CORSConfigFromAppConfig keeps method/header tuning while allowing every embed origin.
|
||||
func CORSConfigFromAppConfig(cfg *config.Config) CORSConfig {
|
||||
devMode := cfg.Server.Mode == "debug"
|
||||
return CORSConfig{
|
||||
AllowedOrigins: cfg.Server.CORS.AllowedOrigins,
|
||||
AllowedMethods: cfg.Server.CORS.AllowedMethods,
|
||||
AllowedHeaders: cfg.Server.CORS.AllowedHeaders,
|
||||
ExposeHeaders: cfg.Server.CORS.ExposeHeaders,
|
||||
AllowCredentials: cfg.Server.CORS.AllowCredentials,
|
||||
MaxAge: cfg.Server.CORS.MaxAge,
|
||||
DevMode: devMode,
|
||||
AllowedMethods: cfg.Server.CORS.AllowedMethods,
|
||||
AllowedHeaders: cfg.Server.CORS.AllowedHeaders,
|
||||
ExposeHeaders: cfg.Server.CORS.ExposeHeaders,
|
||||
MaxAge: cfg.Server.CORS.MaxAge,
|
||||
DevMode: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,11 +58,38 @@ func TestCORS_DefaultAllowedHeadersIncludeChatwootAuthTokens(t *testing.T) {
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
allowedHeaders := w.Header().Get("Access-Control-Allow-Headers")
|
||||
for _, header := range []string{"access-token", "client", "uid", "token-type", "expiry"} {
|
||||
for _, header := range []string{"access-token", "client", "uid", "token-type", "expiry", "X-Auth-Token", "X-Widget-Token", "X-Identifier-Hash"} {
|
||||
assert.Contains(t, allowedHeaders, header)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCORSConfigFromAppConfig_AllowsWidgetPreflightFromAnyProductionOrigin(t *testing.T) {
|
||||
cfg := &config.Config{Server: config.ServerConfig{
|
||||
Mode: "release",
|
||||
CORS: config.CORSConfig{
|
||||
AllowedOrigins: []string{"https://gochat.example.com"},
|
||||
AllowCredentials: true,
|
||||
},
|
||||
}}
|
||||
router := gin.New()
|
||||
router.Use(CORS(CORSConfigFromAppConfig(cfg)))
|
||||
router.POST("/api/v1/widget/conversations/toggle_typing", func(c *gin.Context) { c.Status(http.StatusOK) })
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodOptions, "/api/v1/widget/conversations/toggle_typing", nil)
|
||||
req.Header.Set("Origin", "https://embedded.example.net")
|
||||
req.Header.Set("Access-Control-Request-Method", http.MethodPost)
|
||||
req.Header.Set("Access-Control-Request-Headers", "X-Auth-Token, X-Widget-Token, X-Identifier-Hash")
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
assert.Equal(t, http.StatusNoContent, w.Code)
|
||||
assert.Equal(t, "*", w.Header().Get("Access-Control-Allow-Origin"))
|
||||
for _, header := range []string{"X-Auth-Token", "X-Widget-Token", "X-Identifier-Hash"} {
|
||||
assert.Contains(t, w.Header().Get("Access-Control-Allow-Headers"), header)
|
||||
}
|
||||
assert.Empty(t, w.Header().Get("Access-Control-Allow-Credentials"))
|
||||
}
|
||||
|
||||
func TestCORS_DefaultExposeHeadersIncludeChatwootAuthTokens(t *testing.T) {
|
||||
cfg := CORSConfig{DevMode: true}
|
||||
router := gin.New()
|
||||
@@ -316,8 +343,8 @@ func TestCORSConfigFromAppConfig_DebugMode(t *testing.T) {
|
||||
|
||||
mwCfg := CORSConfigFromAppConfig(cfg)
|
||||
assert.True(t, mwCfg.DevMode)
|
||||
assert.Equal(t, []string{"https://app.example.com"}, mwCfg.AllowedOrigins)
|
||||
assert.True(t, mwCfg.AllowCredentials)
|
||||
assert.Empty(t, mwCfg.AllowedOrigins)
|
||||
assert.False(t, mwCfg.AllowCredentials)
|
||||
assert.Equal(t, 3600, mwCfg.MaxAge)
|
||||
}
|
||||
|
||||
@@ -337,12 +364,12 @@ func TestCORSConfigFromAppConfig_ProductionMode(t *testing.T) {
|
||||
}
|
||||
|
||||
mwCfg := CORSConfigFromAppConfig(cfg)
|
||||
assert.False(t, mwCfg.DevMode)
|
||||
assert.Equal(t, []string{"https://app.example.com", "*.internal.com"}, mwCfg.AllowedOrigins)
|
||||
assert.True(t, mwCfg.DevMode)
|
||||
assert.Empty(t, mwCfg.AllowedOrigins)
|
||||
assert.Equal(t, []string{"GET", "POST", "PUT"}, mwCfg.AllowedMethods)
|
||||
assert.Equal(t, []string{"Authorization", "Content-Type"}, mwCfg.AllowedHeaders)
|
||||
assert.Equal(t, []string{"X-Total-Count"}, mwCfg.ExposeHeaders)
|
||||
assert.True(t, mwCfg.AllowCredentials)
|
||||
assert.False(t, mwCfg.AllowCredentials)
|
||||
assert.Equal(t, 7200, mwCfg.MaxAge)
|
||||
}
|
||||
|
||||
@@ -355,7 +382,7 @@ func TestCORSConfigFromAppConfig_EmptyCORS(t *testing.T) {
|
||||
}
|
||||
|
||||
mwCfg := CORSConfigFromAppConfig(cfg)
|
||||
assert.False(t, mwCfg.DevMode)
|
||||
assert.True(t, mwCfg.DevMode)
|
||||
assert.Empty(t, mwCfg.AllowedOrigins)
|
||||
assert.Empty(t, mwCfg.AllowedMethods) // defaults applied in CORS() middleware, not here
|
||||
}
|
||||
|
||||
@@ -2018,7 +2018,7 @@ func TestCORSConfigFromAppConfig_Cov7(t *testing.T) {
|
||||
cfg.Server.CORS.AllowedOrigins = []string{"https://app.com"}
|
||||
result := CORSConfigFromAppConfig(cfg)
|
||||
assert.True(t, result.DevMode)
|
||||
assert.Equal(t, []string{"https://app.com"}, result.AllowedOrigins)
|
||||
assert.Empty(t, result.AllowedOrigins)
|
||||
}
|
||||
|
||||
// ===========================
|
||||
|
||||
Reference in New Issue
Block a user