-
Notifications
You must be signed in to change notification settings - Fork 0
/
be_router.go
249 lines (221 loc) · 8.55 KB
/
be_router.go
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
// Copyright (c) 2022 The Go-Enjin Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package be
import (
"net/http"
"net/http/pprof"
"path/filepath"
"sort"
"strings"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/urfave/cli/v2"
"github.com/go-corelibs/maps"
clPath "github.com/go-corelibs/path"
clStrings "github.com/go-corelibs/strings"
"github.com/go-enjin/be/pkg/feature"
"github.com/go-enjin/be/pkg/log"
"github.com/go-enjin/be/pkg/net/headers"
"github.com/go-enjin/be/pkg/request"
"github.com/go-enjin/be/pkg/request/argv"
"github.com/go-enjin/be/pkg/signals"
)
func (e *Enjin) setupRouter(ctx *cli.Context, router *chi.Mux) (err error) {
e.Emit(signals.PreEnjinSetupRouter, feature.EnjinTag.String(), interface{}(e).(feature.Internals))
if e.debug {
if value := ctx.String("debug-pprof"); value != "" {
path := clPath.TrimSlash(filepath.Clean("/"+value)) + "/"
pathLen := len(path)
profiles := map[string]http.Handler{
"goroutine": pprof.Handler("goroutine"), // stack traces of all current goroutines
"heap": pprof.Handler("heap"), // a sampling of memory allocations of live objects
"allocs": pprof.Handler("allocs"), // a sampling of all past memory allocations
"threadcreate": pprof.Handler("threadcreate"), // stack traces that led to the creation of new OS threads
"block": pprof.Handler("block"), // stack traces that led to blocking on synchronization primitives
"mutex": pprof.Handler("mutex"), // stack traces of holders of contended mutexes
}
log.WarnF("including all pprof handlers: %s<goroutine|heap|allocs|threadcreate|block|mutex>", path)
router.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, path) {
before, _, _ := strings.Cut(r.URL.Path[pathLen:], "/")
if profile, ok := profiles[before]; ok {
profile.ServeHTTP(w, r)
return
}
}
next.ServeHTTP(w, r)
})
})
}
}
router.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r = request.Set(r,
request.KeyEnjinID, e.String(),
request.KeyHomePath, "/",
)
w.Header().Set("Server", e.ServerName())
next.ServeHTTP(w, r)
})
})
router.Use(middleware.RequestID)
// gzip compression for default compressible content types
router.Use(middleware.Compress(5))
router.Use(e.eb.fPanicHandler.PanicHandler)
router.Use(argv.Middleware)
if e.eb.hotReload {
log.DebugF("including hot-reload middleware")
router.Use(e.hotReloadMiddleware)
}
// request modifier features are expected to modify the request object
// in-place, before any further feature processing
if count := len(e.eb.fRequestModifiers); count > 0 {
var tags feature.Tags
for _, rm := range e.eb.fRequestModifiers {
tags = append(tags, rm.Tag())
}
log.DebugF("including %d request modifier middlewares: %+v", count, tags)
router.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
for _, rm := range e.eb.fRequestModifiers {
rm.ModifyRequest(w, r)
}
next.ServeHTTP(w, r)
})
})
}
// request rewriter features are expected to return a modified request
// object, potentially dropping data if requests are modified WithContext
// and not Clone
if count := len(e.eb.fRequestRewriters); count > 0 {
var tags feature.Tags
for _, rr := range e.eb.fRequestRewriters {
tags = append(tags, rr.Tag())
}
log.DebugF("including %d request rewriter middlewares: %+v", count, tags)
router.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
for _, rr := range e.eb.fRequestRewriters {
if modified := rr.RewriteRequest(w, r); modified != nil {
r = modified
}
}
next.ServeHTTP(w, r)
})
})
}
// logging after requests modified so proxy has a chance to populate ip
router.Use(middleware.Logger)
// these should be request modifiers instead of enjin middleware
router.Use(e.eb.fLocaleHandler.LocaleHandler)
router.Use(e.redirectionMiddleware)
router.Use(e.headersMiddleware)
// operational security measures
router.Use(e.domainsMiddleware)
router.Use(e.permissionsPolicy.PrepareRequestMiddleware)
router.Use(e.contentSecurityPolicy.PrepareRequestMiddleware)
router.Use(e.requestFiltersMiddleware)
// header policy modifier features do not block next.ServeHTTP calls and
// must happen before blocking middleware features (ones that may not call
// next.ServeHTTP having already served the response)
for _, ppm := range e.eb.fPermissionsPolicyModifiers {
log.DebugF("including %v modify permissions policy middleware", ppm.Tag())
router.Use(e.permissionsPolicy.ModifyPolicyMiddleware(ppm.ModifyPermissionsPolicy))
}
for _, cspm := range e.eb.fContentSecurityPolicyModifiers {
log.DebugF("including %v modify content security policy middleware", cspm.Tag())
router.Use(e.contentSecurityPolicy.ModifyPolicyMiddleware(cspm.ModifyContentSecurityPolicy))
}
for _, cspFnTag := range e.eb.cspModifierFnOrder {
log.DebugF("including %v modify content security policy func", cspFnTag)
router.Use(e.contentSecurityPolicy.ModifyPolicyMiddleware(e.eb.cspModifierFns[cspFnTag]))
}
// theme static files [blocking middleware]
if t, ee := e.GetTheme(); ee != nil {
log.WarnF("not including any theme middleware: %v", ee)
} else {
if t.StaticFS() != nil {
router.Use(t.Middleware)
}
if tp := t.GetParent(); tp != nil {
if tp.StaticFS() != nil {
router.Use(tp.Middleware)
}
}
}
router.Use(e.userAuthMiddleware)
// potentially blocking middleware features that do not require standard
// page rendering or data response facilities
for _, um := range e.eb.fUseMiddlewares {
log.DebugF("including %v use middleware", um.Tag())
if mw := um.Use(e); mw != nil {
router.Use(mw)
}
}
// header modifier features that happen after potentially blocking features
// that did not actually serve a response
for _, hm := range e.eb.fHeadersModifiers {
log.DebugF("including %v use-after modify headers middleware", hm.Tag())
router.Use(headers.ModifyAfterUseMiddleware(hm.ModifyHeaders))
}
// processor middleware features are potentially blocking
for _, proc := range e.eb.fProcessors {
log.DebugF("including %v processor middleware", proc.Tag())
router.Use(func(next http.Handler) http.Handler {
innerProc := proc // prevent outer scoped proc overwriting
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
innerProc.Process(e, next, w, r)
})
})
}
// route processor middleware features, in order of longest to shortest
sortedRoutes := maps.Keys(e.eb.processors)
sort.Sort(clStrings.SortByLength(sortedRoutes))
for _, route := range sortedRoutes {
log.DebugF("including enjin %v route processor middleware", route)
router.Use(func(next http.Handler) http.Handler {
innerRoute := route // prevent outer scoped route overwriting
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == innerRoute {
if e.eb.processors[innerRoute](e, w, r) {
return
}
}
next.ServeHTTP(w, r)
})
})
}
// middleware features have a final chance to apply enjin changes before
// error handling router changes are made
for _, am := range e.eb.fApplyMiddlewares {
log.DebugF("including %v apply middleware", am.Tag())
if err = am.Apply(e); err != nil {
return
}
}
// error handling router changes
router.NotFound(e.ServeNotFound)
router.MethodNotAllowed(e.Serve405)
// standard page processing catch-all-not-already-routed
if e.eb.fRoutePagesHandler != nil {
log.DebugF("default routing handler: %s", e.eb.fRoutePagesHandler.Tag())
router.HandleFunc("/*", e.eb.fRoutePagesHandler.RoutePage)
} else {
log.DebugF("default routing handler: .ServeNotFound")
router.HandleFunc("/*", e.ServeNotFound)
}
e.Emit(signals.PostEnjinSetupRouter, feature.EnjinTag.String(), interface{}(e).(feature.Internals))
return
}