| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "regexp" |
| 6 | "strconv" |
| 7 | |
| 8 | "amadan.net/oficina/equipo/internal/wire" |
| 9 | ) |
| 10 | |
| 11 | // Preview steps (release preview slice): an approved candidate's static |
| 12 | // output published to a temporary Carloku site. They are ancillary: |
| 13 | // progress skips them, so a preview never moves a task or asks anything. |
| 14 | |
| 15 | var ( |
| 16 | previewDigest = regexp.MustCompile(`^[0-9a-f]{64}$`) |
| 17 | previewURL = regexp.MustCompile(`^https://(tmp|eq)-[a-z0-9-]+\.[a-z0-9-]+(\.[a-z0-9-]+)+/$`) |
| 18 | ) |
| 19 | |
| 20 | func decodePreview(raw string) *wire.PreviewResult { |
| 21 | if raw == "" { |
| 22 | return nil |
| 23 | } |
| 24 | var p wire.PreviewResult |
| 25 | if json.Unmarshal([]byte(raw), &p) != nil { |
| 26 | return nil |
| 27 | } |
| 28 | return &p |
| 29 | } |
| 30 | |
| 31 | // schedulePreview places one preview step for the approved candidate, |
| 32 | // once: only when Review said the candidate has a preview config, and |
| 33 | // only on a primary that speaks wire.ProtocolInjectionDefences. |
| 34 | func (t *txn) schedulePreview(k *taskRecord) error { |
| 35 | steps, err := t.steps(k.ID) |
| 36 | if err != nil { |
| 37 | return err |
| 38 | } |
| 39 | p := progressFor(*k, steps) |
| 40 | if p.moved || p.candidate == "" || p.review == nil || p.review.State != wire.StepDone || p.review.Verdict != wire.VerdictApprove || !p.review.HasPreview || p.eng == nil { |
| 41 | return nil |
| 42 | } |
| 43 | autonomy, err := t.projectAutonomy(k.ProjectID) |
| 44 | if err != nil { |
| 45 | return err |
| 46 | } |
| 47 | if autonomy.PublicPreviews && !autonomy.PublicPreviewsSince.IsZero() && (p.review.FinishedAt == nil || !p.review.FinishedAt.After(autonomy.PublicPreviewsSince)) { |
| 48 | // An old approval is not a new publication decision when the setting changes. |
| 49 | rs, err := t.runners(p.eng.Person) |
| 50 | if err != nil { |
| 51 | return err |
| 52 | } |
| 53 | for _, r := range rs { |
| 54 | if r.Role == wire.RolePrimary && r.Hello.Capabilities != nil && r.Hello.Capabilities.PreviewHost != nil && r.Hello.Capabilities.PreviewHost.Kind == wire.PreviewHostCarlokuTemp { |
| 55 | return nil |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | for _, s := range steps { |
| 60 | if s.Specialist == wire.SpecialistPreview && s.CandidateSHA == p.candidate { |
| 61 | return nil |
| 62 | } |
| 63 | } |
| 64 | primary, err := t.s.authority.PrimaryRunner(t.db, p.eng.Person) |
| 65 | if err != nil || primary == "" { |
| 66 | return err |
| 67 | } |
| 68 | rs, err := t.runners(p.eng.Person) |
| 69 | if err != nil { |
| 70 | return err |
| 71 | } |
| 72 | for _, r := range rs { |
| 73 | // The current host and project setting govern scheduling. |
| 74 | if r.ID == primary { |
| 75 | if reason, err := t.previewHostAuthority(k.ProjectID, r); err != nil || reason != "" { |
| 76 | return err |
| 77 | } |
| 78 | return t.nextStep(k, steps, stepRecord{Specialist: wire.SpecialistPreview, Person: p.eng.Person, Round: p.eng.Round, BaseSHA: k.BaseSHA, CandidateSHA: p.candidate}) |
| 79 | } |
| 80 | } |
| 81 | return nil |
| 82 | } |
| 83 | |
| 84 | // authorizePreview decides a preview step's start and each publish check |
| 85 | // (spec §1.4): the current attempt, on the primary at protocol 28, of a |
| 86 | // task not cancelled, whose newest candidate is the step's and approved, |
| 87 | // whose creator is still an owner; a publish check also needs the |
| 88 | // recorded built digest, and exactly it. Every decision is audited. |
| 89 | func (t *txn) authorizePreview(l Lease, s *stepRecord, purpose, digest string) (string, error) { |
| 90 | refused, err := t.previewRefusal(l, s, purpose, digest) |
| 91 | if err != nil { |
| 92 | return "", err |
| 93 | } |
| 94 | outcome := "allowed" |
| 95 | if refused != "" { |
| 96 | outcome = "refused:" + refused |
| 97 | } |
| 98 | if err := t.auditPreview(l.Runner.RunnerID, "preview.authorize", s, purpose+":"+outcome+":"+shortDigest(digest)); err != nil { |
| 99 | return "", err |
| 100 | } |
| 101 | return refused, nil |
| 102 | } |
| 103 | |
| 104 | func (t *txn) previewRefusal(l Lease, s *stepRecord, purpose, digest string) (string, error) { |
| 105 | if l.Protocol < wire.ProtocolInjectionDefences || purpose != "" && purpose != wire.LeasePurposePreview { |
| 106 | return "withdrawn", nil |
| 107 | } |
| 108 | primary, err := t.s.authority.PrimaryRunner(t.db, s.Person) |
| 109 | if err != nil { |
| 110 | return "", err |
| 111 | } |
| 112 | k, err := t.loadTask(s.TaskID) |
| 113 | if err != nil { |
| 114 | return "", err |
| 115 | } |
| 116 | if primary != l.Runner.RunnerID || k.CancelRequested || k.Stage == wire.StageCancelled || t.isOwner(k.Creator) != nil { |
| 117 | return "withdrawn", nil |
| 118 | } |
| 119 | rs, err := t.runners(s.Person) |
| 120 | if err != nil { |
| 121 | return "", err |
| 122 | } |
| 123 | found, publicHost := false, false |
| 124 | for _, r := range rs { |
| 125 | if r.ID == l.Runner.RunnerID { |
| 126 | found = true |
| 127 | publicHost = r.Hello.Capabilities != nil && r.Hello.Capabilities.PreviewHost != nil && r.Hello.Capabilities.PreviewHost.Kind == wire.PreviewHostCarlokuTemp |
| 128 | if reason, err := t.previewHostAuthority(k.ProjectID, r); reason != "" || err != nil { |
| 129 | return reason, err |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | if !found { |
| 134 | return "preview_host", nil |
| 135 | } |
| 136 | steps, err := t.steps(k.ID) |
| 137 | if err != nil { |
| 138 | return "", err |
| 139 | } |
| 140 | p := progressFor(k, steps) |
| 141 | // The approved candidate while the branch is at it, or once the task |
| 142 | // is done the commit a preview of it builds (its merged commit). |
| 143 | if !previewMayBuild(k, p, s.CandidateSHA) { |
| 144 | return "withdrawn", nil |
| 145 | } |
| 146 | grant := previewGrant(*s) |
| 147 | if grant.Digest != "" { |
| 148 | if grant.Candidate != s.CandidateSHA || t.isOwner(grant.Owner) != nil { |
| 149 | return "withdrawn", nil |
| 150 | } |
| 151 | if purpose == wire.LeasePurposePreview && grant.Digest != digest { |
| 152 | return "withdrawn", nil |
| 153 | } |
| 154 | } |
| 155 | if publicHost && grant.Digest == "" { |
| 156 | autonomy, err := t.projectAutonomy(k.ProjectID) |
| 157 | if err != nil { |
| 158 | return "", err |
| 159 | } |
| 160 | if !autonomy.PublicPreviewsSince.IsZero() && (p.review.FinishedAt == nil || !p.review.FinishedAt.After(autonomy.PublicPreviewsSince)) { |
| 161 | return "withdrawn", nil |
| 162 | } |
| 163 | } |
| 164 | if purpose != wire.LeasePurposePreview { |
| 165 | return "", nil |
| 166 | } |
| 167 | built := decodePreview(s.Preview) |
| 168 | if built == nil || built.Digest == "" { |
| 169 | return wire.RefusedPreviewNotBuilt, nil |
| 170 | } |
| 171 | if digest != built.Digest { |
| 172 | return "withdrawn", nil |
| 173 | } |
| 174 | return "", nil |
| 175 | } |
| 176 | |
| 177 | // previewBuilt records a running preview report's export, once per |
| 178 | // attempt, from the primary at protocol 28. |
| 179 | func previewBuilt(l Lease, role string, s *stepRecord, v *wire.StepReport) bool { |
| 180 | b := v.Preview |
| 181 | if s.Specialist != wire.SpecialistPreview || b == nil || b.Phase != wire.PreviewBuilt || s.Preview != "" || role != wire.RolePrimary || l.Protocol < wire.ProtocolInjectionDefences { |
| 182 | return false |
| 183 | } |
| 184 | if !previewDigest.MatchString(b.Digest) || b.Files < 1 || b.Files > 2000 || b.Bytes < 0 || b.Bytes > 50<<20 { |
| 185 | return false |
| 186 | } |
| 187 | raw, _ := json.Marshal(wire.PreviewResult{Phase: wire.PreviewBuilt, Digest: b.Digest, Files: b.Files, Bytes: b.Bytes}) |
| 188 | s.Preview = string(raw) |
| 189 | return true |
| 190 | } |
| 191 | |
| 192 | // acceptPreviewDone judges a preview step's final report: from the |
| 193 | // primary at protocol 28, for this task's app, the export recorded as |
| 194 | // built, deployed with its URL or unconfirmed. ok false ignores it. |
| 195 | func acceptPreviewDone(l Lease, role string, s *stepRecord, v *wire.StepReport) (string, bool) { |
| 196 | d := v.Preview |
| 197 | built := decodePreview(s.Preview) |
| 198 | if d == nil || built == nil || d.Phase != wire.PreviewDone || role != wire.RolePrimary || l.Protocol < wire.ProtocolInjectionDefences || !v.Termination { |
| 199 | return "", false |
| 200 | } |
| 201 | // An unconfirmed outcome may come without the digest (a restart that |
| 202 | // lost the export's marker): it is still this attempt's outcome. |
| 203 | // The app is the task's on its preview host: tmp-<task> on Carloku |
| 204 | // temporary sites, eq-<task> on a CARLOS devbox. |
| 205 | if d.App != "tmp-"+s.TaskID && d.App != "eq-"+s.TaskID || d.Digest != built.Digest && (d.Outcome != wire.PreviewUnconfirmed || d.Digest != "") { |
| 206 | return "", false |
| 207 | } |
| 208 | out := wire.PreviewResult{Phase: wire.PreviewDone, App: d.App, Digest: built.Digest, Files: built.Files, Bytes: built.Bytes, Outcome: d.Outcome} |
| 209 | switch d.Outcome { |
| 210 | case wire.PreviewDeployed: |
| 211 | if !previewURL.MatchString(d.URL) || len(d.URL) > 200 || d.URL[len("https://"):len("https://")+len(d.App)+1] != d.App+"." { |
| 212 | return "", false |
| 213 | } |
| 214 | if d.Unsafe && previewGrant(*s).Digest != built.Digest { |
| 215 | return "", false |
| 216 | } |
| 217 | out.Unsafe = previewGrant(*s).Digest == built.Digest |
| 218 | out.URL, out.ExpiresAt, out.Version = d.URL, d.ExpiresAt, clipVersion(d.Version) |
| 219 | case wire.PreviewUnconfirmed: |
| 220 | default: |
| 221 | return "", false |
| 222 | } |
| 223 | raw, _ := json.Marshal(out) |
| 224 | return string(raw), true |
| 225 | } |
| 226 | |
| 227 | func clipVersion(v string) string { |
| 228 | if len(v) > 64 { |
| 229 | return "" |
| 230 | } |
| 231 | return v |
| 232 | } |
| 233 | |
| 234 | func shortDigest(d string) string { return d[:min(len(d), 12)] } |
| 235 | |
| 236 | // auditPreview writes one audit row for a preview action, with no |
| 237 | // credential: the step, attempt and candidate, then what happened. |
| 238 | func (t *txn) auditPreview(actor, kind string, s *stepRecord, what string) error { |
| 239 | if t.s.authority.Audit == nil { |
| 240 | return nil |
| 241 | } |
| 242 | return t.s.authority.Audit(t.db, "runner:"+actor, kind, s.TaskID+"/"+s.ID+"/"+strconv.FormatInt(s.Attempt, 10)+"@"+short(s.CandidateSHA)+":"+what) |
| 243 | } |
| 244 | |
| 245 | // fencePreviews settles every queued or running preview step placed on a |
| 246 | // runner that connects below wire.ProtocolInjectionDefences: a dispatch it has not |
| 247 | // received is retired, one it may hold is cancelled, and the step ends |
| 248 | // runner_outdated. Nothing is published by it. |
| 249 | func (t *txn) fencePreviews(l Lease) error { |
| 250 | if l.Protocol >= wire.ProtocolInjectionDefences { |
| 251 | return nil |
| 252 | } |
| 253 | var held []stepRecord |
| 254 | if err := t.db.Where("runner_id = ? AND specialist = ? AND state IN ?", l.Runner.RunnerID, wire.SpecialistPreview, []string{wire.StepQueued, wire.StepRunning}).Find(&held).Error; err != nil { |
| 255 | return err |
| 256 | } |
| 257 | for i := range held { |
| 258 | s := &held[i] |
| 259 | k, err := t.loadTask(s.TaskID) |
| 260 | if err != nil { |
| 261 | return err |
| 262 | } |
| 263 | now := t.now() |
| 264 | res := t.db.Model(&commandRecord{}).Where("runner_id = ? AND kind = ? AND acked_at IS NULL AND body LIKE ?", s.RunnerID, wire.FrameDispatch, `%"step_id":"`+s.ID+`"%`).Update("acked_at", now) |
| 265 | if res.Error != nil { |
| 266 | return res.Error |
| 267 | } |
| 268 | if res.RowsAffected == 0 && s.State == wire.StepRunning { |
| 269 | if err := t.commandTo(s.RunnerID, s.Person, wire.FrameCancelStep, wire.CancelStepCommand{Person: s.Person, TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt}); err != nil { |
| 270 | return err |
| 271 | } |
| 272 | } |
| 273 | s.State, s.Reason, s.Terminated, s.FinishedAt = wire.StepCancelled, wire.ReasonRunnerOutdated, true, &now |
| 274 | if err := t.auditPreview(l.Runner.RunnerID, "preview.failed", s, wire.ReasonRunnerOutdated); err != nil { |
| 275 | return err |
| 276 | } |
| 277 | if err := t.saveStep(s, &k); err != nil { |
| 278 | return err |
| 279 | } |
| 280 | } |
| 281 | return nil |
| 282 | } |
| 283 | |
| 284 | // settlePreview ends a preview attempt that started but cannot run on and |
| 285 | // gave no outcome (withdrawn, its runner removed): once its export was |
| 286 | // recorded as built it may have published, so it is done and could not be |
| 287 | // confirmed; before that nothing was published and it is cancelled. |
| 288 | // Either way no replacement attempt follows. The caller saves the step. |
| 289 | func (t *txn) settlePreview(k *taskRecord, s *stepRecord) error { |
| 290 | now := t.now() |
| 291 | s.Terminated, s.FinishedAt, s.Withdrawn = true, &now, false |
| 292 | kind := "preview.failed" |
| 293 | if built := decodePreview(s.Preview); built != nil && built.Digest != "" { |
| 294 | raw, _ := json.Marshal(wire.PreviewResult{Phase: wire.PreviewDone, App: "tmp-" + s.TaskID, Digest: built.Digest, Files: built.Files, Bytes: built.Bytes, Outcome: wire.PreviewUnconfirmed}) |
| 295 | s.State, s.Reason, s.Preview, kind = wire.StepDone, "withdrawn", string(raw), "preview.unconfirmed" |
| 296 | } else { |
| 297 | s.State, s.Reason = wire.StepCancelled, "withdrawn" |
| 298 | } |
| 299 | return t.auditPreview(s.RunnerID, kind, s, "withdrawn") |
| 300 | } |
| 301 | |
| 302 | func (t *txn) previewHostAuthority(project string, r runnerInfo) (string, error) { |
| 303 | if r.Protocol < wire.ProtocolInjectionDefences { |
| 304 | return wire.ReasonRunnerOutdated, nil |
| 305 | } |
| 306 | cap := r.Hello.Capabilities |
| 307 | if r.Removing || cap == nil || !cap.Previews || cap.PreviewHost == nil { |
| 308 | return "preview_host", nil |
| 309 | } |
| 310 | switch cap.PreviewHost.Kind { |
| 311 | case wire.PreviewHostDevbox: |
| 312 | return "", nil |
| 313 | case wire.PreviewHostCarlokuTemp: |
| 314 | authority, err := t.projectAutonomy(project) |
| 315 | if err != nil { |
| 316 | return "", err |
| 317 | } |
| 318 | if !authority.PublicPreviews { |
| 319 | return "preview_public_disabled", nil |
| 320 | } |
| 321 | return "", nil |
| 322 | default: |
| 323 | return "preview_host", nil |
| 324 | } |
| 325 | } |
| 326 | |