showcase
- v0.2.4
- 37 commits
- 1 branch
- 6 tags
- updated
- CI 2/2
proxy_test.go
12.6 KB · 308 lines
1package server23import (4 "io"5 "log/slog"6 "net/http"7 "net/http/cgi"8 "net/http/httptest"9 "os"10 "os/exec"11 "path/filepath"12 "slices"13 "strings"14 "testing"15)1617// upstream is a fake Gitea that records what reaches it.18type upstream struct {19 got []*http.Request20 resp func(w http.ResponseWriter, r *http.Request)21}2223func proxyServer(t *testing.T, u *upstream, ready bool) *Server {24 t.Helper()25 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {26 u.got = append(u.got, r.Clone(r.Context()))27 if u.resp != nil {28 u.resp(w, r)29 return30 }31 w.Header().Set("Set-Cookie", "i_like_gitea=1")32 w.Header().Set("X-Gitea-Debug", "yes")33 w.Header().Set("Www-Authenticate", `Bearer realm="http://gitea.tailnet.example:3000/v2/token",service="container_registry",scope="*"`)34 io.WriteString(w, "upstream "+r.URL.RequestURI())35 }))36 t.Cleanup(srv.Close)37 s := testServer(t, ready)38 cfg := *s.Cfg39 cfg.GiteaURL = srv.URL40 return New(&cfg, s.Root, s.Ready, slog.New(slog.NewTextHandler(io.Discard, nil)))41}4243func TestProxyRoutes(t *testing.T) {44 u := &upstream{}45 s := proxyServer(t, u, true)46 pack := map[string]string{"Content-Type": "application/x-git-upload-pack-request"}47 cases := []struct {48 method, path string49 hdr map[string]string50 status int51 upstream string // expected upstream RequestURI, "" if it must not be reached52 }{53 {"GET", "/repo-a.git/info/refs?service=git-upload-pack", nil, 200, "/daniel/repo-a.git/info/refs?service=git-upload-pack"},54 {"POST", "/repo-a.git/git-upload-pack", pack, 200, "/daniel/repo-a.git/git-upload-pack"},55 {"GET", "/v2/", nil, 200, "/v2/"},56 {"HEAD", "/v2/", nil, 200, "/v2/"},57 {"GET", "/v2/token?scope=repository:daniel/repo-a:pull&service=container_registry", nil, 200, "/v2/token?scope=repository:daniel/repo-a:pull&service=container_registry"},58 {"GET", "/v2/daniel/repo-a/manifests/latest", nil, 200, "/v2/daniel/repo-a/manifests/latest"},59 {"HEAD", "/v2/daniel/tools/cli/blobs/sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", nil, 200, "/v2/daniel/tools/cli/blobs/sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},60 {"GET", "/v2/daniel/repo-a/manifests/sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", nil, 200, "/v2/daniel/repo-a/manifests/sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},61 {"GET", "/repo-a/releases/download/v1.0/app.tar.gz", nil, 200, "/daniel/repo-a/releases/download/v1.0/app.tar.gz"},6263 // push and anything else on these prefixes never reaches Gitea64 {"GET", "/repo-a.git/info/refs?service=git-receive-pack", nil, 403, ""},65 {"POST", "/repo-a.git/git-receive-pack", nil, 403, ""},66 {"GET", "/repo-a.git/info/refs", nil, 404, ""},67 {"GET", "/repo-a.git/info/refs?service=git-upload-pack&x=1", nil, 404, ""},68 {"GET", "/repo-a.git/HEAD", nil, 404, ""},69 {"POST", "/repo-a.git/git-upload-pack", nil, 404, ""},70 {"GET", "/secret.git/info/refs?service=git-upload-pack", nil, 404, ""},71 {"GET", "/repo-a.git/../secret.git/info/refs?service=git-upload-pack", nil, 404, ""},72 {"PUT", "/v2/daniel/repo-a/manifests/latest", nil, 404, ""},73 {"POST", "/v2/daniel/repo-a/blobs/uploads/", nil, 404, ""},74 {"PATCH", "/v2/daniel/repo-a/blobs/uploads/x", nil, 404, ""},75 {"DELETE", "/v2/daniel/repo-a/manifests/latest", nil, 404, ""},76 {"GET", "/v2/token?scope=repository:daniel/repo-a:pull,push", nil, 404, ""},77 {"GET", "/v2/token?scope=repository:daniel/secret:pull", nil, 404, ""},78 {"GET", "/v2/daniel/secret/manifests/latest", nil, 404, ""},79 {"GET", "/v2/other/repo-a/manifests/latest", nil, 404, ""},80 {"GET", "/v2/_catalog", nil, 404, ""},81 {"GET", "/v2/daniel/repo-a/blobs/uploads", nil, 404, ""},82 {"GET", "/v2/daniel/repo-a/blobs/sha256:abc", nil, 404, ""},83 {"GET", "/v2/daniel/repo-a/manifests/-bad", nil, 404, ""},84 {"GET", "/v2/daniel/repo-a/tags/list", nil, 404, ""},85 {"GET", "/secret/releases/download/v1/x", nil, 404, ""},86 {"GET", "/repo-a/releases/download/v1/a/b", nil, 404, ""},87 {"GET", "/api/v1/repos/daniel/repo-a", nil, 404, ""},88 {"GET", "/daniel/repo-a.git/info/refs?service=git-upload-pack", nil, 404, ""},89 }90 for _, c := range cases {91 u.got = nil92 req := httptest.NewRequest(c.method, c.path, nil)93 req.Header.Set("Cookie", "session=abc")94 req.Header.Set("Authorization", "Basic ZGFuaWVsOnNlY3JldA==")95 for k, v := range c.hdr {96 req.Header.Set(k, v)97 }98 w := httptest.NewRecorder()99 s.ServeHTTP(w, req)100 if w.Code != c.status {101 t.Errorf("%s %s: status %d, want %d", c.method, c.path, w.Code, c.status)102 }103 switch {104 case c.upstream == "" && len(u.got) > 0:105 t.Errorf("%s %s: reached upstream as %s", c.method, c.path, u.got[0].URL.RequestURI())106 case c.upstream != "" && len(u.got) != 1:107 t.Errorf("%s %s: did not reach upstream", c.method, c.path)108 case c.upstream != "":109 g := u.got[0]110 if g.URL.RequestURI() != c.upstream {111 t.Errorf("%s %s: upstream got %s, want %s", c.method, c.path, g.URL.RequestURI(), c.upstream)112 }113 if g.Header.Get("Cookie") != "" || g.Header.Get("X-Forwarded-For") != "" {114 t.Errorf("%s %s: forwarded cookie or proxy headers", c.method, c.path)115 }116 if g.Header.Get("Authorization") != "" { // the test sends Basic credentials117 t.Errorf("%s %s: forwarded credentials", c.method, c.path)118 }119 h := w.Header()120 if h.Get("Set-Cookie") != "" || h.Get("X-Gitea-Debug") != "" {121 t.Errorf("%s %s: leaked upstream headers", c.method, c.path)122 }123 if a := h.Get("Www-Authenticate"); strings.Contains(a, "tailnet") || !strings.Contains(a, `realm="https://code.danieldaum.net/v2/token"`) {124 t.Errorf("%s %s: realm not rewritten: %s", c.method, c.path, a)125 }126 }127 }128}129130func TestProxyBeforeFirstBuild(t *testing.T) {131 u := &upstream{}132 s := proxyServer(t, u, false)133 w := httptest.NewRecorder()134 s.ServeHTTP(w, httptest.NewRequest("GET", "/repo-a.git/info/refs?service=git-upload-pack", nil))135 if w.Code != 200 || len(u.got) != 1 {136 t.Errorf("clone route before first build: %d", w.Code)137 }138 w = httptest.NewRecorder()139 req := httptest.NewRequest("GET", "/v2/daniel/repo-a/manifests/latest", nil)140 req.Header.Set("Authorization", "Bearer anon-token")141 s.ServeHTTP(w, req)142 if len(u.got) != 2 || u.got[1].Header.Get("Authorization") != "Bearer anon-token" {143 t.Error("registry bearer token was not forwarded")144 }145}146147func TestProxyResponses(t *testing.T) {148 u := &upstream{}149 s := proxyServer(t, u, true)150151 u.resp = func(w http.ResponseWriter, r *http.Request) {152 w.Header().Set("Content-Type", "text/html")153 io.WriteString(w, "<script>alert(1)</script>")154 }155 w := httptest.NewRecorder()156 s.ServeHTTP(w, httptest.NewRequest("GET", "/repo-a/releases/download/v1/x.html", nil))157 if w.Header().Get("Content-Type") != "application/octet-stream" || w.Header().Get("Content-Disposition") != "attachment" {158 t.Errorf("release asset served as %q", w.Header().Get("Content-Type"))159 }160161 u.resp = func(w http.ResponseWriter, r *http.Request) {162 http.Redirect(w, r, "http://minio.tailnet.example/bucket/blob", http.StatusTemporaryRedirect)163 }164 w = httptest.NewRecorder()165 s.ServeHTTP(w, httptest.NewRequest("GET", "/v2/daniel/repo-a/blobs/sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", nil))166 if w.Code != http.StatusBadGateway || strings.Contains(w.Header().Get("Location"), "tailnet") {167 t.Errorf("upstream redirect passed through: %d %s", w.Code, w.Header().Get("Location"))168 }169170 u.resp = func(w http.ResponseWriter, r *http.Request) {171 w.Header().Set("Www-Authenticate", `Basic realm="Gitea"`)172 w.WriteHeader(http.StatusUnauthorized)173 }174 w = httptest.NewRecorder()175 s.ServeHTTP(w, httptest.NewRequest("GET", "/repo-a.git/info/refs?service=git-upload-pack", nil))176 if w.Header().Get("Www-Authenticate") != "" {177 t.Error("Basic challenge passed through; git would prompt for credentials")178 }179180 u.resp = func(w http.ResponseWriter, r *http.Request) { io.Copy(io.Discard, r.Body) }181 big := strings.NewReader(strings.Repeat("x", maxUploadPack+1))182 req := httptest.NewRequest("POST", "/repo-a.git/git-upload-pack", big)183 req.Header.Set("Content-Type", "application/x-git-upload-pack-request")184 w = httptest.NewRecorder()185 s.ServeHTTP(w, req)186 if w.Code == http.StatusOK {187 t.Error("oversized upload-pack body was accepted")188 }189}190191// TestCloneAndPush runs real git through the proxy: clone works, push fails.192func TestCloneAndPush(t *testing.T) {193 git := func(dir string, args ...string) error {194 cmd := exec.Command("git", args...)195 cmd.Dir = dir196 cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1", "GIT_TERMINAL_PROMPT=0",197 "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@t", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@t")198 out, err := cmd.CombinedOutput()199 if err != nil {200 t.Logf("git %v: %s", args, out)201 }202 return err203 }204 root := t.TempDir()205 work := filepath.Join(root, "work")206 os.MkdirAll(work, 0o755)207 os.WriteFile(filepath.Join(work, "f"), []byte("hi\n"), 0o644)208 if git(work, "init", "-q", "-b", "main") != nil || git(work, "add", "f") != nil ||209 git(work, "commit", "-q", "--no-gpg-sign", "-m", "c") != nil ||210 git(root, "clone", "-q", "--bare", work, "daniel/repo-a.git") != nil ||211 git(filepath.Join(root, "daniel/repo-a.git"), "config", "http.receivepack", "true") != nil {212 t.Fatal("fixture setup failed")213 }214 gitPath, _ := exec.LookPath("git")215 backend := &cgi.Handler{Path: gitPath, Args: []string{"http-backend"},216 Env: []string{"GIT_PROJECT_ROOT=" + root, "GIT_HTTP_EXPORT_ALL=1"}}217 up := httptest.NewServer(backend)218 defer up.Close()219220 s := testServer(t, true)221 cfg := *s.Cfg222 cfg.GiteaURL = up.URL223 site := httptest.NewServer(New(&cfg, s.Root, s.Ready, s.Log))224 defer site.Close()225226 clone := filepath.Join(root, "clone")227 if err := git(root, "clone", "-q", site.URL+"/repo-a.git", clone); err != nil {228 t.Fatal("clone through the proxy failed")229 }230 if b, _ := os.ReadFile(filepath.Join(clone, "f")); string(b) != "hi\n" {231 t.Fatal("clone has wrong content")232 }233 os.WriteFile(filepath.Join(clone, "f"), []byte("changed\n"), 0o644)234 git(clone, "commit", "-qam", "push attempt", "--no-gpg-sign")235 if err := git(clone, "push", "-q", "origin", "main"); err == nil {236 t.Fatal("push through the proxy succeeded")237 }238 if err := git(root, "clone", "-q", site.URL+"/secret.git", filepath.Join(root, "nope")); err == nil {239 t.Fatal("cloned a repo that is not allowlisted")240 }241}242243// Clones, pulls and downloads stay at the root under a base_path.244func TestProxyRoutesIgnoreBasePath(t *testing.T) {245 u := &upstream{}246 s := proxyServer(t, u, true)247 s.Cfg.BasePath = "/projects"248 for path, want := range map[string]string{249 "/repo-a.git/info/refs?service=git-upload-pack": "/daniel/repo-a.git/info/refs?service=git-upload-pack",250 "/v2/": "/v2/",251 "/repo-a/releases/download/v1.0/app.tar.gz": "/daniel/repo-a/releases/download/v1.0/app.tar.gz",252 } {253 u.got = nil254 w := do(s, "GET", path, nil)255 if w.Code != 200 || len(u.got) != 1 || u.got[0].RequestURI != want {256 t.Errorf("GET %s: %d, upstream %v, want %q", path, w.Code, u.got, want)257 }258 }259}260261// TestProxyDropsHeaders: only forwardHeaders reach Gitea, so headers Gitea262// might trust (reverse-proxy auth, its own X-Gitea-*) can't be injected.263func TestProxyDropsHeaders(t *testing.T) {264 u := &upstream{}265 s := proxyServer(t, u, true)266 req := httptest.NewRequest("GET", "/repo-a.git/info/refs?service=git-upload-pack", nil)267 for k, v := range map[string]string{268 "X-WEBAUTH-USER": "daniel", "X-Forwarded-User": "daniel", "X-Gitea-OTP": "1", "Cookie": "i_like_gitea=1",269 "Authorization": "Basic ZGFuaWVsOnB3", "Proxy-Authorization": "Basic eA==", "Git-Protocol": "version=2",270 } {271 req.Header.Set(k, v)272 }273 s.ServeHTTP(httptest.NewRecorder(), req)274 if len(u.got) != 1 {275 t.Fatalf("upstream got %d requests", len(u.got))276 }277 for k := range u.got[0].Header {278 if !slices.Contains(forwardHeaders, k) {279 t.Errorf("header %s reached Gitea", k)280 }281 }282 if u.got[0].Header.Get("Authorization") != "" {283 t.Error("credentials reached Gitea on a git route")284 }285 if u.got[0].Header.Get("Git-Protocol") != "version=2" {286 t.Error("Git-Protocol was dropped; protocol v2 clones need it")287 }288}289290// TestProxyGitSlots: past maxGitProxied concurrent git requests, more get291// a 503 instead of piling onto Gitea.292func TestProxyGitSlots(t *testing.T) {293 s := proxyServer(t, &upstream{}, true)294 for range maxGitProxied {295 s.gitSlots <- struct{}{}296 }297 w := httptest.NewRecorder()298 s.ServeHTTP(w, httptest.NewRequest("GET", "/repo-a.git/info/refs?service=git-upload-pack", nil))299 if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") == "" {300 t.Errorf("full slots: got %d", w.Code)301 }302 <-s.gitSlots303 w = httptest.NewRecorder()304 s.ServeHTTP(w, httptest.NewRequest("GET", "/repo-a.git/info/refs?service=git-upload-pack", nil))305 if w.Code != http.StatusOK {306 t.Errorf("free slot: got %d", w.Code)307 }308}