| 1 | package equipo |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/equipo/personapi" |
| 5 | "context" |
| 6 | "crypto/rand" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "slices" |
| 11 | "strings" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/equipo/setup" |
| 15 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 16 | "amadan.net/oficina/equipo/internal/wire" |
| 17 | "gorm.io/gorm" |
| 18 | ) |
| 19 | |
| 20 | func runnerAt(tx *gorm.DB, instance, id string) (runnerRecord, error) { |
| 21 | var runner runnerRecord |
| 22 | if err := tx.Where("id = ?", id).First(&runner).Error; err != nil { |
| 23 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 24 | return runner, ErrForbidden |
| 25 | } |
| 26 | return runner, storeError(err) |
| 27 | } |
| 28 | if runner.InstanceID != instance || runner.RevokedAt != nil { |
| 29 | return runner, ErrForbidden |
| 30 | } |
| 31 | return runner, nil |
| 32 | } |
| 33 | |
| 34 | func mintRunnerCredential(tx *gorm.DB, runner runnerRecord, now time.Time) (runnerproto.RunnerCredential, error) { |
| 35 | token := runnerSecret() |
| 36 | record := runnerCredentialRecord{ID: rand.Text(), RunnerID: runner.ID, InstanceID: runner.InstanceID, Audience: runnerproto.RunnerAudience, Person: runner.Person, MachineKeyHash: runner.MachineKeyHash, TokenHash: runnerHash(runnerproto.RunnerAudience, token), ExpiresAt: now.Add(30 * 24 * time.Hour)} |
| 37 | if err := tx.Create(&record).Error; err != nil { |
| 38 | return runnerproto.RunnerCredential{}, storeError(err) |
| 39 | } |
| 40 | cred := runnerproto.RunnerCredential{Version: 1, Token: token, TokenType: "Bearer", RunnerID: runner.ID, CredentialID: record.ID, Person: runner.Person, ExpiresAt: record.ExpiresAt} |
| 41 | if runner.Role == wire.RoleWorker { |
| 42 | // Only a worker's credential names its role: a primary's stays |
| 43 | // what older runners decode. |
| 44 | cred.Role = wire.RoleWorker |
| 45 | } |
| 46 | return cred, nil |
| 47 | } |
| 48 | |
| 49 | func authenticateRunnerAt(tx *gorm.DB, token string, now time.Time) (runnerRecord, runnerCredentialRecord, error) { |
| 50 | var credential runnerCredentialRecord |
| 51 | if _, err := runnerproto.DecodeBytes(token, 32); err != nil { |
| 52 | return runnerRecord{}, credential, ErrForbidden |
| 53 | } |
| 54 | instance, err := runnerInstance(tx) |
| 55 | if err != nil { |
| 56 | return runnerRecord{}, credential, err |
| 57 | } |
| 58 | if err := tx.Where("token_hash = ?", runnerHash(runnerproto.RunnerAudience, token)).First(&credential).Error; err != nil { |
| 59 | if errors.Is(err, gorm.ErrRecordNotFound) { |
| 60 | return runnerRecord{}, credential, ErrForbidden |
| 61 | } |
| 62 | return runnerRecord{}, credential, storeError(err) |
| 63 | } |
| 64 | if credential.Audience != runnerproto.RunnerAudience || credential.InstanceID != instance || credential.RevokedAt != nil || !now.Before(credential.ExpiresAt) { |
| 65 | return runnerRecord{}, credential, ErrForbidden |
| 66 | } |
| 67 | runner, err := runnerAt(tx, instance, credential.RunnerID) |
| 68 | if err != nil { |
| 69 | return runner, credential, err |
| 70 | } |
| 71 | if runner.Person != credential.Person || runner.MachineKeyHash != credential.MachineKeyHash { |
| 72 | return runner, credential, ErrForbidden |
| 73 | } |
| 74 | if _, err := currentRunnerMember(tx, runner.Person); err != nil { |
| 75 | return runner, credential, err |
| 76 | } |
| 77 | return runner, credential, nil |
| 78 | } |
| 79 | |
| 80 | func (s *Store) AuthenticateRunner(ctx context.Context, token string) (RunnerPrincipal, error) { |
| 81 | var principal RunnerPrincipal |
| 82 | err := s.write(ctx, func(tx *gorm.DB) error { |
| 83 | runner, credential, err := authenticateRunnerAt(tx, token, s.runnerClock.Now().UTC()) |
| 84 | if err != nil { |
| 85 | return err |
| 86 | } |
| 87 | principal = RunnerPrincipal{RunnerID: runner.ID, Person: runner.Person, CredentialID: credential.ID} |
| 88 | return nil |
| 89 | }) |
| 90 | if err != nil { |
| 91 | return RunnerPrincipal{}, err |
| 92 | } |
| 93 | return principal, nil |
| 94 | } |
| 95 | |
| 96 | func (s *Store) RotateRunnerCredential(ctx context.Context, token string) (runnerproto.RunnerCredential, error) { |
| 97 | var result runnerproto.RunnerCredential |
| 98 | err := s.write(ctx, func(tx *gorm.DB) error { |
| 99 | now := s.runnerClock.Now().UTC() |
| 100 | runner, credential, err := authenticateRunnerAt(tx, token, now) |
| 101 | if err != nil { |
| 102 | return err |
| 103 | } |
| 104 | if credential.RotatedAt != nil { |
| 105 | return ErrForbidden |
| 106 | } |
| 107 | credential.RotatedAt = &now |
| 108 | if overlap := now.Add(5 * time.Minute); credential.ExpiresAt.After(overlap) { |
| 109 | credential.ExpiresAt = overlap |
| 110 | } |
| 111 | updated := tx.Model(&runnerCredentialRecord{}).Where("id = ? AND rotated_at IS NULL AND revoked_at IS NULL", credential.ID).Select("ExpiresAt", "RotatedAt").Updates(&credential) |
| 112 | if updated.Error != nil { |
| 113 | return storeError(updated.Error) |
| 114 | } |
| 115 | if updated.RowsAffected != 1 { |
| 116 | return ErrConflict |
| 117 | } |
| 118 | result, err = mintRunnerCredential(tx, runner, now) |
| 119 | if err != nil { |
| 120 | return err |
| 121 | } |
| 122 | return appendAudit(tx, Actor{Address: runner.Person}, "runner.credential.rotate", runner.ID) |
| 123 | }) |
| 124 | if err != nil { |
| 125 | return runnerproto.RunnerCredential{}, err |
| 126 | } |
| 127 | return result, nil |
| 128 | } |
| 129 | |
| 130 | func revokeRunnerAt(tx *gorm.DB, id string, now time.Time) error { |
| 131 | var connections []connectionRecord |
| 132 | if err := tx.Where("runner_id = ?", id).Find(&connections).Error; err != nil { |
| 133 | return storeError(err) |
| 134 | } |
| 135 | for _, c := range connections { |
| 136 | if err := invalidateConnection(tx, c, "runner_revoked", now); err != nil { |
| 137 | return err |
| 138 | } |
| 139 | } |
| 140 | updated := tx.Model(&runnerRecord{}).Where("id = ? AND revoked_at IS NULL", id).Select("RevokedAt", "Revision").Updates(map[string]any{"RevokedAt": now, "Revision": gorm.Expr("revision + 1")}) |
| 141 | if updated.Error != nil { |
| 142 | return storeError(updated.Error) |
| 143 | } |
| 144 | if err := tx.Model(&runnerCredentialRecord{}).Where("runner_id = ? AND revoked_at IS NULL", id).Select("RevokedAt").Updates(&runnerCredentialRecord{RevokedAt: &now}).Error; err != nil { |
| 145 | return storeError(err) |
| 146 | } |
| 147 | return storeError(tx.Model(&runnerEnrolment{}).Where("runner_id = ? AND revoked_at IS NULL", id).Select("RevokedAt").Updates(&runnerEnrolment{RevokedAt: &now}).Error) |
| 148 | } |
| 149 | |
| 150 | // RevokeRunner removes a runner. Work it may have started keeps it |
| 151 | // removing (it can still report that work's end, and gets no new work) |
| 152 | // until the end is proven; only then is it revoked. |
| 153 | func (s *Store) RevokeRunner(ctx context.Context, actor Actor, runnerID string, revision int64) error { |
| 154 | return s.removeRunner(ctx, actor, runnerID, revision, false) |
| 155 | } |
| 156 | |
| 157 | func (s *Store) removeRunner(ctx context.Context, actor Actor, runnerID string, revision int64, immediately bool) error { |
| 158 | return s.write(ctx, func(tx *gorm.DB) error { |
| 159 | member, err := currentRunnerMember(tx, actor.Address) |
| 160 | if err != nil { |
| 161 | return err |
| 162 | } |
| 163 | instance, err := runnerInstance(tx) |
| 164 | if err != nil { |
| 165 | return err |
| 166 | } |
| 167 | var runner runnerRecord |
| 168 | err = tx.First(&runner, "id=? AND instance_id=?", runnerID, instance).Error |
| 169 | if err != nil { |
| 170 | return err |
| 171 | } |
| 172 | if member.Role != RoleOwner && member.Address != runner.Person { |
| 173 | return ErrForbidden |
| 174 | } |
| 175 | if req, ok := personapi.RequestFrom(ctx); ok && req.Operation == "revoke_runner" && runner.Person != actor.Address { |
| 176 | return ErrNotFound |
| 177 | } |
| 178 | var ack personapi.Ack |
| 179 | if replay, e := personapi.Replay(tx, ctx, &ack, ErrConflict); e != nil || replay { |
| 180 | return e |
| 181 | } |
| 182 | if runner.RevokedAt != nil || runner.Revision != revision { |
| 183 | return ErrConflict |
| 184 | } |
| 185 | now := s.runnerClock.Now().UTC() |
| 186 | // Removing from here on: it gets no new work, so nothing withdrawn |
| 187 | // below is placed back on it. |
| 188 | if err := tx.Model(&runnerRecord{}).Where("id = ?", runnerID).Update("removing_at", now).Error; err != nil { |
| 189 | return storeError(err) |
| 190 | } |
| 191 | // Its work first: never-started attempts go elsewhere now; work it |
| 192 | // may have started is cancelled, and with now (a lost machine) it |
| 193 | // is quarantined instead of awaited. |
| 194 | uncertain, err := s.Chat().RemoveRunner(tx, runner.Person, runnerID, immediately) |
| 195 | if err != nil { |
| 196 | return err |
| 197 | } |
| 198 | kind := "runner.revoke" |
| 199 | switch { |
| 200 | case immediately: |
| 201 | kind = "runner.remove_now" |
| 202 | err = revokeRunnerAt(tx, runnerID, now) |
| 203 | case uncertain > 0: |
| 204 | // Removing: it reports the proofs, gets no new work, and is |
| 205 | // revoked when the last one arrives. |
| 206 | kind = "runner.removing" |
| 207 | err = storeError(tx.Model(&runnerRecord{}).Where("id = ?", runnerID).Update("revision", gorm.Expr("revision + 1")).Error) |
| 208 | default: |
| 209 | err = revokeRunnerAt(tx, runnerID, now) |
| 210 | } |
| 211 | if err != nil { |
| 212 | return err |
| 213 | } |
| 214 | if err := appendAudit(tx, actor, kind, runnerID); err != nil { |
| 215 | return err |
| 216 | } |
| 217 | return personapi.SaveResult(tx, ctx, personapi.Ack{Revision: revision + 1}, ErrConflict) |
| 218 | }) |
| 219 | } |
| 220 | |
| 221 | func revokePersonRunners(tx *gorm.DB, person string, now time.Time) error { |
| 222 | var runners []runnerRecord |
| 223 | if err := tx.Where("person = ? AND revoked_at IS NULL", person).Find(&runners).Error; err != nil { |
| 224 | return storeError(err) |
| 225 | } |
| 226 | for _, runner := range runners { |
| 227 | if err := revokeRunnerAt(tx, runner.ID, now); err != nil { |
| 228 | return err |
| 229 | } |
| 230 | } |
| 231 | return nil |
| 232 | } |
| 233 | |
| 234 | func (s *Store) runnersFor(ctx context.Context, actor Actor) ([]machineRecord, error) { |
| 235 | var result []machineRecord |
| 236 | err := s.write(ctx, func(tx *gorm.DB) error { |
| 237 | member, err := currentRunnerMember(tx, actor.Address) |
| 238 | if err != nil { |
| 239 | return err |
| 240 | } |
| 241 | instance, err := runnerInstance(tx) |
| 242 | if err != nil { |
| 243 | return err |
| 244 | } |
| 245 | query := tx.Where("instance_id = ?", instance) |
| 246 | if member.Role != RoleOwner { |
| 247 | query = query.Where("revoked_at IS NULL AND person = ?", member.Address) |
| 248 | } else { |
| 249 | query = query.Where("revoked_at IS NULL OR id IN (SELECT runner_id FROM supervised_trials WHERE revoked_at IS NULL)") |
| 250 | } |
| 251 | var records []runnerRecord |
| 252 | if err := query.Order("id").Find(&records).Error; err != nil { |
| 253 | return storeError(err) |
| 254 | } |
| 255 | for _, record := range records { |
| 256 | var history supervisedTrialRecord |
| 257 | err := tx.Where("runner_id=?", record.ID).Order("acknowledged_at DESC").First(&history).Error |
| 258 | if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { |
| 259 | return storeError(err) |
| 260 | } |
| 261 | if err == nil { |
| 262 | record.TrialOwner = history.Owner |
| 263 | record.TrialAt = history.AcknowledgedAt |
| 264 | record.TrialVersions = history.Versions |
| 265 | } |
| 266 | if record.Report, err = runnerReport(tx, record.ID); err != nil { |
| 267 | return storeError(err) |
| 268 | } |
| 269 | facts, err := machineFactsOf(tx, record.ID) |
| 270 | if err != nil { |
| 271 | return storeError(err) |
| 272 | } |
| 273 | result = append(result, machineRecord{Runner: record.Runner, Facts: facts}) |
| 274 | } |
| 275 | return nil |
| 276 | }) |
| 277 | if err != nil { |
| 278 | return nil, err |
| 279 | } |
| 280 | return result, nil |
| 281 | } |
| 282 | |
| 283 | // machineFacts is what the Machines screens say of a runner beyond its |
| 284 | // record, read only for runners runnersFor already allowed: its |
| 285 | // connection (none until its first hello), what its last hello said, |
| 286 | // and its enrolment's approval. |
| 287 | type machineFacts struct { |
| 288 | // Session: the runner has connected at least once. |
| 289 | Session, Connected bool |
| 290 | SeenAt time.Time |
| 291 | Protocol int |
| 292 | Label string |
| 293 | Versions map[string]string |
| 294 | Tags []string |
| 295 | // PreviewHost: the preview host the runner says it pairs with. |
| 296 | PreviewHost *wire.PreviewHost |
| 297 | EnrolledAt *time.Time |
| 298 | EnrolledBy string |
| 299 | } |
| 300 | |
| 301 | // machineRecord is a runner as the Machines screens list it. |
| 302 | type machineRecord struct { |
| 303 | Runner |
| 304 | Facts machineFacts |
| 305 | } |
| 306 | |
| 307 | func machineFactsOf(tx *gorm.DB, id string) (machineFacts, error) { |
| 308 | var f machineFacts |
| 309 | var sessions []struct { |
| 310 | Connected bool |
| 311 | SeenAt *time.Time |
| 312 | Protocol int |
| 313 | Hello string |
| 314 | } |
| 315 | if err := tx.Raw(`SELECT coalesce(connected, 0) AS connected, seen_at, coalesce(protocol, 1) AS protocol, coalesce(hello, '') AS hello FROM runner_sessions WHERE runner_id = ?`, id).Scan(&sessions).Error; err != nil { |
| 316 | return f, err |
| 317 | } |
| 318 | if len(sessions) == 1 && sessions[0].SeenAt != nil { |
| 319 | v := sessions[0] |
| 320 | f.Session, f.Connected, f.SeenAt, f.Protocol = true, v.Connected, *v.SeenAt, max(v.Protocol, wire.Protocol1) |
| 321 | var h wire.Hello |
| 322 | if v.Hello != "" && json.Unmarshal([]byte(v.Hello), &h) == nil { |
| 323 | f.Label, f.Versions = h.Label, h.Versions |
| 324 | if h.Capabilities != nil && wire.ValidCapabilities(*h.Capabilities) == nil { |
| 325 | f.Tags, f.PreviewHost = h.Capabilities.Tags, h.Capabilities.PreviewHost |
| 326 | } |
| 327 | } |
| 328 | } |
| 329 | var enrolments []setup.EnrolmentRecord |
| 330 | if err := tx.Where("runner_id = ? AND approved_at IS NOT NULL", id).Order("approved_at DESC").Limit(1).Find(&enrolments).Error; err != nil { |
| 331 | return f, err |
| 332 | } |
| 333 | if len(enrolments) == 1 { |
| 334 | f.EnrolledAt, f.EnrolledBy = enrolments[0].ApprovedAt, enrolments[0].Person |
| 335 | } |
| 336 | return f, nil |
| 337 | } |
| 338 | |
| 339 | // runnerReport is the runner's newest hello as the Connections view |
| 340 | // shows it: platform, confinement of checks and self-probes, each value |
| 341 | // already checked by the hello's bounds when it was stored. |
| 342 | func runnerReport(tx *gorm.DB, id string) (*setup.RunnerReport, error) { |
| 343 | var hellos []string |
| 344 | if err := tx.Raw(`SELECT coalesce(hello, '') FROM runner_sessions WHERE runner_id = ?`, id).Scan(&hellos).Error; err != nil { |
| 345 | return nil, err |
| 346 | } |
| 347 | if len(hellos) != 1 || hellos[0] == "" { |
| 348 | return nil, nil |
| 349 | } |
| 350 | var h wire.Hello |
| 351 | if json.Unmarshal([]byte(hellos[0]), &h) != nil { |
| 352 | return nil, nil |
| 353 | } |
| 354 | return reportOf(h), nil |
| 355 | } |
| 356 | |
| 357 | // homeMode is the home guard's code for a home folder others can open |
| 358 | // (creds.CodeHomeMode): its fix is chmod 700 ~. |
| 359 | const homeMode = "home_mode" |
| 360 | |
| 361 | // reportOf is what a stored hello says for the Machines page (nil |
| 362 | // without a platform). |
| 363 | func reportOf(h wire.Hello) *setup.RunnerReport { |
| 364 | if h.Platform == nil { |
| 365 | return nil |
| 366 | } |
| 367 | r := &setup.RunnerReport{Platform: h.Platform.OS + "/" + h.Platform.Arch, Sandbox: h.Sandbox} |
| 368 | if h.Capabilities != nil && wire.ValidCapabilities(*h.Capabilities) == nil { |
| 369 | for _, p := range h.Capabilities.Probes { |
| 370 | r.Probes = append(r.Probes, setup.RunnerProbe{ID: p.ID, Verdict: p.Verdict, Detail: probeDetail(p.Detail)}) |
| 371 | } |
| 372 | r.Unproven = unprovenText(h.Capabilities.Unproven, h.Capabilities.UnprovenCount) |
| 373 | macGuards(r, *h.Capabilities) |
| 374 | } |
| 375 | return r |
| 376 | } |
| 377 | |
| 378 | // macGuards adds what a Mac at 37 says of Engineering: whether it can run |
| 379 | // there, in words, and what keeps Claude off it (the home guard, a |
| 380 | // Keychain item) with as whom to change it. A line naming the fix is |
| 381 | // left out while the runner user is unknown. |
| 382 | func macGuards(r *setup.RunnerReport, c wire.Capabilities) { |
| 383 | e := c.Engineering |
| 384 | if e == nil { |
| 385 | return |
| 386 | } |
| 387 | r.Engineering, r.EngineeringState = copyText("runner.engineering."+e.State), e.State |
| 388 | if (e.State == wire.EngineeringProbesFailed || e.State == wire.EngineeringProbesPending) && slices.Contains(strings.Fields(e.Reason), "P2") { |
| 389 | // Every change is scanned for secrets in P2's sandbox. |
| 390 | r.Engineering += " " + copyText("runner.engineering.needs_p2") |
| 391 | } |
| 392 | if c.RunnerUser == "" { |
| 393 | return |
| 394 | } |
| 395 | if e.State == wire.EngineeringHomeOpen { |
| 396 | key := "runner.mac.home_open_folder" |
| 397 | if e.Reason == homeMode { |
| 398 | key = "runner.mac.home_open" |
| 399 | } |
| 400 | r.Guards = append(r.Guards, fmt.Sprintf(copyText(key), c.RunnerUser)) |
| 401 | } |
| 402 | for _, item := range c.HoldingItems { |
| 403 | r.Guards = append(r.Guards, fmt.Sprintf(copyText("runner.mac.keychain_item"), item, c.RunnerUser)) |
| 404 | } |
| 405 | } |
| 406 | |
| 407 | // probeDetail is a probe's detail as the Machines page shows it: each |
| 408 | // coded part (wire.ProbeDetail) worded here with its parameters; words |
| 409 | // a runner sent instead are never shown. |
| 410 | func probeDetail(d string) string { |
| 411 | parts, _ := wire.ParseProbeDetail(d) |
| 412 | var out []string |
| 413 | for _, p := range parts { |
| 414 | if text := copyText("runner.probe_detail." + p.Code); text != "" { |
| 415 | args := make([]any, len(p.Params)) |
| 416 | for i, v := range p.Params { |
| 417 | args[i] = v |
| 418 | } |
| 419 | out = append(out, fmt.Sprintf(text, args...)) |
| 420 | } |
| 421 | } |
| 422 | return strings.Join(out, " ") |
| 423 | } |
| 424 | |
| 425 | // unprovenText words a runner's Unproven code; "" for none or one it |
| 426 | // does not know. |
| 427 | func unprovenText(code string, n int) string { |
| 428 | switch code { |
| 429 | case wire.UnprovenRecordIncomplete: |
| 430 | return copyText("runner.unproven.record_incomplete") |
| 431 | case wire.UnprovenCredential: |
| 432 | return copyText("runner.unproven.credential_unproven") |
| 433 | case wire.UnprovenProcessesLeft: |
| 434 | // A count only: never which processes. |
| 435 | if n > 0 { |
| 436 | return fmt.Sprintf(copyText("runner.unproven.processes_left"), n) |
| 437 | } |
| 438 | } |
| 439 | return "" |
| 440 | } |
| 441 | |
| 442 | // RemoveRunnerNow removes a runner at once, for a lost or compromised |
| 443 | // machine: revoked now, and any step it may still be running is |
| 444 | // quarantined until the task's creator recovers it. |
| 445 | func (s *Store) RemoveRunnerNow(ctx context.Context, actor Actor, runnerID string, revision int64) error { |
| 446 | return s.removeRunner(ctx, actor, runnerID, revision, true) |
| 447 | } |
| 448 | |