| 1 | package operations_test |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "database/sql" |
| 7 | "encoding/json" |
| 8 | "io" |
| 9 | "log/slog" |
| 10 | "net/http" |
| 11 | "net/http/httptest" |
| 12 | "os" |
| 13 | "reflect" |
| 14 | "strings" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | "amadan.net/rastrillo/rastrillo/budget" |
| 19 | "amadan.net/rastrillo/rastrillo/db" |
| 20 | "amadan.net/rastrillo/rastrillo/dbtest" |
| 21 | "amadan.net/rastrillo/rastrillo/sessions" |
| 22 | |
| 23 | "amadan.net/oficina/base/internal/config" |
| 24 | "amadan.net/oficina/base/internal/store" |
| 25 | "amadan.net/oficina/base/internal/web" |
| 26 | ) |
| 27 | |
| 28 | const ( |
| 29 | testOrigin = "http://127.0.0.1:8080" |
| 30 | ownerAddress = "owner@acme.test" |
| 31 | ) |
| 32 | |
| 33 | var schema = dbtest.FromSet(store.BootSchema) |
| 34 | |
| 35 | func TestMain(m *testing.M) { |
| 36 | code := budget.Main(m) |
| 37 | schema.Remove() |
| 38 | os.Exit(code) |
| 39 | } |
| 40 | |
| 41 | type noMail struct{} |
| 42 | |
| 43 | func (noMail) Send(context.Context, string, string, string) error { return nil } |
| 44 | |
| 45 | type noInstaller struct{} |
| 46 | |
| 47 | func (noInstaller) Start(context.Context, string) error { return nil } |
| 48 | func (noInstaller) Uninstall(context.Context, string) error { return nil } |
| 49 | |
| 50 | type base struct { |
| 51 | t *testing.T |
| 52 | url string |
| 53 | db *sql.DB |
| 54 | } |
| 55 | |
| 56 | // newBase serves the whole of Base, wired as main.go wires it, on 127.0.0.1, |
| 57 | // with the owner bootstrapped. |
| 58 | func newBase(t *testing.T, tweak func(*config.Config)) *base { |
| 59 | t.Helper() |
| 60 | logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| 61 | d, err := db.Open(schema.Path(t), logger) |
| 62 | if err != nil { |
| 63 | t.Fatal(err) |
| 64 | } |
| 65 | t.Cleanup(func() { d.Close() }) |
| 66 | if err := store.Bootstrap(context.Background(), d.Writer(), ownerAddress); err != nil { |
| 67 | t.Fatal(err) |
| 68 | } |
| 69 | cfg := config.Config{Origin: testOrigin, Name: "Acme", Owner: ownerAddress, InstanceKey: "test-instance-key", |
| 70 | AllowLoggedMail: true, Slug: "acme", AppsDomain: "bab.oncarlos.com", Timezone: time.UTC} |
| 71 | if tweak != nil { |
| 72 | tweak(&cfg) |
| 73 | } |
| 74 | h, err := web.App(d, cfg, noMail{}, noInstaller{}, logger) |
| 75 | if err != nil { |
| 76 | t.Fatal(err) |
| 77 | } |
| 78 | srv := httptest.NewServer(h) |
| 79 | t.Cleanup(srv.Close) |
| 80 | return &base{t: t, url: srv.URL, db: d.Writer()} |
| 81 | } |
| 82 | |
| 83 | func (b *base) member(email string) store.Member { |
| 84 | b.t.Helper() |
| 85 | m, ok, err := store.MemberByEmail(context.Background(), b.db, email) |
| 86 | if err == nil && !ok { |
| 87 | m, _, err = store.Invite(context.Background(), b.db, email) |
| 88 | } |
| 89 | if err != nil { |
| 90 | b.t.Fatal(err) |
| 91 | } |
| 92 | return m |
| 93 | } |
| 94 | |
| 95 | func (b *base) token(email string) string { |
| 96 | b.t.Helper() |
| 97 | tok, err := store.MintHostToken(context.Background(), b.db, b.member(email).ID) |
| 98 | if err != nil { |
| 99 | b.t.Fatal(err) |
| 100 | } |
| 101 | return tok |
| 102 | } |
| 103 | |
| 104 | type resp struct { |
| 105 | code int |
| 106 | header http.Header |
| 107 | body []byte |
| 108 | } |
| 109 | |
| 110 | func (b *base) send(req *http.Request) resp { |
| 111 | b.t.Helper() |
| 112 | c := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| 113 | res, err := c.Do(req) |
| 114 | if err != nil { |
| 115 | b.t.Fatal(err) |
| 116 | } |
| 117 | defer res.Body.Close() |
| 118 | body, _ := io.ReadAll(res.Body) |
| 119 | if cc := res.Header.Get("Cache-Control"); res.Request.URL.Path != "/" && cc != "no-store" { |
| 120 | b.t.Errorf("%s %s: Cache-Control = %q, want no-store", req.Method, req.URL.Path, cc) |
| 121 | } |
| 122 | for k := range res.Header { |
| 123 | if strings.HasPrefix(strings.ToLower(k), "access-control-") { |
| 124 | b.t.Errorf("%s %s: CORS header %s", req.Method, req.URL.Path, k) |
| 125 | } |
| 126 | } |
| 127 | return resp{res.StatusCode, res.Header, body} |
| 128 | } |
| 129 | |
| 130 | // request is how Equipo's HTTP provider calls: a bearer, JSON both ways, no |
| 131 | // Origin and no cookies. An empty token sends no Authorization. |
| 132 | func (b *base) request(method, path, token, contentType string, body []byte) *http.Request { |
| 133 | b.t.Helper() |
| 134 | var rd io.Reader |
| 135 | if body != nil { |
| 136 | rd = bytes.NewReader(body) |
| 137 | } |
| 138 | req, err := http.NewRequest(method, b.url+path, rd) |
| 139 | if err != nil { |
| 140 | b.t.Fatal(err) |
| 141 | } |
| 142 | if token != "" { |
| 143 | req.Header.Set("Authorization", "Bearer "+token) |
| 144 | } |
| 145 | req.Header.Set("Accept", "application/json") |
| 146 | if contentType != "" { |
| 147 | req.Header.Set("Content-Type", contentType) |
| 148 | } |
| 149 | return req |
| 150 | } |
| 151 | |
| 152 | func (b *base) list(token string) resp { |
| 153 | return b.send(b.request(http.MethodGet, "/api/v1/operations", token, "", nil)) |
| 154 | } |
| 155 | |
| 156 | func (b *base) invoke(token, name string) resp { |
| 157 | return b.send(b.request(http.MethodPost, "/api/v1/operations/"+name, token, "application/json", []byte(`{}`))) |
| 158 | } |
| 159 | |
| 160 | // decode reads a 200's JSON into out. |
| 161 | func (r resp) decode(t *testing.T, out any) { |
| 162 | t.Helper() |
| 163 | if r.code != http.StatusOK { |
| 164 | t.Fatalf("status %d, body %s", r.code, r.body) |
| 165 | } |
| 166 | if ct := r.header.Get("Content-Type"); !strings.HasPrefix(ct, "application/json") { |
| 167 | t.Errorf("Content-Type = %q", ct) |
| 168 | } |
| 169 | if err := json.Unmarshal(r.body, out); err != nil { |
| 170 | t.Fatalf("%v in %s", err, r.body) |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | // refused checks a refusal's status and its {"error":{"code","message"}}. |
| 175 | func (r resp) refused(t *testing.T, what string, status int, code string) { |
| 176 | t.Helper() |
| 177 | if r.code != status { |
| 178 | t.Errorf("%s: status %d, want %d; body %s", what, r.code, status, r.body) |
| 179 | return |
| 180 | } |
| 181 | var env struct { |
| 182 | Error struct{ Code, Message string } `json:"error"` |
| 183 | } |
| 184 | if err := json.Unmarshal(r.body, &env); err != nil || env.Error.Code != code || env.Error.Message == "" { |
| 185 | t.Errorf("%s: body %s, want error code %q with a message", what, r.body, code) |
| 186 | } |
| 187 | if status == http.StatusUnauthorized && r.header.Get("WWW-Authenticate") != "Bearer" { |
| 188 | t.Errorf("%s: WWW-Authenticate = %q, want Bearer", what, r.header.Get("WWW-Authenticate")) |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | type operation struct { |
| 193 | Name string `json:"name"` |
| 194 | Description string `json:"description"` |
| 195 | Scope string `json:"scope"` |
| 196 | ReadOnly bool `json:"read_only"` |
| 197 | Destructive bool `json:"destructive"` |
| 198 | Idempotent bool `json:"idempotent"` |
| 199 | External bool `json:"external"` |
| 200 | App string `json:"app"` |
| 201 | Input json.RawMessage `json:"input_schema"` |
| 202 | Output json.RawMessage `json:"output_schema"` |
| 203 | } |
| 204 | |
| 205 | func TestOperationsList(t *testing.T) { |
| 206 | b := newBase(t, nil) |
| 207 | var env struct { |
| 208 | Operations []operation `json:"operations"` |
| 209 | } |
| 210 | b.list(b.token(ownerAddress)).decode(t, &env) |
| 211 | var names []string |
| 212 | for _, op := range env.Operations { |
| 213 | names = append(names, op.Name) |
| 214 | if !op.ReadOnly || op.Destructive || !op.Idempotent || op.External || op.Scope != "base.read" || op.App != "Base" { |
| 215 | t.Errorf("%s: %+v; want read-only, not destructive, idempotent, not external, base.read, Base", op.Name, op) |
| 216 | } |
| 217 | if op.Description == "" || strings.Contains(op.Description, "—") || strings.Contains(op.Description, "!") { |
| 218 | t.Errorf("%s: description %q", op.Name, op.Description) |
| 219 | } |
| 220 | var in map[string]any |
| 221 | if err := json.Unmarshal(op.Input, &in); err != nil || !reflect.DeepEqual(in, map[string]any{"type": "object", "additionalProperties": false}) { |
| 222 | t.Errorf("%s: input_schema %s (%v)", op.Name, op.Input, err) |
| 223 | } |
| 224 | var out map[string]any |
| 225 | if err := json.Unmarshal(op.Output, &out); err != nil || out["type"] != "object" { |
| 226 | t.Errorf("%s: output_schema %s is not a JSON object schema (%v)", op.Name, op.Output, err) |
| 227 | } |
| 228 | } |
| 229 | if want := []string{"base_apps", "base_people", "base_settings"}; !reflect.DeepEqual(names, want) { |
| 230 | t.Fatalf("operations = %v, want %v", names, want) |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | type settings struct { |
| 235 | Name string `json:"name"` |
| 236 | Timezone string `json:"timezone"` |
| 237 | You struct { |
| 238 | Name string `json:"name"` |
| 239 | Email string `json:"email"` |
| 240 | Role string `json:"role"` |
| 241 | } `json:"you"` |
| 242 | } |
| 243 | |
| 244 | // A host token is one member's: each answers with that member's view, and |
| 245 | // nothing else gets in, not even a signed-in owner's browser. |
| 246 | func TestOperationsTokenIsOneMembers(t *testing.T) { |
| 247 | tz, err := time.LoadLocation("Europe/Madrid") |
| 248 | if err != nil { |
| 249 | t.Fatal(err) |
| 250 | } |
| 251 | b := newBase(t, func(c *config.Config) { c.Timezone = tz }) |
| 252 | ana, owner := b.token("ana@acme.test"), b.token(ownerAddress) |
| 253 | |
| 254 | for _, c := range []struct{ token, email, role string }{{ana, "ana@acme.test", "member"}, {owner, ownerAddress, "owner"}} { |
| 255 | var s settings |
| 256 | b.invoke(c.token, "base_settings").decode(t, &s) |
| 257 | if s.You.Email != c.email || s.You.Role != c.role || s.Name != "Acme" || s.Timezone != "Europe/Madrid" { |
| 258 | t.Errorf("base_settings for %s = %+v", c.email, s) |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | var people struct { |
| 263 | People []struct { |
| 264 | Name, Email, Role string |
| 265 | Joined bool |
| 266 | } `json:"people"` |
| 267 | } |
| 268 | b.invoke(ana, "base_people").decode(t, &people) |
| 269 | got := map[string]string{} |
| 270 | for _, p := range people.People { |
| 271 | got[p.Email] = p.Role |
| 272 | if p.Joined { |
| 273 | t.Errorf("%s has not joined, base_people says joined", p.Email) |
| 274 | } |
| 275 | } |
| 276 | if want := map[string]string{ownerAddress: "owner", "ana@acme.test": "member"}; !reflect.DeepEqual(got, want) { |
| 277 | t.Errorf("base_people = %+v", people) |
| 278 | } |
| 279 | |
| 280 | // One character changed. |
| 281 | last := owner[len(owner)-1] |
| 282 | swap := byte('A') |
| 283 | if last == 'A' { |
| 284 | swap = 'B' |
| 285 | } |
| 286 | b.invoke(owner[:len(owner)-1]+string(swap), "base_settings").refused(t, "altered token", 401, "unauthenticated") |
| 287 | b.list(owner[:len(owner)-1]+string(swap)).refused(t, "altered token, list", 401, "unauthenticated") |
| 288 | b.invoke("", "base_settings").refused(t, "no token", 401, "unauthenticated") |
| 289 | b.list("").refused(t, "no token, list", 401, "unauthenticated") |
| 290 | b.list("not-a-token").refused(t, "not a token", 401, "unauthenticated") |
| 291 | req := b.request(http.MethodGet, "/api/v1/operations", "", "", nil) |
| 292 | req.Header.Set("Authorization", "Basic "+owner) |
| 293 | b.send(req).refused(t, "Basic scheme", 401, "unauthenticated") |
| 294 | |
| 295 | // A signed-in owner's session cookie, with no bearer. The cookie is |
| 296 | // real: it opens Home. |
| 297 | sess, err := sessions.New(sessions.Config{DB: b.db, Origin: testOrigin}) |
| 298 | if err != nil { |
| 299 | t.Fatal(err) |
| 300 | } |
| 301 | cookie, err := sess.Mint(sessions.Session{Subject: ownerAddress, Method: "email", At: time.Now(), AuthTime: time.Now()}) |
| 302 | if err != nil { |
| 303 | t.Fatal(err) |
| 304 | } |
| 305 | home := b.request(http.MethodGet, "/", "", "", nil) |
| 306 | home.AddCookie(&http.Cookie{Name: sess.CookieName(), Value: cookie}) |
| 307 | if r := b.send(home); r.code != http.StatusOK { |
| 308 | t.Fatalf("the owner's cookie does not open Home: %d", r.code) |
| 309 | } |
| 310 | for _, req := range []*http.Request{ |
| 311 | b.request(http.MethodGet, "/api/v1/operations", "", "", nil), |
| 312 | b.request(http.MethodPost, "/api/v1/operations/base_settings", "", "application/json", []byte(`{}`)), |
| 313 | } { |
| 314 | req.AddCookie(&http.Cookie{Name: sess.CookieName(), Value: cookie}) |
| 315 | req.Header.Set("Origin", testOrigin) |
| 316 | b.send(req).refused(t, "cookie only: "+req.Method, 401, "unauthenticated") |
| 317 | } |
| 318 | |
| 319 | // Ana is removed: her token goes with her. |
| 320 | if err := store.RemoveMember(context.Background(), b.db, b.member("ana@acme.test").ID); err != nil { |
| 321 | t.Fatal(err) |
| 322 | } |
| 323 | b.invoke(ana, "base_settings").refused(t, "removed member", 401, "unauthenticated") |
| 324 | b.list(ana).refused(t, "removed member, list", 401, "unauthenticated") |
| 325 | var s settings |
| 326 | b.invoke(owner, "base_settings").decode(t, &s) |
| 327 | if s.You.Email != ownerAddress { |
| 328 | t.Errorf("owner after Ana left = %+v", s) |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | type named struct { |
| 333 | ID string `json:"id"` |
| 334 | Name string `json:"name"` |
| 335 | Address string `json:"address"` |
| 336 | Summary string `json:"summary"` |
| 337 | } |
| 338 | |
| 339 | func TestOperationsBaseApps(t *testing.T) { |
| 340 | b := newBase(t, func(c *config.Config) { |
| 341 | c.OficinaApps = []config.OficinaApp{ |
| 342 | {ID: "fichas", Name: "Fichas", Origin: "https://fichas.oficina.works"}, |
| 343 | {ID: "calendar", Name: "Calendar", Origin: "https://calendar.oficina.works"}, |
| 344 | } |
| 345 | }) |
| 346 | ctx := context.Background() |
| 347 | if ok, err := store.ClaimInstall(ctx, b.db, "welcome", "acme-welcome.bab.oncarlos.com"); err != nil || !ok { |
| 348 | t.Fatal(ok, err) |
| 349 | } |
| 350 | if err := store.SetInstallState(ctx, b.db, "welcome", "installed", ""); err != nil { |
| 351 | t.Fatal(err) |
| 352 | } |
| 353 | if ok, err := store.ClaimInstall(ctx, b.db, "scratchpad", "acme-scratchpad.bab.oncarlos.com"); err != nil || !ok { |
| 354 | t.Fatal(ok, err) |
| 355 | } |
| 356 | |
| 357 | var apps struct { |
| 358 | Installed []named `json:"installed"` |
| 359 | Store []named `json:"store"` |
| 360 | Oficina []named `json:"oficina"` |
| 361 | } |
| 362 | b.invoke(b.token(ownerAddress), "base_apps").decode(t, &apps) |
| 363 | if want := []named{{ID: "welcome", Name: "Welcome", Address: "https://acme-welcome.bab.oncarlos.com/"}}; !reflect.DeepEqual(apps.Installed, want) { |
| 364 | t.Errorf("installed = %+v, want %+v", apps.Installed, want) |
| 365 | } |
| 366 | for _, a := range apps.Store { |
| 367 | if a.ID == "welcome" { |
| 368 | t.Errorf("an installed app is in the store: %+v", apps.Store) |
| 369 | } |
| 370 | } |
| 371 | found := false |
| 372 | for _, a := range apps.Store { |
| 373 | if a.ID == "scratchpad" && a.Name == "Scratchpad" && a.Summary != "" { |
| 374 | found = true |
| 375 | } |
| 376 | } |
| 377 | if !found { |
| 378 | t.Errorf("store %+v lacks Scratchpad, which is not installed", apps.Store) |
| 379 | } |
| 380 | want := []named{ |
| 381 | {ID: "fichas", Name: "Fichas", Address: "https://fichas.oficina.works/"}, |
| 382 | {ID: "calendar", Name: "Calendar", Address: "https://calendar.oficina.works/"}, |
| 383 | } |
| 384 | if !reflect.DeepEqual(apps.Oficina, want) { |
| 385 | t.Errorf("oficina = %+v, want %+v", apps.Oficina, want) |
| 386 | } |
| 387 | |
| 388 | // Lists are lists, never null, when there is nothing to list. |
| 389 | empty := newBase(t, nil) |
| 390 | r := empty.invoke(empty.token(ownerAddress), "base_apps") |
| 391 | if r.code != 200 || !bytes.Contains(r.body, []byte(`"installed":[]`)) || !bytes.Contains(r.body, []byte(`"oficina":[]`)) { |
| 392 | t.Errorf("empty base_apps = %d %s", r.code, r.body) |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | func TestOperationsRefusals(t *testing.T) { |
| 397 | b := newBase(t, nil) |
| 398 | tok := b.token(ownerAddress) |
| 399 | post := func(name, contentType string, body []byte) resp { |
| 400 | return b.send(b.request(http.MethodPost, "/api/v1/operations/"+name, tok, contentType, body)) |
| 401 | } |
| 402 | |
| 403 | post("base_nothing", "application/json", []byte(`{}`)).refused(t, "unknown name", 404, "not_found") |
| 404 | post("base_apps/extra", "application/json", []byte(`{}`)).refused(t, "a path under a name", 404, "not_found") |
| 405 | post("", "application/json", []byte(`{}`)).refused(t, "no name", 404, "not_found") |
| 406 | post("base_apps", "text/plain", []byte(`{}`)).refused(t, "text/plain", 415, "unsupported_media_type") |
| 407 | post("base_apps", "", []byte(`{}`)).refused(t, "no Content-Type", 415, "unsupported_media_type") |
| 408 | for _, body := range []string{`{"a":1}`, `[]`, `null`, ``, `{}{}`, `{`, `"x"`} { |
| 409 | post("base_apps", "application/json", []byte(body)).refused(t, "body "+body, 422, "invalid") |
| 410 | } |
| 411 | big := append([]byte(`{"pad":"`), bytes.Repeat([]byte("x"), 64<<10)...) |
| 412 | big = append(big, `"}`...) |
| 413 | post("base_apps", "application/json", big).refused(t, "over 64 KiB", 413, "too_large") |
| 414 | |
| 415 | // Equipo sends JSON with a charset sometimes, and an Idempotency-Key it |
| 416 | // derives; neither matters here. No Origin header: this is no browser. |
| 417 | req := b.request(http.MethodPost, "/api/v1/operations/base_people", tok, "application/json; charset=utf-8", []byte(" { } ")) |
| 418 | req.Header.Set("Idempotency-Key", "5f1c2a8e-0000-5000-8000-000000000000") |
| 419 | if req.Header.Get("Origin") != "" { |
| 420 | t.Fatal("the request has an Origin") |
| 421 | } |
| 422 | if r := b.send(req); r.code != 200 { |
| 423 | t.Errorf("POST without Origin = %d %s; want 200", r.code, r.body) |
| 424 | } |
| 425 | b.send(b.request(http.MethodDelete, "/api/v1/operations/base_apps", tok, "", nil)).refused(t, "DELETE", 405, "method_not_allowed") |
| 426 | } |
| 427 | |