-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmiddlewares.go
More file actions
262 lines (246 loc) · 10.7 KB
/
middlewares.go
File metadata and controls
262 lines (246 loc) · 10.7 KB
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
250
251
252
253
254
255
256
257
258
259
260
261
262
package revproxy
import (
"fmt"
"log/slog"
"net/http"
"net/url"
"regexp"
"strings"
"github.com/SwissDataScienceCenter/renku-gateway/internal/sessions"
"github.com/SwissDataScienceCenter/renku-gateway/internal/utils"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
// noCookies middleware removes all cookies from a request
func noCookies(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
c.Request().Header.Set("cookie", "")
return next(c)
}
}
// kgProjectsGraphStatusPathRewrite middleware
var kgProjectsGraphRewrites echo.MiddlewareFunc = middleware.RewriteWithConfig(middleware.RewriteConfig{
RegexRules: map[*regexp.Regexp]string{
regexp.MustCompile("^/api/projects/(.*?)/graph/webhooks(.*)"): "/projects/$1/webhooks$2",
regexp.MustCompile("^/api/projects/(.*?)/graph/status(.*)"): "/projects/$1/events/status$2",
},
})
// regexRewrite is a small helper function to produce a path rewrite middleware
func regexRewrite(match, replace string) echo.MiddlewareFunc {
config := middleware.RewriteConfig{
RegexRules: map[*regexp.Regexp]string{
regexp.MustCompile(match): replace,
},
}
return middleware.RewriteWithConfig(config)
}
// stripPrefix middleware removes a prefix from a request's path
func stripPrefix(prefix string) echo.MiddlewareFunc {
return middleware.RewriteWithConfig(middleware.RewriteConfig{
RegexRules: map[*regexp.Regexp]string{
regexp.MustCompile(fmt.Sprintf("^%s/(.+)", prefix)): "/$1",
regexp.MustCompile(fmt.Sprintf("^%s$", prefix)): "/",
},
})
}
// setHost middleware sets the host field and header of a request. Needed to make
// proxying to external services work. Withtout this middleware proxying to
// anything outside of the cluster fails.
func setHost(host string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
c.Request().Host = host
return next(c)
}
}
}
// ensureSession middleware makes sure a session exists by creating a new one if none is found.
func ensureSession(sessions *sessions.SessionStore) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
session, err := sessions.Get(c)
if err != nil || session.ID == "" {
_, err = sessions.Create(c)
}
if err != nil {
return err
}
return next(c)
}
}
}
// checkCoreServiceMetadataVersion checks if the requested path contains a valid
// and available metadata version and if not returns a 404, if the metadata version is
// available the request is let through
func checkCoreServiceMetadataVersion(coreSvcPaths []string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
requestedPath := c.Request().URL.Path
match, err := regexp.MatchString(`^/api/renku/[0-9]+/.*$|^/api/renku/[0-9]+$`, requestedPath)
if err != nil {
return err
}
if !match {
return next(c)
}
for _, path := range coreSvcPaths {
if strings.HasPrefix(requestedPath, path) && path != "/api/renku" {
return next(c)
}
}
return echo.ErrNotFound
}
}
}
// gitlabRedirect redirects from the old-style internal gitlab url to an external Gitlab instance
func gitlabRedirect(newGitlabHost string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
oldURL := c.Request().URL
newURL := *oldURL
newURL.Host = newGitlabHost
newURL.Path = strings.TrimPrefix(newURL.Path, "/gitlab")
newURL.RawPath = strings.TrimPrefix(newURL.RawPath, "/gitlab")
return c.Redirect(http.StatusMovedPermanently, newURL.String())
}
}
}
// uiServerUpstreamInternalGitlabLocation is used to set headers used by the UI server to route 1 specific request for
// Gitlab, when a Renku-bundled Gitlab is used. The UI server needs to cache or further process the results from
// this reqest, therefore it is not possible to fully skip the UI server.
func uiServerUpstreamInternalGitlabLocation(host string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
upstreamPath := *c.Request().URL
upstreamPath.Host = ""
upstreamPath.Scheme = ""
upstreamPathStr := strings.TrimPrefix(upstreamPath.String(), "/ui-server/api")
c.Request().Header.Set("Renku-Gateway-Upstream-Path", "/gitlab/api/v4"+upstreamPathStr)
c.Request().Header.Set("Renku-Gateway-Upstream-Host", host)
return next(c)
}
}
}
// uiServerUpstreamExternalGitlabLocation is used to set headers used by the UI server to route 1 specific request for
// Gitlab, when an external Gitlab is used with Renku. The UI server needs to cache or further process the results from
// this reqest, therefore it is not possible to fully skip the UI server.
func uiServerUpstreamExternalGitlabLocation(host string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
upstreamPath := *c.Request().URL
upstreamPath.Host = ""
upstreamPath.Scheme = ""
upstreamPathStr := strings.TrimPrefix(upstreamPath.String(), "/ui-server/api")
c.Request().Header.Set("Renku-Gateway-Upstream-Path", "/api/v4"+upstreamPathStr)
c.Request().Header.Set("Renku-Gateway-Upstream-Host", host)
return next(c)
}
}
}
// uiServerUpstreamCoreLocation sets headers used by the UI server to determine where to route a specific Core service
// request. Allows us to position the UI server behind the gateway and still have the gateway "tell" the UI server
// where to route this Core service request. Used for only 1 specific endpoint that the UI server needs to cache so
// skipping the UI server on this endpoint is not possible.
func uiServerUpstreamCoreLocation(host string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
upstreamPath := *c.Request().URL
upstreamPath.Host = ""
upstreamPath.Scheme = ""
upstreamPathStr := strings.TrimPrefix(upstreamPath.String(), "/ui-server")
c.Request().Header.Set("Renku-Gateway-Upstream-Path", upstreamPathStr)
c.Request().Header.Set("Renku-Gateway-Upstream-Host", host)
return next(c)
}
}
}
// uiServerUpstreamKgLocation sets headers used by the UI server to determine where to route a specific KG request.
// Allows us to position the UI server behind the gateway and still have the gateway "tell" the UI server
// where to route this KG request. Used for only 1 specific endpoint on the KG that the UI server needs to cache
// so skipping the UI server on this endpoint is not possible.
func uiServerUpstreamKgLocation(host string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
upstreamPath := *c.Request().URL
upstreamPath.Host = ""
upstreamPath.Scheme = ""
upstreamPathStr := strings.TrimPrefix(upstreamPath.String(), "/ui-server/api/kg")
c.Request().Header.Set("Renku-Gateway-Upstream-Path", "/knowledge-graph"+upstreamPathStr)
c.Request().Header.Set("Renku-Gateway-Upstream-Host", host)
return next(c)
}
}
}
// uiServerPathRewrite changes the incoming requests so that the UI server is used (as a second proxy) only for very
// specific endpoints (when absolutely necessary). For all other cases the gateway routes directly to the required
// Renku component and injects the proper credentials required by the specific component.
func UiServerPathRewrite() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
path := c.Request().URL.Path
// For several endpoints below the gateway still cannot skip the UI server.
if strings.HasPrefix(path, "/ui-server/api/allows-iframe") ||
strings.HasPrefix(path, "/ui-server/api/projects") ||
strings.HasPrefix(path, "/ui-server/api/renku/cache.files_upload") ||
strings.HasPrefix(path, "/ui-server/api/kg/entities") ||
strings.HasPrefix(path, "/ui-server/api/last-projects") ||
strings.HasPrefix(path, "/ui-server/api/last-searches") {
return next(c)
}
// Rewrite for /ui-server/auth -> /api/auth.
if strings.HasPrefix(path, "/ui-server/auth") {
originalURL := c.Request().URL.String()
c.Request().URL.Path = "/api" + strings.TrimPrefix(path, "/ui-server")
c.Request().URL.RawPath = "/api" + strings.TrimPrefix(c.Request().URL.RawPath, "/ui-server")
newUrl, err := url.Parse(c.Request().URL.String())
if err != nil {
return err
}
c.Request().URL = newUrl
c.Request().RequestURI = newUrl.String()
slog.Debug("PATH REWRITE", "message", "matched /ui-server/auth", "originalURL", originalURL, "newUrl", newUrl.String(), "requestID", utils.GetRequestID(c))
}
// For all other endpoints the gateway will fully bypass the UI server routing things directly to the proper
// Renku component.
if strings.HasPrefix(path, "/ui-server/api") {
originalURL := c.Request().URL.String()
c.Request().URL.Path = strings.TrimPrefix(path, "/ui-server")
c.Request().URL.RawPath = strings.TrimPrefix(c.Request().URL.RawPath, "/ui-server")
newUrl, err := url.Parse(c.Request().URL.String())
if err != nil {
return err
}
c.Request().URL = newUrl
c.Request().RequestURI = newUrl.String()
slog.Debug("PATH REWRITE", "message", "matched /ui-server/api", "originalURL", originalURL, "newUrl", newUrl.String(), "requestID", utils.GetRequestID(c))
}
return next(c)
}
}
}
// Injects the sessionID as an identifier for an anonymous user. It will only do so if there are no
// headers already injected for the keycloak tokens. Therefore this should always run in the middleware
// chain after all other token injection middelwares have run.
func notebooksAnonymousID(sessions *sessions.SessionStore) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
// The request is not anonymous, continue
if c.Request().Header.Get("Renku-Auth-Access-Token") != "" || c.Request().Header.Get("Renku-Auth-Id-Token") != "" || c.Request().Header.Get("Renku-Auth-Refresh-Token") != "" {
return next(c)
}
// Use the session ID as the anonymous ID
session, err := sessions.Get(c)
if err != nil || session.ID == "" {
session, err = sessions.Create(c)
}
if err != nil {
return err
}
// NOTE: The anonymous session ID must start with a letter, otherwise when we use it to create sessions in k8s
// things fail because a label value must start with a letter. That is why we add `anon-` here to the value.
// Note that valid values for a label in k8s are [a-zA-Z0-9], also -_. and it must start with a letter.
c.Request().Header.Set("Renku-Auth-Anon-Id", "anon-"+session.ID)
return next(c)
}
}
}