package plan3test import ( "amadan.net/oficina/equipo/internal/equipo" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/migrate" "amadan.net/rastrillo/rastrillo/sessions" "crypto/rand" "errors" "io" "log/slog" "net/http" "net/http/httptest" "net/url" "path/filepath" "strings" "testing" "time" ) var invitee = equipo.Actor{Address: "invited@keymail.dev"} func issueInvite(t *testing.T, f *fixture, address string) (equipo.Invitation, string) { t.Helper() in, err := f.Store.CreateInvitation(ctx, owner, address, equipo.RoleMember, equipo.Mutation{RequestID: rand.Text()}) must(t, err) u, err := url.Parse(in.ShareURL) must(t, err) secret := u.Query().Get("secret") if secret == "" || in.Revision != 1 || in.State != "pending" || time.Until(in.ExpiresAt) < 167*time.Hour || time.Until(in.ExpiresAt) > 168*time.Hour { t.Fatal("invalid invitation") } return in, secret } func inviteSession(t *testing.T, f *fixture, a equipo.Actor) { t.Helper() token := rand.Text() now := time.Now().UTC() f.exec(t, "INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", sessions.HashToken(token), a.Address, "keymail", now.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano), now.Add(time.Hour).Format(time.RFC3339Nano)) f.Cookies[a.Address] = &http.Cookie{Name: "rastrillo_session", Value: token, Path: "/"} } func inviteForm(key string) url.Values { return url.Values{"request_id": {key}, "revision": {"1"}} } func verifyInviteIdentity(t *testing.T, f *fixture, address string, returnTo ...string) *httptest.ResponseRecorder { t.Helper() token := rand.Text() f.exec(t, "INSERT INTO auth_links(hash,address,purpose,expires_at) VALUES(?,?,?,?)", sessions.HashToken(token), address, "signin", time.Now().Add(time.Hour).UTC().Format(time.RFC3339)) values := url.Values{"token": {token}} if len(returnTo) != 0 { values.Set("return_to", returnTo[0]) } r := httptest.NewRequest("POST", "/auth/verify", strings.NewReader(values.Encode())) r.Header.Set("Origin", origin) r.Header.Set("Content-Type", "application/x-www-form-urlencoded") w := httptest.NewRecorder() f.Handler.ServeHTTP(w, r) for _, c := range w.Result().Cookies() { if c.Name == "rastrillo_session" && c.Value != "" { f.Cookies[address] = c } } return w } func inviteUpgradeFixture(t *testing.T) *fixture { t.Helper() d, err := db.Open(filepath.Join(t.TempDir(), "invites.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) must(t, err) t.Cleanup(func() { must(t, d.Close()) }) old := &migrate.Set{} for _, m := range equipo.BootSchema.All() { if m.ID != "equipo/0027_invitations" { old.Add(m) } } _, err = migrate.Apply(ctx, d, old) must(t, err) f := &fixture{DB: d} f.exec(t, "INSERT INTO teams(id,name,roster_epoch) VALUES('saved','Saved',7)") f.exec(t, "INSERT INTO members(address,role,revision,active,session_epoch) VALUES('saved@example.com','owner',4,1,123)") f.exec(t, "INSERT INTO audit_events(actor,kind,record_id) VALUES('saved@example.com','old.audit','old')") return f } func inviteRequest(t *testing.T, f *fixture, actor equipo.Actor, method, path string, values url.Values, cookie *http.Cookie, sites ...string) *httptest.ResponseRecorder { t.Helper() r := httptest.NewRequest(method, path, strings.NewReader(values.Encode())) if c := f.Cookies[actor.Address]; c != nil { r.AddCookie(c) } if cookie != nil { r.AddCookie(cookie) } if len(sites) == 0 { sites = []string{origin} } r.Header.Set("Origin", sites[0]) r.Header.Set("Content-Type", "application/x-www-form-urlencoded") w := httptest.NewRecorder() f.Handler.ServeHTTP(w, r) return w } func exchangeInvite(t *testing.T, f *fixture, in equipo.Invitation) *http.Cookie { t.Helper() w := inviteRequest(t, f, equipo.Actor{}, "GET", in.ShareURL, nil, nil) expectHTTP(t, w, 303) if w.Header().Get("Location") != "/invites/"+in.ID { t.Fatal("exchange redirect contains secret or wrong path") } for _, c := range w.Result().Cookies() { if c.Path == "/invites/"+in.ID { if !c.HttpOnly || !c.Secure || c.SameSite != http.SameSiteLaxMode || c.MaxAge <= 0 || c.MaxAge > 900 { t.Fatal("unsafe invite cookie", c.Name) } return c } } t.Fatal("missing path-scoped invite cookie") return nil } func wantInviteError(t *testing.T, got, want error) { t.Helper() if !errors.Is(got, want) { t.Fatalf("got %v, want %v", got, want) } } func inviteCSRF(t *testing.T, f *fixture, actor equipo.Actor, path string, values url.Values, cookie *http.Cookie) { t.Helper() for _, site := range []string{"https://evil.example", ""} { expectHTTP(t, inviteRequest(t, f, actor, "POST", path, values, cookie, site), 403) } } func invalidateInvite(t *testing.T, f *fixture, in equipo.Invitation, state string) { t.Helper() switch state { case "expired": f.exec(t, "UPDATE invitations SET expires_at=? WHERE id=?", time.Now().Add(-time.Hour), in.ID) case "revoked": for range 2 { must(t, f.Store.RevokeInvitation(ctx, owner, in.ID, equipo.Mutation{RequestID: "revoke", Revision: 1})) } case "removed inviter": must(t, f.Store.SetMember(ctx, peer, owner.Address, equipo.RoleMember, false, 1)) case "unavailable roster": f.exec(t, "ALTER TABLE members RENAME TO unavailable_members") case "unavailable invites": f.exec(t, "ALTER TABLE invitations RENAME TO unavailable_invitations") default: t.Fatal("unknown invitation fixture state", state) } } func inviteText(t *testing.T, body string, present bool, texts ...string) { t.Helper() for _, text := range texts { if strings.Contains(body, text) != present { t.Fatalf("page text %q: want present=%t", text, present) } } }