| 1 | package server |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "embed" |
| 8 | "encoding/base64" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "html/template" |
| 12 | "net/http" |
| 13 | "strconv" |
| 14 | "strings" |
| 15 | "time" |
| 16 | ) |
| 17 | |
| 18 | // The pages' templates, and the one stylesheet and one script they carry |
| 19 | // inline. Nothing else is served: no font, image or script is fetched. |
| 20 | var ( |
| 21 | //go:embed templates/*.tmpl |
| 22 | templateFiles embed.FS |
| 23 | //go:embed assets/style.css |
| 24 | styleCSS string |
| 25 | //go:embed assets/plan.js |
| 26 | planJS string |
| 27 | ) |
| 28 | |
| 29 | // The Content-Security-Policy of each route. Every policy admits the |
| 30 | // inline stylesheet by its SHA-256 hash, fetches nothing from another |
| 31 | // origin, opens no connection from a script, and takes no plugin, base |
| 32 | // URL, form submission or frame. The knots page's policy admits its one |
| 33 | // inline script by its hash; every other route's admits no script at all. |
| 34 | // An error page answers with its route's policy. |
| 35 | var ( |
| 36 | knotsPolicy = policy("script-src " + inlineHash(planJS)) |
| 37 | contentPolicy = policy("script-src 'none'") |
| 38 | ) |
| 39 | |
| 40 | func policy(scripts string) string { |
| 41 | return "default-src 'self'; " + scripts + "; style-src " + inlineHash(styleCSS) + |
| 42 | "; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" |
| 43 | } |
| 44 | |
| 45 | // policyFor is the policy of the route a path's segments name: the knots |
| 46 | // page's for /-/knots, and every other route's for the rest. |
| 47 | func policyFor(parts []string, ok bool) string { |
| 48 | if ok && isKnotsPage(parts) { |
| 49 | return knotsPolicy |
| 50 | } |
| 51 | return contentPolicy |
| 52 | } |
| 53 | |
| 54 | func inlineHash(s string) string { |
| 55 | sum := sha256.Sum256([]byte(s)) |
| 56 | return "'sha256-" + base64.StdEncoding.EncodeToString(sum[:]) + "'" |
| 57 | } |
| 58 | |
| 59 | var pages = parsePages("plan", "knot", "tree", "blob", "log", "error", "notfound") |
| 60 | |
| 61 | // parsePages parses each page's template over the shared layout. |
| 62 | func parsePages(names ...string) map[string]*template.Template { |
| 63 | funcs := template.FuncMap{"glyph": glyphClass, "label": stateLabel, "inc": func(i int) int { return i + 1 }} |
| 64 | base := template.Must(template.New("layout").Funcs(funcs).ParseFS(templateFiles, "templates/layout.tmpl")) |
| 65 | m := map[string]*template.Template{} |
| 66 | for _, name := range names { |
| 67 | m[name] = template.Must(template.Must(base.Clone()).ParseFS(templateFiles, "templates/"+name+".tmpl")) |
| 68 | } |
| 69 | return m |
| 70 | } |
| 71 | |
| 72 | // layout is what every page shares: its title, the inline stylesheet, the |
| 73 | // script on the knots page alone, the links to the knots page and to |
| 74 | // each project's source, and the export's age. |
| 75 | type layout struct { |
| 76 | Title string |
| 77 | Style template.CSS |
| 78 | Script template.JS |
| 79 | Nav []link |
| 80 | Fresh *freshness |
| 81 | Content any |
| 82 | } |
| 83 | |
| 84 | // errorPage is a page that answers a request with no content of its own. |
| 85 | type errorPage struct { |
| 86 | Heading string |
| 87 | Text string |
| 88 | } |
| 89 | |
| 90 | // link is one link: its text and where it goes. |
| 91 | type link struct { |
| 92 | Text string |
| 93 | URL string |
| 94 | } |
| 95 | |
| 96 | // page renders the page called name with content as the response, to be |
| 97 | // written with status. A page is rendered whole before anything is |
| 98 | // written, so a failure to render answers 500 rather than half a page. A |
| 99 | // page that would pass the server's maxResponse stops rendering there, |
| 100 | // and answers with the short page that says it is too large. A page the |
| 101 | // response budget has no room for, or whose request runs out of time |
| 102 | // while it renders, answers 503. A request runs no git once it renders, |
| 103 | // so it gives back its git slot first. |
| 104 | func (q *request) page(status int, name, title string, content any) { |
| 105 | q.giveSlot() |
| 106 | data := layout{Title: title, Style: template.CSS(styleCSS), Content: content} |
| 107 | if name == "plan" { |
| 108 | data.Script = template.JS(planJS) |
| 109 | } |
| 110 | if q.e != nil { |
| 111 | data.Nav = append(data.Nav, link{"knots", knotsURL}) |
| 112 | for _, name := range q.idx.public { |
| 113 | p := q.idx.projects[name] |
| 114 | data.Nav = append(data.Nav, link{name + " source", treeURL(q.idx.bases[name], p.SourceTip, nil)}) |
| 115 | } |
| 116 | data.Fresh = freshnessOf(q.e.Collected, q.auth.a.Checked, q.now) |
| 117 | } |
| 118 | q.drop() |
| 119 | if q.s.rendering != nil { |
| 120 | q.s.rendering(name) |
| 121 | } |
| 122 | b := &body{s: q.s, ctx: q.ctx} |
| 123 | err := pages[name].ExecuteTemplate(b, "layout", data) |
| 124 | if err == nil { |
| 125 | q.status, q.ctype, q.body = status, htmlType, b |
| 126 | return |
| 127 | } |
| 128 | b.free() |
| 129 | switch { |
| 130 | case errors.Is(err, errNoBudget): |
| 131 | q.busy() |
| 132 | case errors.Is(err, errTooLarge): |
| 133 | q.tooLarge() |
| 134 | case q.ctx.Err() != nil: |
| 135 | q.fail(fmt.Errorf("rendering %s: %w", name, err)) |
| 136 | default: |
| 137 | q.s.log(fmt.Errorf("rendering %s: %w", name, err)) |
| 138 | q.static(http.StatusInternalServerError, "text/plain; charset=utf-8", notRendered) |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | const htmlType = "text/html; charset=utf-8" |
| 143 | |
| 144 | // tooLarge logs a response that would pass the server's maxResponse, and |
| 145 | // answers with the short page that says the page is too large. |
| 146 | func (q *request) tooLarge() { |
| 147 | q.s.log(fmt.Errorf("rendering %q: the page is larger than %d bytes", q.r.URL.EscapedPath(), q.s.maxResponse)) |
| 148 | q.static(http.StatusInternalServerError, htmlType, tooLargePage) |
| 149 | } |
| 150 | |
| 151 | // static answers with a response made once, when the server starts. It |
| 152 | // shows no export, and takes nothing from the budget. |
| 153 | func (q *request) static(status int, ctype string, page []byte) { |
| 154 | q.drop() |
| 155 | q.status, q.ctype, q.body = status, ctype, &body{pieces: [][]byte{page}, n: len(page)} |
| 156 | } |
| 157 | |
| 158 | // drop gives back the pieces of the response the request rendered, if it |
| 159 | // rendered one. |
| 160 | func (q *request) drop() { |
| 161 | if q.body != nil { |
| 162 | q.body.free() |
| 163 | q.body = nil |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | // The responses made once: three pages, and the text that answers a page |
| 168 | // that failed to render. The not-found page is the one every 404 answers |
| 169 | // with. It shows the box of text the operator chose, whose last line |
| 170 | // links to /, and it names no site, no project and nothing of the |
| 171 | // request. |
| 172 | var ( |
| 173 | busyPage = staticPage("error", "Busy", errorPage{ |
| 174 | Heading: "Busy", Text: "The server is serving too many pages at once. Try again in a few seconds.", |
| 175 | }) |
| 176 | tooLargePage = staticPage("error", "Page too large", errorPage{ |
| 177 | Heading: "Page too large", Text: "This page is larger than the server sends.", |
| 178 | }) |
| 179 | notFoundPage = staticPage("notfound", "Not found", nil) |
| 180 | notRendered = []byte("The server could not render this page.\n") |
| 181 | ) |
| 182 | |
| 183 | func staticPage(name, title string, content any) []byte { |
| 184 | var b bytes.Buffer |
| 185 | data := layout{Title: title, Style: template.CSS(styleCSS), Content: content} |
| 186 | if err := pages[name].ExecuteTemplate(&b, "layout", data); err != nil { |
| 187 | panic(err) |
| 188 | } |
| 189 | return b.Bytes() |
| 190 | } |
| 191 | |
| 192 | // The errors a body's Write fails with: the page is larger than the |
| 193 | // server sends, or the response budget has no piece left for it. |
| 194 | var ( |
| 195 | errTooLarge = errors.New("the page is larger than the server sends") |
| 196 | errNoBudget = errors.New("the response budget is spent") |
| 197 | ) |
| 198 | |
| 199 | // body is a response's body: the pieces it is held in, and their length. |
| 200 | // A page is rendered into pieces of pieceSize, each taken from the |
| 201 | // server's budget and given back by free, until its request's ctx is |
| 202 | // done. Once a body grows past its first SmallPage bytes, all of its |
| 203 | // pieces are held against the large budget too. A static page is one |
| 204 | // piece of its own, and its body has no server. |
| 205 | type body struct { |
| 206 | s *Server |
| 207 | ctx context.Context |
| 208 | pieces [][]byte |
| 209 | n int |
| 210 | } |
| 211 | |
| 212 | // Write appends p to the body. It writes nothing of p that would take the |
| 213 | // body past the server's maxResponse, and fails with errTooLarge, and |
| 214 | // nothing once ctx is done. It fails with errNoBudget when the budget, or |
| 215 | // for a body past its first SmallPage bytes the large budget, has no room |
| 216 | // left for the rest of p. |
| 217 | func (b *body) Write(p []byte) (int, error) { |
| 218 | if err := b.ctx.Err(); err != nil { |
| 219 | return 0, err |
| 220 | } |
| 221 | if len(p) > b.s.maxResponse-b.n { |
| 222 | return 0, errTooLarge |
| 223 | } |
| 224 | written := 0 |
| 225 | for written < len(p) { |
| 226 | last := len(b.pieces) - 1 |
| 227 | if last < 0 || len(b.pieces[last]) == cap(b.pieces[last]) { |
| 228 | if !b.s.take(len(b.pieces)) { |
| 229 | return written, errNoBudget |
| 230 | } |
| 231 | b.pieces = append(b.pieces, make([]byte, 0, pieceSize)) |
| 232 | last++ |
| 233 | } |
| 234 | piece := b.pieces[last] |
| 235 | k := copy(piece[len(piece):cap(piece)], p[written:]) |
| 236 | b.pieces[last] = piece[:len(piece)+k] |
| 237 | written += k |
| 238 | b.n += k |
| 239 | } |
| 240 | return written, nil |
| 241 | } |
| 242 | |
| 243 | // free gives the body's pieces back to the budget, once. |
| 244 | func (b *body) free() { |
| 245 | if b.s != nil { |
| 246 | b.s.give(len(b.pieces)) |
| 247 | } |
| 248 | b.pieces, b.n = nil, 0 |
| 249 | } |
| 250 | |
| 251 | // The budget in pieces: all of it, the large budget, and how many of a |
| 252 | // response's pieces SmallPage is. |
| 253 | const ( |
| 254 | budgetPieces = MaxBuffered / pieceSize |
| 255 | largePieces = MaxLarge / pieceSize |
| 256 | smallPieces = SmallPage / pieceSize |
| 257 | ) |
| 258 | |
| 259 | // take takes a response's piece i from the budget. A response's first |
| 260 | // smallPieces pieces take from the budget alone. The piece that takes it |
| 261 | // past them takes from the large budget too, for itself and for every |
| 262 | // piece before it, and each piece after that takes one more. So responses |
| 263 | // larger than SmallPage hold at most MaxLarge in all, counting their |
| 264 | // first SmallPage bytes, and the rest of the budget is left to the |
| 265 | // others. take takes nothing and is false when either budget has too |
| 266 | // little left. |
| 267 | func (s *Server) take(i int) bool { |
| 268 | large := 0 |
| 269 | switch { |
| 270 | case i == smallPieces: |
| 271 | large = smallPieces + 1 |
| 272 | case i > smallPieces: |
| 273 | large = 1 |
| 274 | } |
| 275 | s.pieces.Lock() |
| 276 | defer s.pieces.Unlock() |
| 277 | if s.held == budgetPieces || s.large+large > largePieces { |
| 278 | return false |
| 279 | } |
| 280 | s.held++ |
| 281 | s.large += large |
| 282 | return true |
| 283 | } |
| 284 | |
| 285 | // give gives back the n pieces a response took. |
| 286 | func (s *Server) give(n int) { |
| 287 | s.pieces.Lock() |
| 288 | defer s.pieces.Unlock() |
| 289 | s.held -= n |
| 290 | if n > smallPieces { |
| 291 | s.large -= n |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | // freshness is when the export's plan was collected, and when the |
| 296 | // publisher last finished a check of the policy, with that check's age as |
| 297 | // of the request. The pages are stale once that check is older than |
| 298 | // StaleAfter: the publisher checks the policy on every pass, whether or |
| 299 | // not the content changed, so a page goes stale only once the publisher |
| 300 | // stops reaching the edge. The collection time is shown apart, and says |
| 301 | // how old the content is; a recent check does not make old content new. |
| 302 | type freshness struct { |
| 303 | Collected string |
| 304 | Checked string |
| 305 | Age string |
| 306 | Stale bool |
| 307 | } |
| 308 | |
| 309 | func freshnessOf(collected string, checked, now time.Time) *freshness { |
| 310 | f := &freshness{Collected: stampOf(collected), Checked: stamp(checked)} |
| 311 | age := now.Sub(checked) |
| 312 | f.Age, f.Stale = ago(age), age > StaleAfter |
| 313 | return f |
| 314 | } |
| 315 | |
| 316 | // stamp is a time as the pages show it, to the minute, in UTC. |
| 317 | func stamp(t time.Time) string { return t.UTC().Format("2006-01-02 15:04 UTC") } |
| 318 | |
| 319 | func parseTime(s string) (time.Time, error) { return time.Parse(time.RFC3339, s) } |
| 320 | |
| 321 | // stampOf is stamp of an RFC 3339 time, or the text as it is when it is |
| 322 | // not one. |
| 323 | func stampOf(s string) string { |
| 324 | t, err := parseTime(s) |
| 325 | if err != nil { |
| 326 | return s |
| 327 | } |
| 328 | return stamp(t) |
| 329 | } |
| 330 | |
| 331 | // ago is an age in words. A negative age, from a clock behind the |
| 332 | // publisher's, reads as the youngest. |
| 333 | func ago(d time.Duration) string { |
| 334 | switch { |
| 335 | case d < time.Minute: |
| 336 | return "less than a minute ago" |
| 337 | case d < time.Hour: |
| 338 | return count(int(d/time.Minute), "minute") + " ago" |
| 339 | case d < 48*time.Hour: |
| 340 | return count(int(d/time.Hour), "hour") + " ago" |
| 341 | } |
| 342 | return count(int(d/(24*time.Hour)), "day") + " ago" |
| 343 | } |
| 344 | |
| 345 | // trimEnd is text without the line ends that close it, which a |
| 346 | // preformatted block would show as blank lines. |
| 347 | func trimEnd(s string) string { return strings.TrimRight(s, "\r\n") } |
| 348 | |
| 349 | func count(n int, noun string) string { |
| 350 | if n == 1 { |
| 351 | return "1 " + noun |
| 352 | } |
| 353 | return strconv.Itoa(n) + " " + noun + "s" |
| 354 | } |
| 355 | |
| 356 | // The derived states valley-plan/v1 gives a knot, and the words the pages |
| 357 | // show for each. ready is shown as free to start. |
| 358 | var stateWords = map[string]string{ |
| 359 | "ready": "free to start", |
| 360 | "in-progress": "in progress", |
| 361 | "blocked": "blocked", |
| 362 | "active": "question or idea", |
| 363 | "done": "done", |
| 364 | "abandoned": "abandoned", |
| 365 | } |
| 366 | |
| 367 | // glyphClass is the class of a state's glyph. A state the pages do not |
| 368 | // know is drawn as active. |
| 369 | func glyphClass(state string) string { |
| 370 | if _, ok := stateWords[state]; ok { |
| 371 | return state |
| 372 | } |
| 373 | return "active" |
| 374 | } |
| 375 | |
| 376 | func stateLabel(state string) string { |
| 377 | if w, ok := stateWords[state]; ok { |
| 378 | return w |
| 379 | } |
| 380 | return state |
| 381 | } |