package webtest import ( "context" "encoding/json" "errors" "net/http" "net/url" "reflect" "strings" "sync" "testing" "amadan.net/oficina/base/internal/catalog" "amadan.net/oficina/base/internal/install" "amadan.net/oficina/base/internal/store" ) // Store and People for the native app (docs/api/base-native-v1.md "Store" // and "People"): the pages' own builders and owner checks, as JSON. type apiStoreRowShape struct { ID string `json:"id"` Name string `json:"name"` Summary string `json:"summary"` Tint string `json:"tint"` IconSVG string `json:"icon_svg"` State string `json:"state"` Error string `json:"error"` } type apiStoreShape struct { Owner bool `json:"owner"` Rows []apiStoreRowShape `json:"rows"` } type apiPersonShape struct { ID string `json:"id"` Initial string `json:"initial"` Name string `json:"name"` Email string `json:"email"` Role string `json:"role"` } type apiPeopleShape struct { Owner bool `json:"owner"` People []apiPersonShape `json:"people"` } // jsonAnswer checks an answer's status, that it is JSON and never cached, // and decodes it. func jsonAnswer[T any](t *testing.T, where string, r Resp, code int) T { t.Helper() if r.Code != code || r.Header.Get("Content-Type") != "application/json" || r.Header.Get("Cache-Control") != "no-store" { t.Fatalf("%s: %d %q %q, want %d JSON no-store: %s", where, r.Code, r.Header.Get("Content-Type"), r.Header.Get("Cache-Control"), code, r.Body) } return decode[T](t, r) } // refusedWith checks a JSON refusal's status and code. func refusedWith(t *testing.T, where string, r Resp, code int, want string) { t.Helper() got := jsonAnswer[map[string]any](t, where, r, code) if !reflect.DeepEqual(got, map[string]any{"code": want}) { t.Errorf("%s: %s, want {\"code\":%q}", where, r.Body, want) } } // maria is a member who isn't the owner, signed in on the native app. func (a *testApp) maria() *testApp { a.t.Helper() if _, _, err := store.Invite(context.Background(), a.DB, "maria@acme.test"); err != nil { a.t.Fatal(err) } a.newBrowser().link("maria@acme.test", "subject-maria") return a.nativeSignIn("subject-maria") } func TestAPIStore(t *testing.T) { a := newHomeApp(t) a.link(ownerAddress, "subject-owner") a.setInstall("welcome", "installed", "") a.setInstall("scratchpad", "installing", "") a.setInstall("contra", "failed", "The app did not start answering") app := a.nativeSignIn("subject-owner") r := app.nativeGet("/api/v1/store") var raw map[string]json.RawMessage if err := json.Unmarshal([]byte(r.Body), &raw); err != nil || len(raw) != 2 { t.Fatalf("store's keys: %v %s", err, r.Body) } s := jsonAnswer[apiStoreShape](t, "store", r, 200) if !s.Owner { t.Error("the owner reads as not the owner") } all := catalog.All() if len(s.Rows) != len(all) { t.Fatalf("%d rows for %d catalogue entries", len(s.Rows), len(all)) } for i, e := range all { row := s.Rows[i] if row.ID != e.ID || row.Name != e.Name || row.Summary != e.Summary || row.Tint != e.Tint || row.IconSVG != e.Icon || !strings.HasPrefix(row.IconSVG, ": %d %s", r.Code, r.Body) } if _, ok, err := store.MemberByEmail(t.Context(), a.DB, "ana@acme.test"); err != nil || !ok { t.Errorf("ana is gone: %v %v", ok, err) } } // teamInstaller is an Installer whose answers each test decides. start runs // inside Start, after the call is counted, and its error is Start's. type teamInstaller struct { mu sync.Mutex starts []string uninstalls []string start func(app string) error uninstallErr error } func (i *teamInstaller) Start(_ context.Context, app string) error { i.mu.Lock() i.starts = append(i.starts, app) start := i.start i.mu.Unlock() if start != nil { return start(app) } return nil } func (i *teamInstaller) Uninstall(_ context.Context, app string) error { i.mu.Lock() defer i.mu.Unlock() i.uninstalls = append(i.uninstalls, app) return i.uninstallErr } func (i *teamInstaller) counts() (starts, uninstalls int) { i.mu.Lock() defer i.mu.Unlock() return len(i.starts), len(i.uninstalls) } // rowState is app's state in a store answer. func rowState(t *testing.T, s apiStoreShape, app string) string { t.Helper() for _, r := range s.Rows { if r.ID == app { return r.State } } t.Fatalf("no row %q in %+v", app, s) return "" } type apiStoreAnswer struct { Store apiStoreShape `json:"store"` } // postNoOrigin is a native POST without the Origin the CSRF check needs. func (a *testApp) postNoOrigin(target string) Resp { a.t.Helper() req, _ := http.NewRequest(http.MethodPost, a.base+target, nil) req.Header.Set("Accept", "application/json") return a.do(req) } func TestAPIStoreInstall(t *testing.T) { inst := &teamInstaller{} a := newHomeAppInstalling(t, inst, nil) a.link(ownerAddress, "subject-owner") app := a.nativeSignIn("subject-owner") // The real Installer claims the install before Start returns. inst.start = func(id string) error { a.setInstall(id, "installing", ""); return nil } got := jsonAnswer[apiStoreAnswer](t, "install", app.nativePost("/api/v1/store/scratchpad/install", ""), http.StatusAccepted) if rowState(t, got.Store, "scratchpad") != "installing" || !got.Store.Owner { t.Errorf("install answered %+v", got.Store) } if s, _ := inst.counts(); s != 1 { t.Fatalf("%d Start calls, want 1", s) } // Already installing: 202 as it stands. Installed: 200. Neither starts. got = jsonAnswer[apiStoreAnswer](t, "installing again", app.nativePost("/api/v1/store/scratchpad/install", "{}"), http.StatusAccepted) if rowState(t, got.Store, "scratchpad") != "installing" { t.Errorf("installing again: %+v", got.Store) } a.setInstall("scratchpad", "installed", "") got = jsonAnswer[apiStoreAnswer](t, "installed", app.nativePost("/api/v1/store/scratchpad/install", ""), http.StatusOK) if rowState(t, got.Store, "scratchpad") != "installed" { t.Errorf("installed: %+v", got.Store) } if s, _ := inst.counts(); s != 1 { t.Fatalf("%d Start calls after the repeats, want 1", s) } // The real Start returns an error only from before its claim, so a // failed Start never started this attempt. A failed row whose retry // can't start is 503, not the old failure answered as if it ran. a.setInstall("contra", "failed", "The app did not start answering") inst.start = func(string) error { return errors.New("database locked") } refusedWith(t, "retry not started", app.nativePost("/api/v1/store/contra/install", ""), http.StatusServiceUnavailable, "unavailable") // Nor does an app never installed show anything for it. if _, err := a.DB.Exec(`DELETE FROM installs WHERE app = 'contra'`); err != nil { t.Fatal(err) } refusedWith(t, "start failed, nothing claimed", app.nativePost("/api/v1/store/contra/install", ""), http.StatusServiceUnavailable, "unavailable") // Another request claimed it meanwhile: the row reads installing, 202. inst.start = func(id string) error { a.setInstall(id, "installing", "") return errors.New("already claimed") } got = jsonAnswer[apiStoreAnswer](t, "claimed by another request", app.nativePost("/api/v1/store/contra/install", ""), http.StatusAccepted) if rowState(t, got.Store, "contra") != "installing" { t.Errorf("claimed by another request: %+v", got.Store) } // A failed row's retry that starts is 202, installing. a.setInstall("contra", "failed", "") inst.start = func(id string) error { a.setInstall(id, "installing", ""); return nil } got = jsonAnswer[apiStoreAnswer](t, "try again", app.nativePost("/api/v1/store/contra/install", ""), http.StatusAccepted) if rowState(t, got.Store, "contra") != "installing" { t.Errorf("try again: %+v", got.Store) } before, _ := inst.counts() refusedWith(t, "unknown app", app.nativePost("/api/v1/store/nope/install", ""), http.StatusNotFound, "unknown_app") refusedWith(t, "member", a.maria().nativePost("/api/v1/store/scratchpad/install", ""), http.StatusForbidden, "owner_only") if r := app.postNoOrigin("/api/v1/store/scratchpad/install"); r.Code != http.StatusForbidden { t.Errorf("no Origin: %d %s", r.Code, r.Body) } if r := app.postFrom("https://evil.test", "/api/v1/store/scratchpad/install", nil); r.Code != http.StatusForbidden { t.Errorf("another site: %d %s", r.Code, r.Body) } if s, _ := inst.counts(); s != before { t.Errorf("a refused install reached Start (%d -> %d)", before, s) } } func TestAPIStoreUninstall(t *testing.T) { inst := &teamInstaller{} a := newHomeAppInstalling(t, inst, nil) a.link(ownerAddress, "subject-owner") app := a.nativeSignIn("subject-owner") a.setInstall("scratchpad", "installed", "") // The real Installer removes the row; the fake leaves that to the test. got := jsonAnswer[apiStoreAnswer](t, "uninstall", app.nativePost("/api/v1/store/scratchpad/uninstall", ""), http.StatusOK) if !got.Store.Owner || len(got.Store.Rows) != len(catalog.All()) { t.Errorf("uninstall answered %+v", got.Store) } if _, u := inst.counts(); u != 1 { t.Fatalf("%d Uninstall calls, want 1", u) } inst.uninstallErr = install.ErrBusy refusedWith(t, "busy", app.nativePost("/api/v1/store/scratchpad/uninstall", ""), http.StatusConflict, "busy") inst.uninstallErr = store.ErrNoInstall jsonAnswer[apiStoreAnswer](t, "already uninstalled", app.nativePost("/api/v1/store/scratchpad/uninstall", ""), http.StatusOK) inst.uninstallErr = errors.New("platform down") refusedWith(t, "uninstall failed", app.nativePost("/api/v1/store/scratchpad/uninstall", ""), http.StatusServiceUnavailable, "unavailable") inst.uninstallErr = nil _, before := inst.counts() refusedWith(t, "unknown app", app.nativePost("/api/v1/store/nope/uninstall", ""), http.StatusNotFound, "unknown_app") refusedWith(t, "member", a.maria().nativePost("/api/v1/store/scratchpad/uninstall", ""), http.StatusForbidden, "owner_only") if r := app.postNoOrigin("/api/v1/store/scratchpad/uninstall"); r.Code != http.StatusForbidden { t.Errorf("no Origin: %d %s", r.Code, r.Body) } if _, u := inst.counts(); u != before { t.Errorf("a refused uninstall reached Uninstall (%d -> %d)", before, u) } // The store unreadable after the uninstall. if _, err := a.DB.Exec(`DROP TABLE installs`); err != nil { t.Fatal(err) } refusedWith(t, "store unreadable", app.nativePost("/api/v1/store/scratchpad/uninstall", ""), http.StatusServiceUnavailable, "unavailable") } type apiPersonAnswer struct { Person apiPersonShape `json:"person"` } func TestAPIPeopleInvite(t *testing.T) { a := newHomeApp(t) a.link(ownerAddress, "subject-owner") app := a.nativeSignIn("subject-owner") n := len(a.mailbox()) got := jsonAnswer[apiPersonAnswer](t, "invite", app.nativePost("/api/v1/people", `{"email":" Maria@Acme.test "}`), http.StatusOK) m, ok, err := store.MemberByEmail(t.Context(), a.DB, "maria@acme.test") if err != nil || !ok { t.Fatalf("maria: %v %v", ok, err) } if want := (apiPersonShape{ID: m.ID, Initial: "M", Email: "maria@acme.test", Role: "invited"}); got.Person != want { t.Errorf("invite answered %+v, want %+v", got.Person, want) } box := a.mailbox() if len(box) != n+1 || box[len(box)-1].To != "maria@acme.test" { t.Fatalf("want one invitation to maria, mailbox grew by %d", len(box)-n) } // The same address again sends nothing, and answers the same person. again := jsonAnswer[apiPersonAnswer](t, "invite again", app.nativePost("/api/v1/people", `{"email":"maria@acme.test"}`), http.StatusOK) if again.Person != got.Person || len(a.mailbox()) != n+1 { t.Errorf("invite again: %+v, mailbox grew by %d", again.Person, len(a.mailbox())-n) } // The owner is already here. if o := jsonAnswer[apiPersonAnswer](t, "invite the owner", app.nativePost("/api/v1/people", `{"email":"`+ownerAddress+`"}`), http.StatusOK); o.Person.Role != "owner" || o.Person.ID != a.ownerID() { t.Errorf("invite the owner: %+v", o.Person) } for _, body := range []string{`{"email":"not an email"}`, `{"email":""}`, `{}`, `{"email":"Bob "}`} { refusedWith(t, "bad address "+body, app.nativePost("/api/v1/people", body), http.StatusUnprocessableEntity, "bad_email") } // A failing mailer: 502, and inviting again sends. a.mail.mu.Lock() a.mail.fail = true a.mail.mu.Unlock() refusedWith(t, "mail down", app.nativePost("/api/v1/people", `{"email":"bob@acme.test"}`), http.StatusBadGateway, "mail_failed") a.mail.mu.Lock() a.mail.fail = false a.mail.mu.Unlock() bob := jsonAnswer[apiPersonAnswer](t, "retry", app.nativePost("/api/v1/people", `{"email":"bob@acme.test"}`), http.StatusOK) if bob.Person.Email != "bob@acme.test" || len(a.mailbox()) != n+2 { t.Errorf("retry: %+v, mailbox grew by %d", bob.Person, len(a.mailbox())-n) } // Refusals that send nothing. Maria signs in first, which mails her a // sign-in link. maria := a.maria() sent := len(a.mailbox()) refusedWith(t, "member", maria.nativePost("/api/v1/people", `{"email":"carla@acme.test"}`), http.StatusForbidden, "owner_only") form := app.postFrom(homeOrigin, "/api/v1/people", url.Values{"email": {"carla@acme.test"}}) if form.Code != http.StatusUnsupportedMediaType { t.Errorf("a form body: %d %s", form.Code, form.Body) } big := `{"email":"carla@acme.test","pad":"` + strings.Repeat("x", 4<<10) + `"}` if r := app.nativePost("/api/v1/people", big); r.Code != http.StatusRequestEntityTooLarge { t.Errorf("a body over 4 KiB: %d %s", r.Code, r.Body) } if r := app.nativePost("/api/v1/people", `{"email":`); r.Code != http.StatusBadRequest { t.Errorf("broken JSON: %d %s", r.Code, r.Body) } if len(a.mailbox()) != sent { t.Errorf("a refused invite sent mail") } // Inside the CSRF check: no Origin, or another site's, with a JSON body. for _, origin := range []string{"", "https://evil.test"} { req, _ := http.NewRequest(http.MethodPost, a.base+"/api/v1/people", strings.NewReader(`{"email":"carla@acme.test"}`)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") if origin != "" { req.Header.Set("Origin", origin) } if r := app.do(req); r.Code != http.StatusForbidden { t.Errorf("invite with Origin %q: %d %s", origin, r.Code, r.Body) } } if len(a.mailbox()) != sent { t.Errorf("a refused invite sent mail") } if _, ok, _ := store.MemberByEmail(t.Context(), a.DB, "carla@acme.test"); ok { t.Error("a refused invite added carla") } // The owner's web session (the cookie from signing in on the web) may // write too: it is the same member gate. if web := jsonAnswer[apiPersonAnswer](t, "invite from the web session", a.nativePost("/api/v1/people", `{"email":"dana@acme.test"}`), http.StatusOK); web.Person.Email != "dana@acme.test" { t.Errorf("invite from the web session: %+v", web.Person) } // The members can't be written. if _, err := a.DB.Exec(`CREATE TRIGGER no_invites BEFORE INSERT ON members BEGIN SELECT RAISE(ABORT, 'locked'); END`); err != nil { t.Fatal(err) } refusedWith(t, "members unwritable", app.nativePost("/api/v1/people", `{"email":"erin@acme.test"}`), http.StatusServiceUnavailable, "unavailable") } // Without a session every write is 401, as the reads are. func TestAPITeamWritesRefuseWithoutSession(t *testing.T) { a := newHomeApp(t) a.link(ownerAddress, "subject-owner") none := a.newBrowser() for _, p := range []string{"/api/v1/store/scratchpad/install", "/api/v1/store/scratchpad/uninstall", "/api/v1/people"} { refusedWith(t, "no session, POST "+p, none.nativePost(p, `{"email":"x@acme.test"}`), http.StatusUnauthorized, "unauthenticated") } }