feat(19.3-02): per-group CORS policies through cors:<profile> with router-registered preflights

- surf: LoadCORSProfiles reads http.cors_profiles.<name> (http.cors keys
  without paths, validated the same way); factory cors:<profile> sets the
  profile's headers; an unknown profile fails boot naming plugin and route
- BuildRouter registers OPTIONS <path> (owner surf, recovery only) for every
  path whose routes name cors:<profile>; two profiles on one path, an existing
  OPTIONS route or overlap with http.cors.paths fail boot
- docs: CORS profiles section, middleware table and README rows
This commit is contained in:
Jakub Zych
2026-10-15 17:51:58 +02:00
parent e7659f2f4b
commit 5055e8bb61
5 changed files with 274 additions and 1 deletions

View File

@@ -212,6 +212,145 @@ func pathScopedCORS(cfg CORSConfig, next http.Handler) http.Handler {
})
}
// corsProfileName is the character set of a cors_profiles name, the plugin-id
// set without dots: lower-case letters, digits, underscore and dash.
var corsProfileName = regexp.MustCompile(`^[a-z0-9_-]+$`)
// LoadCORSProfiles reads every child of http.cors_profiles. A profile takes
// the http.cors keys except paths (it applies to the routes that name
// cors:<profile>) and is validated like http.cors, with errors naming
// http.cors_profiles.<name>.<key>. A missing section yields an empty map.
func LoadCORSProfiles(cfg *compass.Config) (map[string]CORSConfig, error) {
out := map[string]CORSConfig{}
if cfg == nil || !cfg.Has("http.cors_profiles") {
return out, nil
}
raw, _ := cfg.Lookup("http.cors_profiles")
tree, ok := raw.(map[string]any)
if !ok {
return nil, fmt.Errorf("surf: http.cors_profiles must be a map of profile names, got %T", raw)
}
for name := range tree {
if !corsProfileName.MatchString(name) {
return nil, fmt.Errorf("surf: http.cors_profiles.%s: a profile name uses lower-case letters, digits, underscore and dash", name)
}
prefix := "http.cors_profiles." + name
var pc CORSConfig
if err := cfg.LoadSection(prefix, &pc); err != nil {
return nil, fmt.Errorf("surf: %s: %w", prefix, err)
}
if len(pc.Paths) > 0 {
return nil, fmt.Errorf("surf: %s.paths is not allowed: a profile applies to the routes that name cors:%s", prefix, name)
}
if err := validateCORSConfig(prefix, pc); err != nil {
return nil, err
}
out[name] = pc
}
return out, nil
}
// profileMiddleware sets the profile's CORS headers on a non-OPTIONS request;
// preflights reach the OPTIONS route compile registers instead.
func (p *corsPolicy) profileMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodOptions {
p.apply(w.Header(), r.Header.Get("Origin"))
}
next.ServeHTTP(w, r)
})
}
// routeCORSProfile returns the profile a route names through cors:<profile>,
// or "" when it names none. Two different profiles on one route are an error.
func routeCORSProfile(rt route) (string, error) {
profile := ""
for _, name := range rt.middleware {
base, param, ok := strings.Cut(name, ":")
if !ok || base != "cors" {
continue
}
if profile != "" && profile != param {
return "", fmt.Errorf("surf: route %s %s (plugin %q) names two CORS profiles, %q and %q", rt.method, rt.path, rt.pluginID, profile, param)
}
profile = param
}
return profile, nil
}
// addCORSPreflights registers one OPTIONS route per path whose routes name
// cors:<profile>, answering the preflight from that profile. ServeMux would
// otherwise answer such a preflight with 405 before any route middleware
// runs. A path that two profiles claim, a path the global http.cors.paths
// also matches (the global wrapper would answer its preflight first) and an
// OPTIONS route a plugin already declared are boot errors.
func (r *Router) addCORSPreflights() error {
if len(r.corsProfiles) == 0 {
return nil
}
globs := make([]*regexp.Regexp, 0, len(r.corsCfg.Paths))
for _, p := range r.corsCfg.Paths {
if re := compileLaravelGlob(p); re != nil {
globs = append(globs, re)
}
}
type claim struct {
profile string
owner route
}
claims := map[string]claim{}
var order []string
for _, rt := range r.routes {
if rt.preflight {
continue
}
profile, err := routeCORSProfile(rt)
if err != nil {
return err
}
if profile == "" {
continue
}
if _, ok := r.corsProfiles[profile]; !ok {
return fmt.Errorf("surf: plugin %q route %s %s references unknown CORS profile %q (define http.cors_profiles.%s)", rt.pluginID, rt.method, rt.path, profile, profile)
}
if pathMatchesCORS(globs, rt.path) {
return fmt.Errorf("surf: route %s %s (plugin %q) names cors:%s but its path also matches http.cors.paths; the global CORS wrapper would answer its preflight first", rt.method, rt.path, rt.pluginID, profile)
}
if prev, ok := claims[rt.path]; ok {
if prev.profile != profile {
return fmt.Errorf("surf: path %s has routes with different CORS profiles: %s %s (plugin %q) names cors:%s, %s %s (plugin %q) names cors:%s", rt.path, prev.owner.method, prev.owner.path, prev.owner.pluginID, prev.profile, rt.method, rt.path, rt.pluginID, profile)
}
continue
}
claims[rt.path] = claim{profile: profile, owner: rt}
order = append(order, rt.path)
}
for _, path := range order {
c := claims[path]
key := http.MethodOptions + " " + path
if prev, ok := r.seen[key]; ok {
return fmt.Errorf("surf: route %s registered by %s collides with the preflight route cors:%s needs", key, prev, c.profile)
}
r.seen[key] = corsPreflightOwner
policy := r.corsProfiles[c.profile]
r.routes = append(r.routes, route{
pluginID: corsPreflightOwner,
method: http.MethodOptions,
path: path,
handler: http.HandlerFunc(policy.preflight),
constraints: append([]Constraint(nil), c.owner.constraints...),
raw: true,
preflight: true,
})
}
return nil
}
// corsPreflightOwner is the plugin ID route:list shows for the OPTIONS
// routes addCORSPreflights registers.
const corsPreflightOwner = "surf"
// writeOptions answers an OPTIONS request on a CORS path with 204 and the
// headers Laravel's HandleCors (fruitcake/php-cors) sends, so recorded PHP
// preflights replay unchanged. Every answer carries Symfony's default