package server import ( "net/http" "net/http/httptest" "testing" "github.com/cdnutter/canon/internal/config" ) func TestSafeNextBlocksOffsite(t *testing.T) { bad := []string{"", "x", "https://evil.example", "//evil.example", "/\\evil.example", "/\t/evil.example", "/\n/evil.example", "/\r/evil.example", "/%09/evil.example\x00", "/a\\b", "\\\\evil.example", "/\x7f/evil.example"} for _, in := range bad { if got := safeNext(in); got != "/admin" { t.Errorf("safeNext(%q) = %q, want /admin", in, got) } if got := safePublicNext(in); got != "/" { t.Errorf("safePublicNext(%q) = %q, want /", in, got) } } for _, in := range []string{"/", "/admin", "/l/movies?x=1", "/admin/lists/3#top"} { if got := safeNext(in); got != in { t.Errorf("safeNext(%q) = %q, want unchanged", in, got) } } // The redirect a browser actually sees must stay on this site. for _, in := range bad { w := httptest.NewRecorder() http.Redirect(w, httptest.NewRequest("GET", "/login", nil), safeNext(in), http.StatusSeeOther) if loc := w.Header().Get("Location"); loc != "/admin" { t.Errorf("next=%q redirected to %q", in, loc) } } } func TestClientIPUsesProxyAddedEntry(t *testing.T) { s := &Server{cfg: config.Config{TrustProxy: true}} r := httptest.NewRequest("GET", "/", nil) r.Header.Set("X-Forwarded-For", "6.6.6.6, 203.0.113.9") if got := s.clientIP(r); got != "203.0.113.9" { t.Errorf("clientIP = %q, want the proxy-added 203.0.113.9", got) } s.cfg.TrustProxy = false if got := s.clientIP(r); got != "192.0.2.1" { t.Errorf("clientIP without proxy trust = %q, want RemoteAddr host", got) } }