package mapatest import ( "context" "io" "log/slog" "net/http" "net/http/httptest" "net/url" "path/filepath" "regexp" "strings" "sync" "testing" "amadan.net/rastrillo/rastrillo/db" "gorm.io/gorm" "amadan.net/oficina/mapa/internal/mapa" ) // capturingMailer records what the app sends instead of sending it. type capturingMailer struct { mutex sync.Mutex sent []string } func (mailer *capturingMailer) Send(_ context.Context, to, subject, body string) error { mailer.mutex.Lock() defer mailer.mutex.Unlock() mailer.sent = append(mailer.sent, to+"\n"+subject+"\n"+body) return nil } func (mailer *capturingMailer) count() int { mailer.mutex.Lock() defer mailer.mutex.Unlock() return len(mailer.sent) } func (mailer *capturingMailer) last(t *testing.T) string { t.Helper() mailer.mutex.Lock() defer mailer.mutex.Unlock() if len(mailer.sent) == 0 { t.Fatal("no email was sent") } return mailer.sent[len(mailer.sent)-1] } // wired is the app exactly as main.go builds it, App, NewAuth, UseAuth, // with a capturing mailer and NO test identity, over the database in // dir, admitting owners. type wired struct { handler http.Handler mailer *capturingMailer built mapa.Built db *db.DB } func (app wired) database() *gorm.DB { return app.db.G } func (app wired) close() error { return app.db.Close() } func wiredApp(t *testing.T, dir, owners string) wired { t.Helper() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) database, err := db.Open(filepath.Join(dir, "mapa.db"), logger) if err != nil { t.Fatal(err) } t.Cleanup(func() { database.Close() }) config := testConfig(t, owners) built, err := mapa.App(database, config, logger) if err != nil { t.Fatal(err) } mailer := &capturingMailer{} signins, err := mapa.NewAuth(database.Writer(), mapa.AuthEnv{ Origin: config.Origin, InstanceKey: config.InstanceKey, Mailer: mailer}, logger, built.Admit) if err != nil { t.Fatal(err) } built.UseAuth(signins) return wired{handler: built.Mux, mailer: mailer, built: built, db: database} } func send(handler http.Handler, method, target string, form url.Values, cookies []*http.Cookie) *httptest.ResponseRecorder { request := httptest.NewRequest(method, target, strings.NewReader(form.Encode())) request.Header.Set("Content-Type", "application/x-www-form-urlencoded") request.Header.Set("Origin", testOrigin) for _, cookie := range cookies { request.AddCookie(cookie) } recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, request) return recorder } var linkToken = regexp.MustCompile(`/auth/verify\?token=([A-Za-z0-9_\-%.~]+)`) // signIn walks the email path as a person does and returns the session // cookies. force=1 takes the plain-email path, which dials nothing. func signIn(t *testing.T, app wired, address string) []*http.Cookie { t.Helper() begin := send(app.handler, http.MethodPost, "/auth/begin", url.Values{"address": {address}, "force": {"1"}}, nil) if begin.Header().Get("Location") != "/signin?sent=1" { t.Fatalf("begin: %d %q", begin.Code, begin.Header().Get("Location")) } mail := app.mailer.last(t) if !strings.HasPrefix(mail, address+"\nSign in to Mapa\n") { t.Fatalf("the email is not the door's:\n%s", mail) } match := linkToken.FindStringSubmatch(mail) if match == nil { t.Fatalf("no sign-in link:\n%s", mail) } confirm := send(app.handler, http.MethodGet, "/auth/verify?token="+match[1], nil, nil) if confirm.Code != http.StatusOK || len(confirm.Result().Cookies()) != 0 { t.Fatal("the link's GET must draw the door and spend nothing") } verify := send(app.handler, http.MethodPost, "/auth/verify", url.Values{"token": {match[1]}}, nil) if strings.Contains(verify.Header().Get("Location"), "err=") { t.Fatalf("verify failed: %q", verify.Header().Get("Location")) } return verify.Result().Cookies() } func TestASignInCompletesEndToEnd(t *testing.T) { app := wiredApp(t, t.TempDir(), Ana) cookies := signIn(t, app, Ana) home := send(app.handler, http.MethodGet, "/", nil, cookies) if home.Code != http.StatusOK || !strings.Contains(home.Body.String(), "Today") { t.Fatalf("GET / signed in: %d", home.Code) } } func TestSignedOutIsSentToTheDoor(t *testing.T) { app := wiredApp(t, t.TempDir(), Ana) home := send(app.handler, http.MethodGet, "/", nil, nil) if home.Code != http.StatusSeeOther || !strings.HasPrefix(home.Header().Get("Location"), "/signin") { t.Fatalf("signed out: %d %q", home.Code, home.Header().Get("Location")) } door := send(app.handler, http.MethodGet, "/signin", nil, nil) if !strings.Contains(door.Body.String(), "estilo-door") { t.Fatal("the sign-in page is not estilo's door") } } // A stranger gets the same outcome as a member, and no email. func TestAStrangerIsSentNothing(t *testing.T) { app := wiredApp(t, t.TempDir(), Ana) begin := send(app.handler, http.MethodPost, "/auth/begin", url.Values{"address": {"nobody@example.com"}, "force": {"1"}}, nil) if begin.Header().Get("Location") != "/signin?sent=1" || app.mailer.count() != 0 { t.Fatal("a stranger was told apart from a member, or mailed") } } // Gate 9 in the lone shape: a member taken off the admission list can no // longer sign in, and a session they already hold stops working. func TestARemovedMemberIsOut(t *testing.T) { dir := t.TempDir() before := wiredApp(t, dir, Ana+","+Bo) cookies := signIn(t, before, Bo) if send(before.handler, http.MethodGet, "/", nil, cookies).Code != http.StatusOK { t.Fatal("Bo could not sign in while admitted") } written := send(before.handler, http.MethodPost, "/scratch", url.Values{"body": {"Bo's own"}}, cookies) pageID := strings.TrimPrefix(written.Header().Get("Location"), "/p/") after := wiredApp(t, dir, Ana) if code := send(after.handler, http.MethodGet, "/", nil, cookies).Code; code != http.StatusNotFound { t.Fatalf("Bo's old session still opens Today: %d", code) } send(after.handler, http.MethodPost, "/auth/begin", url.Values{"address": {Bo}, "force": {"1"}}, nil) if after.mailer.count() != 0 { t.Fatal("Bo, removed, was sent a sign-in link") } // Under gate 5's reading, ownership survives removal: Bo's page is // kept, and the S2 rule still answers for it, by name. id, _, err := after.built.Store.RowID(context.Background(), pageID) if err != nil { t.Fatal(err) } readable, err := after.built.Store.MayRead(context.Background(), Bo, id, after.built.Admit) if err != nil || !readable { t.Fatalf("Bo's own page after removal: %v, %v", readable, err) } }