oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1package docs
2
3import (
4 "fmt"
5 "go/ast"
6 "go/parser"
7 "go/token"
8 "net/http"
9 "net/http/httptest"
10 "net/url"
11 "path/filepath"
12 "regexp"
13 "sort"
14 "strings"
15 "testing"
16)
17
18func browserGet(app *App, cookies []*http.Cookie, method, path string) *httptest.ResponseRecorder {
19 req := httptest.NewRequest(method, path, nil)
20 req.Header.Set("Accept", "text/html,application/xhtml+xml;q=0.9,*/*;q=0.8")
21 for _, c := range cookies {
22 req.AddCookie(c)
23 }
24 rec := httptest.NewRecorder()
25 app.Handler().ServeHTTP(rec, req)
26 return rec
27}
28
29func signedInForTest(t *testing.T, app *App, address string) []*http.Cookie {
30 t.Helper()
31 link, err := app.TestSignIn(t, address)
32 if err != nil {
33 t.Fatal(err)
34 }
35 rec := httptest.NewRecorder()
36 app.Handler().ServeHTTP(rec, confirmRequest(link))
37 return rec.Result().Cookies()
38}
39
40var pageTitle = regexp.MustCompile(`<title>([^<]*)</title>`)
41
42// Every error a browser can navigate to is the error page, inside the
43// normal layout and bar, showing the viewer's own chrome (spec §3). The
44// table is {unknown route, a page GET of a POST-only path, a missing
45// document, a bad parameter, a panic} × {signed in, signed out}.
46func TestHTMLErrorsRenderTheErrorPage(t *testing.T) {
47 app, err := NewForTest(t)
48 if err != nil {
49 t.Fatal(err)
50 }
51 alice := signedInForTest(t, app, "alice@example.com")
52 panics := app.handlers.recoverToErrorPage(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { panic("boom") }))
53
54 type result struct {
55 code int
56 contentType string
57 body string
58 }
59 serveCase := func(cookies []*http.Cookie, run func([]*http.Cookie) *httptest.ResponseRecorder) result {
60 rec := run(cookies)
61 return result{rec.Code, rec.Header().Get("Content-Type"), rec.Body.String()}
62 }
63 path := func(method, p string) func([]*http.Cookie) *httptest.ResponseRecorder {
64 return func(c []*http.Cookie) *httptest.ResponseRecorder { return browserGet(app, c, method, p) }
65 }
66 panicking := func(c []*http.Cookie) *httptest.ResponseRecorder {
67 req := httptest.NewRequest(http.MethodGet, "/d/anything", nil)
68 req.Header.Set("Accept", "text/html")
69 for _, cookie := range c {
70 req.AddCookie(cookie)
71 }
72 rec := httptest.NewRecorder()
73 panics.ServeHTTP(rec, req)
74 return rec
75 }
76 badParameter := func(c []*http.Cookie) *httptest.ResponseRecorder {
77 req := httptest.NewRequest(http.MethodPost, "/documents", strings.NewReader("title="+strings.Repeat("x", 2000)))
78 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
79 req.Header.Set("Accept", "text/html")
80 req.Header.Set("Sec-Fetch-Site", "same-origin")
81 for _, cookie := range c {
82 req.AddCookie(cookie)
83 }
84 rec := httptest.NewRecorder()
85 app.Handler().ServeHTTP(rec, req)
86 return rec
87 }
88
89 cases := []struct {
90 name string
91 signedIn bool
92 run func([]*http.Cookie) *httptest.ResponseRecorder
93 status int
94 title string
95 }{
96 {"unknown route", true, path("GET", "/no/such/page"), 404, "docs.error.page.404.title · docs.app.name"},
97 {"unknown route", false, path("GET", "/no/such/page"), 404, "docs.error.page.404.title · docs.app.name"},
98 {"GET of a POST-only path", true, path("GET", "/signout"), 404, "docs.error.page.404.title · docs.app.name"},
99 {"GET of a POST-only path", false, path("GET", "/documents"), 404, "docs.error.page.404.title · docs.app.name"},
100 {"missing document", true, path("GET", "/d/doesnotexist"), 404, "docs.error.page.document.title · docs.app.name"},
101 {"missing published document", false, path("GET", "/p/doesnotexist"), 404, "docs.error.page.document.title · docs.app.name"},
102 {"missing export", true, path("GET", "/d/doesnotexist/export.pdf"), 404, "docs.error.page.document.title · docs.app.name"},
103 {"bad parameter", true, badParameter, 400, "docs.error.page.400.title · docs.app.name"},
104 {"panic", true, panicking, 500, "docs.error.page.500.title · docs.app.name"},
105 {"panic", false, panicking, 500, "docs.error.page.500.title · docs.app.name"},
106 }
107 for _, c := range cases {
108 who := "signed out"
109 var cookies []*http.Cookie
110 if c.signedIn {
111 who, cookies = "signed in", alice
112 }
113 t.Run(c.name+", "+who, func(t *testing.T) {
114 got := serveCase(cookies, c.run)
115 if got.code != c.status {
116 t.Fatalf("status %d, want %d", got.code, c.status)
117 }
118 if !strings.HasPrefix(got.contentType, "text/html") {
119 t.Fatalf("Content-Type %q, want text/html", got.contentType)
120 }
121 if m := pageTitle.FindStringSubmatch(got.body); m == nil || m[1] != c.title {
122 t.Fatalf("<title> %v, want %q", m, c.title)
123 }
124 if !strings.Contains(got.body, "<header estilo-bar") || !strings.Contains(got.body, "<div rst-error>") {
125 t.Fatal("the error page is not inside the layout and bar")
126 }
127 if account := strings.Contains(got.body, "<details estilo-account"); account != c.signedIn {
128 t.Fatalf("account menu present = %v, want %v", account, c.signedIn)
129 }
130 if c.status == 500 && !regexp.MustCompile(`rst-error-ref dir="auto">docs.error.ref [a-z0-9]{6}<`).MatchString(got.body) {
131 t.Fatal("a 500 page carries no reference")
132 }
133 })
134 }
135
136 // Non-HTML stays non-HTML: the editor's fetches and the native apps
137 // never ask for a page and never get one.
138 for _, p := range []string{"/no/such/page", "/d/doesnotexist/updates"} {
139 req := httptest.NewRequest(http.MethodGet, p, nil)
140 for _, c := range alice {
141 req.AddCookie(c)
142 }
143 rec := httptest.NewRecorder()
144 app.Handler().ServeHTTP(rec, req)
145 if rec.Code != 404 || strings.HasPrefix(rec.Header().Get("Content-Type"), "text/html") {
146 t.Errorf("%s without Accept: %d %q, want a plain 404", p, rec.Code, rec.Header().Get("Content-Type"))
147 }
148 }
149 // Any other method to a known path is 405 in plain text, with Allow.
150 req := httptest.NewRequest(http.MethodDelete, "/signout", nil)
151 req.Header.Set("Sec-Fetch-Site", "same-origin")
152 rec := httptest.NewRecorder()
153 app.Handler().ServeHTTP(rec, req)
154 if rec.Code != http.StatusMethodNotAllowed || rec.Header().Get("Allow") != "POST" {
155 t.Errorf("DELETE /signout: %d Allow=%q", rec.Code, rec.Header().Get("Allow"))
156 }
157}
158
159// The error page's Back link is offered only for a same-origin Referer
160// that is not this page (rastrillo's rule; otherwise it is an open
161// redirect).
162func TestErrorPageBackLinkIsSameOriginOnly(t *testing.T) {
163 app, _ := NewForTest(t)
164 h := app.handlers
165 for referer, want := range map[string]string{
166 DefaultOrigin + "/d/abc?x=1": "/d/abc?x=1",
167 "https://evil.example/d/abc": "",
168 DefaultOrigin + "/no/such/page": "",
169 "//evil.example/": "",
170 "http://user@localhost:8080/d/abc": "",
171 } {
172 req := httptest.NewRequest(http.MethodGet, "/no/such/page", nil)
173 req.Header.Set("Referer", referer)
174 if got := h.sameOriginReferer(req); got != want {
175 t.Errorf("Referer %q: back %q, want %q", referer, got, want)
176 }
177 }
178}
179
180// httpErrorSites lists every remaining http.Error / http.NotFound call in
181// this package, keyed "file:function", with how many each has. Every one
182// is classified below as a non-HTML answer; an unclassified new site
183// fails the test, so a page handler cannot quietly go back to plain text.
184func httpErrorSites(t *testing.T) map[string]int {
185 t.Helper()
186 fset := token.NewFileSet()
187 files, err := filepath.Glob("*.go")
188 if err != nil {
189 t.Fatal(err)
190 }
191 sites := map[string]int{}
192 for _, f := range files {
193 if strings.HasSuffix(f, "_test.go") || f == "testing.go" {
194 continue
195 }
196 file, err := parser.ParseFile(fset, f, nil, 0)
197 if err != nil {
198 t.Fatal(err)
199 }
200 for _, d := range file.Decls {
201 fn, ok := d.(*ast.FuncDecl)
202 if !ok {
203 continue
204 }
205 name := fn.Name.Name
206 if fn.Recv != nil {
207 typ := fn.Recv.List[0].Type
208 if s, ok := typ.(*ast.StarExpr); ok {
209 typ = s.X
210 }
211 if id, ok := typ.(*ast.Ident); ok {
212 name = id.Name + "." + name
213 }
214 }
215 ast.Inspect(fn, func(n ast.Node) bool {
216 call, ok := n.(*ast.CallExpr)
217 if !ok {
218 return true
219 }
220 if sel, ok := call.Fun.(*ast.SelectorExpr); ok {
221 if x, ok := sel.X.(*ast.Ident); ok && x.Name == "http" && (sel.Sel.Name == "Error" || sel.Sel.Name == "NotFound") {
222 sites[f+":"+name]++
223 }
224 }
225 return true
226 })
227 }
228 }
229 return sites
230}
231
232func TestEveryPlainTextErrorIsClassified(t *testing.T) {
233 // file:function → count, and why it is not a page.
234 classified := map[string]struct {
235 n int
236 why string
237 }{
238 "dashboard.go:handlers.dashboardProvider": {1, "private server-to-server dashboard JSON; missing response authorization fails closed"},
239 "app.go:New": {1, "live stream re-check: an EventSource, never a page"},
240 "assets.go:serveIcon": {1, "static asset 404"},
241 "assets.go:serveBundle": {1, "static asset 404"},
242 "auth.go:requireAdmissionOf": {2, "shared guard in front of page and fetch routes; its non-GET 403 must stay text for save-queue.mjs, and a GET never reaches the 503 without a database stall (R3)"},
243 "errors.go:handlers.fail": {1, "the non-HTML half of the negotiated answer"},
244 "errors.go:handlers.errorPage": {1, "the error page itself could not render"},
245 "errors.go:handlers.methodNotAllowed": {1, "405 for a non-GET method, which no navigation sends"},
246 "errors.go:handlers.recoverToErrorPage": {1, "the non-HTML half of a recovered panic"},
247 "errors.go:App.ErrorPage": {1, "the non-HTML half of rastrillo's recovered panic"},
248 "handlers.go:handlers.updatesGet": {3, "the update log, fetched by the editor"},
249 "handlers.go:handlers.updatesPost": {10, "the update log, posted by the editor (and its late-answer 503, live push §5)"},
250 "handlers.go:parseSince": {1, "the update log's cursor"},
251 "home_return.go:returnMemory.guard": {1, "405 for a non-GET method"},
252 "home_connect.go:homeRoutes.render": {1, "connect's page before the handlers exist: unreachable once New returns"},
253 "home_render.go:renderer.homeLinkBack": {1, "the page itself could not render"},
254 "identity.go:identityResolver.middleware": {1, "shared guard in front of page and fetch routes (R3)"},
255 "identity.go:refuseIdentity": {1, "non-GET refusal; a GET redirects to sign-in"},
256 "native.go:nativeApprover": {1, "a native session refused native approval: the same 401 requireCurrent answers a signed-out approval"},
257 "native.go:nativeJSON": {1, "native API JSON"},
258 "native.go:handlers.nativeList": {2, "native API JSON"},
259 "search.go:handlers.searchJSON": {3, "jump-to palette JSON"},
260 "stream.go:handlers.stream": {9, "live update stream (its 400 for a bad push cursor, its 503 for a team lease it cannot read)"},
261 "team_access.go:teamRuntime.admission": {1, "shared guard, identity missing: a wiring failure, not a page state"},
262 "team_emission.go:writeGuardedBody": {1, "response already guarded"},
263 }
264 got := httpErrorSites(t)
265 var problems []string
266 for site, n := range got {
267 c, ok := classified[site]
268 switch {
269 case !ok:
270 problems = append(problems, fmt.Sprintf("%s: %d unclassified plain-text error(s) — a page handler should call h.fail", site, n))
271 case c.n != n:
272 problems = append(problems, fmt.Sprintf("%s: %d plain-text error(s), classified %d (%s)", site, n, c.n, c.why))
273 }
274 }
275 for site := range classified {
276 if _, ok := got[site]; !ok {
277 problems = append(problems, site+": classified but no longer present — drop it from the list")
278 }
279 }
280 sort.Strings(problems)
281 for _, p := range problems {
282 t.Error(p)
283 }
284 if len(got) == 0 {
285 t.Fatal("found no http.Error sites at all; the walk is looking at nothing")
286 }
287}
288
289// A deep link opened signed out, then signed in, lands on the deep link
290// (spec §9.4), in standalone Docs: RequireSession's redirect now carries
291// return_to, GET /signin remembers it, and the magic link lands on
292// /auth/local/complete, which goes back there once.
293func TestSigningInReturnsToTheDeepLink(t *testing.T) {
294 app, _ := NewForTest(t)
295 owner := signedInForTest(t, app, "alice@example.com")
296 req := httptest.NewRequest(http.MethodPost, "/documents", strings.NewReader("title=Minutes"))
297 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
298 req.Header.Set("Sec-Fetch-Site", "same-origin")
299 for _, c := range owner {
300 req.AddCookie(c)
301 }
302 created := httptest.NewRecorder()
303 app.Handler().ServeHTTP(created, req)
304 deep := created.Header().Get("Location") + "?view=1"
305
306 jar := map[string]*http.Cookie{}
307 do := func(method, path string, form ...string) *httptest.ResponseRecorder {
308 // The landing checks the Host, so ask it the way a browser would.
309 req := httptest.NewRequest(method, DefaultOrigin+path, strings.NewReader(strings.Join(form, "")))
310 if method == http.MethodPost {
311 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
312 req.Header.Set("Sec-Fetch-Site", "same-origin")
313 }
314 for _, c := range jar {
315 req.AddCookie(c)
316 }
317 rec := httptest.NewRecorder()
318 app.Handler().ServeHTTP(rec, req)
319 for _, c := range rec.Result().Cookies() {
320 if c.MaxAge < 0 {
321 delete(jar, c.Name)
322 } else {
323 jar[c.Name] = c
324 }
325 }
326 return rec
327 }
328 first := do("GET", deep)
329 signin := first.Header().Get("Location")
330 if first.Code != http.StatusSeeOther || signin != "/signin?return_to="+url.QueryEscape(deep) {
331 t.Fatalf("signed-out deep link: %d %q", first.Code, signin)
332 }
333 if rec := do("GET", signin); rec.Code != 200 || jar[homeReturnCookie] == nil {
334 t.Fatalf("GET %s: %d, return remembered: %v", signin, rec.Code, jar[homeReturnCookie] != nil)
335 }
336 link, err := app.TestSignIn(t, "alice@example.com")
337 if err != nil {
338 t.Fatal(err)
339 }
340 verifyPath, verifyForm := confirmForm(link)
341 verified := do("POST", verifyPath, verifyForm)
342 if verified.Header().Get("Location") != localLinkCompletePath {
343 t.Fatalf("the link landed on %q, not %s", verified.Header().Get("Location"), localLinkCompletePath)
344 }
345 landed := do("GET", localLinkCompletePath)
346 if landed.Code != http.StatusSeeOther || landed.Header().Get("Location") != deep {
347 t.Fatalf("landed on %d %q, want %q", landed.Code, landed.Header().Get("Location"), deep)
348 }
349 if jar[homeReturnCookie] != nil {
350 t.Fatal("the return path outlived its one use")
351 }
352 if again := do("GET", localLinkCompletePath); again.Header().Get("Location") != "/" {
353 t.Fatalf("a second landing went to %q, want the list", again.Header().Get("Location"))
354 }
355 // An abandoned attempt does not win over a later one: a deep link
356 // remembered, then a plain /signin, lands on the list.
357 stale := httptest.NewRecorder()
358 app.Handler().ServeHTTP(stale, httptest.NewRequest(http.MethodGet, DefaultOrigin+"/signin?return_to="+url.QueryEscape(deep), nil))
359 fresh := httptest.NewRequest(http.MethodGet, DefaultOrigin+"/signin", nil)
360 for _, c := range stale.Result().Cookies() {
361 fresh.AddCookie(c)
362 }
363 freshRec := httptest.NewRecorder()
364 app.Handler().ServeHTTP(freshRec, fresh)
365 // The browser's jar: the stale attempt's cookie, replaced by whatever
366 // the plain /signin set.
367 cookies := map[string]*http.Cookie{}
368 for _, c := range append(stale.Result().Cookies(), freshRec.Result().Cookies()...) {
369 cookies[c.Name] = c
370 }
371 landing := httptest.NewRequest(http.MethodGet, DefaultOrigin+localLinkCompletePath, nil)
372 for _, c := range cookies {
373 landing.AddCookie(c)
374 }
375 landingRec := httptest.NewRecorder()
376 app.Handler().ServeHTTP(landingRec, landing)
377 if landingRec.Header().Get("Location") != "/" {
378 t.Fatalf("a plain /signin after an abandoned deep link lands on %q, want the list", landingRec.Header().Get("Location"))
379 }
380
381 // Signed in now: GET /signin goes straight back, with no form.
382 if back := do("GET", "/signin?return_to="+url.QueryEscape(deep)); back.Code != http.StatusSeeOther || back.Header().Get("Location") != deep {
383 t.Fatalf("already signed in: %d %q", back.Code, back.Header().Get("Location"))
384 }
385 for _, bad := range []string{"https://evil.example/", "//evil.example/", "/\\evil", "/%09/evil"} {
386 if back := do("GET", "/signin?return_to="+url.QueryEscape(bad)); back.Header().Get("Location") != "/" {
387 t.Errorf("return_to %q sent a signed-in person to %q", bad, back.Header().Get("Location"))
388 }
389 }
390 // Signing out lands on the signed-out page, not straight back on the
391 // form.
392 out := httptest.NewRequest(http.MethodPost, "/signout", nil)
393 out.Header.Set("Sec-Fetch-Site", "same-origin")
394 out.Header.Set("Origin", DefaultOrigin)
395 for _, c := range jar {
396 out.AddCookie(c)
397 }
398 outRec := httptest.NewRecorder()
399 app.Handler().ServeHTTP(outRec, out)
400 if outRec.Code != http.StatusSeeOther || outRec.Header().Get("Location") != "/signed-out" {
401 t.Fatalf("sign out: %d %q", outRec.Code, outRec.Header().Get("Location"))
402 }
403}
404
405// The layout links estilo's stylesheets in the suite's order, each at a
406// content-hashed path, and the brand icons are served from estilo.
407func TestEstiloChromeAssetsAreLinkedInOrder(t *testing.T) {
408 app, _ := NewForTest(t)
409 body := browserGet(app, nil, "GET", "/signin").Body.String()
410 order := []string{`<meta charset="utf-8">`, "/static/tokens.", "/static/theme.", "/static/brand/brand.", "/static/estilo/base.", "/static/estilo/menu.", "/static/estilo/chrome."}
411 last := -1
412 for _, marker := range order {
413 i := strings.Index(body, marker)
414 if i < 0 || i < last {
415 t.Fatalf("%s is missing or out of order", marker)
416 }
417 last = i
418 }
419 for _, name := range []string{"base", "menu", "chrome"} {
420 m := regexp.MustCompile(`/static/estilo/` + name + `\.[0-9a-f]{16}\.css`).FindString(body)
421 if m == "" {
422 t.Fatalf("%s.css is not fingerprinted", name)
423 }
424 if rec := browserGet(app, nil, "GET", m); rec.Code != 200 || !strings.HasPrefix(rec.Header().Get("Content-Type"), "text/css") {
425 t.Fatalf("%s: %d", m, rec.Code)
426 }
427 }
428 icon := browserGet(app, nil, "GET", "/static/estilo/brand/docs.svg")
429 if icon.Code != 200 || icon.Header().Get("Content-Type") != "image/svg+xml" {
430 t.Fatalf("brand icon: %d", icon.Code)
431 }
432}
433