Repository navigation
Expand file tree
/
Copy pathredirect.go
More file actions
553 lines (466 loc) · 15.2 KB
/
Copy pathredirect.go
File metadata and controls
553 lines (466 loc) · 15.2 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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
// ⚡️ Fiber is an Express inspired web framework written in Go with ☕️
// 📝 GitHub Repository: https://github.com/gofiber/fiber
// 📌 API Documentation: https://docs.gofiber.io
package fiber
import (
"bytes"
"encoding/hex"
"net/url"
"strings"
"sync"
"github.com/gofiber/utils/v2"
"github.com/valyala/bytebufferpool"
"github.com/valyala/fasthttp"
"github.com/gofiber/fiber/v3/internal/fieldname"
"github.com/gofiber/fiber/v3/internal/schemehost"
"github.com/gofiber/fiber/v3/internal/urlnorm"
)
// Pool for redirection
var (
redirectPool = sync.Pool{
New: func() any {
return &Redirect{
status: StatusSeeOther,
messages: make(redirectionMsgs, 0),
}
},
}
oldInputPool = sync.Pool{
New: func() any {
return make(map[string]string)
},
}
)
const maxPoolableMapSize = 64
// maxPoolableMessages matches the msgp arrays limit below: a redirect holding more sets no cookie.
const maxPoolableMessages = 256
// FlashCookieName Cookie name to send flash messages when to use redirection.
const (
FlashCookieName = "fiber_flash"
)
var flashCookieNeedle = []byte(FlashCookieName + "=")
// hasFlashCookie is on the request hot path and runs on every request/response cycle.
// Keep this cheap for users who don't use flash messages:
// 1) a fast raw-header prefilter to avoid unnecessary cookie parsing,
// 2) an exact cookie lookup to avoid prefix false positives (e.g. fiber_flashX).
func hasFlashCookie(header *fasthttp.RequestHeader) bool {
// A request built programmatically has no raw headers, so the prefilter cannot answer for it.
if rawHeaders := header.RawHeaders(); len(rawHeaders) > 0 && !bytes.Contains(rawHeaders, flashCookieNeedle) {
return false
}
return header.Cookie(FlashCookieName) != nil
}
// redirectionMsgs is a struct that used to store flash messages and old input data in cookie using MSGP.
// msgp -file="redirect.go" -o="redirect_msgp.go" -unexported
// Cookie payloads are limited to ~4KB, so keep flash message counts bounded but usable.
//
//msgp:limit arrays:256 maps:32 marshal:true
//msgp:ignore Redirect RedirectConfig OldInputData FlashMessage
type redirectionMsg struct {
key string
value string
level uint8
isOldInput bool
}
type redirectionMsgs []redirectionMsg
// OldInputData is a struct that holds the old input data.
type OldInputData struct {
Key string
Value string
}
// FlashMessage is a struct that holds the flash message data.
type FlashMessage struct {
Key string
Value string
Level uint8
}
// Redirect is a struct that holds the redirect data.
type Redirect struct {
c *DefaultCtx // Embed ctx
messages redirectionMsgs // Flash messages and old input data
status int // Status code of redirection. Default: 303 StatusSeeOther
}
// RedirectConfig A config to use with Redirect().Route()
// You can specify queries or route parameters.
// NOTE: We don't use net/url to parse parameters because of it has poor performance. You have to pass map.
type RedirectConfig struct {
Params Map // Route parameters
Queries map[string]string // Query map
}
// AcquireRedirect return default Redirect reference from the redirect pool
func AcquireRedirect() *Redirect {
redirect, ok := redirectPool.Get().(*Redirect)
if !ok {
panic(errRedirectTypeAssertion)
}
return redirect
}
// ReleaseRedirect returns c acquired via Redirect to redirect pool.
//
// It is forbidden accessing req and/or its members after returning
// it to redirect pool.
func ReleaseRedirect(r *Redirect) {
// A large WithInput form grows the array past what the cookie can carry; once
// pooled, every later release would clear all of it.
if len(r.messages) > maxPoolableMessages {
return
}
r.release()
redirectPool.Put(r)
}
func (r *Redirect) release() {
r.status = StatusSeeOther
// Zero before truncating: WithInput copies the whole request body into these
// entries, and a bare [:0] leaves those strings reachable from the backing
// array for as long as the pooled *Redirect lives.
clear(r.messages[:cap(r.messages)])
r.messages = r.messages[:0]
r.c = nil
}
func acquireOldInput() map[string]string {
oldInput, ok := oldInputPool.Get().(map[string]string)
if !ok {
return make(map[string]string)
}
return oldInput
}
func releaseOldInput(oldInput map[string]string) {
if len(oldInput) > maxPoolableMapSize {
return
}
clear(oldInput)
oldInputPool.Put(oldInput)
}
// Status sets the status code of redirection.
// If status is not specified, status defaults to 303 See Other.
func (r *Redirect) Status(code int) *Redirect {
r.status = code
return r
}
// With You can send flash messages by using With().
// They will be sent as a cookie.
// You can get them by using: Redirect().Messages(), Redirect().Message()
// The cookie payload is MessagePack encoded, so keys and values need no escaping.
// Calling With again with the same key replaces the earlier message.
// No cookie is set when Config.DisableFlashMessages is on.
func (r *Redirect) With(key, value string, level ...uint8) *Redirect {
// Get level
var msgLevel uint8
if len(level) > 0 {
msgLevel = level[0]
}
// Override old message if exists
for i, msg := range r.messages {
if msg.key == key && !msg.isOldInput {
r.messages[i].value = value
r.messages[i].level = msgLevel
return r
}
}
r.messages = append(r.messages, redirectionMsg{
key: key,
value: value,
level: msgLevel,
})
return r
}
// WithInput You can send input data by using WithInput().
// They will be sent as a cookie.
// This method can send form, multipart form, query data to redirected route.
// You can get them by using: Redirect().OldInputs(), Redirect().OldInput()
// It does nothing when Config.DisableFlashMessages is on.
func (r *Redirect) WithInput() *Redirect {
if r.c.app.config.DisableFlashMessages {
return r
}
ctype := bindMediaType(&r.c.RequestCtx().Request.Header)
oldInput := acquireOldInput()
defer releaseOldInput(oldInput)
switch ctype {
case MIMEApplicationForm, MIMEMultipartForm:
_ = r.c.Bind().Form(oldInput) //nolint:errcheck // not needed
default:
_ = r.c.Bind().Query(oldInput) //nolint:errcheck // not needed
}
// Add old input data
for k, v := range oldInput {
r.messages = append(r.messages, redirectionMsg{
key: k,
value: v,
isOldInput: true,
})
}
return r
}
// Messages Get flash messages.
func (r *Redirect) Messages() []FlashMessage {
if len(r.c.flashMessages) == 0 {
return nil
}
flashMessages := make([]FlashMessage, 0, len(r.c.flashMessages))
writeIdx := 0
for _, msg := range r.c.flashMessages {
if msg.isOldInput {
r.c.flashMessages[writeIdx] = msg
writeIdx++
continue
}
flashMessages = append(flashMessages, FlashMessage{
Key: msg.key,
Value: msg.value,
Level: msg.level,
})
}
for i := writeIdx; i < len(r.c.flashMessages); i++ {
r.c.flashMessages[i] = redirectionMsg{}
}
r.c.flashMessages = r.c.flashMessages[:writeIdx]
return flashMessages
}
// Message Get flash message by key.
func (r *Redirect) Message(key string) FlashMessage {
if len(r.c.flashMessages) == 0 {
return FlashMessage{}
}
var flashMessage FlashMessage
found := false
writeIdx := 0
for _, msg := range r.c.flashMessages {
if msg.isOldInput || found || msg.key != key {
r.c.flashMessages[writeIdx] = msg
writeIdx++
continue
}
flashMessage = FlashMessage{
Key: msg.key,
Value: msg.value,
Level: msg.level,
}
found = true
}
for i := writeIdx; i < len(r.c.flashMessages); i++ {
r.c.flashMessages[i] = redirectionMsg{}
}
r.c.flashMessages = r.c.flashMessages[:writeIdx]
return flashMessage
}
// OldInputs Get old input data.
func (r *Redirect) OldInputs() []OldInputData {
// Count old inputs first to avoid allocation if none exist
count := 0
for _, msg := range r.c.flashMessages {
if msg.isOldInput {
count++
}
}
if count == 0 {
return nil
}
inputs := make([]OldInputData, 0, count)
for _, msg := range r.c.flashMessages {
if msg.isOldInput {
inputs = append(inputs, OldInputData{
Key: msg.key,
Value: msg.value,
})
}
}
return inputs
}
// OldInput Get old input data by key.
func (r *Redirect) OldInput(key string) OldInputData {
msgs := r.c.flashMessages
for _, msg := range msgs {
if msg.key == key && msg.isOldInput {
return OldInputData{
Key: msg.key,
Value: msg.value,
}
}
}
return OldInputData{}
}
// To redirect to the URL derived from the specified path, with specified status.
func (r *Redirect) To(location string) error {
r.c.setCanonical(HeaderLocation, location)
r.c.Status(r.status)
r.processFlashMessages()
return nil
}
// Route redirects to the Route registered in the app with appropriate parameters.
// If you want to send queries or params to route, you should use config parameter.
func (r *Redirect) Route(name string, config ...RedirectConfig) error {
// Check config
cfg := RedirectConfig{}
if len(config) > 0 {
cfg = config[0]
}
// Get location from route name. buildRouteURL already holds the composed
// path to this origin, so only the query is left to place.
route := r.c.App().GetRoute(name)
location, err := r.c.getLocationFromRoute(&route, cfg.Params)
if err != nil {
return err
}
// Check queries
if len(cfg.Queries) > 0 {
queryText := bytebufferpool.Get()
defer bytebufferpool.Put(queryText)
first := true
for k, v := range cfg.Queries {
if !first {
queryText.WriteByte('&')
}
first = false
queryText.WriteString(k)
queryText.WriteByte('=')
// Escape the value so characters like &, =, # or + don't break the
// query string. Keys are left as-is to preserve the nested-key
// convention (e.g. `data[0][name]`) used elsewhere.
queryText.B = utils.AppendQueryEscape(queryText.B, v)
}
// Concatenated here rather than in a helper: the result goes straight to
// To, so escape analysis can build it on the stack. Returning it from a
// function cost an allocation per redirect.
query := r.c.app.toString(queryText.Bytes())
separator, fragment := queryMergePoint(location)
if fragment < 0 {
return r.To(location + separator + query)
}
return r.To(location[:fragment] + separator + query + location[fragment:])
}
return r.To(location)
}
// queryMergePoint says where a query belongs in location: the separator that
// introduces it, and where the fragment starts, or -1.
func queryMergePoint(location string) (separator string, fragment int) { //nolint:nonamedreturns // the two results are easy to swap without names
fragment = strings.IndexByte(location, '#')
query := location
if fragment >= 0 {
query = location[:fragment]
}
if strings.IndexByte(query, '?') >= 0 {
return "&", fragment
}
return "?", fragment
}
// Back redirect to the URL to referer.
// It validates that the Referer is same-origin to prevent open redirect attacks.
// If the Referer is missing, invalid, or cross-origin, the fallback URL is used.
func (r *Redirect) Back(fallback ...string) error {
location := r.refererHeader()
if location != "" {
// Reject invalid or cross-origin referrers, and redirect to the
// normalized form so every client resolves it the same way the
// same-origin check did.
normalized, ok := r.sameOriginReferer(location)
if !ok {
normalized = ""
}
location = normalized
}
if location == "" {
// Check fallback URL
if len(fallback) == 0 {
err := ErrRedirectBackNoFallback
r.c.Status(err.Code)
return err
}
location = fallback[0]
}
// A 300, 301 or 308 is cacheable by default, and the Referer picks its target.
if r.status == StatusMultipleChoices || r.status == StatusMovedPermanently || r.status == StatusPermanentRedirect {
r.c.Vary(HeaderReferer)
}
return r.To(location)
}
// refererHeader returns the Referer, matching the field name the way a recipient
// must (RFC 9110 §5.1). Ctx.Get is byte-exact, so under DisableHeaderNormalizing
// a lower-case "referer:" read as absent and Back always took the fallback.
func (r *Redirect) refererHeader() string {
if v := r.c.Get(HeaderReferer); v != "" {
return v
}
if !r.c.app.config.DisableHeaderNormalizing {
return ""
}
return r.c.app.toString(fieldname.First(&r.c.fasthttp.Request.Header, HeaderReferer, false))
}
// sameOriginReferer reports whether the Referer resolves back to the origin now
// being served, returning the normalized form safe to echo. A browser's
// normalization decides that, not net/url: " //evil.com", "/\evil.com", "///x".
func (r *Redirect) sameOriginReferer(location string) (string, bool) {
// The normalized value is what gets redirected to, so a client that does
// not apply these rules itself cannot resolve a different origin than the
// one validated here.
location = urlnorm.Referer(location)
if location == "" {
return "", false
}
// An absolute path stays on the current origin, but "//host" is a
// network-path reference that switches to another one.
if location[0] == '/' && !strings.HasPrefix(location, "//") {
return location, true
}
parsed, err := url.Parse(location)
if err != nil {
return "", false
}
if parsed.Host == "" {
// A scheme with no authority ("javascript:", "mailto:") is no same-origin
// reference; anything else is a relative path — except an empty authority
// ("//?x", "//#f", "//@"), which names no origin and resolves nowhere.
return location, parsed.Scheme == "" && !strings.HasPrefix(location, "//")
}
return location, schemehost.Match(parsed.Scheme, parsed.Host, r.c.Scheme(), r.c.Host())
}
// parseAndClearFlashMessages is a method to get flash messages before they are getting removed
func (r *Redirect) parseAndClearFlashMessages() {
// UnmarshalMsg re-slices this capacity rather than allocating, and the
// generated decoder assigns only the fields the message carries — so an empty
// map keeps whatever the slot held, and the destination must arrive zeroed.
clear(r.c.flashMessages[:cap(r.c.flashMessages)])
r.c.flashMessages = r.c.flashMessages[:0]
// parse flash messages
if cookieValue, err := hex.DecodeString(r.c.Cookies(FlashCookieName)); err == nil {
if _, err := r.c.flashMessages.UnmarshalMsg(cookieValue); err != nil {
// UnmarshalMsg re-slices to the length the payload declared before
// it decodes any element, so a failure partway leaves the slice
// holding zero-valued entries. Drop them.
r.c.flashMessages = r.c.flashMessages[:0]
}
}
// Expire the cookie whatever the payload turned out to be, including the
// hex-decode failure above. A value this application cannot decode it never
// will, so leaving it means re-running hex and msgp on every later request.
r.c.Cookie(&Cookie{
Name: FlashCookieName,
Value: "",
Path: "/",
MaxAge: -1,
HTTPOnly: true,
Secure: r.c.Secure(),
})
}
// processFlashMessages sets the flash messages and old input data as cookies.
//
// The payload is hex-encoded, not signed, and WithInput copies the whole form
// into it — so the cookie is HTTPOnly, and Secure whenever the request was TLS.
func (r *Redirect) processFlashMessages() {
if len(r.messages) == 0 || r.c.app.config.DisableFlashMessages {
return
}
val, err := r.messages.MarshalMsg(nil)
if err != nil {
return
}
dst := make([]byte, hex.EncodedLen(len(val)))
hex.Encode(dst, val)
r.c.Cookie(&Cookie{
Name: FlashCookieName,
Value: r.c.app.toString(dst),
SessionOnly: true,
HTTPOnly: true,
Secure: r.c.Secure(),
})
}