oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1package docs
2
3import (
4 "context"
5 "crypto/hmac"
6 "crypto/sha256"
7 "encoding/base64"
8 "encoding/hex"
9 "encoding/json"
10 "errors"
11 "strconv"
12 "time"
13 "unicode/utf8"
14
15 access "amadan.net/oficina/agent-access.git"
16 "amadan.net/oficina/home/handoff/seal"
17 "amadan.net/oficina/home/roster"
18 "github.com/carlosframework/docs/internal/core"
19 "github.com/google/uuid"
20 "gorm.io/gorm"
21)
22
23const agentResultLimit = 1 << 20
24
25type documentAgent struct {
26 store *Store
27 resolver identityResolver
28 list allowlist
29 origin, issuer, identityIssuer, team string
30 key []byte
31 notify func(int64, int64)
32}
33type agentBlock struct {
34 Type string `json:"type"`
35 Text string `json:"text"`
36 Level uint8 `json:"level,omitempty"`
37}
38type agentCreateInput struct {
39 Team string `json:"team"`
40 ClientID string `json:"client_id"`
41 Title string `json:"title"`
42 Blocks []agentBlock `json:"blocks"`
43}
44type agentDocument struct {
45 ID string `json:"id"`
46 Title string `json:"title"`
47 URL string `json:"url"`
48 UpdatedAt string `json:"updated_at"`
49}
50type agentBody struct {
51 agentDocument
52 Revision string `json:"body_revision"`
53 Text string `json:"text"`
54 Content json.RawMessage `json:"content"`
55}
56type agentReceipt struct {
57 Coordinate string `gorm:"primaryKey"`
58 Content string
59 DocumentID int64
60}
61type agentAttribution struct {
62 DocumentID int64 `gorm:"primaryKey"`
63 OperatorID int64
64 ClientSealed []byte
65}
66
67func (agentAttribution) TableName() string { return "docs_agent_attribution" }
68
69type agentCreated struct {
70 agentDocument
71 Revision string `json:"body_revision"`
72}
73
74func (agentReceipt) TableName() string { return "docs_agent_receipts" }
75
76func (a *documentAgent) digest(domain string, value any) string {
77 raw, _ := json.Marshal(value) // only fixed structs and string slices enter here
78 mac := hmac.New(sha256.New, a.key)
79 mac.Write([]byte("oficina/docs/agent/v1/" + domain + "\x00"))
80 mac.Write(raw)
81 return hex.EncodeToString(mac.Sum(nil))
82}
83func (a *documentAgent) bind(tx *gorm.DB) error {
84 want := a.digest("keycheck", []string{"immutable-authority", a.identityIssuer, a.issuer, a.team})
85 // This write reserves SQLite's writer before checking state or receipts.
86 if err := tx.Exec("INSERT INTO docs_agent_state(id,keycheck) SELECT 1,? WHERE NOT EXISTS(SELECT 1 FROM docs_agent_receipts) AND NOT EXISTS(SELECT 1 FROM docs_agent_attribution) AND NOT EXISTS(SELECT 1 FROM docs_agent_update_receipts) AND NOT EXISTS(SELECT 1 FROM docs_agent_update_attribution) ON CONFLICT(id) DO NOTHING", want).Error; err != nil {
87 return err
88 }
89 var got string
90 if err := tx.Raw("SELECT keycheck FROM docs_agent_state WHERE id=1").Scan(&got).Error; err != nil {
91 return err
92 }
93 if !hmac.Equal([]byte(got), []byte(want)) {
94 return access.Fail("unavailable", "Agent receipt authority requires an explicit migration.")
95 }
96 return nil
97}
98func agentFailure(err error) error {
99 if err == nil {
100 return nil
101 }
102 var failure access.Failure
103 if errors.As(err, &failure) {
104 return failure
105 }
106 if errors.Is(err, gorm.ErrRecordNotFound) || errors.Is(err, ErrNotWritable) {
107 return access.Fail("not_found", "This document is unavailable.")
108 }
109 if errors.Is(err, errIdentityRefused) || errors.Is(err, errTeamNotMember) {
110 return access.Fail("forbidden", "This identity is not admitted for that operation.")
111 }
112 return access.Fail("unavailable", "Document authority or storage is unavailable.")
113}
114func (a *documentAgent) prepare(ctx context.Context, p access.Principal, write bool) (context.Context, requestIdentity, error) {
115 return a.prepareMode(ctx, p, write, write)
116}
117
118func (a *documentAgent) prepareMode(ctx context.Context, p access.Principal, write, create bool) (context.Context, requestIdentity, error) {
119 scope := "docs:read"
120 if write {
121 scope = "docs:write"
122 }
123 if p.Client == "" || !p.Allows(a.team, scope) {
124 return ctx, requestIdentity{}, access.Fail("forbidden", "This connection does not allow that team and operation.")
125 }
126 id, err := a.resolver.resolveHome(ctx, p.Subject)
127 if err != nil {
128 return ctx, id, agentFailure(err)
129 }
130 if a.store.team == nil {
131 admitted, e := a.list.allows(actorAddress(id.Actor))
132 if e != nil {
133 return ctx, id, agentFailure(e)
134 }
135 if !admitted || create && !a.list.configured(actorAddress(id.Actor)) {
136 return ctx, id, agentFailure(errIdentityRefused)
137 }
138 }
139 if existing, ok := ctx.Value(accessContextKey{}).(*requestAccess); ok && existing != nil {
140 if existing.runtime != a.store.team || !sameActor(existing.actor, id.Actor) {
141 return ctx, id, agentFailure(errIdentityRefused)
142 }
143 } else {
144 guard := &requestAccess{actor: id.Actor, responseStore: a.store, responseDocs: map[int64]permission{}}
145 if a.store.team != nil {
146 guard = a.store.team.resolveAccess(ctx, id)
147 guard.responseStore = a.store
148 guard.responseDocs = map[int64]permission{}
149 }
150 ctx = withAccess(ctx, guard)
151 }
152 if create {
153 if e := a.store.requireMember(ctx, id.Actor); e != nil {
154 return ctx, id, agentFailure(e)
155 }
156 }
157 return ctx, id, nil
158}
159func (a *documentAgent) remember(ctx context.Context, doc *Document) {
160 if guard, ok := ctx.Value(accessContextKey{}).(*requestAccess); ok && guard != nil {
161 guard.responseDocs[doc.ID] = permissionRead
162 }
163}
164func (a *documentAgent) summary(doc *Document) agentDocument {
165 return agentDocument{doc.Sqid, doc.Title, a.origin + "/d/" + doc.Sqid, doc.UpdatedAt.UTC().Format(time.RFC3339Nano)}
166}
167func agentBounded(value any) (any, error) {
168 body, err := json.Marshal(value)
169 if err != nil {
170 return nil, agentFailure(err)
171 }
172 if len(body) > agentResultLimit {
173 return nil, access.Fail("too_large", "The document result exceeds 1 MiB.")
174 }
175 return value, nil
176}
177func (a *documentAgent) body(ctx context.Context, actor Actor, sqid string) (any, error) {
178 doc, err := a.store.GetFor(ctx, actor, sqid)
179 if err != nil {
180 return nil, agentFailure(err)
181 }
182 h, seq, _, err := a.store.replay(ctx, doc)
183 if err != nil {
184 return nil, agentFailure(err)
185 }
186 defer h.Close(ctx)
187 text, err := h.Text(ctx)
188 if err != nil {
189 return nil, agentFailure(err)
190 }
191 content, err := h.JSON(ctx)
192 if err != nil {
193 return nil, agentFailure(err)
194 }
195 a.remember(ctx, doc)
196 return agentBounded(agentBody{a.summary(doc), strconv.FormatInt(seq, 10), text, json.RawMessage(content)})
197}
198
199type agentCursor struct {
200 At string `json:"at"`
201 ID string `json:"id"`
202}
203
204func (a *documentAgent) documents(ctx context.Context, actor Actor, limit int, cursor string) (any, error) {
205 if a.store.team != nil {
206 guard, ok := a.store.access(ctx, actor)
207 if !ok || guard.state() == roster.Unknown {
208 return nil, agentFailure(errTeamUnavailable)
209 }
210 guard.agentList = true
211 }
212 if limit == 0 {
213 limit = 20
214 }
215 if limit < 1 || limit > 100 {
216 return nil, access.Fail("invalid", "Choose a page size from 1 to 100.")
217 }
218 q := a.store.permissionScope(ctx, a.store.db.WithContext(ctx), actor, permissionRead).Where("documents.deleted_at IS NULL")
219 if cursor != "" {
220 var c agentCursor
221 raw, err := base64.RawURLEncoding.Strict().DecodeString(cursor)
222 if err != nil || len(raw) > 256 || base64.RawURLEncoding.EncodeToString(raw) != cursor || access.UniqueJSON(raw) != nil || json.Unmarshal(raw, &c) != nil {
223 return nil, access.Fail("invalid", "Invalid document cursor.")
224 }
225 at, e1 := time.Parse(time.RFC3339Nano, c.At)
226 id, e2 := strconv.ParseInt(c.ID, 10, 64)
227 if e1 != nil || e2 != nil || id <= 0 || strconv.FormatInt(id, 10) != c.ID || at.UTC().Format(time.RFC3339Nano) != c.At {
228 return nil, access.Fail("invalid", "Invalid document cursor.")
229 }
230 q = q.Where("(documents.updated_at < ? OR (documents.updated_at = ? AND documents.id < ?))", at, at, id)
231 }
232 var rows []*Document
233 if err := q.Order("documents.updated_at DESC, documents.id DESC").Limit(limit + 1).Find(&rows).Error; err != nil {
234 return nil, agentFailure(err)
235 }
236 next := ""
237 if len(rows) > limit {
238 rows = rows[:limit]
239 last := rows[len(rows)-1]
240 raw, _ := json.Marshal(agentCursor{last.UpdatedAt.UTC().Format(time.RFC3339Nano), strconv.FormatInt(last.ID, 10)})
241 next = base64.RawURLEncoding.EncodeToString(raw)
242 }
243 items := make([]agentDocument, 0, len(rows))
244 for _, doc := range rows {
245 a.remember(ctx, doc)
246 items = append(items, a.summary(doc))
247 }
248 return agentBounded(struct {
249 Documents []agentDocument `json:"documents"`
250 Next string `json:"next_cursor"`
251 }{items, next})
252}
253
254// checkCreator runs on the reserved writer. It reads the same identity tables as
255// the resolver without opening a second SQL connection inside the transaction.
256func (a *documentAgent) checkCreator(ctx context.Context, tx *gorm.DB, p access.Principal, id requestIdentity) error {
257 guard, ok := ctx.Value(accessContextKey{}).(*requestAccess)
258 if !ok || guard == nil || guard.delegationCheck == nil {
259 return errIdentityRefused
260 }
261 if err := guard.delegationCheck(ctx); err != nil {
262 return err
263 }
264
265 current, err := a.resolver.resolveHomeOn(ctx, tx.Statement.ConnPool, p.Subject)
266 if err != nil {
267 return err
268 }
269 if !sameActor(current.Actor, id.Actor) {
270 return errIdentityRefused
271 }
272 if a.store.team == nil && !a.list.configured(actorAddress(id.Actor)) {
273 return errIdentityRefused
274 }
275 return a.store.requireMember(ctx, id.Actor)
276}
277func (a *documentAgent) create(ctx context.Context, p access.Principal, id requestIdentity, input agentCreateInput) (any, error) {
278 u, err := uuid.Parse(input.ClientID)
279 // The title is made one line (handlers.go's cleanTitle) before it is
280 // checked or stored; the retry digest below keeps the title as sent.
281 title := cleanTitle(input.Title)
282 if err != nil || u == uuid.Nil || u.String() != input.ClientID || !utf8.ValidString(input.Title) || title == "" || len(input.Title) > 512 || len(input.Blocks) > 200 {
283 return nil, access.Fail("invalid", "Invalid title, client UUID or initial content.")
284 }
285 blocks := make([]core.InitialBlock, len(input.Blocks))
286 total := 0
287 for i, b := range input.Blocks {
288 total += len(b.Text)
289 if !utf8.ValidString(b.Text) || total > 128<<10 || b.Type != "paragraph" && b.Type != "heading" || b.Type == "paragraph" && b.Level != 0 || b.Type == "heading" && (b.Level < 1 || b.Level > 6) {
290 return nil, access.Fail("invalid", "Invalid initial content.")
291 }
292 blocks[i] = core.InitialBlock{Text: b.Text, Level: b.Level}
293 }
294 if a.store.content == nil {
295 return nil, access.Fail("unavailable", "Activate sealed document storage before agent writes.")
296 }
297 coordinate := a.digest("coordinate", []string{a.identityIssuer, a.issuer, p.Subject, p.Client, a.team, input.ClientID})
298 payload := a.digest("content", struct {
299 Title string
300 Blocks []agentBlock
301 }{input.Title, input.Blocks})
302 var doc Document
303 err = a.store.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
304 if e := a.bind(tx); e != nil {
305 return e
306 }
307 if e := a.checkCreator(ctx, tx, p, id); e != nil {
308 return e
309 }
310 var receipt agentReceipt
311 e := tx.Where("coordinate=?", coordinate).First(&receipt).Error
312 if e == nil {
313 if receipt.Content != payload {
314 return access.Fail("conflict", "This client UUID already names different initial content.")
315 }
316 if e = tx.Where("id=? AND deleted_at IS NULL", receipt.DocumentID).First(&doc).Error; e != nil {
317 return e
318 }
319 if err := a.store.checkPermission(ctx, tx, id.Actor, doc.ID, permissionRead); err != nil {
320 return err
321 }
322 return a.checkCreator(ctx, tx, p, id)
323 }
324 if !errors.Is(e, gorm.ErrRecordNotFound) {
325 return e
326 }
327 store := a.store.boundTo(tx)
328 created, e := store.CreateDraft(ctx, id.Actor.PersonID, title, "")
329 if e != nil {
330 return e
331 }
332 update, e := store.core.InitialUpdate(ctx, created.GUID, created.ClientID, blocks)
333 if e != nil {
334 return e
335 }
336 if _, e = store.ApplyUpdate(ctx, created, id.Actor, update); e != nil {
337 return e
338 }
339 sealer, e := seal.New(a.key, "oficina/docs")
340 if e != nil {
341 return e
342 }
343 client, e := sealer.Seal("agent-client/"+created.GUID, []byte(p.Client))
344 if e != nil {
345 return e
346 }
347 if e = tx.Create(&agentAttribution{created.ID, id.Actor.PersonID, client}).Error; e != nil {
348 return e
349 }
350 receipt = agentReceipt{coordinate, payload, created.ID}
351 if e = tx.Create(&receipt).Error; e != nil {
352 return e
353 }
354 doc = *created
355 return a.checkCreator(ctx, tx, p, id)
356 })
357 if err != nil {
358 return nil, agentFailure(err)
359 }
360 // A retry reads the current body, including intervening browser edits.
361 current, e := a.store.GetFor(ctx, id.Actor, doc.Sqid)
362 if e != nil {
363 return nil, agentFailure(e)
364 }
365 h, seq, _, e := a.store.replay(ctx, current)
366 if e != nil {
367 return nil, agentFailure(e)
368 }
369 defer h.Close(ctx)
370 a.remember(ctx, current)
371 return agentBounded(agentCreated{a.summary(current), strconv.FormatInt(seq, 10)})
372}
373