package route import ( "net/http" "net/http/httptest" "strings" "testing" "time" "git.dev.alexdunmow.com/block/pluginsdk/auth" ) func serve(r http.Handler, method, path string, headers map[string]string) int { req := httptest.NewRequest(method, path, strings.NewReader("name=a")) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") for k, v := range headers { req.Header.Set(k, v) } rec := httptest.NewRecorder() r.ServeHTTP(rec, req) return rec.Code } func ok(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) } func TestAccessLevels(t *testing.T) { r := New("demo") r.Handle("GET", "/", Public, ok) r.Handle("GET", "/mine", Visitor, ok) r.Handle("GET", "/requests", Admin, ok) r.Form("/submit", ok) admin := map[string]string{auth.HeaderVerifiedUserID: "7b0d9a8e-1d0b-4c1b-9a35-0d6f7f3c2a11", auth.HeaderVerifiedRole: "admin"} viewer := map[string]string{auth.HeaderVerifiedUserID: "7b0d9a8e-1d0b-4c1b-9a35-0d6f7f3c2a11", auth.HeaderVerifiedRole: "viewer"} visitor := map[string]string{auth.HeaderVerifiedPublicUserID: "7b0d9a8e-1d0b-4c1b-9a35-0d6f7f3c2a11"} captcha := map[string]string{auth.HeaderVerifiedCaptcha: "1"} cases := []struct { method, path string headers map[string]string want int }{ {"GET", "/api/plugins/demo/", nil, 200}, {"GET", "/api/plugins/demo/other", nil, 404}, {"GET", "/api/plugins/demo/mine", nil, 401}, {"GET", "/api/plugins/demo/mine", visitor, 200}, {"GET", "/api/plugins/demo/requests", nil, 401}, {"GET", "/api/plugins/demo/requests", visitor, 401}, {"GET", "/api/plugins/demo/requests", viewer, 403}, {"GET", "/api/plugins/demo/requests", admin, 200}, {"POST", "/api/plugins/demo/submit", nil, 403}, {"POST", "/api/plugins/demo/submit", captcha, 200}, {"GET", "/api/plugins/demo/submit", captcha, 405}, } for _, c := range cases { if got := serve(r, c.method, c.path, c.headers); got != c.want { t.Errorf("%s %s %v = %d, want %d", c.method, c.path, c.headers, got, c.want) } } if got := len(r.Routes()); got != 4 { t.Errorf("Routes() has %d entries, want 4", got) } } func TestPublicWritesMustUseForm(t *testing.T) { defer func() { if recover() == nil { t.Fatal("a public POST registered with Handle did not panic") } }() New("demo").Handle("POST", "/submit", Public, ok) } func TestMissingAccessPanics(t *testing.T) { defer func() { if recover() == nil { t.Fatal("a route with no access level did not panic") } }() New("demo").Handle("GET", "/x", 0, ok) } func TestFormLimit(t *testing.T) { now := time.Unix(0, 0) l := newLimiter(FormBurst, FormsPerMinute, func() time.Time { return now }) for i := range FormBurst { if !l.allow() { t.Fatalf("submission %d refused inside the burst", i) } } if l.allow() { t.Fatal("submission past the burst was allowed") } now = now.Add(2 * time.Second) if !l.allow() { t.Fatal("a submission two seconds later was refused") } }