summaryrefslogtreecommitdiff
path: root/workhorse/internal/upstream/upstream.go
blob: c0678b1cb3e3c68e3426e810720b1b05bcc35a4d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
/*
The upstream type implements http.Handler.

In this file we handle request routing and interaction with the authBackend.
*/

package upstream

import (
	"fmt"
	"os"
	"sync"
	"time"

	"net/http"
	"net/url"
	"strings"

	"github.com/sirupsen/logrus"

	"gitlab.com/gitlab-org/labkit/correlation"

	apipkg "gitlab.com/gitlab-org/gitlab/workhorse/internal/api"
	"gitlab.com/gitlab-org/gitlab/workhorse/internal/config"
	"gitlab.com/gitlab-org/gitlab/workhorse/internal/helper"
	"gitlab.com/gitlab-org/gitlab/workhorse/internal/log"
	proxypkg "gitlab.com/gitlab-org/gitlab/workhorse/internal/proxy"
	"gitlab.com/gitlab-org/gitlab/workhorse/internal/rejectmethods"
	"gitlab.com/gitlab-org/gitlab/workhorse/internal/upload"
	"gitlab.com/gitlab-org/gitlab/workhorse/internal/upstream/roundtripper"
	"gitlab.com/gitlab-org/gitlab/workhorse/internal/urlprefix"
)

var (
	DefaultBackend         = helper.URLMustParse("http://localhost:8080")
	requestHeaderBlacklist = []string{
		upload.RewrittenFieldsHeader,
	}
	geoProxyApiPollingInterval = 10 * time.Second
	geoProxyWorkhorseHeaders   = map[string]string{"Gitlab-Workhorse-Geo-Proxy": "1"}
)

type upstream struct {
	config.Config
	URLPrefix             urlprefix.Prefix
	Routes                []routeEntry
	RoundTripper          http.RoundTripper
	CableRoundTripper     http.RoundTripper
	APIClient             *apipkg.API
	geoProxyBackend       *url.URL
	geoLocalRoutes        []routeEntry
	geoProxyCableRoute    routeEntry
	geoProxyRoute         routeEntry
	geoProxyPollSleep     func(time.Duration)
	accessLogger          *logrus.Logger
	enableGeoProxyFeature bool
	mu                    sync.RWMutex
}

func NewUpstream(cfg config.Config, accessLogger *logrus.Logger) http.Handler {
	return newUpstream(cfg, accessLogger, configureRoutes)
}

func newUpstream(cfg config.Config, accessLogger *logrus.Logger, routesCallback func(*upstream)) http.Handler {
	up := upstream{
		Config:       cfg,
		accessLogger: accessLogger,
		// Kind of a feature flag. See https://gitlab.com/groups/gitlab-org/-/epics/5914#note_564974130
		enableGeoProxyFeature: os.Getenv("GEO_SECONDARY_PROXY") != "0",
		geoProxyBackend:       &url.URL{},
	}
	if up.geoProxyPollSleep == nil {
		up.geoProxyPollSleep = time.Sleep
	}
	if up.Backend == nil {
		up.Backend = DefaultBackend
	}
	if up.CableBackend == nil {
		up.CableBackend = up.Backend
	}
	if up.CableSocket == "" {
		up.CableSocket = up.Socket
	}
	up.RoundTripper = roundtripper.NewBackendRoundTripper(up.Backend, up.Socket, up.ProxyHeadersTimeout, cfg.DevelopmentMode)
	up.CableRoundTripper = roundtripper.NewBackendRoundTripper(up.CableBackend, up.CableSocket, up.ProxyHeadersTimeout, cfg.DevelopmentMode)
	up.configureURLPrefix()
	up.APIClient = apipkg.NewAPI(
		up.Backend,
		up.Version,
		up.RoundTripper,
	)

	routesCallback(&up)

	if up.enableGeoProxyFeature {
		go up.pollGeoProxyAPI()
	}

	var correlationOpts []correlation.InboundHandlerOption
	if cfg.PropagateCorrelationID {
		correlationOpts = append(correlationOpts, correlation.WithPropagation())
	}
	if cfg.TrustedCIDRsForPropagation != nil {
		correlationOpts = append(correlationOpts, correlation.WithCIDRsTrustedForPropagation(cfg.TrustedCIDRsForPropagation))
	}
	if cfg.TrustedCIDRsForXForwardedFor != nil {
		correlationOpts = append(correlationOpts, correlation.WithCIDRsTrustedForXForwardedFor(cfg.TrustedCIDRsForXForwardedFor))
	}

	handler := correlation.InjectCorrelationID(&up, correlationOpts...)
	// TODO: move to LabKit https://gitlab.com/gitlab-org/gitlab/-/issues/324823
	handler = rejectmethods.NewMiddleware(handler)
	return handler
}

func (u *upstream) configureURLPrefix() {
	relativeURLRoot := u.Backend.Path
	if !strings.HasSuffix(relativeURLRoot, "/") {
		relativeURLRoot += "/"
	}
	u.URLPrefix = urlprefix.Prefix(relativeURLRoot)
}

func (u *upstream) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	helper.FixRemoteAddr(r)

	helper.DisableResponseBuffering(w)

	// Drop RequestURI == "*" (FIXME: why?)
	if r.RequestURI == "*" {
		helper.HTTPError(w, r, "Connection upgrade not allowed", http.StatusBadRequest)
		return
	}

	// Disallow connect
	if r.Method == "CONNECT" {
		helper.HTTPError(w, r, "CONNECT not allowed", http.StatusBadRequest)
		return
	}

	// Check URL Root
	URIPath := urlprefix.CleanURIPath(r.URL.EscapedPath())
	prefix := u.URLPrefix
	if !prefix.Match(URIPath) {
		helper.HTTPError(w, r, fmt.Sprintf("Not found %q", URIPath), http.StatusNotFound)
		return
	}

	cleanedPath := prefix.Strip(URIPath)

	route := u.findRoute(cleanedPath, r)

	if route == nil {
		// The protocol spec in git/Documentation/technical/http-protocol.txt
		// says we must return 403 if no matching service is found.
		helper.HTTPError(w, r, "Forbidden", http.StatusForbidden)
		return
	}

	for _, h := range requestHeaderBlacklist {
		r.Header.Del(h)
	}

	route.handler.ServeHTTP(w, r)
}

func (u *upstream) findRoute(cleanedPath string, r *http.Request) *routeEntry {
	if u.enableGeoProxyFeature {
		if route := u.findGeoProxyRoute(cleanedPath, r); route != nil {
			return route
		}
	}

	for _, ro := range u.Routes {
		if ro.isMatch(cleanedPath, r) {
			return &ro
		}
	}

	return nil
}

func (u *upstream) findGeoProxyRoute(cleanedPath string, r *http.Request) *routeEntry {
	u.mu.RLock()
	defer u.mu.RUnlock()

	if u.geoProxyBackend.String() == "" {
		log.WithRequest(r).Debug("Geo Proxy: Not a Geo proxy")
		return nil
	}

	// Some routes are safe to serve from this GitLab instance
	for _, ro := range u.geoLocalRoutes {
		if ro.isMatch(cleanedPath, r) {
			log.WithRequest(r).Debug("Geo Proxy: Handle this request locally")
			return &ro
		}
	}

	log.WithRequest(r).WithFields(log.Fields{"geoProxyBackend": u.geoProxyBackend}).Debug("Geo Proxy: Forward this request")

	if cleanedPath == "/-/cable" {
		return &u.geoProxyCableRoute
	}

	return &u.geoProxyRoute
}

func (u *upstream) pollGeoProxyAPI() {
	for {
		u.callGeoProxyAPI()
		u.geoProxyPollSleep(geoProxyApiPollingInterval)
	}
}

// Calls /api/v4/geo/proxy and sets up routes
func (u *upstream) callGeoProxyAPI() {
	geoProxyURL, err := u.APIClient.GetGeoProxyURL()
	if err != nil {
		log.WithError(err).WithFields(log.Fields{"geoProxyBackend": u.geoProxyBackend}).Error("Geo Proxy: Unable to determine Geo Proxy URL. Fallback on cached value.")
		return
	}

	if u.geoProxyBackend.String() != geoProxyURL.String() {
		log.WithFields(log.Fields{"oldGeoProxyURL": u.geoProxyBackend, "newGeoProxyURL": geoProxyURL}).Info("Geo Proxy: URL changed")
		u.updateGeoProxyFields(geoProxyURL)
	}
}

func (u *upstream) updateGeoProxyFields(geoProxyURL *url.URL) {
	u.mu.Lock()
	defer u.mu.Unlock()

	u.geoProxyBackend = geoProxyURL

	if u.geoProxyBackend.String() == "" {
		return
	}

	geoProxyRoundTripper := roundtripper.NewBackendRoundTripper(u.geoProxyBackend, "", u.ProxyHeadersTimeout, u.DevelopmentMode)
	geoProxyUpstream := proxypkg.NewProxy(
		u.geoProxyBackend,
		u.Version,
		geoProxyRoundTripper,
		proxypkg.WithCustomHeaders(geoProxyWorkhorseHeaders),
	)
	u.geoProxyCableRoute = u.wsRoute(`^/-/cable\z`, geoProxyUpstream)
	u.geoProxyRoute = u.route("", "", geoProxyUpstream, withGeoProxy())
}