| 1 | package serve |
| 2 | |
| 3 | import ( |
| 4 | "net/http" |
| 5 | "net/http/httptest" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | |
| 9 | "reasonix/internal/config" |
| 10 | "reasonix/internal/control" |
| 11 | ) |
| 12 | |
| 13 | // TestServeRejectsNonJSONPost guards the CSRF defense: a state-changing POST that |
| 14 | // isn't application/json is refused, so a page the user visits can't drive the |
| 15 | // unauthenticated localhost server with a simple cross-origin POST (text/plain, |
| 16 | // no preflight). The same-origin frontend always sends JSON and is unaffected. |
| 17 | func TestServeRejectsNonJSONPost(t *testing.T) { |
| 18 | got := make(chan string, 1) |
| 19 | bc := NewBroadcaster() |
| 20 | ctrl := control.New(control.Options{Runner: fakeRunner{got: got}, Sink: bc}) |
| 21 | srv := httptest.NewServer(New(ctrl, bc, config.ServeConfig{}).Handler()) |
| 22 | defer srv.Close() |
| 23 | |
| 24 | for _, ct := range []string{"text/plain", "application/x-www-form-urlencoded", ""} { |
| 25 | req, _ := http.NewRequest(http.MethodPost, srv.URL+"/submit", strings.NewReader(`{"input":"pwn"}`)) |
| 26 | if ct != "" { |
| 27 | req.Header.Set("Content-Type", ct) |
| 28 | } |
| 29 | resp, err := http.DefaultClient.Do(req) |
| 30 | if err != nil { |
| 31 | t.Fatal(err) |
| 32 | } |
| 33 | resp.Body.Close() |
| 34 | if resp.StatusCode != http.StatusUnsupportedMediaType { |
| 35 | t.Errorf("Content-Type %q: status = %d, want 415", ct, resp.StatusCode) |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | select { |
| 40 | case in := <-got: |
| 41 | t.Fatalf("a non-JSON POST reached the runner with %q — CSRF guard bypassed", in) |
| 42 | default: |
| 43 | } |
| 44 | } |
| 45 |