package webtest import ( "bytes" "context" "crypto/tls" "encoding/base64" "encoding/json" "fmt" "html" "io" "log/slog" "net/http" "net/http/cookiejar" "net/http/httptest" "net/url" "regexp" "strings" "sync" "time" "testing" "amadan.net/oficina/home/connect" "amadan.net/rastrillo/rastrillo/assertion" "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/store" "amadan.net/oficina/base/internal/web" ) // Base with Oficina ID on. It is served in-process at an https origin, // because connect's cookies are __Host- cookies, which a cookie jar only // sends over https, and its assertions name an https audience. const ( homeOrigin = "https://base.acme.test" homeIssuer = "https://id.oficina.test" homeConsumer = "base" homeKeyID = "k1" ) var homeSchema = dbtest.FromSet(store.Boot(true)) // oficina plays id.oficina.test: it holds the key Base trusts for Oficina // assertions. type oficina struct { key *crypto.Keypair cfg config.Config } // newHomeApp builds Base exactly as main.go does with every BASE_HOME_* // setting present, with an assertion key so it can hand off to apps too. func newHomeApp(t *testing.T) *testApp { return newHomeAppWith(t, nil) } // newHomeAppWith is newHomeApp with a last say over the configuration. func newHomeAppWith(t *testing.T, tweak func(*config.Config)) *testApp { t.Helper() return newHomeAppInstalling(t, noInstaller{}, tweak) } // newHomeAppInstalling is newHomeAppWith with the Installer of the // caller's choice. func newHomeAppInstalling(t *testing.T, inst web.Installer, tweak func(*config.Config)) *testApp { t.Helper() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) d, err := db.Open(homeSchema.Path(t), logger) if err != nil { t.Fatalf("db.Open: %v", err) } t.Cleanup(func() { d.Close() }) if err := store.Bootstrap(context.Background(), d.Writer(), ownerAddress); err != nil { t.Fatal(err) } key, err := crypto.Generate() if err != nil { t.Fatal(err) } keys, _ := json.Marshal(map[string]string{homeKeyID: base64.StdEncoding.EncodeToString(key.SignPub())}) home, err := config.LoadHome(&connect.Credentials{ Issuer: homeIssuer, ConsumerID: homeConsumer, KeysBase64: base64.StdEncoding.EncodeToString(keys), DEKBase64: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{9}, 32)), }, homeOrigin) if err != nil || home == nil { t.Fatalf("LoadHome: %+v %v", home, err) } signing, err := crypto.Generate() if err != nil { t.Fatal(err) } cfg := config.Config{Origin: homeOrigin, Name: "Acme", Owner: ownerAddress, InstanceKey: "test-instance-key", AllowLoggedMail: true, Slug: "acme", AppsDomain: "bab.oncarlos.com", Timezone: time.UTC, AssertionKey: signing, Home: home} if tweak != nil { tweak(&cfg) } mailer := &capturingMailer{} h, err := web.App(d, cfg, mailer, inst, logger) if err != nil { t.Fatalf("web.App: %v", err) } return &testApp{seenMu: &sync.Mutex{}, t: t, client: inProcessClient(h), mail: mailer, DB: d.Writer(), base: homeOrigin, origin: homeOrigin, localSignin: "/signin/local", home: &oficina{key: key, cfg: cfg}} } // inProcessClient is a browser for h alone: a cookie jar, no redirects // followed, and every request to homeOrigin served by h without a socket. func inProcessClient(h http.Handler) *http.Client { jar, _ := cookiejar.New(nil) return &http.Client{Jar: jar, Transport: handlerTransport{h}, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} } type handlerTransport struct{ h http.Handler } func (t handlerTransport) RoundTrip(r *http.Request) (*http.Response, error) { if r.URL.Scheme+"://"+r.URL.Host != homeOrigin { return nil, fmt.Errorf("test browser: no route to %s", r.URL.Redacted()) } in := r.Clone(r.Context()) in.RequestURI, in.Host, in.RemoteAddr, in.TLS = r.URL.RequestURI(), r.URL.Host, "192.0.2.10:4321", &tls.ConnectionState{} if in.Body == nil { in.Body = http.NoBody } w := httptest.NewRecorder() t.h.ServeHTTP(w, in) res := w.Result() res.Request = r return res, nil } // newBrowser is another browser on the same Base: an empty cookie jar. func (a *testApp) newBrowser() *testApp { b := *a jar, _ := cookiejar.New(nil) c := *a.client c.Jar = jar b.client = &c return &b } var startLinkRE = regexp.MustCompile(`href="(/auth/start[^"]*)"`) // oficinaButton is the href of the sign-in page's "Sign in with Oficina". func (a *testApp) oficinaButton(page Resp) string { a.t.Helper() m := startLinkRE.FindStringSubmatch(page.Body) if m == nil { a.t.Fatalf("no Sign in with Oficina link in:\n%s", page.Body) } return html.UnescapeString(m[1]) } // atOficina follows a 303 to the issuer's /authorize as id.oficina would: // it signs an assertion for subject with the request's nonce, has the // browser post it back to /auth/assertion, and returns what /auth/finish // answers. authAge is how long ago the person last proved who they are. func (a *testApp) atOficina(toIssuer Resp, subject string, authAge time.Duration) Resp { a.t.Helper() if toIssuer.Code != http.StatusSeeOther { a.t.Fatalf("want a 303 to Oficina, got %d %q\n%s", toIssuer.Code, toIssuer.Location(), toIssuer.Body) } u, err := url.Parse(toIssuer.Location()) if err != nil || u.Scheme+"://"+u.Host != homeIssuer || u.Path != "/authorize" { a.t.Fatalf("not sent to Oficina: %q", toIssuer.Location()) } q := u.Query() if q.Get("consumer") != homeConsumer || q.Get("nonce") == "" { a.t.Fatalf("authorize query: %v", q) } now := time.Now().Unix() jti, err := assertion.RandomID() if err != nil { a.t.Fatal(err) } token, err := assertion.Sign(a.home.key, assertion.Claims{Version: 1, Issuer: homeIssuer, Audience: homeOrigin, Subject: subject, KeyID: homeKeyID, ID: jti, Nonce: q.Get("nonce"), IssuedAt: now, ExpiresAt: now + 90, AuthTime: now - int64(authAge/time.Second)}) if err != nil { a.t.Fatal(err) } cb := a.postFrom(homeIssuer, "/auth/assertion", url.Values{"assertion": {token}}) if cb.Code != http.StatusSeeOther || cb.Location() != "/auth/finish" { a.t.Fatalf("assertion callback: %d %q\n%s", cb.Code, cb.Location(), cb.Body) } return a.get("/auth/finish") } // postFrom posts a form as a page on origin would. func (a *testApp) postFrom(origin, target string, form url.Values) Resp { a.t.Helper() req, _ := http.NewRequest(http.MethodPost, a.base+target, strings.NewReader(form.Encode())) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Origin", origin) return a.do(req) } // signInWithOficina presses "Sign in with Oficina" on /signin and comes back // from Oficina as subject. It returns /auth/finish's answer. func (a *testApp) signInWithOficina(subject string) Resp { a.t.Helper() page := a.get("/signin") if page.Code != 200 { a.t.Fatalf("signin page: %d %q", page.Code, page.Location()) } return a.atOficina(a.get(a.oficinaButton(page)), subject, time.Hour) } // link connects email's member to the Oficina subject from scratch, the way // a person does it from Settings: sign in with email, Connect your Oficina // account, prove it at Oficina, confirm. It leaves this browser signed in // locally. func (a *testApp) link(email, subject string) { a.t.Helper() r := a.signIn(email) if r.Code != 303 || r.Location() != connect.LocalCompletePath { a.t.Fatalf("local sign-in: %d %q", r.Code, r.Location()) } if land := a.get(r.Location()); land.Code != 303 || land.Location() != "/" { a.t.Fatalf("local landing: %d %q", land.Code, land.Location()) } settings := a.get("/settings") if !strings.Contains(settings.Body, `href="/account/home"`) { a.t.Fatalf("settings offers no Connect:\n%s", settings.Body) } start := a.get("/account/home") if start.Code != 200 || !strings.Contains(start.Body, "Connect your Oficina account") { a.t.Fatalf("connect page: %d\n%s", start.Code, start.Body) } toIssuer := a.get(a.post("/account/home", nil).Location()) finish := a.atOficina(toIssuer, subject, 30*time.Second) a.confirmLink(finish, email) } // confirmLink takes /auth/finish's 303 to the confirm step through to // "Accounts connected". func (a *testApp) confirmLink(finish Resp, email string) { a.t.Helper() if finish.Code != 303 || finish.Location() != "/account/home/confirm" { a.t.Fatalf("link finish: %d %q\n%s", finish.Code, finish.Location(), finish.Body) } confirm := a.get("/account/home/confirm") if confirm.Code != 200 || !strings.Contains(confirm.Body, "Connect these two accounts?") || !strings.Contains(confirm.Body, email) { a.t.Fatalf("confirm page: %d\n%s", confirm.Code, confirm.Body) } done := a.post("/account/home/confirm", nil) if done.Code != 303 || !strings.HasPrefix(done.Location(), "/account/home/confirm?connected=1") { a.t.Fatalf("confirm: %d %q", done.Code, done.Location()) } if page := a.get(done.Location()); page.Code != 200 || !strings.Contains(page.Body, "Accounts connected") { a.t.Fatalf("connected page: %d\n%s", page.Code, page.Body) } }