oficina / base Public

Merge branch 'api/store-people' into main

claude agent, operated by paul@keymail.dev 5105b892f47e3ec9aaddeaec54312187bf0b410e parent a48071eparent 492a0c7
12 files changed, +1,220 −63
  • .rastrillo/budgets.txt +1 −0
  • docs/api/base-native-v1.md +75 −3
  • docs/superpowers/plans/2026-11-28-native-slice2-part1.md +3 −3
  • docs/superpowers/specs/2026-11-23-base-native-design.md +4 −2
  • internal/web/api_team.go +232 −0
  • internal/web/app.go +5 −0
  • internal/web/main_test.go +5 −1
  • internal/web/people.go +105 −41
  • internal/web/store.go +39 −12
  • internal/web/team_internal_test.go +235 −0
  • internal/webtest/api_team_test.go +508 −0
  • internal/webtest/oficina_harness_test.go +8 −1

CI passed — 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 ./...
=== govulncheck ===
go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./...
No vulnerabilities found.
=== gitleaks ===
8:18PM INF Unknown SCM platform. Use --platform to include links in findings. host=amadan.net
8:18PM INF 1 commits scanned.
8:18PM INF scanned ~2846469 bytes (2.85 MB) in 322ms
8:18PM INF no leaks found
=== budget ===
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size
budget size: 22 directories within budget
=== script-test ===
scripts/prepare-apps_test.sh
ok   releases lookup failure stops before ship
ok   app owned elsewhere stops the script
ok   apps listing failure stops before create
ok   ambiguous release dir is refused
ok   explicit version resolves the ambiguity
ok   releases match is exact, not substring
ok   shipped version is only promoted, existing app not created
ok   fresh account creates, ships, promotes to edge, enables
ok   failing promote stops the script
ok   ship is retried while uploads are rate limited
all passed
hack/fonts_test.sh
fonts_test: ok
=== test ===
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -count=1 ./...

receipt: test step 10.177s against a 60s target (the gate's other steps are not in this figure)
receipt: 16 packages ran, 0 cached, 6 without tests, 0 failed
receipt: slow package 8.859s amadan.net/oficina/base/internal/webtest
receipt: slow package 631ms amadan.net/oficina/base/internal/equipo
receipt: slow package 600ms amadan.net/oficina/base/internal/operations
receipt: slow package 451ms amadan.net/oficina/base/internal/issuer
receipt: slow package 264ms amadan.net/oficina/base/internal/consumer
receipt: slow test 1.51s amadan.net/oficina/base/internal/webtest TestHomeDoesNotWaitOnAStalledSnapshot
receipt: slow test 1.08s amadan.net/oficina/base/internal/webtest TestAskZoneIsToldOnce
receipt: slow test 620ms amadan.net/oficina/base/internal/webtest TestAskUploadStalledBodyFreesItsSlot
receipt: slow test 520ms amadan.net/oficina/base/internal/operations TestOperationsRefusals
receipt: slow test 510ms amadan.net/oficina/base/internal/equipo TestUploadRefusals
=== native ===
strings: copy review's strings.json is not here (git-ignored); its comparison skipped
strings: 120 in the catalog, 117 used
worktree-lib_test: ok
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 7f295e8..0eca99e 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -1 +1,2 @@
time internal/webtest 20s end-to-end web tests drive real servers, uploads and Equipo fakes; 8-13s on the hub since attachments
+size internal/webtest - 8500 test lines past 8000 with the Store and People JSON; the split by feature is owed, see discussion 8
diff --git a/docs/api/base-native-v1.md b/docs/api/base-native-v1.md
index ddc1135..e94af98 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`). 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
@@ -81,6 +81,78 @@ this document breaks the web too.
`currentColor`. Own pages' `url`s are Base's web pages.
- Optional keys are absent, never `null` or `""`.
+## Store and People
+
+What the Store and People pages show, from the same builders, behind the
+same member gate: any member's session, the native one or the web's
+cookie. Every answer is JSON and `no-store`. A refusal is
+`{"code": "…"}`. Without a session, or for someone who is no longer a
+member, every route answers `401 {"code":"unauthenticated"}`, as above.
+An app that hears `404` from a read is talking to an older Base, and opens
+the web page instead.
+
+### `GET /api/v1/store`
+
+```json
+{
+ "owner": true,
+ "rows": [
+ {"id": "welcome", "name": "Welcome", "summary": "…", "tint": "amber", "icon_svg": "<svg …>", "state": "installed", "error": ""},
+ {"id": "scratchpad", "name": "Scratchpad", "summary": "…", "tint": "rose", "icon_svg": "<svg …>", "state": "installing", "error": ""},
+ {"id": "contra", "name": "Contra", "summary": "…", "tint": "teal", "icon_svg": "<svg …>", "state": "failed", "error": "The app did not start answering"}
+ ]
+}
+```
+
+- `rows` is the whole catalogue, in its order. `state` is `""` (not
+ installed), `installing`, `installed` or `failed`. `error` is a failed
+ install's reason, and may be `""` (show "The install didn't finish.").
+- `owner` is whether this member may install and uninstall. Every member
+ sees the same rows.
+- `icon_svg` is line art drawn in `currentColor` on `tint`, as in
+ `/api/v1/home`.
+- `503 {"code":"unavailable"}`: Base couldn't read its installs.
+
+### `GET /api/v1/people`
+
+```json
+{
+ "owner": true,
+ "people": [
+ {"id": "…", "initial": "O", "name": "", "email": "owner@acme.test", "role": "owner"},
+ {"id": "…", "initial": "A", "name": "Ana Ruiz", "email": "ana@acme.test", "role": "member"},
+ {"id": "…", "initial": "B", "name": "", "email": "bob@acme.test", "role": "invited"}
+ ]
+}
+```
+
+- `people` is everyone here, in the order they were invited, as the page
+ lists them.
+- `role` is `owner`, `member`, or `invited` (hasn't signed in yet).
+- `name` is `""` for someone who has given none: show `email` then.
+ `initial` is the first letter of the name, or else of the address.
+- `owner` is whether this member may invite.
+- `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 (another request started it) answers `202` as it stands; anything else is `503 unavailable`, and nothing was started. A row that still reads failed then shows an earlier failure, not this attempt. |
+| `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/docs/superpowers/plans/2026-11-28-native-slice2-part1.md b/docs/superpowers/plans/2026-11-28-native-slice2-part1.md
index 4240420..42566d9 100644
--- a/docs/superpowers/plans/2026-11-28-native-slice2-part1.md
+++ b/docs/superpowers/plans/2026-11-28-native-slice2-part1.md
@@ -94,7 +94,7 @@ so: 22 numbered tasks, one spike, and one conditional task.
| Route | Answers |
|---|---|
| `GET /api/v1/store` | `200 {owner, rows}`; `503 {"code":"unavailable"}` when the installs can't be read |
- | `POST …/install` | `202 {"store"}` with the app installing. An app already installing answers `202` and one already installed answers `200`; neither calls `Start`. When `Start` fails, the store is read again: if the row now shows installing or failed, `202` as it stands; otherwise `503 unavailable`, and nothing was claimed. Also `403 owner_only`, `404 unknown_app` |
+ | `POST …/install` | `202 {"store"}` with the app installing. An app already installing answers `202` and one already installed answers `200`; neither calls `Start`. When `Start` fails, the store is read again: if the row now shows installing (another request claimed it), `202` as it stands; otherwise `503 unavailable`, and nothing was claimed. `Start` fails only before its claim, so a row reading failed then is an earlier failure (Fable's code review, should-fix 1). Also `403 owner_only`, `404 unknown_app` |
| `POST …/uninstall` | `200 {"store"}`, also when already uninstalled; `409 {"code":"busy"}`; `403`; `404`; `503` |
| `GET /api/v1/people` | `200 {owner, people: [{id, initial, name, email, role}]}`. `role` is `owner`, `member` or `invited`, so there's no `joined`. `503` when members can't be read |
| `POST /api/v1/people` | `200 {"person"}`: the person invited, or already here. Also `422 {"code":"bad_email"}`; `502 {"code":"mail_failed"}` (invite again to retry); `403 owner_only`; `415` for a non-JSON body; `503` |
@@ -263,8 +263,8 @@ Base, native/slice2-part1 (native/apple/Sources/BaseKit unless shown)
- **`TestAPIStoreInstall`:**
- the owner gets `202` with the row installing, and `Start` is called once;
- an app already installing gets `202`, and one already installed gets `200`, with `Start` not called;
- - a `Start` that fails having claimed the install (the row reads failed) gets `202`;
- - a `Start` that fails having claimed nothing gets `503`;
+ - a `Start` that fails while another request has claimed the install (the row reads installing) gets `202`;
+ - a `Start` that fails having claimed nothing gets `503`, a failed row's retry included;
- a member gets `403 owner_only`, and an unknown app `404 unknown_app`;
- no `Origin` gets `403` (CSRF).
- **`TestAPIStoreUninstall`:** `200`; `409 busy` (an installer answering `install.ErrBusy`); `200` when already uninstalled; `403`; `404`.
diff --git a/docs/superpowers/specs/2026-11-23-base-native-design.md b/docs/superpowers/specs/2026-11-23-base-native-design.md
index f3ea002..081c914 100644
--- a/docs/superpowers/specs/2026-11-23-base-native-design.md
+++ b/docs/superpowers/specs/2026-11-23-base-native-design.md
@@ -681,8 +681,10 @@ same owner checks:
- An app already installing answers `202`, and one already installed
`200`, both with the store and without starting anything.
- If starting the install fails, the store is read again. A row that now
- shows installing or failed answers `202` as it stands. Otherwise the
- answer is `503 unavailable`, and nothing was claimed.
+ shows installing (another request started it) answers `202` as it
+ stands. Otherwise the answer is `503 unavailable`, and nothing was
+ claimed: starting fails only before its claim, so a row that still
+ reads failed shows an earlier failure.
- **`POST /api/v1/store/{app}/uninstall`:** `200 {store}`, `409 busy`
while installing, `403 owner_only` if not the owner.
- **`GET /api/v1/people`:** `{owner, people: [{id, initial, name, email,
diff --git a/internal/web/api_team.go b/internal/web/api_team.go
new file mode 100644
index 0000000..b278838
--- /dev/null
+++ b/internal/web/api_team.go
@@ -0,0 +1,232 @@
+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"
+// and "People"): what the pages of the same names show, from the same
+// builders, behind the same member gate and owner checks.
+
+type apiStoreRow struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Summary string `json:"summary"`
+ Tint string `json:"tint"`
+ IconSVG string `json:"icon_svg"`
+ // State is "", "installing", "installed" or "failed"; Error is a
+ // failed install's reason, and may be "".
+ State string `json:"state"`
+ Error string `json:"error"`
+}
+
+type apiStore struct {
+ Owner bool `json:"owner"`
+ Rows []apiStoreRow `json:"rows"`
+}
+
+func storeJSON(c storeContent) apiStore {
+ out := apiStore{Owner: c.IsOwner, Rows: []apiStoreRow{}}
+ for _, r := range c.Rows {
+ out.Rows = append(out.Rows, apiStoreRow{ID: r.ID, Name: r.Name, Summary: r.Summary, Tint: r.Tint, IconSVG: r.Icon, State: r.State, Error: r.Error})
+ }
+ return out
+}
+
+type apiPerson struct {
+ ID string `json:"id"`
+ Initial string `json:"initial"`
+ // Name is "" for someone who has given none; show Email then.
+ Name string `json:"name"`
+ Email string `json:"email"`
+ // Role is "owner", "member" or "invited" (not yet signed in).
+ Role string `json:"role"`
+}
+
+type apiPeople struct {
+ Owner bool `json:"owner"`
+ People []apiPerson `json:"people"`
+}
+
+func personJSON(p personRow) apiPerson {
+ return apiPerson{ID: p.ID, Initial: p.Initial, Name: p.Name, Email: p.Email, Role: p.Role}
+}
+
+// apiStoreRead is GET /api/v1/store.
+func (a *app) apiStoreRead(w http.ResponseWriter, r *http.Request) {
+ me, _ := CurrentMember(r)
+ c, err := a.storeContent(r.Context(), me)
+ if err != nil {
+ a.logger.Error("api store", "err", err)
+ writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"})
+ return
+ }
+ writeJSON(w, http.StatusOK, storeJSON(c))
+}
+
+// apiPeopleRead is GET /api/v1/people.
+func (a *app) apiPeopleRead(w http.ResponseWriter, r *http.Request) {
+ me, _ := CurrentMember(r)
+ c, err := a.peopleContent(r.Context(), me)
+ if err != nil {
+ a.logger.Error("api people", "err", err)
+ writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"})
+ return
+ }
+ out := apiPeople{Owner: c.IsOwner, People: []apiPerson{}}
+ for _, p := range c.People {
+ out.People = append(out.People, personJSON(p))
+ }
+ 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. Start returns an error only from before its claim (install.go),
+// so when it fails the store is read again: a row that now reads installing
+// was claimed by another request and is answered 202 as it stands, and
+// anything else, a failed row included (that failure is an earlier one),
+// is 503: this attempt never started.
+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" {
+ 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 b37a994..d3d7e2e 100644
--- a/internal/web/app.go
+++ b/internal/web/app.go
@@ -208,6 +208,11 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger
r.Post("/settings/appearance", a.settingsAppearance)
r.Get("/api/v1/me", a.apiMeRead)
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/web/main_test.go b/internal/web/main_test.go
index f5e07b5..2ce8b44 100644
--- a/internal/web/main_test.go
+++ b/internal/web/main_test.go
@@ -7,4 +7,8 @@ import (
"amadan.net/rastrillo/rastrillo/budget"
)
-func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
+func TestMain(m *testing.M) {
+ code := budget.Main(m)
+ teamSchema.Remove()
+ os.Exit(code)
+}
diff --git a/internal/web/people.go b/internal/web/people.go
index 576a892..a46bc8b 100644
--- a/internal/web/people.go
+++ b/internal/web/people.go
@@ -12,81 +12,145 @@ import (
)
type personRow struct {
+ ID string
Initial string
Name string
Email string
- Owner bool
- Joined bool
+ // Role is "owner", "member" (signed in at least once) or "invited"
+ // (not yet), as the page's tag says.
+ Role string
+ Owner bool
+ // Joined is true once they have signed in.
+ Joined bool
}
type peoplePage struct {
- Name string
- IsOwner bool
+ Name string
+ peopleContent
BadEmail bool
MailFailed bool
- People []personRow
}
-func (a *app) people(w http.ResponseWriter, r *http.Request) {
- me, _ := CurrentMember(r)
- ms, err := store.Members(r.Context(), a.db)
+// peopleContent is what People shows a member: everyone here, in the
+// order they were invited. The People page and the JSON (GET
+// /api/v1/people) both draw from it.
+type peopleContent struct {
+ IsOwner bool
+ People []personRow
+}
+
+func (a *app) peopleContent(ctx context.Context, me store.Member) (peopleContent, error) {
+ ms, err := store.Members(ctx, a.db)
if err != nil {
- a.logger.Error("people: list", "err", err)
- http.Error(w, "unavailable", http.StatusServiceUnavailable)
- return
+ return peopleContent{}, fmt.Errorf("members: %w", err)
}
- page := peoplePage{Name: a.cfg.Name, IsOwner: me.Role == "owner", BadEmail: r.URL.Query().Get("problem") == "email", MailFailed: r.URL.Query().Get("problem") == "mail"}
+ c := peopleContent{IsOwner: me.Role == "owner"}
for _, m := range ms {
- label := m.Name
- if label == "" {
- label = m.Email
- }
- page.People = append(page.People, personRow{
- Initial: strings.ToUpper(string([]rune(label)[:1])),
- Name: m.Name, Email: m.Email,
- Owner: m.Role == "owner", Joined: m.JoinedAt != nil,
- })
+ c.People = append(c.People, personFor(m))
}
- w.Header().Set("Cache-Control", "no-store")
- a.render(w, r, "people", page)
+ return c, nil
}
-// invite adds a teammate and emails them where to sign in. Only the owner may.
-// Inviting an address that is already here changes nothing and sends nothing.
-func (a *app) invite(w http.ResponseWriter, r *http.Request) {
+func personFor(m store.Member) personRow {
+ label := m.Name
+ if label == "" {
+ label = m.Email
+ }
+ p := personRow{
+ ID: m.ID,
+ Initial: strings.ToUpper(string([]rune(label)[:1])),
+ Name: m.Name, Email: m.Email,
+ Owner: m.Role == "owner", Joined: m.JoinedAt != nil,
+ }
+ switch {
+ case p.Owner:
+ p.Role = "owner"
+ case p.Joined:
+ p.Role = "member"
+ default:
+ p.Role = "invited"
+ }
+ return p
+}
+
+func (a *app) people(w http.ResponseWriter, r *http.Request) {
me, _ := CurrentMember(r)
- if me.Role != "owner" {
- http.Error(w, "forbidden", http.StatusForbidden)
+ c, err := a.peopleContent(r.Context(), me)
+ if err != nil {
+ a.logger.Error("people", "err", err)
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
return
}
- email := strings.ToLower(strings.TrimSpace(r.PostFormValue("email")))
+ w.Header().Set("Cache-Control", "no-store")
+ a.render(w, r, "people", peoplePage{Name: a.cfg.Name, peopleContent: c,
+ BadEmail: r.URL.Query().Get("problem") == "email", MailFailed: r.URL.Query().Get("problem") == "mail"})
+}
+
+// inviteResult is how an invitation went, apart from Base failing to read
+// or write its own store.
+type inviteResult int
+
+const (
+ // inviteOK: the person is here, invited now or before.
+ inviteOK inviteResult = iota
+ // inviteBadEmail: what was given isn't one plain email address.
+ inviteBadEmail
+ // inviteMailFailed: they are invited, but the email wasn't delivered.
+ // Inviting them again sends it.
+ inviteMailFailed
+)
+
+// invitePerson adds a teammate by address, trimmed and lowercased, and
+// emails them where to sign in. An address already here changes nothing.
+// It sends until one invitation has been delivered, so a failed send is
+// retried by inviting again. The caller checks that the member asking is
+// the owner.
+func (a *app) invitePerson(ctx context.Context, raw string) (store.Member, inviteResult, error) {
+ email := strings.ToLower(strings.TrimSpace(raw))
addr, err := netmail.ParseAddress(email)
if err != nil || addr.Address != email || addr.Name != "" {
- http.Redirect(w, r, "/people?problem=email", http.StatusSeeOther)
- return
+ return store.Member{}, inviteBadEmail, nil
}
- m, _, err := store.Invite(r.Context(), a.db, email)
+ m, _, err := store.Invite(ctx, a.db, email)
if err != nil {
- a.logger.Error("invite", "err", err)
- http.Error(w, "unavailable", http.StatusServiceUnavailable)
- return
+ return store.Member{}, 0, fmt.Errorf("invite: %w", err)
}
- // Send until one invitation has been delivered, so a failed send can be
- // retried by inviting again.
if m.Role == "member" && m.JoinedAt == nil && m.InviteSentAt == nil {
- ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 20*time.Second)
+ // The send outlives the request: a person who gives up waiting
+ // mustn't leave a half-sent invitation.
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second)
defer cancel()
subject, body := invitationEmail(a.cfg.Name, a.cfg.Origin)
if err := a.mailer.Send(ctx, email, subject, body); err != nil {
a.logger.Error("invite: send", "err", err)
- http.Redirect(w, r, "/people?problem=mail", http.StatusSeeOther)
- return
+ return m, inviteMailFailed, nil
}
if err := store.MarkInviteSent(ctx, a.db, m.ID); err != nil {
a.logger.Error("invite: mark sent", "err", err)
}
}
- http.Redirect(w, r, "/people", http.StatusSeeOther)
+ return m, inviteOK, nil
+}
+
+// invite is the People page's form. Only the owner may.
+func (a *app) invite(w http.ResponseWriter, r *http.Request) {
+ me, _ := CurrentMember(r)
+ if me.Role != "owner" {
+ http.Error(w, "forbidden", http.StatusForbidden)
+ return
+ }
+ _, res, err := a.invitePerson(r.Context(), r.PostFormValue("email"))
+ switch {
+ case err != nil:
+ a.logger.Error("invite", "err", err)
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
+ case res == inviteBadEmail:
+ http.Redirect(w, r, "/people?problem=email", http.StatusSeeOther)
+ case res == inviteMailFailed:
+ http.Redirect(w, r, "/people?problem=mail", http.StatusSeeOther)
+ default:
+ http.Redirect(w, r, "/people", http.StatusSeeOther)
+ }
}
func invitationEmail(name, origin string) (subject, body string) {
diff --git a/internal/web/store.go b/internal/web/store.go
index 81e6c37..f2f29c8 100644
--- a/internal/web/store.go
+++ b/internal/web/store.go
@@ -1,7 +1,9 @@
package web
import (
+ "context"
"errors"
+ "fmt"
"html/template"
"net/http"
@@ -22,35 +24,60 @@ type storeRow struct {
func (s storeRow) IconHTML() template.HTML { return template.HTML(s.Icon) }
type storePage struct {
- Name string
+ Name string
+ storeContent
+ Busy bool
+}
+
+// storeContent is what the Store shows a member: a row per catalogue
+// entry, in the catalogue's order, with its install's state and error. The
+// Store page and the JSON (GET /api/v1/store) both draw from it.
+type storeContent struct {
IsOwner bool
- Busy bool
Installing bool
Rows []storeRow
}
-func (a *app) storePage(w http.ResponseWriter, r *http.Request) {
- me, _ := CurrentMember(r)
- installs, err := store.Installs(r.Context(), a.db)
+// row is the entry id's row, and false when the catalogue has no such app.
+func (c storeContent) row(id string) (storeRow, bool) {
+ for _, r := range c.Rows {
+ if r.ID == id {
+ return r, true
+ }
+ }
+ return storeRow{}, false
+}
+
+func (a *app) storeContent(ctx context.Context, me store.Member) (storeContent, error) {
+ installs, err := store.Installs(ctx, a.db)
if err != nil {
- a.logger.Error("store: installs", "err", err)
- http.Error(w, "unavailable", http.StatusServiceUnavailable)
- return
+ return storeContent{}, fmt.Errorf("installs: %w", err)
}
state := map[string]store.Install{}
for _, in := range installs {
state[in.App] = in
}
- page := storePage{Name: a.cfg.Name, IsOwner: me.Role == "owner", Busy: r.URL.Query().Get("problem") == "busy"}
+ c := storeContent{IsOwner: me.Role == "owner"}
for _, e := range catalog.All() {
in := state[e.ID]
- page.Rows = append(page.Rows, storeRow{Entry: e, State: in.State, Error: in.Error})
+ c.Rows = append(c.Rows, storeRow{Entry: e, State: in.State, Error: in.Error})
if in.State == "installing" {
- page.Installing = true
+ c.Installing = true
}
}
+ return c, nil
+}
+
+func (a *app) storePage(w http.ResponseWriter, r *http.Request) {
+ me, _ := CurrentMember(r)
+ c, err := a.storeContent(r.Context(), me)
+ if err != nil {
+ a.logger.Error("store", "err", err)
+ http.Error(w, "unavailable", http.StatusServiceUnavailable)
+ return
+ }
w.Header().Set("Cache-Control", "no-store")
- a.render(w, r, "store", page)
+ a.render(w, r, "store", storePage{Name: a.cfg.Name, storeContent: c, Busy: r.URL.Query().Get("problem") == "busy"})
}
// owner returns the catalogue entry named in the URL when the signed-in
diff --git a/internal/web/team_internal_test.go b/internal/web/team_internal_test.go
new file mode 100644
index 0000000..1029e1d
--- /dev/null
+++ b/internal/web/team_internal_test.go
@@ -0,0 +1,235 @@
+package web
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "log/slog"
+ "strings"
+ "sync"
+ "testing"
+
+ "amadan.net/rastrillo/rastrillo/dbtest"
+
+ "amadan.net/oficina/base/internal/catalog"
+ "amadan.net/oficina/base/internal/config"
+ "amadan.net/oficina/base/internal/store"
+)
+
+// The Store and People builders, shared by the pages and their JSON
+// (docs/api/base-native-v1.md "Store" and "People").
+
+var teamSchema = dbtest.FromSet(store.BootSchema)
+
+// teamMailer records what it sends, or fails while fail is set.
+type teamMailer struct {
+ mu sync.Mutex
+ to []string
+ fail bool
+}
+
+func (m *teamMailer) Send(_ context.Context, to, _, _ string) error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.fail {
+ return errors.New("smtp down")
+ }
+ m.to = append(m.to, to)
+ return nil
+}
+
+func (m *teamMailer) sent() int {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ return len(m.to)
+}
+
+// teamApp is just enough of the app for the builders: a database with the
+// owner in it, a name and origin, and a mailer.
+func teamApp(t *testing.T) (*app, *teamMailer, store.Member) {
+ t.Helper()
+ db := teamSchema.Open(t)
+ if err := store.Bootstrap(t.Context(), db, "owner@acme.test"); err != nil {
+ t.Fatal(err)
+ }
+ owner, _, err := store.MemberByEmail(t.Context(), db, "owner@acme.test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ m := &teamMailer{}
+ return &app{db: db, cfg: config.Config{Name: "Acme", Origin: "https://base.acme.test"}, mailer: m, logger: slog.New(slog.DiscardHandler)}, m, owner
+}
+
+func setInstall(t *testing.T, db *sql.DB, app, state, errMsg string) {
+ t.Helper()
+ if _, err := db.Exec(`INSERT INTO installs (app, host, state, error, updated_at) VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
+ ON CONFLICT (app) DO UPDATE SET state = excluded.state, error = excluded.error`, app, app+".acme.test", state, errMsg); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestStoreContent(t *testing.T) {
+ a, _, owner := teamApp(t)
+ all := catalog.All()
+ if len(all) < 3 {
+ t.Fatalf("the catalogue has %d entries; this test needs three", len(all))
+ }
+ setInstall(t, a.db, all[0].ID, "installed", "")
+ setInstall(t, a.db, all[1].ID, "failed", "The app did not start answering")
+
+ c, err := a.storeContent(t.Context(), owner)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !c.IsOwner || c.Installing {
+ t.Errorf("owner %v, installing %v", c.IsOwner, c.Installing)
+ }
+ if len(c.Rows) != len(all) {
+ t.Fatalf("%d rows for %d catalogue entries", len(c.Rows), len(all))
+ }
+ for i, e := range all {
+ if c.Rows[i].ID != e.ID {
+ t.Fatalf("row %d is %q, want the catalogue's order (%q)", i, c.Rows[i].ID, e.ID)
+ }
+ }
+ if r := c.Rows[0]; r.State != "installed" || r.Error != "" {
+ t.Errorf("installed row: %+v", r)
+ }
+ if r := c.Rows[1]; r.State != "failed" || r.Error != "The app did not start answering" {
+ t.Errorf("failed row: %+v", r)
+ }
+ if r := c.Rows[2]; r.State != "" {
+ t.Errorf("an app never installed: state %q", r.State)
+ }
+
+ setInstall(t, a.db, all[2].ID, "installing", "")
+ member, _, err := store.Invite(t.Context(), a.db, "maria@acme.test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ c, err = a.storeContent(t.Context(), member)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if c.IsOwner || !c.Installing || c.Rows[2].State != "installing" {
+ t.Errorf("a member, with one installing: owner %v, installing %v, %+v", c.IsOwner, c.Installing, c.Rows[2])
+ }
+
+ // A failed read is an error, never an empty store.
+ if _, err := a.db.Exec(`DROP TABLE installs`); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := a.storeContent(t.Context(), owner); err == nil {
+ t.Error("storeContent with the installs unreadable: no error")
+ }
+}
+
+func TestPeopleContent(t *testing.T) {
+ a, _, owner := teamApp(t)
+ ana, _, err := store.Invite(t.Context(), a.db, "ana@acme.test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := a.db.Exec(`UPDATE members SET name = 'Ana Ruiz' WHERE id = ?`, ana.ID); err != nil {
+ t.Fatal(err)
+ }
+ if err := store.MarkJoined(t.Context(), a.db, ana.ID); err != nil {
+ t.Fatal(err)
+ }
+ if err := store.MarkJoined(t.Context(), a.db, owner.ID); err != nil {
+ t.Fatal(err)
+ }
+ maria, _, err := store.Invite(t.Context(), a.db, "maria@acme.test")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ c, err := a.peopleContent(t.Context(), owner)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !c.IsOwner {
+ t.Error("the owner reads as not the owner")
+ }
+ var got []string
+ for _, p := range c.People {
+ got = append(got, strings.Join([]string{p.ID, p.Initial, p.Name, p.Email, p.Role}, "|"))
+ }
+ want := []string{
+ owner.ID + "|O||owner@acme.test|owner",
+ ana.ID + "|A|Ana Ruiz|ana@acme.test|member",
+ maria.ID + "|M||maria@acme.test|invited",
+ }
+ if strings.Join(got, "\n") != strings.Join(want, "\n") {
+ t.Fatalf("people:\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
+ }
+
+ c, err = a.peopleContent(t.Context(), maria)
+ if err != nil || c.IsOwner {
+ t.Errorf("a member: owner %v, %v", c.IsOwner, err)
+ }
+
+ if _, err := a.db.Exec(`DROP TABLE members`); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := a.peopleContent(t.Context(), owner); err == nil {
+ t.Error("peopleContent with the members unreadable: no error")
+ }
+}
+
+func TestInvitePerson(t *testing.T) {
+ a, mail, owner := teamApp(t)
+ ctx := t.Context()
+
+ m, res, err := a.invitePerson(ctx, " Maria@Acme.test ")
+ if err != nil || res != inviteOK || m.Email != "maria@acme.test" || m.Role != "member" {
+ t.Fatalf("invite: %+v %v %v", m, res, err)
+ }
+ if mail.sent() != 1 {
+ t.Fatalf("%d invitations sent, want 1", mail.sent())
+ }
+ // Delivered once, it is never sent again.
+ again, res, err := a.invitePerson(ctx, "maria@acme.test")
+ if err != nil || res != inviteOK || again.ID != m.ID || mail.sent() != 1 {
+ t.Fatalf("invite again: %+v %v %v, %d sent", again, res, err, mail.sent())
+ }
+ // An address already here, the owner's, sends nothing and answers them.
+ if o, res, err := a.invitePerson(ctx, "owner@acme.test"); err != nil || res != inviteOK || o.ID != owner.ID || mail.sent() != 1 {
+ t.Fatalf("invite the owner: %+v %v %v, %d sent", o, res, err, mail.sent())
+ }
+
+ for _, bad := range []string{"", "not an email", "Maria <maria@acme.test>", "maria@acme.test, bob@acme.test"} {
+ if _, res, err := a.invitePerson(ctx, bad); err != nil || res != inviteBadEmail {
+ t.Errorf("invite %q: %v %v", bad, res, err)
+ }
+ }
+ if ms, _ := store.Members(ctx, a.db); len(ms) != 2 {
+ t.Errorf("%d members after the bad addresses, want 2", len(ms))
+ }
+
+ // A failed send leaves the member invited with nothing delivered, so
+ // inviting again sends.
+ mail.mu.Lock()
+ mail.fail = true
+ mail.mu.Unlock()
+ if _, res, err := a.invitePerson(ctx, "bob@acme.test"); err != nil || res != inviteMailFailed {
+ t.Fatalf("invite with the mail down: %v %v", res, err)
+ }
+ mail.mu.Lock()
+ mail.fail = false
+ mail.mu.Unlock()
+ if b, res, err := a.invitePerson(ctx, "bob@acme.test"); err != nil || res != inviteOK || b.Email != "bob@acme.test" || mail.sent() != 2 {
+ t.Fatalf("invite after the failure: %+v %v %v, %d sent", b, res, err, mail.sent())
+ }
+ if b, _, _ := store.MemberByEmail(ctx, a.db, "bob@acme.test"); b.InviteSentAt == nil {
+ t.Error("the delivery was not recorded")
+ }
+
+ // The store failing is an error.
+ if _, err := a.db.Exec(`DROP TABLE members`); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := a.invitePerson(ctx, "carla@acme.test"); err == nil {
+ t.Error("invite with the members unwritable: no error")
+ }
+}
diff --git a/internal/webtest/api_team_test.go b/internal/webtest/api_team_test.go
new file mode 100644
index 0000000..8390d9c
--- /dev/null
+++ b/internal/webtest/api_team_test.go
@@ -0,0 +1,508 @@
+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, "<svg") {
+ t.Errorf("row %d: %+v, want the catalogue's %q in its order", i, row, e.ID)
+ }
+ }
+ states := map[string]string{}
+ for _, row := range s.Rows {
+ states[row.ID] = row.State + "|" + row.Error
+ }
+ if want := map[string]string{"welcome": "installed|", "scratchpad": "installing|", "contra": "failed|The app did not start answering"}; !reflect.DeepEqual(states, want) {
+ t.Errorf("states: %v, want %v", states, want)
+ }
+
+ // A member who isn't the owner sees the same rows.
+ m := jsonAnswer[apiStoreShape](t, "member's store", a.maria().nativeGet("/api/v1/store"), 200)
+ if m.Owner || !reflect.DeepEqual(m.Rows, s.Rows) {
+ t.Errorf("member's store: owner %v, rows differ: %v", m.Owner, !reflect.DeepEqual(m.Rows, s.Rows))
+ }
+
+ // The installs unreadable.
+ if _, err := a.DB.Exec(`DROP TABLE installs`); err != nil {
+ t.Fatal(err)
+ }
+ refusedWith(t, "installs unreadable", app.nativeGet("/api/v1/store"), http.StatusServiceUnavailable, "unavailable")
+}
+
+func TestAPIPeople(t *testing.T) {
+ a := newHomeApp(t)
+ a.link(ownerAddress, "subject-owner")
+ ana, _, err := store.Invite(t.Context(), a.DB, "ana@acme.test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := a.DB.Exec(`UPDATE members SET name = 'Ana Ruiz' WHERE id = ?`, ana.ID); err != nil {
+ t.Fatal(err)
+ }
+ a.newBrowser().link("ana@acme.test", "subject-ana")
+ invited, _, err := store.Invite(t.Context(), a.DB, "bob@acme.test")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ r := a.nativeSignIn("subject-owner").nativeGet("/api/v1/people")
+ var raw map[string]json.RawMessage
+ if err := json.Unmarshal([]byte(r.Body), &raw); err != nil || len(raw) != 2 {
+ t.Fatalf("people's keys: %v %s", err, r.Body)
+ }
+ p := jsonAnswer[apiPeopleShape](t, "people", r, 200)
+ want := apiPeopleShape{Owner: true, People: []apiPersonShape{
+ {ID: a.ownerID(), Initial: "O", Name: "", Email: ownerAddress, Role: "owner"},
+ {ID: ana.ID, Initial: "A", Name: "Ana Ruiz", Email: "ana@acme.test", Role: "member"},
+ {ID: invited.ID, Initial: "B", Name: "", Email: "bob@acme.test", Role: "invited"},
+ }}
+ if !reflect.DeepEqual(p, want) {
+ t.Fatalf("people:\n got %+v\nwant %+v", p, want)
+ }
+ // Each row has exactly these keys: no joined.
+ var rows struct {
+ People []map[string]any `json:"people"`
+ }
+ _ = json.Unmarshal([]byte(r.Body), &rows)
+ if len(rows.People[0]) != 5 {
+ t.Errorf("a person's keys: %v", rows.People[0])
+ }
+
+ // Ana, a member, and the owner's own browser session on the web, get
+ // the same people.
+ if got := jsonAnswer[apiPeopleShape](t, "ana's people", a.nativeSignIn("subject-ana").nativeGet("/api/v1/people"), 200); got.Owner || !reflect.DeepEqual(got.People, want.People) {
+ t.Errorf("ana's people: %+v", got)
+ }
+ if got := jsonAnswer[apiPeopleShape](t, "web session's people", a.get("/api/v1/people"), 200); !reflect.DeepEqual(got, want) {
+ t.Errorf("web session's people: %+v", got)
+ }
+
+ // A member row that can't be read: the list fails, while the owner's
+ // own row, which the gate reads, still can be.
+ if _, err := a.DB.Exec(`INSERT INTO members (id, email, role, invited_at) VALUES ('broken', 'broken@acme.test', 'member', 'not a time')`); err != nil {
+ t.Fatal(err)
+ }
+ refusedWith(t, "members unreadable", a.nativeSignIn("subject-owner").nativeGet("/api/v1/people"), http.StatusServiceUnavailable, "unavailable")
+}
+
+func TestAPITeamRefusesWithoutSession(t *testing.T) {
+ a := newHomeApp(t)
+ a.link(ownerAddress, "subject-owner")
+ maria := a.maria()
+ none := a.newBrowser()
+ for _, p := range []string{"/api/v1/store", "/api/v1/people"} {
+ r := none.nativeGet(p)
+ refusedWith(t, "no session, "+p, r, http.StatusUnauthorized, "unauthenticated")
+ if r.Location() != "" {
+ t.Errorf("no session, %s: redirected to %q", p, r.Location())
+ }
+ }
+
+ // Maria, removed, is nobody.
+ m, _, err := store.MemberByEmail(t.Context(), a.DB, "maria@acme.test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := store.RemoveMember(t.Context(), a.DB, m.ID); err != nil {
+ t.Fatal(err)
+ }
+ for _, p := range []string{"/api/v1/store", "/api/v1/people"} {
+ refusedWith(t, "removed, "+p, maria.nativeGet(p), http.StatusUnauthorized, "unauthenticated")
+ }
+}
+
+// Nothing removes a member (spec 7.4): there is no route to.
+func TestAPIPeopleHasNoRemove(t *testing.T) {
+ a := newHomeApp(t)
+ a.link(ownerAddress, "subject-owner")
+ ana, _, err := store.Invite(t.Context(), a.DB, "ana@acme.test")
+ if err != nil {
+ t.Fatal(err)
+ }
+ app := a.nativeSignIn("subject-owner")
+ req, _ := http.NewRequest(http.MethodDelete, a.base+"/api/v1/people/"+ana.ID, nil)
+ req.Header.Set("Origin", homeOrigin)
+ req.Header.Set("Accept", "application/json")
+ if r := app.do(req); r.Code != http.StatusNotFound && r.Code != http.StatusMethodNotAllowed {
+ t.Errorf("DELETE /api/v1/people/<id>: %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 <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)
+ }
+ // 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")
+ }
+}
diff --git a/internal/webtest/oficina_harness_test.go b/internal/webtest/oficina_harness_test.go
index 32daf42..2cba342 100644
--- a/internal/webtest/oficina_harness_test.go
+++ b/internal/webtest/oficina_harness_test.go
@@ -57,6 +57,13 @@ func newHomeApp(t *testing.T) *testApp { return newHomeAppWith(t, nil) }
// newHomeAppWith is newHomeApp with a last say over the configuration.
func newHomeAppWith(t *testing.T, tweak func(*config.Config)) *testApp {
+ t.Helper()
+ return newHomeAppInstalling(t, noInstaller{}, tweak)
+}
+
+// newHomeAppInstalling is newHomeAppWith with the Installer of the
+// caller's choice.
+func newHomeAppInstalling(t *testing.T, inst web.Installer, tweak func(*config.Config)) *testApp {
t.Helper()
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
d, err := db.Open(homeSchema.Path(t), logger)
@@ -90,7 +97,7 @@ func newHomeAppWith(t *testing.T, tweak func(*config.Config)) *testApp {
tweak(&cfg)
}
mailer := &capturingMailer{}
- h, err := web.App(d, cfg, mailer, noInstaller{}, logger)
+ h, err := web.App(d, cfg, mailer, inst, logger)
if err != nil {
t.Fatalf("web.App: %v", err)
}