| 1 | package docs |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "math" |
| 7 | mrand "math/rand/v2" |
| 8 | "strconv" |
| 9 | "unicode/utf8" |
| 10 | |
| 11 | access "amadan.net/oficina/agent-access.git" |
| 12 | "amadan.net/oficina/home/handoff/seal" |
| 13 | "github.com/carlosframework/docs/internal/core" |
| 14 | "github.com/google/uuid" |
| 15 | "gorm.io/gorm" |
| 16 | ) |
| 17 | |
| 18 | type agentEdit struct { |
| 19 | Index uint32 `json:"index"` |
| 20 | Delete uint32 `json:"delete_count"` |
| 21 | Blocks []agentBlock `json:"blocks"` |
| 22 | } |
| 23 | type agentUpdateInput struct { |
| 24 | Team string `json:"team"` |
| 25 | ID string `json:"id"` |
| 26 | ClientID string `json:"client_id"` |
| 27 | Expected string `json:"expected_revision"` |
| 28 | Edits []agentEdit `json:"edits"` |
| 29 | } |
| 30 | type agentUpdated struct { |
| 31 | ID string `json:"id"` |
| 32 | URL string `json:"url"` |
| 33 | Revision string `json:"revision"` |
| 34 | } |
| 35 | type agentUpdateReceipt struct { |
| 36 | Coordinate string `gorm:"primaryKey"` |
| 37 | Content string |
| 38 | DocumentID int64 |
| 39 | Revision int64 |
| 40 | } |
| 41 | |
| 42 | func (agentUpdateReceipt) TableName() string { return "docs_agent_update_receipts" } |
| 43 | |
| 44 | type agentUpdateAttribution struct { |
| 45 | DocumentID int64 |
| 46 | Revision int64 |
| 47 | OperatorID int64 |
| 48 | ClientSealed []byte |
| 49 | } |
| 50 | |
| 51 | func (agentUpdateAttribution) TableName() string { return "docs_agent_update_attribution" } |
| 52 | |
| 53 | func validatedAgentEdits(in agentUpdateInput) (int64, []core.BlockEdit, error) { |
| 54 | bad := access.Fail("invalid", "Invalid revision, client UUID or document edits.") |
| 55 | id, e := uuid.Parse(in.ClientID) |
| 56 | if e != nil || id == uuid.Nil || id.String() != in.ClientID { |
| 57 | return 0, nil, bad |
| 58 | } |
| 59 | expected, e := strconv.ParseInt(in.Expected, 10, 64) |
| 60 | if e != nil || expected < 0 || strconv.FormatInt(expected, 10) != in.Expected || len(in.Edits) == 0 || len(in.Edits) > 32 { |
| 61 | return 0, nil, bad |
| 62 | } |
| 63 | result := make([]core.BlockEdit, len(in.Edits)) |
| 64 | inserted, deleted, total := 0, uint64(0), 0 |
| 65 | for i, edit := range in.Edits { |
| 66 | if edit.Delete > 200 || len(edit.Blocks) > 200 || edit.Delete == 0 && len(edit.Blocks) == 0 || uint64(edit.Index)+uint64(edit.Delete) > math.MaxUint32 { |
| 67 | return 0, nil, bad |
| 68 | } |
| 69 | if i > 0 && (edit.Index >= in.Edits[i-1].Index || uint64(edit.Index)+uint64(edit.Delete) > uint64(in.Edits[i-1].Index)) { |
| 70 | return 0, nil, bad |
| 71 | } |
| 72 | inserted += len(edit.Blocks) |
| 73 | deleted += uint64(edit.Delete) |
| 74 | if inserted > 200 || deleted > 200 { |
| 75 | return 0, nil, access.Fail("too_large", "The edit exceeds the block limit.") |
| 76 | } |
| 77 | result[i] = core.BlockEdit{Index: edit.Index, Delete: edit.Delete, Blocks: make([]core.InitialBlock, len(edit.Blocks))} |
| 78 | for j, b := range edit.Blocks { |
| 79 | if !utf8.ValidString(b.Text) || b.Type != "paragraph" && b.Type != "heading" || b.Type == "paragraph" && b.Level != 0 || b.Type == "heading" && (b.Level < 1 || b.Level > 6) { |
| 80 | return 0, nil, bad |
| 81 | } |
| 82 | total += len(b.Text) |
| 83 | if total > 128<<10 { |
| 84 | return 0, nil, access.Fail("too_large", "The edit exceeds the text limit.") |
| 85 | } |
| 86 | result[i].Blocks[j] = core.InitialBlock{Text: b.Text, Level: b.Level} |
| 87 | } |
| 88 | } |
| 89 | return expected, result, nil |
| 90 | } |
| 91 | |
| 92 | func (a *documentAgent) checkEditor(ctx context.Context, tx *gorm.DB, p access.Principal, id requestIdentity, docID int64) error { |
| 93 | guard, ok := ctx.Value(accessContextKey{}).(*requestAccess) |
| 94 | if !ok || guard == nil || guard.delegationCheck == nil { |
| 95 | return errIdentityRefused |
| 96 | } |
| 97 | if e := guard.delegationCheck(ctx); e != nil { |
| 98 | return e |
| 99 | } |
| 100 | current, e := a.resolver.resolveHomeOn(ctx, tx.Statement.ConnPool, p.Subject) |
| 101 | if e != nil { |
| 102 | return e |
| 103 | } |
| 104 | if !sameActor(current.Actor, id.Actor) { |
| 105 | return errIdentityRefused |
| 106 | } |
| 107 | if a.store.team == nil && !a.list.configured(actorAddress(id.Actor)) { |
| 108 | store := a.store.boundTo(tx) |
| 109 | allowed, err := store.HasGrant(ctx, actorAddress(id.Actor)) |
| 110 | if err != nil { |
| 111 | return err |
| 112 | } |
| 113 | if !allowed { |
| 114 | return errIdentityRefused |
| 115 | } |
| 116 | } |
| 117 | return a.store.checkPermission(ctx, tx, id.Actor, docID, permissionWrite) |
| 118 | } |
| 119 | |
| 120 | func (a *documentAgent) update(ctx context.Context, p access.Principal, id requestIdentity, in agentUpdateInput) (any, error) { |
| 121 | expected, edits, err := validatedAgentEdits(in) |
| 122 | if err != nil { |
| 123 | return nil, err |
| 124 | } |
| 125 | if a.store.content == nil { |
| 126 | return nil, access.Fail("unavailable", "Activate sealed document storage before agent writes.") |
| 127 | } |
| 128 | coordinate := a.digest("update-coordinate", []string{a.identityIssuer, a.issuer, p.Subject, p.Client, a.team, "docs_update", in.ClientID}) |
| 129 | payload := a.digest("update-content", struct { |
| 130 | ID, Expected string |
| 131 | Edits []agentEdit |
| 132 | }{in.ID, in.Expected, in.Edits}) |
| 133 | var doc Document |
| 134 | var revision int64 |
| 135 | created := false |
| 136 | err = a.store.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { |
| 137 | if e := a.bind(tx); e != nil { |
| 138 | return e |
| 139 | } |
| 140 | // The target lookup grants no authority; checkEditor performs the complete |
| 141 | // transaction-local identity and current permission check before any body work. |
| 142 | if e := tx.Where("sqid=? AND deleted_at IS NULL", in.ID).First(&doc).Error; e != nil { |
| 143 | return e |
| 144 | } |
| 145 | if e := a.checkEditor(ctx, tx, p, id, doc.ID); e != nil { |
| 146 | return e |
| 147 | } |
| 148 | var receipt agentUpdateReceipt |
| 149 | e := tx.Where("coordinate=?", coordinate).First(&receipt).Error |
| 150 | if e == nil { |
| 151 | if receipt.Content != payload { |
| 152 | return access.Fail("conflict", "This client UUID already names different edits.") |
| 153 | } |
| 154 | if receipt.DocumentID != doc.ID || receipt.Revision <= 0 { |
| 155 | return access.Fail("unavailable", "The edit receipt is inconsistent.") |
| 156 | } |
| 157 | var count int64 |
| 158 | if e = tx.Model(&DocUpdate{}).Where("doc_id=? AND seq=?", doc.ID, receipt.Revision).Count(&count).Error; e != nil { |
| 159 | return e |
| 160 | } |
| 161 | if count != 1 { |
| 162 | return access.Fail("unavailable", "The edit receipt is inconsistent.") |
| 163 | } |
| 164 | revision = receipt.Revision |
| 165 | return a.checkEditor(ctx, tx, p, id, doc.ID) |
| 166 | } |
| 167 | if !errors.Is(e, gorm.ErrRecordNotFound) { |
| 168 | return e |
| 169 | } |
| 170 | store := a.store.boundTo(tx) |
| 171 | seq, e := store.currentSeq(ctx, doc.ID) |
| 172 | if e != nil { |
| 173 | return e |
| 174 | } |
| 175 | if seq != expected { |
| 176 | return access.Fail("conflict", "The document body changed. Read it again before editing.") |
| 177 | } |
| 178 | if seq == math.MaxInt64 { |
| 179 | return access.Fail("unavailable", "The document revision limit was reached.") |
| 180 | } |
| 181 | var update []byte |
| 182 | for attempt := 0; attempt < 8; attempt++ { |
| 183 | replayDoc := doc |
| 184 | replayDoc.ClientID = uint64(mrand.Uint32N(math.MaxUint32)) + 1 |
| 185 | h, replayed, _, e := store.replay(ctx, &replayDoc) |
| 186 | if e != nil { |
| 187 | return e |
| 188 | } |
| 189 | if replayed != expected { |
| 190 | h.Close(ctx) |
| 191 | return access.Fail("unavailable", "The document replay is inconsistent.") |
| 192 | } |
| 193 | update, e = h.EditUpdate(ctx, edits) // consumes h, including on collision/refusal |
| 194 | if errors.Is(e, core.ErrEditCollision) { |
| 195 | continue |
| 196 | } |
| 197 | if errors.Is(e, core.ErrEditInvalid) || errors.Is(e, core.ErrEditPending) { |
| 198 | return access.Fail("invalid", "The current document structure or edit coordinates are unsupported.") |
| 199 | } |
| 200 | if errors.Is(e, core.ErrEditTooLarge) { |
| 201 | return access.Fail("too_large", "The document edit exceeds its limit.") |
| 202 | } |
| 203 | if e != nil { |
| 204 | return e |
| 205 | } |
| 206 | break |
| 207 | } |
| 208 | if len(update) == 0 { |
| 209 | return access.Fail("unavailable", "Could not allocate a document editing identity.") |
| 210 | } |
| 211 | revision, e = store.ApplyUpdate(ctx, &doc, id.Actor, update) |
| 212 | if e != nil { |
| 213 | return e |
| 214 | } |
| 215 | sealer, e := seal.New(a.key, "oficina/docs") |
| 216 | if e != nil { |
| 217 | return e |
| 218 | } |
| 219 | purpose := "agent-update-client/" + doc.GUID + "/" + strconv.FormatInt(revision, 10) + "/" + coordinate |
| 220 | client, e := sealer.Seal(purpose, []byte(p.Client)) |
| 221 | if e != nil { |
| 222 | return e |
| 223 | } |
| 224 | if e = tx.Create(&agentUpdateAttribution{doc.ID, revision, id.Actor.PersonID, client}).Error; e != nil { |
| 225 | return e |
| 226 | } |
| 227 | if e = tx.Create(&agentUpdateReceipt{coordinate, payload, doc.ID, revision}).Error; e != nil { |
| 228 | return e |
| 229 | } |
| 230 | if e = a.checkEditor(ctx, tx, p, id, doc.ID); e != nil { |
| 231 | return e |
| 232 | } |
| 233 | created = true |
| 234 | return nil |
| 235 | }) |
| 236 | if err != nil { |
| 237 | return nil, agentFailure(err) |
| 238 | } |
| 239 | if created && a.notify != nil { |
| 240 | a.notify(doc.ID, revision) |
| 241 | } |
| 242 | if guard, ok := ctx.Value(accessContextKey{}).(*requestAccess); ok && guard != nil { |
| 243 | guard.responseDocs[doc.ID] = permissionWrite |
| 244 | } |
| 245 | return agentUpdated{doc.Sqid, a.origin + "/d/" + doc.Sqid, strconv.FormatInt(revision, 10)}, nil |
| 246 | } |
| 247 | |