oficina / base Public

The Store and People writes for the native app

Task 3 of the native slice 2 part 1 plan, P2's answers:
- POST /api/v1/store/{app}/install: 202 {store} installing; 202 already
  installing and 200 installed without calling Start; a failed Start is
  202 if the row now reads installing or failed, else 503 unavailable.
- POST /api/v1/store/{app}/uninstall: 200 {store}, also when already
  uninstalled; 409 busy; 503.
- POST /api/v1/people, {email}: 200 {person}; 422 bad_email; 502
  mail_failed (invite again to send); 415 json_only; 413 too_large over
  4 KiB; 400 bad_request.
Each write is the owner's (403 owner_only first), 404 unknown_app for the
Store, inside the CSRF check. The docs gain the table.

Gate: go test -p 4 ./internal/webtest -run 'TestAPIStore|TestAPIPeople|TestAPITeam': ok.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Summary

Task 3: the Store and People JSON writes, documented
claude agent, operated by paul@keymail.dev 5b27e0bd4797a0313b79f98eac590e7cbfc87cd6 parent e07282e
4 files changed, +427 −3
  • docs/api/base-native-v1.md +21 −3
  • internal/web/api_team.go +149 −0
  • internal/web/app.go +3 −0
  • internal/webtest/api_team_test.go +254 −0

CI failed — run details

CI log
=== build ===
CGO_ENABLED=0 go build ./...
=== vet ===
go vet ./...
=== fmt-check ===
=== staticcheck ===
go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./...
internal/webtest/api_team_test.go:438:2: this value of sent is never used (SA4006)
exit status 1
make: *** [Makefile:63: staticcheck] Error 1

amadan: step staticcheck failed: exit status 2

amadan: job failed at step staticcheck — its output is above, not at the tail of this log
diff --git a/docs/api/base-native-v1.md b/docs/api/base-native-v1.md
index a9c822a..8f50d7a 100644
--- a/docs/api/base-native-v1.md
+++ b/docs/api/base-native-v1.md
@@ -2,9 +2,9 @@
What Base's Mac and iPhone app may rely on. Everything here is pinned by
tests in `internal/webtest` (`native_test.go`, `api_test.go`,
-`ask_native_contract_test.go`, `ask_oficina_native_test.go`, `api_team_test.go`). The Ask
-routes are the same ones the web's `ask.js` uses, so a change that breaks
-this document breaks the web too.
+`api_team_test.go`, `ask_native_contract_test.go`,
+`ask_oficina_native_test.go`). The Ask routes are the same ones the web's
+`ask.js` uses, so a change that breaks this document breaks the web too.
## Signing in
@@ -135,6 +135,24 @@ the web page instead.
- `503 {"code":"unavailable"}`: Base couldn't read its members.
- Nothing removes a member: `DELETE /api/v1/people/{id}` isn't a route.
+### The writes
+
+The owner's alone. They are POSTs, inside Base's CSRF check, which the
+kit's `Origin` passes. Install and uninstall take no body (one is
+ignored); an invite takes JSON.
+
+| Route | Answers |
+|---|---|
+| `POST /api/v1/store/{app}/install` | `202 {"store": …}` with the app installing: poll `GET /api/v1/store` every 2 s while any row is. An app already installing answers `202`, and one already installed `200`, and neither starts anything. A failed row may be installed again (the page's "Try again"). If the install couldn't be started, the store is read again: a row that now shows installing or failed answers `202` as it stands; otherwise `503 unavailable`, and nothing was claimed. |
+| `POST /api/v1/store/{app}/uninstall` | `200 {"store": …}`, also when it was uninstalled already. `409 {"code":"busy"}` while it is still installing ("This app is still installing. Try again in a moment."). `503 unavailable`. |
+| `POST /api/v1/people` | Body `{"email": "…"}`, trimmed and lowercased. `200 {"person": …}`, a person as in `GET /api/v1/people`: invited now, or already here (nothing is sent then). `422 {"code":"bad_email"}`: not one plain address. `502 {"code":"mail_failed"}`: they are invited but the email wasn't delivered; invite them again to send it. `415 {"code":"json_only"}` for a body that isn't `application/json`, `413 {"code":"too_large"}` over 4 KiB, `400 {"code":"bad_request"}` for JSON that doesn't parse. `503 unavailable`. |
+
+Every write also answers `403 {"code":"owner_only"}` to a member who isn't
+the owner, before anything else, and the Store's `404
+{"code":"unknown_app"}` for an app the catalogue doesn't have. A POST with
+no `Origin` (or another site's) is `403` in plain text, from the CSRF
+check.
+
## Ask Base
No Ask route answers `401` while Base's session is good: Equipo refusing
diff --git a/internal/web/api_team.go b/internal/web/api_team.go
index e0ecb94..3091a3d 100644
--- a/internal/web/api_team.go
+++ b/internal/web/api_team.go
@@ -1,7 +1,16 @@
package web
import (
+ "encoding/json"
+ "errors"
+ "io"
"net/http"
+
+ "github.com/go-chi/chi/v5"
+
+ "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"
@@ -79,3 +88,143 @@ func (a *app) apiPeopleRead(w http.ResponseWriter, r *http.Request) {
}
writeJSON(w, http.StatusOK, out)
}
+
+// apiStoreAnswer is a Store write's answer: the store as it now stands.
+type apiStoreAnswer struct {
+ Store apiStore `json:"store"`
+}
+
+// apiOwner is the catalogue entry named in the URL when the member asking
+// is the owner. Otherwise it answers 403 owner_only or 404 unknown_app, in
+// that order, as the page's owner check does.
+func (a *app) apiOwner(w http.ResponseWriter, me store.Member, id string) (catalog.Entry, bool) {
+ if me.Role != "owner" {
+ writeJSON(w, http.StatusForbidden, apiError{Code: "owner_only"})
+ return catalog.Entry{}, false
+ }
+ e, ok := catalog.Get(id)
+ if !ok {
+ writeJSON(w, http.StatusNotFound, apiError{Code: "unknown_app"})
+ return catalog.Entry{}, false
+ }
+ return e, true
+}
+
+// apiStoreInstall is POST /api/v1/store/{app}/install. It answers 202 with
+// the app installing, and the app polls the store until it isn't. An app
+// already installing answers 202 and one installed 200, and neither starts
+// anything. When Start fails the store is read again: a row that now shows
+// installing or failed is answered 202 as it stands, and otherwise nothing
+// was claimed and the answer is 503.
+func (a *app) apiStoreInstall(w http.ResponseWriter, r *http.Request) {
+ me, _ := CurrentMember(r)
+ e, ok := a.apiOwner(w, me, chi.URLParam(r, "app"))
+ if !ok {
+ return
+ }
+ c, err := a.storeContent(r.Context(), me)
+ if err != nil {
+ a.logger.Error("api install", "app", e.ID, "err", err)
+ writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"})
+ return
+ }
+ switch row, _ := c.row(e.ID); row.State {
+ case "installing":
+ writeJSON(w, http.StatusAccepted, apiStoreAnswer{storeJSON(c)})
+ return
+ case "installed":
+ writeJSON(w, http.StatusOK, apiStoreAnswer{storeJSON(c)})
+ return
+ }
+ startErr := a.inst.Start(r.Context(), e.ID)
+ if startErr != nil {
+ a.logger.Error("api install", "app", e.ID, "err", startErr)
+ }
+ if c, err = a.storeContent(r.Context(), me); err != nil {
+ a.logger.Error("api install", "app", e.ID, "err", err)
+ writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"})
+ return
+ }
+ if row, _ := c.row(e.ID); startErr != nil && row.State != "installing" && row.State != "failed" {
+ writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"})
+ return
+ }
+ writeJSON(w, http.StatusAccepted, apiStoreAnswer{storeJSON(c)})
+}
+
+// apiStoreUninstall is POST /api/v1/store/{app}/uninstall: 200 with the
+// store, also when it was uninstalled already, and 409 busy while it is
+// still installing.
+func (a *app) apiStoreUninstall(w http.ResponseWriter, r *http.Request) {
+ me, _ := CurrentMember(r)
+ e, ok := a.apiOwner(w, me, chi.URLParam(r, "app"))
+ if !ok {
+ return
+ }
+ switch err := a.inst.Uninstall(r.Context(), e.ID); {
+ case errors.Is(err, install.ErrBusy):
+ writeJSON(w, http.StatusConflict, apiError{Code: "busy"})
+ return
+ case errors.Is(err, store.ErrNoInstall):
+ // Already uninstalled.
+ case err != nil:
+ a.logger.Error("api uninstall", "app", e.ID, "err", err)
+ writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"})
+ return
+ }
+ c, err := a.storeContent(r.Context(), me)
+ if err != nil {
+ a.logger.Error("api uninstall", "app", e.ID, "err", err)
+ writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"})
+ return
+ }
+ writeJSON(w, http.StatusOK, apiStoreAnswer{storeJSON(c)})
+}
+
+// maxInviteBody bounds POST /api/v1/people's body, {"email": …}.
+const maxInviteBody = 4 << 10
+
+// apiPeopleInvite is POST /api/v1/people, {"email": …}: the People form's
+// invitation, as JSON. It answers 200 with the person, invited now or
+// already here.
+func (a *app) apiPeopleInvite(w http.ResponseWriter, r *http.Request) {
+ me, _ := CurrentMember(r)
+ if me.Role != "owner" {
+ writeJSON(w, http.StatusForbidden, apiError{Code: "owner_only"})
+ return
+ }
+ if !isJSONBody(r) {
+ writeJSON(w, http.StatusUnsupportedMediaType, apiError{Code: "json_only"})
+ return
+ }
+ raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxInviteBody))
+ if err != nil {
+ if mbe := (*http.MaxBytesError)(nil); errors.As(err, &mbe) {
+ writeJSON(w, http.StatusRequestEntityTooLarge, apiError{Code: "too_large"})
+ return
+ }
+ writeJSON(w, http.StatusBadRequest, apiError{Code: "bad_request"})
+ return
+ }
+ var in struct {
+ Email string `json:"email"`
+ }
+ if err := json.Unmarshal(raw, &in); err != nil {
+ writeJSON(w, http.StatusBadRequest, apiError{Code: "bad_request"})
+ return
+ }
+ m, res, err := a.invitePerson(r.Context(), in.Email)
+ switch {
+ case err != nil:
+ a.logger.Error("api invite", "err", err)
+ writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"})
+ case res == inviteBadEmail:
+ writeJSON(w, http.StatusUnprocessableEntity, apiError{Code: "bad_email"})
+ case res == inviteMailFailed:
+ writeJSON(w, http.StatusBadGateway, apiError{Code: "mail_failed"})
+ default:
+ writeJSON(w, http.StatusOK, struct {
+ Person apiPerson `json:"person"`
+ }{personJSON(personFor(m))})
+ }
+}
diff --git a/internal/web/app.go b/internal/web/app.go
index 505341c..d3d7e2e 100644
--- a/internal/web/app.go
+++ b/internal/web/app.go
@@ -210,6 +210,9 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger
r.Get("/api/v1/home", a.apiHomeRead)
r.Get("/api/v1/store", a.apiStoreRead)
r.Get("/api/v1/people", a.apiPeopleRead)
+ r.Post("/api/v1/store/{app}/install", a.apiStoreInstall)
+ r.Post("/api/v1/store/{app}/uninstall", a.apiStoreUninstall)
+ r.Post("/api/v1/people", a.apiPeopleInvite)
r.With(ownSignInOnly).Post(registerBeginPath, a.pk.RegisterBegin)
r.With(ownSignInOnly).Post(registerFinishPath, a.pk.RegisterFinish)
r.Method(http.MethodGet, "/authorize", authorize)
diff --git a/internal/webtest/api_team_test.go b/internal/webtest/api_team_test.go
index acc10bd..be6c0f1 100644
--- a/internal/webtest/api_team_test.go
+++ b/internal/webtest/api_team_test.go
@@ -3,12 +3,16 @@ 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"
)
@@ -214,3 +218,253 @@ func TestAPIPeopleHasNoRemove(t *testing.T) {
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)
+ }
+
+ // Start failing, having claimed the install, which reads failed: 202
+ // with the row as it stands.
+ inst.start = func(id string) error {
+ a.setInstall(id, "failed", "The app did not start answering")
+ return errors.New("platform down")
+ }
+ got = jsonAnswer[apiStoreAnswer](t, "start failed, claimed", app.nativePost("/api/v1/store/contra/install", ""), http.StatusAccepted)
+ if rowState(t, got.Store, "contra") != "failed" {
+ t.Errorf("start failed, claimed: %+v", got.Store)
+ }
+ // Start failing having claimed nothing: 503, and nothing is installing.
+ inst.start = func(string) error { return errors.New("database locked") }
+ 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")
+ // A failed row's retry starts again.
+ 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 <bob@acme.test>"}`} {
+ 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)
+ }
+ sent := len(a.mailbox())
+
+ // Refusals that send nothing.
+ refusedWith(t, "member", a.maria().nativePost("/api/v1/people", `{"email":"carla@acme.test"}`), http.StatusForbidden, "owner_only")
+ sent = len(a.mailbox()) // maria's own sign-in link
+ 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")
+ }
+ if _, ok, _ := store.MemberByEmail(t.Context(), a.DB, "carla@acme.test"); ok {
+ t.Error("a refused invite added carla")
+ }
+}
+
+// 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")
+ }
+}