| 1 | package personapi |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/rastrillo/rastrillo/carlos" |
| 5 | "amadan.net/rastrillo/rastrillo/clientip" |
| 6 | "context" |
| 7 | "crypto/rand" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "mime" |
| 11 | "net/http" |
| 12 | "strconv" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/equipo/kernel" |
| 15 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 16 | "github.com/go-chi/chi/v5" |
| 17 | ) |
| 18 | |
| 19 | type Handler struct { |
| 20 | NotificationActions func() bool |
| 21 | App Application |
| 22 | CursorCodec kernel.CursorCodec |
| 23 | Authenticate func(*http.Request) (PersonPrincipal, error) |
| 24 | AuthenticateRoute func(*http.Request, Route) (PersonPrincipal, error) |
| 25 | Invalid, Forbidden, NotFound, Conflict, Unavailable, CursorExpired error |
| 26 | } |
| 27 | type Route struct { |
| 28 | Method, Path, Operation string |
| 29 | Update bool |
| 30 | Input func() any |
| 31 | } |
| 32 | |
| 33 | var Routes = []Route{ |
| 34 | {"GET", "/me", "me", false, nil}, {"GET", "/capabilities", "capabilities", false, nil}, |
| 35 | {"GET", "/me/settings", "settings", false, nil}, {"PATCH", "/me/settings", "settings", true, func() any { return &SettingsInput{} }}, |
| 36 | {"GET", "/people", "people", false, nil}, |
| 37 | {"GET", "/conversation", "conversation", false, nil}, {"POST", "/conversation/messages", "send", false, func() any { return &MessageInput{} }}, |
| 38 | {"GET", "/conversation/cards", "cards", false, nil}, {"GET", "/cards/{id}", "card", false, nil}, |
| 39 | {"GET", "/tasks", "tasks", false, nil}, {"GET", "/tasks/{id}", "task", false, nil}, {"POST", "/tasks", "propose", false, func() any { return &PlanInput{} }}, |
| 40 | {"POST", "/tasks/{id}/cancel", "cancel", true, func() any { return &struct{}{} }}, |
| 41 | {"GET", "/tasks/{id}/thread", "thread", false, nil}, {"POST", "/tasks/{id}/thread/messages", "send_thread", false, func() any { return &MessageInput{} }}, |
| 42 | {"POST", "/conversation/messages/{id}/route", "route", true, func() any { return &RouteInput{} }}, |
| 43 | {"GET", "/tasks/{id}/plan", "plan", false, nil}, {"PATCH", "/tasks/{id}/plan", "edit_plan", true, func() any { return &PlanInput{} }}, |
| 44 | {"POST", "/tasks/{id}/plan/approve", "approve_plan", true, func() any { return &struct{}{} }}, |
| 45 | {"POST", "/tasks/{id}/project", "project", true, func() any { return &ProjectInput{} }}, |
| 46 | {"GET", "/questions/{id}", "question", false, nil}, {"POST", "/questions/{id}/answer", "answer", true, func() any { return &AnswerInput{} }}, |
| 47 | {"POST", "/tasks/{id}/rendered-approval", "rendered", true, func() any { return &RenderedInput{} }}, |
| 48 | {"POST", "/tasks/{id}/acknowledge-merge", "merge", true, func() any { return &MergeInput{} }}, |
| 49 | {"GET", "/journey", "journey", false, nil}, {"GET", "/needs-you", "needs_you", false, nil}, |
| 50 | {"GET", "/preferences", "preferences", false, nil}, {"POST", "/preferences", "preference", false, func() any { return &PreferenceInput{} }}, |
| 51 | {"PATCH", "/preferences/{id}", "preference", true, func() any { return &PreferenceInput{} }}, {"DELETE", "/preferences/{id}", "delete_preference", true, func() any { return &struct{}{} }}, |
| 52 | {"GET", "/coordinator", "coordinator", false, nil}, {"PATCH", "/coordinator", "binding", true, func() any { return &BindingInput{} }}, |
| 53 | {"POST", "/coordinator/reset", "reset", true, func() any { return &struct{}{} }}, {"POST", "/coordinator/retry", "retry", true, func() any { return &RetryInput{} }}, |
| 54 | {"PATCH", "/coordinator/limits", "limits", true, func() any { return &LimitsInput{} }}, |
| 55 | } |
| 56 | |
| 57 | func (h *Handler) Router() chi.Router { |
| 58 | r := chi.NewRouter() |
| 59 | for _, route := range Routes { |
| 60 | r.Method(route.Method, route.Path, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 61 | w.Header().Set("Cache-Control", "no-store") |
| 62 | req = req.WithContext(context.WithValue(req.Context(), errorScopeKey{}, route.Operation)) |
| 63 | p, err := h.AuthenticateRoute(req, route) |
| 64 | if err != nil { |
| 65 | h.Failure(w, req, err) |
| 66 | return |
| 67 | } |
| 68 | // Match Rastrillo auth: trust the CARLOS edge, and no headers off CARLOS. |
| 69 | hops := 0 |
| 70 | if carlos.Running() { |
| 71 | hops = clientip.DefaultHops |
| 72 | } |
| 73 | ctx := WithDeviceSource(req.Context(), clientip.From(req, hops)) |
| 74 | if !p.Pending { |
| 75 | ctx = context.WithValue(ctx, principalKey{}, p) |
| 76 | } |
| 77 | // Pending recipients get only this operation's actor, without member authority. |
| 78 | ctx = context.WithValue(ctx, actorKey{}, p.Address) |
| 79 | h.serve(route).ServeHTTP(w, req.WithContext(ctx)) |
| 80 | })) |
| 81 | } |
| 82 | r.NotFound(func(w http.ResponseWriter, r *http.Request) { |
| 83 | if _, err := h.Authenticate(r); err != nil { |
| 84 | h.Failure(w, r, err) |
| 85 | return |
| 86 | } |
| 87 | WriteError(w, r, 404, "not_found", nil) |
| 88 | }) |
| 89 | r.MethodNotAllowed(func(w http.ResponseWriter, r *http.Request) { |
| 90 | if _, err := h.Authenticate(r); err != nil { |
| 91 | h.Failure(w, r, err) |
| 92 | return |
| 93 | } |
| 94 | WriteError(w, r, 405, "method_not_allowed", nil) |
| 95 | }) |
| 96 | return r |
| 97 | } |
| 98 | func (h *Handler) serve(route Route) http.Handler { |
| 99 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 100 | address, _ := r.Context().Value(actorKey{}).(string) |
| 101 | a := kernel.Actor{Address: address} |
| 102 | id := chi.URLParam(r, "id") |
| 103 | if v := chi.URLParam(r, "address"); v != "" { |
| 104 | id = v |
| 105 | } |
| 106 | if v := chi.URLParam(r, "key"); v != "" { |
| 107 | id += "/" + v |
| 108 | } |
| 109 | var out Result |
| 110 | var err error |
| 111 | var input any |
| 112 | if route.Input == nil { |
| 113 | cursor, limit, e := ListQuery(r) |
| 114 | if e != nil { |
| 115 | WriteError(w, r, 422, "invalid_input", nil) |
| 116 | return |
| 117 | } |
| 118 | out, err = h.read(r.Context(), a, route.Operation, id, cursor, limit) |
| 119 | } else { |
| 120 | if len(r.URL.Query()) != 0 { |
| 121 | WriteError(w, r, 422, "invalid_input", nil) |
| 122 | return |
| 123 | } |
| 124 | m, status := Mutation(r, route.Update) |
| 125 | if route.Operation == "native_device" && len(r.Header.Values("Idempotency-Key")) == 0 { |
| 126 | m = kernel.Mutation{} |
| 127 | status = 0 |
| 128 | } |
| 129 | if status != 0 { |
| 130 | code := "invalid_input" |
| 131 | if status == 428 { |
| 132 | code = "precondition_required" |
| 133 | } |
| 134 | WriteError(w, r, status, code, nil) |
| 135 | return |
| 136 | } |
| 137 | input = route.Input() |
| 138 | media, _, e := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| 139 | if e != nil || media != "application/json" || Decode(r.Body, input) != nil { |
| 140 | WriteError(w, r, 422, "invalid_input", nil) |
| 141 | return |
| 142 | } |
| 143 | request := Request{Principal: a.Address, Operation: route.Operation, Resource: id, RequestID: m.RequestID} |
| 144 | if route.Operation == "begin_device" { |
| 145 | request.Principal = input.(*BeginDeviceInput).PublicKey |
| 146 | } |
| 147 | if route.Operation == "exchange_device" { |
| 148 | request.Resource = input.(*PersonDeviceProof).ID |
| 149 | } |
| 150 | request.InputHash, err = CanonicalHash(struct { |
| 151 | Input any |
| 152 | Revision int64 |
| 153 | }{input, m.Revision}) |
| 154 | if err == nil { |
| 155 | out, err = h.mutate(WithRequest(r.Context(), request), a, route.Operation, id, input, m) |
| 156 | } |
| 157 | } |
| 158 | if err != nil { |
| 159 | if h.revisionConflict(err) { |
| 160 | if _, authErr := h.AuthenticateRoute(r, route); authErr != nil { |
| 161 | h.Failure(w, r, authErr) |
| 162 | return |
| 163 | } |
| 164 | current, readErr := h.currentRevision(r.Context(), a, route.Operation, id, input) |
| 165 | if readErr != nil { |
| 166 | h.Failure(w, r, readErr) |
| 167 | return |
| 168 | } |
| 169 | WriteError(w, r, 409, "revision_conflict", current) |
| 170 | } else { |
| 171 | h.Failure(w, r, err) |
| 172 | } |
| 173 | return |
| 174 | } |
| 175 | w.Header().Set("ETag", `"`+strconv.FormatInt(out.Revision, 10)+`"`) |
| 176 | w.Header().Set("Content-Type", "application/json") |
| 177 | _ = json.NewEncoder(w).Encode(out.Value) |
| 178 | }) |
| 179 | } |
| 180 | func WriteError(w http.ResponseWriter, r *http.Request, status int, code string, current *int64) { |
| 181 | w.Header().Set("Cache-Control", "no-store") |
| 182 | w.Header().Set("Content-Type", "application/json") |
| 183 | request := r.Header.Get("Idempotency-Key") |
| 184 | if request == "" || len(request) > 256 { |
| 185 | request = rand.Text() |
| 186 | } |
| 187 | w.WriteHeader(status) |
| 188 | _ = json.NewEncoder(w).Encode(Error{Code: code, CopyKey: errorCopyKey(r, code), RequestID: request, CurrentRevision: current}) |
| 189 | } |
| 190 | |
| 191 | var ErrUnauthenticated = errors.New("api.unauthenticated") |
| 192 | |
| 193 | func (h *Handler) Failure(w http.ResponseWriter, r *http.Request, err error) { |
| 194 | code, status := "unavailable", 503 |
| 195 | switch { |
| 196 | case errors.Is(err, ErrSubscriptionExpired): |
| 197 | code, status = "subscription_expired", 410 |
| 198 | case errors.Is(err, ErrDeviceExpired): |
| 199 | code, status = "device_expired", 410 |
| 200 | case errors.Is(err, ErrSlowDown): |
| 201 | code, status = "slow_down", 429 |
| 202 | case errors.Is(err, ErrPending): |
| 203 | code, status = "authorization_pending", 409 |
| 204 | case errors.Is(err, ErrUnauthenticated): |
| 205 | code, status = "unauthenticated", 401 |
| 206 | case errors.Is(err, h.Invalid), errors.Is(err, team.ErrInvalid): |
| 207 | code, status = "invalid_input", 422 |
| 208 | case errors.Is(err, h.Forbidden), errors.Is(err, team.ErrScope), errors.Is(err, team.ErrGrantRevoked): |
| 209 | code, status = "forbidden", 403 |
| 210 | case errors.Is(err, h.NotFound): |
| 211 | code, status = "not_found", 404 |
| 212 | case h.revisionConflict(err): |
| 213 | code, status = "revision_conflict", 409 |
| 214 | case errors.Is(err, h.CursorExpired): |
| 215 | code, status = "cursor_expired", 410 |
| 216 | } |
| 217 | WriteError(w, r, status, code, nil) |
| 218 | } |
| 219 | |
| 220 | type principalKey struct{} |
| 221 | type actorKey struct{} |
| 222 | |
| 223 | func (h *Handler) revisionConflict(err error) bool { |
| 224 | return errors.Is(err, h.Conflict) || errors.Is(err, team.ErrRevision) || errors.Is(err, team.ErrConflict) || errors.Is(err, team.ErrState) |
| 225 | } |
| 226 | func (h *Handler) currentRevision(ctx context.Context, a kernel.Actor, op, id string, input any) (*int64, error) { |
| 227 | switch op { |
| 228 | case "subscribe_notifications": |
| 229 | n := int64(0) |
| 230 | return &n, nil |
| 231 | case "unsubscribe_notifications", "ack_notification": |
| 232 | sub, err := h.App.NotificationSubscription(ctx, a, id) |
| 233 | return &sub.Revision, err |
| 234 | case "edit_plan", "approve_plan", "project": |
| 235 | op = "plan" |
| 236 | case "rendered", "merge", "cancel": |
| 237 | op = "task" |
| 238 | case "answer": |
| 239 | op = "question" |
| 240 | case "reset", "binding": |
| 241 | op = "coordinator" |
| 242 | case "preference", "delete_preference": |
| 243 | op = "preference" |
| 244 | case "route": |
| 245 | op = "message" |
| 246 | case "retry": |
| 247 | op, id = "turn", input.(*RetryInput).TurnID |
| 248 | case "limits": |
| 249 | id = input.(*LimitsInput).Person |
| 250 | case "send": |
| 251 | op = "conversation" |
| 252 | case "send_thread": |
| 253 | op = "thread" |
| 254 | case "propose": |
| 255 | op = "conversation" |
| 256 | case "settings": |
| 257 | default: |
| 258 | return h.extendedRevision(ctx, a, op, id, input) |
| 259 | } |
| 260 | out, err := h.read(ctx, a, op, id, "", 50) |
| 261 | if err != nil { |
| 262 | return nil, err |
| 263 | } |
| 264 | return &out.Revision, nil |
| 265 | } |
| 266 | |
| 267 | type errorScopeKey struct{} |
| 268 | |
| 269 | func errorCopyKey(r *http.Request, code string) string { |
| 270 | op, _ := r.Context().Value(errorScopeKey{}).(string) |
| 271 | if code == "subscription_expired" || op == "notifications" && code == "cursor_expired" { |
| 272 | return "notifications." + code |
| 273 | } |
| 274 | switch code { |
| 275 | case "invalid_input", "forbidden", "revision_conflict": |
| 276 | switch op { |
| 277 | case "roster", "set_roster": |
| 278 | return "roster." + code |
| 279 | case "budgets", "save_budgets": |
| 280 | return "budgets." + code |
| 281 | } |
| 282 | } |
| 283 | return "api." + code |
| 284 | } |
| 285 | |