package main import ( "compress/gzip" "io" "net/http" "net/http/httptest" "strings" "testing" "testing/fstest" ) func TestWithCORSAllowsOnlyListedOrigins(t *testing.T) { const listed = "https://dashboard.example.com" next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) cases := []struct { name string allowed []string origin string want string }{ {name: "listed origin is echoed", allowed: []string{listed}, origin: listed, want: listed}, {name: "unlisted origin gets no header", allowed: []string{listed}, origin: "https://evil.example", want: ""}, {name: "no allow list means no CORS", allowed: nil, origin: listed, want: ""}, {name: "no origin header means no CORS", allowed: []string{listed}, origin: "", want: ""}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { recorder := httptest.NewRecorder() request := httptest.NewRequest(http.MethodGet, "/api/lists", nil) if tc.origin != "" { request.Header.Set("Origin", tc.origin) } withCORS(tc.allowed, next).ServeHTTP(recorder, request) if got := recorder.Header().Get("Access-Control-Allow-Origin"); got != tc.want { t.Fatalf("Access-Control-Allow-Origin = %q, want %q", got, tc.want) } wantCredentials := "" if tc.want != "" { wantCredentials = "true" } if got := recorder.Header().Get("Access-Control-Allow-Credentials"); got != wantCredentials { t.Fatalf("Access-Control-Allow-Credentials = %q, want %q", got, wantCredentials) } }) } } func TestWithCORSPreflightAllowsPatchForListedOrigin(t *testing.T) { const listed = "https://dashboard.example.com" handler := withCORS([]string{listed}, http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) recorder := httptest.NewRecorder() request := httptest.NewRequest(http.MethodOptions, "/api/auth/users/1", nil) request.Header.Set("Origin", listed) handler.ServeHTTP(recorder, request) if recorder.Code != http.StatusNoContent { t.Fatalf("preflight status = %d, want %d", recorder.Code, http.StatusNoContent) } if methods := recorder.Header().Get("Access-Control-Allow-Methods"); !strings.Contains(methods, "PATCH") { t.Fatalf("Access-Control-Allow-Methods = %q, want PATCH included", methods) } } func TestWithSecurityHeadersSetsFramingAndSniffingDefaults(t *testing.T) { handler := withSecurityHeaders(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })) recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) want := map[string]string{ "X-Content-Type-Options": "nosniff", "X-Frame-Options": "DENY", "Content-Security-Policy": "frame-ancestors 'none'", "Referrer-Policy": "strict-origin-when-cross-origin", } for name, value := range want { if got := recorder.Header().Get(name); got != value { t.Fatalf("%s = %q, want %q", name, got, value) } } } func TestWithGzipCompressesOnlyWhenAccepted(t *testing.T) { handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) })) accepted := httptest.NewRecorder() request := httptest.NewRequest(http.MethodGet, "/web/data", nil) request.Header.Set("Accept-Encoding", "gzip, deflate") handler.ServeHTTP(accepted, request) if got := accepted.Header().Get("Content-Encoding"); got != "gzip" { t.Fatalf("Content-Encoding = %q, want gzip", got) } reader, err := gzip.NewReader(accepted.Body) if err != nil { t.Fatalf("gzip.NewReader() error = %v", err) } body, err := io.ReadAll(reader) if err != nil { t.Fatalf("reading gzip body error = %v", err) } if got := strings.TrimSpace(string(body)); got != `{"ok":true}` { t.Fatalf("decompressed body = %q, want the JSON document", got) } plain := httptest.NewRecorder() handler.ServeHTTP(plain, httptest.NewRequest(http.MethodGet, "/web/data", nil)) if got := plain.Header().Get("Content-Encoding"); got != "" { t.Fatalf("Content-Encoding without Accept-Encoding = %q, want none", got) } if got := strings.TrimSpace(plain.Body.String()); got != `{"ok":true}` { t.Fatalf("plain body = %q, want the JSON document", got) } } func TestWithGzipLeavesNotModifiedWithoutBody(t *testing.T) { handler := withGzip(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("ETag", `W/"abc"`) w.WriteHeader(http.StatusNotModified) })) recorder := httptest.NewRecorder() request := httptest.NewRequest(http.MethodGet, "/web/data", nil) request.Header.Set("Accept-Encoding", "gzip") handler.ServeHTTP(recorder, request) if recorder.Code != http.StatusNotModified { t.Fatalf("status = %d, want %d", recorder.Code, http.StatusNotModified) } if got := recorder.Header().Get("Content-Encoding"); got != "" { t.Fatalf("Content-Encoding on 304 = %q, want none", got) } if recorder.Body.Len() != 0 { t.Fatalf("304 body length = %d, want 0", recorder.Body.Len()) } } func TestSPAFileServerCachesHashedAssetsLong(t *testing.T) { root := fstest.MapFS{ "index.html": {Data: []byte("")}, "favicon.svg": {Data: []byte("")}, "_app/immutable/app.abc.js": {Data: []byte("console.log(1)")}, } handler := spaFileServer(root) cases := []struct { path string want string }{ {path: "/", want: "no-cache"}, {path: "/favicon.svg", want: "no-cache"}, {path: "/_app/immutable/app.abc.js", want: "public, max-age=31536000, immutable"}, {path: "/lists/123", want: "no-cache"}, } for _, tc := range cases { t.Run(tc.path, func(t *testing.T) { recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, tc.path, nil)) if got := recorder.Header().Get("Cache-Control"); got != tc.want { t.Fatalf("Cache-Control = %q, want %q", got, tc.want) } }) } } func TestDecodeJSONLimitRejectsOversizedBodies(t *testing.T) { type payload struct { Name string `json:"name"` } small := httptest.NewRecorder() var ok payload if err := decodeJSONLimit(small, httptest.NewRequest(http.MethodPost, "/api/lists", strings.NewReader(`{"name":"a"}`)), &ok, 64); err != nil { t.Fatalf("decodeJSONLimit() within limit error = %v", err) } large := httptest.NewRecorder() var tooBig payload body := `{"name":"` + strings.Repeat("a", 256) + `"}` err := decodeJSONLimit(large, httptest.NewRequest(http.MethodPost, "/api/lists", strings.NewReader(body)), &tooBig, 64) if err == nil { t.Fatal("decodeJSONLimit() over limit returned no error") } answer := httptest.NewRecorder() writeDecodeError(answer, err, "Invalid JSON body") if answer.Code != http.StatusRequestEntityTooLarge { t.Fatalf("status for oversized body = %d, want %d", answer.Code, http.StatusRequestEntityTooLarge) } malformed := httptest.NewRecorder() err = decodeJSONLimit(malformed, httptest.NewRequest(http.MethodPost, "/api/lists", strings.NewReader(`{`)), &tooBig, 64) writeDecodeError(malformed, err, "Invalid JSON body") if malformed.Code != http.StatusBadRequest { t.Fatalf("status for malformed body = %d, want %d", malformed.Code, http.StatusBadRequest) } }