oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package equipo
2
3import (
4 "context"
5 "encoding/base64"
6 "encoding/json"
7 "errors"
8 "io"
9 "math"
10 "mime"
11 "net/http"
12 "strings"
13
14 access "amadan.net/oficina/agent-access.git"
15 "amadan.net/oficina/equipo/internal/equipo/chat"
16 "amadan.net/oficina/equipo/internal/equipo/oficinaid"
17 "amadan.net/oficina/equipo/internal/equipo/personapi"
18 "amadan.net/oficina/home/connect"
19 "github.com/sqids/sqids-go"
20 "gorm.io/gorm"
21 "gorm.io/gorm/logger"
22 "gorm.io/plugin/dbresolver"
23)
24
25func validatedAgentConfig(cfg Config) (*access.RemoteVerifier, error) {
26 if cfg.AgentIssuer == "" && cfg.AgentTeam == "" {
27 return nil, nil
28 }
29 //lint:ignore ST1005 User-facing errors preserve the sentences in copy.go.
30 fail := func() (*access.RemoteVerifier, error) { return nil, errors.New(copyAgentConfig) }
31 if cfg.Home == nil || cfg.AgentIssuer == "" || len(cfg.AgentTeam) == 0 || len(cfg.AgentTeam) > 64 {
32 return fail()
33 }
34 codec, err := sqids.New()
35 if err != nil {
36 return fail()
37 }
38 ids := codec.Decode(cfg.AgentTeam)
39 if len(ids) != 1 || ids[0] == 0 || ids[0] > math.MaxInt64 {
40 return fail()
41 }
42 canonical, err := codec.Encode(ids)
43 if err != nil || canonical != cfg.AgentTeam {
44 return fail()
45 }
46 // Revalidate even hand-built Config values at router construction.
47 keys := map[string]string{}
48 for k, v := range cfg.Home.Keys {
49 keys[k] = base64.StdEncoding.EncodeToString(v)
50 }
51 manifest, err := json.Marshal(keys)
52 if err != nil {
53 return fail()
54 }
55 _, err = connect.DecodeCredentials(&connect.Credentials{Issuer: cfg.Home.Issuer, ConsumerID: cfg.Home.ConsumerID, KeysBase64: base64.StdEncoding.EncodeToString(manifest), DEKBase64: base64.StdEncoding.EncodeToString(cfg.Home.DEK)}, cfg.Origin)
56 if err != nil {
57 return fail()
58 }
59 verifier, err := access.NewRemoteVerifier(cfg.AgentIssuer, cfg.Origin+"/api/v1", cfg.Home.Issuer)
60 if err != nil {
61 return fail()
62 }
63 return verifier, nil
64}
65
66type equipoAgent struct {
67 store *Store
68 home *oficinaid.Store
69 team string
70}
71type agentIdentityKey struct{}
72type agentIdentity struct {
73 home *oficinaid.Store
74 subject, address string
75}
76
77// Re-resolve the authenticated Home link inside the same transaction as
78// every application read. An unlink or replaced local account denies access.
79func (id agentIdentity) current(ctx context.Context, tx *gorm.DB) error {
80 _, address, err := id.home.Links.ResolveOn(ctx, tx.Statement.ConnPool, id.home.Config.Issuer, id.subject)
81 if err != nil || address != id.address {
82 return ErrForbidden
83 }
84 return nil
85}
86func (a *equipoAgent) prepare(ctx context.Context, p access.Principal) (context.Context, string, error) {
87 var address string
88 var epoch int64
89 err := a.store.db.G.Session(&gorm.Session{Logger: logger.Discard}).WithContext(ctx).Clauses(dbresolver.Write).Transaction(func(tx *gorm.DB) error {
90 _, v, e := a.home.Links.ResolveOn(ctx, tx.Statement.ConnPool, a.home.Config.Issuer, p.Subject)
91 if e != nil {
92 return ErrForbidden
93 }
94 address = v
95 m, e := currentRunnerMember(tx, address)
96 if e != nil {
97 return e
98 }
99 epoch = m.SessionEpoch
100 return nil
101 })
102 if err != nil {
103 return ctx, "", agentFailure(err)
104 }
105 ctx = context.WithValue(ctx, agentIdentityKey{}, agentIdentity{a.home, p.Subject, address})
106 return personapi.WithVerifiedPrincipal(ctx, personapi.PersonPrincipal{Address: address, SessionEpoch: epoch}), address, nil
107}
108
109const agentResultLimit = 1 << 20
110const agentItemSchema = `{"type":"object","required":["id","title","revision"],"properties":{"id":{"type":"string"},"title":{"type":"string"},"revision":{"type":"integer"}},"additionalProperties":true}`
111const agentListSchema = `{"type":"object","required":["items","truncated"],"additionalProperties":false,"properties":{"items":{"type":"array","maxItems":100,"items":` + agentItemSchema + `},"truncated":{"type":"boolean"}}}`
112
113type agentInput struct {
114 Team string `json:"team"`
115 ID string `json:"id"`
116 Limit int `json:"limit"`
117}
118type agentPage[T any] struct {
119 Items []T `json:"items"`
120 Truncated bool `json:"truncated"`
121}
122
123func agentBound[T any](items []T, limit int, sourceLimited bool) agentPage[T] {
124 if limit == 0 {
125 limit = 100
126 }
127 truncated := len(items) > limit || sourceLimited
128 if len(items) > limit {
129 items = items[:limit]
130 }
131 if items == nil {
132 items = []T{}
133 }
134 return agentPage[T]{items, truncated}
135}
136func (a *equipoAgent) registry() (*access.Registry, error) {
137 var ops []access.Operation
138 for _, name := range []string{"equipo_projects_list", "equipo_tasks_list", "equipo_task_get", "equipo_needs_you"} {
139 props := `,"limit":{"type":"integer","minimum":1,"maximum":100}`
140 required := `"team"`
141 output := agentListSchema
142 if name == "equipo_task_get" {
143 props = `,"id":{"type":"string","minLength":1,"maxLength":128}`
144 required += `,"id"`
145 output = `{"type":"object","required":["task"],"additionalProperties":false,"properties":{"task":` + agentItemSchema + `}}`
146 }
147 ops = append(ops, access.Operation{Name: name, Description: copyText("agent." + name), Scope: "equipo:read", ReadOnly: true, Idempotent: true,
148 Input: json.RawMessage(`{"type":"object","additionalProperties":false,"required":[` + required + `],"properties":{"team":{"type":"string","minLength":1,"maxLength":64}` + props + `}}`), Output: json.RawMessage(output),
149 Available: func(p access.Principal) bool { return p.Allows(a.team, "equipo:read") },
150 Invoke: func(ctx context.Context, p access.Principal, raw json.RawMessage) (any, error) {
151 var in agentInput
152 if err := json.Unmarshal(raw, &in); err != nil {
153 return nil, access.Fail("invalid", copyAgentInvalid)
154 }
155 if in.Team != a.team {
156 return nil, access.Fail("forbidden", copyAgentForbidden)
157 }
158 ctx, person, err := a.prepare(ctx, p)
159 if err != nil {
160 return nil, err
161 }
162 result, err := a.read(ctx, person, name, in)
163 if err != nil {
164 return nil, agentFailure(err)
165 }
166 body, err := json.Marshal(result)
167 if err != nil {
168 return nil, err
169 }
170 if len(body) > agentResultLimit {
171 return nil, access.Fail("too_large", copyAgentTooLarge)
172 }
173 return result, nil
174 },
175 })
176 }
177 return access.NewRegistry(ops...)
178}
179func (a *equipoAgent) read(ctx context.Context, person, name string, in agentInput) (any, error) {
180 ctx = chat.WithPrivateReads(ctx)
181 c := a.store.Chat()
182 switch name {
183 case "equipo_projects_list":
184 v, e := c.Projects(ctx, person)
185 return agentBound(v.Items, in.Limit, false), e
186 case "equipo_tasks_list":
187 v, capped, e := c.TasksWithSourceCap(ctx, person)
188 return agentBound(v.Items, in.Limit, capped), e
189 case "equipo_needs_you":
190 v, e := c.NeedsYou(ctx, person)
191 return agentBound(v.Items, in.Limit, true), e
192 case "equipo_task_get":
193 v, e := c.Task(ctx, person, in.ID)
194 return map[string]any{"task": v}, e
195 }
196 return nil, ErrNotFound
197}
198func agentFailure(err error) error {
199 switch {
200 case errors.Is(err, ErrForbidden), errors.Is(err, chat.ErrForbidden):
201 return access.Fail("forbidden", copyAgentForbidden)
202 case errors.Is(err, ErrNotFound), errors.Is(err, chat.ErrNotFound), errors.Is(err, gorm.ErrRecordNotFound):
203 return access.Fail("not_found", copyAgentNotFound)
204 default:
205 return access.Fail("unavailable", copyAgentUnavailable)
206 }
207}
208func agentWriteFailure(w http.ResponseWriter, err error) {
209 f := access.SafeFailure(err)
210 status := map[string]int{"unauthenticated": 401, "forbidden": 403, "not_found": 404, "invalid": 422, "too_large": 413, "unsupported_media_type": 415, "unavailable": 503}[f.Code]
211 if status == 0 {
212 status = 500
213 }
214 if status == 401 {
215 w.Header().Set("WWW-Authenticate", "Bearer")
216 }
217 w.Header().Set("Content-Type", "application/json")
218 w.WriteHeader(status)
219 _ = json.NewEncoder(w).Encode(map[string]any{"error": f})
220}
221func newEquipoAgent(store *Store, cfg Config, home *oficinaid.Store, verifier access.Verifier) (http.Handler, error) {
222 a := &equipoAgent{store, home, cfg.AgentTeam}
223 registry, err := a.registry()
224 if err != nil {
225 return nil, err
226 }
227 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
228 w.Header().Set("Cache-Control", "no-store")
229 parts := strings.Fields(r.Header.Get("Authorization"))
230 if len(r.Header.Values("Authorization")) != 1 || len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
231 agentWriteFailure(w, access.Fail("unauthenticated", copyAgentUnauthenticated))
232 return
233 }
234 p, err := verifier.Verify(r.Context(), parts[1])
235 if err != nil {
236 agentWriteFailure(w, err)
237 return
238 }
239 if p.Subject == "" || p.Grant == "" {
240 agentWriteFailure(w, access.Fail("unauthenticated", copyAgentUnauthenticated))
241 return
242 }
243 ctx, _, err := a.prepare(r.Context(), p)
244 if err != nil {
245 agentWriteFailure(w, err)
246 return
247 }
248 var result any
249 if r.Method == "GET" && r.URL.Path == "/api/v1/operations" {
250 result = map[string]any{"operations": registry.List(p)}
251 } else {
252 name := strings.TrimPrefix(r.URL.Path, "/api/v1/operations/")
253 if r.Method != "POST" || !strings.HasPrefix(r.URL.Path, "/api/v1/operations/") || strings.Contains(name, "/") {
254 agentWriteFailure(w, access.Fail("not_found", copyAgentNotFound))
255 return
256 }
257 media, _, e := mime.ParseMediaType(r.Header.Get("Content-Type"))
258 if e != nil || media != "application/json" {
259 agentWriteFailure(w, access.Fail("unsupported_media_type", copyAgentMedia))
260 return
261 }
262 raw, e := io.ReadAll(io.LimitReader(r.Body, access.MaxPayload+1))
263 if e != nil {
264 agentWriteFailure(w, access.Fail("invalid", copyAgentInvalid))
265 return
266 }
267 result, err = registry.Call(ctx, p, name, raw)
268 if err != nil {
269 agentWriteFailure(w, err)
270 return
271 }
272 }
273 w.Header().Set("Content-Type", "application/json")
274 _ = json.NewEncoder(w).Encode(result)
275 }), nil
276}
277func agentRoutes(handler http.Handler) func(http.Handler) http.Handler {
278 return func(next http.Handler) http.Handler {
279 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
280 if r.URL.Path == "/api/v1/operations" || strings.HasPrefix(r.URL.Path, "/api/v1/operations/") {
281 handler.ServeHTTP(w, r)
282 return
283 }
284 next.ServeHTTP(w, r)
285 })
286 }
287}
288