| 1 | package equipo |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "encoding/hex" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "time" |
| 10 | |
| 11 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 12 | "gorm.io/gorm" |
| 13 | "gorm.io/gorm/clause" |
| 14 | ) |
| 15 | |
| 16 | func (e *Execution) rotateContained(tx *gorm.DB, a runnerAssignment, q RunnerRequest, now time.Time, allowLive bool) (CredentialRotation, error) { |
| 17 | result := CredentialRotation{CleanupTokens: map[string]string{}} |
| 18 | var runner runnerRecord |
| 19 | if err := tx.First(&runner, "id=?", a.RunnerID).Error; err != nil { |
| 20 | return result, storeError(err) |
| 21 | } |
| 22 | var credentials []runnerCredentialRecord |
| 23 | if err := tx.Where("runner_id=? AND revoked_at IS NULL AND expires_at>?", a.RunnerID, now).Find(&credentials).Error; err != nil { |
| 24 | return result, storeError(err) |
| 25 | } |
| 26 | live := allowLive && runner.RevokedAt == nil && len(credentials) > 0 |
| 27 | if _, err := currentRunnerMember(tx, runner.Person); err != nil { |
| 28 | if !errors.Is(err, ErrForbidden) && !errors.Is(err, ErrNotFound) { |
| 29 | return result, err |
| 30 | } |
| 31 | live = false |
| 32 | } |
| 33 | if err := tx.Model(&runnerCredentialRecord{}).Where("runner_id=? AND revoked_at IS NULL", a.RunnerID).Select("RevokedAt").Updates(&runnerCredentialRecord{RevokedAt: &now}).Error; err != nil { |
| 34 | return result, storeError(err) |
| 35 | } |
| 36 | rotation := runnerRotation{RunnerID: a.RunnerID, AssignmentID: a.ID, RequestID: q.RequestID, State: "cleanup_only"} |
| 37 | if live { |
| 38 | credential, err := mintRunnerCredential(tx, runner, now) |
| 39 | if err != nil { |
| 40 | return result, err |
| 41 | } |
| 42 | // Rotation cannot extend the predecessor's remaining authority. |
| 43 | expiry := credentials[0].ExpiresAt |
| 44 | for _, c := range credentials { |
| 45 | if c.ExpiresAt.Before(expiry) { |
| 46 | expiry = c.ExpiresAt |
| 47 | } |
| 48 | } |
| 49 | credential.ExpiresAt = expiry |
| 50 | if err := tx.Model(&runnerCredentialRecord{}).Where("id=?", credential.CredentialID).Select("ExpiresAt").Updates(&runnerCredentialRecord{ExpiresAt: expiry}).Error; err != nil { |
| 51 | return result, storeError(err) |
| 52 | } |
| 53 | result.Bearer = credential |
| 54 | rotation.State = "pending" |
| 55 | rotation.CredentialID = credential.CredentialID |
| 56 | } |
| 57 | var cleanups []runnerCleanup |
| 58 | if err := tx.Where("runner_id=?", a.RunnerID).Find(&cleanups).Error; err != nil { |
| 59 | return result, storeError(err) |
| 60 | } |
| 61 | for _, c := range cleanups { |
| 62 | if c.AssignmentID == a.ID { |
| 63 | raw, err := json.Marshal(c) |
| 64 | if err != nil { |
| 65 | return result, err |
| 66 | } |
| 67 | recovery := runnerObservation{AssignmentID: a.ID, RequestID: "rotation/" + q.RequestID, Operation: "rotation_recovery", Payload: string(raw), At: now} |
| 68 | if err = tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&recovery).Error; err != nil { |
| 69 | return result, storeError(err) |
| 70 | } |
| 71 | } |
| 72 | token := runnerSecret() |
| 73 | if err := tx.Model(&runnerCleanup{}).Where("id=?", c.ID).Select("TokenHash").Updates(&runnerCleanup{TokenHash: runnerHash(runnerproto.CleanupAudience, token)}).Error; err != nil { |
| 74 | return result, storeError(err) |
| 75 | } |
| 76 | if now.Before(c.ExpiresAt) { |
| 77 | result.CleanupTokens[c.AssignmentID] = token |
| 78 | } |
| 79 | } |
| 80 | if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "runner_id"}}, DoUpdates: clause.AssignmentColumns([]string{"assignment_id", "request_id", "state", "credential_id"})}).Create(&rotation).Error; err != nil { |
| 81 | return result, storeError(err) |
| 82 | } |
| 83 | return result, appendAudit(tx, Actor{Address: a.Person}, "runner.containment.rotate", a.ID) |
| 84 | } |
| 85 | |
| 86 | // AcknowledgeRotation is called only after the runner durably journals all of |
| 87 | // the replacement credentials. Until this acknowledgement admission is closed. |
| 88 | func (e *Execution) AcknowledgeRotation(ctx context.Context, p RunnerPrincipal, requestID string) error { |
| 89 | return e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| 90 | if _, err := runnerPrincipalAt(tx, p, e.store.runnerClock.Now().UTC()); err != nil { |
| 91 | return err |
| 92 | } |
| 93 | var rotation runnerRotation |
| 94 | if err := tx.First(&rotation, "runner_id=?", p.RunnerID).Error; err != nil { |
| 95 | return storeError(err) |
| 96 | } |
| 97 | if rotation.CredentialID != p.CredentialID || rotation.RequestID != requestID || (rotation.State != "pending" && rotation.State != "ready") { |
| 98 | return ErrForbidden |
| 99 | } |
| 100 | return storeError(tx.Model(&runnerRotation{}).Where("runner_id=?", p.RunnerID).Select("State").Updates(&runnerRotation{State: "ready"}).Error) |
| 101 | }) |
| 102 | } |
| 103 | |
| 104 | // Commit the admission barrier before changing credentials. If the second |
| 105 | // transaction fails, the runner remains blocked and can retry containment. |
| 106 | func (e *Execution) containmentBarrier(ctx context.Context, p RunnerPrincipal, token string, q RunnerRequest) error { |
| 107 | if e.validators.Containment == nil { |
| 108 | return ErrUnavailable |
| 109 | } |
| 110 | return e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| 111 | var a runnerAssignment |
| 112 | if err := tx.First(&a, "id=?", q.AssignmentID).Error; err != nil { |
| 113 | return storeError(err) |
| 114 | } |
| 115 | if a.ProtocolVersion != runnerproto.DirectVersion { |
| 116 | return ErrForbidden |
| 117 | } |
| 118 | if !binding(a, q) { |
| 119 | return ErrForbidden |
| 120 | } |
| 121 | now := e.store.runnerClock.Now().UTC() |
| 122 | if token == "" { |
| 123 | if _, err := runnerPrincipalAt(tx, p, now); err != nil { |
| 124 | return err |
| 125 | } |
| 126 | if a.RunnerID != p.RunnerID || a.Person != p.Person { |
| 127 | return ErrForbidden |
| 128 | } |
| 129 | } else { |
| 130 | var c runnerCleanup |
| 131 | if err := tx.First(&c, "token_hash=?", runnerHash(runnerproto.CleanupAudience, token)).Error; err != nil { |
| 132 | return storeError(err) |
| 133 | } |
| 134 | instance, err := runnerInstance(tx) |
| 135 | if err != nil { |
| 136 | return err |
| 137 | } |
| 138 | var r runnerRecord |
| 139 | if err := tx.First(&r, "id=?", a.RunnerID).Error; err != nil { |
| 140 | return storeError(err) |
| 141 | } |
| 142 | if c.AssignmentID != a.ID || c.RunnerID != a.RunnerID || c.Person != a.Person || c.Audience != runnerproto.CleanupAudience || c.InstanceID != instance || r.InstanceID != instance || c.MachineKeyHash != r.MachineKeyHash || c.AttemptID != a.AttemptID || c.Fence != a.Fence || !now.Before(c.ExpiresAt) { |
| 143 | return ErrForbidden |
| 144 | } |
| 145 | } |
| 146 | var prior runnerObservation |
| 147 | err := tx.First(&prior, "assignment_id=? AND request_id=?", a.ID, q.RequestID).Error |
| 148 | if err == nil || a.State == "contained" { |
| 149 | return nil |
| 150 | } |
| 151 | if !errors.Is(err, gorm.ErrRecordNotFound) { |
| 152 | return storeError(err) |
| 153 | } |
| 154 | value, err := assignmentValue(a) |
| 155 | if err != nil { |
| 156 | return err |
| 157 | } |
| 158 | if err := e.validators.Containment(ctx, value, q); err != nil { |
| 159 | return err |
| 160 | } |
| 161 | rotation := runnerRotation{RunnerID: a.RunnerID, AssignmentID: a.ID, RequestID: q.RequestID, State: "containing"} |
| 162 | if err := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "runner_id"}}, DoUpdates: clause.AssignmentColumns([]string{"assignment_id", "request_id", "state", "credential_id"})}).Create(&rotation).Error; err != nil { |
| 163 | return storeError(err) |
| 164 | } |
| 165 | return appendAudit(tx, Actor{Address: a.Person}, "runner.containment.pending", a.ID) |
| 166 | }) |
| 167 | } |
| 168 | |
| 169 | // A lost rotation reply may be recovered with the predecessor cleanup token, |
| 170 | // only for the original containment request while admission remains blocked. |
| 171 | func (e *Execution) recoverRotation(ctx context.Context, token string, q RunnerRequest) (CredentialRotation, bool, error) { |
| 172 | var result CredentialRotation |
| 173 | found := false |
| 174 | err := e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| 175 | var rotation runnerRotation |
| 176 | err := tx.First(&rotation, "assignment_id=? AND request_id=? AND state IN ?", q.AssignmentID, q.RequestID, []string{"pending", "cleanup_only"}).Error |
| 177 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 178 | return nil |
| 179 | } |
| 180 | if err != nil { |
| 181 | return storeError(err) |
| 182 | } |
| 183 | var recovery runnerObservation |
| 184 | err = tx.First(&recovery, "assignment_id=? AND request_id=? AND operation=?", q.AssignmentID, "rotation/"+q.RequestID, "rotation_recovery").Error |
| 185 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 186 | return nil |
| 187 | } |
| 188 | if err != nil { |
| 189 | return storeError(err) |
| 190 | } |
| 191 | var saved runnerCleanup |
| 192 | if json.Unmarshal([]byte(recovery.Payload), &saved) != nil { |
| 193 | return ErrUnavailable |
| 194 | } |
| 195 | if saved.TokenHash != runnerHash(runnerproto.CleanupAudience, token) { |
| 196 | return nil |
| 197 | } |
| 198 | found = true |
| 199 | now := e.store.runnerClock.Now().UTC() |
| 200 | if !now.Before(saved.ExpiresAt) || saved.AttemptID != int64(q.Handle.Attempt) || saved.Fence != q.Handle.Fence { |
| 201 | return ErrForbidden |
| 202 | } |
| 203 | var a runnerAssignment |
| 204 | if err = tx.First(&a, "id=?", q.AssignmentID).Error; err != nil { |
| 205 | return storeError(err) |
| 206 | } |
| 207 | if !binding(a, q) || a.State != "contained" || rotation.RunnerID != a.RunnerID || saved.RunnerID != a.RunnerID { |
| 208 | return ErrForbidden |
| 209 | } |
| 210 | var original runnerObservation |
| 211 | if err = tx.First(&original, "assignment_id=? AND request_id=? AND operation='contained'", a.ID, q.RequestID).Error; err != nil { |
| 212 | return storeError(err) |
| 213 | } |
| 214 | raw, _ := json.Marshal(q) |
| 215 | sum := sha256.Sum256(raw) |
| 216 | if hex.EncodeToString(sum[:]) != original.PayloadHash { |
| 217 | return ErrConflict |
| 218 | } |
| 219 | result, err = e.rotateContained(tx, a, q, now, rotation.State == "pending" && !now.Before(recovery.At) && now.Before(recovery.At.Add(5*time.Minute))) |
| 220 | return err |
| 221 | }) |
| 222 | return result, found, err |
| 223 | } |
| 224 | |