debian-mirror-gitlab/workhorse/internal/upstream/routes.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

438 lines
16 KiB
Go
Raw Normal View History

2021-02-22 17:27:13 +05:30
package upstream
import (
"net/http"
"net/url"
"regexp"
"github.com/gorilla/websocket"
2022-11-25 23:54:43 +05:30
"github.com/prometheus/client_golang/prometheus"
2021-02-22 17:27:13 +05:30
"gitlab.com/gitlab-org/labkit/log"
"gitlab.com/gitlab-org/labkit/tracing"
2021-10-27 15:23:28 +05:30
apipkg "gitlab.com/gitlab-org/gitlab/workhorse/internal/api"
"gitlab.com/gitlab-org/gitlab/workhorse/internal/artifacts"
"gitlab.com/gitlab-org/gitlab/workhorse/internal/builds"
"gitlab.com/gitlab-org/gitlab/workhorse/internal/channel"
"gitlab.com/gitlab-org/gitlab/workhorse/internal/config"
2021-11-18 22:05:49 +05:30
"gitlab.com/gitlab-org/gitlab/workhorse/internal/dependencyproxy"
2021-10-27 15:23:28 +05:30
"gitlab.com/gitlab-org/gitlab/workhorse/internal/git"
"gitlab.com/gitlab-org/gitlab/workhorse/internal/helper"
"gitlab.com/gitlab-org/gitlab/workhorse/internal/imageresizer"
proxypkg "gitlab.com/gitlab-org/gitlab/workhorse/internal/proxy"
"gitlab.com/gitlab-org/gitlab/workhorse/internal/queueing"
"gitlab.com/gitlab-org/gitlab/workhorse/internal/secret"
"gitlab.com/gitlab-org/gitlab/workhorse/internal/senddata"
"gitlab.com/gitlab-org/gitlab/workhorse/internal/sendfile"
"gitlab.com/gitlab-org/gitlab/workhorse/internal/sendurl"
"gitlab.com/gitlab-org/gitlab/workhorse/internal/staticpages"
"gitlab.com/gitlab-org/gitlab/workhorse/internal/upload"
2021-02-22 17:27:13 +05:30
)
type matcherFunc func(*http.Request) bool
type routeEntry struct {
method string
regex *regexp.Regexp
handler http.Handler
matchers []matcherFunc
}
type routeOptions struct {
2022-01-26 12:08:38 +05:30
tracing bool
isGeoProxyRoute bool
matchers []matcherFunc
2021-02-22 17:27:13 +05:30
}
const (
apiPattern = `^/api/`
ciAPIPattern = `^/ci/api/`
2021-03-11 19:13:27 +05:30
gitProjectPattern = `^/.+\.git/`
2021-11-18 22:05:49 +05:30
geoGitProjectPattern = `^/[^-].+\.git/` // Prevent matching routes like /-/push_from_secondary
2021-02-22 17:27:13 +05:30
projectPattern = `^/([^/]+/){1,}[^/]+/`
2022-10-11 01:57:18 +05:30
apiProjectPattern = apiPattern + `v4/projects/[^/]+` // API: Projects can be encoded via group%2Fsubgroup%2Fproject
2023-01-13 00:05:48 +05:30
apiGroupPattern = apiPattern + `v4/groups/[^/]+`
2021-12-11 22:18:48 +05:30
apiTopicPattern = apiPattern + `v4/topics`
2021-02-22 17:27:13 +05:30
snippetUploadPattern = `^/uploads/personal_snippet`
userUploadPattern = `^/uploads/user`
importPattern = `^/import/`
)
2021-03-05 16:19:46 +05:30
var (
// For legacy reasons, user uploads are stored in public/uploads. To
// prevent anybody who knows/guesses the URL of a user-uploaded file
// from downloading it we configure static.ServeExisting to treat files
// under public/uploads/ as if they do not exist.
staticExclude = []string{"/uploads/"}
)
2021-02-22 17:27:13 +05:30
func compileRegexp(regexpStr string) *regexp.Regexp {
if len(regexpStr) == 0 {
return nil
}
return regexp.MustCompile(regexpStr)
}
func withMatcher(f matcherFunc) func(*routeOptions) {
return func(options *routeOptions) {
options.matchers = append(options.matchers, f)
}
}
func withoutTracing() func(*routeOptions) {
return func(options *routeOptions) {
options.tracing = false
}
}
2022-01-26 12:08:38 +05:30
func withGeoProxy() func(*routeOptions) {
return func(options *routeOptions) {
options.isGeoProxyRoute = true
}
}
func (u *upstream) observabilityMiddlewares(handler http.Handler, method string, regexpStr string, opts *routeOptions) http.Handler {
2021-02-22 17:27:13 +05:30
handler = log.AccessLogger(
handler,
log.WithAccessLogger(u.accessLogger),
log.WithExtraFields(func(r *http.Request) log.Fields {
return log.Fields{
"route": regexpStr, // This field matches the `route` label in Prometheus metrics
}
}),
)
handler = instrumentRoute(handler, method, regexpStr) // Add prometheus metrics
2022-01-26 12:08:38 +05:30
if opts != nil && opts.isGeoProxyRoute {
handler = instrumentGeoProxyRoute(handler, method, regexpStr) // Add Geo prometheus metrics
}
2021-02-22 17:27:13 +05:30
return handler
}
func (u *upstream) route(method, regexpStr string, handler http.Handler, opts ...func(*routeOptions)) routeEntry {
// Instantiate a route with the defaults
options := routeOptions{
tracing: true,
}
for _, f := range opts {
f(&options)
}
2022-01-26 12:08:38 +05:30
handler = u.observabilityMiddlewares(handler, method, regexpStr, &options)
2021-02-22 17:27:13 +05:30
handler = denyWebsocket(handler) // Disallow websockets
if options.tracing {
// Add distributed tracing
handler = tracing.Handler(handler, tracing.WithRouteIdentifier(regexpStr))
}
return routeEntry{
method: method,
regex: compileRegexp(regexpStr),
handler: handler,
matchers: options.matchers,
}
}
func (u *upstream) wsRoute(regexpStr string, handler http.Handler, matchers ...matcherFunc) routeEntry {
method := "GET"
2022-01-26 12:08:38 +05:30
handler = u.observabilityMiddlewares(handler, method, regexpStr, nil)
2021-02-22 17:27:13 +05:30
return routeEntry{
method: method,
regex: compileRegexp(regexpStr),
handler: handler,
matchers: append(matchers, websocket.IsWebSocketUpgrade),
}
}
// Creates matcherFuncs for a particular content type.
func isContentType(contentType string) func(*http.Request) bool {
return func(r *http.Request) bool {
return helper.IsContentType(contentType, r.Header.Get("Content-Type"))
}
}
func (ro *routeEntry) isMatch(cleanedPath string, req *http.Request) bool {
if ro.method != "" && req.Method != ro.method {
return false
}
if ro.regex != nil && !ro.regex.MatchString(cleanedPath) {
return false
}
ok := true
for _, matcher := range ro.matchers {
ok = matcher(req)
if !ok {
break
}
}
return ok
}
2021-11-18 22:05:49 +05:30
func buildProxy(backend *url.URL, version string, rt http.RoundTripper, cfg config.Config, dependencyProxyInjector *dependencyproxy.Injector) http.Handler {
2021-02-22 17:27:13 +05:30
proxier := proxypkg.NewProxy(backend, version, rt)
return senddata.SendData(
sendfile.SendFile(apipkg.Block(proxier)),
git.SendArchive,
git.SendBlob,
git.SendDiff,
git.SendPatch,
git.SendSnapshot,
artifacts.SendEntry,
sendurl.SendURL,
imageresizer.NewResizer(cfg),
2021-11-18 22:05:49 +05:30
dependencyProxyInjector,
2021-02-22 17:27:13 +05:30
)
}
// Routing table
// We match against URI not containing the relativeUrlRoot:
// see upstream.ServeHTTP
2021-03-05 16:19:46 +05:30
func configureRoutes(u *upstream) {
2021-09-30 23:02:18 +05:30
api := u.APIClient
2021-03-05 16:19:46 +05:30
static := &staticpages.Static{DocumentRoot: u.DocumentRoot, Exclude: staticExclude}
2021-11-18 22:05:49 +05:30
dependencyProxyInjector := dependencyproxy.NewInjector()
proxy := buildProxy(u.Backend, u.Version, u.RoundTripper, u.Config, dependencyProxyInjector)
2021-02-22 17:27:13 +05:30
cableProxy := proxypkg.NewProxy(u.CableBackend, u.Version, u.CableRoundTripper)
assetsNotFoundHandler := NotFoundUnless(u.DevelopmentMode, proxy)
if u.AltDocumentRoot != "" {
2021-03-05 16:19:46 +05:30
altStatic := &staticpages.Static{DocumentRoot: u.AltDocumentRoot, Exclude: staticExclude}
2021-02-22 17:27:13 +05:30
assetsNotFoundHandler = altStatic.ServeExisting(
u.URLPrefix,
staticpages.CacheExpireMax,
NotFoundUnless(u.DevelopmentMode, proxy),
)
}
signingTripper := secret.NewRoundTripper(u.RoundTripper, u.Version)
2021-11-18 22:05:49 +05:30
signingProxy := buildProxy(u.Backend, u.Version, signingTripper, u.Config, dependencyProxyInjector)
2021-02-22 17:27:13 +05:30
2022-07-16 23:28:13 +05:30
preparer := upload.NewObjectStoragePreparer(u.Config)
requestBodyUploader := upload.RequestBody(api, signingProxy, preparer)
mimeMultipartUploader := upload.Multipart(api, signingProxy, preparer)
2022-08-13 15:12:31 +05:30
tempfileMultipartProxy := upload.FixedPreAuthMultipart(api, proxy, preparer)
2022-11-25 23:54:43 +05:30
ciAPIProxyQueue := queueing.QueueRequests("ci_api_job_requests", tempfileMultipartProxy, u.APILimit, u.APIQueueLimit, u.APIQueueTimeout, prometheus.DefaultRegisterer)
2022-10-11 01:57:18 +05:30
ciAPILongPolling := builds.RegisterHandler(ciAPIProxyQueue, u.watchKeyHandler, u.APICILongPollingDuration)
2021-02-22 17:27:13 +05:30
2022-07-16 23:28:13 +05:30
dependencyProxyInjector.SetUploadHandler(requestBodyUploader)
2021-11-18 22:05:49 +05:30
2021-02-22 17:27:13 +05:30
// Serve static files or forward the requests
defaultUpstream := static.ServeExisting(
u.URLPrefix,
staticpages.CacheDisabled,
2022-04-04 11:22:00 +05:30
static.DeployPage(static.ErrorPagesUnless(u.DevelopmentMode, staticpages.ErrorFormatHTML, tempfileMultipartProxy)),
2021-02-22 17:27:13 +05:30
)
probeUpstream := static.ErrorPagesUnless(u.DevelopmentMode, staticpages.ErrorFormatJSON, proxy)
healthUpstream := static.ErrorPagesUnless(u.DevelopmentMode, staticpages.ErrorFormatText, proxy)
u.Routes = []routeEntry{
// Git Clone
u.route("GET", gitProjectPattern+`info/refs\z`, git.GetInfoRefsHandler(api)),
u.route("POST", gitProjectPattern+`git-upload-pack\z`, contentEncodingHandler(git.UploadPack(api)), withMatcher(isContentType("application/x-git-upload-pack-request"))),
u.route("POST", gitProjectPattern+`git-receive-pack\z`, contentEncodingHandler(git.ReceivePack(api)), withMatcher(isContentType("application/x-git-receive-pack-request"))),
2022-07-16 23:28:13 +05:30
u.route("PUT", gitProjectPattern+`gitlab-lfs/objects/([0-9a-f]{64})/([0-9]+)\z`, requestBodyUploader, withMatcher(isContentType("application/octet-stream"))),
2021-02-22 17:27:13 +05:30
// CI Artifacts
2022-07-16 23:28:13 +05:30
u.route("POST", apiPattern+`v4/jobs/[0-9]+/artifacts\z`, contentEncodingHandler(upload.Artifacts(api, signingProxy, preparer))),
u.route("POST", ciAPIPattern+`v1/builds/[0-9]+/artifacts\z`, contentEncodingHandler(upload.Artifacts(api, signingProxy, preparer))),
2021-02-22 17:27:13 +05:30
// ActionCable websocket
u.wsRoute(`^/-/cable\z`, cableProxy),
// Terminal websocket
u.wsRoute(projectPattern+`-/environments/[0-9]+/terminal.ws\z`, channel.Handler(api)),
u.wsRoute(projectPattern+`-/jobs/[0-9]+/terminal.ws\z`, channel.Handler(api)),
// Proxy Job Services
u.wsRoute(projectPattern+`-/jobs/[0-9]+/proxy.ws\z`, channel.Handler(api)),
// Long poll and limit capacity given to jobs/request and builds/register.json
u.route("", apiPattern+`v4/jobs/request\z`, ciAPILongPolling),
u.route("", ciAPIPattern+`v1/builds/register.json\z`, ciAPILongPolling),
2021-04-29 21:17:54 +05:30
// Not all API endpoints support encoded project IDs
// (e.g. `group%2Fproject`), but for the sake of consistency we
// use the apiProjectPattern regex throughout. API endpoints
// that do not support this will return 400 regardless of
// whether they are accelerated by Workhorse or not. See
// https://gitlab.com/gitlab-org/gitlab/-/merge_requests/56731.
2021-02-22 17:27:13 +05:30
// Maven Artifact Repository
2022-10-11 01:57:18 +05:30
u.route("PUT", apiProjectPattern+`/packages/maven/`, requestBodyUploader),
2021-02-22 17:27:13 +05:30
// Conan Artifact Repository
2022-07-16 23:28:13 +05:30
u.route("PUT", apiPattern+`v4/packages/conan/`, requestBodyUploader),
2022-10-11 01:57:18 +05:30
u.route("PUT", apiProjectPattern+`/packages/conan/`, requestBodyUploader),
2021-02-22 17:27:13 +05:30
// Generic Packages Repository
2022-10-11 01:57:18 +05:30
u.route("PUT", apiProjectPattern+`/packages/generic/`, requestBodyUploader),
2021-02-22 17:27:13 +05:30
// NuGet Artifact Repository
2022-10-11 01:57:18 +05:30
u.route("PUT", apiProjectPattern+`/packages/nuget/`, mimeMultipartUploader),
2021-02-22 17:27:13 +05:30
// PyPI Artifact Repository
2022-10-11 01:57:18 +05:30
u.route("POST", apiProjectPattern+`/packages/pypi`, mimeMultipartUploader),
2021-02-22 17:27:13 +05:30
// Debian Artifact Repository
2022-10-11 01:57:18 +05:30
u.route("PUT", apiProjectPattern+`/packages/debian/`, requestBodyUploader),
// RPM Artifact Repository
u.route("POST", apiProjectPattern+`/packages/rpm/`, requestBodyUploader),
2021-03-11 19:13:27 +05:30
// Gem Artifact Repository
2022-10-11 01:57:18 +05:30
u.route("POST", apiProjectPattern+`/packages/rubygems/`, requestBodyUploader),
2021-02-22 17:27:13 +05:30
2021-06-08 01:23:25 +05:30
// Terraform Module Package Repository
2022-10-11 01:57:18 +05:30
u.route("PUT", apiProjectPattern+`/packages/terraform/modules/`, requestBodyUploader),
2021-06-08 01:23:25 +05:30
// Helm Artifact Repository
2022-10-11 01:57:18 +05:30
u.route("POST", apiProjectPattern+`/packages/helm/api/[^/]+/charts\z`, mimeMultipartUploader),
2021-06-08 01:23:25 +05:30
2021-02-22 17:27:13 +05:30
// We are porting API to disk acceleration
// we need to declare each routes until we have fixed all the routes on the rails codebase.
// Overall status can be seen at https://gitlab.com/groups/gitlab-org/-/epics/1802#current-status
2022-10-11 01:57:18 +05:30
u.route("POST", apiProjectPattern+`/wikis/attachments\z`, tempfileMultipartProxy),
2023-01-13 00:05:48 +05:30
u.route("POST", apiGroupPattern+`/wikis/attachments\z`, tempfileMultipartProxy),
2022-04-04 11:22:00 +05:30
u.route("POST", apiPattern+`graphql\z`, tempfileMultipartProxy),
u.route("POST", apiTopicPattern, tempfileMultipartProxy),
u.route("PUT", apiTopicPattern, tempfileMultipartProxy),
2022-07-16 23:28:13 +05:30
u.route("POST", apiPattern+`v4/groups/import`, mimeMultipartUploader),
u.route("POST", apiPattern+`v4/projects/import`, mimeMultipartUploader),
2021-02-22 17:27:13 +05:30
// Project Import via UI upload acceleration
2022-07-16 23:28:13 +05:30
u.route("POST", importPattern+`gitlab_project`, mimeMultipartUploader),
2021-02-22 17:27:13 +05:30
// Group Import via UI upload acceleration
2022-07-16 23:28:13 +05:30
u.route("POST", importPattern+`gitlab_group`, mimeMultipartUploader),
2021-02-22 17:27:13 +05:30
2022-05-07 20:08:51 +05:30
// Issuable Metric image upload
2022-10-11 01:57:18 +05:30
u.route("POST", apiProjectPattern+`/issues/[0-9]+/metric_images\z`, mimeMultipartUploader),
2021-02-22 17:27:13 +05:30
2022-05-07 20:08:51 +05:30
// Alert Metric image upload
2022-10-11 01:57:18 +05:30
u.route("POST", apiProjectPattern+`/alert_management_alerts/[0-9]+/metric_images\z`, mimeMultipartUploader),
2022-05-07 20:08:51 +05:30
2021-02-22 17:27:13 +05:30
// Requirements Import via UI upload acceleration
2022-07-16 23:28:13 +05:30
u.route("POST", projectPattern+`requirements_management/requirements/import_csv`, mimeMultipartUploader),
2021-02-22 17:27:13 +05:30
2023-06-20 00:43:36 +05:30
// Work items Import via UI upload acceleration
u.route("POST", projectPattern+`work_items/import_csv`, mimeMultipartUploader),
2021-04-29 21:17:54 +05:30
// Uploads via API
2022-10-11 01:57:18 +05:30
u.route("POST", apiProjectPattern+`/uploads\z`, mimeMultipartUploader),
// Project Avatar
u.route("POST", apiPattern+`v4/projects\z`, tempfileMultipartProxy),
u.route("PUT", apiProjectPattern+`\z`, tempfileMultipartProxy),
// Group Avatar
u.route("POST", apiPattern+`v4/groups\z`, tempfileMultipartProxy),
u.route("PUT", apiPattern+`v4/groups/[^/]+\z`, tempfileMultipartProxy),
// User Avatar
u.route("POST", apiPattern+`v4/users\z`, tempfileMultipartProxy),
u.route("PUT", apiPattern+`v4/users/[0-9]+\z`, tempfileMultipartProxy),
2021-04-29 21:17:54 +05:30
2021-02-22 17:27:13 +05:30
// Explicitly proxy API requests
u.route("", apiPattern, proxy),
u.route("", ciAPIPattern, proxy),
// Serve assets
u.route(
"", `^/assets/`,
static.ServeExisting(
u.URLPrefix,
staticpages.CacheExpireMax,
assetsNotFoundHandler,
),
withoutTracing(), // Tracing on assets is very noisy
),
// Uploads
2022-07-16 23:28:13 +05:30
u.route("POST", projectPattern+`uploads\z`, mimeMultipartUploader),
u.route("POST", snippetUploadPattern, mimeMultipartUploader),
u.route("POST", userUploadPattern, mimeMultipartUploader),
2021-02-22 17:27:13 +05:30
// health checks don't intercept errors and go straight to rails
// TODO: We should probably not return a HTML deploy page?
2021-10-27 15:23:28 +05:30
// https://gitlab.com/gitlab-org/gitlab/-/issues/336326
2021-02-22 17:27:13 +05:30
u.route("", "^/-/(readiness|liveness)$", static.DeployPage(probeUpstream)),
u.route("", "^/-/health$", static.DeployPage(healthUpstream)),
// This route lets us filter out health checks from our metrics.
u.route("", "^/-/", defaultUpstream),
u.route("", "", defaultUpstream),
}
2021-10-27 15:23:28 +05:30
// Routes which should actually be served locally by a Geo Proxy. If none
// matches, then then proxy the request.
u.geoLocalRoutes = []routeEntry{
// Git and LFS requests
//
// Note that Geo already redirects pushes, with special terminal output.
// Note that excessive secondary lag can cause unexpected behavior since
// pulls are performed against a different source of truth. Ideally, we'd
// proxy/redirect pulls as well, when the secondary is not up-to-date.
//
2021-11-18 22:05:49 +05:30
u.route("GET", geoGitProjectPattern+`info/refs\z`, git.GetInfoRefsHandler(api)),
u.route("POST", geoGitProjectPattern+`git-upload-pack\z`, contentEncodingHandler(git.UploadPack(api)), withMatcher(isContentType("application/x-git-upload-pack-request"))),
u.route("GET", geoGitProjectPattern+`gitlab-lfs/objects/([0-9a-f]{64})\z`, defaultUpstream),
2021-10-27 15:23:28 +05:30
// Serve health checks from this Geo secondary
u.route("", "^/-/(readiness|liveness)$", static.DeployPage(probeUpstream)),
u.route("", "^/-/health$", static.DeployPage(healthUpstream)),
u.route("", "^/-/metrics$", defaultUpstream),
// Authentication routes
2021-11-11 11:23:49 +05:30
u.route("", "^/users/auth/geo/(sign_in|sign_out)$", defaultUpstream),
2021-10-27 15:23:28 +05:30
u.route("", "^/oauth/geo/(auth|callback|logout)$", defaultUpstream),
// Admin Area > Geo routes
2022-05-07 20:08:51 +05:30
u.route("", "^/admin/geo/replication/projects", defaultUpstream),
u.route("", "^/admin/geo/replication/designs", defaultUpstream),
2021-10-27 15:23:28 +05:30
// Geo API routes
u.route("", "^/api/v4/geo_replication", defaultUpstream),
2021-12-11 22:18:48 +05:30
u.route("", "^/api/v4/geo/proxy_git_ssh", defaultUpstream),
2022-04-04 11:22:00 +05:30
u.route("", "^/api/v4/geo/graphql", defaultUpstream),
2021-12-11 22:18:48 +05:30
// Internal API routes
u.route("", "^/api/v4/internal", defaultUpstream),
2021-10-27 15:23:28 +05:30
2022-05-07 20:08:51 +05:30
u.route(
"", `^/assets/`,
static.ServeExisting(
u.URLPrefix,
staticpages.CacheExpireMax,
assetsNotFoundHandler,
),
withoutTracing(), // Tracing on assets is very noisy
),
2021-10-27 15:23:28 +05:30
// Don't define a catch-all route. If a route does not match, then we know
// the request should be proxied.
}
2021-02-22 17:27:13 +05:30
}
func denyWebsocket(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if websocket.IsWebSocketUpgrade(r) {
2023-03-04 22:38:38 +05:30
httpError(w, r, "websocket upgrade not allowed", http.StatusBadRequest)
2021-02-22 17:27:13 +05:30
return
}
next.ServeHTTP(w, r)
})
}