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 "errors"
5 "net/http"
6 "strconv"
7 "strings"
8
9 "gorm.io/gorm"
10
11 "amadan.net/oficina/sheets/internal/sheets/store"
12)
13
14// Rename exists because Create stopped asking for a name.
15//
16// The sheet list used to carry a form with a title field, so a sheet
17// was named once, at the moment it was made, and never again — there
18// was no rename route and layout.html said so in a comment. That was
19// survivable only because the title field existed. Removing it in
20// favour of a one-click Create, which lands every new sheet as
21// "Untitled sheet", would have made the missing route the whole
22// product: a list of sheets all called the same thing, distinguished
23// only by their preview thumbnails, with no way to fix any of them.
24//
25// So this is not a feature that arrived beside the topbar Create
26// button. It is the other half of it.
27
28// errBlankTitle is returned rather than silently keeping the old title.
29// A person who cleared the field and submitted meant something by it,
30// and the honest answer is that a sheet needs a name — the same rule
31// createSheet applies.
32var errBlankTitle = errors.New("sheets: a sheet needs a title")
33
34// handleSheetRename renames a sheet from the title in the top bar.
35//
36// Editors, not just owners: renaming is an edit to the document, of a
37// piece with editing a cell, and mayWrite is what says who may make
38// one. A viewer or commenter gets the 404 that AGENTS.md requires for
39// a row that is not theirs to change — never a 403, which would
40// confirm the sheet exists to somebody who may not see it.
41func (a *App) handleSheetRename(w http.ResponseWriter, r *http.Request) {
42 s, ok := a.sheetFromURL(w, r)
43 if !ok {
44 return
45 }
46 viewer, ok := a.actor(r)
47 if !ok {
48 a.notFound(w, r)
49 return
50 }
51 // Bounded, then parsed, and only THEN authorised. The order is the
52 // point and it is deliberately not the order the rest of the app
53 // uses.
54 //
55 // Every other write route here authorises first and reads the body
56 // after (openTab before the decode, in handlers_format and
57 // handlers_size). That leaves the body read — the one step whose
58 // duration the client chooses — sitting between the permission
59 // check and the write, so an editor can begin a rename, hold the
60 // body open while their grant is revoked, then finish it and have
61 // the write go through. Reading first collapses that: the delay a
62 // client controls now happens BEFORE anything is checked, and the
63 // gap between mayWrite and the UPDATE is straight-line code.
64 //
65 // It is not free — a request that turns out to be forbidden has
66 // paid to parse its own body — but the cap on the line below is
67 // what makes that cheap enough to be the obvious trade. The wider
68 // question, whether every other write route should be reordered
69 // the same way, is a real one and belongs in the branch discussion
70 // rather than in this handler.
71 //
72 // 8 KiB matches handlers_format's cap on the same shape of form
73 // post. Go's own ParseForm ceiling for a urlencoded body is 10 MiB,
74 // so this is not the difference between bounded and unbounded — it
75 // is three orders of magnitude off a limit no rename needs, for a
76 // value truncated to maxTitleRunes moments later.
77 r.Body = http.MaxBytesReader(w, r.Body, 8<<10)
78 if err := r.ParseForm(); err != nil {
79 // Refused rather than carried on with. FormValue would swallow
80 // this error and fall through to the QUERY, which is how
81 // ?title=x on an oversized body silently became the new name —
82 // caught by review, not by the suite.
83 a.badRequest(w, r, http.StatusBadRequest, "Malformed request.")
84 return
85 }
86 // PostForm, never Form: the title comes from the body a person
87 // submitted, never from the URL. r.FormValue merges the query in,
88 // so with it a GET-shaped ?title= could rename a sheet — a
89 // state-changing value arriving somewhere it can be linked to.
90 //
91 // Read field by field into a local, never bound onto a GORM model
92 // (AGENTS.md / Mechanical rules): a form that could reach the model
93 // could set CreatedBy, or DeletedAt, or an id.
94 title := r.PostForm.Get("title")
95
96 // Last thing before the write, with nothing client-paced in
97 // between. See the note above on why this moved down here.
98 if !a.mayWrite(s.ID, viewer) {
99 a.notFound(w, r)
100 return
101 }
102
103 if err := a.renameSheet(a.writeGuard(r.Context(), s.ID, viewer, SheetEditor), s.ID, title); err != nil {
104 if a.guardRefused(w, r, err) {
105 return
106 }
107 if errors.Is(err, errBlankTitle) {
108 if wantsNative(r) {
109 http.Error(w, "A sheet needs a title.", 400)
110 return
111 }
112 // Straight back to the sheet, which still shows the name it
113 // had. Nothing was changed and there is nothing to explain
114 // that the unchanged title does not already say.
115 a.sheetRedirect(w, r, s.ID)
116 return
117 }
118 a.fail(w, r, err)
119 return
120 }
121 // 303 rather than a render: a POST that renders is a POST that
122 // resubmits on reload.
123 a.sheetRedirect(w, r, s.ID)
124}
125
126// sheetRedirect sends the browser back to a sheet.
127func (a *App) sheetRedirect(w http.ResponseWriter, r *http.Request, id uint64) {
128 if nativeNotice(w, r, "renamed") {
129 return
130 }
131 http.Redirect(w, r, "/sheets/"+strconv.FormatUint(id, 10), http.StatusSeeOther)
132}
133
134// renameSheet writes a new sealed title.
135//
136// The title is sealed under the same "sheet.title" purpose createSheet
137// uses. A rename that wrote plaintext would put a sheet's name in the
138// database file, and the one rule does not have an exception for the
139// second time a name is set.
140//
141// Update names its column explicitly rather than saving a struct, so
142// this statement cannot touch a field nobody asked it to. GORM bumps
143// UpdatedAt as part of it, which is what makes a renamed sheet rise to
144// the top of the list — correct, since renaming it is changing it.
145func (a *App) renameSheet(g store.Guard, sheetID uint64, title string) error {
146 if a.db == nil {
147 return errNoDB
148 }
149 if a.sealer == nil {
150 return errNoSealer
151 }
152 clean := strings.TrimSpace(title)
153 if clean == "" {
154 return errBlankTitle
155 }
156 // Truncated to the same limit createSheet applies, by runes rather
157 // than bytes so a multi-byte title is cut where a character ends.
158 if r := []rune(clean); len(r) > maxTitleRunes {
159 clean = string(r[:maxTitleRunes])
160 }
161 sealed, err := a.sealer.Seal("sheet.title", []byte(clean))
162 if err != nil {
163 return err
164 }
165 return a.guarded(g, func(db *gorm.DB) error {
166 return db.Model(&store.Sheet{}).
167 Where("id = ?", sheetID).
168 Update("title_sealed", sealed).Error
169 })
170}
171