|
4 | 4 | "net/http" |
5 | 5 | "net/http/httptest" |
6 | 6 | "net/url" |
| 7 | + "strings" |
7 | 8 | "testing" |
8 | 9 |
|
9 | 10 | "github.com/go-chi/chi/v5" |
@@ -271,3 +272,58 @@ func TestStripPrefix(t *testing.T) { |
271 | 272 | t.Fatalf("got: %q, want: %q", resp, "404 page not found\n") |
272 | 273 | } |
273 | 274 | } |
| 275 | + |
| 276 | +func TestRedirectSlashes_PreventBackslashRelativeOpenRedirect(t *testing.T) { |
| 277 | + h := RedirectSlashes(http.NotFoundHandler()) |
| 278 | + |
| 279 | + tests := []struct { |
| 280 | + name string |
| 281 | + target string |
| 282 | + }{ |
| 283 | + { |
| 284 | + name: `raw backslash: /\evil.com/`, |
| 285 | + target: `/\evil.com/`, |
| 286 | + }, |
| 287 | + { |
| 288 | + name: `encoded backslash: /%5Cevil.com/`, |
| 289 | + target: "/%5Cevil.com/", |
| 290 | + }, |
| 291 | + } |
| 292 | + |
| 293 | + for _, tc := range tests { |
| 294 | + t.Run(tc.name, func(t *testing.T) { |
| 295 | + req := httptest.NewRequest(http.MethodGet, "http://example.test"+tc.target, nil) |
| 296 | + rr := httptest.NewRecorder() |
| 297 | + |
| 298 | + h.ServeHTTP(rr, req) |
| 299 | + res := rr.Result() |
| 300 | + defer res.Body.Close() |
| 301 | + |
| 302 | + if res.StatusCode != http.StatusMovedPermanently { |
| 303 | + t.Fatalf("expected %d, got %d", http.StatusMovedPermanently, res.StatusCode) |
| 304 | + } |
| 305 | + |
| 306 | + loc := res.Header.Get("Location") |
| 307 | + if loc == "" { |
| 308 | + t.Fatalf("expected Location header to be set") |
| 309 | + } |
| 310 | + |
| 311 | + // The core security assertions: |
| 312 | + if strings.Contains(loc, `\`) { |
| 313 | + t.Fatalf("Location must not contain backslashes: %q", loc) |
| 314 | + } |
| 315 | + if strings.HasPrefix(loc, "//") { |
| 316 | + t.Fatalf("Location must not be protocol-relative: %q", loc) |
| 317 | + } |
| 318 | + if !strings.HasPrefix(loc, "/") { |
| 319 | + t.Fatalf("Location must be an absolute-path reference starting with '/': %q", loc) |
| 320 | + } |
| 321 | + |
| 322 | + // Optional stronger assertion if your middleware normalizes to /evil.com exactly: |
| 323 | + // (Keep or remove depending on your chosen behavior.) |
| 324 | + if loc != "/evil.com" { |
| 325 | + t.Fatalf("expected Location %q, got %q", "/evil.com", loc) |
| 326 | + } |
| 327 | + }) |
| 328 | + } |
| 329 | +} |
0 commit comments