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
3// HTML error pages (spec §3). Before this every failure a browser could
4// reach was http.Error's plain text in the browser's monospace font, with
5// no chrome, no <title> and no way back: "Not found." for a stale link or
6// a revoked share, and chi's own "404 page not found" for an unknown
7// route.
8//
9// Which answers are pages is decided by the request, not the route: a
10// page is rendered only when Accept names text/html, as every browser
11// navigation and form post does. a.notFound is the case the spec names
12// (§3.3): one helper reached from the grid's page and from its /api
13// fetches through sheetFromURL, so the split has to happen inside it.
14// The grid's fetches, the live stream and the native apps never ask for
15// HTML, so they keep the plain answers they have always had.
16//
17// A missing sheet and one that is not shared with you are the same 404
18// (AGENTS.md): nothing here distinguishes them, so nothing is enumerable.
19
20import (
21 "errors"
22 "fmt"
23 "log/slog"
24 "net/http"
25 "net/url"
26 "runtime/debug"
27 "strings"
28
29 "amadan.net/oficina/estilo.git/chrome"
30 "amadan.net/rastrillo/rastrillo"
31 "github.com/go-chi/chi/v5"
32)
33
34var errNoTemplate = errors.New("sheets: no such page template")
35
36// errorCopy is one row of the spec's §3.2 table.
37type errorCopy struct {
38 title, heading, body string
39}
40
41// errorKind says which row a failure is.
42type errorKind int
43
44const (
45 // kindRoute: nothing lives at this address.
46 kindRoute errorKind = iota
47 // kindSheet: the sheet (or link) is missing, or not shared with you.
48 kindSheet
49 // kindStatus: the page for the status itself (400, 403, 413, 5xx).
50 kindStatus
51)
52
53func copyFor(status int, kind errorKind) errorCopy {
54 switch {
55 case status == http.StatusNotFound && kind == kindSheet:
56 return errorCopy{"Sheet not available", "This sheet isn’t available", "It may have been deleted, or it hasn’t been shared with you."}
57 case status == http.StatusNotFound:
58 return errorCopy{"Page not found", "We can’t find that page", "The link may be out of date, or the page may have moved."}
59 case status == http.StatusForbidden:
60 return errorCopy{"No access", "You don’t have access to this page", "Ask whoever runs this team if you think you should."}
61 case status == http.StatusRequestEntityTooLarge:
62 return errorCopy{"Too long", "That’s too long", "Go back, make it shorter and try again."}
63 case status == http.StatusBadRequest:
64 return errorCopy{"That didn’t work", "That didn’t work", "Go back and try again."}
65 case status == http.StatusServiceUnavailable:
66 return errorCopy{appName + " is unavailable", appName + " is unavailable right now", "Try again in a few minutes."}
67 }
68 return errorCopy{"Something went wrong", "Something went wrong", "Try again in a moment. If it keeps happening, quote the reference below."}
69}
70
71type errorPageView struct {
72 Error chrome.ErrorPage
73}
74
75// wantsHTML reports whether the request asked for a page.
76func wantsHTML(r *http.Request) bool {
77 return strings.Contains(r.Header.Get("Accept"), "text/html")
78}
79
80// notFound answers 404 with nothing that could name a sheet: the "sheet
81// not available" page for a browser, and the plain "Not found." it has
82// always been for the grid's fetches and the native apps.
83//
84// In team mode with standing Unknown it is a retryable 503 instead, for
85// a sheet that exists and one that does not alike: whether it is theirs
86// could not be decided, and a 404 would say it was not (team_access.go).
87func (a *App) notFound(w http.ResponseWriter, r *http.Request) {
88 if a.teamUnknown(r) {
89 a.unavailable(w, r)
90 return
91 }
92 a.answer(w, r, http.StatusNotFound, kindSheet, "Not found.")
93}
94
95// routeNotFound is the router's NotFound: an unknown address.
96func (a *App) routeNotFound(w http.ResponseWriter, r *http.Request) {
97 a.answer(w, r, http.StatusNotFound, kindRoute, "Not found.")
98}
99
100// forbidden answers a request that needed an actor and had none. Behind
101// requireSession it is unreachable; it is what a handler says if that
102// guard is ever not in front of it.
103func (a *App) forbidden(w http.ResponseWriter, r *http.Request) {
104 a.answer(w, r, http.StatusForbidden, kindStatus, "Sign in first.")
105}
106
107// badRequest answers a form that could not be read, or asked for
108// something the route cannot do. text is the plain answer a script or a
109// native client has always read.
110func (a *App) badRequest(w http.ResponseWriter, r *http.Request, status int, text string) {
111 a.answer(w, r, status, kindStatus, text)
112}
113
114// fail answers 500.
115//
116// The error is deliberately dropped rather than shown or logged: it can
117// carry a sealed title's plaintext, a cell's contents, or a SQL
118// statement quoting either, and `carlos logs` is platform-held storage
119// we cannot grep or redact (AGENTS.md / Mechanical rules). The page
120// quotes a reference, and the log line carries that reference and the
121// route pattern, never the path: a /l/ path is a capability.
122func (a *App) fail(w http.ResponseWriter, r *http.Request, _ error) {
123 if !wantsHTML(r) {
124 http.Error(w, "Something went wrong.", http.StatusInternalServerError)
125 return
126 }
127 ref := rastrillo.NewRef()
128 slog.Error("sheets: error page", "ref", ref, "route", routePattern(r))
129 a.errorPage(w, r, http.StatusInternalServerError, kindStatus, ref)
130}
131
132func (a *App) answer(w http.ResponseWriter, r *http.Request, status int, kind errorKind, text string) {
133 if !wantsHTML(r) {
134 http.Error(w, text, status)
135 return
136 }
137 a.errorPage(w, r, status, kind, "")
138}
139
140// routePattern is the matched route, "/sheets/{sheetID}" rather than the
141// path it matched: safe to log whatever the path held.
142func routePattern(r *http.Request) string {
143 if rc := chi.RouteContext(r.Context()); rc != nil && rc.RoutePattern() != "" {
144 return rc.RoutePattern()
145 }
146 return "(unrouted)"
147}
148
149// errorPage renders the page for status inside the normal layout, with
150// whatever chrome the request's session gives it. ref is the reference a
151// 500 quotes, empty otherwise.
152func (a *App) errorPage(w http.ResponseWriter, r *http.Request, status int, kind errorKind, ref string) {
153 c := copyFor(status, kind)
154 page := chrome.ErrorPage{
155 Status: status,
156 Title: c.heading,
157 Body: c.body,
158 Home: chrome.Link{Href: "/", Label: "Go to " + appName},
159 }
160 // Try again is the same URL, and only for a GET: re-sending a POST
161 // from an error page is the one thing it must never do.
162 if status >= 500 && r.Method == http.MethodGet {
163 page.Home = chrome.Link{Href: r.URL.RequestURI(), Label: "Try again"}
164 }
165 if ref != "" {
166 page.Ref, page.RefLabel = ref, "Reference:"
167 }
168 if back := a.sameOriginReferer(r); back != "" && status < 500 {
169 page.Back = &chrome.Link{Href: back, Label: "Back"}
170 }
171 t, ok := pages["error"]
172 var buf strings.Builder
173 if ok {
174 err := t.ExecuteTemplate(&buf, "layout", PageData{Frame: a.frameFor(r, titled(c.title)), Data: errorPageView{Error: page}})
175 ok = err == nil
176 }
177 w.Header().Set("Cache-Control", "no-store")
178 if !ok {
179 // The page could not render: say so in the plainest way left.
180 http.Error(w, "Something went wrong.", status)
181 return
182 }
183 pageHeaders(w)
184 w.Header().Set("Content-Type", "text/html; charset=utf-8")
185 w.WriteHeader(status)
186 _, _ = w.Write([]byte(buf.String()))
187}
188
189// sameOriginReferer is the page a person came from, when it is this app
190// and not this page: rastrillo's rule for the error page's Back link. An
191// unchecked Referer is an open redirect with better manners.
192func (a *App) sameOriginReferer(r *http.Request) string {
193 raw := r.Header.Get("Referer")
194 if raw == "" || a.origin == "" {
195 return ""
196 }
197 u, err := url.Parse(raw)
198 if err != nil || u.User != nil || u.Scheme+"://"+u.Host != a.origin {
199 return ""
200 }
201 back := u.EscapedPath()
202 if u.RawQuery != "" {
203 back += "?" + u.RawQuery
204 }
205 if !strings.HasPrefix(back, "/") || strings.HasPrefix(back, "//") || back == r.URL.RequestURI() || strings.HasPrefix(back, "/l/") {
206 return ""
207 }
208 return back
209}
210
211// methodNotAllowed is the router's MethodNotAllowed. A GET or HEAD to a
212// path that only takes a POST (somebody opening /signout from history) is
213// the same 404 page as an unknown route: to a person there is no page
214// there. Any other method gets 405 in plain text, with the Allow header
215// set here — chi's default sets it, a custom handler does not.
216func (a *App) methodNotAllowed(routes chi.Routes) http.HandlerFunc {
217 return func(w http.ResponseWriter, r *http.Request) {
218 var allowed []string
219 for _, m := range []string{http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete} {
220 if routes.Match(chi.NewRouteContext(), m, r.URL.Path) {
221 allowed = append(allowed, m)
222 }
223 }
224 get := false
225 for _, m := range allowed {
226 get = get || m == http.MethodGet
227 }
228 if (r.Method == http.MethodGet || r.Method == http.MethodHead) && !get {
229 a.routeNotFound(w, r)
230 return
231 }
232 w.Header().Set("Allow", strings.Join(allowed, ", "))
233 http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
234 }
235}
236
237// recoverToErrorPage turns a panic in a handler into the 500 page with a
238// reference, logged with the stack under the same reference.
239//
240// It is mounted INSIDE the signed-in group, after the session guard, so
241// the page carries the viewer's own chrome: mounted outside, every 500
242// would look signed out, which is Calendar's bug (spec §3.3). Panics
243// outside it reach rastrillo.Serve's own recoverer through
244// App.ErrorPage.
245func (a *App) recoverToErrorPage(next http.Handler) http.Handler {
246 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
247 defer func() {
248 v := recover()
249 if v == nil {
250 return
251 }
252 if v == http.ErrAbortHandler {
253 panic(v)
254 }
255 ref := rastrillo.NewRef()
256 // The panic value and stack name code, not content: a panic
257 // raised with a cell's text in it would be a bug in its own
258 // right, and the value is logged as the fmt of its type only.
259 slog.Error("sheets: panic", "ref", ref, "route", routePattern(r), "panic", fmt.Sprintf("%T", v), "stack", string(debug.Stack()))
260 if !wantsHTML(r) {
261 http.Error(w, "Something went wrong.", http.StatusInternalServerError)
262 return
263 }
264 a.errorPage(w, r, http.StatusInternalServerError, kindStatus, ref)
265 }()
266 next.ServeHTTP(w, r)
267 })
268}
269
270// ErrorPage is rastrillo.Options.ErrorPage: the page rastrillo.Serve's
271// own panic recovery renders, for a panic outside the signed-in group.
272// It reads the session optionally like every other error page.
273func (a *App) ErrorPage(w http.ResponseWriter, r *http.Request, status int, ref string) {
274 if !wantsHTML(r) {
275 http.Error(w, "Something went wrong.", status)
276 return
277 }
278 a.errorPage(w, r, status, kindStatus, ref)
279}
280