Skip to content

Commit 169bd66

Browse files
Merge pull request #16204 from liggitt/cors-escaping
Automatic merge from submit-queue Generate escaped regexes for cors config this ensures the generated config matches hosts exactly instead of treating `.` like a "match any character" rule
2 parents 381a143 + b81f5a5 commit 169bd66

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

pkg/cmd/server/start/master_args.go

+20-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"net"
66
"net/url"
77
"path"
8+
"regexp"
89
"strconv"
910

1011
"github.com/spf13/pflag"
@@ -127,6 +128,19 @@ func (args MasterArgs) GetConfigFileToWrite() string {
127128
return path.Join(args.ConfigDir.Value(), "master-config.yaml")
128129
}
129130

131+
// makeHostMatchRegex returns a regex that matches this host exactly.
132+
// If host contains a port, the returned regex matches the port exactly.
133+
// If host does not contain a port, the returned regex matches any port or no port.
134+
func makeHostMatchRegex(host string) string {
135+
if _, _, err := net.SplitHostPort(host); err == nil {
136+
// we have a port, match the end exactly
137+
return "//" + regexp.QuoteMeta(host) + "$"
138+
} else {
139+
// we don't have a port, match a port separator or the end
140+
return "//" + regexp.QuoteMeta(host) + "(:|$)"
141+
}
142+
}
143+
130144
// BuildSerializeableMasterConfig takes the MasterArgs (partially complete config) and uses them along with defaulting behavior to create the fully specified
131145
// config object for starting the master
132146
func (args MasterArgs) BuildSerializeableMasterConfig() (*configapi.MasterConfig, error) {
@@ -149,7 +163,12 @@ func (args MasterArgs) BuildSerializeableMasterConfig() (*configapi.MasterConfig
149163
// always include localhost as an allowed CORS origin
150164
// always include master public address as an allowed CORS origin
151165
corsAllowedOrigins := sets.NewString(args.CORSAllowedOrigins...)
152-
corsAllowedOrigins.Insert(assetPublicAddr.Host, masterPublicAddr.Host, "localhost", "127.0.0.1")
166+
corsAllowedOrigins.Insert(
167+
makeHostMatchRegex(assetPublicAddr.Host),
168+
makeHostMatchRegex(masterPublicAddr.Host),
169+
makeHostMatchRegex("localhost"),
170+
makeHostMatchRegex("127.0.0.1"),
171+
)
153172

154173
etcdAddress, err := args.GetEtcdAddress()
155174
if err != nil {

0 commit comments

Comments
 (0)