package httpsecurity import ( "errors" "net/http" "net/http/httptest" "strings" "testing" ) func TestWriteProblemUsesSafeFallbackForCustomStatus(t *testing.T) { t.Parallel() recorder := httptest.NewRecorder() err := &HTTPError{ StatusCode: 599, Header: http.Header{"X-Security-Policy": []string{"local"}}, Cause: errors.New("secret backend details"), } if !WriteProblem(recorder, "request-123", err) { t.Fatal("WriteProblem() = false, want true") } if recorder.Code != 599 { t.Fatalf("status = %d, want 599", recorder.Code) } if got := recorder.Header().Get("X-Security-Policy"); got != "local" { t.Fatalf("X-Security-Policy = %q, want local", got) } body := recorder.Body.String() for _, want := range []string{`"code":"SECURITY_REJECTED"`, `"title":"Request rejected"`, `"requestId":"request-123"`} { if !strings.Contains(body, want) { t.Fatalf("body = %s, want %s", body, want) } } if strings.Contains(body, "secret backend details") { t.Fatalf("body leaked cause: %s", body) } } func TestWriteProblemIgnoresNonSecurityErrors(t *testing.T) { t.Parallel() recorder := httptest.NewRecorder() if WriteProblem(recorder, "request-123", errors.New("plain error")) { t.Fatal("WriteProblem() = true, want false") } if recorder.Code != http.StatusOK || recorder.Body.Len() != 0 { t.Fatalf("recorder = status %d body %q, want untouched", recorder.Code, recorder.Body.String()) } }