oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package chat
2
3import (
4 "bytes"
5 "context"
6 "crypto/sha256"
7 "encoding/base64"
8 "encoding/hex"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "net/netip"
13 "strings"
14 "time"
15
16 "amadan.net/oficina/equipo/internal/attach"
17 "amadan.net/oficina/equipo/internal/websource"
18 "amadan.net/oficina/equipo/internal/wire"
19 "gorm.io/gorm"
20)
21
22// A Research step's results (Research spec §5, slice R3). Kept images
23// arrive first, in research_file chunks bound to the step's running
24// attempt and its runner, in order and bounded; a complete file is
25// checked against its hash and sniffed as a PNG within bounds. The done
26// report's fetch log, kept images and findings are checked again here
27// (the runner checked them too) and stored; findings that do not check
28// become the "ended without findings" gap, and images that do not check
29// are dropped, never stored.
30
31// researchRecord is the findings of one done Research attempt. Revision
32// is the step's revision that recorded it.
33type researchRecord struct {
34 StepID string `gorm:"primaryKey"`
35 Attempt int64 `gorm:"primaryKey"`
36 TaskID string `gorm:"index:chat_research_task"`
37 Revision int64
38 Findings string
39 CreatedAt time.Time
40}
41
42func (researchRecord) TableName() string { return "chat_research" }
43
44// researchFetchRecord is one line of a done attempt's fetch log, in
45// order. Hops is a JSON list.
46type researchFetchRecord struct {
47 StepID string `gorm:"primaryKey"`
48 Attempt int64 `gorm:"primaryKey"`
49 Idx int `gorm:"primaryKey"`
50 TaskID string
51 SourceID string
52 Origin string
53 Parent string
54 URL string
55 Hops string
56 Address string
57 Status int
58 Type string
59 Bytes int64
60 SHA256 string `gorm:"column:sha256"`
61 Millis int64
62 Reason string
63}
64
65func (researchFetchRecord) TableName() string { return "chat_research_fetches" }
66
67// taskFileRecord is an image a Research attempt sends: while it arrives
68// (Received of Total chunks, Bytes of Size), complete once checked, and
69// kept once the done report names it. Anything not kept when the step
70// ends is deleted with its bytes.
71type taskFileRecord struct {
72 ID string `gorm:"primaryKey"`
73 TaskID string `gorm:"index:chat_task_file_task"`
74 StepID string `gorm:"index:chat_task_file_step"`
75 Attempt int64
76 RunnerID string
77 ImageID string
78 SourceID string
79 Role string
80 Description string
81 MediaType string
82 Size int64
83 SHA256 string `gorm:"column:sha256"`
84 Total int
85 Received int
86 Bytes int64
87 Width int
88 Height int
89 Complete bool
90 Kept bool
91 CreatedAt time.Time
92 UpdatedAt time.Time
93 // Source is taskFileResearch (an image a Research attempt kept) or
94 // taskFileRender (a Design capture); Option is the Design option the
95 // capture shows and TreeDigest the tree it was rendered from.
96 Source string `gorm:"not null;default:research"`
97 Option string `gorm:"not null;default:''"`
98 TreeDigest string `gorm:"not null;default:''"`
99}
100
101func (taskFileRecord) TableName() string { return "chat_task_files" }
102
103// Task file sources (chat_task_files.source).
104const (
105 taskFileResearch = "research"
106 taskFileRender = "render"
107)
108
109// taskFileDataRecord is one chunk of a task file's bytes, apart, so
110// listing files never loads them.
111type taskFileDataRecord struct {
112 FileID string `gorm:"primaryKey"`
113 Idx int `gorm:"primaryKey"`
114 Data []byte
115}
116
117func (taskFileDataRecord) TableName() string { return "chat_task_file_data" }
118
119// Bounds of a fetch log line beyond the wire's.
120const (
121 maxFetchType = 100
122 maxFetchBytes = 64 << 20
123 maxFetchMillis = int64(time.Hour / time.Millisecond)
124)
125
126// refuseFile refuses a research_file chunk: acked and dropped, logged.
127func refuseFile(why string) error {
128 return fmt.Errorf("%w: research_file: %s", ErrRefused, why)
129}
130
131// researchFile keeps one chunk of a kept image only from the runner the
132// Research step is placed on, for the step's current attempt while it
133// runs, at protocol 13, in order, within bounds, and at most
134// wire.MaxKeptImages images per attempt. The last chunk completes the
135// file only when the whole is the declared size and hash and sniffs as a
136// PNG within bounds, byte for byte as attach keeps it; otherwise it is
137// refused and the file never completes.
138func (t *txn) researchFile(l Lease, v *wire.ResearchFile) error {
139 if l.Protocol < wire.ProtocolResearch {
140 return refuseFile("below protocol 13")
141 }
142 if !wire.ValidImageID(v.ImageID) || !wire.ValidSHA256(v.SHA256) || v.Size < 1 || v.Size > wire.MaxKeptImageBytes ||
143 v.Total < 1 || v.Total > wire.MaxResearchFileChunks || v.Index < 0 || v.Index >= v.Total || len(v.Data) > base64.StdEncoding.EncodedLen(wire.ResearchFileChunk) {
144 return refuseFile("bad chunk")
145 }
146 data, err := base64.StdEncoding.DecodeString(v.Data)
147 if err != nil || len(data) == 0 || len(data) > wire.ResearchFileChunk {
148 return refuseFile("bad chunk data")
149 }
150 var s stepRecord
151 if err := t.db.Where("id = ? AND task_id = ?", v.StepID, v.TaskID).First(&s).Error; errors.Is(err, gorm.ErrRecordNotFound) {
152 return refuseFile("no such step")
153 } else if err != nil {
154 return err
155 }
156 if s.Specialist != wire.SpecialistResearch || s.Person != l.Runner.Person || s.RunnerID != l.Runner.RunnerID {
157 return refuseFile("not this runner's Research step")
158 }
159 if s.State != wire.StepRunning || v.Attempt != s.Attempt {
160 return refuseFile("attempt not current")
161 }
162 k, err := t.loadTask(s.TaskID)
163 if err != nil {
164 return err
165 }
166 if wire.FinalStage(k.Stage) || k.CancelRequested {
167 return refuseFile("task ended")
168 }
169 now := t.now()
170 var f taskFileRecord
171 err = t.db.Where("step_id = ? AND attempt = ? AND image_id = ?", s.ID, s.Attempt, v.ImageID).First(&f).Error
172 fresh := errors.Is(err, gorm.ErrRecordNotFound)
173 if err != nil && !fresh {
174 return err
175 }
176 if fresh {
177 if v.Index != 0 {
178 return refuseFile("chunk out of order")
179 }
180 var n int64
181 if err := t.db.Model(&taskFileRecord{}).Where("step_id = ? AND attempt = ?", s.ID, s.Attempt).Count(&n).Error; err != nil {
182 return err
183 }
184 if n >= wire.MaxKeptImages {
185 return refuseFile("too many images")
186 }
187 f = taskFileRecord{ID: newID("tf_"), TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt, RunnerID: l.Runner.RunnerID, ImageID: v.ImageID, Size: v.Size, SHA256: v.SHA256, Total: v.Total, CreatedAt: now}
188 } else if f.Complete || f.Total != v.Total || f.Size != v.Size || f.SHA256 != v.SHA256 || v.Index != f.Received {
189 return refuseFile("chunk out of order")
190 }
191 f.Received, f.Bytes, f.UpdatedAt = f.Received+1, f.Bytes+int64(len(data)), now
192 if f.Bytes > f.Size || f.Received == f.Total && f.Bytes != f.Size {
193 return refuseFile("size does not match")
194 }
195 if err := t.db.Create(&taskFileDataRecord{FileID: f.ID, Idx: v.Index, Data: data}).Error; err != nil {
196 return err
197 }
198 if f.Received == f.Total {
199 whole, err := t.fileBytes(f.ID)
200 if err != nil {
201 return err
202 }
203 w, h, why := checkKeptImage(whole, f.Size, f.SHA256)
204 if why != "" {
205 return refuseFile(why)
206 }
207 f.Complete, f.MediaType, f.Width, f.Height = true, attach.PNG, w, h
208 }
209 if fresh {
210 return t.db.Create(&f).Error
211 }
212 return t.db.Model(&taskFileRecord{}).Where("id = ?", f.ID).Select("received", "bytes", "complete", "media_type", "width", "height", "updated_at").Updates(&f).Error
213}
214
215// checkKeptImage checks a complete kept image: exactly size bytes with
216// that SHA-256, a PNG by its bytes that attach keeps unchanged (nothing
217// after IEND, no location), within the kept image bounds. why is "" when
218// it checks.
219func checkKeptImage(data []byte, size int64, sha string) (w, h int, why string) {
220 if int64(len(data)) != size {
221 return 0, 0, "size does not match"
222 }
223 sum := sha256.Sum256(data)
224 if hex.EncodeToString(sum[:]) != sha {
225 return 0, 0, "hash does not match"
226 }
227 info, clean, err := attach.Inspect("image.png", attach.PNG, data)
228 if err != nil || info.MediaType != attach.PNG || !bytes.Equal(clean, data) {
229 return 0, 0, "not a PNG"
230 }
231 if info.Width < 1 || info.Height < 1 || info.Width > wire.MaxKeptSide || info.Height > wire.MaxKeptSide {
232 return 0, 0, "image too large"
233 }
234 return info.Width, info.Height, ""
235}
236
237// fileBytes are a task file's chunks, in order.
238func (t *txn) fileBytes(id string) ([]byte, error) {
239 var rows []taskFileDataRecord
240 if err := t.db.Where("file_id = ?", id).Order("idx").Find(&rows).Error; err != nil {
241 return nil, err
242 }
243 var out []byte
244 for _, r := range rows {
245 out = append(out, r.Data...)
246 }
247 return out, nil
248}
249
250// keptImage is a done report's image record and the file it names.
251type keptImage struct {
252 file taskFileRecord
253 meta wire.ResearchImage
254}
255
256// researchResult stores a done Research attempt's results (before its
257// step is saved, so the Engineering it releases can be handed them): the
258// fetch log's lines that check (saneFetches; refused targets as audit
259// text); the images whose records check against their complete files;
260// and the findings, decoded strictly against the log's citable source
261// ids and those images. A missing payload, a log that is too long, or
262// findings that do not check store the gap instead, with no images. Files the attempt sent and the report does not
263// keep are deleted.
264func (t *txn) researchResult(k *taskRecord, s *stepRecord, v *wire.StepReport) error {
265 findings := wire.NoFindings()
266 var fetches []wire.ResearchFetch
267 var keep []keptImage
268 if r := v.Research; r != nil {
269 if lines, sources, ok := saneFetches(r.Fetches); ok {
270 fetches = lines
271 images, err := t.checkImages(s, r.Images, sources)
272 if err != nil {
273 return err
274 }
275 kept := map[string]bool{}
276 for _, m := range images {
277 kept[m.meta.ID] = true
278 }
279 if f, err := wire.DecodeFindings(r.Findings, sources, kept); err == nil {
280 findings, keep = normalFindings(f), images
281 }
282 }
283 }
284 raw, err := json.Marshal(findings)
285 if err != nil {
286 return err
287 }
288 if err := t.db.Create(&researchRecord{StepID: s.ID, Attempt: s.Attempt, TaskID: k.ID, Findings: string(raw), CreatedAt: t.now()}).Error; err != nil {
289 return err
290 }
291 if err := t.storeFetches(k, s, fetches); err != nil {
292 return err
293 }
294 for _, m := range keep {
295 m.file.Kept, m.file.SourceID, m.file.Role, m.file.Description, m.file.UpdatedAt = true, m.meta.SourceID, m.meta.Role, m.meta.Description, t.now()
296 if err := t.db.Model(&taskFileRecord{}).Where("id = ?", m.file.ID).Select("kept", "source_id", "role", "description", "updated_at").Updates(&m.file).Error; err != nil {
297 return err
298 }
299 }
300 return t.dropResearchFiles(s.ID)
301}
302
303// storeFetches stores an attempt's fetch log lines, in order.
304func (t *txn) storeFetches(k *taskRecord, s *stepRecord, fetches []wire.ResearchFetch) error {
305 for i, f := range fetches {
306 hops, _ := json.Marshal(f.Hops)
307 row := researchFetchRecord{StepID: s.ID, Attempt: s.Attempt, Idx: i + 1, TaskID: k.ID, SourceID: f.SourceID, Origin: f.Origin, Parent: f.Parent, URL: f.URL, Hops: string(hops), Address: f.Address, Status: f.Status, Type: f.Type, Bytes: f.Bytes, SHA256: f.SHA256, Millis: f.Millis, Reason: f.Reason}
308 if err := t.db.Create(&row).Error; err != nil {
309 return err
310 }
311 }
312 return nil
313}
314
315// researchFetchLog stores the fetch log of an attempt that ended without
316// being done (failed or cancelled, the model's failure included): the
317// audit of what was requested is kept however Research ended. There are
318// no findings to store.
319func (t *txn) researchFetchLog(k *taskRecord, s *stepRecord, v *wire.StepReport) error {
320 if v.Research == nil {
321 return nil
322 }
323 lines, _, ok := saneFetches(v.Research.Fetches)
324 if !ok {
325 return nil
326 }
327 var n int64
328 if err := t.db.Model(&researchFetchRecord{}).Where("step_id = ? AND attempt = ?", s.ID, s.Attempt).Count(&n).Error; err != nil || n > 0 {
329 return err
330 }
331 return t.storeFetches(k, s, lines)
332}
333
334// normalFindings has empty lists rather than none, so the stored JSON is
335// one shape.
336func normalFindings(f wire.ResearchFindings) wire.ResearchFindings {
337 if f.Facts == nil {
338 f.Facts = []wire.ResearchFact{}
339 }
340 if f.Images == nil {
341 f.Images = []string{}
342 }
343 if f.Gaps == nil {
344 f.Gaps = []string{}
345 }
346 return f
347}
348
349// checkImages are the report's image records that check: at most
350// wire.MaxKeptImages of them (more and none are kept), each valid, once,
351// from a source in this attempt's log, naming a complete file of this
352// attempt with the same hash, size and pixel size.
353func (t *txn) checkImages(s *stepRecord, list []wire.ResearchImage, sources map[string]bool) ([]keptImage, error) {
354 if len(list) > wire.MaxKeptImages {
355 return nil, nil
356 }
357 var out []keptImage
358 seen := map[string]bool{}
359 for _, m := range list {
360 if !wire.ValidResearchImage(m) || seen[m.ID] || !sources[m.SourceID] {
361 continue
362 }
363 var f taskFileRecord
364 if err := t.db.Where("step_id = ? AND attempt = ? AND image_id = ? AND complete = ?", s.ID, s.Attempt, m.ID, true).First(&f).Error; errors.Is(err, gorm.ErrRecordNotFound) {
365 continue
366 } else if err != nil {
367 return nil, err
368 }
369 if f.SHA256 != m.SHA256 || f.Size != m.Size || f.Width != m.Width || f.Height != m.Height {
370 continue
371 }
372 seen[m.ID] = true
373 out = append(out, keptImage{file: f, meta: m})
374 }
375 return out, nil
376}
377
378// saneFetches is the fetch log as it is stored, and the source ids
379// findings may cite. A log longer than wire.MaxResearchFetches is not
380// sane (ok false: none of it is kept). Otherwise every line that checks
381// is kept (saneFetch), and a line that does not is dropped alone: a
382// correctly refused target never costs the rest of the audit. Only
383// lines whose URL is canonical name a citable source.
384func saneFetches(lines []wire.ResearchFetch) (out []wire.ResearchFetch, sources map[string]bool, ok bool) {
385 if len(lines) > wire.MaxResearchFetches {
386 return nil, nil, false
387 }
388 out, sources = []wire.ResearchFetch{}, map[string]bool{}
389 for _, f := range lines {
390 c, canonical, ok := saneFetch(f)
391 if !ok {
392 continue
393 }
394 out = append(out, c)
395 if canonical {
396 sources[c.SourceID] = true
397 }
398 }
399 return out, sources, true
400}
401
402// saneFetch checks one fetch log line: its ids, origin and reason are
403// the runner's short codes; its URL and each hop's parse under the one
404// URL contract (stored canonical), or, on a line that records a refusal
405// (a reason), are kept as bounded escaped audit text (auditText); its
406// addresses, statuses, type, sizes, hash and time are in shape. canonical
407// reports that the line's own URL is canonical.
408func saneFetch(f wire.ResearchFetch) (out wire.ResearchFetch, canonical, ok bool) {
409 switch f.Origin {
410 case wire.ResearchOriginPerson, wire.ResearchOriginProposed, wire.ResearchOriginExpanded:
411 default:
412 return f, false, false
413 }
414 if !wire.ValidSourceID(f.SourceID) || f.Parent != "" && !wire.ValidSourceID(f.Parent) || f.Reason != "" && !wire.ValidFetchWord(f.Reason) {
415 return f, false, false
416 }
417 target := func(raw string) (string, bool, bool) {
418 if u, err := websource.Parse(raw); err == nil {
419 return u.String(), true, true
420 }
421 if f.Reason == "" || raw == "" {
422 return "", false, false
423 }
424 return auditText(raw), false, true
425 }
426 if f.URL, canonical, ok = target(f.URL); !ok {
427 return f, false, false
428 }
429 if len(f.Hops) > wire.MaxResearchHops {
430 return f, false, false
431 }
432 hops := make([]wire.ResearchHop, 0, len(f.Hops))
433 for _, h := range f.Hops {
434 if h.URL, _, ok = target(h.URL); !ok || !saneAddress(h.Address) || h.Status < 0 || h.Status > 599 {
435 return f, false, false
436 }
437 hops = append(hops, h)
438 }
439 f.Hops = hops
440 if !saneAddress(f.Address) || len(f.Type) > maxFetchType {
441 return f, false, false
442 }
443 for _, r := range f.Type {
444 if r < 0x20 || r > 0x7e {
445 return f, false, false
446 }
447 }
448 if f.Status < 0 || f.Status > 599 || f.Bytes < 0 || f.Bytes > maxFetchBytes || f.Millis < 0 || f.Millis > maxFetchMillis || f.SHA256 != "" && !wire.ValidSHA256(f.SHA256) {
449 return f, false, false
450 }
451 return f, canonical, true
452}
453
454// saneAddress: none, or a canonical IP address with no zone.
455func saneAddress(s string) bool {
456 if s == "" {
457 return true
458 }
459 a, err := netip.ParseAddr(s)
460 return err == nil && a.Zone() == "" && a.String() == s
461}
462
463// auditText is a refused target as the log keeps it: printable ASCII
464// only (every other byte, space and invalid UTF-8 included, is
465// percent-escaped, so no control or bidirectional character survives),
466// at most websource.MaxURL bytes.
467func auditText(raw string) string {
468 const hex = "0123456789ABCDEF"
469 var b strings.Builder
470 for i := 0; i < len(raw); i++ {
471 c := raw[i]
472 piece := string(c)
473 if c <= 0x20 || c >= 0x7f {
474 piece = "%" + string(hex[c>>4]) + string(hex[c&15])
475 }
476 if b.Len()+len(piece) > websource.MaxURL {
477 break
478 }
479 b.WriteString(piece)
480 }
481 return b.String()
482}
483
484// dropResearchFiles deletes a Research step's files that are not kept,
485// and their bytes.
486func (t *txn) dropResearchFiles(stepID string) error {
487 var ids []string
488 if err := t.db.Model(&taskFileRecord{}).Where("step_id = ? AND kept = ?", stepID, false).Pluck("id", &ids).Error; err != nil || len(ids) == 0 {
489 return err
490 }
491 if err := t.db.Where("file_id IN ?", ids).Delete(&taskFileDataRecord{}).Error; err != nil {
492 return err
493 }
494 return t.db.Where("id IN ?", ids).Delete(&taskFileRecord{}).Error
495}
496
497// researchView is a Research step's latest result on the task's read
498// shape: its done findings, or, for an attempt that ended otherwise, its
499// fetch log alone; nil before it has either.
500func (t *txn) researchView(s stepRecord) (*wire.StepResearch, error) {
501 var rec researchRecord
502 if err := t.db.Where("step_id = ?", s.ID).Order("attempt DESC").First(&rec).Error; errors.Is(err, gorm.ErrRecordNotFound) {
503 // Not done: the fetch log of its latest attempt, if it kept one,
504 // with no findings.
505 var line researchFetchRecord
506 if err := t.db.Where("step_id = ?", s.ID).Order("attempt DESC").First(&line).Error; errors.Is(err, gorm.ErrRecordNotFound) {
507 return nil, nil
508 } else if err != nil {
509 return nil, err
510 }
511 rec = researchRecord{StepID: s.ID, Attempt: line.Attempt}
512 } else if err != nil {
513 return nil, err
514 }
515 v := &wire.StepResearch{Attempt: rec.Attempt, Fetches: []wire.ResearchFetch{}, Images: []wire.StepResearchImage{}}
516 if rec.Findings != "" {
517 if err := json.Unmarshal([]byte(rec.Findings), &v.Findings); err != nil {
518 return nil, err
519 }
520 }
521 v.Findings = normalFindings(v.Findings)
522 var lines []researchFetchRecord
523 if err := t.db.Where("step_id = ? AND attempt = ?", s.ID, rec.Attempt).Order("idx").Find(&lines).Error; err != nil {
524 return nil, err
525 }
526 for _, l := range lines {
527 f := wire.ResearchFetch{SourceID: l.SourceID, Origin: l.Origin, Parent: l.Parent, URL: l.URL, Address: l.Address, Status: l.Status, Type: l.Type, Bytes: l.Bytes, SHA256: l.SHA256, Millis: l.Millis, Reason: l.Reason}
528 if err := json.Unmarshal([]byte(l.Hops), &f.Hops); err != nil {
529 return nil, err
530 }
531 if len(f.Hops) == 0 {
532 f.Hops = nil
533 }
534 v.Fetches = append(v.Fetches, f)
535 }
536 var files []taskFileRecord
537 if err := t.db.Where("step_id = ? AND attempt = ? AND kept = ?", s.ID, rec.Attempt, true).Order("image_id").Find(&files).Error; err != nil {
538 return nil, err
539 }
540 for _, f := range files {
541 v.Images = append(v.Images, wire.StepResearchImage{ID: f.ID, ImageID: f.ImageID, SourceID: f.SourceID, Role: f.Role, Description: f.Description, Size: f.Size, Width: f.Width, Height: f.Height})
542 }
543 return v, nil
544}
545
546// TaskFile is a kept image of a task, for anyone who may read the task
547// (a current member): its record and bytes. Only kept, complete files
548// of that task; anything else is not found.
549func (s *Store) TaskFile(ctx context.Context, person, taskID, id string) (name string, data []byte, err error) {
550 err = s.read(ctx, func(tx *gorm.DB) error {
551 if err := s.authority.CurrentPerson(ctx, tx); err != nil {
552 return err
553 }
554 t := &txn{s: s, db: tx}
555 if _, err := t.loadTask(taskID); err != nil {
556 return err
557 }
558 var f taskFileRecord
559 if err := tx.Where("id = ? AND task_id = ? AND kept = ? AND complete = ?", id, taskID, true, true).First(&f).Error; errors.Is(err, gorm.ErrRecordNotFound) {
560 return ErrNotFound
561 } else if err != nil {
562 return err
563 }
564 if data, err = t.fileBytes(f.ID); err != nil {
565 return err
566 }
567 if int64(len(data)) != f.Size {
568 return ErrNotFound
569 }
570 name = f.ImageID + ".png"
571 if f.Source == taskFileRender {
572 // A capture's id is its file name.
573 name = f.ImageID
574 }
575 return nil
576 })
577 return name, data, err
578}
579