package scratchpad_test import ( "context" "crypto/tls" "encoding/json" "html" "io" "log/slog" "net" "net/http" "net/http/cookiejar" "net/http/httptest" "net/url" "os" "regexp" "strings" "testing" "time" "amadan.net/rastrillo/rastrillo/assertion" "amadan.net/rastrillo/rastrillo/budget" "amadan.net/rastrillo/rastrillo/crypto" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/dbtest" "amadan.net/oficina/base/internal/config" "amadan.net/oficina/base/internal/consumer" "amadan.net/oficina/base/internal/install" "amadan.net/oficina/base/internal/scratchpad" ) const ( issuerOrigin = "https://base.test" appOrigin = "https://acme-scratchpad.test" ) var schema = dbtest.FromSet(scratchpad.BootSchema) func TestMain(m *testing.M) { code := budget.Main(m) schema.Remove() os.Exit(code) } type pad struct { t *testing.T key *crypto.Keypair addr string } // newPad serves Scratchpad over TLS, configured as Base would install it. func newPad(t *testing.T) *pad { t.Helper() key, err := crypto.Generate() if err != nil { t.Fatal(err) } vars := install.AppVars(config.Config{Origin: issuerOrigin, AssertionKey: key}, "scratchpad", appOrigin) cfg, err := consumer.Load(func(k string) string { return vars[k] }) if err != nil { t.Fatal(err) } logger := slog.New(slog.NewTextHandler(io.Discard, nil)) d, err := db.Open(schema.Path(t), logger) if err != nil { t.Fatal(err) } t.Cleanup(func() { d.Close() }) h, err := scratchpad.App(d, cfg, logger) if err != nil { t.Fatalf("App: %v", err) } srv := httptest.NewTLSServer(h) // 127.0.0.1 only t.Cleanup(srv.Close) return &pad{t: t, key: key, addr: srv.Listener.Addr().String()} } type resp struct { Code int Header http.Header Body string } type browser struct { p *pad client *http.Client } func (p *pad) browser() *browser { jar, _ := cookiejar.New(nil) tr := &http.Transport{ DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) { return (&net.Dialer{}).DialContext(ctx, network, p.addr) }, TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // the test server's own certificate } p.t.Cleanup(tr.CloseIdleConnections) return &browser{p: p, client: &http.Client{Jar: jar, Transport: tr, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}} } func (b *browser) do(method, path string, form url.Values, origin string) resp { b.p.t.Helper() var body io.Reader if form != nil { body = strings.NewReader(form.Encode()) } req, _ := http.NewRequest(method, appOrigin+path, body) if form != nil { req.Header.Set("Content-Type", "application/x-www-form-urlencoded") } if origin != "" { req.Header.Set("Origin", origin) } res, err := b.client.Do(req) if err != nil { b.p.t.Fatal(err) } defer res.Body.Close() raw, _ := io.ReadAll(res.Body) return resp{res.StatusCode, res.Header, string(raw)} } func (b *browser) get(path string) resp { b.p.t.Helper(); return b.do(http.MethodGet, path, nil, "") } var revisionRE = regexp.MustCompile(``) // revision is the revision the notepad form on body carries, or "". func revision(body string) string { if m := revisionRE.FindStringSubmatch(body); m != nil { return m[1] } return "" } // save loads the page and posts its notepad form with note, as a person // editing it would. func (b *browser) save(note string) resp { b.p.t.Helper() return b.saveAt(revision(b.get("/").Body), note) } // saveAt posts the notepad form as a page loaded at rev would. func (b *browser) saveAt(rev, note string) resp { b.p.t.Helper() return b.do(http.MethodPost, "/", url.Values{"note": {note}, "revision": {rev}}, appOrigin) } // signIn runs the handoff with an assertion signed as Base would sign it. func (b *browser) signIn(sub, name, base string) { b.p.t.Helper() r := b.get("/") if r.Code != http.StatusSeeOther { b.p.t.Fatalf("signed-out page: %d", r.Code) } r = b.get(r.Header.Get("Location")) u, _ := url.Parse(r.Header.Get("Location")) if r.Code != http.StatusSeeOther || u.Host != "base.test" { b.p.t.Fatalf("start: %d %q", r.Code, r.Header.Get("Location")) } kid, _ := install.KeySet(b.p.key) jti, _ := assertion.RandomID() ext, _ := json.Marshal(map[string]string{"name": name, "email": sub + "@acme.test", "base": base}) now := time.Now().Unix() token, err := assertion.Sign(b.p.key, assertion.Claims{Version: 1, Issuer: issuerOrigin, Audience: appOrigin, Subject: sub, KeyID: kid, ID: jti, Nonce: u.Query().Get("nonce"), IssuedAt: now, ExpiresAt: now + 120, AuthTime: now, Ext: ext}) if err != nil { b.p.t.Fatal(err) } if r := b.do(http.MethodPost, consumer.AssertionPath, url.Values{"assertion": {token}}, issuerOrigin); r.Code != http.StatusSeeOther { b.p.t.Fatalf("assertion: %d %s", r.Code, r.Body) } if r := b.get(consumer.FinishPath); r.Code != http.StatusSeeOther || r.Header.Get("Location") != "/" { b.p.t.Fatalf("finish: %d %q", r.Code, r.Header.Get("Location")) } } func TestNotesSharedAcrossMembers(t *testing.T) { p := newPad(t) paul, ana := p.browser(), p.browser() paul.signIn("member-paul", "Paul", "Acme Ltd") ana.signIn("member-ana", "Ana", "Acme Ltd") page := paul.get("/") if page.Code != 200 || !strings.Contains(page.Body, "Signed in as Paul, Acme Ltd") { t.Fatalf("Paul's page: %d\n%s", page.Code, page.Body) } if !strings.Contains(page.Body, `today") { t.Errorf("the note is not escaped") } // Ana's edit replaces it for Paul too. if r := ana.save("Coffee ordered"); r.Code != http.StatusSeeOther { t.Fatalf("Ana's save: %d", r.Code) } if page := paul.get("/"); !strings.Contains(page.Body, "Coffee ordered") || strings.Contains(page.Body, "tomorrow") { t.Errorf("Paul's page after Ana's edit:\n%s", page.Body) } } func TestNotesNeedSignIn(t *testing.T) { p := newPad(t) b := p.browser() if r := b.get("/"); r.Code != http.StatusSeeOther || r.Header.Get("Location") != consumer.StartPath+"?return_to=%2F" { t.Fatalf("signed-out page: %d %q", r.Code, r.Header.Get("Location")) } if r := b.save("hello"); r.Code != http.StatusForbidden { t.Fatalf("signed-out save: %d", r.Code) } } func TestNotesRefuseCrossOriginSave(t *testing.T) { p := newPad(t) b := p.browser() b.signIn("member-paul", "Paul", "Acme Ltd") b.save("kept") for _, origin := range []string{"https://evil.test", issuerOrigin} { if r := b.do(http.MethodPost, "/", url.Values{"note": {"defaced"}}, origin); r.Code != http.StatusForbidden { t.Errorf("save from %s: %d, want 403", origin, r.Code) } } if page := b.get("/"); !strings.Contains(page.Body, "kept") || strings.Contains(page.Body, "defaced") { t.Errorf("note changed by a cross-origin post:\n%s", page.Body) } } func TestNotesRefuseOversizedNote(t *testing.T) { p := newPad(t) b := p.browser() b.signIn("member-paul", "Paul", "Acme Ltd") if r := b.save(strings.Repeat("x", 70*1024)); r.Code == http.StatusSeeOther { t.Fatalf("a 70 KiB note was saved") } } func TestScratchpadServesTheLook(t *testing.T) { p := newPad(t) b := p.browser() b.signIn("member-paul", "Paul", "Acme Ltd") page := b.get("/") i := strings.Index(page.Body, `href="/static/app.`) if i < 0 { t.Fatalf("no stylesheet link:\n%s", page.Body) } href := page.Body[i+len(`href="`):] href = href[:strings.Index(href, `"`)] if r := b.get(href); r.Code != 200 || !strings.Contains(r.Header.Get("Content-Type"), "css") { t.Errorf("stylesheet %s: %d %q", href, r.Code, r.Header.Get("Content-Type")) } } // Finding 6 (R29): two people edit the same note; the second save is refused // and keeps what they typed, and saving again from there replaces the note. func TestStaleSaveIsRefused(t *testing.T) { p := newPad(t) paul, ana := p.browser(), p.browser() paul.signIn("member-paul", "Paul", "Acme Ltd") ana.signIn("member-ana", "Ana", "Acme Ltd") paul.save("first draft") paulRev, anaRev := revision(paul.get("/").Body), revision(ana.get("/").Body) if paulRev == "" || paulRev != anaRev { t.Fatalf("revisions %q and %q", paulRev, anaRev) } if r := paul.saveAt(paulRev, "Paul's "); r.Code != http.StatusSeeOther { t.Fatalf("Paul's save: %d", r.Code) } r := ana.saveAt(anaRev, "Ana's edit") if r.Code != http.StatusConflict { t.Fatalf("stale save: %d, want 409\n%s", r.Code, r.Body) } if !strings.Contains(r.Body, "Someone else saved this note while you were editing it.") { t.Errorf("no explanation:\n%s", r.Body) } if !strings.Contains(r.Body, "\nAna's edit") { t.Errorf("Ana's text is not in the form:\n%s", r.Body) } if !strings.Contains(r.Body, html.EscapeString("Paul's ")) { t.Errorf("the saved note is not shown:\n%s", r.Body) } if page := paul.get("/"); !strings.Contains(page.Body, html.EscapeString("Paul's ")) || strings.Contains(page.Body, "Ana") { t.Fatalf("the stale save changed the note:\n%s", page.Body) } // Saving the refused page again is a deliberate replace. if r := ana.saveAt(revision(r.Body), "Ana's edit"); r.Code != http.StatusSeeOther { t.Fatalf("second save: %d\n%s", r.Code, r.Body) } if page := paul.get("/"); !strings.Contains(page.Body, "Ana's edit") { t.Errorf("Ana's second save did not land:\n%s", page.Body) } // A form with no revision is not a save of anything in particular. if r := ana.saveAt("", "no revision"); r.Code != http.StatusConflict { t.Errorf("save without a revision: %d", r.Code) } } // Findings 7 and 8: Scratchpad links back to Base's Home, and signs out of // itself onto the shared signed-out page. func TestScratchpadLinksHomeAndSignsOut(t *testing.T) { p := newPad(t) b := p.browser() b.signIn("member-paul", "Paul", "Acme Ltd") page := b.get("/").Body if !strings.Contains(page, `
base`) { t.Errorf("no link to Base's Home:\n%s", page) } if !strings.Contains(page, `
`) { t.Errorf("no sign-out control:\n%s", page) } if r := b.do(http.MethodPost, consumer.SignOutPath, url.Values{}, appOrigin); r.Code != http.StatusSeeOther || r.Header.Get("Location") != consumer.SignedOutPath { t.Fatalf("sign out: %d %q", r.Code, r.Header.Get("Location")) } if r := b.get("/"); r.Code != http.StatusSeeOther || !strings.HasPrefix(r.Header.Get("Location"), consumer.StartPath) { t.Fatalf("still signed in after signing out: %d", r.Code) } }