gunk-dev/the-valley

server.go

source9787759f09camain's published tip history
8.9 KiB
1// Package server is the web UI's read side. It serves the active export
2// of a receiver's state directory to anonymous readers: the plan page,
3// each knot, and a source browser over each public project's main.
4//
5// # Snapshots
6//
7// Every request opens the store's active generation once, with
8// export.Store.Open, and serves its whole response from that generation.
9// It releases the generation when the response is written. An activation
10// during the request changes nothing the request reads.
11//
12// # Routes
13//
14// The server answers GET and HEAD alone:
15//
16// / the plan page
17// /knots/<project>/<id> one knot, with its body and comments
18// /source/<project>/ a redirect to the tree at main's tip
19// /source/<project>/tree/<commit>/<path> a directory and its README
20// /source/<project>/blob/<commit>/<path> a file
21// /source/<project>/log/<commit> the history that ends at a commit
22//
23// Every source link names its project, a full commit ID and a path. A
24// commit is served only when export.Reachable finds it reachable from the
25// project's published source tip, and a path is resolved one tree entry
26// at a time from that commit's tree, so no other object can be named.
27//
28// # Access
29//
30// Every route checks that the export holds its project as public. A
31// project it does not hold answers exactly as a project that does not
32// exist: every 404 is the same page.
33//
34// # Safety
35//
36// Every page is rendered on the server with html/template, so everything
37// read from the export or a repository is escaped. Each response carries
38// a strict Content-Security-Policy: default-src 'self', and one inline
39// stylesheet and one inline script admitted by their SHA-256 hashes. No
40// repository file is served as itself: a file is shown as escaped text,
41// and a binary file or one larger than MaxFile is not shown at all.
42package server
43
44import (
45 "context"
46 "errors"
47 "log"
48 "net/http"
49 "net/url"
50 "strings"
51 "sync"
52 "time"
53
54 "the-valley/webui/export"
55)
56
57// StaleAfter is how old an export may be before its pages mark it stale.
58const StaleAfter = 5 * time.Minute
59
60// The bounds on what one request reads from a repository.
61const (
62 // MaxFile is the largest file a page shows, README or otherwise.
63 MaxFile = 1 << 20
64 // MaxLines is the most lines of a file a page shows.
65 MaxLines = 10_000
66 // MaxShown is the most bytes a page spends on a file's text once it
67 // is escaped, counting each line's markup on a file page. A page
68 // stops at the line that would take it past MaxShown.
69 MaxShown = 2 << 20
70 // MaxEntries is the most entries a directory page lists.
71 MaxEntries = 1000
72 // MaxRead is the most bytes of output a page reads from one git
73 // listing: a directory's entries, or a page of history. git is
74 // stopped once it prints more.
75 MaxRead = 4 << 20
76 // MaxDepth is the most path segments a source route takes.
77 MaxDepth = 64
78 // MaxPlanDepth is the most levels of knots a milestone's tree
79 // shows, and the most parents a knot's trail names.
80 MaxPlanDepth = 32
81 // LogPage is the number of commits on one page of a log.
82 LogPage = 50
83 // MaxGit is the most source requests that run git at once. Others
84 // wait for one to finish.
85 MaxGit = 8
86 // gitTimeout bounds the git commands of one request.
87 gitTimeout = 15 * time.Second
88)
89
90// Config is what a Server serves from.
91type Config struct {
92 // Store is the receiver's state directory.
93 Store *export.Store
94 // Now is the clock an export's age is read against. Nil is time.Now.
95 Now func() time.Time
96 // Log is told of each failure a reader sees only as an error page.
97 // Nil logs with the standard logger.
98 Log func(error)
99}
100
101// Server is the read side's HTTP handler.
102type Server struct {
103 store *export.Store
104 now func() time.Time
105 log func(error)
106 git chan struct{}
107
108 mu sync.Mutex
109 cached *snapshot
110
111 // opened, when set, is called with each generation a request opens,
112 // before the request reads anything from it.
113 opened func(export.Generation)
114}
115
116// New is a Server over c's store.
117func New(c Config) *Server {
118 s := &Server{store: c.Store, now: c.Now, log: c.Log, git: make(chan struct{}, MaxGit)}
119 if s.now == nil {
120 s.now = time.Now
121 }
122 if s.log == nil {
123 s.log = func(err error) { log.Print(err) }
124 }
125 return s
126}
127
128// snapshot is one generation's export, decoded, and its index. A
129// generation is immutable once active, and its directory names its
130// sequence, so a snapshot is kept for as long as its generation is the
131// one requests open.
132type snapshot struct {
133 dir string
134 e *export.Export
135 idx *index
136}
137
138// request is one request, and the generation it serves from.
139type request struct {
140 s *Server
141 w http.ResponseWriter
142 r *http.Request
143 g export.Generation
144 e *export.Export
145 idx *index
146 now time.Time
147}
148
149func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
150 setHeaders(w.Header())
151 q := &request{s: s, w: w, r: r, now: s.now()}
152 if r.Method != http.MethodGet && r.Method != http.MethodHead {
153 w.Header().Set("Allow", "GET, HEAD")
154 q.page(http.StatusMethodNotAllowed, "error", "Method not allowed", errorPage{
155 Heading: "Method not allowed", Text: "This server answers GET and HEAD alone.",
156 })
157 return
158 }
159 g, release, err := s.store.Open()
160 defer release()
161 if errors.Is(err, export.ErrNoExport) {
162 q.page(http.StatusServiceUnavailable, "error", "Nothing published", errorPage{
163 Heading: "Nothing published yet", Text: "No export has been activated on this server.",
164 })
165 return
166 }
167 if err != nil {
168 q.fail(err)
169 return
170 }
171 if s.opened != nil {
172 s.opened(g)
173 }
174 snap, err := s.snapshot(g)
175 if err != nil {
176 q.fail(err)
177 return
178 }
179 q.g, q.e, q.idx = g, snap.e, snap.idx
180 q.route()
181}
182
183// snapshot reads the generation's export, or keeps the one read last when
184// it is the same generation's.
185func (s *Server) snapshot(g export.Generation) (*snapshot, error) {
186 s.mu.Lock()
187 cached := s.cached
188 s.mu.Unlock()
189 if cached != nil && cached.dir == g.Dir {
190 return cached, nil
191 }
192 e, err := g.Export()
193 if err != nil {
194 return nil, err
195 }
196 snap := &snapshot{dir: g.Dir, e: e, idx: newIndex(e)}
197 s.mu.Lock()
198 s.cached = snap
199 s.mu.Unlock()
200 return snap, nil
201}
202
203// route dispatches on the path's segments, each unescaped on its own, so
204// an escaped slash stays inside its segment.
205func (q *request) route() {
206 parts, ok := segments(q.r.URL.EscapedPath())
207 switch {
208 case !ok:
209 q.notFound()
210 case len(parts) == 1 && parts[0] == "":
211 q.plan()
212 case len(parts) == 3 && parts[0] == "knots":
213 q.knot(parts[1], parts[2])
214 case len(parts) >= 2 && parts[0] == "source":
215 q.source(parts[1], parts[2:])
216 default:
217 q.notFound()
218 }
219}
220
221func segments(escaped string) ([]string, bool) {
222 rest, ok := strings.CutPrefix(escaped, "/")
223 if !ok {
224 return nil, false
225 }
226 parts := strings.Split(rest, "/")
227 for i, p := range parts {
228 u, err := url.PathUnescape(p)
229 if err != nil {
230 return nil, false
231 }
232 parts[i] = u
233 }
234 return parts, true
235}
236
237// project is the export's project called name, when the export holds it
238// as public. Every route that names a project asks here first, and a
239// project it refuses answers as one that does not exist.
240func (q *request) project(name string) (*export.Project, bool) { return q.idx.project(name) }
241
242func (idx *index) project(name string) (*export.Project, bool) {
243 p, ok := idx.projects[name]
244 if !ok || p.Visibility != export.Public {
245 return nil, false
246 }
247 return p, true
248}
249
250// notFound is the one 404 page, whatever was not found. It names nothing
251// of the request, so a hidden project, a missing one, an unreachable
252// commit and a missing path all answer alike.
253func (q *request) notFound() {
254 q.page(http.StatusNotFound, "error", "Not found", errorPage{
255 Heading: "Not found", Text: "Nothing is published at this address.",
256 })
257}
258
259// fail logs err and answers with the one 500 page, which says nothing of
260// the failure. A reader that went away is answered with nothing: git
261// killed for it fails, and that is no failure of the server's.
262func (q *request) fail(err error) {
263 if q.r.Context().Err() != nil {
264 return
265 }
266 q.s.log(err)
267 q.page(http.StatusInternalServerError, "error", "Error", errorPage{
268 Heading: "Something went wrong", Text: "The server could not read this page.",
269 })
270}
271
272// gitContext is the context the request's git commands run under. It
273// waits for one of the MaxGit slots, and done gives the slot back.
274func (q *request) gitContext() (ctx context.Context, done func(), err error) {
275 select {
276 case q.s.git <- struct{}{}:
277 case <-q.r.Context().Done():
278 return nil, func() {}, q.r.Context().Err()
279 }
280 ctx, cancel := context.WithTimeout(q.r.Context(), gitTimeout)
281 return ctx, func() { cancel(); <-q.s.git }, nil
282}
283
284// setHeaders sets the headers every response carries.
285func setHeaders(h http.Header) {
286 h.Set("Content-Security-Policy", csp)
287 h.Set("X-Content-Type-Options", "nosniff")
288 h.Set("X-Frame-Options", "DENY")
289 h.Set("Referrer-Policy", "no-referrer")
290 h.Set("Cross-Origin-Opener-Policy", "same-origin")
291 h.Set("Cross-Origin-Resource-Policy", "same-origin")
292 h.Set("Cache-Control", "no-cache")
293}