gunk-dev/the-valley

server.go

sourceabcc65061e04main's published tip history
8.2 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 // MaxEntries is the most entries a directory page lists.
65 MaxEntries = 1000
66 // MaxDepth is the most path segments a source route takes.
67 MaxDepth = 64
68 // LogPage is the number of commits on one page of a log.
69 LogPage = 50
70 // MaxGit is the most source requests that run git at once. Others
71 // wait for one to finish.
72 MaxGit = 8
73 // gitTimeout bounds the git commands of one request.
74 gitTimeout = 15 * time.Second
75)
76
77// Config is what a Server serves from.
78type Config struct {
79 // Store is the receiver's state directory.
80 Store *export.Store
81 // Now is the clock an export's age is read against. Nil is time.Now.
82 Now func() time.Time
83 // Log is told of each failure a reader sees only as an error page.
84 // Nil logs with the standard logger.
85 Log func(error)
86}
87
88// Server is the read side's HTTP handler.
89type Server struct {
90 store *export.Store
91 now func() time.Time
92 log func(error)
93 git chan struct{}
94
95 mu sync.Mutex
96 cached *snapshot
97
98 // opened, when set, is called with each generation a request opens,
99 // before the request reads anything from it.
100 opened func(export.Generation)
101}
102
103// New is a Server over c's store.
104func New(c Config) *Server {
105 s := &Server{store: c.Store, now: c.Now, log: c.Log, git: make(chan struct{}, MaxGit)}
106 if s.now == nil {
107 s.now = time.Now
108 }
109 if s.log == nil {
110 s.log = func(err error) { log.Print(err) }
111 }
112 return s
113}
114
115// snapshot is one generation's export, decoded, and its index. A
116// generation is immutable once active, and its directory names its
117// sequence, so a snapshot is kept for as long as its generation is the
118// one requests open.
119type snapshot struct {
120 dir string
121 e *export.Export
122 idx *index
123}
124
125// request is one request, and the generation it serves from.
126type request struct {
127 s *Server
128 w http.ResponseWriter
129 r *http.Request
130 g export.Generation
131 e *export.Export
132 idx *index
133 now time.Time
134}
135
136func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
137 setHeaders(w.Header())
138 q := &request{s: s, w: w, r: r, now: s.now()}
139 if r.Method != http.MethodGet && r.Method != http.MethodHead {
140 w.Header().Set("Allow", "GET, HEAD")
141 q.page(http.StatusMethodNotAllowed, "error", "Method not allowed", errorPage{
142 Heading: "Method not allowed", Text: "This server answers GET and HEAD alone.",
143 })
144 return
145 }
146 g, release, err := s.store.Open()
147 defer release()
148 if errors.Is(err, export.ErrNoExport) {
149 q.page(http.StatusServiceUnavailable, "error", "Nothing published", errorPage{
150 Heading: "Nothing published yet", Text: "No export has been activated on this server.",
151 })
152 return
153 }
154 if err != nil {
155 q.fail(err)
156 return
157 }
158 if s.opened != nil {
159 s.opened(g)
160 }
161 snap, err := s.snapshot(g)
162 if err != nil {
163 q.fail(err)
164 return
165 }
166 q.g, q.e, q.idx = g, snap.e, snap.idx
167 q.route()
168}
169
170// snapshot reads the generation's export, or keeps the one read last when
171// it is the same generation's.
172func (s *Server) snapshot(g export.Generation) (*snapshot, error) {
173 s.mu.Lock()
174 cached := s.cached
175 s.mu.Unlock()
176 if cached != nil && cached.dir == g.Dir {
177 return cached, nil
178 }
179 e, err := g.Export()
180 if err != nil {
181 return nil, err
182 }
183 snap := &snapshot{dir: g.Dir, e: e, idx: newIndex(e)}
184 s.mu.Lock()
185 s.cached = snap
186 s.mu.Unlock()
187 return snap, nil
188}
189
190// route dispatches on the path's segments, each unescaped on its own, so
191// an escaped slash stays inside its segment.
192func (q *request) route() {
193 parts, ok := segments(q.r.URL.EscapedPath())
194 switch {
195 case !ok:
196 q.notFound()
197 case len(parts) == 1 && parts[0] == "":
198 q.plan()
199 case len(parts) == 3 && parts[0] == "knots":
200 q.knot(parts[1], parts[2])
201 case len(parts) >= 2 && parts[0] == "source":
202 q.source(parts[1], parts[2:])
203 default:
204 q.notFound()
205 }
206}
207
208func segments(escaped string) ([]string, bool) {
209 rest, ok := strings.CutPrefix(escaped, "/")
210 if !ok {
211 return nil, false
212 }
213 parts := strings.Split(rest, "/")
214 for i, p := range parts {
215 u, err := url.PathUnescape(p)
216 if err != nil {
217 return nil, false
218 }
219 parts[i] = u
220 }
221 return parts, true
222}
223
224// project is the export's project called name, when the export holds it
225// as public. Every route that names a project asks here first, and a
226// project it refuses answers as one that does not exist.
227func (q *request) project(name string) (*export.Project, bool) {
228 p, ok := q.idx.projects[name]
229 if !ok || p.Visibility != export.Public {
230 return nil, false
231 }
232 return p, true
233}
234
235// notFound is the one 404 page, whatever was not found. It names nothing
236// of the request, so a hidden project, a missing one, an unreachable
237// commit and a missing path all answer alike.
238func (q *request) notFound() {
239 q.page(http.StatusNotFound, "error", "Not found", errorPage{
240 Heading: "Not found", Text: "Nothing is published at this address.",
241 })
242}
243
244// fail logs err and answers with the one 500 page, which says nothing of
245// the failure. A reader that went away is answered with nothing: git
246// killed for it fails, and that is no failure of the server's.
247func (q *request) fail(err error) {
248 if q.r.Context().Err() != nil {
249 return
250 }
251 q.s.log(err)
252 q.page(http.StatusInternalServerError, "error", "Error", errorPage{
253 Heading: "Something went wrong", Text: "The server could not read this page.",
254 })
255}
256
257// gitContext is the context the request's git commands run under. It
258// waits for one of the MaxGit slots, and done gives the slot back.
259func (q *request) gitContext() (ctx context.Context, done func(), err error) {
260 select {
261 case q.s.git <- struct{}{}:
262 case <-q.r.Context().Done():
263 return nil, func() {}, q.r.Context().Err()
264 }
265 ctx, cancel := context.WithTimeout(q.r.Context(), gitTimeout)
266 return ctx, func() { cancel(); <-q.s.git }, nil
267}
268
269// setHeaders sets the headers every response carries.
270func setHeaders(h http.Header) {
271 h.Set("Content-Security-Policy", csp)
272 h.Set("X-Content-Type-Options", "nosniff")
273 h.Set("X-Frame-Options", "DENY")
274 h.Set("Referrer-Policy", "no-referrer")
275 h.Set("Cross-Origin-Opener-Policy", "same-origin")
276 h.Set("Cross-Origin-Resource-Policy", "same-origin")
277 h.Set("Cache-Control", "no-cache")
278}