Files
Paul PicazoandClaude Opus 5.5 d66a219bcb feat(cors): let a UI on another origin connect, static host previews included (#2362)
## What this does

Server changes so the UI can be served from another origin, such as a
Cloudflare Pages project and its previews, against an existing backend.
It ships before the frontend, which is parked on
[`backup/static-frontend-1a`](https://github.com/ppicazo/CoreScope/tree/backup/static-frontend-1a)
and will come as its own PR.

- **Exposed headers:** allowed origins get
`Access-Control-Expose-Headers: Retry-After, X-CoreScope-Load-Status`.
The UI reads both, and cross-origin they are `null` without this.
- **Wildcard origins:** an entry may be `scheme://*.host[:port]`, such
as `https://*.myproject.pages.dev`. It matches exactly one leftmost
label (each deploy and branch preview) for both CORS and `/ws`, but not
`myproject.pages.dev` itself. The part after `*.` needs at least three
labels, so `*.pages.dev` is refused. Refused or malformed wildcards are
dropped at startup with a log line. That floor is a sanity check, not a
Public Suffix List lookup: `https://*.s3.amazonaws.com` passes and would
admit every S3 website endpoint, so a wildcard belongs only over a host
the operator controls.
- **Case:** exact entries now match case-insensitively for CORS (was
`==`), as they already did for `/ws`.
- **Test only:** pins that the three anonymous POSTs (`/api/decode`,
`/api/packets/observations`, `/api/paths/inspect`) accept a `text/plain`
JSON body, which keeps them free of a preflight.

Credentials stay off, so nothing a listed origin sends rides on cookies.
Beyond GET, a listed origin, and so every deployment under a wildcard
entry, can:

- call those three anonymous POSTs as simple requests. That predates
this PR; they compute an answer and write nothing.
`Access-Control-Allow-Methods: GET, HEAD, OPTIONS` only governs
preflighted requests.
- with `userManagement.enabled`, use the existing bearer tier for
companion linking (`/api/auth/device-token`, `/api/auth/me`,
`/api/auth/logout`, `/api/account/settings`, `/api/account/companions*`)
with POST, PUT and DELETE. Those routes need a device token in
`Authorization`, not a cookie, but a preview deployment gets them too.
On such a server, list a wildcard only if previews may use them.

## Configuring

```yaml
- CORS_ALLOWED_ORIGINS=https://existing-embed.example,https://myproject.pages.dev,https://*.myproject.pages.dev
```

The env var replaces `corsAllowedOrigins`, so keep the origins already
listed there.

## Testing

- `go test ./...`, `go vet` and `gofmt` are clean in `cmd/server`. The
new tests were written first and failed first.
- In Chromium, the static build from the backup branch, served on
`pr-1.proj.preview.localhost`, passed its split E2E (9/9, WebSocket
included) against this server.
- From the same setup, the project origin connected, a two-level
subdomain was blocked, and `X-CoreScope-Load-Status` read `ready` where
master gives `null`.

## Performance

These run per request in the CORS middleware and the `/ws` handshake,
and they allocate nothing. Same-origin requests skip them.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 17:46:17 +01:00

68 lines
2.1 KiB
Go

package main
import (
"net/http/httptest"
"strings"
"testing"
)
// A frontend served from another origin (a static host listed in
// CORS_ALLOWED_ORIGINS) reads two response headers besides Content-Type:
// Retry-After (api() on a warm-up 503, node-reach.js on a 429) and
// X-CoreScope-Load-Status (warmup-banner.js). Cross-origin, fetch exposes only
// the CORS-safelisted headers unless the server lists the rest in
// Access-Control-Expose-Headers; without it both read as null.
func exposedHeaders(t *testing.T, origins []string, origin string) map[string]bool {
t.Helper()
handler := newTestServerWithCORS(origins).corsMiddleware(dummyHandler)
req := httptest.NewRequest("GET", "/api/stats", nil)
if origin != "" {
req.Header.Set("Origin", origin)
}
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
got := map[string]bool{}
for _, v := range rr.Header().Values("Access-Control-Expose-Headers") {
for _, name := range strings.Split(v, ",") {
if name = strings.TrimSpace(name); name != "" {
got[strings.ToLower(name)] = true
}
}
}
return got
}
func TestCORS_ExposesRetryAfterAndLoadStatus(t *testing.T) {
for _, tc := range []struct {
name string
origins []string
}{
{"listed origin", []string{"https://beta.example"}},
{"wildcard", []string{"*"}},
} {
got := exposedHeaders(t, tc.origins, "https://beta.example")
for _, want := range []string{"retry-after", "x-corescope-load-status"} {
if !got[want] {
t.Errorf("%s: Access-Control-Expose-Headers lacks %s, got %v", tc.name, want, got)
}
}
}
}
func TestCORS_NoExposeHeadersWithoutAnAllowedOrigin(t *testing.T) {
for _, tc := range []struct {
name string
origins []string
origin string
}{
{"no CORS list", nil, "https://beta.example"},
{"unlisted origin", []string{"https://beta.example"}, "https://evil.example"},
{"same-origin request (no Origin header)", []string{"https://beta.example"}, ""},
} {
if got := exposedHeaders(t, tc.origins, tc.origin); len(got) != 0 {
t.Errorf("%s: expected no Access-Control-Expose-Headers, got %v", tc.name, got)
}
}
}