showcase
- v0.2.4
- 37 commits
- 1 branch
- 6 tags
- updated
- CI 2/2
feat: add git and registry proxy with route allowlist
Showing 6 changed files with 416 additions and 7 deletions.
cmd/daumdev/main.go
+1 −1
@@ -35,7 +35,7 @@ func main() {35353636 b := build.New(cfg, *data)3737 if !*once {38 srv := &server.Server{Cfg: cfg, Root: b.Current, Ready: b.Ready, Log: slog.Default()}38 srv := server.New(cfg, b.Current, b.Ready, slog.Default())3939 if *serveDir != "" {4040 srv.Root, srv.Ready = func() string { return *serveDir }, func() bool { return true }4141 } else {
docs/decisions.md
+23 −0
@@ -127,3 +127,26 @@ details are in `docs/theme.md`. This replaces the spec's original127127 the TCP peer.128128- `-serve-dir DIR` (dev only) serves a finished build without building; `just129129 serve` and `just demo` use it.130131## Git and registry proxy132133- Proxy routes are matched before anything else and work before the first134 build. Within the `.git`, `/v2` and `releases/download` prefixes anything not135 explicitly allowed is a 404. Any path or query containing136 `git-receive-pack` is a 403.137- Requests to Gitea never carry `Cookie` or `X-Forwarded-*`. `Authorization`138 passes only when it is a `Bearer` token on a registry manifest or blob139 route, which is the anonymous token Gitea just issued. Basic credentials140 are never forwarded.141- `/v2/token` is forwarded only when every `scope` is a pull of an142 allowlisted image. `_catalog` and `tags/list` are 404.143- Any 3xx from Gitea becomes a 502, so storage or tailnet URLs never reach144 clients. With Gitea's local storage, blobs and assets are served directly,145 so this doesn't happen in practice.146- Release assets are always `application/octet-stream` with147 `Content-Disposition: attachment`.148- The `git-upload-pack` body is capped at 10 MB and must have the git149 request content type.150- Gitea must allow anonymous HTTP git and registry reads151 (`REQUIRE_SIGNIN_VIEW = false`, HTTP git not disabled), or public clones and152 pulls fail.
internal/server/proxy.goadded
+152 −0
@@ -0,0 +1,152 @@1package server23import (4 "context"5 "errors"6 "net/http"7 "net/http/httputil"8 "net/url"9 "regexp"10 "strings"11 "time"12)1314const maxUploadPack = 10 << 201516var realmRe = regexp.MustCompile(`realm="[^"]*"`)1718// newProxy forwards allowlisted git, registry and release-download requests19// to Gitea. It never forwards cookies or proxy headers, refuses upstream20// redirects, and strips cookies and Gitea headers from responses.21func (s *Server) newProxy() *httputil.ReverseProxy {22 up, _ := url.Parse(s.Cfg.GiteaURL)23 t := http.DefaultTransport.(*http.Transport).Clone()24 t.Proxy, t.ResponseHeaderTimeout = nil, 60*time.Second25 return &httputil.ReverseProxy{26 Rewrite: func(pr *httputil.ProxyRequest) {27 pr.Out.URL.Path, pr.Out.URL.RawPath = pr.In.Context().Value(upstreamPath{}).(string), ""28 pr.SetURL(up)29 pr.Out.Host = up.Host30 pr.Out.Header.Del("Cookie")31 // only the registry's own (anonymous) bearer tokens pass, never credentials32 a := pr.In.Header.Get("Authorization")33 if !strings.HasPrefix(pr.In.URL.Path, "/v2/") || pr.In.URL.Path == "/v2/token" || !strings.HasPrefix(a, "Bearer ") {34 pr.Out.Header.Del("Authorization")35 }36 },37 FlushInterval: -1, // stream clones and layers38 Transport: t,39 ModifyResponse: func(resp *http.Response) error {40 if resp.StatusCode >= 300 && resp.StatusCode < 400 {41 return errors.New("upstream redirect refused") // would leak a tailnet or storage URL42 }43 h := resp.Header44 h.Del("Set-Cookie")45 for k := range h {46 if lk := strings.ToLower(k); strings.HasPrefix(lk, "x-gitea") || strings.HasPrefix(lk, "x-forgejo") {47 h.Del(k)48 }49 }50 if v := h.Get("Www-Authenticate"); v != "" {51 h.Set("Www-Authenticate", realmRe.ReplaceAllLiteralString(v, `realm="`+s.Cfg.SiteURL+`/v2/token"`))52 }53 if strings.Contains(resp.Request.URL.Path, "/releases/download/") {54 // uploaded assets could be anything, including HTML55 h.Set("Content-Type", "application/octet-stream")56 h.Set("Content-Disposition", "attachment")57 }58 return nil59 },60 ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {61 s.Log.Warn("proxy", "path", r.URL.Path, "err", err)62 http.Error(w, "bad gateway", http.StatusBadGateway)63 },64 }65}6667type upstreamPath struct{}6869// proxyRoute handles the pass-through routes and reports whether p was one.70// Within them anything not explicitly allowed is refused.71func (s *Server) proxyRoute(w http.ResponseWriter, r *http.Request) bool {72 p, user := r.URL.Path, s.Cfg.User73 if !clean(p) {74 return false // route() turns it into a 40475 }76 first, rest, _ := strings.Cut(strings.TrimPrefix(p, "/"), "/")77 get := r.Method == http.MethodGet || r.Method == http.MethodHead78 noBody := r.ContentLength == 0 && len(r.TransferEncoding) == 079 var target string8081 switch {82 case strings.Contains(p, "git-receive-pack") || strings.Contains(r.URL.RawQuery, "git-receive-pack"):83 http.Error(w, "this is a read-only mirror", http.StatusForbidden)84 return true8586 case strings.HasSuffix(first, ".git"): // smart HTTP clone87 repo := strings.TrimSuffix(first, ".git")88 switch {89 case !s.Cfg.HasRepo(repo):90 case rest == "info/refs" && r.Method == http.MethodGet && r.URL.RawQuery == "service=git-upload-pack" && noBody:91 target = "/" + user + "/" + repo + ".git/info/refs"92 case rest == "git-upload-pack" && r.Method == http.MethodPost &&93 r.Header.Get("Content-Type") == "application/x-git-upload-pack-request":94 r.Body = http.MaxBytesReader(w, r.Body, maxUploadPack)95 target = "/" + user + "/" + repo + ".git/git-upload-pack"96 }9798 case first == "v2": // container registry, pull only99 switch {100 case !get || !noBody:101 case rest == "":102 target = "/v2/"103 case rest == "token" && s.pullOnly(r.URL.Query()["scope"]):104 target = "/v2/token"105 default:106 if sub, ok := strings.CutPrefix(rest, user+"/"); ok {107 if image, ok := s.registryImage(sub); ok {108 target = "/v2/" + user + "/" + image + p[len("/v2/"+user+"/"+image):]109 }110 }111 }112113 case s.Cfg.HasRepo(first) && strings.HasPrefix(rest, "releases/download/"):114 parts := strings.Split(strings.TrimPrefix(rest, "releases/download/"), "/")115 if get && noBody && len(parts) == 2 && parts[0] != "" && parts[1] != "" {116 target = "/" + user + "/" + first + "/" + rest117 }118119 default:120 return false121 }122123 if target == "" {124 http.NotFound(w, r)125 return true126 }127 s.proxy.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), upstreamPath{}, target)))128 return true129}130131// registryImage splits "<image>/(manifests|blobs)/<ref>" and checks the132// image against the allowlist. Image names may contain slashes.133func (s *Server) registryImage(rest string) (string, bool) {134 for _, kind := range []string{"/manifests/", "/blobs/"} {135 if i := strings.LastIndex(rest, kind); i > 0 {136 image, ref := rest[:i], rest[i+len(kind):]137 return image, ref != "" && !strings.Contains(ref, "/") && s.Cfg.HasImage(image)138 }139 }140 return "", false141}142143// pullOnly allows token requests whose scopes are all pulls of allowlisted images.144func (s *Server) pullOnly(scopes []string) bool {145 for _, sc := range scopes {146 image, ok := strings.CutPrefix(sc, "repository:"+s.Cfg.User+"/")147 if !ok || !strings.HasSuffix(image, ":pull") || !s.Cfg.HasImage(strings.TrimSuffix(image, ":pull")) {148 return false149 }150 }151 return true152}
internal/server/proxy_test.goadded
+226 −0
@@ -0,0 +1,226 @@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 "strings"13 "testing"14)1516// upstream is a fake Gitea that records what reaches it.17type upstream struct {18 got []*http.Request19 resp func(w http.ResponseWriter, r *http.Request)20}2122func proxyServer(t *testing.T, u *upstream, ready bool) *Server {23 t.Helper()24 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {25 u.got = append(u.got, r.Clone(r.Context()))26 if u.resp != nil {27 u.resp(w, r)28 return29 }30 w.Header().Set("Set-Cookie", "i_like_gitea=1")31 w.Header().Set("X-Gitea-Debug", "yes")32 w.Header().Set("Www-Authenticate", `Bearer realm="http://gitea.tailnet.example:3000/v2/token",service="container_registry",scope="*"`)33 io.WriteString(w, "upstream "+r.URL.RequestURI())34 }))35 t.Cleanup(srv.Close)36 s := testServer(t, ready)37 cfg := *s.Cfg38 cfg.GiteaURL = srv.URL39 return New(&cfg, s.Root, s.Ready, slog.New(slog.NewTextHandler(io.Discard, nil)))40}4142func TestProxyRoutes(t *testing.T) {43 u := &upstream{}44 s := proxyServer(t, u, true)45 pack := map[string]string{"Content-Type": "application/x-git-upload-pack-request"}46 cases := []struct {47 method, path string48 hdr map[string]string49 status int50 upstream string // expected upstream RequestURI, "" if it must not be reached51 }{52 {"GET", "/repo-a.git/info/refs?service=git-upload-pack", nil, 200, "/daniel/repo-a.git/info/refs?service=git-upload-pack"},53 {"POST", "/repo-a.git/git-upload-pack", pack, 200, "/daniel/repo-a.git/git-upload-pack"},54 {"GET", "/v2/", nil, 200, "/v2/"},55 {"HEAD", "/v2/", nil, 200, "/v2/"},56 {"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"},57 {"GET", "/v2/daniel/repo-a/manifests/latest", nil, 200, "/v2/daniel/repo-a/manifests/latest"},58 {"HEAD", "/v2/daniel/tools/cli/blobs/sha256:abc", nil, 200, "/v2/daniel/tools/cli/blobs/sha256:abc"},59 {"GET", "/repo-a/releases/download/v1.0/app.tar.gz", nil, 200, "/daniel/repo-a/releases/download/v1.0/app.tar.gz"},6061 // push and anything else on these prefixes never reaches Gitea62 {"GET", "/repo-a.git/info/refs?service=git-receive-pack", nil, 403, ""},63 {"POST", "/repo-a.git/git-receive-pack", nil, 403, ""},64 {"GET", "/repo-a.git/info/refs", nil, 404, ""},65 {"GET", "/repo-a.git/info/refs?service=git-upload-pack&x=1", nil, 404, ""},66 {"GET", "/repo-a.git/HEAD", nil, 404, ""},67 {"POST", "/repo-a.git/git-upload-pack", nil, 404, ""},68 {"GET", "/secret.git/info/refs?service=git-upload-pack", nil, 404, ""},69 {"GET", "/repo-a.git/../secret.git/info/refs?service=git-upload-pack", nil, 404, ""},70 {"PUT", "/v2/daniel/repo-a/manifests/latest", nil, 404, ""},71 {"POST", "/v2/daniel/repo-a/blobs/uploads/", nil, 404, ""},72 {"PATCH", "/v2/daniel/repo-a/blobs/uploads/x", nil, 404, ""},73 {"DELETE", "/v2/daniel/repo-a/manifests/latest", nil, 404, ""},74 {"GET", "/v2/token?scope=repository:daniel/repo-a:pull,push", nil, 404, ""},75 {"GET", "/v2/token?scope=repository:daniel/secret:pull", nil, 404, ""},76 {"GET", "/v2/daniel/secret/manifests/latest", nil, 404, ""},77 {"GET", "/v2/other/repo-a/manifests/latest", nil, 404, ""},78 {"GET", "/v2/_catalog", nil, 404, ""},79 {"GET", "/v2/daniel/repo-a/tags/list", nil, 404, ""},80 {"GET", "/secret/releases/download/v1/x", nil, 404, ""},81 {"GET", "/repo-a/releases/download/v1/a/b", nil, 404, ""},82 {"GET", "/api/v1/repos/daniel/repo-a", nil, 404, ""},83 {"GET", "/daniel/repo-a.git/info/refs?service=git-upload-pack", nil, 404, ""},84 }85 for _, c := range cases {86 u.got = nil87 req := httptest.NewRequest(c.method, c.path, nil)88 req.Header.Set("Cookie", "session=abc")89 req.Header.Set("Authorization", "Basic ZGFuaWVsOnNlY3JldA==")90 for k, v := range c.hdr {91 req.Header.Set(k, v)92 }93 w := httptest.NewRecorder()94 s.ServeHTTP(w, req)95 if w.Code != c.status {96 t.Errorf("%s %s: status %d, want %d", c.method, c.path, w.Code, c.status)97 }98 switch {99 case c.upstream == "" && len(u.got) > 0:100 t.Errorf("%s %s: reached upstream as %s", c.method, c.path, u.got[0].URL.RequestURI())101 case c.upstream != "" && len(u.got) != 1:102 t.Errorf("%s %s: did not reach upstream", c.method, c.path)103 case c.upstream != "":104 g := u.got[0]105 if g.URL.RequestURI() != c.upstream {106 t.Errorf("%s %s: upstream got %s, want %s", c.method, c.path, g.URL.RequestURI(), c.upstream)107 }108 if g.Header.Get("Cookie") != "" || g.Header.Get("X-Forwarded-For") != "" {109 t.Errorf("%s %s: forwarded cookie or proxy headers", c.method, c.path)110 }111 if g.Header.Get("Authorization") != "" { // the test sends Basic credentials112 t.Errorf("%s %s: forwarded credentials", c.method, c.path)113 }114 h := w.Header()115 if h.Get("Set-Cookie") != "" || h.Get("X-Gitea-Debug") != "" {116 t.Errorf("%s %s: leaked upstream headers", c.method, c.path)117 }118 if a := h.Get("Www-Authenticate"); strings.Contains(a, "tailnet") || !strings.Contains(a, `realm="https://daum.dev/v2/token"`) {119 t.Errorf("%s %s: realm not rewritten: %s", c.method, c.path, a)120 }121 }122 }123}124125func TestProxyBeforeFirstBuild(t *testing.T) {126 u := &upstream{}127 s := proxyServer(t, u, false)128 w := httptest.NewRecorder()129 s.ServeHTTP(w, httptest.NewRequest("GET", "/repo-a.git/info/refs?service=git-upload-pack", nil))130 if w.Code != 200 || len(u.got) != 1 {131 t.Errorf("clone route before first build: %d", w.Code)132 }133 w = httptest.NewRecorder()134 req := httptest.NewRequest("GET", "/v2/daniel/repo-a/manifests/latest", nil)135 req.Header.Set("Authorization", "Bearer anon-token")136 s.ServeHTTP(w, req)137 if len(u.got) != 2 || u.got[1].Header.Get("Authorization") != "Bearer anon-token" {138 t.Error("registry bearer token was not forwarded")139 }140}141142func TestProxyResponses(t *testing.T) {143 u := &upstream{}144 s := proxyServer(t, u, true)145146 u.resp = func(w http.ResponseWriter, r *http.Request) {147 w.Header().Set("Content-Type", "text/html")148 io.WriteString(w, "<script>alert(1)</script>")149 }150 w := httptest.NewRecorder()151 s.ServeHTTP(w, httptest.NewRequest("GET", "/repo-a/releases/download/v1/x.html", nil))152 if w.Header().Get("Content-Type") != "application/octet-stream" || w.Header().Get("Content-Disposition") != "attachment" {153 t.Errorf("release asset served as %q", w.Header().Get("Content-Type"))154 }155156 u.resp = func(w http.ResponseWriter, r *http.Request) {157 http.Redirect(w, r, "http://minio.tailnet.example/bucket/blob", http.StatusTemporaryRedirect)158 }159 w = httptest.NewRecorder()160 s.ServeHTTP(w, httptest.NewRequest("GET", "/v2/daniel/repo-a/blobs/sha256:abc", nil))161 if w.Code != http.StatusBadGateway || strings.Contains(w.Header().Get("Location"), "tailnet") {162 t.Errorf("upstream redirect passed through: %d %s", w.Code, w.Header().Get("Location"))163 }164165 u.resp = func(w http.ResponseWriter, r *http.Request) { io.Copy(io.Discard, r.Body) }166 big := strings.NewReader(strings.Repeat("x", maxUploadPack+1))167 req := httptest.NewRequest("POST", "/repo-a.git/git-upload-pack", big)168 req.Header.Set("Content-Type", "application/x-git-upload-pack-request")169 w = httptest.NewRecorder()170 s.ServeHTTP(w, req)171 if w.Code == http.StatusOK {172 t.Error("oversized upload-pack body was accepted")173 }174}175176// TestCloneAndPush runs real git through the proxy: clone works, push fails.177func TestCloneAndPush(t *testing.T) {178 git := func(dir string, args ...string) error {179 cmd := exec.Command("git", args...)180 cmd.Dir = dir181 cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_CONFIG_NOSYSTEM=1", "GIT_TERMINAL_PROMPT=0",182 "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@t", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@t")183 out, err := cmd.CombinedOutput()184 if err != nil {185 t.Logf("git %v: %s", args, out)186 }187 return err188 }189 root := t.TempDir()190 work := filepath.Join(root, "work")191 os.MkdirAll(work, 0o755)192 os.WriteFile(filepath.Join(work, "f"), []byte("hi\n"), 0o644)193 if git(work, "init", "-q", "-b", "main") != nil || git(work, "add", "f") != nil ||194 git(work, "commit", "-q", "--no-gpg-sign", "-m", "c") != nil ||195 git(root, "clone", "-q", "--bare", work, "daniel/repo-a.git") != nil ||196 git(filepath.Join(root, "daniel/repo-a.git"), "config", "http.receivepack", "true") != nil {197 t.Fatal("fixture setup failed")198 }199 gitPath, _ := exec.LookPath("git")200 backend := &cgi.Handler{Path: gitPath, Args: []string{"http-backend"},201 Env: []string{"GIT_PROJECT_ROOT=" + root, "GIT_HTTP_EXPORT_ALL=1"}}202 up := httptest.NewServer(backend)203 defer up.Close()204205 s := testServer(t, true)206 cfg := *s.Cfg207 cfg.GiteaURL = up.URL208 site := httptest.NewServer(New(&cfg, s.Root, s.Ready, s.Log))209 defer site.Close()210211 clone := filepath.Join(root, "clone")212 if err := git(root, "clone", "-q", site.URL+"/repo-a.git", clone); err != nil {213 t.Fatal("clone through the proxy failed")214 }215 if b, _ := os.ReadFile(filepath.Join(clone, "f")); string(b) != "hi\n" {216 t.Fatal("clone has wrong content")217 }218 os.WriteFile(filepath.Join(clone, "f"), []byte("changed\n"), 0o644)219 git(clone, "commit", "-qam", "push attempt", "--no-gpg-sign")220 if err := git(clone, "push", "-q", "origin", "main"); err == nil {221 t.Fatal("push through the proxy succeeded")222 }223 if err := git(root, "clone", "-q", site.URL+"/secret.git", filepath.Join(root, "nope")); err == nil {224 t.Fatal("cloned a repo that is not allowlisted")225 }226}
internal/server/server.go
+11 −0
@@ -10,6 +10,7 @@ import (1010 "log/slog"1111 "net"1212 "net/http"13 "net/http/httputil"1314 "net/netip"1415 "os"1516 "path"@@ -27,6 +28,13 @@ type Server struct {2728 Root func() string // directory of the current build2829 Ready func() bool2930 Log *slog.Logger31 proxy *httputil.ReverseProxy32}3334func New(cfg *config.Config, root func() string, ready func() bool, log *slog.Logger) *Server {35 s := &Server{Cfg: cfg, Root: root, Ready: ready, Log: log}36 s.proxy = s.newProxy()37 return s3038}31393240// ListenAndServe serves until ctx ends, then shuts down gracefully.@@ -64,6 +72,9 @@ func (s *Server) route(w http.ResponseWriter, r *http.Request) {6472 h.Set("X-Content-Type-Options", "nosniff")6573 h.Set("Referrer-Policy", "no-referrer")6674 h.Set("Content-Security-Policy", csp)75 if s.proxyRoute(w, r) { // works before the first build, too76 return77 }67786879 if r.Method != http.MethodGet && r.Method != http.MethodHead {6980 http.NotFound(w, r)
internal/server/server_test.go
+3 −6
@@ -37,12 +37,9 @@ func testServer(t *testing.T, ready bool) *Server {3737 os.MkdirAll(filepath.Dir(p), 0o755)3838 os.WriteFile(p, []byte(body), 0o644)3939 }40 return &Server{41 Cfg: &config.Config{Repos: []string{"repo-a"}, TrustedProxies: []string{"10.0.0.1"}},42 Root: func() string { return root },43 Ready: func() bool { return ready },44 Log: slog.New(slog.NewTextHandler(io.Discard, nil)),45 }40 cfg := &config.Config{GiteaURL: "http://127.0.0.1:1", User: "daniel", SiteURL: "https://daum.dev",41 Repos: []string{"repo-a"}, Images: []string{"repo-a", "tools/cli"}, TrustedProxies: []string{"10.0.0.1"}}42 return New(cfg, func() string { return root }, func() bool { return ready }, slog.New(slog.NewTextHandler(io.Discard, nil)))4643}47444845func do(s *Server, method, target string, body io.Reader) *httptest.ResponseRecorder {