仰望星辰工作室

gitcat

gitcat/ internal/server/issues_test.go 10.8 KB · 290 行 原始文件
1package server
2
3import (
4 "net/http"
5 "net/http/httptest"
6 "net/url"
7 "strings"
8 "testing"
9
10 "gitcat/internal/store"
11)
12
13// getCaptchaID 走真实接口请求一张验证码图,返回 Cookie 里的 id 与对应明文。
14func getCaptchaID(t *testing.T, srv *Server, repo string) string {
15 t.Helper()
16 r := httptest.NewRequest(http.MethodGet, "/"+repo+"/issues/captcha.png", nil)
17 w := httptest.NewRecorder()
18 srv.Handler().ServeHTTP(w, r)
19 if w.Code != http.StatusOK {
20 t.Fatalf("验证码接口返回 %d", w.Code)
21 }
22 if ct := w.Header().Get("Content-Type"); ct != "image/png" {
23 t.Fatalf("验证码 Content-Type = %q,期望 image/png", ct)
24 }
25 for _, c := range w.Result().Cookies() {
26 if c.Name == CaptchaCookieName {
27 return c.Value
28 }
29 }
30 t.Fatal("验证码响应未设置 Cookie")
31 return ""
32}
33
34// postIssue 模拟表单提交。
35func postIssue(srv *Server, repo string, form url.Values, cookie *http.Cookie, csrf string) *httptest.ResponseRecorder {
36 form.Set("csrf", csrf)
37 r := httptest.NewRequest(http.MethodPost, "/"+repo+"/issues/new", strings.NewReader(form.Encode()))
38 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
39 if cookie != nil {
40 r.AddCookie(cookie)
41 }
42 w := httptest.NewRecorder()
43 srv.Handler().ServeHTTP(w, r)
44 return w
45}
46
47func TestIssuesPageRender(t *testing.T) {
48 srv, st, _, _ := newTestServer(t)
49 dir := makeRepo(t, srv, st, "issuetab", nil)
50 commitFiles(t, dir, "first", map[string]string{"a.go": "package a\n"})
51
52 page := getPage(srv, "/issuetab")
53 if !strings.Contains(page, `href="/issuetab/issues"`) {
54 t.Error("仓库 Tab 缺少议题入口")
55 }
56 if page := getPage(srv, "/issuetab/issues"); !strings.Contains(page, "还没有议题") {
57 t.Error("空列表应渲染空状态")
58 }
59 if page := getPage(srv, "/issuetab/issues"); !strings.Contains(page, "还没有议题") {
60 t.Error("议题列表页应可访问")
61 }
62 if page := getPage(srv, "/issuetab/issues/new"); !strings.Contains(page, "captcha.png") {
63 t.Error("游客表单应包含验证码图片")
64 }
65}
66
67// TestIssueGuestFlow 是本功能的硬性要求:游客必须过 5 位数字验证码才能提交。
68func TestIssueGuestFlow(t *testing.T) {
69 srv, st, _, _ := newTestServer(t)
70 dir := makeRepo(t, srv, st, "visitor", nil)
71 commitFiles(t, dir, "first", map[string]string{"a.go": "package a\n"})
72
73 form := url.Values{"title": {"游客报告的问题"}, "content": {"复现步骤……"}, "nickname": {"路 人 甲"}}
74 id := getCaptchaID(t, srv, "visitor")
75
76 // 1) 没带验证码 Cookie → 拒绝
77 w := postIssue(srv, "visitor", cloneForm(form), nil, "")
78 if w.Code != http.StatusFound {
79 t.Fatalf("无验证码提交应重定向回表单,实际 %d", w.Code)
80 }
81 if f := flashOf(w); !strings.Contains(f, "验证码") {
82 t.Errorf("应提示验证码错误,实际 flash=%q", f)
83 }
84
85 // 2) 错误验证码 → 拒绝(正确码同时被作废,所以重新取一张)
86 id = getCaptchaID(t, srv, "visitor")
87 w = postIssue(srv, "visitor", cloneForm(form), &http.Cookie{Name: CaptchaCookieName, Value: id}, "")
88 if !strings.Contains(flashOf(w), "验证码") {
89 t.Errorf("错误验证码应被拒绝,实际 flash=%q", flashOf(w))
90 }
91
92 // 3) 正确验证码 → 创建成功,作者为游客快照
93 id = getCaptchaID(t, srv, "visitor")
94 code, _ := srv.captchas.Code(id)
95 form.Set("captcha", code)
96 w = postIssue(srv, "visitor", cloneForm(form), &http.Cookie{Name: CaptchaCookieName, Value: id}, "")
97 if w.Code != http.StatusFound || !strings.Contains(w.Header().Get("Location"), "/visitor/issues") {
98 t.Fatalf("正确验证码应创建成功并跳转列表,实际 %d -> %s", w.Code, w.Header().Get("Location"))
99 }
100 issue, err := st.IssueByNumber(mustRepoID(t, st, "visitor"), 1)
101 if err != nil {
102 t.Fatalf("议题未落库: %v", err)
103 }
104 if issue.AuthorUsername != "guest" || issue.UserID != nil {
105 t.Errorf("游客议题作者快照错误: %q user_id=%v", issue.AuthorUsername, issue.UserID)
106 }
107 if issue.AuthorDisplay != "路 人 甲" {
108 t.Errorf("游客昵称 = %q", issue.AuthorDisplay)
109 }
110
111 // 4) 验证码一次性:同一 id 第二次提交(即使码正确)必须失败
112 w = postIssue(srv, "visitor", cloneForm(form), &http.Cookie{Name: CaptchaCookieName, Value: id}, "")
113 if !strings.Contains(flashOf(w), "验证码") {
114 t.Errorf("验证码应一次性,重放应被拒,实际 flash=%q", flashOf(w))
115 }
116
117 // 5) 列表与详情页可见
118 page := getPage(srv, "/visitor/issues")
119 if !strings.Contains(page, "游客报告的问题") || !strings.Contains(page, "路 人 甲") {
120 t.Error("列表页应显示游客议题")
121 }
122 if page := getPage(srv, "/visitor/issues/1"); !strings.Contains(page, "复现步骤") || !strings.Contains(page, "#1") {
123 t.Error("详情页应显示议题内容与编号")
124 }
125 // 详情页 Markdown 被转义为安全 HTML
126 if page := getPage(srv, "/visitor/issues/1"); strings.Contains(page, "<script>alert") {
127 t.Error("议题内容中的 HTML 不应原样输出")
128 }
129}
130
131// TestIssueLoggedInFlow 登录成员免验证码、走 CSRF。
132func TestIssueLoggedInFlow(t *testing.T) {
133 srv, st, alice, _ := newTestServer(t)
134 dir := makeRepo(t, srv, st, "member", alice)
135 commitFiles(t, dir, "first", map[string]string{"a.go": "package a\n"})
136
137 const sid, csrf = "issue-session", "issue-csrf"
138 if err := st.CreateSession(sid, alice.ID, csrf, 3600e9, "127.0.0.1", "test"); err != nil {
139 t.Fatalf("建会话失败: %v", err)
140 }
141 cookie := &http.Cookie{Name: SessionCookieName, Value: sid}
142
143 // 缺 CSRF → 400(fail 走页面渲染)
144 form := url.Values{"title": {"成员的问题"}}
145 if w := postIssue(srv, "member", cloneForm(form), cookie, ""); w.Code != http.StatusBadRequest {
146 t.Fatalf("缺 CSRF 应 400,实际 %d", w.Code)
147 }
148
149 // 正确 CSRF → 成功
150 w := postIssue(srv, "member", cloneForm(form), cookie, csrf)
151 if w.Code != http.StatusFound {
152 t.Fatalf("带 CSRF 提交应成功,实际 %d:%s", w.Code, w.Body.String())
153 }
154 issue, err := st.IssueByNumber(mustRepoID(t, st, "member"), 1)
155 if err != nil {
156 t.Fatalf("议题未落库: %v", err)
157 }
158 if issue.AuthorUsername != "alice" || issue.UserID == nil {
159 t.Errorf("成员议题作者应为 alice: %q", issue.AuthorUsername)
160 }
161 // 无验证码字段也要求不校验验证码 Cookie —— 登录用户完全不需要验证码
162}
163
164// TestIssueManagePermissions 关闭 / 重开 / 删除仅限仓库创建者与管理员。
165func TestIssueManagePermissions(t *testing.T) {
166 srv, st, alice, bob := newTestServer(t)
167 dir := makeRepo(t, srv, st, "manage", alice)
168 commitFiles(t, dir, "first", map[string]string{"a.go": "package a\n"})
169 if _, err := st.CreateIssue(mustRepoID(t, st, "manage"), nil, "guest", "访客", "待处理", ""); err != nil {
170 t.Fatalf("造议题失败: %v", err)
171 }
172
173 bobSid, bobCsrf := "bob-session", "bob-csrf"
174 if err := st.CreateSession(bobSid, bob.ID, bobCsrf, 3600e9, "127.0.0.1", "test"); err != nil {
175 t.Fatalf("建会话失败: %v", err)
176 }
177
178 postStatus := func(user *store.User, csrf string) *httptest.ResponseRecorder {
179 r := httptest.NewRequest(http.MethodPost, "/manage/issues/1/status", strings.NewReader(url.Values{"csrf": {csrf}}.Encode()))
180 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
181 if user != nil {
182 sid := user.Username + "-sess"
183 if err := st.CreateSession(sid, user.ID, csrf, 3600e9, "127.0.0.1", "test"); err != nil {
184 t.Fatalf("建会话失败: %v", err)
185 }
186 r.AddCookie(&http.Cookie{Name: SessionCookieName, Value: sid})
187 }
188 w := httptest.NewRecorder()
189 srv.Handler().ServeHTTP(w, r)
190 return w
191 }
192
193 // 游客 → 403
194 if w := postStatus(nil, ""); w.Code != http.StatusForbidden {
195 t.Errorf("游客关闭议题应 403,实际 %d", w.Code)
196 }
197 // 无关成员 → 403
198 if w := postStatus(bob, bobCsrf); w.Code != http.StatusForbidden {
199 t.Errorf("无关成员关闭议题应 403,实际 %d", w.Code)
200 }
201 // 管理员 → 成功关闭
202 if w := postStatus(alice, "alice-sess-csrf"); w.Code != http.StatusFound {
203 t.Fatalf("管理员关闭议题应成功,实际 %d", w.Code)
204 }
205 issue, _ := st.IssueByNumber(mustRepoID(t, st, "manage"), 1)
206 if issue.Status != store.IssueClosed {
207 t.Errorf("议题状态 = %q,期望 closed", issue.Status)
208 }
209
210 // 删除同理:无关成员 403,管理员成功
211 del := func(user *store.User, csrf string) *httptest.ResponseRecorder {
212 r := httptest.NewRequest(http.MethodPost, "/manage/issues/1/delete", strings.NewReader(url.Values{"csrf": {csrf}}.Encode()))
213 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
214 if user != nil {
215 sid := user.Username + "-sess"
216 _ = st.CreateSession(sid, user.ID, csrf, 3600e9, "127.0.0.1", "test")
217 r.AddCookie(&http.Cookie{Name: SessionCookieName, Value: sid})
218 }
219 w := httptest.NewRecorder()
220 srv.Handler().ServeHTTP(w, r)
221 return w
222 }
223 if w := del(bob, bobCsrf); w.Code != http.StatusForbidden {
224 t.Errorf("无关成员删除议题应 403,实际 %d", w.Code)
225 }
226 if w := del(alice, "alice-sess-csrf"); w.Code != http.StatusFound {
227 t.Errorf("管理员删除议题应成功,实际 %d", w.Code)
228 }
229 if _, err := st.IssueByNumber(mustRepoID(t, st, "manage"), 1); err == nil {
230 t.Error("议题删除后不应能再查到")
231 }
232}
233
234// TestIssueValidation 标题 / 内容长度校验。
235func TestIssueValidation(t *testing.T) {
236 srv, st, alice, _ := newTestServer(t)
237 dir := makeRepo(t, srv, st, "valid", alice)
238 commitFiles(t, dir, "first", map[string]string{"a.go": "package a\n"})
239 const csrf = "valid-csrf"
240 _ = st.CreateSession("valid-sess", alice.ID, csrf, 3600e9, "127.0.0.1", "test")
241 cookie := &http.Cookie{Name: SessionCookieName, Value: "valid-sess"}
242
243 long := strings.Repeat("标", maxIssueTitleRunes+1)
244 if w := postIssue(srv, "valid", url.Values{"title": {long}}, cookie, csrf); w.Code != http.StatusBadRequest {
245 t.Errorf("超长标题应 400,实际 %d", w.Code)
246 }
247 empty := url.Values{"title": {" "}}
248 if w := postIssue(srv, "valid", empty, cookie, csrf); w.Code != http.StatusBadRequest {
249 t.Errorf("空标题应 400,实际 %d", w.Code)
250 }
251 longBody := strings.Repeat("内容", maxIssueContentRunes/2+10)
252 if w := postIssue(srv, "valid", url.Values{"title": {"ok"}, "content": {longBody}}, cookie, csrf); w.Code != http.StatusBadRequest {
253 t.Errorf("超长内容应 400,实际 %d", w.Code)
254 }
255}
256
257// ---------------------------------------------------------------- 小工具
258
259func cloneForm(src url.Values) url.Values {
260 dst := url.Values{}
261 for k, vs := range src {
262 dst[k] = append([]string(nil), vs...)
263 }
264 return dst
265}
266
267func mustRepoID(t *testing.T, st interface {
268 RepoByName(string) (*store.Repo, error)
269}, name string) int64 {
270 t.Helper()
271 r, err := st.RepoByName(name)
272 if err != nil {
273 t.Fatalf("读取仓库 %s 失败: %v", name, err)
274 }
275 return r.ID
276}
277
278// flashOf 从重定向响应里取出 flash Cookie 的值(urlencoded)。
279func flashOf(w *httptest.ResponseRecorder) string {
280 for _, c := range w.Result().Cookies() {
281 if c.Name == "gitcat_flash" {
282 v, err := url.QueryUnescape(c.Value)
283 if err != nil {
284 return c.Value
285 }
286 return v
287 }
288 }
289 return ""
290}