gunk-dev/the-valley

reader.go

source672eff5ffaecmain's published tip history
11.7 KiB
1package server
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "mime"
11 "net/http"
12 "strings"
13
14 "the-valley/exactjson"
15 "the-valley/web/export"
16 "the-valley/web/readerstate"
17)
18
19// The reader's own pages: the page a read link opens, and the page that
20// signs a reader out. Each answers GET and HEAD with a page, and POST
21// with the transaction the page's script asks for. sessionPage answers
22// GET and HEAD alone, with the session the request carries, which the
23// reader page's script asks for before it tries again.
24const (
25 redeemPage = "redeem"
26 logoutPage = "logout"
27 sessionPage = "session"
28 logoutURL = "/" + own + "/" + logoutPage
29)
30
31// readerPageOf is the reader page a path's segments name, /-/redeem,
32// /-/logout or /-/session, or "" for any other path. A server with no
33// browser state has no reader pages.
34func (s *Server) readerPageOf(parts []string, ok bool) string {
35 if s.readers == nil || !ok || len(parts) != 2 || parts[0] != own {
36 return ""
37 }
38 switch parts[1] {
39 case redeemPage, logoutPage, sessionPage:
40 return parts[1]
41 }
42 return ""
43}
44
45// posted reports whether a reader page answers POST.
46func posted(page string) bool { return page == redeemPage || page == logoutPage }
47
48// cookieName is the session cookie's name. The __Host- prefix makes a
49// browser keep it only when it was set over HTTPS, with Path=/ and no
50// Domain, so it is this host's alone.
51const cookieName = "__Host-valley-reader"
52
53// sessionAge is how long a browser keeps the session cookie after the
54// last response that renewed it, in seconds: 30 days. It is the browser's
55// retention alone: the server keeps no expiry.
56const sessionAge = 2592000
57
58// sessionCookie is the Set-Cookie value that gives a browser token, or,
59// for "", that clears the cookie.
60func sessionCookie(token string) string {
61 age := sessionAge
62 if token == "" {
63 age = 0
64 }
65 return fmt.Sprintf("%s=%s; Secure; HttpOnly; Path=/; SameSite=Lax; Max-Age=%d", cookieName, token, age)
66}
67
68// carriedCookie reports whether the request carries the session cookie,
69// and its value when it carries it exactly once. Every Cookie header and
70// every pair in each is counted, so a request that carries the cookie
71// twice carries no token.
72func carriedCookie(r *http.Request) (carried bool, token string) {
73 n := 0
74 for _, header := range r.Header.Values("Cookie") {
75 for _, pair := range strings.Split(header, ";") {
76 name, value, _ := strings.Cut(strings.Trim(pair, " \t"), "=")
77 if name == cookieName {
78 n++
79 token = value
80 }
81 }
82 }
83 if n != 1 {
84 token = ""
85 }
86 return n > 0, token
87}
88
89// session is the session a request carries, as the browser state resolved
90// it under one authorization.
91type session struct {
92 // token is the session cookie's value when the request carries it
93 // once, and valid is set when it names a valid session, whose
94 // principal is reader. reader is anyone for every other request.
95 token string
96 reader string
97 valid bool
98 // unavailable is set when the request carries the session cookie and
99 // the browser state cannot be read.
100 unavailable bool
101}
102
103// same reports whether two resolutions give a request the same reader.
104func (st session) same(o session) bool {
105 return st.reader == o.reader && st.valid == o.valid && st.unavailable == o.unavailable
106}
107
108// readState takes the browser state's read lock, for the session's
109// resolution and, at the final check, for the headers written after it,
110// waiting for it until ctx is done. done gives it back. A server with no
111// browser state holds nothing.
112func (s *Server) readState(ctx context.Context) (r readerstate.Reading, done func(), err error) {
113 if s.readers == nil {
114 return readerstate.Reading{}, func() {}, nil
115 }
116 if r, err = s.readers.Read(ctx); err != nil {
117 return r, nil, err
118 }
119 return r, r.Done, nil
120}
121
122// sessionOf resolves the session cookie a request carries under the
123// authorization a, with the browser state's read lock held as r.
124func (s *Server) sessionOf(r readerstate.Reading, carried bool, token string, a *export.Authorization) session {
125 if s.readers == nil || !carried {
126 return session{reader: export.Anyone}
127 }
128 principal, err := r.Session(token, a)
129 switch {
130 case err != nil:
131 return session{reader: export.Anyone, unavailable: true}
132 case principal == "":
133 return session{reader: export.Anyone}
134 }
135 return session{token: token, reader: principal, valid: true}
136}
137
138// resolve is sessionOf, taking and giving back the read lock itself. A
139// request whose context is done before it takes the lock is answered as
140// one whose state cannot be read; its last check, under the same context,
141// writes none of it.
142func (s *Server) resolve(ctx context.Context, carried bool, token string, a *export.Authorization) session {
143 if s.readers == nil || !carried {
144 return session{reader: export.Anyone}
145 }
146 r, done, err := s.readState(ctx)
147 if err != nil {
148 return session{reader: export.Anyone, unavailable: true}
149 }
150 defer done()
151 return s.sessionOf(r, carried, token, a)
152}
153
154// hold takes the serving lock shared and reads the stored authorization
155// under it, for a browser-state transaction (readerstate.Hold).
156func (s *Server) hold(ctx context.Context) (*export.Authorization, func(), error) {
157 release, err := s.store.HoldServing(ctx)
158 if err != nil {
159 return nil, nil, err
160 }
161 return s.readAuthorization().a, release, nil
162}
163
164// Prepare creates the empty browser state when there is none yet and the
165// stored authorization was read, parsed, and carries no binding. Every
166// request asks again while the state is still to be created, so the state
167// is created once the host delivers an authorization with no binding,
168// with no restart. A server with no browser state does nothing.
169func (s *Server) Prepare(ctx context.Context) {
170 s.prepare(ctx, s.readAuthorization())
171}
172
173// prepare waits for the browser state's locks only until ctx is done. A
174// request whose wait ended so goes on, and is answered as one past its
175// deadline.
176func (s *Server) prepare(ctx context.Context, auth authState) {
177 if s.readers == nil || auth.a == nil || len(auth.a.Bindings) > 0 {
178 return
179 }
180 if pending, err := s.readers.Pending(ctx); err != nil || !pending {
181 return
182 }
183 if _, err := s.readers.Initialize(ctx, s.hold); err != nil && ctx.Err() == nil {
184 s.log(fmt.Errorf("creating the browser state: %w", err))
185 }
186}
187
188// maxPost is the most bytes of a reader page's POST body.
189const maxPost = 1 << 10
190
191// The fixed answers of a reader page's POST. Every credential the
192// browser state refuses answers refusedLink, whatever the reason, and
193// every request that breaks the POST's contract answers refusedPost.
194const (
195 refusedLink = "This link cannot be used. Request another link.\n"
196 refusedPost = "This request is refused.\n"
197 anotherReader = "Another reader is signed in on this browser.\n"
198 unavailable = "Sign-in is unavailable on this server right now. Try again later.\n"
199)
200
201// post answers a POST to a reader page: a redemption, or a logout. It
202// runs once, under the request's deadline, outside the rendering loop,
203// and touches no export. Its headers are set already.
204func (s *Server) post(ctx context.Context, w http.ResponseWriter, r *http.Request, page string) {
205 body, ok := checkReaderPost(ctx, w, r, s.origin)
206 if !ok {
207 answer(w, http.StatusForbidden, refusedPost)
208 return
209 }
210 _, token := carriedCookie(r)
211 var err error
212 switch page {
213 case redeemPage:
214 // The credential is a string, present and not null: {} and
215 // {"credential":null} break the post's contract, as any other
216 // shape does, before the browser state is reached.
217 var in struct {
218 Credential *string `json:"credential"`
219 }
220 if exactjson.Decode(body, &in) != nil || in.Credential == nil {
221 answer(w, http.StatusForbidden, refusedPost)
222 return
223 }
224 s.prepare(ctx, s.readAuthorization())
225 var next string
226 next, err = s.readers.Redeem(ctx, s.hold, *in.Credential, token)
227 if err == nil {
228 w.Header().Set("Set-Cookie", sessionCookie(next))
229 }
230 case logoutPage:
231 var in struct{}
232 if exactjson.Decode(body, &in) != nil {
233 answer(w, http.StatusForbidden, refusedPost)
234 return
235 }
236 if err = s.readers.Logout(ctx, s.hold, token); err == nil {
237 w.Header().Set("Set-Cookie", sessionCookie(""))
238 }
239 }
240 switch {
241 case err == nil:
242 w.WriteHeader(http.StatusNoContent)
243 case errors.Is(err, readerstate.ErrRefused):
244 answer(w, http.StatusForbidden, refusedLink)
245 case errors.Is(err, readerstate.ErrSignedIn):
246 answer(w, http.StatusConflict, anotherReader)
247 case r.Context().Err() != nil:
248 default:
249 if ctx.Err() == nil {
250 s.log(fmt.Errorf("%s: %w", page, err))
251 }
252 answer(w, http.StatusServiceUnavailable, unavailable)
253 }
254}
255
256// answer writes a short plain-text response.
257func answer(w http.ResponseWriter, status int, text string) {
258 h := w.Header()
259 h.Set("Content-Type", "text/plain; charset=utf-8")
260 h.Set("Content-Length", fmt.Sprint(len(text)))
261 w.WriteHeader(status)
262 io.WriteString(w, text)
263}
264
265// checkReaderPost holds a reader page's POST to its contract, and returns
266// its body. The request carries exactly one Origin, the server's public
267// origin; exactly one Content-Type, application/json with at most a UTF-8
268// charset; exactly one X-Valley-Reader: 1; no Content-Encoding; and no
269// query. Its body is at most maxPost bytes and is one JSON object. The
270// body is read under the request's deadline. A request held to none of it
271// is answered by no browser state.
272func checkReaderPost(ctx context.Context, w http.ResponseWriter, r *http.Request, origin string) ([]byte, bool) {
273 h := r.Header
274 one := func(name string) (string, bool) {
275 vs := h.Values(name)
276 if len(vs) != 1 {
277 return "", false
278 }
279 return vs[0], true
280 }
281 if v, ok := one("Origin"); !ok || origin == "" || v != origin {
282 return nil, false
283 }
284 if v, ok := one("X-Valley-Reader"); !ok || v != "1" {
285 return nil, false
286 }
287 if v, ok := one("Content-Type"); !ok || !jsonType(v) {
288 return nil, false
289 }
290 if len(h.Values("Content-Encoding")) > 0 || r.URL.RawQuery != "" || r.URL.ForceQuery || r.ContentLength > maxPost {
291 return nil, false
292 }
293 if deadline, ok := ctx.Deadline(); ok {
294 _ = http.NewResponseController(w).SetReadDeadline(deadline)
295 }
296 body, err := io.ReadAll(io.LimitReader(r.Body, maxPost+1))
297 if err != nil || len(body) > maxPost {
298 return nil, false
299 }
300 if trimmed := bytes.TrimLeft(body, " \t\r\n"); len(trimmed) == 0 || trimmed[0] != '{' {
301 return nil, false
302 }
303 return body, true
304}
305
306// jsonType reports whether a Content-Type is application/json, with no
307// parameter but a UTF-8 charset.
308func jsonType(v string) bool {
309 media, params, err := mime.ParseMediaType(v)
310 if err != nil || media != "application/json" {
311 return false
312 }
313 for k, p := range params {
314 if k != "charset" || !strings.EqualFold(p, "utf-8") {
315 return false
316 }
317 }
318 return true
319}
320
321// readerContent is what a reader page shows: whether the request carries
322// a valid session.
323type readerContent struct {
324 Session bool
325}
326
327// readerPage answers GET and HEAD of a reader page. It needs no export
328// and no authorization, so it renders when nothing is published.
329func (q *request) readerPage() {
330 if q.rpage == sessionPage {
331 q.sessionState()
332 return
333 }
334 title := "Continue as reader"
335 if q.rpage == logoutPage {
336 title = "Sign out"
337 }
338 q.page(http.StatusOK, q.rpage, title, readerContent{Session: q.sess.valid})
339}
340
341// sessionState answers /-/session: {"link":"<credential-id>"}, the ID of
342// the link the request's valid session was redeemed from, or
343// {"link":""} for a request with no valid session. The ID is not secret:
344// it names the link, and redeems nothing.
345func (q *request) sessionState() {
346 id := ""
347 if q.sess.valid {
348 id, _, _ = strings.Cut(q.sess.token, ".")
349 }
350 data, _ := json.Marshal(struct {
351 Link string `json:"link"`
352 }{id})
353 q.static(http.StatusOK, "application/json", data)
354}
355
356// unavailablePage answers a request that carries the session cookie while
357// the browser state cannot be read.
358func (q *request) unavailablePage() {
359 q.static(http.StatusServiceUnavailable, htmlType, unavailableHTML)
360}