package handlers import ( "context" "crypto/hmac" "crypto/sha256" "encoding/hex" "encoding/json" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "strings" "testing" "github.com/gin-gonic/gin" ) // cookieChecker: the admin is whoever sends the cookie "admin=1". type cookieChecker struct{} func (cookieChecker) IsAdmin(_ http.ResponseWriter, r *http.Request) bool { c, err := r.Cookie("admin") return err == nil && c.Value == "1" } // dirRepo applies edits straight to a work tree and reindexes, standing in // for repo.Repo without a remote. type dirRepo struct { dir string srv *Server msg []string } func (d *dirRepo) Mutate(_ context.Context, message string, edit func(string) error) error { if err := edit(d.dir); err != nil { return err } d.msg = append(d.msg, message) return d.srv.Reload(d.dir) } func setup(t *testing.T) (*gin.Engine, *dirRepo, *int) { t.Helper() gin.SetMode(gin.TestMode) dir := t.TempDir() for _, p := range []string{"solved/moocast/main.cpp", "solving/watermelon/main.cpp"} { os.MkdirAll(filepath.Join(dir, filepath.Dir(p)), 0o755) os.WriteFile(filepath.Join(dir, p), []byte("int main() {}\n"), 0o644) } for _, args := range [][]string{{"init", "--quiet"}, {"add", "-A"}, {"-c", "user.name=t", "-c", "user.email=t@t", "commit", "--quiet", "-m", "init"}} { cmd := exec.Command("git", args...) cmd.Dir = dir if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("git %v: %v\n%s", args, err, out) } } pulls := 0 srv := &Server{Checker: cookieChecker{}, WebhookSecret: "s3cret", Pull: func() { pulls++ }} repo := &dirRepo{dir: dir, srv: srv} srv.Repo = repo if err := srv.Reload(dir); err != nil { t.Fatal(err) } r := gin.New() srv.Routes(r.Group("/usaco/api")) return r, repo, &pulls } func do(r *gin.Engine, method, path, body string, admin bool, headers ...string) *httptest.ResponseRecorder { req := httptest.NewRequest(method, path, strings.NewReader(body)) if admin { req.Header.Set("Cookie", "admin=1") } for i := 0; i+1 < len(headers); i += 2 { req.Header.Set(headers[i], headers[i+1]) } rec := httptest.NewRecorder() r.ServeHTTP(rec, req) return rec } func names(t *testing.T, rec *httptest.ResponseRecorder) []string { t.Helper() var body struct { Problems []struct{ Name string } `json:"problems"` } if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { t.Fatal(err) } var out []string for _, p := range body.Problems { out = append(out, p.Name) } return out } func TestVisibility(t *testing.T) { r, _, _ := setup(t) if got := names(t, do(r, "GET", "/usaco/api/problems", "", false)); len(got) != 1 || got[0] != "moocast" { t.Fatalf("public list = %v, want only the solved problem", got) } if got := names(t, do(r, "GET", "/usaco/api/problems", "", true)); len(got) != 2 { t.Fatalf("admin list = %v, want both", got) } if rec := do(r, "GET", "/usaco/api/problems/watermelon", "", false); rec.Code != 404 { t.Fatalf("public GET of an unsolved problem = %d, want 404", rec.Code) } if rec := do(r, "GET", "/usaco/api/problems/watermelon", "", true); rec.Code != 200 { t.Fatalf("admin GET of an unsolved problem = %d, want 200", rec.Code) } if rec := do(r, "GET", "/usaco/api/problems/moocast", "", false); rec.Code != 200 { t.Fatalf("public GET of a solved problem = %d, want 200", rec.Code) } } func TestNameValidation(t *testing.T) { r, _, _ := setup(t) for _, name := range []string{"..", ".git", "Moocast", "%2e%2e", "a%2Fb"} { if rec := do(r, "GET", "/usaco/api/problems/"+name, "", true); rec.Code != 404 { t.Errorf("GET %q = %d, want 404", name, rec.Code) } } } func TestWritesNeedAdmin(t *testing.T) { r, repo, _ := setup(t) if rec := do(r, "POST", "/usaco/api/problems/moocast/status", `{"to":"skipped"}`, false); rec.Code != 401 { t.Fatalf("anonymous status change = %d, want 401", rec.Code) } if rec := do(r, "PUT", "/usaco/api/problems/moocast/meta", `{"notes":"x"}`, false); rec.Code != 401 { t.Fatalf("anonymous meta edit = %d, want 401", rec.Code) } if len(repo.msg) != 0 { t.Fatalf("refused writes still committed %v", repo.msg) } } func TestStatusChange(t *testing.T) { r, repo, _ := setup(t) rec := do(r, "POST", "/usaco/api/problems/watermelon/status", `{"to":"solved"}`, true) if rec.Code != 200 || !strings.Contains(rec.Body.String(), `"status":"solved"`) { t.Fatalf("solve = %d %s", rec.Code, rec.Body) } if _, err := os.Stat(filepath.Join(repo.dir, "solved", "watermelon", "main.cpp")); err != nil { t.Fatal("directory was not moved") } if len(repo.msg) != 1 || repo.msg[0] != "Solve watermelon" { t.Fatalf("commit messages = %v, want the CLI's \"Solve watermelon\"", repo.msg) } if rec := do(r, "POST", "/usaco/api/problems/watermelon/status", `{"to":"elsewhere"}`, true); rec.Code != 400 { t.Fatalf("bad status = %d, want 400", rec.Code) } } func TestMetaEdit(t *testing.T) { r, repo, _ := setup(t) pdir := filepath.Join(repo.dir, "solved", "moocast") rec := do(r, "PUT", "/usaco/api/problems/moocast/meta", `{"url":" https://usaco.org/x ","notes":"# idea\n"}`, true) if rec.Code != 200 { t.Fatalf("meta = %d %s", rec.Code, rec.Body) } if b, _ := os.ReadFile(filepath.Join(pdir, ".url")); string(b) != "https://usaco.org/x\n" { t.Fatalf(".url = %q", b) } if b, _ := os.ReadFile(filepath.Join(pdir, "notes.md")); string(b) != "# idea\n" { t.Fatalf("notes.md = %q", b) } // Clearing a field removes its file; leaving one out leaves it alone. do(r, "PUT", "/usaco/api/problems/moocast/meta", `{"notes":""}`, true) if _, err := os.Stat(filepath.Join(pdir, "notes.md")); err == nil { t.Fatal("clearing notes left notes.md") } if _, err := os.Stat(filepath.Join(pdir, ".url")); err != nil { t.Fatal("an edit without url removed .url") } if rec := do(r, "PUT", "/usaco/api/problems/moocast/meta", `{"url":"javascript:alert(1)"}`, true); rec.Code != 400 { t.Fatalf("javascript: url = %d, want 400", rec.Code) } } func TestWebhookSignature(t *testing.T) { r, _, pulls := setup(t) body := `{"ref":"refs/heads/main"}` mac := hmac.New(sha256.New, []byte("s3cret")) mac.Write([]byte(body)) good := hex.EncodeToString(mac.Sum(nil)) if rec := do(r, "POST", "/usaco/api/hooks/gitea", body, false, "X-Gitea-Signature", "00"+good[2:]); rec.Code != 401 { t.Fatalf("bad signature = %d, want 401", rec.Code) } if rec := do(r, "POST", "/usaco/api/hooks/gitea", body, false); rec.Code != 401 { t.Fatalf("no signature = %d, want 401", rec.Code) } if *pulls != 0 { t.Fatal("an unsigned hook triggered a pull") } if rec := do(r, "POST", "/usaco/api/hooks/gitea", body, false, "X-Gitea-Signature", good); rec.Code != 202 { t.Fatalf("good signature = %d, want 202", rec.Code) } if *pulls != 1 { t.Fatalf("pulls = %d, want 1", *pulls) } }