| 1 | package equipo |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "encoding/hex" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "strings" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/equipo/internal/equipo/team" |
| 13 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 14 | "gorm.io/gorm" |
| 15 | ) |
| 16 | |
| 17 | func requestValid(q RunnerRequest) bool { |
| 18 | return q.Version == 2 && q.RequestID != "" && len(q.RequestID) <= 256 && q.AssignmentID != "" |
| 19 | } |
| 20 | func binding(a runnerAssignment, q RunnerRequest) bool { |
| 21 | return a.TeamID == string(q.Scope.Account) && a.JobID == int64(q.Scope.Job) && a.AttemptID == int64(q.Handle.Attempt) && a.Fence == q.Handle.Fence && a.RunnerID == q.Handle.Runner |
| 22 | } |
| 23 | func (e *Execution) Mutate(ctx context.Context, p RunnerPrincipal, op string, q RunnerRequest) (any, error) { |
| 24 | if !requestValid(q) { |
| 25 | return nil, ErrInvalid |
| 26 | } |
| 27 | if op == "events" { |
| 28 | var event runnerproto.Event |
| 29 | if runnerproto.DecodeLimit(strings.NewReader(string(q.Event)), &event, runnerproto.MaxEventBytes+4096) != nil || event.AssignmentID != q.AssignmentID || event.Scope != q.Scope || event.Handle != q.Handle || event.ID != q.RequestID || event.ActionID != q.ActionID { |
| 30 | return nil, ErrInvalid |
| 31 | } |
| 32 | return nil, e.IngestRunnerEvent(ctx, p, event) |
| 33 | } |
| 34 | if op == "contained" { |
| 35 | if err := e.containmentBarrier(ctx, p, "", q); err != nil { |
| 36 | return nil, err |
| 37 | } |
| 38 | } |
| 39 | var result any |
| 40 | err := e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| 41 | if err := e.syncExposure(ctx, tx); err != nil { |
| 42 | return err |
| 43 | } |
| 44 | var a runnerAssignment |
| 45 | if err := tx.First(&a, "id=?", q.AssignmentID).Error; err != nil { |
| 46 | return storeError(err) |
| 47 | } |
| 48 | if !binding(a, q) { |
| 49 | return ErrForbidden |
| 50 | } |
| 51 | historical := op == "conclude" || op == "receipts" || op == "lost" || op == "contained" |
| 52 | value, err := assignmentValue(a) |
| 53 | if err != nil { |
| 54 | return err |
| 55 | } |
| 56 | if historical { |
| 57 | if _, err := runnerPrincipalAt(tx, p, e.store.runnerClock.Now().UTC()); err != nil { |
| 58 | return err |
| 59 | } |
| 60 | if a.RunnerID != p.RunnerID || a.Person != p.Person { |
| 61 | return ErrForbidden |
| 62 | } |
| 63 | } else { |
| 64 | value, err = e.assignmentCurrent(ctx, tx, p, a) |
| 65 | if err != nil { |
| 66 | return err |
| 67 | } |
| 68 | } |
| 69 | if (op == "complete" || (op == "artifacts" && q.Artifact != nil && q.Artifact.Role == team.RoleAnswer)) && a.Kind == "step" { |
| 70 | var state string |
| 71 | if err = tx.Raw("SELECT state FROM attempts WHERE id=? AND fence=?", q.Handle.Attempt, q.Handle.Fence).Row().Scan(&state); err != nil { |
| 72 | return err |
| 73 | } |
| 74 | if state == "succeeded" { |
| 75 | var task Task |
| 76 | if err = tx.First(&task, "id=?", a.TaskID).Error; err != nil { |
| 77 | return err |
| 78 | } |
| 79 | if task.Kind == "recommendation" || task.Kind == "investigation" { |
| 80 | if op == "complete" { |
| 81 | if q.Result == nil || q.Result.Outcome != team.OutcomeSuccess { |
| 82 | return ErrConflict |
| 83 | } |
| 84 | return nil |
| 85 | } |
| 86 | result, err = e.registerArtifactOnce(ctx, tx, a, q) |
| 87 | return err |
| 88 | } |
| 89 | } |
| 90 | } |
| 91 | if !historical { |
| 92 | if err := e.Core.AdmissionAvailable(ctx); err != nil { |
| 93 | return err |
| 94 | } |
| 95 | if a.State != "claimed" { |
| 96 | return ErrForbidden |
| 97 | } |
| 98 | if a.Kind == "step" { |
| 99 | if err := e.Core.ValidateHandle(ctx, q.Scope, q.Handle); err != nil { |
| 100 | return err |
| 101 | } |
| 102 | } else if !e.store.runnerClock.Now().Before(a.LeaseDeadline) { |
| 103 | return ErrForbidden |
| 104 | } |
| 105 | } |
| 106 | result, err = e.mutateAt(ctx, tx, a, value, op, q, false) |
| 107 | return err |
| 108 | }) |
| 109 | if err != nil { |
| 110 | return nil, err |
| 111 | } |
| 112 | return result, nil |
| 113 | } |
| 114 | func (e *Execution) Cleanup(ctx context.Context, token, op string, q RunnerRequest) (any, error) { |
| 115 | if !requestValid(q) || (op != "receipts" && op != "lost" && op != "contained") { |
| 116 | return nil, ErrForbidden |
| 117 | } |
| 118 | if op == "contained" { |
| 119 | rotation, found, err := e.recoverRotation(ctx, token, q) |
| 120 | if found || err != nil { |
| 121 | return rotation, err |
| 122 | } |
| 123 | if err := e.containmentBarrier(ctx, RunnerPrincipal{}, token, q); err != nil { |
| 124 | return nil, err |
| 125 | } |
| 126 | } |
| 127 | var result any |
| 128 | err := e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| 129 | var cleanup runnerCleanup |
| 130 | if err := tx.First(&cleanup, "token_hash=?", runnerHash(runnerproto.CleanupAudience, token)).Error; err != nil { |
| 131 | return storeError(err) |
| 132 | } |
| 133 | now := e.store.runnerClock.Now().UTC() |
| 134 | if cleanup.Audience != runnerproto.CleanupAudience || !now.Before(cleanup.ExpiresAt) || cleanup.AssignmentID != q.AssignmentID || cleanup.AttemptID != int64(q.Handle.Attempt) || cleanup.Fence != q.Handle.Fence { |
| 135 | return ErrForbidden |
| 136 | } |
| 137 | var runner runnerRecord |
| 138 | if err := tx.First(&runner, "id=?", cleanup.RunnerID).Error; err != nil { |
| 139 | return storeError(err) |
| 140 | } |
| 141 | instance, err := runnerInstance(tx) |
| 142 | if err != nil { |
| 143 | return err |
| 144 | } |
| 145 | if cleanup.InstanceID != instance || runner.InstanceID != instance || runner.Person != cleanup.Person || runner.MachineKeyHash != cleanup.MachineKeyHash { |
| 146 | return ErrForbidden |
| 147 | } |
| 148 | var a runnerAssignment |
| 149 | if err := tx.First(&a, "id=?", q.AssignmentID).Error; err != nil { |
| 150 | return storeError(err) |
| 151 | } |
| 152 | if !binding(a, q) || a.RunnerID != runner.ID || a.Person != runner.Person { |
| 153 | return ErrForbidden |
| 154 | } |
| 155 | value, err := assignmentValue(a) |
| 156 | if err != nil { |
| 157 | return err |
| 158 | } |
| 159 | result, err = e.mutateAt(ctx, tx, a, value, op, q, true) |
| 160 | return err |
| 161 | }) |
| 162 | if err != nil { |
| 163 | return nil, err |
| 164 | } |
| 165 | return result, nil |
| 166 | } |
| 167 | func observeRunner(tx *gorm.DB, a runnerAssignment, op string, q RunnerRequest, now time.Time) (bool, error) { |
| 168 | raw, err := json.Marshal(q) |
| 169 | if err != nil { |
| 170 | return false, err |
| 171 | } |
| 172 | sum := sha256.Sum256(raw) |
| 173 | hash := hex.EncodeToString(sum[:]) |
| 174 | var old runnerObservation |
| 175 | err = tx.First(&old, "assignment_id=? AND request_id=?", a.ID, q.RequestID).Error |
| 176 | if err == nil { |
| 177 | if old.Operation != op || old.PayloadHash != hash { |
| 178 | return false, ErrConflict |
| 179 | } |
| 180 | return true, nil |
| 181 | } |
| 182 | if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 183 | return false, storeError(err) |
| 184 | } |
| 185 | return false, storeError(tx.Create(&runnerObservation{AssignmentID: a.ID, RequestID: q.RequestID, Operation: op, PayloadHash: hash, Payload: string(raw), At: now}).Error) |
| 186 | } |
| 187 | func (e *Execution) mutateAt(ctx context.Context, tx *gorm.DB, a runnerAssignment, value Assignment, op string, q RunnerRequest, cleanup bool) (any, error) { |
| 188 | now := e.store.runnerClock.Now().UTC() |
| 189 | if op == "intend" || op == "admit" || op == "publication_ready" || op == "publication_authorize" { |
| 190 | if err := runnerTimelineAvailable(tx, a.ID); err != nil { |
| 191 | return nil, err |
| 192 | } |
| 193 | } |
| 194 | switch op { |
| 195 | case "validate": |
| 196 | return value.Selection, nil |
| 197 | case "conclude": |
| 198 | return e.concludeAt(ctx, tx, a, q) |
| 199 | case "evidence": |
| 200 | if a.Kind != "step" { |
| 201 | return nil, ErrInvalid |
| 202 | } |
| 203 | if q.ArtifactID > 0 { |
| 204 | return e.Core.Artifact(ctx, q.Scope, q.ArtifactID) |
| 205 | } |
| 206 | return e.Core.Artifacts(ctx, q.Scope) |
| 207 | case "freeze", "freeze_feature": |
| 208 | var frozen runnerproto.FreezeRequest |
| 209 | if a.Kind != "step" || runnerproto.DecodeLimit(strings.NewReader(string(q.Prepared)), &frozen, 8192) != nil { |
| 210 | return nil, ErrInvalid |
| 211 | } |
| 212 | if op == "freeze_feature" { |
| 213 | return nil, e.Core.FreezeFeatureEvidence(ctx, q.Scope, q.Handle, frozen.ReproductionHash, frozen.DefinitionHash) |
| 214 | } |
| 215 | return nil, e.Core.FreezeBugEvidence(ctx, q.Scope, q.Handle, frozen.ExpectedSymptom, frozen.DefinitionHash, frozen.ReproductionHash) |
| 216 | case "question_resolved": |
| 217 | return nil, e.resolveQuestion(ctx, tx, a, value, q) |
| 218 | case "questions": |
| 219 | return e.recordQuestion(ctx, tx, a, value, q) |
| 220 | case "answers": |
| 221 | return e.questionAnswers(ctx, tx, a) |
| 222 | case "renew": |
| 223 | deadline := now.Add(60 * time.Second) |
| 224 | if a.Kind == "step" { |
| 225 | var err error |
| 226 | deadline, err = e.Core.Renew(ctx, q.Scope, q.Handle) |
| 227 | if err != nil { |
| 228 | return nil, err |
| 229 | } |
| 230 | } |
| 231 | return deadline, storeError(tx.Model(&runnerAssignment{}).Where("id=?", a.ID).Select("LeaseDeadline").Updates(&runnerAssignment{LeaseDeadline: deadline}).Error) |
| 232 | case "publication_ready": |
| 233 | if a.Kind != "step" { |
| 234 | return nil, ErrInvalid |
| 235 | } |
| 236 | return e.Core.Publication(ctx, q.Scope, q.Handle) |
| 237 | case "publication_authorize": |
| 238 | if a.Kind != "step" { |
| 239 | return nil, ErrInvalid |
| 240 | } |
| 241 | return e.Core.AuthorizePublication(ctx, q.Scope, q.Handle, q.ActionID, q.RequestID) |
| 242 | case "intend": |
| 243 | if a.Kind != "step" || q.Intent == nil { |
| 244 | return nil, ErrInvalid |
| 245 | } |
| 246 | raw, _ := json.Marshal(q.Intent) |
| 247 | if len(raw) > runnerproto.MaxActionBytes { |
| 248 | return nil, ErrInvalid |
| 249 | } |
| 250 | return e.Core.Intend(ctx, q.Scope, q.Handle, *q.Intent) |
| 251 | case "admit": |
| 252 | if a.Kind != "step" { |
| 253 | return nil, ErrInvalid |
| 254 | } |
| 255 | return e.Core.AdmitOnce(ctx, q.Scope, q.Handle, q.ActionID, q.RequestID) |
| 256 | case "receipts", "lost": |
| 257 | // Authenticated runners and cleanup holders report observations, not trusted |
| 258 | // billing receipts. Reconciliation validators perform settlement later. |
| 259 | action, err := e.Core.GetAction(ctx, q.Scope, q.ActionID) |
| 260 | if err != nil { |
| 261 | return nil, err |
| 262 | } |
| 263 | if action.Attempt != q.Handle.Attempt || action.Fence != q.Handle.Fence { |
| 264 | return nil, ErrForbidden |
| 265 | } |
| 266 | if op == "receipts" && q.Receipt == nil { |
| 267 | return nil, ErrInvalid |
| 268 | } |
| 269 | _, err = observeRunner(tx, a, op, q, now) |
| 270 | if err != nil { |
| 271 | return nil, err |
| 272 | } |
| 273 | if op == "lost" && (action.State == team.ActionDispatching || action.State == team.ActionUncertain) { |
| 274 | return nil, e.Core.Lost(ctx, q.Scope, q.ActionID, "runner_unknown_outcome") |
| 275 | } |
| 276 | if !cleanup && op == "receipts" && e.validators.Receipt != nil { |
| 277 | receipt, err := e.validators.Receipt(ctx, value, q) |
| 278 | if err != nil { |
| 279 | return nil, err |
| 280 | } |
| 281 | return nil, e.recordVerifiedReceipt(ctx, tx, a, q, receipt) |
| 282 | } |
| 283 | return nil, nil |
| 284 | case "contained": |
| 285 | if e.validators.Containment == nil { |
| 286 | return nil, ErrUnavailable |
| 287 | } |
| 288 | retry, err := observeRunner(tx, a, op, q, now) |
| 289 | if err != nil { |
| 290 | return nil, err |
| 291 | } |
| 292 | if retry || a.State == "contained" { |
| 293 | return CredentialRotation{}, nil |
| 294 | } |
| 295 | if err := e.validators.Containment(ctx, value, q); err != nil { |
| 296 | return nil, err |
| 297 | } |
| 298 | if a.Kind == "step" { |
| 299 | if err := e.Core.ContainUntrusted(ctx, q.Scope, q.Handle); err != nil { |
| 300 | return nil, err |
| 301 | } |
| 302 | } |
| 303 | if err := tx.Model(&runnerAssignment{}).Where("id=?", a.ID).Select("State").Updates(&runnerAssignment{State: "contained"}).Error; err != nil { |
| 304 | return nil, storeError(err) |
| 305 | } |
| 306 | if err := finishTaskCancellation(tx, a.TaskID); err != nil { |
| 307 | return nil, err |
| 308 | } |
| 309 | return e.rotateContained(tx, a, q, now, true) |
| 310 | case "stop": |
| 311 | if a.Kind == "step" { |
| 312 | return nil, e.Core.StopAttempt(ctx, q.Scope, q.Handle, "runner_stop") |
| 313 | } |
| 314 | return nil, storeError(tx.Model(&runnerAssignment{}).Where("id=?", a.ID).Select("State").Updates(&runnerAssignment{State: "fenced"}).Error) |
| 315 | case "release": |
| 316 | if a.Kind != "step" { |
| 317 | return nil, ErrInvalid |
| 318 | } |
| 319 | return nil, e.Core.Release(ctx, q.Scope, q.Handle, q.Reason, "runner_release") |
| 320 | case "complete": |
| 321 | if a.Kind != "step" || q.Result == nil { |
| 322 | return nil, ErrInvalid |
| 323 | } |
| 324 | if err := e.Core.Complete(ctx, q.Scope, q.Handle, *q.Result); err != nil { |
| 325 | return nil, err |
| 326 | } |
| 327 | if q.Result.Outcome == team.OutcomeFailure { |
| 328 | return nil, storeError(tx.Model(&Task{}).Where("id=?", a.TaskID).Select("State").Updates(&Task{State: "failed"}).Error) |
| 329 | } |
| 330 | return nil, nil |
| 331 | case "prepare": |
| 332 | if a.Kind != "prepare" || e.validators.Prepare == nil { |
| 333 | return nil, ErrUnavailable |
| 334 | } |
| 335 | prepared, err := e.validators.Prepare(ctx, value, q) |
| 336 | if err != nil { |
| 337 | return nil, err |
| 338 | } |
| 339 | var task Task |
| 340 | if err := tx.First(&task, "id=?", a.TaskID).Error; err != nil { |
| 341 | return nil, storeError(err) |
| 342 | } |
| 343 | // The validated payload is applied through Task 7's transaction checks. |
| 344 | var credential runnerCredentialRecord |
| 345 | if err := tx.Where("runner_id=? AND revoked_at IS NULL AND expires_at>?", a.RunnerID, now).First(&credential).Error; err != nil { |
| 346 | return nil, storeError(err) |
| 347 | } |
| 348 | task, err = e.store.PrepareBug(ctx, RunnerPrincipal{RunnerID: a.RunnerID, Person: a.Person, CredentialID: credential.ID}, task.ID, task.Revision, prepared) |
| 349 | if err != nil { |
| 350 | return nil, err |
| 351 | } |
| 352 | return task, storeError(tx.Model(&runnerAssignment{}).Where("id=?", a.ID).Select("State").Updates(&runnerAssignment{State: "prepared"}).Error) |
| 353 | case "artifacts": |
| 354 | if a.Kind != "step" || q.Artifact == nil || len(q.Artifact.Payload) > runnerproto.MaxArtifactBytes { |
| 355 | return nil, ErrInvalid |
| 356 | } |
| 357 | art, err := e.registerArtifactOnce(ctx, tx, a, q) |
| 358 | if err != nil { |
| 359 | return nil, err |
| 360 | } |
| 361 | if q.Artifact.Role == team.RoleAnswer { |
| 362 | if err = e.Core.Complete(ctx, q.Scope, q.Handle, team.AttemptResult{Outcome: team.OutcomeSuccess}); err != nil { |
| 363 | return nil, err |
| 364 | } |
| 365 | if err = e.deliverAnswerAt(ctx, tx, a, q); err != nil { |
| 366 | return nil, err |
| 367 | } |
| 368 | } |
| 369 | return art, nil |
| 370 | } |
| 371 | return nil, ErrInvalid |
| 372 | } |
| 373 | |
| 374 | func (e *Execution) ReadArtifact(ctx context.Context, p RunnerPrincipal, q RunnerRequest, id team.ArtifactID) (team.Artifact, error) { |
| 375 | if !requestValid(q) { |
| 376 | return team.Artifact{}, ErrInvalid |
| 377 | } |
| 378 | var result team.Artifact |
| 379 | err := e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| 380 | var a runnerAssignment |
| 381 | if err := tx.First(&a, "id=?", q.AssignmentID).Error; err != nil { |
| 382 | return storeError(err) |
| 383 | } |
| 384 | if !binding(a, q) || a.State != "claimed" { |
| 385 | return ErrForbidden |
| 386 | } |
| 387 | if _, err := e.assignmentCurrent(ctx, tx, p, a); err != nil { |
| 388 | return err |
| 389 | } |
| 390 | if err := e.Core.ValidateHandle(ctx, q.Scope, q.Handle); err != nil { |
| 391 | return err |
| 392 | } |
| 393 | var err error |
| 394 | result, err = e.Core.Artifact(ctx, q.Scope, id) |
| 395 | return err |
| 396 | }) |
| 397 | if err != nil { |
| 398 | return team.Artifact{}, err |
| 399 | } |
| 400 | return result, nil |
| 401 | } |
| 402 | |