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