oficina / base Public

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

Plain git — no account needed to clone.

Download

Download this file

1package issuer_test
2
3import (
4 "context"
5 "crypto/tls"
6 "database/sql"
7 "encoding/json"
8 "html"
9 "io"
10 "log/slog"
11 "net"
12 "net/http"
13 "net/http/cookiejar"
14 "net/http/httptest"
15 "net/url"
16 "os"
17 "regexp"
18 "strings"
19 "testing"
20 "time"
21 "unicode/utf8"
22
23 "amadan.net/rastrillo/rastrillo/assertion"
24 "amadan.net/rastrillo/rastrillo/budget"
25 "amadan.net/rastrillo/rastrillo/crypto"
26 "amadan.net/rastrillo/rastrillo/db"
27 "amadan.net/rastrillo/rastrillo/dbtest"
28
29 "amadan.net/oficina/base/internal/config"
30 "amadan.net/oficina/base/internal/install"
31 "amadan.net/oficina/base/internal/issuer"
32 "amadan.net/oficina/base/internal/store"
33 "amadan.net/oficina/base/internal/web"
34)
35
36const (
37 baseOrigin = "https://base.acme.test"
38 appOrigin = "https://acme-scratchpad.bab.oncarlos.com"
39 ownerAddress = "owner@acme.test"
40 handoffCSP = "default-src 'self'; style-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'self'; form-action " + appOrigin
41)
42
43var schema = dbtest.FromSet(store.BootSchema)
44
45func TestMain(m *testing.M) {
46 code := budget.Main(m)
47 schema.Remove()
48 os.Exit(code)
49}
50
51func testConfig(t *testing.T) config.Config {
52 t.Helper()
53 kp, err := crypto.Generate()
54 if err != nil {
55 t.Fatal(err)
56 }
57 return config.Config{Origin: baseOrigin, Name: "Acme", Owner: ownerAddress, InstanceKey: "test-instance-key",
58 AllowLoggedMail: true, Slug: "acme", AppsDomain: "bab.oncarlos.com", Timezone: time.UTC, AssertionKey: kp}
59}
60
61func openDB(t *testing.T) *db.DB {
62 t.Helper()
63 d, err := db.Open(schema.Path(t), slog.New(slog.NewTextHandler(io.Discard, nil)))
64 if err != nil {
65 t.Fatal(err)
66 }
67 t.Cleanup(func() { d.Close() })
68 if err := store.Bootstrap(context.Background(), d.Writer(), ownerAddress); err != nil {
69 t.Fatal(err)
70 }
71 return d
72}
73
74// setInstall gives app an install row in state.
75func setInstall(t *testing.T, sdb *sql.DB, cfg config.Config, app, state string) {
76 t.Helper()
77 ctx := context.Background()
78 _, host := install.HostFor(cfg, app)
79 if _, err := store.ClaimInstall(ctx, sdb, app, host); err != nil {
80 t.Fatal(err)
81 }
82 if state != "installing" {
83 if err := store.SetInstallState(ctx, sdb, app, state, ""); err != nil {
84 t.Fatal(err)
85 }
86 }
87}
88
89type mailbox struct{ last string }
90
91func (m *mailbox) Send(_ context.Context, _, _, body string) error { m.last = body; return nil }
92
93type noInstaller struct{}
94
95func (noInstaller) Start(context.Context, string) error { return nil }
96func (noInstaller) Uninstall(context.Context, string) error { return nil }
97
98type resp struct {
99 Code int
100 Header http.Header
101 Body string
102}
103
104// base is the whole app behind TLS. Requests name cfg.Origin's host and are
105// dialled to the test server, so cookies and origins are what a browser
106// would see.
107type base struct {
108 t *testing.T
109 cfg config.Config
110 db *sql.DB
111 mail *mailbox
112 client *http.Client
113}
114
115func newBase(t *testing.T) *base {
116 t.Helper()
117 cfg := testConfig(t)
118 d := openDB(t)
119 mail := &mailbox{}
120 h, err := web.App(d, cfg, mail, noInstaller{}, slog.New(slog.NewTextHandler(io.Discard, nil)))
121 if err != nil {
122 t.Fatalf("web.App: %v", err)
123 }
124 srv := httptest.NewTLSServer(h) // 127.0.0.1 only
125 t.Cleanup(srv.Close)
126 b := &base{t: t, cfg: cfg, db: d.Writer(), mail: mail}
127 b.client = b.newClient(srv.Listener.Addr().String())
128 return b
129}
130
131func (b *base) newClient(addr string) *http.Client {
132 jar, _ := cookiejar.New(nil)
133 tr := &http.Transport{
134 DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
135 return (&net.Dialer{}).DialContext(ctx, network, addr)
136 },
137 TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // the test server's own certificate
138 }
139 b.t.Cleanup(tr.CloseIdleConnections)
140 return &http.Client{Jar: jar, Transport: tr, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
141}
142
143func (b *base) do(c *http.Client, method, path string, form url.Values) resp {
144 b.t.Helper()
145 var body io.Reader
146 if form != nil {
147 body = strings.NewReader(form.Encode())
148 }
149 req, _ := http.NewRequest(method, b.cfg.Origin+path, body)
150 if form != nil {
151 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
152 req.Header.Set("Origin", b.cfg.Origin)
153 }
154 res, err := c.Do(req)
155 if err != nil {
156 b.t.Fatal(err)
157 }
158 defer res.Body.Close()
159 raw, _ := io.ReadAll(res.Body)
160 return resp{res.StatusCode, res.Header, string(raw)}
161}
162
163func (b *base) get(path string) resp { b.t.Helper(); return b.do(b.client, http.MethodGet, path, nil) }
164
165var (
166 formRE = regexp.MustCompile(`(?s)<form[^>]*action="([^"]*)"[^>]*>(.*?)</form>`)
167 inputRE = regexp.MustCompile(`<input[^>]*>`)
168 attrRE = regexp.MustCompile(`(\w[\w-]*)="([^"]*)"`)
169 linkRE = regexp.MustCompile(`https?://[^\s"<>]+/auth/verify\?[^\s"<>]+`)
170 tokenRE = regexp.MustCompile(`[A-Za-z0-9_-]{40,}\.[A-Za-z0-9_-]{86}`)
171)
172
173// fields returns the named inputs of the form posting to action, and whether
174// there is one.
175func fields(body, action string) (url.Values, bool) {
176 for _, m := range formRE.FindAllStringSubmatch(body, -1) {
177 if html.UnescapeString(m[1]) != action {
178 continue
179 }
180 v := url.Values{}
181 for _, in := range inputRE.FindAllString(m[2], -1) {
182 attrs := map[string]string{}
183 for _, kv := range attrRE.FindAllStringSubmatch(in, -1) {
184 attrs[kv[1]] = html.UnescapeString(kv[2])
185 }
186 if attrs["name"] != "" {
187 v.Set(attrs["name"], attrs["value"])
188 }
189 }
190 return v, true
191 }
192 return nil, false
193}
194
195// signIn follows an emailed link for email, as webtest's helper does.
196func (b *base) signIn(email string) {
197 b.t.Helper()
198 page := b.get("/signin?rec=1&force=1")
199 v, ok := fields(page.Body, "/auth/begin")
200 if page.Code != 200 || !ok {
201 b.t.Fatalf("signin page: %d\n%s", page.Code, page.Body)
202 }
203 v.Set("address", email)
204 if r := b.do(b.client, http.MethodPost, "/auth/begin", v); r.Code != 303 {
205 b.t.Fatalf("begin: %d %s", r.Code, r.Body)
206 }
207 link := linkRE.FindString(html.UnescapeString(b.mail.last))
208 if link == "" {
209 b.t.Fatalf("no sign-in link in %q", b.mail.last)
210 }
211 u, _ := url.Parse(link)
212 confirm := b.get(u.RequestURI())
213 cv, ok := fields(confirm.Body, "/auth/verify")
214 if confirm.Code != 200 || !ok {
215 b.t.Fatalf("confirm page: %d", confirm.Code)
216 }
217 if r := b.do(b.client, http.MethodPost, "/auth/verify", cv); r.Code != 303 || r.Location() != "/" {
218 b.t.Fatalf("verify: %d %q", r.Code, r.Location())
219 }
220}
221
222func (r resp) Location() string { return r.Header.Get("Location") }
223
224func owner(t *testing.T, sdb *sql.DB) store.Member {
225 t.Helper()
226 m, ok, err := store.MemberByEmail(context.Background(), sdb, ownerAddress)
227 if err != nil || !ok {
228 t.Fatalf("owner: %v %v", ok, err)
229 }
230 return m
231}
232
233func nonce(t *testing.T) string {
234 t.Helper()
235 n, err := assertion.RandomID()
236 if err != nil {
237 t.Fatal(err)
238 }
239 return n
240}
241
242func verifier(t *testing.T, cfg config.Config) *assertion.Verifier {
243 t.Helper()
244 kid, pub := install.KeySet(cfg.AssertionKey)
245 v, err := assertion.NewVerifier(cfg.Origin, appOrigin, map[string][]byte{kid: pub})
246 if err != nil {
247 t.Fatal(err)
248 }
249 return v
250}
251
252func authorizePath(consumer, n string) string {
253 return "/authorize?" + url.Values{"consumer": {consumer}, "nonce": {n}}.Encode()
254}
255
256func TestAuthorizeSignsForInstalledApp(t *testing.T) {
257 b := newBase(t)
258 setInstall(t, b.db, b.cfg, "scratchpad", "installed")
259 before := time.Now().Unix()
260 b.signIn(ownerAddress)
261 signedIn := time.Now().Unix()
262 // Cross a second boundary so auth_time (sign-in) and iat (now) differ.
263 time.Sleep(time.Until(time.Now().Truncate(time.Second).Add(time.Second + 10*time.Millisecond)))
264 n := nonce(t)
265 page := b.get(authorizePath("scratchpad", n))
266 if page.Code != 200 {
267 t.Fatalf("authorize: %d %s", page.Code, page.Body)
268 }
269 v, ok := fields(page.Body, appOrigin+"/auth/assertion")
270 if !ok {
271 t.Fatalf("no form posting to the app:\n%s", page.Body)
272 }
273 if !regexp.MustCompile(`<form[^>]*method="post"`).MatchString(page.Body) {
274 t.Errorf("the form does not POST:\n%s", page.Body)
275 }
276 claims, err := verifier(t, b.cfg).Verify(v.Get("assertion"), time.Now())
277 if err != nil {
278 t.Fatalf("verify: %v", err)
279 }
280 m := owner(t, b.db)
281 kid, _ := install.KeySet(b.cfg.AssertionKey)
282 if claims.Audience != appOrigin || claims.Issuer != baseOrigin || claims.Subject != m.ID || claims.Nonce != n || claims.KeyID != kid {
283 t.Errorf("claims: %+v", claims)
284 }
285 if claims.ExpiresAt-claims.IssuedAt != 120 || claims.IssuedAt <= signedIn || claims.IssuedAt > time.Now().Unix() {
286 t.Errorf("lifetime: iat %d exp %d", claims.IssuedAt, claims.ExpiresAt)
287 }
288 if claims.AuthTime < before || claims.AuthTime > signedIn || claims.AuthTime >= claims.IssuedAt {
289 t.Errorf("auth_time %d, iat %d", claims.AuthTime, claims.IssuedAt)
290 }
291 var ext map[string]string
292 if err := json.Unmarshal(claims.Ext, &ext); err != nil {
293 t.Fatalf("ext: %v", err)
294 }
295 if len(ext) != 3 || ext["name"] != m.Name || ext["email"] != ownerAddress || ext["base"] != "Acme" {
296 t.Errorf("ext: %s", claims.Ext)
297 }
298 if len(claims.ID) != 22 || claims.ID == claims.Nonce {
299 t.Errorf("jti %q", claims.ID)
300 }
301
302 if got := page.Header.Get("Cache-Control"); got != "no-store" {
303 t.Errorf("Cache-Control %q", got)
304 }
305 // origin, not no-referrer: the app checks that the POST's Origin is Base,
306 // and no-referrer would make browsers send Origin: null (R21).
307 if got := page.Header.Get("Referrer-Policy"); got != "origin" {
308 t.Errorf("Referrer-Policy %q, want origin", got)
309 }
310 if metas := regexp.MustCompile(`<meta name="referrer"[^>]*>`).FindAllString(page.Body, -1); len(metas) != 1 || metas[0] != `<meta name="referrer" content="origin">` {
311 t.Errorf("referrer meta: %q", metas)
312 }
313 if got := page.Header.Values("Content-Security-Policy"); len(got) != 1 || got[0] != handoffCSP {
314 t.Errorf("CSP %q, want %q", got, handoffCSP)
315 }
316 if !strings.Contains(page.Body, `type="submit"`) || !strings.Contains(page.Body, ">Continue<") {
317 t.Errorf("no Continue button:\n%s", page.Body)
318 }
319 // The only script is a deferred file of Base's own; nothing inline.
320 scripts := regexp.MustCompile(`<script[^>]*>`).FindAllString(page.Body, -1)
321 if len(scripts) != 1 || !strings.Contains(scripts[0], " defer") {
322 t.Fatalf("scripts: %q", scripts)
323 }
324 src := regexp.MustCompile(`src="(/static/[^"]+\.js)"`).FindStringSubmatch(scripts[0])
325 if src == nil || !strings.Contains(page.Body, `<script defer src="`+src[1]+`"></script>`) {
326 t.Fatalf("script is not an empty external tag: %q", scripts)
327 }
328 js := b.get(src[1])
329 if js.Code != 200 || !strings.Contains(js.Header.Get("Content-Type"), "javascript") || !strings.Contains(js.Body, "submit()") {
330 t.Errorf("script %s: %d %q\n%s", src[1], js.Code, js.Header.Get("Content-Type"), js.Body)
331 }
332
333 // A second visit is a fresh assertion with a fresh jti.
334 again, _ := fields(b.get(authorizePath("scratchpad", n)).Body, appOrigin+"/auth/assertion")
335 c2, err := verifier(t, b.cfg).Verify(again.Get("assertion"), time.Now())
336 if err != nil || c2.ID == claims.ID {
337 t.Errorf("second assertion: %v, jti %q then %q", err, claims.ID, c2.ID)
338 }
339}
340
341// noAssertion fails if body carries anything that looks like a token or the
342// handoff form.
343func noAssertion(t *testing.T, body string) {
344 t.Helper()
345 if strings.Contains(body, `name="assertion"`) || strings.Contains(body, "/auth/assertion") || tokenRE.MatchString(body) {
346 t.Errorf("refusal carries an assertion:\n%s", body)
347 }
348}
349
350func TestAuthorizeRefusals(t *testing.T) {
351 good := "AAAAAAAAAAAAAAAAAAAAAA" // a 16-byte value, as RandomID encodes it
352 cases := []struct {
353 name string
354 path func(t *testing.T) string
355 signIn bool
356 before func(t *testing.T, b *base) // after sign-in
357 code int
358 }{
359 {name: "no session", path: func(t *testing.T) string { return authorizePath("scratchpad", nonce(t)) }, code: http.StatusSeeOther},
360 {name: "unknown consumer", signIn: true, path: func(t *testing.T) string { return authorizePath("nope", nonce(t)) }, code: http.StatusNotFound},
361 {name: "consumer path trick", signIn: true, path: func(t *testing.T) string { return authorizePath("../scratchpad", nonce(t)) }, code: http.StatusNotFound},
362 {name: "consumer missing", signIn: true, path: func(t *testing.T) string { return "/authorize?nonce=" + nonce(t) }, code: http.StatusNotFound},
363 {name: "consumer twice", signIn: true, path: func(t *testing.T) string {
364 return "/authorize?consumer=scratchpad&consumer=welcome&nonce=" + nonce(t)
365 }, code: http.StatusBadRequest},
366 {name: "consumer installing", signIn: true, path: func(t *testing.T) string { return authorizePath("welcome", nonce(t)) }, code: http.StatusNotFound},
367 {name: "consumer failed", signIn: true, path: func(t *testing.T) string { return authorizePath("broken", nonce(t)) }, code: http.StatusNotFound},
368 {name: "nonce missing", signIn: true, path: func(*testing.T) string { return "/authorize?consumer=scratchpad" }, code: http.StatusBadRequest},
369 {name: "nonce empty", signIn: true, path: func(*testing.T) string { return authorizePath("scratchpad", "") }, code: http.StatusBadRequest},
370 {name: "nonce short", signIn: true, path: func(*testing.T) string { return authorizePath("scratchpad", good[:21]) }, code: http.StatusBadRequest},
371 {name: "nonce long", signIn: true, path: func(*testing.T) string { return authorizePath("scratchpad", good+"A") }, code: http.StatusBadRequest},
372 {name: "nonce padded", signIn: true, path: func(*testing.T) string { return authorizePath("scratchpad", good[:20]+"==") }, code: http.StatusBadRequest},
373 {name: "nonce std alphabet", signIn: true, path: func(*testing.T) string { return authorizePath("scratchpad", good[:21]+"+") }, code: http.StatusBadRequest},
374 {name: "nonce noncanonical", signIn: true, path: func(*testing.T) string { return authorizePath("scratchpad", good[:21]+"B") }, code: http.StatusBadRequest},
375 {name: "nonce with space", signIn: true, path: func(*testing.T) string { return authorizePath("scratchpad", good+" ") }, code: http.StatusBadRequest},
376 {name: "nonce twice", signIn: true, path: func(t *testing.T) string {
377 return "/authorize?consumer=scratchpad&nonce=" + nonce(t) + "&nonce=" + nonce(t)
378 }, code: http.StatusBadRequest},
379 {name: "member removed after signing in", signIn: true, path: func(t *testing.T) string { return authorizePath("scratchpad", nonce(t)) },
380 before: func(t *testing.T, b *base) {
381 if _, err := b.db.Exec(`DELETE FROM members WHERE email = ?`, ownerAddress); err != nil {
382 t.Fatal(err)
383 }
384 }, code: http.StatusForbidden},
385 }
386 for _, tc := range cases {
387 t.Run(tc.name, func(t *testing.T) {
388 b := newBase(t)
389 setInstall(t, b.db, b.cfg, "scratchpad", "installed")
390 setInstall(t, b.db, b.cfg, "welcome", "installing")
391 setInstall(t, b.db, b.cfg, "broken", "failed")
392 if tc.signIn {
393 b.signIn(ownerAddress)
394 }
395 if tc.before != nil {
396 tc.before(t, b)
397 }
398 r := b.get(tc.path(t))
399 if r.Code != tc.code {
400 t.Errorf("status %d, want %d\n%s", r.Code, tc.code, r.Body)
401 }
402 if tc.code == http.StatusSeeOther && !strings.HasPrefix(r.Location(), "/signin") {
403 t.Errorf("redirect to %q, want sign-in", r.Location())
404 }
405 noAssertion(t, r.Body)
406 })
407 }
408}
409
410// TestAuthorizeAuthTime drives the handler directly to pin auth_time: the
411// session's sign-in time when known, else iat.
412func TestAuthorizeAuthTime(t *testing.T) {
413 cfg := testConfig(t)
414 d := openDB(t)
415 setInstall(t, d.Writer(), cfg, "scratchpad", "installed")
416 m := owner(t, d.Writer())
417 signedIn := time.Now().Add(-3 * time.Hour).Truncate(time.Second)
418 cases := []struct {
419 name string
420 at time.Time
421 ok bool
422 want func(iat int64) int64
423 }{
424 {"sign-in time", signedIn, true, func(int64) int64 { return signedIn.Unix() }},
425 {"unknown", time.Time{}, false, func(iat int64) int64 { return iat }},
426 {"in the future", time.Now().Add(time.Hour), true, func(iat int64) int64 { return iat }},
427 }
428 for _, tc := range cases {
429 t.Run(tc.name, func(t *testing.T) {
430 h, err := issuer.New(d.Writer(), cfg,
431 func(*http.Request) (store.Member, bool) { return m, true },
432 func(*http.Request) (time.Time, bool) { return tc.at, tc.ok },
433 slog.New(slog.NewTextHandler(io.Discard, nil)))
434 if err != nil {
435 t.Fatal(err)
436 }
437 w := httptest.NewRecorder()
438 h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, authorizePath("scratchpad", nonce(t)), nil))
439 v, ok := fields(w.Body.String(), appOrigin+"/auth/assertion")
440 if w.Code != 200 || !ok {
441 t.Fatalf("%d\n%s", w.Code, w.Body)
442 }
443 c, err := verifier(t, cfg).Verify(v.Get("assertion"), time.Now())
444 if err != nil {
445 t.Fatal(err)
446 }
447 if c.AuthTime != tc.want(c.IssuedAt) {
448 t.Errorf("auth_time %d, want %d (iat %d)", c.AuthTime, tc.want(c.IssuedAt), c.IssuedAt)
449 }
450 })
451 }
452}
453
454func TestAuthorizeWithoutMemberRefuses(t *testing.T) {
455 cfg := testConfig(t)
456 d := openDB(t)
457 setInstall(t, d.Writer(), cfg, "scratchpad", "installed")
458 h, err := issuer.New(d.Writer(), cfg,
459 func(*http.Request) (store.Member, bool) { return store.Member{}, false },
460 func(*http.Request) (time.Time, bool) { return time.Now(), true },
461 slog.New(slog.NewTextHandler(io.Discard, nil)))
462 if err != nil {
463 t.Fatal(err)
464 }
465 w := httptest.NewRecorder()
466 h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, authorizePath("scratchpad", nonce(t)), nil))
467 if w.Code != http.StatusForbidden {
468 t.Errorf("status %d", w.Code)
469 }
470 noAssertion(t, w.Body.String())
471}
472
473func TestNewNeedsKey(t *testing.T) {
474 cfg := testConfig(t)
475 cfg.AssertionKey = nil
476 d := openDB(t)
477 _, err := issuer.New(d.Writer(), cfg, web.CurrentMember, func(*http.Request) (time.Time, bool) { return time.Time{}, false }, nil)
478 if err == nil {
479 t.Fatal("New accepted a missing assertion key")
480 }
481}
482
483// Finding 1: the assertion goes to the host Base installed the app at, which
484// is where the app was told its own origin is, even after the slug or apps
485// domain changed. It still never comes from the request.
486func TestAuthorizeUsesRecordedHost(t *testing.T) {
487 b := newBase(t)
488 ctx := context.Background()
489 const old = "https://oldco-scratchpad.old.example"
490 if _, err := store.ClaimInstall(ctx, b.db, "scratchpad", strings.TrimPrefix(old, "https://")); err != nil {
491 t.Fatal(err)
492 }
493 if err := store.SetInstallState(ctx, b.db, "scratchpad", "installed", ""); err != nil {
494 t.Fatal(err)
495 }
496 b.signIn(ownerAddress)
497 page := b.get(authorizePath("scratchpad", nonce(t)))
498 v, ok := fields(page.Body, old+"/auth/assertion")
499 if page.Code != 200 || !ok {
500 t.Fatalf("authorize: %d\n%s", page.Code, page.Body)
501 }
502 kid, pub := install.KeySet(b.cfg.AssertionKey)
503 ver, err := assertion.NewVerifier(b.cfg.Origin, old, map[string][]byte{kid: pub})
504 if err != nil {
505 t.Fatal(err)
506 }
507 if c, err := ver.Verify(v.Get("assertion"), time.Now()); err != nil || c.Audience != old {
508 t.Fatalf("assertion for %q: %v", c.Audience, err)
509 }
510 if got := page.Header.Get("Content-Security-Policy"); !strings.HasSuffix(got, "form-action "+old) {
511 t.Errorf("CSP %q", got)
512 }
513}
514
515// Finding 10: display fields are cut to fit rastrillo's 1 KiB limit on Ext,
516// at a character boundary, so a very long name never breaks the handoff.
517func TestAuthorizeBoundsDisplayFields(t *testing.T) {
518 for name, tc := range map[string]struct{ member, base string }{
519 "long name": {strings.Repeat("Ana María ", 300), "Acme"},
520 "name that escapes": {strings.Repeat("<&>", 400), "Acme"},
521 "long base name": {"Paul", strings.Repeat("Acme Holdings ", 200)},
522 "multibyte at the edge": {strings.Repeat("é", 1000), strings.Repeat("日本", 400)},
523 } {
524 t.Run(name, func(t *testing.T) {
525 cfg := testConfig(t)
526 cfg.Name = tc.base
527 d := openDB(t)
528 setInstall(t, d.Writer(), cfg, "scratchpad", "installed")
529 m := owner(t, d.Writer())
530 m.Name = tc.member
531 m.Email = strings.Repeat("x", 400) + "@acme.test"
532 h, err := issuer.New(d.Writer(), cfg,
533 func(*http.Request) (store.Member, bool) { return m, true },
534 func(*http.Request) (time.Time, bool) { return time.Time{}, false },
535 slog.New(slog.NewTextHandler(io.Discard, nil)))
536 if err != nil {
537 t.Fatal(err)
538 }
539 w := httptest.NewRecorder()
540 h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, authorizePath("scratchpad", nonce(t)), nil))
541 v, ok := fields(w.Body.String(), appOrigin+"/auth/assertion")
542 if w.Code != 200 || !ok {
543 t.Fatalf("authorize: %d\n%s", w.Code, w.Body)
544 }
545 c, err := verifier(t, cfg).Verify(v.Get("assertion"), time.Now())
546 if err != nil {
547 t.Fatal(err)
548 }
549 var ext map[string]string
550 if err := json.Unmarshal(c.Ext, &ext); err != nil || len(c.Ext) > 1024 {
551 t.Fatalf("ext %d bytes: %v", len(c.Ext), err)
552 }
553 for field, full := range map[string]string{"name": tc.member, "email": m.Email, "base": tc.base} {
554 got := ext[field]
555 if got == "" || !utf8.ValidString(got) {
556 t.Errorf("%s = %q", field, got)
557 }
558 if got != full && !strings.HasPrefix(full, strings.TrimSuffix(got, "…")) {
559 t.Errorf("%s %q is not a prefix of the original", field, got)
560 }
561 }
562 })
563 }
564}
565