| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/base64" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "net/http" |
| 9 | "time" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/diffscan" |
| 12 | "amadan.net/oficina/equipo/internal/equipo/personapi" |
| 13 | "amadan.net/oficina/equipo/internal/wire" |
| 14 | "github.com/go-chi/chi/v5" |
| 15 | "gorm.io/gorm" |
| 16 | ) |
| 17 | |
| 18 | type changeDiffRecord struct { |
| 19 | StepID string `gorm:"primaryKey"` |
| 20 | Attempt int64 `gorm:"primaryKey"` |
| 21 | Idx int `gorm:"primaryKey"` |
| 22 | TaskID string `gorm:"index:chat_diff_task"` |
| 23 | RunnerID string |
| 24 | Base string |
| 25 | Candidate string |
| 26 | Collection string |
| 27 | Total int |
| 28 | Path string |
| 29 | Patch string |
| 30 | Reason string |
| 31 | Truncated bool |
| 32 | Accepted bool |
| 33 | ExpiresAt time.Time `gorm:"index:chat_diff_expiry"` |
| 34 | } |
| 35 | |
| 36 | func (changeDiffRecord) TableName() string { return "chat_change_diffs" } |
| 37 | func (r changeDiffRecord) file() wire.FileDiff { |
| 38 | return wire.FileDiff{Path: r.Path, Patch: r.Patch, Reason: r.Reason, Truncated: r.Truncated} |
| 39 | } |
| 40 | |
| 41 | var ErrDiffChanged = errors.New("diff candidate changed") |
| 42 | |
| 43 | func (t *txn) pruneChangeDiffs() error { |
| 44 | return t.db.Where("expires_at <= ?", t.now()).Delete(&changeDiffRecord{}).Error |
| 45 | } |
| 46 | |
| 47 | func (t *txn) changeDiff(l Lease, v *wire.ChangeDiffUpload) error { |
| 48 | refuse := func() error { return ErrRefused } |
| 49 | if l.Protocol < wire.ProtocolChangeDiffs || !wire.ValidSHA256(v.Collection) || !wire.ValidSHA256(v.SHA256) || v.Total < 1 || v.Total > wire.MaxChangeEntries || v.Index < 0 || v.Index >= v.Total || v.Size < 0 || v.Size > wire.MaxFileDiffBytes || len(v.Data) > base64.StdEncoding.EncodedLen(wire.MaxFileDiffBytes) { |
| 50 | return refuse() |
| 51 | } |
| 52 | var step stepRecord |
| 53 | if err := t.db.Where("id = ? AND task_id = ?", v.StepID, v.TaskID).First(&step).Error; err != nil { |
| 54 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 55 | return refuse() |
| 56 | } |
| 57 | return err |
| 58 | } |
| 59 | if step.Specialist != wire.SpecialistEngineering || step.Person != l.Runner.Person || step.Attempt != v.Attempt || step.Retired || step.BaseSHA != v.Base || step.CandidateSHA != v.Candidate || !validSHA(v.Candidate) { |
| 60 | return refuse() |
| 61 | } |
| 62 | if v.Publication == "" { |
| 63 | // The primary's own candidate, from the runner it runs on, while it |
| 64 | // runs. A worker's diffs are never kept: the primary measures a |
| 65 | // worker's candidate when it publishes it. |
| 66 | role, err := t.s.authority.RunnerRole(t.db, l.Runner.RunnerID) |
| 67 | if err != nil { |
| 68 | return err |
| 69 | } |
| 70 | if role != wire.RolePrimary || step.RunnerID != l.Runner.RunnerID || step.State != wire.StepRunning { |
| 71 | return refuse() |
| 72 | } |
| 73 | } else if ok, err := t.publicationUploader(l, step, v.Publication); err != nil || !ok { |
| 74 | if err != nil { |
| 75 | return err |
| 76 | } |
| 77 | return refuse() |
| 78 | } |
| 79 | k, err := t.loadTask(step.TaskID) |
| 80 | if err != nil { |
| 81 | return err |
| 82 | } |
| 83 | if wire.FinalStage(k.Stage) || k.CancelRequested || k.MoveProject != "" { |
| 84 | return refuse() |
| 85 | } |
| 86 | data, err := base64.StdEncoding.DecodeString(v.Data) |
| 87 | if err != nil || len(data) != v.Size || wire.DiffDigest(data) != v.SHA256 { |
| 88 | return refuse() |
| 89 | } |
| 90 | file := wire.FileDiff{Path: v.Path, Patch: string(data), Reason: v.Reason, Truncated: v.Truncated} |
| 91 | if !wire.ValidFileDiff(file) { |
| 92 | return refuse() |
| 93 | } |
| 94 | ctx, cancel := context.WithTimeout(t.db.Statement.Context, 10*time.Second) |
| 95 | defer cancel() |
| 96 | if diffscan.Check(ctx, file.Patch, nil) != "" { |
| 97 | return refuse() |
| 98 | } |
| 99 | if err := t.pruneChangeDiffs(); err != nil { |
| 100 | return err |
| 101 | } |
| 102 | var rows []changeDiffRecord |
| 103 | if err := t.db.Where("step_id = ? AND attempt = ?", step.ID, step.Attempt).Order("idx").Find(&rows).Error; err != nil { |
| 104 | return err |
| 105 | } |
| 106 | bytes := 0 |
| 107 | for _, r := range rows { |
| 108 | if r.Collection != v.Collection || r.Total != v.Total || r.RunnerID != l.Runner.RunnerID || r.Base != v.Base || r.Candidate != v.Candidate { |
| 109 | return refuse() |
| 110 | } |
| 111 | if r.Idx == v.Index { |
| 112 | if r.file() == file { |
| 113 | return nil |
| 114 | } |
| 115 | return refuse() |
| 116 | } |
| 117 | if r.Path == v.Path || r.Accepted { |
| 118 | return refuse() |
| 119 | } |
| 120 | bytes += len(r.Patch) |
| 121 | } |
| 122 | if len(rows) != v.Index || bytes+len(data) > wire.MaxCandidateDiffBytes { |
| 123 | return refuse() |
| 124 | } |
| 125 | expires := t.now().Add(15 * time.Minute) |
| 126 | if len(rows) > 0 { |
| 127 | expires = rows[0].ExpiresAt |
| 128 | } |
| 129 | record := changeDiffRecord{StepID: step.ID, Attempt: step.Attempt, Idx: v.Index, TaskID: k.ID, RunnerID: l.Runner.RunnerID, Base: v.Base, Candidate: v.Candidate, Collection: v.Collection, Total: v.Total, Path: file.Path, Patch: file.Patch, Reason: file.Reason, Truncated: file.Truncated, ExpiresAt: expires} |
| 130 | return t.db.Create(&record).Error |
| 131 | } |
| 132 | |
| 133 | // publicationUploader: l may upload diffs bound to publication for step, |
| 134 | // a worker's Engineering attempt (protocol 37). Only the primary the |
| 135 | // publication was given to, while it is the person's primary, for the |
| 136 | // step's own publication while it is pending or published, |
| 137 | // whether or not the worker's final report has come; never another |
| 138 | // runner, an earlier publication or a failed one. |
| 139 | func (t *txn) publicationUploader(l Lease, step stepRecord, publication string) (bool, error) { |
| 140 | if l.Protocol < wire.ProtocolMacEngineering { |
| 141 | return false, nil |
| 142 | } |
| 143 | primary, err := t.s.authority.PrimaryRunner(t.db, l.Runner.Person) |
| 144 | if err != nil { |
| 145 | return false, err |
| 146 | } |
| 147 | if primary == "" || primary != l.Runner.RunnerID || step.PublicationRunner != primary || step.RunnerID == primary { |
| 148 | return false, nil |
| 149 | } |
| 150 | if step.PublicationID != publication || step.Publication != wire.PublicationPending && step.Publication != wire.PublicationPublished { |
| 151 | return false, nil |
| 152 | } |
| 153 | return step.State == wire.StepRunning || step.State == wire.StepDone, nil |
| 154 | } |
| 155 | |
| 156 | // A collection becomes readable only with its matching accepted final report. |
| 157 | // Missing, conflicting and incomplete collections never affect Engineering. |
| 158 | // uploader is the runner whose uploads count: the step's own runner for the |
| 159 | // primary's candidate, the publication's primary for a worker's. |
| 160 | func (t *txn) acceptChangeDiffs(l Lease, step stepRecord, collection, uploader string) error { |
| 161 | if l.Protocol < wire.ProtocolChangeDiffs || step.Specialist != wire.SpecialistEngineering || !wire.ValidSHA256(collection) { |
| 162 | return nil |
| 163 | } |
| 164 | var facts wire.ChangeFiles |
| 165 | if json.Unmarshal([]byte(step.ChangeFiles), &facts) != nil || !wire.ValidChangeFiles(&facts) || facts.Base != step.BaseSHA || facts.SHA != step.CandidateSHA { |
| 166 | return nil |
| 167 | } |
| 168 | var rows []changeDiffRecord |
| 169 | if err := t.db.Where("step_id = ? AND attempt = ? AND collection = ? AND expires_at > ?", step.ID, step.Attempt, collection, t.now()).Order("idx").Find(&rows).Error; err != nil { |
| 170 | return err |
| 171 | } |
| 172 | if len(rows) == 0 || len(rows) != len(facts.Entries) { |
| 173 | return nil |
| 174 | } |
| 175 | paths := map[string]bool{} |
| 176 | for _, e := range facts.Entries { |
| 177 | paths[e.Path] = true |
| 178 | } |
| 179 | files := make([]wire.FileDiff, 0, len(rows)) |
| 180 | for i, r := range rows { |
| 181 | if r.Total != len(rows) || r.Idx != i || r.TaskID != step.TaskID || r.RunnerID != uploader || r.Base != step.BaseSHA || r.Candidate != step.CandidateSHA || !paths[r.Path] { |
| 182 | return nil |
| 183 | } |
| 184 | delete(paths, r.Path) |
| 185 | files = append(files, r.file()) |
| 186 | } |
| 187 | if rows[0].Accepted { |
| 188 | return nil |
| 189 | } |
| 190 | if wire.DiffCollection(files) != collection { |
| 191 | return nil |
| 192 | } |
| 193 | if err := t.db.Model(&changeDiffRecord{}).Where("step_id = ? AND attempt = ? AND accepted = ?", step.ID, step.Attempt, false).Updates(map[string]any{"accepted": true, "expires_at": t.now().Add(7 * 24 * time.Hour)}).Error; err != nil { |
| 194 | return err |
| 195 | } |
| 196 | // Keep only a deadline after pruning bytes, so the device can distinguish |
| 197 | // expiry from an old runner that never uploaded display patches. |
| 198 | if err := t.db.Model(&stepRecord{}).Where("id = ? AND attempt = ?", step.ID, step.Attempt).Updates(map[string]any{"change_diff_expires_at": t.now().Add(7 * 24 * time.Hour), "change_diff_attempt": step.Attempt}).Error; err != nil { |
| 199 | return err |
| 200 | } |
| 201 | return t.auditPreview(l.Runner.RunnerID, "changes.accepted", &step, collection) |
| 202 | } |
| 203 | |
| 204 | func (s *Store) ChangeDiff(ctx context.Context, person, id, candidate, path string) (out wire.ChangeDiff, err error) { |
| 205 | err = s.read(ctx, func(db *gorm.DB) error { |
| 206 | if err := s.authority.CurrentPerson(ctx, db); err != nil { |
| 207 | return err |
| 208 | } |
| 209 | tx := &txn{s: s, db: db} |
| 210 | task, err := tx.loadTask(id) |
| 211 | if err != nil { |
| 212 | return err |
| 213 | } |
| 214 | view, err := tx.taskView(task) |
| 215 | if err != nil { |
| 216 | return err |
| 217 | } |
| 218 | if candidate != view.CandidateSHA { |
| 219 | return ErrDiffChanged |
| 220 | } |
| 221 | if !wire.ValidChangePath(path) { |
| 222 | return ErrNotFound |
| 223 | } |
| 224 | var step stepRecord |
| 225 | err = db.Where("task_id = ? AND specialist = ? AND candidate_sha = ? AND state = ? AND retired = ?", id, wire.SpecialistEngineering, candidate, wire.StepDone, false).Order("idx DESC").First(&step).Error |
| 226 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 227 | return ErrNotFound |
| 228 | } |
| 229 | if err != nil { |
| 230 | return err |
| 231 | } |
| 232 | facts := stepChangeFilesView(step) |
| 233 | if facts == nil { |
| 234 | return ErrNotFound |
| 235 | } |
| 236 | var entry *wire.ChangedFile |
| 237 | for i := range facts.Entries { |
| 238 | if facts.Entries[i].Path == path { |
| 239 | entry = &facts.Entries[i] |
| 240 | break |
| 241 | } |
| 242 | } |
| 243 | if entry == nil { |
| 244 | return ErrNotFound |
| 245 | } |
| 246 | out = wire.ChangeDiff{TaskID: id, StepID: step.ID, Attempt: step.Attempt, Base: facts.Base, Candidate: candidate, Status: entry.Status, OldPath: entry.OldPath, FileDiff: wire.FileDiff{Path: path, Reason: wire.DiffUnavailable}} |
| 247 | var row changeDiffRecord |
| 248 | err = db.Where("step_id = ? AND attempt = ? AND path = ? AND accepted = ?", step.ID, step.Attempt, path, true).First(&row).Error |
| 249 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 250 | if step.ChangeDiffAttempt == step.Attempt && step.ChangeDiffExpiresAt != nil && !step.ChangeDiffExpiresAt.After(s.now()) { |
| 251 | out.Reason = wire.DiffExpired |
| 252 | } |
| 253 | return nil |
| 254 | } |
| 255 | if err != nil { |
| 256 | return err |
| 257 | } |
| 258 | if !row.ExpiresAt.After(s.now()) { |
| 259 | out.Reason = wire.DiffExpired |
| 260 | return nil |
| 261 | } |
| 262 | if row.Candidate != candidate || row.Base != facts.Base || !wire.ValidFileDiff(row.file()) { |
| 263 | return nil |
| 264 | } |
| 265 | out.FileDiff = row.file() |
| 266 | out.HiddenCharacters = wire.PatchHasHiddenCharacters(out.Patch) |
| 267 | raw, err := json.Marshal(out) |
| 268 | if err != nil { |
| 269 | return err |
| 270 | } |
| 271 | if len(raw) > wire.MaxDiffResponseBytes { |
| 272 | out.FileDiff = wire.FileDiff{Path: path, Reason: wire.DiffTooLarge} |
| 273 | out.HiddenCharacters = false |
| 274 | } |
| 275 | // Same transaction/snapshot as task read; repeat roster and identity checks |
| 276 | // immediately before returning content. |
| 277 | if err := s.authority.CurrentPerson(ctx, db); err != nil { |
| 278 | return err |
| 279 | } |
| 280 | fresh, err := tx.loadTask(id) |
| 281 | if err != nil { |
| 282 | return err |
| 283 | } |
| 284 | newView, err := tx.taskView(fresh) |
| 285 | if err != nil { |
| 286 | return err |
| 287 | } |
| 288 | if newView.CandidateSHA != candidate { |
| 289 | return ErrDiffChanged |
| 290 | } |
| 291 | return nil |
| 292 | }) |
| 293 | if err != nil { |
| 294 | out = wire.ChangeDiff{} |
| 295 | } |
| 296 | return out, err |
| 297 | } |
| 298 | |
| 299 | func (h *HTTP) changeDiff(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| 300 | w.Header().Set("Cache-Control", "no-store") |
| 301 | out, err := h.Store.ChangeDiff(r.Context(), p.Address, chi.URLParam(r, "id"), r.URL.Query().Get("candidate_sha"), r.URL.Query().Get("path")) |
| 302 | if errors.Is(err, ErrDiffChanged) { |
| 303 | personapi.WriteError(w, r, 409, "preview_changed", nil) |
| 304 | return |
| 305 | } |
| 306 | if err != nil { |
| 307 | h.fail(w, r, err) |
| 308 | return |
| 309 | } |
| 310 | writeJSON(w, 200, out) |
| 311 | } |
| 312 | |
| 313 | // A newer pushed candidate makes the previous display collection obsolete, |
| 314 | // including candidates from old runners or Copy that upload no replacement. |
| 315 | func (t *txn) discardOldChangeDiffs(k taskRecord, s stepRecord) error { |
| 316 | if !s.Pushed || s.State != wire.StepDone || s.Retired || s.Specialist != wire.SpecialistEngineering && s.Specialist != wire.SpecialistCopy { |
| 317 | return nil |
| 318 | } |
| 319 | var steps []stepRecord |
| 320 | if err := t.db.Where("task_id = ? AND coalesce(retired, 0) = 0", k.ID).Order("idx").Find(&steps).Error; err != nil { |
| 321 | return err |
| 322 | } |
| 323 | current := progressFor(k, steps).candidate |
| 324 | if current == "" { |
| 325 | return nil |
| 326 | } |
| 327 | return t.db.Where("task_id = ? AND accepted = ? AND candidate <> ?", k.ID, true, current).Delete(&changeDiffRecord{}).Error |
| 328 | } |
| 329 | |