| 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 renders its whole response from that |
| 9 | // generation. An activation during the request changes nothing the |
| 10 | // request reads. Each generation's export is read once, however many |
| 11 | // requests open it at once, and is kept while the generation is the |
| 12 | // newest one read. |
| 13 | // |
| 14 | // # Admission |
| 15 | // |
| 16 | // A source request runs git, and at most MaxGit run at once. A source |
| 17 | // request takes one of those slots before it opens a generation, and |
| 18 | // waits for one only while fewer than MaxWaiting wait. Its time is |
| 19 | // bounded from when it arrives: the wait, its git commands and its |
| 20 | // rendering. A source request the server cannot admit, or that runs out |
| 21 | // of time, answers 503. |
| 22 | // |
| 23 | // A response is rendered whole before it is written. A request gives back |
| 24 | // its generation and its git slot before it writes, so a reader that |
| 25 | // reads slowly holds neither. |
| 26 | // |
| 27 | // # Routes |
| 28 | // |
| 29 | // The server answers GET and HEAD alone: |
| 30 | // |
| 31 | // / the plan page |
| 32 | // /knots/<project>/<id> one knot, with its body and comments |
| 33 | // /source/<project>/ a redirect to the tree at main's tip |
| 34 | // /source/<project>/tree/<commit>/<path> a directory and its README |
| 35 | // /source/<project>/blob/<commit>/<path> a file |
| 36 | // /source/<project>/log/<commit> the history that ends at a commit |
| 37 | // |
| 38 | // Every source link names its project, a full commit ID and a path. A |
| 39 | // commit is served only when export.Reachable finds it reachable from the |
| 40 | // project's published source tip, and a path is resolved one tree entry |
| 41 | // at a time from that commit's tree, so no other object can be named. |
| 42 | // |
| 43 | // # Access |
| 44 | // |
| 45 | // Every route checks that the export holds its project as public. A |
| 46 | // project it does not hold answers exactly as a project that does not |
| 47 | // exist: every 404 is the same page. |
| 48 | // |
| 49 | // # Safety |
| 50 | // |
| 51 | // Every page is rendered on the server with html/template, so everything |
| 52 | // read from the export or a repository is escaped. Each response carries |
| 53 | // a strict Content-Security-Policy: default-src 'self', and one inline |
| 54 | // stylesheet and one inline script admitted by their SHA-256 hashes. No |
| 55 | // repository file is served as itself: a file is shown as escaped text, |
| 56 | // and a binary file or one larger than MaxFile is not shown at all. |
| 57 | package server |
| 58 | |
| 59 | import ( |
| 60 | "context" |
| 61 | "errors" |
| 62 | "log" |
| 63 | "net/http" |
| 64 | "net/url" |
| 65 | "strconv" |
| 66 | "strings" |
| 67 | "sync" |
| 68 | "time" |
| 69 | |
| 70 | "the-valley/webui/export" |
| 71 | ) |
| 72 | |
| 73 | // StaleAfter is how old an export may be before its pages mark it stale. |
| 74 | const StaleAfter = 5 * time.Minute |
| 75 | |
| 76 | // The bounds on what one request reads from a repository. |
| 77 | const ( |
| 78 | // MaxFile is the largest file a page shows, README or otherwise. |
| 79 | MaxFile = 1 << 20 |
| 80 | // MaxLines is the most lines of a file a page shows. |
| 81 | MaxLines = 10_000 |
| 82 | // MaxShown is the most bytes a page spends on a file's text once it |
| 83 | // is escaped, counting each line's markup on a file page. A page |
| 84 | // stops at the line that would take it past MaxShown. |
| 85 | MaxShown = 2 << 20 |
| 86 | // MaxEntries is the most entries a directory page lists. |
| 87 | MaxEntries = 1000 |
| 88 | // MaxRead is the most bytes of output a page reads from one git |
| 89 | // listing: a directory's entries, or a page of history. git is |
| 90 | // stopped once it prints more. |
| 91 | MaxRead = 4 << 20 |
| 92 | // MaxDepth is the most path segments a source route takes. |
| 93 | MaxDepth = 64 |
| 94 | // MaxPlanDepth is the most levels of knots a milestone's tree |
| 95 | // shows, and the most parents a knot's trail names. |
| 96 | MaxPlanDepth = 32 |
| 97 | // LogPage is the number of commits on one page of a log. |
| 98 | LogPage = 50 |
| 99 | // MaxGit is the most source requests that run git at once. |
| 100 | MaxGit = 8 |
| 101 | // MaxWaiting is the most source requests that wait for one of the |
| 102 | // MaxGit to finish. A source request that finds every slot taken |
| 103 | // and MaxWaiting waiting answers 503 at once. |
| 104 | MaxWaiting = 16 |
| 105 | // gitTimeout bounds a source request from when it arrives: its wait |
| 106 | // for a slot, its git commands and its rendering. |
| 107 | gitTimeout = 15 * time.Second |
| 108 | // MaxLoads is the most generations whose export is read at once. |
| 109 | MaxLoads = 2 |
| 110 | ) |
| 111 | |
| 112 | // Config is what a Server serves from. |
| 113 | type Config struct { |
| 114 | // Store is the receiver's state directory. |
| 115 | Store *export.Store |
| 116 | // Now is the clock an export's age is read against. Nil is time.Now. |
| 117 | Now func() time.Time |
| 118 | // Log is told of each failure a reader sees only as an error page. |
| 119 | // Nil logs with the standard logger. |
| 120 | Log func(error) |
| 121 | } |
| 122 | |
| 123 | // Server is the read side's HTTP handler. |
| 124 | type Server struct { |
| 125 | store *export.Store |
| 126 | now func() time.Time |
| 127 | log func(error) |
| 128 | // timeout is gitTimeout, which a test shortens. |
| 129 | timeout time.Duration |
| 130 | // slots holds a token for each source request running git, and |
| 131 | // waiting one for each source request waiting for a slot. |
| 132 | slots chan struct{} |
| 133 | waiting chan struct{} |
| 134 | // loaders holds a token for each export being read. |
| 135 | loaders chan struct{} |
| 136 | |
| 137 | mu sync.Mutex |
| 138 | // cached is the newest generation's snapshot read so far. |
| 139 | cached *snapshot |
| 140 | // loads are the reads of generations' exports under way, by sequence. |
| 141 | loads map[int64]*load |
| 142 | |
| 143 | // The test hooks. opened, when set, is called with each generation a |
| 144 | // request opens, before the request reads anything from it. admitted |
| 145 | // is called when a source request takes a git slot, before it opens |
| 146 | // a generation. loading is called with each generation whose export |
| 147 | // is read, before it is read. |
| 148 | opened func(export.Generation) |
| 149 | admitted func() |
| 150 | loading func(export.Generation) |
| 151 | } |
| 152 | |
| 153 | // New is a Server over c's store. |
| 154 | func New(c Config) *Server { |
| 155 | s := &Server{store: c.Store, now: c.Now, log: c.Log, timeout: gitTimeout, |
| 156 | slots: make(chan struct{}, MaxGit), waiting: make(chan struct{}, MaxWaiting), |
| 157 | loaders: make(chan struct{}, MaxLoads), loads: map[int64]*load{}} |
| 158 | if s.now == nil { |
| 159 | s.now = time.Now |
| 160 | } |
| 161 | if s.log == nil { |
| 162 | s.log = func(err error) { log.Print(err) } |
| 163 | } |
| 164 | return s |
| 165 | } |
| 166 | |
| 167 | // snapshot is one generation's export, decoded, and its index. A |
| 168 | // generation is immutable once active, and its sequence names it, so a |
| 169 | // snapshot serves every request that opens its generation. |
| 170 | type snapshot struct { |
| 171 | seq int64 |
| 172 | e *export.Export |
| 173 | idx *index |
| 174 | } |
| 175 | |
| 176 | // load is one read of a generation's export, which every request that |
| 177 | // opens the generation while it runs waits for. |
| 178 | type load struct { |
| 179 | done chan struct{} |
| 180 | snap *snapshot |
| 181 | err error |
| 182 | } |
| 183 | |
| 184 | // request is one request, the generation it serves from, and the |
| 185 | // response it renders. |
| 186 | type request struct { |
| 187 | s *Server |
| 188 | w http.ResponseWriter |
| 189 | r *http.Request |
| 190 | // ctx is the context the request's git commands run under. A source |
| 191 | // request's ends at its deadline. |
| 192 | ctx context.Context |
| 193 | g export.Generation |
| 194 | e *export.Export |
| 195 | idx *index |
| 196 | now time.Time |
| 197 | |
| 198 | // The response: a status and a page, or a redirect. It is written |
| 199 | // once the request has given back its generation and git slot. |
| 200 | status int |
| 201 | ctype string |
| 202 | body []byte |
| 203 | location string |
| 204 | } |
| 205 | |
| 206 | func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 207 | setHeaders(w.Header()) |
| 208 | q := &request{s: s, w: w, r: r, ctx: r.Context(), now: s.now()} |
| 209 | q.serve() |
| 210 | q.write() |
| 211 | } |
| 212 | |
| 213 | // serve renders the request's response. A source request is admitted |
| 214 | // first, and holds its git slot until serve returns. Every request holds |
| 215 | // its generation until serve returns. |
| 216 | func (q *request) serve() { |
| 217 | if q.r.Method != http.MethodGet && q.r.Method != http.MethodHead { |
| 218 | q.w.Header().Set("Allow", "GET, HEAD") |
| 219 | q.page(http.StatusMethodNotAllowed, "error", "Method not allowed", errorPage{ |
| 220 | Heading: "Method not allowed", Text: "This server answers GET and HEAD alone.", |
| 221 | }) |
| 222 | return |
| 223 | } |
| 224 | parts, ok := segments(q.r.URL.EscapedPath()) |
| 225 | if ok && runsGit(parts) { |
| 226 | ctx, cancel := context.WithTimeout(q.r.Context(), q.s.timeout) |
| 227 | defer cancel() |
| 228 | done, admitted := q.s.admit(ctx) |
| 229 | if !admitted { |
| 230 | q.busy() |
| 231 | return |
| 232 | } |
| 233 | defer done() |
| 234 | q.ctx = ctx |
| 235 | if q.s.admitted != nil { |
| 236 | q.s.admitted() |
| 237 | } |
| 238 | } |
| 239 | g, release, err := q.s.store.Open() |
| 240 | defer release() |
| 241 | if errors.Is(err, export.ErrNoExport) { |
| 242 | q.page(http.StatusServiceUnavailable, "error", "Nothing published", errorPage{ |
| 243 | Heading: "Nothing published yet", Text: "No export has been activated on this server.", |
| 244 | }) |
| 245 | return |
| 246 | } |
| 247 | if err != nil { |
| 248 | q.fail(err) |
| 249 | return |
| 250 | } |
| 251 | if q.s.opened != nil { |
| 252 | q.s.opened(g) |
| 253 | } |
| 254 | snap, err := q.s.snapshot(q.ctx, g) |
| 255 | if err != nil { |
| 256 | q.fail(err) |
| 257 | return |
| 258 | } |
| 259 | q.g, q.e, q.idx = g, snap.e, snap.idx |
| 260 | q.route(parts, ok) |
| 261 | } |
| 262 | |
| 263 | // runsGit reports whether a path is a source route that reads a |
| 264 | // repository: a tree, a file or a log. |
| 265 | func runsGit(parts []string) bool { |
| 266 | return len(parts) >= 3 && parts[0] == "source" && (parts[2] == "tree" || parts[2] == "blob" || parts[2] == "log") |
| 267 | } |
| 268 | |
| 269 | // admit takes a git slot for a source request. When every slot is taken, |
| 270 | // it waits for one until ctx is done, unless MaxWaiting requests wait |
| 271 | // already. done gives the slot back. |
| 272 | func (s *Server) admit(ctx context.Context) (done func(), ok bool) { |
| 273 | give := func() { <-s.slots } |
| 274 | select { |
| 275 | case s.slots <- struct{}{}: |
| 276 | return give, true |
| 277 | default: |
| 278 | } |
| 279 | select { |
| 280 | case s.waiting <- struct{}{}: |
| 281 | default: |
| 282 | return nil, false |
| 283 | } |
| 284 | defer func() { <-s.waiting }() |
| 285 | select { |
| 286 | case s.slots <- struct{}{}: |
| 287 | return give, true |
| 288 | case <-ctx.Done(): |
| 289 | return nil, false |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | // snapshot is the generation's snapshot: the cached one when it is the |
| 294 | // generation's, and otherwise the one a single read of the generation's |
| 295 | // export gives every request that waits for it. A request stops waiting |
| 296 | // when ctx is done. At most MaxLoads exports are read at once. A read is |
| 297 | // kept only when its generation is newer than the cached one, so a |
| 298 | // request still serving an older generation never displaces a newer. |
| 299 | func (s *Server) snapshot(ctx context.Context, g export.Generation) (*snapshot, error) { |
| 300 | s.mu.Lock() |
| 301 | if c := s.cached; c != nil && c.seq == g.Sequence { |
| 302 | s.mu.Unlock() |
| 303 | return c, nil |
| 304 | } |
| 305 | l, ok := s.loads[g.Sequence] |
| 306 | if !ok { |
| 307 | l = &load{done: make(chan struct{})} |
| 308 | s.loads[g.Sequence] = l |
| 309 | go s.load(g, l) |
| 310 | } |
| 311 | s.mu.Unlock() |
| 312 | select { |
| 313 | case <-l.done: |
| 314 | return l.snap, l.err |
| 315 | case <-ctx.Done(): |
| 316 | return nil, ctx.Err() |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | // load reads g's export for every request waiting on l. It reads while |
| 321 | // those requests hold g open. Should they all go away first, an |
| 322 | // activation may delete g, and the read fails, for no one. |
| 323 | func (s *Server) load(g export.Generation, l *load) { |
| 324 | s.loaders <- struct{}{} |
| 325 | defer func() { <-s.loaders }() |
| 326 | if s.loading != nil { |
| 327 | s.loading(g) |
| 328 | } |
| 329 | e, err := g.Export() |
| 330 | if err == nil { |
| 331 | l.snap = &snapshot{seq: g.Sequence, e: e, idx: newIndex(e)} |
| 332 | } |
| 333 | l.err = err |
| 334 | s.mu.Lock() |
| 335 | delete(s.loads, g.Sequence) |
| 336 | if l.snap != nil && (s.cached == nil || s.cached.seq < g.Sequence) { |
| 337 | s.cached = l.snap |
| 338 | } |
| 339 | s.mu.Unlock() |
| 340 | close(l.done) |
| 341 | } |
| 342 | |
| 343 | // route dispatches on the path's segments, each unescaped on its own, so |
| 344 | // an escaped slash stays inside its segment. ok is false for a path whose |
| 345 | // segments do not unescape. |
| 346 | func (q *request) route(parts []string, ok bool) { |
| 347 | switch { |
| 348 | case !ok: |
| 349 | q.notFound() |
| 350 | case len(parts) == 1 && parts[0] == "": |
| 351 | q.plan() |
| 352 | case len(parts) == 3 && parts[0] == "knots": |
| 353 | q.knot(parts[1], parts[2]) |
| 354 | case len(parts) >= 2 && parts[0] == "source": |
| 355 | q.source(parts[1], parts[2:]) |
| 356 | default: |
| 357 | q.notFound() |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | func segments(escaped string) ([]string, bool) { |
| 362 | rest, ok := strings.CutPrefix(escaped, "/") |
| 363 | if !ok { |
| 364 | return nil, false |
| 365 | } |
| 366 | parts := strings.Split(rest, "/") |
| 367 | for i, p := range parts { |
| 368 | u, err := url.PathUnescape(p) |
| 369 | if err != nil { |
| 370 | return nil, false |
| 371 | } |
| 372 | parts[i] = u |
| 373 | } |
| 374 | return parts, true |
| 375 | } |
| 376 | |
| 377 | // project is the export's project called name, when the export holds it |
| 378 | // as public. Every route that names a project asks here first, and a |
| 379 | // project it refuses answers as one that does not exist. |
| 380 | func (q *request) project(name string) (*export.Project, bool) { return q.idx.project(name) } |
| 381 | |
| 382 | func (idx *index) project(name string) (*export.Project, bool) { |
| 383 | p, ok := idx.projects[name] |
| 384 | if !ok || p.Visibility != export.Public { |
| 385 | return nil, false |
| 386 | } |
| 387 | return p, true |
| 388 | } |
| 389 | |
| 390 | // notFound is the one 404 page, whatever was not found. It names nothing |
| 391 | // of the request, so a hidden project, a missing one, an unreachable |
| 392 | // commit and a missing path all answer alike. |
| 393 | func (q *request) notFound() { |
| 394 | q.page(http.StatusNotFound, "error", "Not found", errorPage{ |
| 395 | Heading: "Not found", Text: "Nothing is published at this address.", |
| 396 | }) |
| 397 | } |
| 398 | |
| 399 | // fail logs err and answers with the one 500 page, which says nothing of |
| 400 | // the failure. A reader that went away is answered with nothing: git |
| 401 | // killed for it fails, and that is no failure of the server's. A source |
| 402 | // request that ran out of time answers 503. |
| 403 | func (q *request) fail(err error) { |
| 404 | if q.r.Context().Err() != nil { |
| 405 | return |
| 406 | } |
| 407 | q.s.log(err) |
| 408 | if q.ctx.Err() != nil { |
| 409 | q.busy() |
| 410 | return |
| 411 | } |
| 412 | q.page(http.StatusInternalServerError, "error", "Error", errorPage{ |
| 413 | Heading: "Something went wrong", Text: "The server could not read this page.", |
| 414 | }) |
| 415 | } |
| 416 | |
| 417 | // busy answers a source request the server has no time for: it could not |
| 418 | // be admitted, or it ran out of time. A reader that went away is answered |
| 419 | // with nothing. |
| 420 | func (q *request) busy() { |
| 421 | if q.r.Context().Err() != nil { |
| 422 | return |
| 423 | } |
| 424 | q.w.Header().Set("Retry-After", "5") |
| 425 | q.page(http.StatusServiceUnavailable, "error", "Busy", errorPage{ |
| 426 | Heading: "Busy", Text: "The server is reading too many pages at once. Try again in a few seconds.", |
| 427 | }) |
| 428 | } |
| 429 | |
| 430 | // redirect answers with a redirect to url. |
| 431 | func (q *request) redirect(url string) { q.location = url } |
| 432 | |
| 433 | // write writes the rendered response, or nothing for a reader that went |
| 434 | // away. |
| 435 | func (q *request) write() { |
| 436 | switch { |
| 437 | case q.location != "": |
| 438 | http.Redirect(q.w, q.r, q.location, http.StatusFound) |
| 439 | case q.status != 0: |
| 440 | h := q.w.Header() |
| 441 | h.Set("Content-Type", q.ctype) |
| 442 | h.Set("Content-Length", strconv.Itoa(len(q.body))) |
| 443 | q.w.WriteHeader(q.status) |
| 444 | q.w.Write(q.body) |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | // setHeaders sets the headers every response carries. |
| 449 | func setHeaders(h http.Header) { |
| 450 | h.Set("Content-Security-Policy", csp) |
| 451 | h.Set("X-Content-Type-Options", "nosniff") |
| 452 | h.Set("X-Frame-Options", "DENY") |
| 453 | h.Set("Referrer-Policy", "no-referrer") |
| 454 | h.Set("Cross-Origin-Opener-Policy", "same-origin") |
| 455 | h.Set("Cross-Origin-Resource-Policy", "same-origin") |
| 456 | h.Set("Cache-Control", "no-cache") |
| 457 | } |