package main import ( "encoding/json" "net/http" "net/http/httptest" "strings" "testing" ) const testToken = "0123456789abcdef0123456789abcdef" // gitleaks:allow func newTestHandler() http.Handler { return newHandler(testToken) } func perform(handler http.Handler, method, path, token, body string) *httptest.ResponseRecorder { request := httptest.NewRequest(method, path, strings.NewReader(body)) if token != "" { request.Header.Set(authHeader, token) } recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, request) return recorder } func validPlanBody(action string) string { return `{"action":"` + action + `","args":["@alice"],"reply_uid":0,"candidates":[{"uid":101,"username":"alice"}],"actor_allowed":true,"bot_allowed":true,"chat_type":"supergroup","protected_uids":[],"bot_username":"iishkogatewaybot"}` } func errorMessage(t *testing.T, recorder *httptest.ResponseRecorder) string { t.Helper() var payload map[string]string if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil { t.Fatalf("error body is not JSON: %v (%q)", err, recorder.Body.String()) } if len(payload) != 1 { t.Fatalf("error body keys = %d, want 1 (%q)", len(payload), recorder.Body.String()) } message, ok := payload["error"] if !ok || message == "" { t.Fatalf("error body = %q", recorder.Body.String()) } return message } func TestHealthz(t *testing.T) { recorder := perform(newTestHandler(), http.MethodGet, "/healthz", "", "") if recorder.Code != http.StatusOK { t.Fatalf("status = %d, want 200", recorder.Code) } if body := strings.TrimSpace(recorder.Body.String()); body != `{"status":"ok"}` { t.Fatalf("body = %q", body) } if contentType := recorder.Header().Get("Content-Type"); contentType != "application/json; charset=utf-8" { t.Fatalf("content type = %q", contentType) } recorder = perform(newTestHandler(), http.MethodPost, "/healthz", "", "") if recorder.Code != http.StatusMethodNotAllowed { t.Fatalf("POST /healthz status = %d, want 405", recorder.Code) } } func TestPlanAuth(t *testing.T) { handler := newTestHandler() tests := []struct { name string token string }{ {"missing", ""}, {"empty header", ""}, {"wrong", "fedcba9876543210fedcba9876543210"}, {"prefix", testToken[:len(testToken)-1]}, {"longer", testToken + "x"}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { recorder := perform(handler, http.MethodPost, "/v1/plan", test.token, validPlanBody(ActionBan)) if recorder.Code != http.StatusUnauthorized { t.Fatalf("status = %d, want 401 (%q)", recorder.Code, recorder.Body.String()) } message := errorMessage(t, recorder) if strings.Contains(message, testToken) { t.Fatal("error response echoed the token") } }) } request := httptest.NewRequest(http.MethodPost, "/v1/plan", strings.NewReader(validPlanBody(ActionBan))) request.Header.Add(authHeader, testToken) request.Header.Add(authHeader, testToken) recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, request) if recorder.Code != http.StatusUnauthorized { t.Fatalf("duplicate header status = %d, want 401", recorder.Code) } recorder = perform(handler, http.MethodPost, "/v1/plan", testToken+","+testToken, validPlanBody(ActionBan)) if recorder.Code != http.StatusUnauthorized { t.Fatalf("combined header status = %d, want 401", recorder.Code) } recorder = perform(handler, http.MethodPost, "/v1/plan", "", `{"action":`) if recorder.Code != http.StatusUnauthorized { t.Fatalf("auth must run before body parsing, status = %d", recorder.Code) } } func TestPlanSuccess(t *testing.T) { recorder := perform(newTestHandler(), http.MethodPost, "/v1/plan", testToken, validPlanBody(ActionBan)) if recorder.Code != http.StatusOK { t.Fatalf("status = %d, want 200 (%q)", recorder.Code, recorder.Body.String()) } if contentType := recorder.Header().Get("Content-Type"); contentType != "application/json; charset=utf-8" { t.Fatalf("content type = %q", contentType) } if cacheControl := recorder.Header().Get("Cache-Control"); cacheControl != "no-store" { t.Fatalf("cache control = %q", cacheControl) } if options := recorder.Header().Get("X-Content-Type-Options"); options != "nosniff" { t.Fatalf("content type options = %q", options) } var response Response if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil { t.Fatalf("decode response: %v", err) } if response.Action != ActionBan || response.TargetUID != 101 { t.Fatalf("response = %+v", response) } if response.DurationSeconds != 0 || response.Mode != "" || response.Reason != "" { t.Fatalf("unexpected optional fields: %+v", response) } var raw map[string]json.RawMessage if err := json.Unmarshal(recorder.Body.Bytes(), &raw); err != nil { t.Fatalf("decode raw response: %v", err) } for _, key := range []string{"action", "target_uid", "duration_seconds", "mode", "reason"} { if _, ok := raw[key]; !ok { t.Fatalf("response is missing key %q: %s", key, recorder.Body.String()) } } if len(raw) != 5 { t.Fatalf("response has %d keys, want 5: %s", len(raw), recorder.Body.String()) } } func TestPlanRouting(t *testing.T) { handler := newTestHandler() cases := []struct { method string path string token string want int }{ {http.MethodGet, "/v1/plan", testToken, http.StatusMethodNotAllowed}, {http.MethodOptions, "/v1/plan", testToken, http.StatusMethodNotAllowed}, {http.MethodPost, "/v1/plans", testToken, http.StatusNotFound}, {http.MethodGet, "/v1/plan/", testToken, http.StatusNotFound}, {http.MethodGet, "/healthz/", "", http.StatusNotFound}, {http.MethodGet, "/", "", http.StatusNotFound}, } for _, test := range cases { t.Run(test.method+" "+test.path, func(t *testing.T) { recorder := perform(handler, test.method, test.path, test.token, validPlanBody(ActionBan)) if recorder.Code != test.want { t.Fatalf("status = %d, want %d (%q)", recorder.Code, test.want, recorder.Body.String()) } }) } } func TestPlanJSONErrors(t *testing.T) { handler := newTestHandler() tests := []struct { name string body string }{ {"empty", ""}, {"whitespace", " \n"}, {"truncated", `{"action":`}, {"syntax", `{"action":"resolve",}`}, {"top level array", `[]`}, {"top level null", `null`}, {"wrong type", `{"action":"resolve","reply_uid":"101"}`}, {"unknown field", `{"action":"resolve","reply_uid":101,"extra":true}`}, {"unknown nested field", `{"action":"resolve","candidates":[{"uid":1,"username":"a","extra":true}]}`}, {"trailing true", `{"action":"resolve","reply_uid":101} true`}, {"trailing object", `{"action":"resolve","reply_uid":101}{"action":"resolve"}`}, {"trailing junk", `{"action":"resolve","reply_uid":101}x`}, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { recorder := perform(handler, http.MethodPost, "/v1/plan", testToken, test.body) if recorder.Code != http.StatusBadRequest { t.Fatalf("status = %d, want 400 (%q)", recorder.Code, recorder.Body.String()) } errorMessage(t, recorder) }) } } func TestPlanTrailingDataMessage(t *testing.T) { recorder := perform(newTestHandler(), http.MethodPost, "/v1/plan", testToken, `{"action":"resolve","reply_uid":101} true`) if recorder.Code != http.StatusBadRequest { t.Fatalf("status = %d, want 400", recorder.Code) } if message := errorMessage(t, recorder); message != msgTrailingData { t.Fatalf("message = %q, want %q", message, msgTrailingData) } } func TestPlanPolicyErrorStatus(t *testing.T) { body := `{"action":"ban","args":["@alice"],"reply_uid":0,"candidates":[{"uid":101,"username":"alice"}],"actor_allowed":false,"bot_allowed":true,"chat_type":"supergroup","protected_uids":[],"bot_username":"iishkogatewaybot"}` recorder := perform(newTestHandler(), http.MethodPost, "/v1/plan", testToken, body) if recorder.Code != http.StatusForbidden { t.Fatalf("status = %d, want 403 (%q)", recorder.Code, recorder.Body.String()) } if message := errorMessage(t, recorder); message != msgPermissions { t.Fatalf("message = %q, want %q", message, msgPermissions) } } func TestPlanBodyLimit(t *testing.T) { handler := newTestHandler() base := `{"action":"resolve","reply_uid":101}` if len(base) > maxBodyBytes { t.Fatalf("base body %d exceeds limit %d", len(base), maxBodyBytes) } exactBody := base + strings.Repeat(" ", maxBodyBytes-len(base)) if len(exactBody) != maxBodyBytes { t.Fatalf("body length = %d, want %d", len(exactBody), maxBodyBytes) } recorder := perform(handler, http.MethodPost, "/v1/plan", testToken, exactBody) if recorder.Code != http.StatusOK { t.Fatalf("exact limit status = %d, want 200 (%q)", recorder.Code, recorder.Body.String()) } tooLarge := exactBody + " " recorder = perform(handler, http.MethodPost, "/v1/plan", testToken, tooLarge) if recorder.Code != http.StatusRequestEntityTooLarge { t.Fatalf("over limit status = %d, want 413 (%q)", recorder.Code, recorder.Body.String()) } errorMessage(t, recorder) } func TestLoadToken(t *testing.T) { valid := strings.Repeat("a", minTokenLength) t.Setenv(tokenEnvVar, valid) token, err := loadToken() if err != nil || token != valid { t.Fatalf("loadToken() = %q, %v", token, err) } for _, value := range []string{"", strings.Repeat("a", minTokenLength-1)} { t.Setenv(tokenEnvVar, value) if _, err := loadToken(); err == nil { t.Fatalf("loadToken accepted %d characters", len(value)) } } } func TestValidateAddr(t *testing.T) { valid := []string{"127.0.0.1:48003", "127.0.0.2:1", "[::1]:48003"} for _, addr := range valid { if err := validateAddr(addr); err != nil { t.Fatalf("validateAddr(%q) = %v", addr, err) } } invalid := []string{ "", "127.0.0.1", ":48003", "localhost:48003", "0.0.0.0:48003", "[::]:48003", "8.8.8.8:48003", "127.0.0.1:0", "127.0.0.1:65536", "127.0.0.1:abc", "::1:48003", } for _, addr := range invalid { if err := validateAddr(addr); err == nil { t.Fatalf("validateAddr(%q) = nil, want error", addr) } } }