| 1 | package webtest |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "net/http" |
| 8 | "net/url" |
| 9 | "reflect" |
| 10 | "strings" |
| 11 | "sync" |
| 12 | "testing" |
| 13 | |
| 14 | "amadan.net/oficina/base/internal/catalog" |
| 15 | "amadan.net/oficina/base/internal/install" |
| 16 | "amadan.net/oficina/base/internal/store" |
| 17 | ) |
| 18 | |
| 19 | // Store and People for the native app (docs/api/base-native-v1.md "Store" |
| 20 | // and "People"): the pages' own builders and owner checks, as JSON. |
| 21 | |
| 22 | type apiStoreRowShape struct { |
| 23 | ID string `json:"id"` |
| 24 | Name string `json:"name"` |
| 25 | Summary string `json:"summary"` |
| 26 | Tint string `json:"tint"` |
| 27 | IconSVG string `json:"icon_svg"` |
| 28 | State string `json:"state"` |
| 29 | Error string `json:"error"` |
| 30 | } |
| 31 | |
| 32 | type apiStoreShape struct { |
| 33 | Owner bool `json:"owner"` |
| 34 | Rows []apiStoreRowShape `json:"rows"` |
| 35 | } |
| 36 | |
| 37 | type apiPersonShape struct { |
| 38 | ID string `json:"id"` |
| 39 | Initial string `json:"initial"` |
| 40 | Name string `json:"name"` |
| 41 | Email string `json:"email"` |
| 42 | Role string `json:"role"` |
| 43 | } |
| 44 | |
| 45 | type apiPeopleShape struct { |
| 46 | Owner bool `json:"owner"` |
| 47 | People []apiPersonShape `json:"people"` |
| 48 | } |
| 49 | |
| 50 | // jsonAnswer checks an answer's status, that it is JSON and never cached, |
| 51 | // and decodes it. |
| 52 | func jsonAnswer[T any](t *testing.T, where string, r Resp, code int) T { |
| 53 | t.Helper() |
| 54 | if r.Code != code || r.Header.Get("Content-Type") != "application/json" || r.Header.Get("Cache-Control") != "no-store" { |
| 55 | 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) |
| 56 | } |
| 57 | return decode[T](t, r) |
| 58 | } |
| 59 | |
| 60 | // refusedWith checks a JSON refusal's status and code. |
| 61 | func refusedWith(t *testing.T, where string, r Resp, code int, want string) { |
| 62 | t.Helper() |
| 63 | got := jsonAnswer[map[string]any](t, where, r, code) |
| 64 | if !reflect.DeepEqual(got, map[string]any{"code": want}) { |
| 65 | t.Errorf("%s: %s, want {\"code\":%q}", where, r.Body, want) |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | // maria is a member who isn't the owner, signed in on the native app. |
| 70 | func (a *testApp) maria() *testApp { |
| 71 | a.t.Helper() |
| 72 | if _, _, err := store.Invite(context.Background(), a.DB, "maria@acme.test"); err != nil { |
| 73 | a.t.Fatal(err) |
| 74 | } |
| 75 | a.newBrowser().link("maria@acme.test", "subject-maria") |
| 76 | return a.nativeSignIn("subject-maria") |
| 77 | } |
| 78 | |
| 79 | func TestAPIStore(t *testing.T) { |
| 80 | a := newHomeApp(t) |
| 81 | a.link(ownerAddress, "subject-owner") |
| 82 | a.setInstall("welcome", "installed", "") |
| 83 | a.setInstall("scratchpad", "installing", "") |
| 84 | a.setInstall("contra", "failed", "The app did not start answering") |
| 85 | app := a.nativeSignIn("subject-owner") |
| 86 | |
| 87 | r := app.nativeGet("/api/v1/store") |
| 88 | var raw map[string]json.RawMessage |
| 89 | if err := json.Unmarshal([]byte(r.Body), &raw); err != nil || len(raw) != 2 { |
| 90 | t.Fatalf("store's keys: %v %s", err, r.Body) |
| 91 | } |
| 92 | s := jsonAnswer[apiStoreShape](t, "store", r, 200) |
| 93 | if !s.Owner { |
| 94 | t.Error("the owner reads as not the owner") |
| 95 | } |
| 96 | all := catalog.All() |
| 97 | if len(s.Rows) != len(all) { |
| 98 | t.Fatalf("%d rows for %d catalogue entries", len(s.Rows), len(all)) |
| 99 | } |
| 100 | for i, e := range all { |
| 101 | row := s.Rows[i] |
| 102 | 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") { |
| 103 | t.Errorf("row %d: %+v, want the catalogue's %q in its order", i, row, e.ID) |
| 104 | } |
| 105 | } |
| 106 | states := map[string]string{} |
| 107 | for _, row := range s.Rows { |
| 108 | states[row.ID] = row.State + "|" + row.Error |
| 109 | } |
| 110 | if want := map[string]string{"welcome": "installed|", "scratchpad": "installing|", "contra": "failed|The app did not start answering"}; !reflect.DeepEqual(states, want) { |
| 111 | t.Errorf("states: %v, want %v", states, want) |
| 112 | } |
| 113 | |
| 114 | // A member who isn't the owner sees the same rows. |
| 115 | m := jsonAnswer[apiStoreShape](t, "member's store", a.maria().nativeGet("/api/v1/store"), 200) |
| 116 | if m.Owner || !reflect.DeepEqual(m.Rows, s.Rows) { |
| 117 | t.Errorf("member's store: owner %v, rows differ: %v", m.Owner, !reflect.DeepEqual(m.Rows, s.Rows)) |
| 118 | } |
| 119 | |
| 120 | // The installs unreadable. |
| 121 | if _, err := a.DB.Exec(`DROP TABLE installs`); err != nil { |
| 122 | t.Fatal(err) |
| 123 | } |
| 124 | refusedWith(t, "installs unreadable", app.nativeGet("/api/v1/store"), http.StatusServiceUnavailable, "unavailable") |
| 125 | } |
| 126 | |
| 127 | func TestAPIPeople(t *testing.T) { |
| 128 | a := newHomeApp(t) |
| 129 | a.link(ownerAddress, "subject-owner") |
| 130 | ana, _, err := store.Invite(t.Context(), a.DB, "ana@acme.test") |
| 131 | if err != nil { |
| 132 | t.Fatal(err) |
| 133 | } |
| 134 | if _, err := a.DB.Exec(`UPDATE members SET name = 'Ana Ruiz' WHERE id = ?`, ana.ID); err != nil { |
| 135 | t.Fatal(err) |
| 136 | } |
| 137 | a.newBrowser().link("ana@acme.test", "subject-ana") |
| 138 | invited, _, err := store.Invite(t.Context(), a.DB, "bob@acme.test") |
| 139 | if err != nil { |
| 140 | t.Fatal(err) |
| 141 | } |
| 142 | |
| 143 | r := a.nativeSignIn("subject-owner").nativeGet("/api/v1/people") |
| 144 | var raw map[string]json.RawMessage |
| 145 | if err := json.Unmarshal([]byte(r.Body), &raw); err != nil || len(raw) != 2 { |
| 146 | t.Fatalf("people's keys: %v %s", err, r.Body) |
| 147 | } |
| 148 | p := jsonAnswer[apiPeopleShape](t, "people", r, 200) |
| 149 | want := apiPeopleShape{Owner: true, People: []apiPersonShape{ |
| 150 | {ID: a.ownerID(), Initial: "O", Name: "", Email: ownerAddress, Role: "owner"}, |
| 151 | {ID: ana.ID, Initial: "A", Name: "Ana Ruiz", Email: "ana@acme.test", Role: "member"}, |
| 152 | {ID: invited.ID, Initial: "B", Name: "", Email: "bob@acme.test", Role: "invited"}, |
| 153 | }} |
| 154 | if !reflect.DeepEqual(p, want) { |
| 155 | t.Fatalf("people:\n got %+v\nwant %+v", p, want) |
| 156 | } |
| 157 | // Each row has exactly these keys: no joined. |
| 158 | var rows struct { |
| 159 | People []map[string]any `json:"people"` |
| 160 | } |
| 161 | _ = json.Unmarshal([]byte(r.Body), &rows) |
| 162 | if len(rows.People[0]) != 5 { |
| 163 | t.Errorf("a person's keys: %v", rows.People[0]) |
| 164 | } |
| 165 | |
| 166 | // Ana, a member, and the owner's own browser session on the web, get |
| 167 | // the same people. |
| 168 | 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) { |
| 169 | t.Errorf("ana's people: %+v", got) |
| 170 | } |
| 171 | if got := jsonAnswer[apiPeopleShape](t, "web session's people", a.get("/api/v1/people"), 200); !reflect.DeepEqual(got, want) { |
| 172 | t.Errorf("web session's people: %+v", got) |
| 173 | } |
| 174 | |
| 175 | // A member row that can't be read: the list fails, while the owner's |
| 176 | // own row, which the gate reads, still can be. |
| 177 | if _, err := a.DB.Exec(`INSERT INTO members (id, email, role, invited_at) VALUES ('broken', 'broken@acme.test', 'member', 'not a time')`); err != nil { |
| 178 | t.Fatal(err) |
| 179 | } |
| 180 | refusedWith(t, "members unreadable", a.nativeSignIn("subject-owner").nativeGet("/api/v1/people"), http.StatusServiceUnavailable, "unavailable") |
| 181 | } |
| 182 | |
| 183 | func TestAPITeamRefusesWithoutSession(t *testing.T) { |
| 184 | a := newHomeApp(t) |
| 185 | a.link(ownerAddress, "subject-owner") |
| 186 | maria := a.maria() |
| 187 | none := a.newBrowser() |
| 188 | for _, p := range []string{"/api/v1/store", "/api/v1/people"} { |
| 189 | r := none.nativeGet(p) |
| 190 | refusedWith(t, "no session, "+p, r, http.StatusUnauthorized, "unauthenticated") |
| 191 | if r.Location() != "" { |
| 192 | t.Errorf("no session, %s: redirected to %q", p, r.Location()) |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | // Maria, removed, is nobody. |
| 197 | m, _, err := store.MemberByEmail(t.Context(), a.DB, "maria@acme.test") |
| 198 | if err != nil { |
| 199 | t.Fatal(err) |
| 200 | } |
| 201 | if err := store.RemoveMember(t.Context(), a.DB, m.ID); err != nil { |
| 202 | t.Fatal(err) |
| 203 | } |
| 204 | for _, p := range []string{"/api/v1/store", "/api/v1/people"} { |
| 205 | refusedWith(t, "removed, "+p, maria.nativeGet(p), http.StatusUnauthorized, "unauthenticated") |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | // Nothing removes a member (spec 7.4): there is no route to. |
| 210 | func TestAPIPeopleHasNoRemove(t *testing.T) { |
| 211 | a := newHomeApp(t) |
| 212 | a.link(ownerAddress, "subject-owner") |
| 213 | ana, _, err := store.Invite(t.Context(), a.DB, "ana@acme.test") |
| 214 | if err != nil { |
| 215 | t.Fatal(err) |
| 216 | } |
| 217 | app := a.nativeSignIn("subject-owner") |
| 218 | req, _ := http.NewRequest(http.MethodDelete, a.base+"/api/v1/people/"+ana.ID, nil) |
| 219 | req.Header.Set("Origin", homeOrigin) |
| 220 | req.Header.Set("Accept", "application/json") |
| 221 | if r := app.do(req); r.Code != http.StatusNotFound && r.Code != http.StatusMethodNotAllowed { |
| 222 | t.Errorf("DELETE /api/v1/people/<id>: %d %s", r.Code, r.Body) |
| 223 | } |
| 224 | if _, ok, err := store.MemberByEmail(t.Context(), a.DB, "ana@acme.test"); err != nil || !ok { |
| 225 | t.Errorf("ana is gone: %v %v", ok, err) |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | // teamInstaller is an Installer whose answers each test decides. start runs |
| 230 | // inside Start, after the call is counted, and its error is Start's. |
| 231 | type teamInstaller struct { |
| 232 | mu sync.Mutex |
| 233 | starts []string |
| 234 | uninstalls []string |
| 235 | start func(app string) error |
| 236 | uninstallErr error |
| 237 | } |
| 238 | |
| 239 | func (i *teamInstaller) Start(_ context.Context, app string) error { |
| 240 | i.mu.Lock() |
| 241 | i.starts = append(i.starts, app) |
| 242 | start := i.start |
| 243 | i.mu.Unlock() |
| 244 | if start != nil { |
| 245 | return start(app) |
| 246 | } |
| 247 | return nil |
| 248 | } |
| 249 | |
| 250 | func (i *teamInstaller) Uninstall(_ context.Context, app string) error { |
| 251 | i.mu.Lock() |
| 252 | defer i.mu.Unlock() |
| 253 | i.uninstalls = append(i.uninstalls, app) |
| 254 | return i.uninstallErr |
| 255 | } |
| 256 | |
| 257 | func (i *teamInstaller) counts() (starts, uninstalls int) { |
| 258 | i.mu.Lock() |
| 259 | defer i.mu.Unlock() |
| 260 | return len(i.starts), len(i.uninstalls) |
| 261 | } |
| 262 | |
| 263 | // rowState is app's state in a store answer. |
| 264 | func rowState(t *testing.T, s apiStoreShape, app string) string { |
| 265 | t.Helper() |
| 266 | for _, r := range s.Rows { |
| 267 | if r.ID == app { |
| 268 | return r.State |
| 269 | } |
| 270 | } |
| 271 | t.Fatalf("no row %q in %+v", app, s) |
| 272 | return "" |
| 273 | } |
| 274 | |
| 275 | type apiStoreAnswer struct { |
| 276 | Store apiStoreShape `json:"store"` |
| 277 | } |
| 278 | |
| 279 | // postNoOrigin is a native POST without the Origin the CSRF check needs. |
| 280 | func (a *testApp) postNoOrigin(target string) Resp { |
| 281 | a.t.Helper() |
| 282 | req, _ := http.NewRequest(http.MethodPost, a.base+target, nil) |
| 283 | req.Header.Set("Accept", "application/json") |
| 284 | return a.do(req) |
| 285 | } |
| 286 | |
| 287 | func TestAPIStoreInstall(t *testing.T) { |
| 288 | inst := &teamInstaller{} |
| 289 | a := newHomeAppInstalling(t, inst, nil) |
| 290 | a.link(ownerAddress, "subject-owner") |
| 291 | app := a.nativeSignIn("subject-owner") |
| 292 | // The real Installer claims the install before Start returns. |
| 293 | inst.start = func(id string) error { a.setInstall(id, "installing", ""); return nil } |
| 294 | |
| 295 | got := jsonAnswer[apiStoreAnswer](t, "install", app.nativePost("/api/v1/store/scratchpad/install", ""), http.StatusAccepted) |
| 296 | if rowState(t, got.Store, "scratchpad") != "installing" || !got.Store.Owner { |
| 297 | t.Errorf("install answered %+v", got.Store) |
| 298 | } |
| 299 | if s, _ := inst.counts(); s != 1 { |
| 300 | t.Fatalf("%d Start calls, want 1", s) |
| 301 | } |
| 302 | |
| 303 | // Already installing: 202 as it stands. Installed: 200. Neither starts. |
| 304 | got = jsonAnswer[apiStoreAnswer](t, "installing again", app.nativePost("/api/v1/store/scratchpad/install", "{}"), http.StatusAccepted) |
| 305 | if rowState(t, got.Store, "scratchpad") != "installing" { |
| 306 | t.Errorf("installing again: %+v", got.Store) |
| 307 | } |
| 308 | a.setInstall("scratchpad", "installed", "") |
| 309 | got = jsonAnswer[apiStoreAnswer](t, "installed", app.nativePost("/api/v1/store/scratchpad/install", ""), http.StatusOK) |
| 310 | if rowState(t, got.Store, "scratchpad") != "installed" { |
| 311 | t.Errorf("installed: %+v", got.Store) |
| 312 | } |
| 313 | if s, _ := inst.counts(); s != 1 { |
| 314 | t.Fatalf("%d Start calls after the repeats, want 1", s) |
| 315 | } |
| 316 | |
| 317 | // The real Start returns an error only from before its claim, so a |
| 318 | // failed Start never started this attempt. A failed row whose retry |
| 319 | // can't start is 503, not the old failure answered as if it ran. |
| 320 | a.setInstall("contra", "failed", "The app did not start answering") |
| 321 | inst.start = func(string) error { return errors.New("database locked") } |
| 322 | refusedWith(t, "retry not started", app.nativePost("/api/v1/store/contra/install", ""), http.StatusServiceUnavailable, "unavailable") |
| 323 | // Nor does an app never installed show anything for it. |
| 324 | if _, err := a.DB.Exec(`DELETE FROM installs WHERE app = 'contra'`); err != nil { |
| 325 | t.Fatal(err) |
| 326 | } |
| 327 | refusedWith(t, "start failed, nothing claimed", app.nativePost("/api/v1/store/contra/install", ""), http.StatusServiceUnavailable, "unavailable") |
| 328 | // Another request claimed it meanwhile: the row reads installing, 202. |
| 329 | inst.start = func(id string) error { |
| 330 | a.setInstall(id, "installing", "") |
| 331 | return errors.New("already claimed") |
| 332 | } |
| 333 | got = jsonAnswer[apiStoreAnswer](t, "claimed by another request", app.nativePost("/api/v1/store/contra/install", ""), http.StatusAccepted) |
| 334 | if rowState(t, got.Store, "contra") != "installing" { |
| 335 | t.Errorf("claimed by another request: %+v", got.Store) |
| 336 | } |
| 337 | // A failed row's retry that starts is 202, installing. |
| 338 | a.setInstall("contra", "failed", "") |
| 339 | inst.start = func(id string) error { a.setInstall(id, "installing", ""); return nil } |
| 340 | got = jsonAnswer[apiStoreAnswer](t, "try again", app.nativePost("/api/v1/store/contra/install", ""), http.StatusAccepted) |
| 341 | if rowState(t, got.Store, "contra") != "installing" { |
| 342 | t.Errorf("try again: %+v", got.Store) |
| 343 | } |
| 344 | before, _ := inst.counts() |
| 345 | |
| 346 | refusedWith(t, "unknown app", app.nativePost("/api/v1/store/nope/install", ""), http.StatusNotFound, "unknown_app") |
| 347 | refusedWith(t, "member", a.maria().nativePost("/api/v1/store/scratchpad/install", ""), http.StatusForbidden, "owner_only") |
| 348 | if r := app.postNoOrigin("/api/v1/store/scratchpad/install"); r.Code != http.StatusForbidden { |
| 349 | t.Errorf("no Origin: %d %s", r.Code, r.Body) |
| 350 | } |
| 351 | if r := app.postFrom("https://evil.test", "/api/v1/store/scratchpad/install", nil); r.Code != http.StatusForbidden { |
| 352 | t.Errorf("another site: %d %s", r.Code, r.Body) |
| 353 | } |
| 354 | if s, _ := inst.counts(); s != before { |
| 355 | t.Errorf("a refused install reached Start (%d -> %d)", before, s) |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | func TestAPIStoreUninstall(t *testing.T) { |
| 360 | inst := &teamInstaller{} |
| 361 | a := newHomeAppInstalling(t, inst, nil) |
| 362 | a.link(ownerAddress, "subject-owner") |
| 363 | app := a.nativeSignIn("subject-owner") |
| 364 | a.setInstall("scratchpad", "installed", "") |
| 365 | |
| 366 | // The real Installer removes the row; the fake leaves that to the test. |
| 367 | got := jsonAnswer[apiStoreAnswer](t, "uninstall", app.nativePost("/api/v1/store/scratchpad/uninstall", ""), http.StatusOK) |
| 368 | if !got.Store.Owner || len(got.Store.Rows) != len(catalog.All()) { |
| 369 | t.Errorf("uninstall answered %+v", got.Store) |
| 370 | } |
| 371 | if _, u := inst.counts(); u != 1 { |
| 372 | t.Fatalf("%d Uninstall calls, want 1", u) |
| 373 | } |
| 374 | |
| 375 | inst.uninstallErr = install.ErrBusy |
| 376 | refusedWith(t, "busy", app.nativePost("/api/v1/store/scratchpad/uninstall", ""), http.StatusConflict, "busy") |
| 377 | inst.uninstallErr = store.ErrNoInstall |
| 378 | jsonAnswer[apiStoreAnswer](t, "already uninstalled", app.nativePost("/api/v1/store/scratchpad/uninstall", ""), http.StatusOK) |
| 379 | inst.uninstallErr = errors.New("platform down") |
| 380 | refusedWith(t, "uninstall failed", app.nativePost("/api/v1/store/scratchpad/uninstall", ""), http.StatusServiceUnavailable, "unavailable") |
| 381 | inst.uninstallErr = nil |
| 382 | _, before := inst.counts() |
| 383 | |
| 384 | refusedWith(t, "unknown app", app.nativePost("/api/v1/store/nope/uninstall", ""), http.StatusNotFound, "unknown_app") |
| 385 | refusedWith(t, "member", a.maria().nativePost("/api/v1/store/scratchpad/uninstall", ""), http.StatusForbidden, "owner_only") |
| 386 | if r := app.postNoOrigin("/api/v1/store/scratchpad/uninstall"); r.Code != http.StatusForbidden { |
| 387 | t.Errorf("no Origin: %d %s", r.Code, r.Body) |
| 388 | } |
| 389 | if _, u := inst.counts(); u != before { |
| 390 | t.Errorf("a refused uninstall reached Uninstall (%d -> %d)", before, u) |
| 391 | } |
| 392 | |
| 393 | // The store unreadable after the uninstall. |
| 394 | if _, err := a.DB.Exec(`DROP TABLE installs`); err != nil { |
| 395 | t.Fatal(err) |
| 396 | } |
| 397 | refusedWith(t, "store unreadable", app.nativePost("/api/v1/store/scratchpad/uninstall", ""), http.StatusServiceUnavailable, "unavailable") |
| 398 | } |
| 399 | |
| 400 | type apiPersonAnswer struct { |
| 401 | Person apiPersonShape `json:"person"` |
| 402 | } |
| 403 | |
| 404 | func TestAPIPeopleInvite(t *testing.T) { |
| 405 | a := newHomeApp(t) |
| 406 | a.link(ownerAddress, "subject-owner") |
| 407 | app := a.nativeSignIn("subject-owner") |
| 408 | n := len(a.mailbox()) |
| 409 | |
| 410 | got := jsonAnswer[apiPersonAnswer](t, "invite", app.nativePost("/api/v1/people", `{"email":" Maria@Acme.test "}`), http.StatusOK) |
| 411 | m, ok, err := store.MemberByEmail(t.Context(), a.DB, "maria@acme.test") |
| 412 | if err != nil || !ok { |
| 413 | t.Fatalf("maria: %v %v", ok, err) |
| 414 | } |
| 415 | if want := (apiPersonShape{ID: m.ID, Initial: "M", Email: "maria@acme.test", Role: "invited"}); got.Person != want { |
| 416 | t.Errorf("invite answered %+v, want %+v", got.Person, want) |
| 417 | } |
| 418 | box := a.mailbox() |
| 419 | if len(box) != n+1 || box[len(box)-1].To != "maria@acme.test" { |
| 420 | t.Fatalf("want one invitation to maria, mailbox grew by %d", len(box)-n) |
| 421 | } |
| 422 | |
| 423 | // The same address again sends nothing, and answers the same person. |
| 424 | again := jsonAnswer[apiPersonAnswer](t, "invite again", app.nativePost("/api/v1/people", `{"email":"maria@acme.test"}`), http.StatusOK) |
| 425 | if again.Person != got.Person || len(a.mailbox()) != n+1 { |
| 426 | t.Errorf("invite again: %+v, mailbox grew by %d", again.Person, len(a.mailbox())-n) |
| 427 | } |
| 428 | // The owner is already here. |
| 429 | 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() { |
| 430 | t.Errorf("invite the owner: %+v", o.Person) |
| 431 | } |
| 432 | |
| 433 | for _, body := range []string{`{"email":"not an email"}`, `{"email":""}`, `{}`, `{"email":"Bob <bob@acme.test>"}`} { |
| 434 | refusedWith(t, "bad address "+body, app.nativePost("/api/v1/people", body), http.StatusUnprocessableEntity, "bad_email") |
| 435 | } |
| 436 | |
| 437 | // A failing mailer: 502, and inviting again sends. |
| 438 | a.mail.mu.Lock() |
| 439 | a.mail.fail = true |
| 440 | a.mail.mu.Unlock() |
| 441 | refusedWith(t, "mail down", app.nativePost("/api/v1/people", `{"email":"bob@acme.test"}`), http.StatusBadGateway, "mail_failed") |
| 442 | a.mail.mu.Lock() |
| 443 | a.mail.fail = false |
| 444 | a.mail.mu.Unlock() |
| 445 | bob := jsonAnswer[apiPersonAnswer](t, "retry", app.nativePost("/api/v1/people", `{"email":"bob@acme.test"}`), http.StatusOK) |
| 446 | if bob.Person.Email != "bob@acme.test" || len(a.mailbox()) != n+2 { |
| 447 | t.Errorf("retry: %+v, mailbox grew by %d", bob.Person, len(a.mailbox())-n) |
| 448 | } |
| 449 | // Refusals that send nothing. Maria signs in first, which mails her a |
| 450 | // sign-in link. |
| 451 | maria := a.maria() |
| 452 | sent := len(a.mailbox()) |
| 453 | refusedWith(t, "member", maria.nativePost("/api/v1/people", `{"email":"carla@acme.test"}`), http.StatusForbidden, "owner_only") |
| 454 | form := app.postFrom(homeOrigin, "/api/v1/people", url.Values{"email": {"carla@acme.test"}}) |
| 455 | if form.Code != http.StatusUnsupportedMediaType { |
| 456 | t.Errorf("a form body: %d %s", form.Code, form.Body) |
| 457 | } |
| 458 | big := `{"email":"carla@acme.test","pad":"` + strings.Repeat("x", 4<<10) + `"}` |
| 459 | if r := app.nativePost("/api/v1/people", big); r.Code != http.StatusRequestEntityTooLarge { |
| 460 | t.Errorf("a body over 4 KiB: %d %s", r.Code, r.Body) |
| 461 | } |
| 462 | if r := app.nativePost("/api/v1/people", `{"email":`); r.Code != http.StatusBadRequest { |
| 463 | t.Errorf("broken JSON: %d %s", r.Code, r.Body) |
| 464 | } |
| 465 | if len(a.mailbox()) != sent { |
| 466 | t.Errorf("a refused invite sent mail") |
| 467 | } |
| 468 | // Inside the CSRF check: no Origin, or another site's, with a JSON body. |
| 469 | for _, origin := range []string{"", "https://evil.test"} { |
| 470 | req, _ := http.NewRequest(http.MethodPost, a.base+"/api/v1/people", strings.NewReader(`{"email":"carla@acme.test"}`)) |
| 471 | req.Header.Set("Content-Type", "application/json") |
| 472 | req.Header.Set("Accept", "application/json") |
| 473 | if origin != "" { |
| 474 | req.Header.Set("Origin", origin) |
| 475 | } |
| 476 | if r := app.do(req); r.Code != http.StatusForbidden { |
| 477 | t.Errorf("invite with Origin %q: %d %s", origin, r.Code, r.Body) |
| 478 | } |
| 479 | } |
| 480 | if len(a.mailbox()) != sent { |
| 481 | t.Errorf("a refused invite sent mail") |
| 482 | } |
| 483 | if _, ok, _ := store.MemberByEmail(t.Context(), a.DB, "carla@acme.test"); ok { |
| 484 | t.Error("a refused invite added carla") |
| 485 | } |
| 486 | |
| 487 | // The owner's web session (the cookie from signing in on the web) may |
| 488 | // write too: it is the same member gate. |
| 489 | 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" { |
| 490 | t.Errorf("invite from the web session: %+v", web.Person) |
| 491 | } |
| 492 | |
| 493 | // The members can't be written. |
| 494 | if _, err := a.DB.Exec(`CREATE TRIGGER no_invites BEFORE INSERT ON members BEGIN SELECT RAISE(ABORT, 'locked'); END`); err != nil { |
| 495 | t.Fatal(err) |
| 496 | } |
| 497 | refusedWith(t, "members unwritable", app.nativePost("/api/v1/people", `{"email":"erin@acme.test"}`), http.StatusServiceUnavailable, "unavailable") |
| 498 | } |
| 499 | |
| 500 | // Without a session every write is 401, as the reads are. |
| 501 | func TestAPITeamWritesRefuseWithoutSession(t *testing.T) { |
| 502 | a := newHomeApp(t) |
| 503 | a.link(ownerAddress, "subject-owner") |
| 504 | none := a.newBrowser() |
| 505 | for _, p := range []string{"/api/v1/store/scratchpad/install", "/api/v1/store/scratchpad/uninstall", "/api/v1/people"} { |
| 506 | refusedWith(t, "no session, POST "+p, none.nativePost(p, `{"email":"x@acme.test"}`), http.StatusUnauthorized, "unauthenticated") |
| 507 | } |
| 508 | } |
| 509 | |