gateway_test.go41 lines, 1.4 KB
| 1 | package gateway_test |
| 2 | |
| 3 | import ( |
| 4 | "log/slog" |
| 5 | "net/http" |
| 6 | "net/http/httptest" |
| 7 | "net/url" |
| 8 | "testing" |
| 9 | |
| 10 | "github.com/fiston-user/payments/internal/gateway" |
| 11 | ) |
| 12 | |
| 13 | func TestProxy(t *testing.T) { |
| 14 | t.Parallel() |
| 15 | // A fake auth service, which answers with the headers it got. |
| 16 | auth := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 17 | w.Header().Set("Got-Request-ID", r.Header.Get("X-Request-ID")) |
| 18 | w.Header().Set("Got-Forwarded-For", r.Header.Get("X-Forwarded-For")) |
| 19 | })) |
| 20 | t.Cleanup(auth.Close) |
| 21 | authURL, _ := url.Parse(auth.URL) |
| 22 | gw := gateway.New(gateway.Config{AuthURL: authURL, Redis: testRedis(t), IPLimit: 10, |
| 23 | UserLimit: 10, Logger: slog.New(slog.DiscardHandler)}) |
| 24 | |
| 25 | req := httptest.NewRequest("POST", "/v1/auth/login", nil) |
| 26 | req.RemoteAddr = "203.0.113.7:51234" |
| 27 | req.Header.Set("X-Request-ID", "req-42") |
| 28 | req.Header.Set("X-Forwarded-For", "6.6.6.6") // made up by the client |
| 29 | rr := httptest.NewRecorder() |
| 30 | gw.ServeHTTP(rr, req) |
| 31 | |
| 32 | // Auth gets our request ID and the real address. The client gets one ID back. |
| 33 | got := rr.Header() |
| 34 | if got.Get("Got-Request-ID") != "req-42" || got.Get("Got-Forwarded-For") != "203.0.113.7" { |
| 35 | t.Errorf("auth got request ID %q from %q, want req-42 from 203.0.113.7", |
| 36 | got.Get("Got-Request-ID"), got.Get("Got-Forwarded-For")) |
| 37 | } |
| 38 | if ids := got.Values("X-Request-ID"); len(ids) != 1 { |
| 39 | t.Errorf("X-Request-ID = %v, want exactly one", ids) |
| 40 | } |
| 41 | } |