| 1 | package mapatest |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "io" |
| 6 | "log/slog" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "net/url" |
| 10 | "path/filepath" |
| 11 | "regexp" |
| 12 | "strings" |
| 13 | "sync" |
| 14 | "testing" |
| 15 | |
| 16 | "amadan.net/rastrillo/rastrillo/db" |
| 17 | "gorm.io/gorm" |
| 18 | |
| 19 | "amadan.net/oficina/mapa/internal/mapa" |
| 20 | ) |
| 21 | |
| 22 | // capturingMailer records what the app sends instead of sending it. |
| 23 | type capturingMailer struct { |
| 24 | mutex sync.Mutex |
| 25 | sent []string |
| 26 | } |
| 27 | |
| 28 | func (mailer *capturingMailer) Send(_ context.Context, to, subject, |
| 29 | body string) error { |
| 30 | mailer.mutex.Lock() |
| 31 | defer mailer.mutex.Unlock() |
| 32 | mailer.sent = append(mailer.sent, to+"\n"+subject+"\n"+body) |
| 33 | return nil |
| 34 | } |
| 35 | |
| 36 | func (mailer *capturingMailer) count() int { |
| 37 | mailer.mutex.Lock() |
| 38 | defer mailer.mutex.Unlock() |
| 39 | return len(mailer.sent) |
| 40 | } |
| 41 | |
| 42 | func (mailer *capturingMailer) last(t *testing.T) string { |
| 43 | t.Helper() |
| 44 | mailer.mutex.Lock() |
| 45 | defer mailer.mutex.Unlock() |
| 46 | if len(mailer.sent) == 0 { |
| 47 | t.Fatal("no email was sent") |
| 48 | } |
| 49 | return mailer.sent[len(mailer.sent)-1] |
| 50 | } |
| 51 | |
| 52 | // wired is the app exactly as main.go builds it, App, NewAuth, UseAuth, |
| 53 | // with a capturing mailer and NO test identity, over the database in |
| 54 | // dir, admitting owners. |
| 55 | type wired struct { |
| 56 | handler http.Handler |
| 57 | mailer *capturingMailer |
| 58 | built mapa.Built |
| 59 | db *db.DB |
| 60 | } |
| 61 | |
| 62 | func (app wired) database() *gorm.DB { return app.db.G } |
| 63 | |
| 64 | func (app wired) close() error { return app.db.Close() } |
| 65 | |
| 66 | func wiredApp(t *testing.T, dir, owners string) wired { |
| 67 | t.Helper() |
| 68 | logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| 69 | database, err := db.Open(filepath.Join(dir, "mapa.db"), logger) |
| 70 | if err != nil { |
| 71 | t.Fatal(err) |
| 72 | } |
| 73 | t.Cleanup(func() { database.Close() }) |
| 74 | config := testConfig(t, owners) |
| 75 | built, err := mapa.App(database, config, logger) |
| 76 | if err != nil { |
| 77 | t.Fatal(err) |
| 78 | } |
| 79 | mailer := &capturingMailer{} |
| 80 | signins, err := mapa.NewAuth(database.Writer(), mapa.AuthEnv{ |
| 81 | Origin: config.Origin, InstanceKey: config.InstanceKey, |
| 82 | Mailer: mailer}, logger, built.Admit) |
| 83 | if err != nil { |
| 84 | t.Fatal(err) |
| 85 | } |
| 86 | built.UseAuth(signins) |
| 87 | return wired{handler: built.Mux, mailer: mailer, built: built, |
| 88 | db: database} |
| 89 | } |
| 90 | |
| 91 | func send(handler http.Handler, method, target string, form url.Values, |
| 92 | cookies []*http.Cookie) *httptest.ResponseRecorder { |
| 93 | request := httptest.NewRequest(method, target, |
| 94 | strings.NewReader(form.Encode())) |
| 95 | request.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 96 | request.Header.Set("Origin", testOrigin) |
| 97 | for _, cookie := range cookies { |
| 98 | request.AddCookie(cookie) |
| 99 | } |
| 100 | recorder := httptest.NewRecorder() |
| 101 | handler.ServeHTTP(recorder, request) |
| 102 | return recorder |
| 103 | } |
| 104 | |
| 105 | var linkToken = regexp.MustCompile(`/auth/verify\?token=([A-Za-z0-9_\-%.~]+)`) |
| 106 | |
| 107 | // signIn walks the email path as a person does and returns the session |
| 108 | // cookies. force=1 takes the plain-email path, which dials nothing. |
| 109 | func signIn(t *testing.T, app wired, address string) []*http.Cookie { |
| 110 | t.Helper() |
| 111 | begin := send(app.handler, http.MethodPost, "/auth/begin", |
| 112 | url.Values{"address": {address}, "force": {"1"}}, nil) |
| 113 | if begin.Header().Get("Location") != "/signin?sent=1" { |
| 114 | t.Fatalf("begin: %d %q", begin.Code, begin.Header().Get("Location")) |
| 115 | } |
| 116 | mail := app.mailer.last(t) |
| 117 | if !strings.HasPrefix(mail, address+"\nSign in to Mapa\n") { |
| 118 | t.Fatalf("the email is not the door's:\n%s", mail) |
| 119 | } |
| 120 | match := linkToken.FindStringSubmatch(mail) |
| 121 | if match == nil { |
| 122 | t.Fatalf("no sign-in link:\n%s", mail) |
| 123 | } |
| 124 | confirm := send(app.handler, http.MethodGet, |
| 125 | "/auth/verify?token="+match[1], nil, nil) |
| 126 | if confirm.Code != http.StatusOK || len(confirm.Result().Cookies()) != 0 { |
| 127 | t.Fatal("the link's GET must draw the door and spend nothing") |
| 128 | } |
| 129 | verify := send(app.handler, http.MethodPost, "/auth/verify", |
| 130 | url.Values{"token": {match[1]}}, nil) |
| 131 | if strings.Contains(verify.Header().Get("Location"), "err=") { |
| 132 | t.Fatalf("verify failed: %q", verify.Header().Get("Location")) |
| 133 | } |
| 134 | return verify.Result().Cookies() |
| 135 | } |
| 136 | |
| 137 | func TestASignInCompletesEndToEnd(t *testing.T) { |
| 138 | app := wiredApp(t, t.TempDir(), Ana) |
| 139 | cookies := signIn(t, app, Ana) |
| 140 | home := send(app.handler, http.MethodGet, "/", nil, cookies) |
| 141 | if home.Code != http.StatusOK || |
| 142 | !strings.Contains(home.Body.String(), "Today") { |
| 143 | t.Fatalf("GET / signed in: %d", home.Code) |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | func TestSignedOutIsSentToTheDoor(t *testing.T) { |
| 148 | app := wiredApp(t, t.TempDir(), Ana) |
| 149 | home := send(app.handler, http.MethodGet, "/", nil, nil) |
| 150 | if home.Code != http.StatusSeeOther || |
| 151 | !strings.HasPrefix(home.Header().Get("Location"), "/signin") { |
| 152 | t.Fatalf("signed out: %d %q", home.Code, |
| 153 | home.Header().Get("Location")) |
| 154 | } |
| 155 | door := send(app.handler, http.MethodGet, "/signin", nil, nil) |
| 156 | if !strings.Contains(door.Body.String(), "estilo-door") { |
| 157 | t.Fatal("the sign-in page is not estilo's door") |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | // A stranger gets the same outcome as a member, and no email. |
| 162 | func TestAStrangerIsSentNothing(t *testing.T) { |
| 163 | app := wiredApp(t, t.TempDir(), Ana) |
| 164 | begin := send(app.handler, http.MethodPost, "/auth/begin", |
| 165 | url.Values{"address": {"nobody@example.com"}, "force": {"1"}}, nil) |
| 166 | if begin.Header().Get("Location") != "/signin?sent=1" || |
| 167 | app.mailer.count() != 0 { |
| 168 | t.Fatal("a stranger was told apart from a member, or mailed") |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | // Gate 9 in the lone shape: a member taken off the admission list can no |
| 173 | // longer sign in, and a session they already hold stops working. |
| 174 | func TestARemovedMemberIsOut(t *testing.T) { |
| 175 | dir := t.TempDir() |
| 176 | before := wiredApp(t, dir, Ana+","+Bo) |
| 177 | cookies := signIn(t, before, Bo) |
| 178 | if send(before.handler, http.MethodGet, "/", nil, |
| 179 | cookies).Code != http.StatusOK { |
| 180 | t.Fatal("Bo could not sign in while admitted") |
| 181 | } |
| 182 | written := send(before.handler, http.MethodPost, "/scratch", |
| 183 | url.Values{"body": {"Bo's own"}}, cookies) |
| 184 | pageID := strings.TrimPrefix(written.Header().Get("Location"), "/p/") |
| 185 | after := wiredApp(t, dir, Ana) |
| 186 | if code := send(after.handler, http.MethodGet, "/", nil, |
| 187 | cookies).Code; code != http.StatusNotFound { |
| 188 | t.Fatalf("Bo's old session still opens Today: %d", code) |
| 189 | } |
| 190 | send(after.handler, http.MethodPost, "/auth/begin", |
| 191 | url.Values{"address": {Bo}, "force": {"1"}}, nil) |
| 192 | if after.mailer.count() != 0 { |
| 193 | t.Fatal("Bo, removed, was sent a sign-in link") |
| 194 | } |
| 195 | // Under gate 5's reading, ownership survives removal: Bo's page is |
| 196 | // kept, and the S2 rule still answers for it, by name. |
| 197 | id, _, err := after.built.Store.RowID(context.Background(), pageID) |
| 198 | if err != nil { |
| 199 | t.Fatal(err) |
| 200 | } |
| 201 | readable, err := after.built.Store.MayRead(context.Background(), Bo, id, |
| 202 | after.built.Admit) |
| 203 | if err != nil || !readable { |
| 204 | t.Fatalf("Bo's own page after removal: %v, %v", readable, err) |
| 205 | } |
| 206 | } |
| 207 | |