http servers: allow CORS to be set with --allow-origin flag - fixes #5078

Some changes about test cases:
Because MiddlewareCORS will return early on OPTIONS request,
this middleware should only be used once at NewServer function.
Test cases should pass AllowOrigin config instead of adding
this middleware again.

A new test case was added to test CORS preflight request with
an authenticator. Preflight request should always return 200 OK
regardless of autentications.

Co-authored-by: yuudi <yuudi@users.noreply.github.com>
This commit is contained in:
yuudi
2023-07-26 05:15:54 -04:00
committed by GitHub
parent 3ed4a2e963
commit 6c8148ef39
8 changed files with 95 additions and 75 deletions

View File

@@ -109,6 +109,7 @@ type Config struct {
TLSKeyBody []byte // TLS PEM Private key body, ignores TLSKey
ClientCA string // Client certificate authority to verify clients with
MinTLSVersion string // MinTLSVersion contains the minimum TLS version that is acceptable.
AllowOrigin string // AllowOrigin sets the Access-Control-Allow-Origin header
}
// AddFlagsPrefix adds flags for the httplib
@@ -122,6 +123,7 @@ func (cfg *Config) AddFlagsPrefix(flagSet *pflag.FlagSet, prefix string) {
flags.StringVarP(flagSet, &cfg.ClientCA, prefix+"client-ca", "", cfg.ClientCA, "Client certificate authority to verify clients with")
flags.StringVarP(flagSet, &cfg.BaseURL, prefix+"baseurl", "", cfg.BaseURL, "Prefix for URLs - leave blank for root")
flags.StringVarP(flagSet, &cfg.MinTLSVersion, prefix+"min-tls-version", "", cfg.MinTLSVersion, "Minimum TLS version that is acceptable")
flags.StringVarP(flagSet, &cfg.AllowOrigin, prefix+"allow-origin", "", cfg.AllowOrigin, "Origin which cross-domain request (CORS) can be executed from")
}
// AddHTTPFlagsPrefix adds flags for the httplib
@@ -236,6 +238,8 @@ func NewServer(ctx context.Context, options ...Option) (*Server, error) {
return nil, err
}
s.mux.Use(MiddlewareCORS(s.cfg.AllowOrigin))
s.initAuth()
for _, addr := range s.cfg.ListenAddr {