package server import ( "archive/zip" "bytes" "io" "net/http" "net/http/httptest" "strings" "testing" ) // TestArchiveDownload 确认源码包端点按 ref 输出可解压的 zip,且默认使用 // 仓库默认分支;非法 ref 不得进入 git 命令行。 func TestArchiveDownload(t *testing.T) { srv, st, _, _ := newTestServer(t) dir := makeRepo(t, srv, st, "proj", nil) commitFiles(t, dir, "init", map[string]string{"a.txt": "hello", "b.txt": "world"}) check := func(path string) { t.Helper() r := httptest.NewRequest(http.MethodGet, path, nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, r) if w.Code != http.StatusOK { t.Fatalf("%s 状态码 = %d,期望 200", path, w.Code) } if ct := w.Header().Get("Content-Type"); ct != "application/zip" { t.Errorf("Content-Type = %q,期望 application/zip", ct) } if disp := w.Header().Get("Content-Disposition"); !strings.Contains(disp, "proj-main.zip") { t.Errorf("Content-Disposition = %q,期望包含 proj-main.zip", disp) } zr, err := zip.NewReader(bytes.NewReader(w.Body.Bytes()), int64(w.Body.Len())) if err != nil { t.Fatalf("响应不是合法 zip: %v", err) } files := map[string]string{} for _, f := range zr.File { rc, err := f.Open() if err != nil { t.Fatalf("打开 %s 失败: %v", f.Name, err) } b, _ := io.ReadAll(rc) _ = rc.Close() files[f.Name] = string(b) } for name, want := range map[string]string{"proj-main/a.txt": "hello", "proj-main/b.txt": "world"} { if files[name] != want { t.Errorf("zip 内 %s = %q,期望 %q", name, files[name], want) } } } check("/proj/archive?ref=main") check("/proj/archive") // 缺省 ref 使用默认分支 // 仓库主页应出现下载入口,并指向当前 ref。 r := httptest.NewRequest(http.MethodGet, "/proj", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, r) if !strings.Contains(w.Body.String(), "Download ZIP") || !strings.Contains(w.Body.String(), `/proj/archive?ref=main`) { t.Error("项目主页缺少 Download ZIP 入口") } for _, ref := range []string{"--upload-pack=evil", "-x", "a..b"} { r := httptest.NewRequest(http.MethodGet, "/proj/archive?ref="+ref, nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, r) if w.Code == http.StatusOK { t.Errorf("非法 ref %q 被放行", ref) } } }