| 1 | // Package operations serves Base's operations to Equipo's Assistant, in |
| 2 | // agent-access's shapes: GET Path lists them, and POST Path/{name} runs one |
| 3 | // for the member whose host token is the request's bearer. Every operation |
| 4 | // here only reads. |
| 5 | package operations |
| 6 | |
| 7 | import ( |
| 8 | "bytes" |
| 9 | "context" |
| 10 | "database/sql" |
| 11 | "encoding/json" |
| 12 | "errors" |
| 13 | "io" |
| 14 | "log/slog" |
| 15 | "mime" |
| 16 | "net/http" |
| 17 | "strings" |
| 18 | |
| 19 | "amadan.net/oficina/base/internal/catalog" |
| 20 | "amadan.net/oficina/base/internal/config" |
| 21 | "amadan.net/oficina/base/internal/store" |
| 22 | ) |
| 23 | |
| 24 | // Path is where the operations live. Mount the handler for Path and every |
| 25 | // path under it, outside CSRF protection and the member gate: its callers |
| 26 | // are servers, and the host token is the only proof it takes. |
| 27 | const Path = "/api/v1/operations" |
| 28 | |
| 29 | // maxInput is the largest request body an operation reads. |
| 30 | const maxInput = 64 << 10 |
| 31 | |
| 32 | // descriptor is an operation as agent-access lists it. |
| 33 | type descriptor struct { |
| 34 | Name string `json:"name"` |
| 35 | Description string `json:"description"` |
| 36 | Scope string `json:"scope"` |
| 37 | ReadOnly bool `json:"read_only"` |
| 38 | Destructive bool `json:"destructive"` |
| 39 | Idempotent bool `json:"idempotent"` |
| 40 | External bool `json:"external"` |
| 41 | App string `json:"app"` |
| 42 | Input json.RawMessage `json:"input_schema"` |
| 43 | Output json.RawMessage `json:"output_schema"` |
| 44 | } |
| 45 | |
| 46 | type operation struct { |
| 47 | descriptor |
| 48 | run func(s *server, ctx context.Context, me store.Member) (any, error) |
| 49 | } |
| 50 | |
| 51 | // noInput is the input schema of an operation that takes nothing. |
| 52 | var noInput = json.RawMessage(`{"type":"object","additionalProperties":false}`) |
| 53 | |
| 54 | func read(name, description string, output json.RawMessage, run func(*server, context.Context, store.Member) (any, error)) operation { |
| 55 | return operation{descriptor{Name: name, Description: description, Scope: "base.read", ReadOnly: true, |
| 56 | Idempotent: true, App: "Base", Input: noInput, Output: output}, run} |
| 57 | } |
| 58 | |
| 59 | // The descriptions are copy (docs/copy-pending.md). |
| 60 | var ops = []operation{ |
| 61 | read("base_apps", |
| 62 | "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.", |
| 63 | schema(object( |
| 64 | "installed", list(texts("id", "name", "address")), |
| 65 | "store", list(texts("id", "name", "summary")), |
| 66 | "oficina", list(texts("id", "name", "address")))), |
| 67 | (*server).apps), |
| 68 | read("base_people", |
| 69 | "Lists the members of this Base with their name, email, role and whether they have joined.", |
| 70 | schema(object("people", list(object("name", str, "email", str, "role", str, "joined", boolean)))), |
| 71 | (*server).people), |
| 72 | read("base_settings", |
| 73 | "Gives this Base's name and time zone, and the name, email and role of the person asking.", |
| 74 | schema(object("name", str, "timezone", str, "you", texts("name", "email", "role"))), |
| 75 | (*server).settings), |
| 76 | } |
| 77 | |
| 78 | type server struct { |
| 79 | db *sql.DB |
| 80 | cfg config.Config |
| 81 | logger *slog.Logger |
| 82 | } |
| 83 | |
| 84 | // Handler answers Path and everything under it. |
| 85 | func Handler(db *sql.DB, cfg config.Config) http.Handler { |
| 86 | s := &server{db: db, cfg: cfg, logger: slog.Default()} |
| 87 | return http.HandlerFunc(s.serve) |
| 88 | } |
| 89 | |
| 90 | func (s *server) serve(w http.ResponseWriter, r *http.Request) { |
| 91 | w.Header().Set("Cache-Control", "no-store") |
| 92 | me, ok, err := s.member(r) |
| 93 | if err != nil { |
| 94 | s.logger.Error("operations: host token lookup", "err", err) |
| 95 | fail(w, http.StatusServiceUnavailable, "unavailable", "Base could not answer. Try again.") |
| 96 | return |
| 97 | } |
| 98 | if !ok { |
| 99 | w.Header().Set("WWW-Authenticate", "Bearer") |
| 100 | fail(w, http.StatusUnauthorized, "unauthenticated", "Base did not accept this token.") |
| 101 | return |
| 102 | } |
| 103 | rest, under := strings.CutPrefix(r.URL.Path, Path) |
| 104 | if !under { |
| 105 | fail(w, http.StatusNotFound, "not_found", "Base has no operation by that name.") |
| 106 | return |
| 107 | } |
| 108 | if rest == "" { |
| 109 | if r.Method != http.MethodGet { |
| 110 | w.Header().Set("Allow", http.MethodGet) |
| 111 | fail(w, http.StatusMethodNotAllowed, "method_not_allowed", "Base does not accept that method here.") |
| 112 | return |
| 113 | } |
| 114 | list := make([]descriptor, len(ops)) |
| 115 | for i, op := range ops { |
| 116 | list[i] = op.descriptor |
| 117 | } |
| 118 | answer(w, struct { |
| 119 | Operations []descriptor `json:"operations"` |
| 120 | }{list}) |
| 121 | return |
| 122 | } |
| 123 | op, found := find(strings.TrimPrefix(rest, "/")) |
| 124 | if !found || !strings.HasPrefix(rest, "/") { |
| 125 | fail(w, http.StatusNotFound, "not_found", "Base has no operation by that name.") |
| 126 | return |
| 127 | } |
| 128 | if r.Method != http.MethodPost { |
| 129 | w.Header().Set("Allow", http.MethodPost) |
| 130 | fail(w, http.StatusMethodNotAllowed, "method_not_allowed", "Base does not accept that method here.") |
| 131 | return |
| 132 | } |
| 133 | if mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")); err != nil || mt != "application/json" { |
| 134 | fail(w, http.StatusUnsupportedMediaType, "unsupported_media_type", "Send the input as JSON.") |
| 135 | return |
| 136 | } |
| 137 | body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxInput)) |
| 138 | if err != nil { |
| 139 | if _, big := errors.AsType[*http.MaxBytesError](err); big { |
| 140 | fail(w, http.StatusRequestEntityTooLarge, "too_large", "The input is too large.") |
| 141 | return |
| 142 | } |
| 143 | fail(w, http.StatusBadRequest, "invalid", "This operation takes no input.") |
| 144 | return |
| 145 | } |
| 146 | // Idempotency-Key is accepted and ignored: nothing here writes. |
| 147 | if !emptyObject(body) { |
| 148 | fail(w, http.StatusUnprocessableEntity, "invalid", "This operation takes no input.") |
| 149 | return |
| 150 | } |
| 151 | out, err := op.run(s, r.Context(), me) |
| 152 | if err != nil { |
| 153 | s.logger.Error("operations: run", "operation", op.Name, "err", err) |
| 154 | fail(w, http.StatusServiceUnavailable, "unavailable", "Base could not answer. Try again.") |
| 155 | return |
| 156 | } |
| 157 | answer(w, out) |
| 158 | } |
| 159 | |
| 160 | // member is the member whose host token the request bears. Cookies count |
| 161 | // for nothing here. |
| 162 | func (s *server) member(r *http.Request) (store.Member, bool, error) { |
| 163 | scheme, token, ok := strings.Cut(r.Header.Get("Authorization"), " ") |
| 164 | if !ok || !strings.EqualFold(scheme, "Bearer") { |
| 165 | return store.Member{}, false, nil |
| 166 | } |
| 167 | return store.MemberByHostToken(r.Context(), s.db, strings.TrimSpace(token)) |
| 168 | } |
| 169 | |
| 170 | func find(name string) (operation, bool) { |
| 171 | for _, op := range ops { |
| 172 | if op.Name == name { |
| 173 | return op, true |
| 174 | } |
| 175 | } |
| 176 | return operation{}, false |
| 177 | } |
| 178 | |
| 179 | // emptyObject reports whether body is one JSON object with no members. |
| 180 | func emptyObject(body []byte) bool { |
| 181 | if t := bytes.TrimSpace(body); len(t) == 0 || t[0] != '{' { |
| 182 | return false |
| 183 | } |
| 184 | dec := json.NewDecoder(bytes.NewReader(body)) |
| 185 | var m map[string]json.RawMessage |
| 186 | if dec.Decode(&m) != nil || len(m) != 0 { |
| 187 | return false |
| 188 | } |
| 189 | var more json.RawMessage |
| 190 | return dec.Decode(&more) == io.EOF |
| 191 | } |
| 192 | |
| 193 | func answer(w http.ResponseWriter, v any) { |
| 194 | w.Header().Set("Content-Type", "application/json") |
| 195 | json.NewEncoder(w).Encode(v) |
| 196 | } |
| 197 | |
| 198 | func fail(w http.ResponseWriter, status int, code, message string) { |
| 199 | w.Header().Set("Content-Type", "application/json") |
| 200 | w.WriteHeader(status) |
| 201 | json.NewEncoder(w).Encode(map[string]map[string]string{"error": {"code": code, "message": message}}) |
| 202 | } |
| 203 | |
| 204 | // placed is an app people can open, at its address. |
| 205 | type placed struct { |
| 206 | ID string `json:"id"` |
| 207 | Name string `json:"name"` |
| 208 | Address string `json:"address"` |
| 209 | } |
| 210 | |
| 211 | // offered is an app the Store offers. |
| 212 | type offered struct { |
| 213 | ID string `json:"id"` |
| 214 | Name string `json:"name"` |
| 215 | Summary string `json:"summary"` |
| 216 | } |
| 217 | |
| 218 | // apps is base_apps: what is installed and ready, at the address it was |
| 219 | // installed at; what the Store offers that is not installed; and the team's |
| 220 | // Oficina apps, in the order the operator listed them. |
| 221 | func (s *server) apps(ctx context.Context, _ store.Member) (any, error) { |
| 222 | installs, err := store.Installs(ctx, s.db) |
| 223 | if err != nil { |
| 224 | return nil, err |
| 225 | } |
| 226 | out := struct { |
| 227 | Installed []placed `json:"installed"` |
| 228 | Store []offered `json:"store"` |
| 229 | Oficina []placed `json:"oficina"` |
| 230 | }{[]placed{}, []offered{}, []placed{}} |
| 231 | installed := map[string]bool{} |
| 232 | for _, in := range installs { |
| 233 | e, ok := catalog.Get(in.App) |
| 234 | if !ok || in.State != "installed" { |
| 235 | continue |
| 236 | } |
| 237 | installed[e.ID] = true |
| 238 | out.Installed = append(out.Installed, placed{ID: e.ID, Name: e.Name, Address: "https://" + in.Host + "/"}) |
| 239 | } |
| 240 | for _, e := range catalog.All() { |
| 241 | if !installed[e.ID] { |
| 242 | out.Store = append(out.Store, offered{ID: e.ID, Name: e.Name, Summary: e.Summary}) |
| 243 | } |
| 244 | } |
| 245 | for _, o := range s.cfg.OficinaApps { |
| 246 | out.Oficina = append(out.Oficina, placed{ID: o.ID, Name: o.Name, Address: o.Origin + "/"}) |
| 247 | } |
| 248 | return out, nil |
| 249 | } |
| 250 | |
| 251 | type person struct { |
| 252 | Name string `json:"name"` |
| 253 | Email string `json:"email"` |
| 254 | Role string `json:"role"` |
| 255 | Joined bool `json:"joined"` |
| 256 | } |
| 257 | |
| 258 | // people is base_people: every member, and whether each has signed in yet. |
| 259 | func (s *server) people(ctx context.Context, _ store.Member) (any, error) { |
| 260 | ms, err := store.Members(ctx, s.db) |
| 261 | if err != nil { |
| 262 | return nil, err |
| 263 | } |
| 264 | out := struct { |
| 265 | People []person `json:"people"` |
| 266 | }{[]person{}} |
| 267 | for _, m := range ms { |
| 268 | out.People = append(out.People, person{Name: m.Name, Email: m.Email, Role: m.Role, Joined: m.JoinedAt != nil}) |
| 269 | } |
| 270 | return out, nil |
| 271 | } |
| 272 | |
| 273 | // settings is base_settings: this Base, and the member asking. |
| 274 | func (s *server) settings(_ context.Context, me store.Member) (any, error) { |
| 275 | type you struct { |
| 276 | Name string `json:"name"` |
| 277 | Email string `json:"email"` |
| 278 | Role string `json:"role"` |
| 279 | } |
| 280 | return struct { |
| 281 | Name string `json:"name"` |
| 282 | Timezone string `json:"timezone"` |
| 283 | You you `json:"you"` |
| 284 | }{s.cfg.Name, s.cfg.Timezone.String(), you{me.Name, me.Email, me.Role}}, nil |
| 285 | } |
| 286 | |
| 287 | // Output schemas, built from these few parts. |
| 288 | var ( |
| 289 | str = map[string]any{"type": "string"} |
| 290 | boolean = map[string]any{"type": "boolean"} |
| 291 | ) |
| 292 | |
| 293 | // object is a closed object schema whose every property is required; kv |
| 294 | // alternates property names and their schemas. |
| 295 | func object(kv ...any) map[string]any { |
| 296 | props := map[string]any{} |
| 297 | var required []string |
| 298 | for i := 0; i < len(kv); i += 2 { |
| 299 | name := kv[i].(string) |
| 300 | props[name] = kv[i+1] |
| 301 | required = append(required, name) |
| 302 | } |
| 303 | return map[string]any{"type": "object", "additionalProperties": false, "required": required, "properties": props} |
| 304 | } |
| 305 | |
| 306 | // texts is an object of string properties. |
| 307 | func texts(names ...string) map[string]any { |
| 308 | kv := make([]any, 0, 2*len(names)) |
| 309 | for _, n := range names { |
| 310 | kv = append(kv, n, str) |
| 311 | } |
| 312 | return object(kv...) |
| 313 | } |
| 314 | |
| 315 | func list(items map[string]any) map[string]any { |
| 316 | return map[string]any{"type": "array", "items": items} |
| 317 | } |
| 318 | |
| 319 | func schema(v map[string]any) json.RawMessage { |
| 320 | b, err := json.Marshal(v) |
| 321 | if err != nil { |
| 322 | panic("operations: " + err.Error()) |
| 323 | } |
| 324 | return b |
| 325 | } |
| 326 | |