forked from cozy/cozy-stack
/
handler.go
414 lines (373 loc) · 10.2 KB
/
handler.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
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
package statik
import (
"errors"
"fmt"
"html/template"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"github.com/cozy/cozy-stack/model/instance/lifecycle"
"github.com/cozy/cozy-stack/model/vfs"
"github.com/cozy/cozy-stack/pkg/assets"
modelAsset "github.com/cozy/cozy-stack/pkg/assets/model"
"github.com/cozy/cozy-stack/pkg/config/config"
"github.com/cozy/cozy-stack/pkg/consts"
"github.com/cozy/cozy-stack/pkg/i18n"
"github.com/cozy/cozy-stack/pkg/logger"
"github.com/cozy/cozy-stack/pkg/utils"
"github.com/cozy/cozy-stack/web/middlewares"
"github.com/labstack/echo/v4"
"github.com/sirupsen/logrus"
)
var (
templatesList = []string{
"authorize.html",
"authorize_move.html",
"authorize_sharing.html",
"compat.html",
"confirm_auth.html",
"error.html",
"import.html",
"instance_blocked.html",
"login.html",
"move_confirm.html",
"move_delegated_auth.html",
"move_in_progress.html",
"move_link.html",
"move_vault.html",
"need_onboarding.html",
"oidc_login.html",
"passphrase_choose.html",
"passphrase_reset.html",
"sharing_discovery.html",
"twofactor.html",
}
)
const (
assetsPrefix = "/assets"
assetsExtPrefix = "/assets/ext"
)
// AssetRenderer is an interface for both a template renderer and an asset HTTP
// handler.
type AssetRenderer interface {
echo.Renderer
http.Handler
}
type dir string
func (d dir) Open(name string) (http.File, error) {
if filepath.Separator != '/' && strings.ContainsRune(name, filepath.Separator) {
return nil, errors.New("http: invalid character in file path")
}
dir := string(d)
if dir == "" {
dir = "."
}
name, _ = ExtractAssetID(name)
fullName := filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name)))
f, err := os.Open(fullName)
if err != nil {
return nil, err
}
return f, nil
}
// NewDirRenderer returns a renderer with assets opened from a specified local
// directory.
func NewDirRenderer(assetsPath string) (AssetRenderer, error) {
list := make([]string, len(templatesList))
for i, name := range templatesList {
list[i] = filepath.Join(assetsPath, "templates", name)
}
t := template.New("stub")
h := http.StripPrefix(assetsPrefix, http.FileServer(dir(assetsPath)))
middlewares.FuncsMap = template.FuncMap{
"t": fmt.Sprintf,
"tHTML": fmt.Sprintf,
"split": strings.Split,
"replace": strings.Replace,
"hasSuffix": strings.HasSuffix,
// XXX We are using assetPath (and not AssetPath) here to avoid caching
// the assets via the sum in the URL. But it means that we have no
// fallback to the default context.
"asset": assetPath,
"ext": fileExtension,
"basename": basename,
"filetype": filetype,
}
var err error
t, err = t.Funcs(middlewares.FuncsMap).ParseFiles(list...)
if err != nil {
return nil, fmt.Errorf("Can't load the assets from %q: %s", assetsPath, err)
}
return &renderer{t: t, Handler: h}, nil
}
// NewRenderer return a renderer with assets loaded form their packed
// representation into the binary.
func NewRenderer() (AssetRenderer, error) {
t := template.New("stub")
middlewares.FuncsMap = template.FuncMap{
"t": fmt.Sprintf,
"tHTML": fmt.Sprintf,
"split": strings.Split,
"replace": strings.Replace,
"hasSuffix": strings.HasSuffix,
"asset": AssetPath,
"ext": fileExtension,
"basename": basename,
"filetype": filetype,
}
for _, name := range templatesList {
tmpl := t.New(name).Funcs(middlewares.FuncsMap)
f, err := assets.Open("/templates/"+name, config.DefaultInstanceContext)
if err != nil {
return nil, fmt.Errorf("Can't load asset %q: %s", name, err)
}
b, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
if _, err = tmpl.Parse(string(b)); err != nil {
return nil, err
}
}
return &renderer{t: t, Handler: NewHandler()}, nil
}
type renderer struct {
http.Handler
t *template.Template
}
func (r *renderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
var funcMap template.FuncMap
i, ok := middlewares.GetInstanceSafe(c)
if ok {
funcMap = template.FuncMap{
"t": i.Translate,
"tHTML": i18n.TranslatorHTML(i.Locale, i.ContextName),
}
} else {
lang := GetLanguageFromHeader(c.Request().Header)
funcMap = template.FuncMap{
"t": i18n.Translator(lang, ""),
"tHTML": i18n.TranslatorHTML(lang, ""),
}
}
var t *template.Template
var err error
if m, ok := data.(echo.Map); ok {
if context, ok := m["ContextName"].(string); ok {
if i != nil {
assets.LoadContextualizedLocale(context, i.Locale)
}
if f, err := assets.Open("/templates/"+name, context); err == nil {
b, err := ioutil.ReadAll(f)
if err != nil {
return err
}
tmpl := template.New(name).Funcs(middlewares.FuncsMap)
if _, err = tmpl.Parse(string(b)); err != nil {
return err
}
t = tmpl
}
}
}
if t == nil {
t, err = r.t.Clone()
if err != nil {
return err
}
}
return t.Funcs(funcMap).ExecuteTemplate(w, name, data)
}
// AssetPath return the fullpath with unique identifier for a given asset file.
func AssetPath(domain, name string, context ...string) string {
ctx := config.DefaultInstanceContext
if len(context) > 0 && context[0] != "" {
ctx = context[0]
}
f, ok := assets.Head(name, ctx)
if !ok {
logger.WithNamespace("assets").WithFields(logrus.Fields{
"domain": domain,
"name": name,
"context": ctx,
}).Errorf("Cannot find asset")
}
if ok {
name = f.NameWithSum
if !f.IsCustom {
context = nil
}
}
return assetPath(domain, name, context...)
}
func assetPath(domain, name string, context ...string) string {
if len(context) > 0 && context[0] != "" {
name = path.Join(assetsExtPrefix, url.PathEscape(context[0]), name)
} else {
name = path.Join(assetsPrefix, name)
}
if domain != "" {
return "//" + domain + name
}
return name
}
// Handler implements http.handler for a subpart of the available assets on a
// specified prefix.
type Handler struct{}
// NewHandler returns a new handler
func NewHandler() Handler {
return Handler{}
}
// ServeHTTP implements the http.Handler interface.
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
// The URL path should be formed in one on those forms:
// /assets/:file...
// /assets/ext/(:context-name)/:file...
var id, name, context string
if strings.HasPrefix(r.URL.Path, assetsExtPrefix+"/") {
nameWithContext := strings.TrimPrefix(r.URL.Path, assetsExtPrefix+"/")
nameWithContextSplit := strings.SplitN(nameWithContext, "/", 2)
if len(nameWithContextSplit) != 2 {
http.Error(w, "File not found", http.StatusNotFound)
return
}
context = nameWithContextSplit[0]
name = nameWithContextSplit[1]
} else {
name = strings.TrimPrefix(r.URL.Path, assetsPrefix)
if inst, err := lifecycle.GetInstance(r.Host); err == nil {
context = inst.ContextName
}
}
name, id = ExtractAssetID(name)
if len(name) > 0 && name[0] != '/' {
name = "/" + name
}
f, ok := assets.Get(name, context)
if !ok {
http.Error(w, "File not found", http.StatusNotFound)
return
}
checkETag := id == ""
h.ServeFile(w, r, f, checkETag)
}
// ServeFile can be used to respond with an asset file to an HTTP request
func (h *Handler) ServeFile(w http.ResponseWriter, r *http.Request, f *modelAsset.Asset, checkETag bool) {
if checkETag && utils.CheckPreconditions(w, r, f.Etag) {
return
}
headers := w.Header()
headers.Set("Content-Type", f.Mime)
headers.Set("Content-Length", f.Size())
headers.Add("Vary", "Accept-Encoding")
acceptsBrotli := strings.Contains(r.Header.Get("Accept-Encoding"), "br")
if acceptsBrotli {
headers.Set("Content-Encoding", "br")
headers.Set("Content-Length", f.BrotliSize())
} else {
headers.Set("Content-Length", f.Size())
}
if checkETag {
headers.Set("Etag", f.Etag)
headers.Set("Cache-Control", "no-cache, public")
} else {
headers.Set("Cache-Control", "max-age=31536000, public, immutable")
}
if r.Method == http.MethodGet {
if acceptsBrotli {
_, _ = io.Copy(w, f.BrotliReader())
} else {
_, _ = io.Copy(w, f.Reader())
}
}
}
// GetLanguageFromHeader return the language tag given the Accept-Language
// header.
func GetLanguageFromHeader(header http.Header) (lang string) {
lang = consts.DefaultLocale
acceptHeader := header.Get("Accept-Language")
if acceptHeader == "" {
return
}
acceptLanguages := utils.SplitTrimString(acceptHeader, ",")
for _, tag := range acceptLanguages {
// tag may contain a ';q=' for a quality factor that we do not take into
// account.
if i := strings.Index(tag, ";q="); i >= 0 {
tag = tag[:i]
}
// tag may contain a '-' to introduce a country variante, that we do not
// take into account.
if i := strings.IndexByte(tag, '-'); i >= 0 {
tag = tag[:i]
}
if utils.IsInArray(tag, consts.SupportedLocales) {
lang = tag
return
}
}
return
}
// ExtractAssetID checks if a long hexadecimal string is contained in given
// file path and returns the original file name and ID (if any). For instance
// <foo.badbeedbadbeef.min.js> = <foo.min.js, badbeefbadbeef>
func ExtractAssetID(file string) (string, string) {
var id string
base := path.Base(file)
off1 := strings.IndexByte(base, '.') + 1
if off1 < len(base) {
off2 := off1 + strings.IndexByte(base[off1:], '.')
if off2 > off1 {
if s := base[off1:off2]; isLongHexString(s) || s == "immutable" {
dir := path.Dir(file)
id = s
file = base[:off1-1] + base[off2:]
if dir != "." {
file = path.Join(dir, file)
}
}
}
}
return file, id
}
func isLongHexString(s string) bool {
if len(s) < 10 {
return false
}
for _, c := range s {
switch {
case c >= '0' && c <= '9':
case c >= 'a' && c <= 'f':
case c >= 'A' && c <= 'F':
default:
return false
}
}
return true
}
func fileExtension(filename string) string {
return path.Ext(filename)
}
func basename(filename string) string {
ext := fileExtension(filename)
return strings.TrimSuffix(filename, ext)
}
func filetype(mime string) string {
if mime == consts.NoteMimeType {
return "note"
}
_, class := vfs.ExtractMimeAndClass(mime)
if class == "shortcut" || class == "application" {
return "files"
}
return class
}