| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "slices" |
| 7 | "strconv" |
| 8 | "strings" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/specialist" |
| 11 | "amadan.net/oficina/equipo/internal/wire" |
| 12 | ) |
| 13 | |
| 14 | // Every attempt is bound to its grant (dynamic specialists §1). A data |
| 15 | // specialist's step records, when dispatched, the specialist it runs as: |
| 16 | // its id, revision, scope and capabilities (bind). Every privileged |
| 17 | // effect of the attempt checks that binding again in its own |
| 18 | // transaction against grantFor for the task's project: the start and |
| 19 | // pre-push authorization and each page_render check (Authorize), and a |
| 20 | // worker commit's push (authorizePublication). Revoking a specialist |
| 21 | // cancels the steps bound to it and withdraws their pending |
| 22 | // publications (cancelSpecialist). |
| 23 | |
| 24 | // reasonSpecialistNoGrant ends a data specialist's maker step that has |
| 25 | // no usable grant (revoked, or its binding no longer holds): nothing of |
| 26 | // that attempt runs. |
| 27 | const reasonSpecialistNoGrant = "specialist_no_grant" |
| 28 | |
| 29 | // auditUsed is the specialist audit action of one dispatch under a |
| 30 | // grant (instance audit kind specialist.used). |
| 31 | const auditUsed = "used" |
| 32 | |
| 33 | // scopeRow is the active row of profile a project's work runs as: the |
| 34 | // project's own, else the team's (""); nil when there is none, or when |
| 35 | // a scope holds more than one (the unique indexes forbid it; it |
| 36 | // denies). It checks nothing else (usableGrant does). |
| 37 | func (t *txn) scopeRow(profile, project string) (*specialistRecord, error) { |
| 38 | var rows []specialistRecord |
| 39 | if err := t.db.Where("profile = ? AND state = ? AND project_id IN ?", profile, wire.SpecialistActive, []string{project, ""}).Order("id").Find(&rows).Error; err != nil { |
| 40 | return nil, err |
| 41 | } |
| 42 | pick := func(scope string) (*specialistRecord, bool) { |
| 43 | var out *specialistRecord |
| 44 | for i := range rows { |
| 45 | if rows[i].ProjectID != scope { |
| 46 | continue |
| 47 | } |
| 48 | if out != nil { |
| 49 | return nil, true |
| 50 | } |
| 51 | out = &rows[i] |
| 52 | } |
| 53 | return out, out != nil |
| 54 | } |
| 55 | if sp, ok := pick(project); ok || project == "" { |
| 56 | return sp, nil |
| 57 | } |
| 58 | sp, _ := pick("") |
| 59 | return sp, nil |
| 60 | } |
| 61 | |
| 62 | // usableGrant is the specialist a profile's work in project runs as and |
| 63 | // the grants it runs under, only when every one of these holds now, read |
| 64 | // in this transaction: the profile is on the menu; scopeRow finds the |
| 65 | // row (a project's own row wins, and when it fails a check below the |
| 66 | // team's row does not stand in for it); its unrevoked grants are |
| 67 | // exactly the profile's capabilities, each once, each at the row's |
| 68 | // revision and given by its approver; and that approver is an owner now. |
| 69 | // Otherwise nil. A lookup error is returned, and denies too. |
| 70 | func (t *txn) usableGrant(profile, project string) (*specialistRecord, []grantRecord, error) { |
| 71 | p, ok := specialist.Lookup(profile) |
| 72 | if !ok { |
| 73 | return nil, nil, nil |
| 74 | } |
| 75 | sp, err := t.scopeRow(profile, project) |
| 76 | if err != nil || sp == nil { |
| 77 | return nil, nil, err |
| 78 | } |
| 79 | if sp.Approver == "" { |
| 80 | return nil, nil, nil |
| 81 | } |
| 82 | var grants []grantRecord |
| 83 | if err := t.db.Where("specialist_id = ? AND revoked_at IS NULL", sp.ID).Find(&grants).Error; err != nil { |
| 84 | return nil, nil, err |
| 85 | } |
| 86 | held := make([]string, 0, len(grants)) |
| 87 | for _, g := range grants { |
| 88 | if g.Revision != sp.Revision || g.GrantedBy != sp.Approver { |
| 89 | return nil, nil, nil |
| 90 | } |
| 91 | held = append(held, g.Capability) |
| 92 | } |
| 93 | want := slices.Clone(p.Capabilities) |
| 94 | slices.Sort(held) |
| 95 | slices.Sort(want) |
| 96 | if !slices.Equal(held, want) { |
| 97 | return nil, nil, nil |
| 98 | } |
| 99 | if err := t.isOwner(sp.Approver); errors.Is(err, ErrForbidden) { |
| 100 | return nil, nil, nil |
| 101 | } else if err != nil { |
| 102 | return nil, nil, err |
| 103 | } |
| 104 | return sp, grants, nil |
| 105 | } |
| 106 | |
| 107 | // grantFor is the specialist a profile's work in project runs as now, if |
| 108 | // its grant is usable (usableGrant); nil otherwise. |
| 109 | func (t *txn) grantFor(profile, project string) (*specialistRecord, error) { |
| 110 | sp, _, err := t.usableGrant(profile, project) |
| 111 | return sp, err |
| 112 | } |
| 113 | |
| 114 | // binding is what a step records of the specialist it runs as: the row, |
| 115 | // its revision and scope, and its profile's capabilities (a JSON list, |
| 116 | // in the menu's order). The zero binding is none. |
| 117 | type binding struct { |
| 118 | ID string |
| 119 | Revision int64 |
| 120 | Project string |
| 121 | Caps string |
| 122 | } |
| 123 | |
| 124 | // bindingOf is the binding a step dispatched under sp records. |
| 125 | func bindingOf(sp specialistRecord) binding { |
| 126 | b := binding{ID: sp.ID, Revision: sp.Revision, Project: sp.ProjectID} |
| 127 | if p, ok := specialist.Lookup(sp.Profile); ok { |
| 128 | raw, _ := json.Marshal(p.Capabilities) |
| 129 | b.Caps = string(raw) |
| 130 | } |
| 131 | return b |
| 132 | } |
| 133 | |
| 134 | func stepBinding(s stepRecord) binding { |
| 135 | return binding{ID: s.SpecialistID, Revision: s.SpecialistRevision, Project: s.SpecialistProject, Caps: s.SpecialistCaps} |
| 136 | } |
| 137 | |
| 138 | // bind records sp's binding on the step (the caller saves s). |
| 139 | func bind(s *stepRecord, sp specialistRecord) { |
| 140 | b := bindingOf(sp) |
| 141 | s.SpecialistID, s.SpecialistRevision, s.SpecialistProject, s.SpecialistCaps = b.ID, b.Revision, b.Project, b.Caps |
| 142 | } |
| 143 | |
| 144 | // boundDispatch puts sp's binding and profile in a maker step's |
| 145 | // dispatch of task k (protocol 38), with whether k is an exploration and |
| 146 | // sp's brief as its owner added it. |
| 147 | func boundDispatch(cmd *wire.DispatchCommand, sp specialistRecord, k taskRecord) { |
| 148 | b := bindingOf(sp) |
| 149 | cmd.SpecialistID, cmd.SpecialistRevision, cmd.SpecialistProject, cmd.Profile = b.ID, b.Revision, b.Project, sp.Profile |
| 150 | cmd.Explore, cmd.SpecialistBrief = wire.NormalKind(k.Kind) == wire.KindExplore, clipText(sp.Brief, wire.MaxSpecialistBrief) |
| 151 | if p, ok := specialist.Lookup(sp.Profile); ok { |
| 152 | cmd.Capabilities = slices.Clone(p.Capabilities) |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | // boundCaps are the capabilities the step's binding records. |
| 157 | func boundCaps(s stepRecord) []string { |
| 158 | var caps []string |
| 159 | if json.Unmarshal([]byte(s.SpecialistCaps), &caps) != nil { |
| 160 | return nil |
| 161 | } |
| 162 | return caps |
| 163 | } |
| 164 | |
| 165 | // bindingHolds reports whether the step's binding is exactly what |
| 166 | // grantFor finds now for its task's project, for the bound row's |
| 167 | // profile. A step with no binding never holds. |
| 168 | func (t *txn) bindingHolds(s stepRecord, k taskRecord) (bool, error) { |
| 169 | var row specialistRecord |
| 170 | if err := t.db.Where("id = ?", s.SpecialistID).Limit(1).Find(&row).Error; err != nil || row.ID == "" { |
| 171 | return false, err |
| 172 | } |
| 173 | sp, err := t.grantFor(row.Profile, k.ProjectID) |
| 174 | if err != nil || sp == nil { |
| 175 | return false, err |
| 176 | } |
| 177 | return bindingOf(*sp) == stepBinding(s), nil |
| 178 | } |
| 179 | |
| 180 | // makerGrant is the specialist the task's maker step runs as at its |
| 181 | // dispatch: the task's maker, found by grantFor for the task's project, |
| 182 | // and the one the step is already bound to when it is (an earlier |
| 183 | // attempt's). nil: no usable grant, and the step must not run (as plain |
| 184 | // Engineering least of all). |
| 185 | func (t *txn) makerGrant(k taskRecord, s stepRecord) (*specialistRecord, error) { |
| 186 | var row specialistRecord |
| 187 | if err := t.db.Where("id = ?", k.MakerSpecialistID).Limit(1).Find(&row).Error; err != nil || row.ID == "" { |
| 188 | return nil, err |
| 189 | } |
| 190 | sp, err := t.grantFor(row.Profile, k.ProjectID) |
| 191 | if err != nil || sp == nil || sp.ID != k.MakerSpecialistID { |
| 192 | return nil, err |
| 193 | } |
| 194 | if s.SpecialistID != "" && stepBinding(s) != bindingOf(*sp) { |
| 195 | return nil, nil |
| 196 | } |
| 197 | return sp, nil |
| 198 | } |
| 199 | |
| 200 | // specialistUsed appends the specialist.used audit row of one dispatch |
| 201 | // under sp, in the dispatch's transaction: the task, the step attempt, |
| 202 | // the runner, the task's project and the binding. Never a credential. |
| 203 | func (t *txn) specialistUsed(sp specialistRecord, k taskRecord, s stepRecord) error { |
| 204 | b := bindingOf(sp) |
| 205 | var caps []string |
| 206 | _ = json.Unmarshal([]byte(b.Caps), &caps) |
| 207 | detail := "profile=" + sp.Profile + " scope=" + sp.ProjectID + " project=" + k.ProjectID + " task=" + k.ID + " step=" + s.ID + " attempt=" + strconv.FormatInt(s.Attempt, 10) + " runner=" + s.RunnerID + " capabilities=" + strings.Join(caps, ",") |
| 208 | a := specialistAuditRecord{ID: newID("sa_"), SpecialistID: sp.ID, Action: auditUsed, Actor: "system", Revision: sp.Revision, Detail: detail, At: t.now()} |
| 209 | if err := t.db.Create(&a).Error; err != nil { |
| 210 | return err |
| 211 | } |
| 212 | if t.s.authority.Audit == nil { |
| 213 | return nil |
| 214 | } |
| 215 | return t.s.authority.Audit(t.db, "system", "specialist."+auditUsed, sp.ID+"@"+sp.Profile+":"+k.ID+"/"+s.ID+"/"+strconv.FormatInt(s.Attempt, 10)) |
| 216 | } |
| 217 | |
| 218 | // authorizeSpecialist is a lease's binding check for a step that is not |
| 219 | // Research (authorizeResearch checks those): a step with no binding on a |
| 220 | // task with no maker is Engineering's own (or a judge's) and unaffected, |
| 221 | // except that it never renders. A maker step is granted only on a |
| 222 | // connection at ProtocolDesign or above, bound to the task's maker, |
| 223 | // while its binding holds (bindingHolds); a render only while that |
| 224 | // binding holds page.render. A step bound to anything else is refused. |
| 225 | func (t *txn) authorizeSpecialist(l Lease, s stepRecord, purpose string) (string, error) { |
| 226 | k, err := t.loadTask(s.TaskID) |
| 227 | if err != nil { |
| 228 | return "", err |
| 229 | } |
| 230 | maker := s.Specialist == wire.SpecialistEngineering && k.MakerSpecialistID != "" |
| 231 | if !maker && s.SpecialistID == "" { |
| 232 | if purpose == wire.LeasePurposeRender { |
| 233 | return "withdrawn", nil |
| 234 | } |
| 235 | return "", nil |
| 236 | } |
| 237 | if !maker || s.SpecialistID != k.MakerSpecialistID || l.Protocol < wire.ProtocolDesign { |
| 238 | return reasonSpecialistNoGrant, nil |
| 239 | } |
| 240 | holds, err := t.bindingHolds(s, k) |
| 241 | if err != nil { |
| 242 | return "", err |
| 243 | } |
| 244 | if !holds { |
| 245 | return reasonSpecialistNoGrant, nil |
| 246 | } |
| 247 | if purpose == wire.LeasePurposeRender && !slices.Contains(boundCaps(s), specialist.CapabilityPageRender) { |
| 248 | return "withdrawn", nil |
| 249 | } |
| 250 | return "", nil |
| 251 | } |
| 252 | |
| 253 | // leasePurposeKnown reports whether a lease purpose is one this instance |
| 254 | // checks for this step kind. Any other is refused, never taken for a |
| 255 | // start check. |
| 256 | func leasePurposeKnown(stepSpecialist, purpose string) bool { |
| 257 | switch purpose { |
| 258 | case "", wire.LeasePurposePreview, wire.LeasePurposePublish, wire.LeasePurposeMint: |
| 259 | // Preview and publish purposes on other steps are refused below. |
| 260 | return true |
| 261 | case wire.LeasePurposeMerge: |
| 262 | return stepSpecialist == wire.SpecialistMerge |
| 263 | case wire.LeasePurposeRender: |
| 264 | return stepSpecialist == wire.SpecialistEngineering |
| 265 | } |
| 266 | return false |
| 267 | } |
| 268 | |
| 269 | // cancelSpecialist settles everything that runs under sp, in its |
| 270 | // revoke's transaction: its Research steps (cancelResearch), its maker |
| 271 | // steps (cancelMakers) and the pending publications of the steps bound |
| 272 | // to it (withdrawPublications). Nothing bound to any other specialist, |
| 273 | // and no step of Engineering's own, is touched. |
| 274 | func (t *txn) cancelSpecialist(sp specialistRecord) error { |
| 275 | if err := t.withdrawPublications(sp); err != nil { |
| 276 | return err |
| 277 | } |
| 278 | if err := t.cancelResearch(sp); err != nil { |
| 279 | return err |
| 280 | } |
| 281 | if err := t.cancelMakers(sp); err != nil { |
| 282 | return err |
| 283 | } |
| 284 | // A task whose steps all ended, proven, is asked about at once. |
| 285 | return t.offerRecoveries(sp) |
| 286 | } |
| 287 | |
| 288 | // cancelMakers gives every unfinished maker step of sp (bound to it, or |
| 289 | // not yet dispatched on a task whose maker it is) the ordinary cancel. |
| 290 | // One that cannot have run ends cancelled at once: never placed, or its |
| 291 | // dispatch retired before its runner took it. One its runner may hold |
| 292 | // is asked to stop and reports its end (its termination proof); its |
| 293 | // leases are refused from now on (authorizeSpecialist). The task waits. |
| 294 | func (t *txn) cancelMakers(sp specialistRecord) error { |
| 295 | var rows []stepRecord |
| 296 | if err := t.db.Where("specialist = ? AND state IN ? AND (specialist_id = ? OR task_id IN (SELECT id FROM chat_tasks WHERE maker_specialist_id = ?))", wire.SpecialistEngineering, []string{wire.StepQueued, wire.StepRunning}, sp.ID, sp.ID).Order("created_at, id").Find(&rows).Error; err != nil { |
| 297 | return err |
| 298 | } |
| 299 | for i := range rows { |
| 300 | s := &rows[i] |
| 301 | k, err := t.loadTask(s.TaskID) |
| 302 | if err != nil { |
| 303 | return err |
| 304 | } |
| 305 | if err := t.closeTransfers(s.ID, s.Attempt); err != nil { |
| 306 | return err |
| 307 | } |
| 308 | if s.RunnerID != "" { |
| 309 | 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+`","attempt":`+itoa64(s.Attempt)+`,%`).Update("acked_at", t.now()) |
| 310 | if res.Error != nil { |
| 311 | return res.Error |
| 312 | } |
| 313 | if res.RowsAffected == 0 || s.StartedAt != nil { |
| 314 | if err := t.commandTo(s.RunnerID, s.Person, wire.FrameCancelStep, wire.CancelStepCommand{Person: s.Person, TaskID: s.TaskID, StepID: s.ID, Attempt: s.Attempt}); err != nil { |
| 315 | return err |
| 316 | } |
| 317 | continue |
| 318 | } |
| 319 | } |
| 320 | now := t.now() |
| 321 | s.State, s.Reason, s.Terminated, s.FinishedAt, s.Placement, s.WaitingSince = wire.StepCancelled, reasonSpecialistNoGrant, true, &now, "", nil |
| 322 | if err := t.saveStep(s, &k); err != nil { |
| 323 | return err |
| 324 | } |
| 325 | } |
| 326 | return nil |
| 327 | } |
| 328 | |
| 329 | // withdrawPublications withdraws the pending publication of every step |
| 330 | // bound to sp: a worker's commit the primary was to push is not pushed. |
| 331 | // Its publish command, if not yet delivered, is retired; its transfers |
| 332 | // are closed; and the publication fails as cancelled, so a primary that |
| 333 | // holds the command is refused its push (authorizePublication). |
| 334 | func (t *txn) withdrawPublications(sp specialistRecord) error { |
| 335 | var rows []stepRecord |
| 336 | if err := t.db.Where("specialist_id = ? AND publication = ?", sp.ID, wire.PublicationPending).Find(&rows).Error; err != nil { |
| 337 | return err |
| 338 | } |
| 339 | for i := range rows { |
| 340 | s := &rows[i] |
| 341 | k, err := t.loadTask(s.TaskID) |
| 342 | if err != nil { |
| 343 | return err |
| 344 | } |
| 345 | if err := t.db.Model(&commandRecord{}).Where("kind = ? AND acked_at IS NULL AND body LIKE ?", wire.FramePublish, `%"publication":"`+s.PublicationID+`"%`).Update("acked_at", t.now()).Error; err != nil { |
| 346 | return err |
| 347 | } |
| 348 | if err := t.closeTransfers(s.ID, s.Attempt); err != nil { |
| 349 | return err |
| 350 | } |
| 351 | s.Publication = wire.PublicationFailed |
| 352 | if wire.StepTerminal(s.State) { |
| 353 | s.Reason = "cancelled" |
| 354 | } |
| 355 | if err := t.saveStep(s, &k); err != nil { |
| 356 | return err |
| 357 | } |
| 358 | if err := t.advance(&k); err != nil { |
| 359 | return err |
| 360 | } |
| 361 | } |
| 362 | return nil |
| 363 | } |
| 364 | |
| 365 | // researchResolvesTo reports whether a Research step of a task in |
| 366 | // project, not yet bound to any grant, would run under sp: sp is that |
| 367 | // project's own row, or the team's and the project has no active row of |
| 368 | // its own. |
| 369 | func (t *txn) researchResolvesTo(sp specialistRecord, project string) (bool, error) { |
| 370 | if sp.ProjectID != "" { |
| 371 | return sp.ProjectID == project, nil |
| 372 | } |
| 373 | var own int64 |
| 374 | if err := t.db.Model(&specialistRecord{}).Where("profile = ? AND state = ? AND project_id = ? AND project_id <> ''", sp.Profile, wire.SpecialistActive, project).Count(&own).Error; err != nil { |
| 375 | return false, err |
| 376 | } |
| 377 | return own == 0, nil |
| 378 | } |
| 379 | |