Serve Base's operations to the member's Assistant
Equipo's Assistant reaches Base through agent-access's operations
contract: GET /api/v1/operations lists base_apps, base_people and
base_settings, and POST /api/v1/operations/{name} with {} runs one for
the member whose host token is the bearer. All three only read.
Host tokens are "bh_" and 32 random bytes in base64url, one per member
(minting again replaces the last), kept only as their SHA-256 in the new
host_tokens table (migration 0009), which goes with the member. The
lookup joins the current members and compares the hashes in constant
time. The route sits in front of the router, outside csrf.Protect and
the member gate, so cookies count for nothing there; every answer is
no-store with no CORS headers.
The descriptions and error messages are in docs/copy-pending.md as
Review 7, pending.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
7 files changed,
+1,035
−1
docs/copy-pending.md+15 −0internal/operations/operations.go+325 −0internal/operations/operations_test.go+426 −0internal/store/hosttokens.go+106 −0internal/store/hosttokens_test.go+135 −0internal/store/migrations/0009_host_tokens.sql+11 −0internal/web/app.go+17 −1
diff --git a/docs/copy-pending.md b/docs/copy-pending.md| index 5a3d553..0dcc79e 100644 |
| --- a/docs/copy-pending.md |
| +++ b/docs/copy-pending.md |
| @@ -307,3 +307,18 @@ Equipo's words, reused as Equipo has them (internal/equipo/copy.go on its base-p |
| | ask_cards.go, ask.js | Publish card's site state | chat.card.publish_chose_publish, work.tl.published, work.tl.publish_unconfirmed, chat.card.publish_chose_not_now | Publishing. / Published / Publish could not be confirmed / Not published. | |
| The cards' questions ("Merge {title} without checks?", "Publish {title} on the web as {app}?") and Equipo's chat lines come from Equipo as it sends them; Base turns their Markdown links into links and shows everything else as text. |
| + |
| +Review 7 (pending): Base's operations for Equipo's Assistant. The Assistant reads these when it looks at what Base can do, and may repeat them to the person. |
| + |
| +| File | Context | Text | |
| +|---|---|---| |
| +| internal/operations/operations.go | Operation description: base_apps | Lists the apps installed on this Base with their addresses, the apps in its Store that are not installed, and the team's Oficina apps with their addresses. | |
| +| internal/operations/operations.go | Operation description: base_people | Lists the members of this Base with their name, email, role and whether they have joined. | |
| +| internal/operations/operations.go | Operation description: base_settings | Gives this Base's name and time zone, and the name, email and role of the person asking. | |
| +| internal/operations/operations.go | Error message: missing, unknown or replaced host token, or a removed member's (401 unauthenticated) | Base did not accept this token. | |
| +| internal/operations/operations.go | Error message: no operation by that name (404 not_found) | Base has no operation by that name. | |
| +| internal/operations/operations.go | Error message: wrong method (405 method_not_allowed) | Base does not accept that method here. | |
| +| internal/operations/operations.go | Error message: input not sent as JSON (415 unsupported_media_type) | Send the input as JSON. | |
| +| internal/operations/operations.go | Error message: input over 64 KiB (413 too_large) | The input is too large. | |
| +| internal/operations/operations.go | Error message: input other than {} (422 invalid) | This operation takes no input. | |
| +| internal/operations/operations.go | Error message: Base's database failed (503 unavailable) | Base could not answer. Try again. | |
diff --git a/internal/operations/operations.go b/internal/operations/operations.go| new file mode 100644 |
| index 0000000..603f18b |
| --- /dev/null |
| +++ b/internal/operations/operations.go |
| @@ -0,0 +1,325 @@ |
| +// Package operations serves Base's operations to Equipo's Assistant, in |
| +// agent-access's shapes: GET Path lists them, and POST Path/{name} runs one |
| +// for the member whose host token is the request's bearer. Every operation |
| +// here only reads. |
| +package operations |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "log/slog" |
| + "mime" |
| + "net/http" |
| + "strings" |
| + |
| + "amadan.net/carlos/base/internal/catalog" |
| + "amadan.net/carlos/base/internal/config" |
| + "amadan.net/carlos/base/internal/store" |
| +) |
| + |
| +// Path is where the operations live. Mount the handler for Path and every |
| +// path under it, outside CSRF protection and the member gate: its callers |
| +// are servers, and the host token is the only proof it takes. |
| +const Path = "/api/v1/operations" |
| + |
| +// maxInput is the largest request body an operation reads. |
| +const maxInput = 64 << 10 |
| + |
| +// descriptor is an operation as agent-access lists it. |
| +type descriptor 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"` |
| +} |
| + |
| +type operation struct { |
| + descriptor |
| + run func(s *server, ctx context.Context, me store.Member) (any, error) |
| +} |
| + |
| +// noInput is the input schema of an operation that takes nothing. |
| +var noInput = json.RawMessage(`{"type":"object","additionalProperties":false}`) |
| + |
| +func read(name, description string, output json.RawMessage, run func(*server, context.Context, store.Member) (any, error)) operation { |
| + return operation{descriptor{Name: name, Description: description, Scope: "base.read", ReadOnly: true, |
| + Idempotent: true, App: "Base", Input: noInput, Output: output}, run} |
| +} |
| + |
| +// The descriptions are copy (docs/copy-pending.md). |
| +var ops = []operation{ |
| + read("base_apps", |
| + "Lists the apps installed on this Base with their addresses, the apps in its Store that are not installed, and the team's Oficina apps with their addresses.", |
| + schema(object( |
| + "installed", list(texts("id", "name", "address")), |
| + "store", list(texts("id", "name", "summary")), |
| + "oficina", list(texts("id", "name", "address")))), |
| + (*server).apps), |
| + read("base_people", |
| + "Lists the members of this Base with their name, email, role and whether they have joined.", |
| + schema(object("people", list(object("name", str, "email", str, "role", str, "joined", boolean)))), |
| + (*server).people), |
| + read("base_settings", |
| + "Gives this Base's name and time zone, and the name, email and role of the person asking.", |
| + schema(object("name", str, "timezone", str, "you", texts("name", "email", "role"))), |
| + (*server).settings), |
| +} |
| + |
| +type server struct { |
| + db *sql.DB |
| + cfg config.Config |
| + logger *slog.Logger |
| +} |
| + |
| +// Handler answers Path and everything under it. |
| +func Handler(db *sql.DB, cfg config.Config) http.Handler { |
| + s := &server{db: db, cfg: cfg, logger: slog.Default()} |
| + return http.HandlerFunc(s.serve) |
| +} |
| + |
| +func (s *server) serve(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + me, ok, err := s.member(r) |
| + if err != nil { |
| + s.logger.Error("operations: host token lookup", "err", err) |
| + fail(w, http.StatusServiceUnavailable, "unavailable", "Base could not answer. Try again.") |
| + return |
| + } |
| + if !ok { |
| + w.Header().Set("WWW-Authenticate", "Bearer") |
| + fail(w, http.StatusUnauthorized, "unauthenticated", "Base did not accept this token.") |
| + return |
| + } |
| + rest, under := strings.CutPrefix(r.URL.Path, Path) |
| + if !under { |
| + fail(w, http.StatusNotFound, "not_found", "Base has no operation by that name.") |
| + return |
| + } |
| + if rest == "" { |
| + if r.Method != http.MethodGet { |
| + w.Header().Set("Allow", http.MethodGet) |
| + fail(w, http.StatusMethodNotAllowed, "method_not_allowed", "Base does not accept that method here.") |
| + return |
| + } |
| + list := make([]descriptor, len(ops)) |
| + for i, op := range ops { |
| + list[i] = op.descriptor |
| + } |
| + answer(w, struct { |
| + Operations []descriptor `json:"operations"` |
| + }{list}) |
| + return |
| + } |
| + op, found := find(strings.TrimPrefix(rest, "/")) |
| + if !found || !strings.HasPrefix(rest, "/") { |
| + fail(w, http.StatusNotFound, "not_found", "Base has no operation by that name.") |
| + return |
| + } |
| + if r.Method != http.MethodPost { |
| + w.Header().Set("Allow", http.MethodPost) |
| + fail(w, http.StatusMethodNotAllowed, "method_not_allowed", "Base does not accept that method here.") |
| + return |
| + } |
| + if mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")); err != nil || mt != "application/json" { |
| + fail(w, http.StatusUnsupportedMediaType, "unsupported_media_type", "Send the input as JSON.") |
| + return |
| + } |
| + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxInput)) |
| + if err != nil { |
| + if _, big := errors.AsType[*http.MaxBytesError](err); big { |
| + fail(w, http.StatusRequestEntityTooLarge, "too_large", "The input is too large.") |
| + return |
| + } |
| + fail(w, http.StatusBadRequest, "invalid", "This operation takes no input.") |
| + return |
| + } |
| + // Idempotency-Key is accepted and ignored: nothing here writes. |
| + if !emptyObject(body) { |
| + fail(w, http.StatusUnprocessableEntity, "invalid", "This operation takes no input.") |
| + return |
| + } |
| + out, err := op.run(s, r.Context(), me) |
| + if err != nil { |
| + s.logger.Error("operations: run", "operation", op.Name, "err", err) |
| + fail(w, http.StatusServiceUnavailable, "unavailable", "Base could not answer. Try again.") |
| + return |
| + } |
| + answer(w, out) |
| +} |
| + |
| +// member is the member whose host token the request bears. Cookies count |
| +// for nothing here. |
| +func (s *server) member(r *http.Request) (store.Member, bool, error) { |
| + scheme, token, ok := strings.Cut(r.Header.Get("Authorization"), " ") |
| + if !ok || !strings.EqualFold(scheme, "Bearer") { |
| + return store.Member{}, false, nil |
| + } |
| + return store.MemberByHostToken(r.Context(), s.db, strings.TrimSpace(token)) |
| +} |
| + |
| +func find(name string) (operation, bool) { |
| + for _, op := range ops { |
| + if op.Name == name { |
| + return op, true |
| + } |
| + } |
| + return operation{}, false |
| +} |
| + |
| +// emptyObject reports whether body is one JSON object with no members. |
| +func emptyObject(body []byte) bool { |
| + if t := bytes.TrimSpace(body); len(t) == 0 || t[0] != '{' { |
| + return false |
| + } |
| + dec := json.NewDecoder(bytes.NewReader(body)) |
| + var m map[string]json.RawMessage |
| + if dec.Decode(&m) != nil || len(m) != 0 { |
| + return false |
| + } |
| + var more json.RawMessage |
| + return dec.Decode(&more) == io.EOF |
| +} |
| + |
| +func answer(w http.ResponseWriter, v any) { |
| + w.Header().Set("Content-Type", "application/json") |
| + json.NewEncoder(w).Encode(v) |
| +} |
| + |
| +func fail(w http.ResponseWriter, status int, code, message string) { |
| + w.Header().Set("Content-Type", "application/json") |
| + w.WriteHeader(status) |
| + json.NewEncoder(w).Encode(map[string]map[string]string{"error": {"code": code, "message": message}}) |
| +} |
| + |
| +// placed is an app people can open, at its address. |
| +type placed struct { |
| + ID string `json:"id"` |
| + Name string `json:"name"` |
| + Address string `json:"address"` |
| +} |
| + |
| +// offered is an app the Store offers. |
| +type offered struct { |
| + ID string `json:"id"` |
| + Name string `json:"name"` |
| + Summary string `json:"summary"` |
| +} |
| + |
| +// apps is base_apps: what is installed and ready, at the address it was |
| +// installed at; what the Store offers that is not installed; and the team's |
| +// Oficina apps, in the order the operator listed them. |
| +func (s *server) apps(ctx context.Context, _ store.Member) (any, error) { |
| + installs, err := store.Installs(ctx, s.db) |
| + if err != nil { |
| + return nil, err |
| + } |
| + out := struct { |
| + Installed []placed `json:"installed"` |
| + Store []offered `json:"store"` |
| + Oficina []placed `json:"oficina"` |
| + }{[]placed{}, []offered{}, []placed{}} |
| + installed := map[string]bool{} |
| + for _, in := range installs { |
| + e, ok := catalog.Get(in.App) |
| + if !ok || in.State != "installed" { |
| + continue |
| + } |
| + installed[e.ID] = true |
| + out.Installed = append(out.Installed, placed{ID: e.ID, Name: e.Name, Address: "https://" + in.Host + "/"}) |
| + } |
| + for _, e := range catalog.All() { |
| + if !installed[e.ID] { |
| + out.Store = append(out.Store, offered{ID: e.ID, Name: e.Name, Summary: e.Summary}) |
| + } |
| + } |
| + for _, o := range s.cfg.OficinaApps { |
| + out.Oficina = append(out.Oficina, placed{ID: o.ID, Name: o.Name, Address: o.Origin + "/"}) |
| + } |
| + return out, nil |
| +} |
| + |
| +type person struct { |
| + Name string `json:"name"` |
| + Email string `json:"email"` |
| + Role string `json:"role"` |
| + Joined bool `json:"joined"` |
| +} |
| + |
| +// people is base_people: every member, and whether each has signed in yet. |
| +func (s *server) people(ctx context.Context, _ store.Member) (any, error) { |
| + ms, err := store.Members(ctx, s.db) |
| + if err != nil { |
| + return nil, err |
| + } |
| + out := struct { |
| + People []person `json:"people"` |
| + }{[]person{}} |
| + for _, m := range ms { |
| + out.People = append(out.People, person{Name: m.Name, Email: m.Email, Role: m.Role, Joined: m.JoinedAt != nil}) |
| + } |
| + return out, nil |
| +} |
| + |
| +// settings is base_settings: this Base, and the member asking. |
| +func (s *server) settings(_ context.Context, me store.Member) (any, error) { |
| + type you struct { |
| + Name string `json:"name"` |
| + Email string `json:"email"` |
| + Role string `json:"role"` |
| + } |
| + return struct { |
| + Name string `json:"name"` |
| + Timezone string `json:"timezone"` |
| + You you `json:"you"` |
| + }{s.cfg.Name, s.cfg.Timezone.String(), you{me.Name, me.Email, me.Role}}, nil |
| +} |
| + |
| +// Output schemas, built from these few parts. |
| +var ( |
| + str = map[string]any{"type": "string"} |
| + boolean = map[string]any{"type": "boolean"} |
| +) |
| + |
| +// object is a closed object schema whose every property is required; kv |
| +// alternates property names and their schemas. |
| +func object(kv ...any) map[string]any { |
| + props := map[string]any{} |
| + var required []string |
| + for i := 0; i < len(kv); i += 2 { |
| + name := kv[i].(string) |
| + props[name] = kv[i+1] |
| + required = append(required, name) |
| + } |
| + return map[string]any{"type": "object", "additionalProperties": false, "required": required, "properties": props} |
| +} |
| + |
| +// texts is an object of string properties. |
| +func texts(names ...string) map[string]any { |
| + kv := make([]any, 0, 2*len(names)) |
| + for _, n := range names { |
| + kv = append(kv, n, str) |
| + } |
| + return object(kv...) |
| +} |
| + |
| +func list(items map[string]any) map[string]any { |
| + return map[string]any{"type": "array", "items": items} |
| +} |
| + |
| +func schema(v map[string]any) json.RawMessage { |
| + b, err := json.Marshal(v) |
| + if err != nil { |
| + panic("operations: " + err.Error()) |
| + } |
| + return b |
| +} |
diff --git a/internal/operations/operations_test.go b/internal/operations/operations_test.go| new file mode 100644 |
| index 0000000..245131f |
| --- /dev/null |
| +++ b/internal/operations/operations_test.go |
| @@ -0,0 +1,426 @@ |
| +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/carlos/base/internal/config" |
| + "amadan.net/carlos/base/internal/store" |
| + "amadan.net/carlos/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") |
| +} |
diff --git a/internal/store/hosttokens.go b/internal/store/hosttokens.go| new file mode 100644 |
| index 0000000..9e12a85 |
| --- /dev/null |
| +++ b/internal/store/hosttokens.go |
| @@ -0,0 +1,106 @@ |
| +package store |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "crypto/subtle" |
| + "database/sql" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "errors" |
| + "time" |
| +) |
| + |
| +// A host token is what Equipo's Assistant presents when it calls Base's |
| +// operations for one member: "bh_" and 32 random bytes in unpadded |
| +// base64url. Base keeps only its SHA-256. |
| +const ( |
| + hostTokenPrefix = "bh_" |
| + hostTokenBytes = 32 |
| +) |
| + |
| +var hostTokenLen = len(hostTokenPrefix) + base64.RawURLEncoding.EncodedLen(hostTokenBytes) |
| + |
| +func hashHostToken(token string) string { |
| + sum := sha256.Sum256([]byte(token)) |
| + return hex.EncodeToString(sum[:]) |
| +} |
| + |
| +// MintHostToken makes a new host token for the member and returns it. It |
| +// replaces the member's last one, which names nobody from then on, and the |
| +// new one counts as not yet registered with Equipo. The token itself is |
| +// never stored: hand it straight to Equipo. |
| +func MintHostToken(ctx context.Context, db *sql.DB, memberID string) (string, error) { |
| + b := make([]byte, hostTokenBytes) |
| + if _, err := rand.Read(b); err != nil { |
| + return "", err |
| + } |
| + token := hostTokenPrefix + base64.RawURLEncoding.EncodeToString(b) |
| + _, err := db.ExecContext(ctx, `INSERT INTO host_tokens (member_id, token_hash, created_at) VALUES (?, ?, ?) |
| + ON CONFLICT (member_id) DO UPDATE SET token_hash = excluded.token_hash, |
| + created_at = excluded.created_at, registered_at = NULL`, |
| + memberID, hashHostToken(token), time.Now().UTC()) |
| + if err != nil { |
| + return "", err |
| + } |
| + return token, nil |
| +} |
| + |
| +// MemberByHostToken is the member whose current host token is token; ok is |
| +// false for anything else, including the token of a member who was removed. |
| +func MemberByHostToken(ctx context.Context, db *sql.DB, token string) (Member, bool, error) { |
| + if len(token) != hostTokenLen || token[:len(hostTokenPrefix)] != hostTokenPrefix { |
| + return Member{}, false, nil |
| + } |
| + if b, err := base64.RawURLEncoding.Strict().DecodeString(token[len(hostTokenPrefix):]); err != nil || len(b) != hostTokenBytes { |
| + return Member{}, false, nil |
| + } |
| + want := hashHostToken(token) |
| + var stored string |
| + m, err := scanMember(withFirst{db.QueryRowContext(ctx, `SELECT t.token_hash, `+memberColsOf("m")+` |
| + FROM host_tokens t JOIN members m ON m.id = t.member_id WHERE t.token_hash = ?`, want), &stored}) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return Member{}, false, nil |
| + } |
| + if err != nil { |
| + return Member{}, false, err |
| + } |
| + if subtle.ConstantTimeCompare([]byte(stored), []byte(want)) != 1 { |
| + return Member{}, false, nil |
| + } |
| + return m, true, nil |
| +} |
| + |
| +// withFirst scans the row's first column into first and the rest into |
| +// what its caller asks for. |
| +type withFirst struct { |
| + row scanner |
| + first any |
| +} |
| + |
| +func (w withFirst) Scan(dest ...any) error { return w.row.Scan(append([]any{w.first}, dest...)...) } |
| + |
| +// DeleteHostToken forgets the member's host token, so it names nobody. |
| +func DeleteHostToken(ctx context.Context, db *sql.DB, memberID string) error { |
| + _, err := db.ExecContext(ctx, `DELETE FROM host_tokens WHERE member_id = ?`, memberID) |
| + return err |
| +} |
| + |
| +// HostRegistered reports whether the member's current host token has been |
| +// given to Equipo. A member with no token is not registered. |
| +func HostRegistered(ctx context.Context, db *sql.DB, memberID string) (bool, error) { |
| + var registered sql.NullTime |
| + err := db.QueryRowContext(ctx, `SELECT registered_at FROM host_tokens WHERE member_id = ?`, memberID).Scan(®istered) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return false, nil |
| + } |
| + return registered.Valid, err |
| +} |
| + |
| +// MarkHostRegistered records that Equipo now holds the member's current |
| +// host token. |
| +func MarkHostRegistered(ctx context.Context, db *sql.DB, memberID string) error { |
| + _, err := db.ExecContext(ctx, `UPDATE host_tokens SET registered_at = ? WHERE member_id = ?`, time.Now().UTC(), memberID) |
| + return err |
| +} |
diff --git a/internal/store/hosttokens_test.go b/internal/store/hosttokens_test.go| new file mode 100644 |
| index 0000000..194c35a |
| --- /dev/null |
| +++ b/internal/store/hosttokens_test.go |
| @@ -0,0 +1,135 @@ |
| +package store |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "regexp" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +var hostTokenRE = regexp.MustCompile(`^bh_[A-Za-z0-9_-]{43}$`) |
| + |
| +// A host token names exactly one member, only until it is replaced or the |
| +// member goes, and Base keeps nothing from which it could be read back. |
| +func TestHostTokenRoundTrip(t *testing.T) { |
| + ctx, db := context.Background(), open(t) |
| + ana, _, err := Invite(ctx, db, "ana@example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + bea, _, err := Invite(ctx, db, "bea@example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + first, err := MintHostToken(ctx, db, ana.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !hostTokenRE.MatchString(first) { |
| + t.Fatalf("token %q is not bh_ and 43 base64url characters", first) |
| + } |
| + beas, err := MintHostToken(ctx, db, bea.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if m, ok, err := MemberByHostToken(ctx, db, first); err != nil || !ok || m.ID != ana.ID || m.Email != "ana@example.com" { |
| + t.Fatalf("first token = %+v %v %v; want ana", m, ok, err) |
| + } |
| + if m, ok, err := MemberByHostToken(ctx, db, beas); err != nil || !ok || m.ID != bea.ID { |
| + t.Fatalf("bea's token = %+v %v %v; want bea", m, ok, err) |
| + } |
| + for _, bad := range []string{"", "bh_", first[:len(first)-1], first + "A", strings.ToUpper(first[:4]) + first[4:]} { |
| + if m, ok, err := MemberByHostToken(ctx, db, bad); err != nil || ok { |
| + t.Errorf("token %q = %+v %v %v; want nobody", bad, m, ok, err) |
| + } |
| + } |
| + |
| + if reg, err := HostRegistered(ctx, db, ana.ID); err != nil || reg { |
| + t.Fatalf("registered before marking = %v, %v", reg, err) |
| + } |
| + if err := MarkHostRegistered(ctx, db, ana.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if reg, err := HostRegistered(ctx, db, ana.ID); err != nil || !reg { |
| + t.Fatalf("registered after marking = %v, %v", reg, err) |
| + } |
| + |
| + second, err := MintHostToken(ctx, db, ana.ID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if second == first { |
| + t.Fatal("minting again gave the same token") |
| + } |
| + if m, ok, err := MemberByHostToken(ctx, db, first); err != nil || ok { |
| + t.Fatalf("replaced token = %+v %v %v; want nobody", m, ok, err) |
| + } |
| + if m, ok, err := MemberByHostToken(ctx, db, second); err != nil || !ok || m.ID != ana.ID { |
| + t.Fatalf("new token = %+v %v %v; want ana", m, ok, err) |
| + } |
| + if reg, err := HostRegistered(ctx, db, ana.ID); err != nil || reg { |
| + t.Fatalf("a new token is registered before Base registers it: %v, %v", reg, err) |
| + } |
| + |
| + // Nothing in the table is a token; the hash is its SHA-256. |
| + rows, err := db.QueryContext(ctx, `SELECT member_id, token_hash, created_at, coalesce(registered_at, '') FROM host_tokens`) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + hashes := map[string]bool{} |
| + n := 0 |
| + for rows.Next() { |
| + var member, hash, created, registered string |
| + if err := rows.Scan(&member, &hash, &created, ®istered); err != nil { |
| + t.Fatal(err) |
| + } |
| + n++ |
| + hashes[hash] = true |
| + for _, col := range []string{member, hash, created, registered} { |
| + for _, tok := range []string{first, second, beas, first[3:], second[3:], beas[3:]} { |
| + if strings.Contains(col, tok) { |
| + t.Errorf("host_tokens holds a token in plain text: %q", col) |
| + } |
| + } |
| + } |
| + } |
| + if err := rows.Close(); err != nil { |
| + t.Fatal(err) |
| + } |
| + if n != 2 { |
| + t.Fatalf("host_tokens has %d rows, want one per member (2)", n) |
| + } |
| + for _, tok := range []string{second, beas} { |
| + sum := sha256.Sum256([]byte(tok)) |
| + if !hashes[hex.EncodeToString(sum[:])] { |
| + t.Errorf("no row holds the SHA-256 of a live token") |
| + } |
| + } |
| + |
| + // Removing a member removes their token with them. |
| + if err := RemoveMember(ctx, db, ana.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if m, ok, err := MemberByHostToken(ctx, db, second); err != nil || ok { |
| + t.Fatalf("removed member's token = %+v %v %v; want nobody", m, ok, err) |
| + } |
| + var left int |
| + if err := db.QueryRowContext(ctx, `SELECT count(*) FROM host_tokens WHERE member_id = ?`, ana.ID).Scan(&left); err != nil { |
| + t.Fatal(err) |
| + } |
| + if left != 0 { |
| + t.Fatalf("removed member still has %d host token rows", left) |
| + } |
| + |
| + if err := DeleteHostToken(ctx, db, bea.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + if m, ok, err := MemberByHostToken(ctx, db, beas); err != nil || ok { |
| + t.Fatalf("deleted token = %+v %v %v; want nobody", m, ok, err) |
| + } |
| + if reg, err := HostRegistered(ctx, db, bea.ID); err != nil || reg { |
| + t.Fatalf("registered with no token = %v, %v", reg, err) |
| + } |
| +} |
diff --git a/internal/store/migrations/0009_host_tokens.sql b/internal/store/migrations/0009_host_tokens.sql| new file mode 100644 |
| index 0000000..ece2df3 |
| --- /dev/null |
| +++ b/internal/store/migrations/0009_host_tokens.sql |
| @@ -0,0 +1,11 @@ |
| +-- A member's host token: what Equipo's Assistant presents when it calls |
| +-- Base's operations for that member. One per member; minting another |
| +-- replaces it. token_hash is the token's SHA-256 in hex, never the token. |
| +-- registered_at is when Base last gave this token to Equipo, NULL until it |
| +-- has. |
| +CREATE TABLE host_tokens ( |
| + member_id text PRIMARY KEY REFERENCES members (id) ON DELETE CASCADE, |
| + token_hash text NOT NULL UNIQUE, |
| + created_at datetime NOT NULL, |
| + registered_at datetime |
| +); |
diff --git a/internal/web/app.go b/internal/web/app.go| index 2b322ea..dd284f3 100644 |
| --- a/internal/web/app.go |
| +++ b/internal/web/app.go |
| @@ -11,6 +11,7 @@ import ( |
| "io/fs" |
| "log/slog" |
| "net/http" |
| + "strings" |
| "time" |
| "github.com/go-chi/chi/v5" |
| @@ -30,6 +31,7 @@ import ( |
| "amadan.net/carlos/base/internal/equipo" |
| "amadan.net/carlos/base/internal/issuer" |
| "amadan.net/carlos/base/internal/look" |
| + "amadan.net/carlos/base/internal/operations" |
| "amadan.net/carlos/base/internal/store" |
| ) |
| @@ -204,7 +206,21 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger |
| a.askRoutes(r) |
| } |
| }) |
| - return r, nil |
| + return withOperations(operations.Handler(d.Writer(), cfg), r), nil |
| +} |
| + |
| +// withOperations sends operations.Path and everything under it to ops and |
| +// the rest to site. ops sits outside site's middleware: no CSRF check (its |
| +// callers are servers, which send no Origin) and no member gate (the |
| +// member's host token is its proof, and cookies count for nothing there). |
| +func withOperations(ops, site http.Handler) http.Handler { |
| + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if p := r.URL.Path; p == operations.Path || strings.HasPrefix(p, operations.Path+"/") { |
| + ops.ServeHTTP(w, r) |
| + return |
| + } |
| + site.ServeHTTP(w, r) |
| + }) |
| } |
| // authorize admits a verified address that belongs to a member, and records |