-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathredirects.go
238 lines (193 loc) · 5.04 KB
/
redirects.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
// Package redirects provides Netlify style _redirects file format parsing.
package redirects
import (
"bufio"
"fmt"
"io"
"net/url"
"strconv"
"strings"
"github.com/ucarion/urlpath"
)
// 64 KiB
const MaxFileSizeInBytes = 65536
// A Rule represents a single redirection or rewrite rule.
type Rule struct {
// From is the path which is matched to perform the rule.
From string
// To is the destination which may be relative, or absolute
// in order to proxy the request to another URL.
To string
// Status is one of the following:
//
// - 3xx a redirect
// - 200 a rewrite
// - defaults to 301 redirect
//
Status int
}
// IsRewrite returns true if the rule represents a rewrite (status 200).
func (r *Rule) IsRewrite() bool {
return r.Status == 200
}
// IsProxy returns true if it's a proxy rule (aka contains a hostname).
func (r *Rule) IsProxy() bool {
u, err := url.Parse(r.To)
if err != nil {
return false
}
return u.Host != ""
}
// MatchAndExpandPlaceholders expands placeholders in `r.To` and returns true if the provided path matches.
// Otherwise it returns false.
func (r *Rule) MatchAndExpandPlaceholders(urlPath string) bool {
// get rule.From, trim trailing slash, ...
fromPath := urlpath.New(strings.TrimSuffix(r.From, "/"))
match, ok := fromPath.Match(urlPath)
if !ok {
return false
}
// We have a match! Perform substitution and return the updated rule
toPath := r.To
toPath = replacePlaceholders(toPath, match)
toPath = replaceSplat(toPath, match)
r.To = toPath
return true
}
func replacePlaceholders(to string, match urlpath.Match) string {
if len(match.Params) > 0 {
for key, value := range match.Params {
to = strings.ReplaceAll(to, ":"+key, value)
}
}
return to
}
func replaceSplat(to string, match urlpath.Match) string {
return strings.ReplaceAll(to, ":splat", match.Trailing)
}
// Must parse utility.
func Must(v []Rule, err error) []Rule {
if err != nil {
panic(err)
}
return v
}
// Parse the given reader.
func Parse(r io.Reader) (rules []Rule, err error) {
limiter := &io.LimitedReader{R: r, N: MaxFileSizeInBytes + 1}
s := bufio.NewScanner(limiter)
for s.Scan() {
// detect when we've read one byte beyond MaxFileSizeInBytes
// and return user-friendly error
if limiter.N <= 0 {
return nil, fmt.Errorf("redirects file size cannot exceed %d bytes", MaxFileSizeInBytes)
}
line := strings.TrimSpace(s.Text())
// empty
if line == "" {
continue
}
// comment
if strings.HasPrefix(line, "#") {
continue
}
// fields
fields := strings.Fields(line)
// missing dst
if len(fields) <= 1 {
return nil, fmt.Errorf("missing 'to' path")
}
if len(fields) > 3 {
return nil, fmt.Errorf("must match format 'from to [status]'")
}
// implicit status
rule := Rule{Status: 301}
// from (must parse as an absolute path)
from, err := parseFrom(fields[0])
if err != nil {
return nil, fmt.Errorf("parsing 'from': %w", err)
}
rule.From = from
// to (must parse as an absolute path or an URL)
to, err := parseTo(fields[1])
if err != nil {
return nil, fmt.Errorf("parsing 'to': %w", err)
}
rule.To = to
// status
if len(fields) > 2 {
code, err := parseStatus(fields[2])
if err != nil {
return nil, fmt.Errorf("parsing status %q: %w", fields[2], err)
}
rule.Status = code
}
rules = append(rules, rule)
}
err = s.Err()
if err != nil {
return nil, err
}
return rules, nil
}
// ParseString parses the given string.
func ParseString(s string) ([]Rule, error) {
return Parse(strings.NewReader(s))
}
func parseFrom(s string) (string, error) {
// enforce a single splat
fromSplats := strings.Count(s, "*")
if fromSplats > 0 {
if !strings.HasSuffix(s, "*") {
return "", fmt.Errorf("path must end with asterisk")
}
if fromSplats > 1 {
return "", fmt.Errorf("path can have at most one asterisk")
}
}
// confirm value is within URL path spec
_, err := url.Parse(s)
if err != nil {
return "", err
}
if !strings.HasPrefix(s, "/") {
return "", fmt.Errorf("path must begin with '/'")
}
return s, nil
}
func parseTo(s string) (string, error) {
// confirm value is within URL path spec
u, err := url.Parse(s)
if err != nil {
return "", err
}
// if the value is a patch attached to full URL, only allow safelisted schemes
if !strings.HasPrefix(s, "/") {
if u.Scheme != "http" && u.Scheme != "https" && u.Scheme != "ipfs" && u.Scheme != "ipns" {
return "", fmt.Errorf("invalid URL scheme")
}
}
return s, nil
}
// parseStatus returns the status code.
func parseStatus(s string) (code int, err error) {
if strings.HasSuffix(s, "!") {
// See https://docs.netlify.com/routing/redirects/rewrites-proxies/#shadowing
return 0, fmt.Errorf("forced redirects (or \"shadowing\") are not supported")
}
code, err = strconv.Atoi(s)
if err != nil {
return 0, err
}
if !isValidStatusCode(code) {
return 0, fmt.Errorf("status code %d is not supported", code)
}
return code, nil
}
func isValidStatusCode(status int) bool {
switch status {
case 200, 301, 302, 303, 307, 308, 404, 410, 451:
return true
}
return false
}