// 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/oficina/base/internal/catalog" "amadan.net/oficina/base/internal/config" "amadan.net/oficina/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 }