oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1package docs
2
3import (
4 "context"
5 "errors"
6 "net/http"
7 "strconv"
8 "time"
9
10 "amadan.net/oficina/home/roster"
11 "amadan.net/rastrillo/rastrillo"
12 "gorm.io/gorm"
13)
14
15func (s *Store) rememberResponse(ctx context.Context, p permission, docs ...*Document) {
16 if s.team == nil {
17 return
18 }
19 a, ok := ctx.Value(accessContextKey{}).(*requestAccess)
20 if !ok || a == nil || a.runtime != s.team {
21 return
22 }
23 if a.responseDocs == nil {
24 a.responseDocs = map[int64]permission{}
25 }
26 a.responseStore = s
27 for _, doc := range docs {
28 if prior, ok := a.responseDocs[doc.ID]; !ok || p > prior {
29 a.responseDocs[doc.ID] = p
30 }
31 }
32}
33func (a *requestAccess) checkResponse(ctx context.Context) error {
34 if a.extraCheck != nil {
35 if err := a.extraCheck(ctx); err != nil {
36 return err
37 }
38 }
39 if a.responseStore == nil {
40 return errTeamUnavailable
41 }
42 if a.runtime != nil && a.state() == roster.Unknown && (a.agentList || len(a.responseDocs) == 0 && !a.partialNotice) {
43 return errTeamUnavailable
44 }
45 for id, p := range a.responseDocs {
46 if e := a.responseStore.checkPermission(ctx, a.responseStore.db.WithContext(ctx), a.actor, id, p); e != nil {
47 return e
48 }
49 }
50 return nil
51}
52
53// writeGuardedBody checks each bounded chunk after rendering has completed.
54// Once headers are sent, refusal must abort the transport rather than produce
55// a successful short body with a sequence number for bytes never received.
56func writeGuardedBody(w http.ResponseWriter, r *http.Request, status int, parts ...[]byte) error {
57 return writeGuardedBodyThen(w, r, status, nil, parts...)
58}
59
60// writeGuardedBodyThen is writeGuardedBody with headers that belong only to
61// an allowed response (Docs images spec §3.3): headers runs once the first
62// check has passed, just before the status is written, so a refusal never
63// carries them. An image's cache, ETag and sandbox CSP are set this way:
64// before it, the response carries the app's own page CSP, as the ordinary
65// 404 does, and a failure is never cached.
66func writeGuardedBodyThen(w http.ResponseWriter, r *http.Request, status int, headers func(http.Header), parts ...[]byte) error {
67 a, team := r.Context().Value(accessContextKey{}).(*requestAccess)
68 if !team || a == nil {
69 if headers != nil {
70 headers(w.Header())
71 }
72 if status != 0 {
73 w.WriteHeader(status)
74 }
75 for _, part := range parts {
76 if _, e := w.Write(part); e != nil {
77 return e
78 }
79 }
80 return nil
81 }
82 fail := func(e error) {
83 w.Header().Del("Docs-Seq")
84 w.Header().Del("Content-Disposition")
85 w.Header().Del("Content-Length")
86 // A refusal is never stored, as the ordinary error page is not
87 // (errors.go).
88 w.Header().Set("Cache-Control", "no-store")
89 code := http.StatusServiceUnavailable
90 key := "docs.error.generic"
91 if errors.Is(e, gorm.ErrRecordNotFound) {
92 code = http.StatusNotFound
93 key = "docs.error.notfound"
94 }
95 http.Error(w, rastrillo.T(r, key), code)
96 }
97 controller := http.NewResponseController(w)
98 prepare := func() error {
99 started := time.Now()
100 remaining := defaultStreamWriteDeadline
101 if a.state() == roster.Member {
102 lease := a.Remaining()
103 if lease <= 0 {
104 return errTeamUnavailable
105 }
106 if lease < remaining {
107 remaining = lease
108 }
109 }
110 deadline := started.Add(remaining)
111 ctx, cancel := context.WithDeadline(r.Context(), deadline)
112 defer cancel()
113 deadline, _ = ctx.Deadline()
114 if e := a.checkResponse(ctx); e != nil {
115 return e
116 }
117 if ctx.Err() != nil {
118 return errTeamUnavailable
119 }
120 if e := controller.SetWriteDeadline(deadline); e != nil {
121 return errTeamUnavailable
122 }
123 return nil
124 }
125 if e := prepare(); e != nil {
126 fail(e)
127 return nil
128 }
129 total := 0
130 for _, part := range parts {
131 total += len(part)
132 }
133 if headers != nil {
134 headers(w.Header())
135 }
136 // A 304 has no body, and its length is the image's, not this empty
137 // one's: it says nothing rather than 0.
138 if status != http.StatusNotModified {
139 w.Header().Set("Content-Length", strconv.Itoa(total))
140 }
141 if status == 0 {
142 status = http.StatusOK
143 }
144 w.WriteHeader(status)
145 defer controller.SetWriteDeadline(time.Time{})
146 for _, part := range parts {
147 for len(part) > 0 {
148 if e := prepare(); e != nil {
149 panic(http.ErrAbortHandler)
150 }
151 n := min(len(part), 64<<10)
152 wrote, e := w.Write(part[:n])
153 if e != nil || wrote != n {
154 panic(http.ErrAbortHandler)
155 }
156 part = part[n:]
157 }
158 }
159 return nil
160}
161