gunk-dev/the-valley

token.go

sourcef007964e2f86main's published tip history
1.8 KiB
1package export
2
3import (
4 "crypto/sha256"
5 "crypto/subtle"
6 "fmt"
7 "io"
8 "net/http"
9 "os"
10 "strings"
11)
12
13// MinToken and MaxToken bound the length of the receiver's token, in
14// bytes.
15const (
16 MinToken = 32
17 MaxToken = 256
18)
19
20// ReadToken reads the receiver's token from the file at path. The file
21// holds one line: MinToken to MaxToken visible ASCII characters, with a
22// newline after them or none. The publisher and the receiver read it with
23// the same rules. An error never quotes the file.
24func ReadToken(path string) (string, error) {
25 f, err := os.Open(path)
26 if err != nil {
27 return "", err
28 }
29 defer f.Close()
30 data, err := io.ReadAll(io.LimitReader(f, MaxToken+2))
31 if err != nil {
32 return "", err
33 }
34 token := strings.TrimSuffix(string(data), "\n")
35 if len(token) < MinToken || len(token) > MaxToken {
36 return "", fmt.Errorf("the token in %s is not %d to %d characters on one line", path, MinToken, MaxToken)
37 }
38 for i := 0; i < len(token); i++ {
39 if token[i] < 0x21 || token[i] > 0x7e {
40 return "", fmt.Errorf("the token in %s holds a character that is not visible ASCII", path)
41 }
42 }
43 return token, nil
44}
45
46// BearerHeader is the value of the Authorization header that carries the
47// token on every request of an upload.
48func BearerHeader(token string) string { return "Bearer " + token }
49
50// CarriesToken reports whether the request carries the token in exactly one
51// Authorization header. It compares SHA-256 sums in constant time, so the
52// time it takes says nothing about how much of the token a request got
53// right, or how long the token is.
54func CarriesToken(r *http.Request, token string) bool {
55 got := r.Header.Values("Authorization")
56 if len(got) != 1 {
57 return false
58 }
59 a := sha256.Sum256([]byte(got[0]))
60 b := sha256.Sum256([]byte(BearerHeader(token)))
61 return subtle.ConstantTimeCompare(a[:], b[:]) == 1
62}