/
build_route.go
205 lines (171 loc) · 4.57 KB
/
build_route.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
package ath
import (
"errors"
"fmt"
"io/fs"
"io/ioutil"
"mime"
"path/filepath"
"regexp"
"strings"
"text/template"
"golang.org/x/exp/slices"
)
type routeBuilder struct {
root string
config Config
template *template.Template
enabledCompression []Compression
allowedCompression map[string]bool
permanent, sized Cache
}
func BuildRoutes(config Config) (map[string]Route, error) {
policy := strings.ReplaceAll(config.CSP.Policy, "CSP_NONCE", "{{.Nonce}}")
tmpl, err := template.New("CSP").Parse(policy)
if err != nil {
return nil, err
}
sized := NewCache(int64(config.ServerCache.MaxMemorySize))
var permanent Cache
if config.ServerCache.RootFileInLRU == true {
permanent = sized
} else {
permanent = NewCache(-1)
}
return (&routeBuilder{
root: config.Args.Directory,
config: config,
template: tmpl,
enabledCompression: config.EnabledCompressions(),
allowedCompression: config.AllowedCompressions(),
permanent: permanent,
sized: sized,
}).buildRoutes()
}
func (b *routeBuilder) buildRoutes() (map[string]Route, error) {
res := make(map[string]Route)
err := filepath.WalkDir(b.root,
func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() == true {
return nil
}
target, route, err := b.buildRoute(path, d)
if err != nil {
return err
}
res[target] = route
return nil
})
return res, err
}
var ErrNonNonceable = errors.New("route is not nonceable")
func (b *routeBuilder) buildRoute(path string, d fs.DirEntry) (string, Route, error) {
target := buildTarget(b.root, path)
if b.config.CSP.Disable == false &&
slices.Contains(b.config.CSP.NoncedPath, target) == true {
nonced, err := b.buildNoncedRoute(path)
if err == nil {
return target, nonced, nil
}
if err != ErrNonNonceable {
return target, nil, err
}
}
route, err := b.buildStaticRoute(path, d)
if err != nil {
return target, nil, err
}
return target, route, nil
}
var ngCspNoncedRx = regexp.MustCompile(`ng_csp_nonced(="[^"]*")?`)
func (b *routeBuilder) buildNoncedRoute(path string) (Route, error) {
content_, err := ioutil.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("open '%s': %w", path, err)
}
content := string(content_)
if strings.Contains(content, "ng_csp_nonced") == false {
return nil, ErrNonNonceable
}
templ, err := b.template.Clone()
if err != nil {
return nil, err
}
templ, err = templ.New("content").Parse(ngCspNoncedRx.ReplaceAllString(content,
"ngCspNonce=\"{{.Nonce}}\""))
if err != nil {
return nil, err
}
name := filepath.Base(path)
mime := mime.TypeByExtension(filepath.Ext(name))
return &NoncedRoute{
route: route{
name: name,
mime: mime,
enabledCompression: b.enabledCompression,
},
template: templ,
}, nil
}
func (b *routeBuilder) buildStaticRoute(path string, d fs.DirEntry) (Route, error) {
name := filepath.Base(path)
mime := mime.TypeByExtension(filepath.Ext(name))
fileinfo, err := d.Info()
if err != nil {
return nil, err
}
return StaticRoute{
route: route{
name: name,
mime: mime,
enabledCompression: b.getCompression(fileinfo),
},
filepath: path,
modtime: fileinfo.ModTime(),
cache: b.getCache(path),
cacheControl: b.getCacheControl(path),
}, nil
}
func (b *routeBuilder) inRoot(path string) bool {
return filepath.Dir(path) == filepath.Clean(b.root)
}
func (b *routeBuilder) getCache(path string) Cache {
if b.inRoot(path) == true {
return b.permanent
}
return b.sized
}
var hashOrVersionRx = regexp.MustCompile(`\A(\.[[:xdigit:]]+|\.v[0-9]+)\z`)
func isVersionned(path string) bool {
ext := filepath.Ext(path)
midExt := filepath.Ext(strings.TrimSuffix(path, ext))
return hashOrVersionRx.MatchString(midExt)
}
func (b *routeBuilder) getCacheControl(path string) string {
if isVersionned(path) == true {
return "max-age=31536000; immutable"
}
if b.config.Cache.MaxAge <= 0 {
return "no-cache"
}
return fmt.Sprintf("max-age=%d; must-revalidate", b.config.Cache.MaxAge)
}
func (b *routeBuilder) getCompression(fileinfo fs.FileInfo) []Compression {
filename := fileinfo.Name()
ext := filepath.Ext(filename)
if ext == ".map" && strings.HasSuffix(filename, ".js.map") {
ext = ".js.map"
}
if b.allowedCompression[ext] == true &&
fileinfo.Size() >= int64(b.config.Compression.Threshold) {
return b.enabledCompression
}
return nil
}
func buildTarget(root, path string) string {
target, _ := filepath.Rel(root, path)
return "/" + target
}