| 1 | package webtest |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/tls" |
| 7 | "encoding/base64" |
| 8 | "encoding/json" |
| 9 | "fmt" |
| 10 | "html" |
| 11 | "io" |
| 12 | "log/slog" |
| 13 | "net/http" |
| 14 | "net/http/cookiejar" |
| 15 | "net/http/httptest" |
| 16 | "net/url" |
| 17 | "regexp" |
| 18 | "strings" |
| 19 | "sync" |
| 20 | "time" |
| 21 | |
| 22 | "testing" |
| 23 | |
| 24 | "amadan.net/oficina/home/connect" |
| 25 | "amadan.net/rastrillo/rastrillo/assertion" |
| 26 | "amadan.net/rastrillo/rastrillo/crypto" |
| 27 | "amadan.net/rastrillo/rastrillo/db" |
| 28 | "amadan.net/rastrillo/rastrillo/dbtest" |
| 29 | |
| 30 | "amadan.net/oficina/base/internal/config" |
| 31 | "amadan.net/oficina/base/internal/store" |
| 32 | "amadan.net/oficina/base/internal/web" |
| 33 | ) |
| 34 | |
| 35 | // Base with Oficina ID on. It is served in-process at an https origin, |
| 36 | // because connect's cookies are __Host- cookies, which a cookie jar only |
| 37 | // sends over https, and its assertions name an https audience. |
| 38 | const ( |
| 39 | homeOrigin = "https://base.acme.test" |
| 40 | homeIssuer = "https://id.oficina.test" |
| 41 | homeConsumer = "base" |
| 42 | homeKeyID = "k1" |
| 43 | ) |
| 44 | |
| 45 | var homeSchema = dbtest.FromSet(store.Boot(true)) |
| 46 | |
| 47 | // oficina plays id.oficina.test: it holds the key Base trusts for Oficina |
| 48 | // assertions. |
| 49 | type oficina struct { |
| 50 | key *crypto.Keypair |
| 51 | cfg config.Config |
| 52 | } |
| 53 | |
| 54 | // newHomeApp builds Base exactly as main.go does with every BASE_HOME_* |
| 55 | // setting present, with an assertion key so it can hand off to apps too. |
| 56 | func newHomeApp(t *testing.T) *testApp { return newHomeAppWith(t, nil) } |
| 57 | |
| 58 | // newHomeAppWith is newHomeApp with a last say over the configuration. |
| 59 | func newHomeAppWith(t *testing.T, tweak func(*config.Config)) *testApp { |
| 60 | t.Helper() |
| 61 | return newHomeAppInstalling(t, noInstaller{}, tweak) |
| 62 | } |
| 63 | |
| 64 | // newHomeAppInstalling is newHomeAppWith with the Installer of the |
| 65 | // caller's choice. |
| 66 | func newHomeAppInstalling(t *testing.T, inst web.Installer, tweak func(*config.Config)) *testApp { |
| 67 | t.Helper() |
| 68 | logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| 69 | d, err := db.Open(homeSchema.Path(t), logger) |
| 70 | if err != nil { |
| 71 | t.Fatalf("db.Open: %v", err) |
| 72 | } |
| 73 | t.Cleanup(func() { d.Close() }) |
| 74 | if err := store.Bootstrap(context.Background(), d.Writer(), ownerAddress); err != nil { |
| 75 | t.Fatal(err) |
| 76 | } |
| 77 | key, err := crypto.Generate() |
| 78 | if err != nil { |
| 79 | t.Fatal(err) |
| 80 | } |
| 81 | keys, _ := json.Marshal(map[string]string{homeKeyID: base64.StdEncoding.EncodeToString(key.SignPub())}) |
| 82 | home, err := config.LoadHome(&connect.Credentials{ |
| 83 | Issuer: homeIssuer, ConsumerID: homeConsumer, |
| 84 | KeysBase64: base64.StdEncoding.EncodeToString(keys), |
| 85 | DEKBase64: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{9}, 32)), |
| 86 | }, homeOrigin) |
| 87 | if err != nil || home == nil { |
| 88 | t.Fatalf("LoadHome: %+v %v", home, err) |
| 89 | } |
| 90 | signing, err := crypto.Generate() |
| 91 | if err != nil { |
| 92 | t.Fatal(err) |
| 93 | } |
| 94 | cfg := config.Config{Origin: homeOrigin, Name: "Acme", Owner: ownerAddress, InstanceKey: "test-instance-key", AllowLoggedMail: true, |
| 95 | Slug: "acme", AppsDomain: "bab.oncarlos.com", Timezone: time.UTC, AssertionKey: signing, Home: home} |
| 96 | if tweak != nil { |
| 97 | tweak(&cfg) |
| 98 | } |
| 99 | mailer := &capturingMailer{} |
| 100 | h, err := web.App(d, cfg, mailer, inst, logger) |
| 101 | if err != nil { |
| 102 | t.Fatalf("web.App: %v", err) |
| 103 | } |
| 104 | return &testApp{seenMu: &sync.Mutex{}, t: t, client: inProcessClient(h), mail: mailer, DB: d.Writer(), |
| 105 | base: homeOrigin, origin: homeOrigin, localSignin: "/signin/local", home: &oficina{key: key, cfg: cfg}} |
| 106 | } |
| 107 | |
| 108 | // inProcessClient is a browser for h alone: a cookie jar, no redirects |
| 109 | // followed, and every request to homeOrigin served by h without a socket. |
| 110 | func inProcessClient(h http.Handler) *http.Client { |
| 111 | jar, _ := cookiejar.New(nil) |
| 112 | return &http.Client{Jar: jar, Transport: handlerTransport{h}, |
| 113 | CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| 114 | } |
| 115 | |
| 116 | type handlerTransport struct{ h http.Handler } |
| 117 | |
| 118 | func (t handlerTransport) RoundTrip(r *http.Request) (*http.Response, error) { |
| 119 | if r.URL.Scheme+"://"+r.URL.Host != homeOrigin { |
| 120 | return nil, fmt.Errorf("test browser: no route to %s", r.URL.Redacted()) |
| 121 | } |
| 122 | in := r.Clone(r.Context()) |
| 123 | in.RequestURI, in.Host, in.RemoteAddr, in.TLS = r.URL.RequestURI(), r.URL.Host, "192.0.2.10:4321", &tls.ConnectionState{} |
| 124 | if in.Body == nil { |
| 125 | in.Body = http.NoBody |
| 126 | } |
| 127 | w := httptest.NewRecorder() |
| 128 | t.h.ServeHTTP(w, in) |
| 129 | res := w.Result() |
| 130 | res.Request = r |
| 131 | return res, nil |
| 132 | } |
| 133 | |
| 134 | // newBrowser is another browser on the same Base: an empty cookie jar. |
| 135 | func (a *testApp) newBrowser() *testApp { |
| 136 | b := *a |
| 137 | jar, _ := cookiejar.New(nil) |
| 138 | c := *a.client |
| 139 | c.Jar = jar |
| 140 | b.client = &c |
| 141 | return &b |
| 142 | } |
| 143 | |
| 144 | var startLinkRE = regexp.MustCompile(`href="(/auth/start[^"]*)"`) |
| 145 | |
| 146 | // oficinaButton is the href of the sign-in page's "Sign in with Oficina". |
| 147 | func (a *testApp) oficinaButton(page Resp) string { |
| 148 | a.t.Helper() |
| 149 | m := startLinkRE.FindStringSubmatch(page.Body) |
| 150 | if m == nil { |
| 151 | a.t.Fatalf("no Sign in with Oficina link in:\n%s", page.Body) |
| 152 | } |
| 153 | return html.UnescapeString(m[1]) |
| 154 | } |
| 155 | |
| 156 | // atOficina follows a 303 to the issuer's /authorize as id.oficina would: |
| 157 | // it signs an assertion for subject with the request's nonce, has the |
| 158 | // browser post it back to /auth/assertion, and returns what /auth/finish |
| 159 | // answers. authAge is how long ago the person last proved who they are. |
| 160 | func (a *testApp) atOficina(toIssuer Resp, subject string, authAge time.Duration) Resp { |
| 161 | a.t.Helper() |
| 162 | if toIssuer.Code != http.StatusSeeOther { |
| 163 | a.t.Fatalf("want a 303 to Oficina, got %d %q\n%s", toIssuer.Code, toIssuer.Location(), toIssuer.Body) |
| 164 | } |
| 165 | u, err := url.Parse(toIssuer.Location()) |
| 166 | if err != nil || u.Scheme+"://"+u.Host != homeIssuer || u.Path != "/authorize" { |
| 167 | a.t.Fatalf("not sent to Oficina: %q", toIssuer.Location()) |
| 168 | } |
| 169 | q := u.Query() |
| 170 | if q.Get("consumer") != homeConsumer || q.Get("nonce") == "" { |
| 171 | a.t.Fatalf("authorize query: %v", q) |
| 172 | } |
| 173 | now := time.Now().Unix() |
| 174 | jti, err := assertion.RandomID() |
| 175 | if err != nil { |
| 176 | a.t.Fatal(err) |
| 177 | } |
| 178 | token, err := assertion.Sign(a.home.key, assertion.Claims{Version: 1, Issuer: homeIssuer, Audience: homeOrigin, Subject: subject, |
| 179 | KeyID: homeKeyID, ID: jti, Nonce: q.Get("nonce"), IssuedAt: now, ExpiresAt: now + 90, AuthTime: now - int64(authAge/time.Second)}) |
| 180 | if err != nil { |
| 181 | a.t.Fatal(err) |
| 182 | } |
| 183 | cb := a.postFrom(homeIssuer, "/auth/assertion", url.Values{"assertion": {token}}) |
| 184 | if cb.Code != http.StatusSeeOther || cb.Location() != "/auth/finish" { |
| 185 | a.t.Fatalf("assertion callback: %d %q\n%s", cb.Code, cb.Location(), cb.Body) |
| 186 | } |
| 187 | return a.get("/auth/finish") |
| 188 | } |
| 189 | |
| 190 | // postFrom posts a form as a page on origin would. |
| 191 | func (a *testApp) postFrom(origin, target string, form url.Values) Resp { |
| 192 | a.t.Helper() |
| 193 | req, _ := http.NewRequest(http.MethodPost, a.base+target, strings.NewReader(form.Encode())) |
| 194 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 195 | req.Header.Set("Origin", origin) |
| 196 | return a.do(req) |
| 197 | } |
| 198 | |
| 199 | // signInWithOficina presses "Sign in with Oficina" on /signin and comes back |
| 200 | // from Oficina as subject. It returns /auth/finish's answer. |
| 201 | func (a *testApp) signInWithOficina(subject string) Resp { |
| 202 | a.t.Helper() |
| 203 | page := a.get("/signin") |
| 204 | if page.Code != 200 { |
| 205 | a.t.Fatalf("signin page: %d %q", page.Code, page.Location()) |
| 206 | } |
| 207 | return a.atOficina(a.get(a.oficinaButton(page)), subject, time.Hour) |
| 208 | } |
| 209 | |
| 210 | // link connects email's member to the Oficina subject from scratch, the way |
| 211 | // a person does it from Settings: sign in with email, Connect your Oficina |
| 212 | // account, prove it at Oficina, confirm. It leaves this browser signed in |
| 213 | // locally. |
| 214 | func (a *testApp) link(email, subject string) { |
| 215 | a.t.Helper() |
| 216 | r := a.signIn(email) |
| 217 | if r.Code != 303 || r.Location() != connect.LocalCompletePath { |
| 218 | a.t.Fatalf("local sign-in: %d %q", r.Code, r.Location()) |
| 219 | } |
| 220 | if land := a.get(r.Location()); land.Code != 303 || land.Location() != "/" { |
| 221 | a.t.Fatalf("local landing: %d %q", land.Code, land.Location()) |
| 222 | } |
| 223 | settings := a.get("/settings") |
| 224 | if !strings.Contains(settings.Body, `href="/account/home"`) { |
| 225 | a.t.Fatalf("settings offers no Connect:\n%s", settings.Body) |
| 226 | } |
| 227 | start := a.get("/account/home") |
| 228 | if start.Code != 200 || !strings.Contains(start.Body, "Connect your Oficina account") { |
| 229 | a.t.Fatalf("connect page: %d\n%s", start.Code, start.Body) |
| 230 | } |
| 231 | toIssuer := a.get(a.post("/account/home", nil).Location()) |
| 232 | finish := a.atOficina(toIssuer, subject, 30*time.Second) |
| 233 | a.confirmLink(finish, email) |
| 234 | } |
| 235 | |
| 236 | // confirmLink takes /auth/finish's 303 to the confirm step through to |
| 237 | // "Accounts connected". |
| 238 | func (a *testApp) confirmLink(finish Resp, email string) { |
| 239 | a.t.Helper() |
| 240 | if finish.Code != 303 || finish.Location() != "/account/home/confirm" { |
| 241 | a.t.Fatalf("link finish: %d %q\n%s", finish.Code, finish.Location(), finish.Body) |
| 242 | } |
| 243 | confirm := a.get("/account/home/confirm") |
| 244 | if confirm.Code != 200 || !strings.Contains(confirm.Body, "Connect these two accounts?") || !strings.Contains(confirm.Body, email) { |
| 245 | a.t.Fatalf("confirm page: %d\n%s", confirm.Code, confirm.Body) |
| 246 | } |
| 247 | done := a.post("/account/home/confirm", nil) |
| 248 | if done.Code != 303 || !strings.HasPrefix(done.Location(), "/account/home/confirm?connected=1") { |
| 249 | a.t.Fatalf("confirm: %d %q", done.Code, done.Location()) |
| 250 | } |
| 251 | if page := a.get(done.Location()); page.Code != 200 || !strings.Contains(page.Body, "Accounts connected") { |
| 252 | a.t.Fatalf("connected page: %d\n%s", page.Code, page.Body) |
| 253 | } |
| 254 | } |
| 255 | |