check / check (push) Successful in 4m34s
The CORS middleware with the `access_control_allow_origin` origin wrapped every route from the router root, so the login and URL generator pages and `/metrics` sent `Access-Control-Allow-Origin` too. It now wraps only `/v1/image/` and `/v1/e/`, which form a `/v1` subrouter so that a browser's preflight `OPTIONS` request still gets its answer; the maintenance mode group moved inside it unchanged. Every other route sends no CORS headers. A new test checks both image routes, a preflight included, and the login and URL generator pages. `README.md` and `config.example.yml` say the setting covers the image routes only. Unverified by test: `/metrics`, whose middleware registers with the process-wide Prometheus registry. Model: opus-5-5
65 lines
1.8 KiB
Go
65 lines
1.8 KiB
Go
package server
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
)
|
|
|
|
// TestCORSOnlyOnImageRoutes verifies that the image routes answer with the
|
|
// configured access_control_allow_origin, a preflight request included, and
|
|
// that the login and URL generator pages send no Access-Control-Allow-Origin,
|
|
// so no other site can read them. /metrics is left out: its middleware
|
|
// registers with the process-wide Prometheus registry, which only one test
|
|
// in this package can do.
|
|
func TestCORSOnlyOnImageRoutes(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
const appOrigin = "https://app.example.com"
|
|
|
|
s := newTestServer(t)
|
|
s.config.AccessControlAllowOrigin = appOrigin
|
|
s.SetupRoutes()
|
|
|
|
requests := []struct {
|
|
method string
|
|
path string
|
|
want string
|
|
}{
|
|
{http.MethodGet, unsignedImagePath, appOrigin},
|
|
{http.MethodHead, unsignedImagePath, appOrigin},
|
|
{http.MethodOptions, unsignedImagePath, appOrigin},
|
|
{http.MethodGet, encryptedImagePath, appOrigin},
|
|
{http.MethodGet, "/", ""},
|
|
{http.MethodOptions, "/", ""},
|
|
{http.MethodPost, "/generate", ""},
|
|
{http.MethodGet, "/logout", ""},
|
|
}
|
|
|
|
for _, tc := range requests {
|
|
t.Run(tc.method+" "+tc.path, func(t *testing.T) {
|
|
t.Parallel()
|
|
|
|
req := httptest.NewRequestWithContext(
|
|
t.Context(), tc.method, tc.path, nil)
|
|
req.Header.Set("Origin", appOrigin)
|
|
|
|
// An OPTIONS request naming the method it asks about is the
|
|
// preflight a browser sends before some cross-origin requests.
|
|
if tc.method == http.MethodOptions {
|
|
req.Header.Set("Access-Control-Request-Method", http.MethodGet)
|
|
}
|
|
|
|
rec := httptest.NewRecorder()
|
|
s.ServeHTTP(rec, req)
|
|
t.Logf("status %d", rec.Code)
|
|
|
|
got := rec.Header().Get("Access-Control-Allow-Origin")
|
|
if got != tc.want {
|
|
t.Errorf("Access-Control-Allow-Origin = %q, want %q",
|
|
got, tc.want)
|
|
}
|
|
})
|
|
}
|
|
}
|