gunk-dev/the-valley

server.go

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