cors icon indicating copy to clipboard operation
cors copied to clipboard

fix: prevent data races from shared header value slices

Open Yanhu007 opened this issue 7 months ago • 2 comments

Fixes #198

Problem

Package-level slice variables (headerVaryOrigin, headerOriginAll, headerTrue) and struct field slices (preflightVary, exposedHeaders, maxAge) are assigned directly to http.Header maps. Since http.Header values are []string, downstream handlers can mutate the backing array (e.g., via append, slices.Sort, or direct index writes), causing data races when the middleware serves concurrent requests.

Fix

  • Replace package-level var slice declarations with const string values
  • Create fresh []string{...} literals at each assignment site, so each request gets its own backing array
  • Apply the same treatment to struct field slices (preflightVary, exposedHeaders, maxAge)

This eliminates the shared mutable state while keeping the same observable behavior. The allocation cost is negligible — one small slice per CORS header per request.

Testing

All existing tests pass, including with -race.

Yanhu007 avatar Apr 14 '26 12:04 Yanhu007

@Yanhu007 See https://github.com/rs/cors/pull/199, which also aims at fixing #198.

jub0bs avatar Apr 22 '26 09:04 jub0bs

append would be thread safe since the slices are at capacity. Sorting or setting headers by index is unrealistic use cases.

@Yanhu007 did you trigger this bug in your own code?

rs avatar Apr 22 '26 10:04 rs