showcase
- v0.2.4
- 37 commits
- 1 branch
- 6 tags
- updated
- CI 2/2
proxy.go
6.5 KB · 187 lines
1package server23import (4 "context"5 "errors"6 "net/http"7 "net/http/httputil"8 "net/url"9 "regexp"10 "slices"11 "strings"12 "time"13)1415const (16 maxUploadPack = 10 << 2017 maxGitProxied = 8 // concurrent clones and fetches; more get a 50318)1920// forwardHeaders are the only request headers that reach Gitea. Anything21// else (cookies, proxy-auth headers like X-WEBAUTH-USER, X-Forwarded-*,22// Gitea's own X-Gitea-*) is dropped, so a visitor can't speak to Gitea as23// anyone but an anonymous client.24var forwardHeaders = []string{25 "Accept", "Accept-Encoding", "Content-Type", "Content-Encoding", "Git-Protocol",26 "User-Agent", "Range", "If-Range", "If-None-Match", "If-Modified-Since", "Authorization",27}2829var (30 realmRe = regexp.MustCompile(`realm="[^"]*"`)31 digestRe = regexp.MustCompile(`^sha256:[a-f0-9]{64}$`)32 refRe = regexp.MustCompile(`^([A-Za-z0-9_][A-Za-z0-9._-]{0,127}|sha256:[a-f0-9]{64})$`)33)3435// newProxy forwards allowlisted git, registry and release-download requests36// to Gitea. It never forwards cookies or proxy headers, refuses upstream37// redirects, and strips cookies and Gitea headers from responses.38func (s *Server) newProxy() *httputil.ReverseProxy {39 up, _ := url.Parse(s.Cfg.GiteaURL)40 t := http.DefaultTransport.(*http.Transport).Clone()41 t.Proxy, t.ResponseHeaderTimeout = nil, 60*time.Second42 return &httputil.ReverseProxy{43 Rewrite: func(pr *httputil.ProxyRequest) {44 pr.Out.URL.Path, pr.Out.URL.RawPath = pr.In.Context().Value(upstreamPath{}).(string), ""45 pr.SetURL(up)46 pr.Out.Host = up.Host47 for k := range pr.Out.Header {48 if !slices.Contains(forwardHeaders, http.CanonicalHeaderKey(k)) {49 pr.Out.Header.Del(k)50 }51 }52 // only the registry's own (anonymous) bearer tokens pass, never credentials53 a := pr.In.Header.Get("Authorization")54 if !strings.HasPrefix(pr.In.URL.Path, "/v2/") || pr.In.URL.Path == "/v2/token" || !strings.HasPrefix(a, "Bearer ") {55 pr.Out.Header.Del("Authorization")56 }57 },58 FlushInterval: -1, // stream clones and layers59 Transport: t,60 ModifyResponse: func(resp *http.Response) error {61 if resp.StatusCode >= 300 && resp.StatusCode < 400 {62 return errors.New("upstream redirect refused") // would leak a tailnet or storage URL63 }64 h := resp.Header65 h.Del("Set-Cookie")66 for k := range h {67 if lk := strings.ToLower(k); strings.HasPrefix(lk, "x-gitea") || strings.HasPrefix(lk, "x-forgejo") {68 h.Del(k)69 }70 }71 // point the registry's token realm at us; drop other challenges so72 // clients never prompt for (or send) credentials73 if v := h.Get("Www-Authenticate"); strings.HasPrefix(v, "Bearer ") {74 h.Set("Www-Authenticate", realmRe.ReplaceAllLiteralString(v, `realm="`+s.Cfg.SiteURL+`/v2/token"`))75 } else {76 h.Del("Www-Authenticate")77 }78 if strings.Contains(resp.Request.URL.Path, "/releases/download/") || strings.Contains(resp.Request.URL.Path, "/blobs/") {79 // uploaded assets and image layers could be anything, including HTML80 h.Set("Content-Type", "application/octet-stream")81 h.Set("Content-Disposition", "attachment")82 }83 return nil84 },85 ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {86 s.Log.Warn("proxy", "path", r.URL.Path, "err", err)87 http.Error(w, "bad gateway", http.StatusBadGateway)88 },89 }90}9192type upstreamPath struct{}9394// proxyRoute handles the pass-through routes and reports whether p was one.95// Within them anything not explicitly allowed is refused.96func (s *Server) proxyRoute(w http.ResponseWriter, r *http.Request) bool {97 p, user := r.URL.Path, s.Cfg.User98 if !clean(p) {99 return false // route() turns it into a 404100 }101 first, rest, _ := strings.Cut(strings.TrimPrefix(p, "/"), "/")102 get := r.Method == http.MethodGet || r.Method == http.MethodHead103 noBody := r.ContentLength == 0 && len(r.TransferEncoding) == 0104 var target string105106 switch {107 case strings.Contains(p, "git-receive-pack") || strings.Contains(r.URL.RawQuery, "git-receive-pack"):108 http.Error(w, "this is a read-only mirror", http.StatusForbidden)109 return true110111 case strings.HasSuffix(first, ".git"): // smart HTTP clone112 repo := strings.TrimSuffix(first, ".git")113 switch {114 case !s.Cfg.HasRepo(repo):115 case rest == "info/refs" && r.Method == http.MethodGet && r.URL.RawQuery == "service=git-upload-pack" && noBody:116 target = "/" + user + "/" + repo + ".git/info/refs"117 case rest == "git-upload-pack" && r.Method == http.MethodPost &&118 r.Header.Get("Content-Type") == "application/x-git-upload-pack-request":119 r.Body = http.MaxBytesReader(w, r.Body, maxUploadPack)120 target = "/" + user + "/" + repo + ".git/git-upload-pack"121 }122123 case first == "v2": // container registry, pull only124 switch {125 case !get || !noBody:126 case rest == "":127 target = "/v2/"128 case rest == "token" && s.pullOnly(r.URL.Query()["scope"]):129 target = "/v2/token"130 default:131 if sub, ok := strings.CutPrefix(rest, user+"/"); ok {132 if image, ok := s.registryImage(sub); ok {133 target = "/v2/" + user + "/" + image + p[len("/v2/"+user+"/"+image):]134 }135 }136 }137138 case s.Cfg.HasRepo(first) && strings.HasPrefix(rest, "releases/download/"):139 parts := strings.Split(strings.TrimPrefix(rest, "releases/download/"), "/")140 if get && noBody && len(parts) == 2 && parts[0] != "" && parts[1] != "" {141 target = "/" + user + "/" + first + "/" + rest142 }143144 default:145 return false146 }147148 if target == "" {149 http.NotFound(w, r)150 return true151 }152 if strings.HasSuffix(first, ".git") { // upload-pack is the expensive one for Gitea153 select {154 case s.gitSlots <- struct{}{}:155 defer func() { <-s.gitSlots }()156 default:157 w.Header().Set("Retry-After", "30")158 http.Error(w, "busy, try again shortly", http.StatusServiceUnavailable)159 return true160 }161 }162 s.proxy.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), upstreamPath{}, target)))163 return true164}165166// registryImage splits "<image>/(manifests|blobs)/<ref>" and checks the167// image against the allowlist. Image names may contain slashes.168func (s *Server) registryImage(rest string) (string, bool) {169 for kind, ok := range map[string]*regexp.Regexp{"/manifests/": refRe, "/blobs/": digestRe} {170 if i := strings.LastIndex(rest, kind); i > 0 {171 image, ref := rest[:i], rest[i+len(kind):]172 return image, ok.MatchString(ref) && s.Cfg.HasImage(image)173 }174 }175 return "", false176}177178// pullOnly allows token requests whose scopes are all pulls of allowlisted images.179func (s *Server) pullOnly(scopes []string) bool {180 for _, sc := range scopes {181 image, ok := strings.CutPrefix(sc, "repository:"+s.Cfg.User+"/")182 if !ok || !strings.HasSuffix(image, ":pull") || !s.Cfg.HasImage(strings.TrimSuffix(image, ":pull")) {183 return false184 }185 }186 return true187}