package operations_test import ( "bytes" "context" "database/sql" "encoding/json" "io" "log/slog" "net/http" "net/http/httptest" "os" "reflect" "strings" "testing" "time" "amadan.net/rastrillo/rastrillo/budget" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/dbtest" "amadan.net/rastrillo/rastrillo/sessions" "amadan.net/oficina/base/internal/config" "amadan.net/oficina/base/internal/store" "amadan.net/oficina/base/internal/web" ) const ( testOrigin = "http://127.0.0.1:8080" ownerAddress = "owner@acme.test" ) var schema = dbtest.FromSet(store.BootSchema) func TestMain(m *testing.M) { code := budget.Main(m) schema.Remove() os.Exit(code) } type noMail struct{} func (noMail) Send(context.Context, string, string, string) error { return nil } type noInstaller struct{} func (noInstaller) Start(context.Context, string) error { return nil } func (noInstaller) Uninstall(context.Context, string) error { return nil } type base struct { t *testing.T url string db *sql.DB } // newBase serves the whole of Base, wired as main.go wires it, on 127.0.0.1, // with the owner bootstrapped. func newBase(t *testing.T, tweak func(*config.Config)) *base { t.Helper() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) d, err := db.Open(schema.Path(t), logger) if err != nil { t.Fatal(err) } t.Cleanup(func() { d.Close() }) if err := store.Bootstrap(context.Background(), d.Writer(), ownerAddress); err != nil { t.Fatal(err) } cfg := config.Config{Origin: testOrigin, Name: "Acme", Owner: ownerAddress, InstanceKey: "test-instance-key", AllowLoggedMail: true, Slug: "acme", AppsDomain: "bab.oncarlos.com", Timezone: time.UTC} if tweak != nil { tweak(&cfg) } h, err := web.App(d, cfg, noMail{}, noInstaller{}, logger) if err != nil { t.Fatal(err) } srv := httptest.NewServer(h) t.Cleanup(srv.Close) return &base{t: t, url: srv.URL, db: d.Writer()} } func (b *base) member(email string) store.Member { b.t.Helper() m, ok, err := store.MemberByEmail(context.Background(), b.db, email) if err == nil && !ok { m, _, err = store.Invite(context.Background(), b.db, email) } if err != nil { b.t.Fatal(err) } return m } func (b *base) token(email string) string { b.t.Helper() tok, err := store.MintHostToken(context.Background(), b.db, b.member(email).ID) if err != nil { b.t.Fatal(err) } return tok } type resp struct { code int header http.Header body []byte } func (b *base) send(req *http.Request) resp { b.t.Helper() c := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} res, err := c.Do(req) if err != nil { b.t.Fatal(err) } defer res.Body.Close() body, _ := io.ReadAll(res.Body) if cc := res.Header.Get("Cache-Control"); res.Request.URL.Path != "/" && cc != "no-store" { b.t.Errorf("%s %s: Cache-Control = %q, want no-store", req.Method, req.URL.Path, cc) } for k := range res.Header { if strings.HasPrefix(strings.ToLower(k), "access-control-") { b.t.Errorf("%s %s: CORS header %s", req.Method, req.URL.Path, k) } } return resp{res.StatusCode, res.Header, body} } // request is how Equipo's HTTP provider calls: a bearer, JSON both ways, no // Origin and no cookies. An empty token sends no Authorization. func (b *base) request(method, path, token, contentType string, body []byte) *http.Request { b.t.Helper() var rd io.Reader if body != nil { rd = bytes.NewReader(body) } req, err := http.NewRequest(method, b.url+path, rd) if err != nil { b.t.Fatal(err) } if token != "" { req.Header.Set("Authorization", "Bearer "+token) } req.Header.Set("Accept", "application/json") if contentType != "" { req.Header.Set("Content-Type", contentType) } return req } func (b *base) list(token string) resp { return b.send(b.request(http.MethodGet, "/api/v1/operations", token, "", nil)) } func (b *base) invoke(token, name string) resp { return b.send(b.request(http.MethodPost, "/api/v1/operations/"+name, token, "application/json", []byte(`{}`))) } // decode reads a 200's JSON into out. func (r resp) decode(t *testing.T, out any) { t.Helper() if r.code != http.StatusOK { t.Fatalf("status %d, body %s", r.code, r.body) } if ct := r.header.Get("Content-Type"); !strings.HasPrefix(ct, "application/json") { t.Errorf("Content-Type = %q", ct) } if err := json.Unmarshal(r.body, out); err != nil { t.Fatalf("%v in %s", err, r.body) } } // refused checks a refusal's status and its {"error":{"code","message"}}. func (r resp) refused(t *testing.T, what string, status int, code string) { t.Helper() if r.code != status { t.Errorf("%s: status %d, want %d; body %s", what, r.code, status, r.body) return } var env struct { Error struct{ Code, Message string } `json:"error"` } if err := json.Unmarshal(r.body, &env); err != nil || env.Error.Code != code || env.Error.Message == "" { t.Errorf("%s: body %s, want error code %q with a message", what, r.body, code) } if status == http.StatusUnauthorized && r.header.Get("WWW-Authenticate") != "Bearer" { t.Errorf("%s: WWW-Authenticate = %q, want Bearer", what, r.header.Get("WWW-Authenticate")) } } type operation struct { Name string `json:"name"` Description string `json:"description"` Scope string `json:"scope"` ReadOnly bool `json:"read_only"` Destructive bool `json:"destructive"` Idempotent bool `json:"idempotent"` External bool `json:"external"` App string `json:"app"` Input json.RawMessage `json:"input_schema"` Output json.RawMessage `json:"output_schema"` } func TestOperationsList(t *testing.T) { b := newBase(t, nil) var env struct { Operations []operation `json:"operations"` } b.list(b.token(ownerAddress)).decode(t, &env) var names []string for _, op := range env.Operations { names = append(names, op.Name) if !op.ReadOnly || op.Destructive || !op.Idempotent || op.External || op.Scope != "base.read" || op.App != "Base" { t.Errorf("%s: %+v; want read-only, not destructive, idempotent, not external, base.read, Base", op.Name, op) } if op.Description == "" || strings.Contains(op.Description, "—") || strings.Contains(op.Description, "!") { t.Errorf("%s: description %q", op.Name, op.Description) } var in map[string]any if err := json.Unmarshal(op.Input, &in); err != nil || !reflect.DeepEqual(in, map[string]any{"type": "object", "additionalProperties": false}) { t.Errorf("%s: input_schema %s (%v)", op.Name, op.Input, err) } var out map[string]any if err := json.Unmarshal(op.Output, &out); err != nil || out["type"] != "object" { t.Errorf("%s: output_schema %s is not a JSON object schema (%v)", op.Name, op.Output, err) } } if want := []string{"base_apps", "base_people", "base_settings"}; !reflect.DeepEqual(names, want) { t.Fatalf("operations = %v, want %v", names, want) } } type settings struct { Name string `json:"name"` Timezone string `json:"timezone"` You struct { Name string `json:"name"` Email string `json:"email"` Role string `json:"role"` } `json:"you"` } // A host token is one member's: each answers with that member's view, and // nothing else gets in, not even a signed-in owner's browser. func TestOperationsTokenIsOneMembers(t *testing.T) { tz, err := time.LoadLocation("Europe/Madrid") if err != nil { t.Fatal(err) } b := newBase(t, func(c *config.Config) { c.Timezone = tz }) ana, owner := b.token("ana@acme.test"), b.token(ownerAddress) for _, c := range []struct{ token, email, role string }{{ana, "ana@acme.test", "member"}, {owner, ownerAddress, "owner"}} { var s settings b.invoke(c.token, "base_settings").decode(t, &s) if s.You.Email != c.email || s.You.Role != c.role || s.Name != "Acme" || s.Timezone != "Europe/Madrid" { t.Errorf("base_settings for %s = %+v", c.email, s) } } var people struct { People []struct { Name, Email, Role string Joined bool } `json:"people"` } b.invoke(ana, "base_people").decode(t, &people) got := map[string]string{} for _, p := range people.People { got[p.Email] = p.Role if p.Joined { t.Errorf("%s has not joined, base_people says joined", p.Email) } } if want := map[string]string{ownerAddress: "owner", "ana@acme.test": "member"}; !reflect.DeepEqual(got, want) { t.Errorf("base_people = %+v", people) } // One character changed. last := owner[len(owner)-1] swap := byte('A') if last == 'A' { swap = 'B' } b.invoke(owner[:len(owner)-1]+string(swap), "base_settings").refused(t, "altered token", 401, "unauthenticated") b.list(owner[:len(owner)-1]+string(swap)).refused(t, "altered token, list", 401, "unauthenticated") b.invoke("", "base_settings").refused(t, "no token", 401, "unauthenticated") b.list("").refused(t, "no token, list", 401, "unauthenticated") b.list("not-a-token").refused(t, "not a token", 401, "unauthenticated") req := b.request(http.MethodGet, "/api/v1/operations", "", "", nil) req.Header.Set("Authorization", "Basic "+owner) b.send(req).refused(t, "Basic scheme", 401, "unauthenticated") // A signed-in owner's session cookie, with no bearer. The cookie is // real: it opens Home. sess, err := sessions.New(sessions.Config{DB: b.db, Origin: testOrigin}) if err != nil { t.Fatal(err) } cookie, err := sess.Mint(sessions.Session{Subject: ownerAddress, Method: "email", At: time.Now(), AuthTime: time.Now()}) if err != nil { t.Fatal(err) } home := b.request(http.MethodGet, "/", "", "", nil) home.AddCookie(&http.Cookie{Name: sess.CookieName(), Value: cookie}) if r := b.send(home); r.code != http.StatusOK { t.Fatalf("the owner's cookie does not open Home: %d", r.code) } for _, req := range []*http.Request{ b.request(http.MethodGet, "/api/v1/operations", "", "", nil), b.request(http.MethodPost, "/api/v1/operations/base_settings", "", "application/json", []byte(`{}`)), } { req.AddCookie(&http.Cookie{Name: sess.CookieName(), Value: cookie}) req.Header.Set("Origin", testOrigin) b.send(req).refused(t, "cookie only: "+req.Method, 401, "unauthenticated") } // Ana is removed: her token goes with her. if err := store.RemoveMember(context.Background(), b.db, b.member("ana@acme.test").ID); err != nil { t.Fatal(err) } b.invoke(ana, "base_settings").refused(t, "removed member", 401, "unauthenticated") b.list(ana).refused(t, "removed member, list", 401, "unauthenticated") var s settings b.invoke(owner, "base_settings").decode(t, &s) if s.You.Email != ownerAddress { t.Errorf("owner after Ana left = %+v", s) } } type named struct { ID string `json:"id"` Name string `json:"name"` Address string `json:"address"` Summary string `json:"summary"` } func TestOperationsBaseApps(t *testing.T) { b := newBase(t, func(c *config.Config) { c.OficinaApps = []config.OficinaApp{ {ID: "fichas", Name: "Fichas", Origin: "https://fichas.oficina.works"}, {ID: "calendar", Name: "Calendar", Origin: "https://calendar.oficina.works"}, } }) ctx := context.Background() if ok, err := store.ClaimInstall(ctx, b.db, "welcome", "acme-welcome.bab.oncarlos.com"); err != nil || !ok { t.Fatal(ok, err) } if err := store.SetInstallState(ctx, b.db, "welcome", "installed", ""); err != nil { t.Fatal(err) } if ok, err := store.ClaimInstall(ctx, b.db, "scratchpad", "acme-scratchpad.bab.oncarlos.com"); err != nil || !ok { t.Fatal(ok, err) } var apps struct { Installed []named `json:"installed"` Store []named `json:"store"` Oficina []named `json:"oficina"` } b.invoke(b.token(ownerAddress), "base_apps").decode(t, &apps) if want := []named{{ID: "welcome", Name: "Welcome", Address: "https://acme-welcome.bab.oncarlos.com/"}}; !reflect.DeepEqual(apps.Installed, want) { t.Errorf("installed = %+v, want %+v", apps.Installed, want) } for _, a := range apps.Store { if a.ID == "welcome" { t.Errorf("an installed app is in the store: %+v", apps.Store) } } found := false for _, a := range apps.Store { if a.ID == "scratchpad" && a.Name == "Scratchpad" && a.Summary != "" { found = true } } if !found { t.Errorf("store %+v lacks Scratchpad, which is not installed", apps.Store) } want := []named{ {ID: "fichas", Name: "Fichas", Address: "https://fichas.oficina.works/"}, {ID: "calendar", Name: "Calendar", Address: "https://calendar.oficina.works/"}, } if !reflect.DeepEqual(apps.Oficina, want) { t.Errorf("oficina = %+v, want %+v", apps.Oficina, want) } // Lists are lists, never null, when there is nothing to list. empty := newBase(t, nil) r := empty.invoke(empty.token(ownerAddress), "base_apps") if r.code != 200 || !bytes.Contains(r.body, []byte(`"installed":[]`)) || !bytes.Contains(r.body, []byte(`"oficina":[]`)) { t.Errorf("empty base_apps = %d %s", r.code, r.body) } } func TestOperationsRefusals(t *testing.T) { b := newBase(t, nil) tok := b.token(ownerAddress) post := func(name, contentType string, body []byte) resp { return b.send(b.request(http.MethodPost, "/api/v1/operations/"+name, tok, contentType, body)) } post("base_nothing", "application/json", []byte(`{}`)).refused(t, "unknown name", 404, "not_found") post("base_apps/extra", "application/json", []byte(`{}`)).refused(t, "a path under a name", 404, "not_found") post("", "application/json", []byte(`{}`)).refused(t, "no name", 404, "not_found") post("base_apps", "text/plain", []byte(`{}`)).refused(t, "text/plain", 415, "unsupported_media_type") post("base_apps", "", []byte(`{}`)).refused(t, "no Content-Type", 415, "unsupported_media_type") for _, body := range []string{`{"a":1}`, `[]`, `null`, ``, `{}{}`, `{`, `"x"`} { post("base_apps", "application/json", []byte(body)).refused(t, "body "+body, 422, "invalid") } big := append([]byte(`{"pad":"`), bytes.Repeat([]byte("x"), 64<<10)...) big = append(big, `"}`...) post("base_apps", "application/json", big).refused(t, "over 64 KiB", 413, "too_large") // Equipo sends JSON with a charset sometimes, and an Idempotency-Key it // derives; neither matters here. No Origin header: this is no browser. req := b.request(http.MethodPost, "/api/v1/operations/base_people", tok, "application/json; charset=utf-8", []byte(" { } ")) req.Header.Set("Idempotency-Key", "5f1c2a8e-0000-5000-8000-000000000000") if req.Header.Get("Origin") != "" { t.Fatal("the request has an Origin") } if r := b.send(req); r.code != 200 { t.Errorf("POST without Origin = %d %s; want 200", r.code, r.body) } b.send(b.request(http.MethodDelete, "/api/v1/operations/base_apps", tok, "", nil)).refused(t, "DELETE", 405, "method_not_allowed") }