diff --git a/cmd/daumdev/main.go b/cmd/daumdev/main.go index 7e41d9d..42661c8 100644 --- a/cmd/daumdev/main.go +++ b/cmd/daumdev/main.go @@ -35,7 +35,7 @@ func main() { b := build.New(cfg, *data) if !*once { - srv := &server.Server{Cfg: cfg, Root: b.Current, Ready: b.Ready, Log: slog.Default()} + srv := server.New(cfg, b.Current, b.Ready, slog.Default()) if *serveDir != "" { srv.Root, srv.Ready = func() string { return *serveDir }, func() bool { return true } } else { diff --git a/docs/decisions.md b/docs/decisions.md index 2a8c10d..89696a0 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -127,3 +127,26 @@ details are in `docs/theme.md`. This replaces the spec's original the TCP peer. - `-serve-dir DIR` (dev only) serves a finished build without building; `just serve` and `just demo` use it. + +## Git and registry proxy + +- Proxy routes are matched before anything else and work before the first + build. Within the `.git`, `/v2` and `releases/download` prefixes anything not + explicitly allowed is a 404. Any path or query containing + `git-receive-pack` is a 403. +- Requests to Gitea never carry `Cookie` or `X-Forwarded-*`. `Authorization` + passes only when it is a `Bearer` token on a registry manifest or blob + route, which is the anonymous token Gitea just issued. Basic credentials + are never forwarded. +- `/v2/token` is forwarded only when every `scope` is a pull of an + allowlisted image. `_catalog` and `tags/list` are 404. +- Any 3xx from Gitea becomes a 502, so storage or tailnet URLs never reach + clients. With Gitea's local storage, blobs and assets are served directly, + so this doesn't happen in practice. +- Release assets are always `application/octet-stream` with + `Content-Disposition: attachment`. +- The `git-upload-pack` body is capped at 10 MB and must have the git + request content type. +- Gitea must allow anonymous HTTP git and registry reads + (`REQUIRE_SIGNIN_VIEW = false`, HTTP git not disabled), or public clones and + pulls fail. diff --git a/internal/server/proxy.go b/internal/server/proxy.go new file mode 100644 index 0000000..9a87432 --- /dev/null +++ b/internal/server/proxy.go @@ -0,0 +1,152 @@ +package server + +import ( + "context" + "errors" + "net/http" + "net/http/httputil" + "net/url" + "regexp" + "strings" + "time" +) + +const maxUploadPack = 10 << 20 + +var realmRe = regexp.MustCompile(`realm="[^"]*"`) + +// newProxy forwards allowlisted git, registry and release-download requests +// to Gitea. It never forwards cookies or proxy headers, refuses upstream +// redirects, and strips cookies and Gitea headers from responses. +func (s *Server) newProxy() *httputil.ReverseProxy { + up, _ := url.Parse(s.Cfg.GiteaURL) + t := http.DefaultTransport.(*http.Transport).Clone() + t.Proxy, t.ResponseHeaderTimeout = nil, 60*time.Second + return &httputil.ReverseProxy{ + Rewrite: func(pr *httputil.ProxyRequest) { + pr.Out.URL.Path, pr.Out.URL.RawPath = pr.In.Context().Value(upstreamPath{}).(string), "" + pr.SetURL(up) + pr.Out.Host = up.Host + pr.Out.Header.Del("Cookie") + // only the registry's own (anonymous) bearer tokens pass, never credentials + a := pr.In.Header.Get("Authorization") + if !strings.HasPrefix(pr.In.URL.Path, "/v2/") || pr.In.URL.Path == "/v2/token" || !strings.HasPrefix(a, "Bearer ") { + pr.Out.Header.Del("Authorization") + } + }, + FlushInterval: -1, // stream clones and layers + Transport: t, + ModifyResponse: func(resp *http.Response) error { + if resp.StatusCode >= 300 && resp.StatusCode < 400 { + return errors.New("upstream redirect refused") // would leak a tailnet or storage URL + } + h := resp.Header + h.Del("Set-Cookie") + for k := range h { + if lk := strings.ToLower(k); strings.HasPrefix(lk, "x-gitea") || strings.HasPrefix(lk, "x-forgejo") { + h.Del(k) + } + } + if v := h.Get("Www-Authenticate"); v != "" { + h.Set("Www-Authenticate", realmRe.ReplaceAllLiteralString(v, `realm="`+s.Cfg.SiteURL+`/v2/token"`)) + } + if strings.Contains(resp.Request.URL.Path, "/releases/download/") { + // uploaded assets could be anything, including HTML + h.Set("Content-Type", "application/octet-stream") + h.Set("Content-Disposition", "attachment") + } + return nil + }, + ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) { + s.Log.Warn("proxy", "path", r.URL.Path, "err", err) + http.Error(w, "bad gateway", http.StatusBadGateway) + }, + } +} + +type upstreamPath struct{} + +// proxyRoute handles the pass-through routes and reports whether p was one. +// Within them anything not explicitly allowed is refused. +func (s *Server) proxyRoute(w http.ResponseWriter, r *http.Request) bool { + p, user := r.URL.Path, s.Cfg.User + if !clean(p) { + return false // route() turns it into a 404 + } + first, rest, _ := strings.Cut(strings.TrimPrefix(p, "/"), "/") + get := r.Method == http.MethodGet || r.Method == http.MethodHead + noBody := r.ContentLength == 0 && len(r.TransferEncoding) == 0 + var target string + + switch { + case strings.Contains(p, "git-receive-pack") || strings.Contains(r.URL.RawQuery, "git-receive-pack"): + http.Error(w, "this is a read-only mirror", http.StatusForbidden) + return true + + case strings.HasSuffix(first, ".git"): // smart HTTP clone + repo := strings.TrimSuffix(first, ".git") + switch { + case !s.Cfg.HasRepo(repo): + case rest == "info/refs" && r.Method == http.MethodGet && r.URL.RawQuery == "service=git-upload-pack" && noBody: + target = "/" + user + "/" + repo + ".git/info/refs" + case rest == "git-upload-pack" && r.Method == http.MethodPost && + r.Header.Get("Content-Type") == "application/x-git-upload-pack-request": + r.Body = http.MaxBytesReader(w, r.Body, maxUploadPack) + target = "/" + user + "/" + repo + ".git/git-upload-pack" + } + + case first == "v2": // container registry, pull only + switch { + case !get || !noBody: + case rest == "": + target = "/v2/" + case rest == "token" && s.pullOnly(r.URL.Query()["scope"]): + target = "/v2/token" + default: + if sub, ok := strings.CutPrefix(rest, user+"/"); ok { + if image, ok := s.registryImage(sub); ok { + target = "/v2/" + user + "/" + image + p[len("/v2/"+user+"/"+image):] + } + } + } + + case s.Cfg.HasRepo(first) && strings.HasPrefix(rest, "releases/download/"): + parts := strings.Split(strings.TrimPrefix(rest, "releases/download/"), "/") + if get && noBody && len(parts) == 2 && parts[0] != "" && parts[1] != "" { + target = "/" + user + "/" + first + "/" + rest + } + + default: + return false + } + + if target == "" { + http.NotFound(w, r) + return true + } + s.proxy.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), upstreamPath{}, target))) + return true +} + +// registryImage splits "/(manifests|blobs)/" and checks the +// image against the allowlist. Image names may contain slashes. +func (s *Server) registryImage(rest string) (string, bool) { + for _, kind := range []string{"/manifests/", "/blobs/"} { + if i := strings.LastIndex(rest, kind); i > 0 { + image, ref := rest[:i], rest[i+len(kind):] + return image, ref != "" && !strings.Contains(ref, "/") && s.Cfg.HasImage(image) + } + } + return "", false +} + +// pullOnly allows token requests whose scopes are all pulls of allowlisted images. +func (s *Server) pullOnly(scopes []string) bool { + for _, sc := range scopes { + image, ok := strings.CutPrefix(sc, "repository:"+s.Cfg.User+"/") + if !ok || !strings.HasSuffix(image, ":pull") || !s.Cfg.HasImage(strings.TrimSuffix(image, ":pull")) { + return false + } + } + return true +} diff --git a/internal/server/proxy_test.go b/internal/server/proxy_test.go new file mode 100644 index 0000000..18d6f3e --- /dev/null +++ b/internal/server/proxy_test.go @@ -0,0 +1,226 @@ +package server + +import ( + "io" + "log/slog" + "net/http" + "net/http/cgi" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// upstream is a fake Gitea that records what reaches it. +type upstream struct { + got []*http.Request + resp func(w http.ResponseWriter, r *http.Request) +} + +func proxyServer(t *testing.T, u *upstream, ready bool) *Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + u.got = append(u.got, r.Clone(r.Context())) + if u.resp != nil { + u.resp(w, r) + return + } + w.Header().Set("Set-Cookie", "i_like_gitea=1") + w.Header().Set("X-Gitea-Debug", "yes") + w.Header().Set("Www-Authenticate", `Bearer realm="http://gitea.tailnet.example:3000/v2/token",service="container_registry",scope="*"`) + io.WriteString(w, "upstream "+r.URL.RequestURI()) + })) + t.Cleanup(srv.Close) + s := testServer(t, ready) + cfg := *s.Cfg + cfg.GiteaURL = srv.URL + return New(&cfg, s.Root, s.Ready, slog.New(slog.NewTextHandler(io.Discard, nil))) +} + +func TestProxyRoutes(t *testing.T) { + u := &upstream{} + s := proxyServer(t, u, true) + pack := map[string]string{"Content-Type": "application/x-git-upload-pack-request"} + cases := []struct { + method, path string + hdr map[string]string + status int + upstream string // expected upstream RequestURI, "" if it must not be reached + }{ + {"GET", "/repo-a.git/info/refs?service=git-upload-pack", nil, 200, "/daniel/repo-a.git/info/refs?service=git-upload-pack"}, + {"POST", "/repo-a.git/git-upload-pack", pack, 200, "/daniel/repo-a.git/git-upload-pack"}, + {"GET", "/v2/", nil, 200, "/v2/"}, + {"HEAD", "/v2/", nil, 200, "/v2/"}, + {"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"}, + {"GET", "/v2/daniel/repo-a/manifests/latest", nil, 200, "/v2/daniel/repo-a/manifests/latest"}, + {"HEAD", "/v2/daniel/tools/cli/blobs/sha256:abc", nil, 200, "/v2/daniel/tools/cli/blobs/sha256:abc"}, + {"GET", "/repo-a/releases/download/v1.0/app.tar.gz", nil, 200, "/daniel/repo-a/releases/download/v1.0/app.tar.gz"}, + + // push and anything else on these prefixes never reaches Gitea + {"GET", "/repo-a.git/info/refs?service=git-receive-pack", nil, 403, ""}, + {"POST", "/repo-a.git/git-receive-pack", nil, 403, ""}, + {"GET", "/repo-a.git/info/refs", nil, 404, ""}, + {"GET", "/repo-a.git/info/refs?service=git-upload-pack&x=1", nil, 404, ""}, + {"GET", "/repo-a.git/HEAD", nil, 404, ""}, + {"POST", "/repo-a.git/git-upload-pack", nil, 404, ""}, + {"GET", "/secret.git/info/refs?service=git-upload-pack", nil, 404, ""}, + {"GET", "/repo-a.git/../secret.git/info/refs?service=git-upload-pack", nil, 404, ""}, + {"PUT", "/v2/daniel/repo-a/manifests/latest", nil, 404, ""}, + {"POST", "/v2/daniel/repo-a/blobs/uploads/", nil, 404, ""}, + {"PATCH", "/v2/daniel/repo-a/blobs/uploads/x", nil, 404, ""}, + {"DELETE", "/v2/daniel/repo-a/manifests/latest", nil, 404, ""}, + {"GET", "/v2/token?scope=repository:daniel/repo-a:pull,push", nil, 404, ""}, + {"GET", "/v2/token?scope=repository:daniel/secret:pull", nil, 404, ""}, + {"GET", "/v2/daniel/secret/manifests/latest", nil, 404, ""}, + {"GET", "/v2/other/repo-a/manifests/latest", nil, 404, ""}, + {"GET", "/v2/_catalog", nil, 404, ""}, + {"GET", "/v2/daniel/repo-a/tags/list", nil, 404, ""}, + {"GET", "/secret/releases/download/v1/x", nil, 404, ""}, + {"GET", "/repo-a/releases/download/v1/a/b", nil, 404, ""}, + {"GET", "/api/v1/repos/daniel/repo-a", nil, 404, ""}, + {"GET", "/daniel/repo-a.git/info/refs?service=git-upload-pack", nil, 404, ""}, + } + for _, c := range cases { + u.got = nil + req := httptest.NewRequest(c.method, c.path, nil) + req.Header.Set("Cookie", "session=abc") + req.Header.Set("Authorization", "Basic ZGFuaWVsOnNlY3JldA==") + for k, v := range c.hdr { + req.Header.Set(k, v) + } + w := httptest.NewRecorder() + s.ServeHTTP(w, req) + if w.Code != c.status { + t.Errorf("%s %s: status %d, want %d", c.method, c.path, w.Code, c.status) + } + switch { + case c.upstream == "" && len(u.got) > 0: + t.Errorf("%s %s: reached upstream as %s", c.method, c.path, u.got[0].URL.RequestURI()) + case c.upstream != "" && len(u.got) != 1: + t.Errorf("%s %s: did not reach upstream", c.method, c.path) + case c.upstream != "": + g := u.got[0] + if g.URL.RequestURI() != c.upstream { + t.Errorf("%s %s: upstream got %s, want %s", c.method, c.path, g.URL.RequestURI(), c.upstream) + } + if g.Header.Get("Cookie") != "" || g.Header.Get("X-Forwarded-For") != "" { + t.Errorf("%s %s: forwarded cookie or proxy headers", c.method, c.path) + } + if g.Header.Get("Authorization") != "" { // the test sends Basic credentials + t.Errorf("%s %s: forwarded credentials", c.method, c.path) + } + h := w.Header() + if h.Get("Set-Cookie") != "" || h.Get("X-Gitea-Debug") != "" { + t.Errorf("%s %s: leaked upstream headers", c.method, c.path) + } + if a := h.Get("Www-Authenticate"); strings.Contains(a, "tailnet") || !strings.Contains(a, `realm="https://daum.dev/v2/token"`) { + t.Errorf("%s %s: realm not rewritten: %s", c.method, c.path, a) + } + } + } +} + +func TestProxyBeforeFirstBuild(t *testing.T) { + u := &upstream{} + s := proxyServer(t, u, false) + w := httptest.NewRecorder() + s.ServeHTTP(w, httptest.NewRequest("GET", "/repo-a.git/info/refs?service=git-upload-pack", nil)) + if w.Code != 200 || len(u.got) != 1 { + t.Errorf("clone route before first build: %d", w.Code) + } + w = httptest.NewRecorder() + req := httptest.NewRequest("GET", "/v2/daniel/repo-a/manifests/latest", nil) + req.Header.Set("Authorization", "Bearer anon-token") + s.ServeHTTP(w, req) + if len(u.got) != 2 || u.got[1].Header.Get("Authorization") != "Bearer anon-token" { + t.Error("registry bearer token was not forwarded") + } +} + +func TestProxyResponses(t *testing.T) { + u := &upstream{} + s := proxyServer(t, u, true) + + u.resp = func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html") + io.WriteString(w, "") + } + w := httptest.NewRecorder() + s.ServeHTTP(w, httptest.NewRequest("GET", "/repo-a/releases/download/v1/x.html", nil)) + if w.Header().Get("Content-Type") != "application/octet-stream" || w.Header().Get("Content-Disposition") != "attachment" { + t.Errorf("release asset served as %q", w.Header().Get("Content-Type")) + } + + u.resp = func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, "http://minio.tailnet.example/bucket/blob", http.StatusTemporaryRedirect) + } + w = httptest.NewRecorder() + s.ServeHTTP(w, httptest.NewRequest("GET", "/v2/daniel/repo-a/blobs/sha256:abc", nil)) + if w.Code != http.StatusBadGateway || strings.Contains(w.Header().Get("Location"), "tailnet") { + t.Errorf("upstream redirect passed through: %d %s", w.Code, w.Header().Get("Location")) + } + + u.resp = func(w http.ResponseWriter, r *http.Request) { io.Copy(io.Discard, r.Body) } + big := strings.NewReader(strings.Repeat("x", maxUploadPack+1)) + req := httptest.NewRequest("POST", "/repo-a.git/git-upload-pack", big) + req.Header.Set("Content-Type", "application/x-git-upload-pack-request") + w = httptest.NewRecorder() + s.ServeHTTP(w, req) + if w.Code == http.StatusOK { + t.Error("oversized upload-pack body was accepted") + } +} + +// TestCloneAndPush runs real git through the proxy: clone works, push fails. +func TestCloneAndPush(t *testing.T) { + git := func(dir string, args ...string) error { + cmd := exec.Command("git", args...) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1", "GIT_TERMINAL_PROMPT=0", + "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@t", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@t") + out, err := cmd.CombinedOutput() + if err != nil { + t.Logf("git %v: %s", args, out) + } + return err + } + root := t.TempDir() + work := filepath.Join(root, "work") + os.MkdirAll(work, 0o755) + os.WriteFile(filepath.Join(work, "f"), []byte("hi\n"), 0o644) + if git(work, "init", "-q", "-b", "main") != nil || git(work, "add", "f") != nil || + git(work, "commit", "-q", "--no-gpg-sign", "-m", "c") != nil || + git(root, "clone", "-q", "--bare", work, "daniel/repo-a.git") != nil || + git(filepath.Join(root, "daniel/repo-a.git"), "config", "http.receivepack", "true") != nil { + t.Fatal("fixture setup failed") + } + gitPath, _ := exec.LookPath("git") + backend := &cgi.Handler{Path: gitPath, Args: []string{"http-backend"}, + Env: []string{"GIT_PROJECT_ROOT=" + root, "GIT_HTTP_EXPORT_ALL=1"}} + up := httptest.NewServer(backend) + defer up.Close() + + s := testServer(t, true) + cfg := *s.Cfg + cfg.GiteaURL = up.URL + site := httptest.NewServer(New(&cfg, s.Root, s.Ready, s.Log)) + defer site.Close() + + clone := filepath.Join(root, "clone") + if err := git(root, "clone", "-q", site.URL+"/repo-a.git", clone); err != nil { + t.Fatal("clone through the proxy failed") + } + if b, _ := os.ReadFile(filepath.Join(clone, "f")); string(b) != "hi\n" { + t.Fatal("clone has wrong content") + } + os.WriteFile(filepath.Join(clone, "f"), []byte("changed\n"), 0o644) + git(clone, "commit", "-qam", "push attempt", "--no-gpg-sign") + if err := git(clone, "push", "-q", "origin", "main"); err == nil { + t.Fatal("push through the proxy succeeded") + } + if err := git(root, "clone", "-q", site.URL+"/secret.git", filepath.Join(root, "nope")); err == nil { + t.Fatal("cloned a repo that is not allowlisted") + } +} diff --git a/internal/server/server.go b/internal/server/server.go index 45ec2ad..81c56da 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -10,6 +10,7 @@ import ( "log/slog" "net" "net/http" + "net/http/httputil" "net/netip" "os" "path" @@ -27,6 +28,13 @@ type Server struct { Root func() string // directory of the current build Ready func() bool Log *slog.Logger + proxy *httputil.ReverseProxy +} + +func New(cfg *config.Config, root func() string, ready func() bool, log *slog.Logger) *Server { + s := &Server{Cfg: cfg, Root: root, Ready: ready, Log: log} + s.proxy = s.newProxy() + return s } // ListenAndServe serves until ctx ends, then shuts down gracefully. @@ -64,6 +72,9 @@ func (s *Server) route(w http.ResponseWriter, r *http.Request) { h.Set("X-Content-Type-Options", "nosniff") h.Set("Referrer-Policy", "no-referrer") h.Set("Content-Security-Policy", csp) + if s.proxyRoute(w, r) { // works before the first build, too + return + } if r.Method != http.MethodGet && r.Method != http.MethodHead { http.NotFound(w, r) diff --git a/internal/server/server_test.go b/internal/server/server_test.go index 8562815..91bd3d3 100644 --- a/internal/server/server_test.go +++ b/internal/server/server_test.go @@ -37,12 +37,9 @@ func testServer(t *testing.T, ready bool) *Server { os.MkdirAll(filepath.Dir(p), 0o755) os.WriteFile(p, []byte(body), 0o644) } - return &Server{ - Cfg: &config.Config{Repos: []string{"repo-a"}, TrustedProxies: []string{"10.0.0.1"}}, - Root: func() string { return root }, - Ready: func() bool { return ready }, - Log: slog.New(slog.NewTextHandler(io.Discard, nil)), - } + cfg := &config.Config{GiteaURL: "http://127.0.0.1:1", User: "daniel", SiteURL: "https://daum.dev", + Repos: []string{"repo-a"}, Images: []string{"repo-a", "tools/cli"}, TrustedProxies: []string{"10.0.0.1"}} + return New(cfg, func() string { return root }, func() bool { return ready }, slog.New(slog.NewTextHandler(io.Discard, nil))) } func do(s *Server, method, target string, body io.Reader) *httptest.ResponseRecorder {