-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
349 lines (307 loc) · 8.38 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
package scratch
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"html/template"
"io/fs"
"log"
"math/rand"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"time"
"git.sr.ht/~mariusor/scratch/assets"
)
type Handler struct {
BasePath storage
Assets assets.Maps
authorization map[string][]byte
}
var rnd = rand.New(rand.NewSource(time.Now().UnixNano()))
var unauthorizedErr = fmt.Errorf("missmatched key")
func (h Handler) CheckKey(r *http.Request) bool {
key := getKeyFromRequest(r)
path := getPathFromRequest(r)
if _, err := h.BasePath.LoadKeyForPath(path); err != nil && errors.Is(err, fs.ErrNotExist) {
return true
}
k, ok := h.authorization[path]
return ok && bytes.Equal(k, key)
}
func getRandomKey() []byte {
return []byte(
base64.RawStdEncoding.Strict().EncodeToString([]byte(fmt.Sprintf("%d", rnd.Uint64()))),
)
}
func (h *Handler) CheckOrUpdateKeyRequest(r *http.Request) (string, error) {
path := getPathFromRequest(r)
if err := r.ParseForm(); err != nil {
return "", err
}
// We load the pw from POST data
pw := []byte(r.PostFormValue("_"))
genNewKey := false
if !h.BasePath.CheckPwForPath(pw, path) {
if !h.CheckKey(r) {
return "", fmt.Errorf("unauthorized to save key %q: %w", path, unauthorizedErr)
}
if len(pw) > 0 {
if err := h.BasePath.SaveKeyForPath(pw, path); err != nil {
return "", fmt.Errorf("unable to save key %q: %w", path, err)
}
genNewKey = true
}
}
key, ok := h.authorization[path]
if genNewKey || !ok || len(key) == 0 {
// Generate random auth token for current path.
// We show it to the user, only if they send the proper pw
key = getRandomKey()
}
h.authorization[path] = key
log.Printf("Generated auth key for %s: %q", path, key)
return string(key), nil
}
func (h Handler) DeleteRequest(r *http.Request) error {
path := getPathFromRequest(r)
if !h.CheckKey(r) {
return fmt.Errorf("unauthorized to delete path %q: %w", path, unauthorizedErr)
}
return h.BasePath.DeletePath(path)
}
func (h Handler) UpdateRequest(r *http.Request) error {
path := getPathFromRequest(r)
if !h.CheckKey(r) {
return fmt.Errorf("%s unauthorized: %w", path, unauthorizedErr)
}
content := r.PostFormValue("_")
if r.PostForm.Has("_") {
log.Printf("saving %dbytes", len(content))
if err := h.BasePath.SavePath(content, path); err != nil {
return err
}
}
return nil
}
func statusError(err error) int {
status := http.StatusInternalServerError
if errors.Is(err, unauthorizedErr) {
status = http.StatusUnauthorized
}
return status
}
func writeError(w http.ResponseWriter, err error) {
log.Printf("Error: %s", err)
http.Error(w, err.Error(), statusError(err))
}
func jsCSRF() template.JS {
csrf := struct{}{}
b, _ := json.Marshal(csrf)
return template.JS(b)
}
type Index struct {
Path string
Files []IndexEntry
}
type IndexEntry struct {
parent *Index
Path string
ModTime time.Time
Size int64
HasSecret bool
}
func (i IndexEntry) URL() template.HTMLAttr {
return template.HTMLAttr("./" + i.Path)
}
var errorRedirectToContent = fmt.Errorf("no children")
func (h Handler) ShowIndexForPath(p string) ([]byte, error) {
out := new(bytes.Buffer)
pathEl := strings.Split(p, "/")
pathEl[0] = "/"
index := Index{
Path: path.Join(pathEl...),
Files: make([]IndexEntry, 0),
}
base := os.DirFS(string(h.BasePath))
fs.WalkDir(base, p, func(file string, d fs.DirEntry, err error) error {
if err != nil {
log.Printf("error: %s", err)
return err
}
fi, err := d.Info()
if err != nil {
log.Printf("error: %s", err)
return err
}
if fi.IsDir() {
if p == file {
return nil
}
ie := IndexEntry{parent: &index, Path: fi.Name()}
keyPath := path.Join(file, KeyFileName)
_, err := fs.Stat(base, keyPath)
ie.HasSecret = (err == nil || !errors.Is(err, fs.ErrNotExist))
contentPath := path.Join(file, ContentFileName)
ci, err := fs.Stat(base, contentPath)
if err != nil {
log.Printf("error: %s", err)
return nil
}
ie.Size = ci.Size()
ie.ModTime = ci.ModTime()
index.Files = append(index.Files, ie)
}
return nil
})
if len(index.Files) == 0 {
return nil, errorRedirectToContent
}
templates := assets.WithPrefix("static/templates", assets.Maps{
"main.html": {"index.html"},
})
t := template.New("main.html").Funcs(template.FuncMap{
"style": h.Assets.StyleNode,
"script": h.Assets.JsNode,
"icon": func(i IndexEntry) template.HTML {
name := "unlock"
if i.HasSecret {
name = "lock"
}
return assets.Icon(name)
},
"title": func() template.HTMLAttr { return template.HTMLAttr(fmt.Sprintf("File index %s", index.Path)) },
})
if _, err := t.ParseFS(templates, templates.Names()...); err != nil {
return out.Bytes(), fmt.Errorf("unable to parse templates %v: %w", templates.Names(), err)
}
if err := t.Execute(out, &index); err != nil {
return out.Bytes(), fmt.Errorf("unable to parse templates %v: %w", templates.Names(), err)
}
return out.Bytes(), nil
}
func (h Handler) ShowRequest(path, defTitle string) ([]byte, time.Time, error) {
out := new(bytes.Buffer)
content, err := h.BasePath.LoadPath(path)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
return out.Bytes(), time.Time{}, fmt.Errorf("unable to load from path %q: %w", path, err)
}
log.Printf("unable to load %q, probably a new file", path)
}
key, _ := h.BasePath.LoadKeyForPath(path)
modTime, _ := h.BasePath.ModTimePath(path)
p := Page{
Secret: key,
Path: path,
Modified: modTime,
Content: template.HTML(content),
}
templates := assets.WithPrefix("static/templates", assets.Maps{
"main.html": {"main.html"},
})
t := template.New("main.html").Funcs(template.FuncMap{
"style": h.Assets.StyleNode,
"script": h.Assets.JsNode,
"csrf": jsCSRF,
"title": p.Title(defTitle),
"help": p.Help(),
})
if _, err := t.ParseFS(templates, templates.Names()...); err != nil {
return out.Bytes(), time.Time{}, fmt.Errorf("unable to parse templates %v: %w", templates.Names(), err)
}
if err := t.Execute(out, &p); err != nil {
return out.Bytes(), time.Time{}, fmt.Errorf("unable to parse templates %v: %w", templates.Names(), err)
}
return out.Bytes(), modTime, nil
}
func RandomURL(r *http.Request) *url.URL {
rPath := base64.RawURLEncoding.Strict().EncodeToString([]byte(fmt.Sprintf("%d", rnd.Uint32())))
u := *r.URL
u.Host = r.Host
u.Path = path.Join(u.Path, rPath)
u.RawQuery = ""
return &u
}
func RedirectToRandom(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, RandomURL(r).String(), http.StatusTemporaryRedirect)
}
var day = 24 * time.Hour
func (h *Handler) Handle(w http.ResponseWriter, r *http.Request) {
st := time.Now()
defer func() {
log.Printf("[%s] %s %s", r.Method, r.URL.Path, time.Now().Sub(st).String())
}()
switch r.Method {
case http.MethodPatch:
key, err := h.CheckOrUpdateKeyRequest(r)
if err != nil {
writeError(w, err)
}
w.Header().Add("Authentication-Info", key)
return
case http.MethodDelete:
if err := h.DeleteRequest(r); err != nil {
writeError(w, err)
}
return
case http.MethodPost:
if err := h.UpdateRequest(r); err != nil {
writeError(w, err)
}
return
case http.MethodGet:
if r.URL.Query().Has("random") {
RedirectToRandom(w, r)
return
}
p := getPathFromRequest(r)
if len(r.URL.Path) > 1 && r.URL.Path[len(r.URL.Path)-1] == '/' {
out, err := h.ShowIndexForPath(p)
if err != nil {
if errors.Is(err, errorRedirectToContent) {
url := filepath.Clean(r.RequestURI)
log.Printf("Redirecting to %s", url)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
return
}
writeError(w, err)
}
w.Write(out)
return
}
out, mod, err := h.ShowRequest(p, cleanHost(r.Host))
if err != nil {
writeError(w, err)
}
if !mod.IsZero() {
//w.Header().Set("Last-Modified", modTime.Format(time.RFC1123))
}
//w.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d", int(day.Seconds())))
w.Write(out)
return
}
http.Error(w, "405 method not allowed", http.StatusMethodNotAllowed)
}
func getPathFromRequest(r *http.Request) string {
host := r.URL.Host
if len(host) == 0 {
host = r.Host
}
return path.Join(host, r.URL.Path)
}
func getKeyFromRequest(r *http.Request) []byte {
return []byte(r.Header.Get("Authorization"))
}
func New(storage string, files assets.Maps) Handler {
return Handler{
BasePath: Storage(storage),
Assets: files,
authorization: make(map[string][]byte),
}
}