oficina / base Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package webtest tests Base from the outside: real HTTP requests against
2// the real router, wired as cmd/base/main.go wires it.
3package webtest
4
5import (
6 "bytes"
7 "context"
8 "database/sql"
9 "errors"
10 "html"
11 "io"
12 "log/slog"
13 "net/http"
14 "net/http/cookiejar"
15 "net/http/httptest"
16 "net/url"
17 "os"
18 "regexp"
19 "strings"
20 "sync"
21 "testing"
22 "time"
23
24 "amadan.net/rastrillo/rastrillo/budget"
25 "amadan.net/rastrillo/rastrillo/db"
26 "amadan.net/rastrillo/rastrillo/dbtest"
27
28 "amadan.net/oficina/base/internal/config"
29 "amadan.net/oficina/base/internal/store"
30 "amadan.net/oficina/base/internal/web"
31)
32
33// testOrigin is the origin newApp wires and post presents as its
34// same-origin evidence: the pair a browser form submission would be.
35const (
36 testOrigin = "http://127.0.0.1:8080"
37 ownerAddress = "owner@acme.test"
38)
39
40// schema is migrated once per test binary and copied for each test.
41var schema = dbtest.FromSet(store.BootSchema)
42
43func TestMain(m *testing.M) {
44 code := budget.Main(m)
45 schema.Remove()
46 homeSchema.Remove()
47 os.Exit(code)
48}
49
50// Mail is one captured message.
51type Mail struct{ To, Subject, Body string }
52
53type capturingMailer struct {
54 mu sync.Mutex
55 sent []Mail
56 fail bool // when set, Send returns an error and records nothing
57}
58
59func (c *capturingMailer) Send(_ context.Context, to, subject, body string) error {
60 c.mu.Lock()
61 defer c.mu.Unlock()
62 if c.fail {
63 return errors.New("smtp down")
64 }
65 c.sent = append(c.sent, Mail{to, subject, body})
66 return nil
67}
68
69type noInstaller struct{}
70
71func (noInstaller) Start(context.Context, string) error { return nil }
72func (noInstaller) Uninstall(context.Context, string) error { return nil }
73
74// Resp is a fully read response.
75type Resp struct {
76 Code int
77 Header http.Header
78 Body string
79}
80
81func (r Resp) Location() string { return r.Header.Get("Location") }
82
83type testApp struct {
84 t *testing.T
85 srv *httptest.Server // nil for an app served in-process (newHomeApp)
86 client *http.Client
87 mail *capturingMailer
88 DB *sql.DB
89 // base prefixes every request path; origin is the same-origin evidence
90 // post presents; localSignin is the page with the email form.
91 base, origin, localSignin string
92 home *oficina // set by newHomeApp
93 // seen is every response so far, for checks that a secret never
94 // reached the browser.
95 seen []Resp
96 // seenMu guards seen; a pointer, so newBrowser's copy shares it.
97 seenMu *sync.Mutex
98 // logs is everything the app logged.
99 logs *logBuffer
100 // header is sent with every request this browser makes (the native
101 // app's Base-Client-Capabilities), unless the request sets it itself.
102 header http.Header
103}
104
105// logBuffer is the app's log, written by its handlers and read by a test.
106type logBuffer struct {
107 mu sync.Mutex
108 b bytes.Buffer
109}
110
111func (l *logBuffer) Write(p []byte) (int, error) {
112 l.mu.Lock()
113 defer l.mu.Unlock()
114 return l.b.Write(p)
115}
116
117func (l *logBuffer) String() string {
118 l.mu.Lock()
119 defer l.mu.Unlock()
120 return l.b.String()
121}
122
123// newApp builds the whole app per test over its own copy of the migrated
124// database, exactly as main.go does, with the owner bootstrapped.
125func newApp(t *testing.T) *testApp { return newAppWith(t, noInstaller{}, time.UTC) }
126
127// newAppWith is newApp with the Installer and time zone of the caller's choice.
128func newAppWith(t *testing.T, inst web.Installer, tz *time.Location) *testApp {
129 t.Helper()
130 return newAppBuilt(t, func(*sql.DB, config.Config) web.Installer { return inst }, tz)
131}
132
133// newAppBuilt is newAppWith for an Installer that needs the app's database
134// and configuration.
135func newAppBuilt(t *testing.T, build func(*sql.DB, config.Config) web.Installer, tz *time.Location) *testApp {
136 t.Helper()
137 return newAppConfigured(t, build, tz, nil)
138}
139
140// newAppConfigured is newAppBuilt with a last say over the configuration.
141func newAppConfigured(t *testing.T, build func(*sql.DB, config.Config) web.Installer, tz *time.Location, tweak func(*config.Config)) *testApp {
142 t.Helper()
143 logs := &logBuffer{}
144 logger := slog.New(slog.NewTextHandler(logs, nil))
145 d, err := db.Open(schema.Path(t), logger)
146 if err != nil {
147 t.Fatalf("db.Open: %v", err)
148 }
149 t.Cleanup(func() { d.Close() })
150 if err := store.Bootstrap(context.Background(), d.Writer(), ownerAddress); err != nil {
151 t.Fatal(err)
152 }
153 cfg := config.Config{Origin: testOrigin, Name: "Acme", Owner: ownerAddress, InstanceKey: "test-instance-key", AllowLoggedMail: true,
154 Slug: "acme", AppsDomain: "bab.oncarlos.com", Timezone: tz}
155 if tweak != nil {
156 tweak(&cfg)
157 }
158 mailer := &capturingMailer{}
159 h, err := web.App(d, cfg, mailer, build(d.Writer(), cfg), logger)
160 if err != nil {
161 t.Fatalf("web.App: %v", err)
162 }
163 srv := httptest.NewServer(h) // 127.0.0.1 only
164 t.Cleanup(srv.Close)
165 jar, _ := cookiejar.New(nil)
166 client := &http.Client{Jar: jar, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
167 return &testApp{seenMu: &sync.Mutex{}, logs: logs, t: t, srv: srv, client: client, mail: mailer, DB: d.Writer(), base: srv.URL, origin: testOrigin, localSignin: "/signin"}
168}
169
170func (a *testApp) do(req *http.Request) Resp {
171 a.t.Helper()
172 a.addHeader(req)
173 res, err := a.client.Do(req)
174 if err != nil {
175 a.t.Fatal(err)
176 }
177 defer res.Body.Close()
178 b, _ := io.ReadAll(res.Body)
179 out := Resp{res.StatusCode, res.Header, string(b)}
180 a.seenMu.Lock()
181 a.seen = append(a.seen, out)
182 a.seenMu.Unlock()
183 return out
184}
185
186// addHeader sets a.header's fields on req where req has none of its own.
187func (a *testApp) addHeader(req *http.Request) {
188 for k, v := range a.header {
189 if _, ok := req.Header[k]; !ok {
190 req.Header[k] = v
191 }
192 }
193}
194
195func (a *testApp) get(target string) Resp {
196 a.t.Helper()
197 req, _ := http.NewRequest(http.MethodGet, a.base+target, nil)
198 return a.do(req)
199}
200
201// post presents the same-origin evidence csrf.Protect requires: every
202// browser sends Origin on a form POST; a test client must too.
203func (a *testApp) post(target string, form url.Values) Resp {
204 a.t.Helper()
205 req, _ := http.NewRequest(http.MethodPost, a.base+target, strings.NewReader(form.Encode()))
206 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
207 req.Header.Set("Origin", a.origin)
208 return a.do(req)
209}
210
211func (a *testApp) mailbox() []Mail {
212 a.mail.mu.Lock()
213 defer a.mail.mu.Unlock()
214 return append([]Mail(nil), a.mail.sent...)
215}
216
217var (
218 formRE = regexp.MustCompile(`(?s)<form[^>]*action="([^"]*)"[^>]*>(.*?)</form>`)
219 inputRE = regexp.MustCompile(`<input[^>]*>`)
220 attrRE = regexp.MustCompile(`(\w[\w-]*)="([^"]*)"`)
221 linkRE = regexp.MustCompile(`https?://[^\s"<>]+/auth/verify\?[^\s"<>]+`)
222)
223
224// formFields returns the hidden and text inputs of the form posting to action.
225func formFields(t *testing.T, body, action string) url.Values {
226 t.Helper()
227 for _, m := range formRE.FindAllStringSubmatch(body, -1) {
228 if html.UnescapeString(m[1]) != action {
229 continue
230 }
231 v := url.Values{}
232 for _, in := range inputRE.FindAllString(m[2], -1) {
233 attrs := map[string]string{}
234 for _, kv := range attrRE.FindAllStringSubmatch(in, -1) {
235 attrs[kv[1]] = html.UnescapeString(kv[2])
236 }
237 if attrs["name"] != "" {
238 v.Set(attrs["name"], attrs["value"])
239 }
240 }
241 return v
242 }
243 t.Fatalf("no form posting to %s in:\n%s", action, body)
244 return nil
245}
246
247// requestLink asks for a sign-in link as a visitor would. ?rec=1 renders the
248// recovery form, which is usable at once; the ordinary one makes a person wait
249// three seconds before it will be accepted.
250func (a *testApp) requestLink(email string) Resp {
251 a.t.Helper()
252 page := a.get(a.localSignin + "?rec=1&force=1")
253 if page.Code != 200 {
254 a.t.Fatalf("signin page: %d", page.Code)
255 }
256 v := formFields(a.t, page.Body, "/auth/begin")
257 v.Set("address", email)
258 return a.post("/auth/begin", v)
259}
260
261// signIn requests a link, follows it from the mailbox and confirms it. It
262// returns the response to the confirm POST: a 303 to "/" on success.
263func (a *testApp) signIn(email string) Resp {
264 a.t.Helper()
265 before := len(a.mailbox())
266 if r := a.requestLink(email); r.Code != 303 {
267 a.t.Fatalf("begin: %d %s", r.Code, r.Body)
268 }
269 box := a.mailbox()
270 if len(box) != before+1 {
271 a.t.Fatalf("want one new email, mailbox has %d (was %d)", len(box), before)
272 }
273 link := linkRE.FindString(html.UnescapeString(box[len(box)-1].Body))
274 if link == "" {
275 a.t.Fatalf("no sign-in link in:\n%s", box[len(box)-1].Body)
276 }
277 u, _ := url.Parse(link)
278 confirm := a.get(u.RequestURI())
279 if confirm.Code != 200 {
280 a.t.Fatalf("confirm page: %d", confirm.Code)
281 }
282 return a.post("/auth/verify", formFields(a.t, confirm.Body, "/auth/verify"))
283}
284