gitcat
1package server
2
3import (
4 "net/http"
5 "net/http/httptest"
6 "os"
7 "path/filepath"
8 "strconv"
9 "strings"
10 "testing"
11)
12
13// TestReleaseDownloadRejectsForgedName 回归:下载接口此前不校验 URL 中的
14// name 段,/files/3/ 后面接任意路径都能命中同一附件并回传完整内容。爬虫把
15// 整条 URL 误拼进路径(…/files/3/https:/mode/sql/index.html)即可反复拉取
16// 大附件刷爆带宽。修复后 name 必须与登记文件名严格一致,畸形路径一律 404。
17func TestReleaseDownloadRejectsForgedName(t *testing.T) {
18 srv, st, _, _ := newTestServer(t)
19 makeRepo(t, srv, st, "demo", nil)
20 repo, err := st.RepoByName("demo")
21 if err != nil {
22 t.Fatalf("读仓库失败: %v", err)
23 }
24
25 rel, err := st.CreateRelease(repo.ID, nil, "alice", "Alice", "v1.0", "v1.0", "")
26 if err != nil {
27 t.Fatalf("建发行版失败: %v", err)
28 }
29 const body = "0123456789"
30 asset, err := st.CreateAsset(rel.ID, "bundle-1.0.zip", int64(len(body)), "deadbeef")
31 if err != nil {
32 t.Fatalf("登记附件失败: %v", err)
33 }
34 adDir := filepath.Join(srv.cfg.DataDir, "releases",
35 strconv.FormatInt(repo.ID, 10), strconv.FormatInt(rel.ID, 10))
36 if err := os.MkdirAll(adDir, 0o755); err != nil {
37 t.Fatalf("建附件目录失败: %v", err)
38 }
39 if err := os.WriteFile(filepath.Join(adDir, strconv.FormatInt(asset.ID, 10)), []byte(body), 0o644); err != nil {
40 t.Fatalf("写附件失败: %v", err)
41 }
42
43 base := "/demo/releases/" + strconv.FormatInt(rel.ID, 10) +
44 "/files/" + strconv.FormatInt(asset.ID, 10) + "/"
45 cases := []struct {
46 name string
47 url string
48 want int
49 }{
50 {"正确文件名", base + "bundle-1.0.zip", http.StatusOK},
51 {"爬虫畸形路径", base + "https:/mode/sql/index.html", http.StatusNotFound},
52 {"伪造单段名", base + "evil.zip", http.StatusNotFound},
53 {"编码伪造名", base + "bundle-1.0%2Fzip", http.StatusNotFound},
54 }
55 for _, tc := range cases {
56 t.Run(tc.name, func(t *testing.T) {
57 r := httptest.NewRequest(http.MethodGet, tc.url, nil)
58 w := httptest.NewRecorder()
59 srv.Handler().ServeHTTP(w, r)
60 if w.Code != tc.want {
61 t.Fatalf("状态码 = %d,期望 %d", w.Code, tc.want)
62 }
63 if tc.want == http.StatusNotFound && strings.Contains(w.Body.String(), "0123456789") {
64 t.Errorf("404 响应不应携带附件内容")
65 }
66 })
67 }
68
69 // 正确文件名下 Range 续传仍然工作。
70 r := httptest.NewRequest(http.MethodGet, base+"bundle-1.0.zip", nil)
71 r.Header.Set("Range", "bytes=0-4")
72 w := httptest.NewRecorder()
73 srv.Handler().ServeHTTP(w, r)
74 if w.Code != http.StatusPartialContent || w.Body.String() != "01234" {
75 t.Fatalf("Range 请求 = %d %q,期望 206 \"01234\"", w.Code, w.Body.String())
76 }
77}