oficina / sheets Public

Clone
git clone https://amadan.net/oficina/sheets

Plain git — no account needed to clone.

Download

Download this file

1package sheets
2
3import (
4 "crypto/rand"
5 "crypto/sha256"
6 "crypto/subtle"
7 "encoding/base64"
8 "encoding/hex"
9 "errors"
10 "time"
11
12 "gorm.io/gorm"
13
14 "amadan.net/oficina/sheets/internal/sheets/store"
15)
16
17// linkTokenBytes is the token's entropy: 32 bytes from crypto/rand.
18//
19// "High-entropy" is spec §8.3's word and this is what it has to mean in
20// practice — 256 bits, so the token cannot be guessed, enumerated, or
21// found by walking a keyspace. It is also why the stored hash can be a
22// fast one: see ShareLink's doc comment.
23const linkTokenBytes = 32
24
25// linkRoles are the only roles a link may carry.
26//
27// Never editor (ruling 12). Every version row carries an actor, and an
28// anonymous editor would write unattributed rows into version history —
29// which is not a policy preference but a thing the history model cannot
30// represent.
31var linkRoles = []SheetRole{SheetViewer, SheetCommenter}
32
33func linkRoleValid(r SheetRole) bool {
34 for _, ok := range linkRoles {
35 if r == ok {
36 return true
37 }
38 }
39 return false
40}
41
42// newLinkToken mints a token and returns it with its hash. The token is
43// returned exactly once, to be shown exactly once.
44func newLinkToken() (token, hash string, err error) {
45 buf := make([]byte, linkTokenBytes)
46 if _, err := rand.Read(buf); err != nil {
47 return "", "", err
48 }
49 token = base64.RawURLEncoding.EncodeToString(buf)
50 return token, hashLinkToken(token), nil
51}
52
53// hashLinkToken is what gets stored and what a lookup compares.
54func hashLinkToken(token string) string {
55 sum := sha256.Sum256([]byte(token))
56 return hex.EncodeToString(sum[:])
57}
58
59// errBadLinkRole is the one createLink failure the person asking can do
60// anything about.
61//
62// It is a sentinel rather than an anonymous error because the handler
63// has to tell it apart from the rest. Every other way this function
64// fails — the token generator, the insert, no database at all — is ours
65// and not theirs, and reporting those as a rejected role choice tells
66// somebody to fix the one thing that was not broken.
67var errBadLinkRole = errors.New("sheets: a link can only view or comment, never edit")
68
69// createLink mints a link for a sheet and returns the token, which the
70// caller must show once and then forget.
71func (a *App) createLink(g store.Guard, sheetID uint64, role SheetRole, by Member) (string, error) {
72 if a.db == nil {
73 return "", errNoDB
74 }
75 if !linkRoleValid(role) {
76 // Named rather than silently downgraded: somebody asking for an
77 // editor link has a expectation this refuses, and refusing
78 // quietly would leave them thinking they made one.
79 return "", errBadLinkRole
80 }
81 token, hash, err := newLinkToken()
82 if err != nil {
83 return "", err
84 }
85 if err := a.guarded(g, func(db *gorm.DB) error {
86 return db.Create(&ShareLink{
87 SheetID: sheetID, TokenHash: hash, Role: string(role), CreatedBy: by.ID,
88 }).Error
89 }); err != nil {
90 return "", err
91 }
92 return token, nil
93}
94
95// linksOn lists a sheet's links for the share screen. The tokens are
96// not among them — they cannot be, which is the point.
97func (a *App) linksOn(sheetID uint64) ([]ShareLink, error) {
98 if a.db == nil {
99 return nil, errNoDB
100 }
101 var rows []ShareLink
102 err := a.db.Where("sheet_id = ? AND revoked_at IS NULL", sheetID).
103 Order("id ASC").Find(&rows).Error
104 return rows, err
105}
106
107// revokeLink turns a link off. The row survives so that somebody
108// holding a stale URL can be told the link was turned off rather than
109// that it never existed.
110func (a *App) revokeLink(g store.Guard, sheetID, linkID uint64) error {
111 if a.db == nil {
112 return errNoDB
113 }
114 now := time.Now().UTC()
115 return a.guarded(g, func(db *gorm.DB) error {
116 return db.Model(&ShareLink{}).
117 Where("id = ? AND sheet_id = ? AND revoked_at IS NULL", linkID, sheetID).
118 Update("revoked_at", now).Error
119 })
120}
121
122// linkFor resolves a token to its live link.
123//
124// The lookup is by hash, so the token never has to be compared against
125// anything stored. The constant-time comparison afterwards is belt and
126// braces on an already-indexed exact match: it costs nothing and
127// removes any argument about the index leaking timing.
128func (a *App) linkFor(token string) (ShareLink, bool) {
129 if a.db == nil || token == "" {
130 return ShareLink{}, false
131 }
132 hash := hashLinkToken(token)
133 var link ShareLink
134 err := a.db.Where("token_hash = ?", hash).First(&link).Error
135 if err != nil {
136 if !errors.Is(err, gorm.ErrRecordNotFound) {
137 return ShareLink{}, false
138 }
139 return ShareLink{}, false
140 }
141 if subtle.ConstantTimeCompare([]byte(link.TokenHash), []byte(hash)) != 1 {
142 return ShareLink{}, false
143 }
144 if link.RevokedAt != nil {
145 return ShareLink{}, false
146 }
147 if !a.sheetExists(link.SheetID) {
148 return ShareLink{}, false
149 }
150 return link, true
151}
152