| 1 | package provision |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "log/slog" |
| 8 | "net/http" |
| 9 | "net/mail" |
| 10 | "slices" |
| 11 | "strings" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/alta/console" |
| 15 | "amadan.net/oficina/alta/homeop" |
| 16 | ) |
| 17 | |
| 18 | // Config is everything the engine reaches. |
| 19 | type Config struct { |
| 20 | Store *Store |
| 21 | Home *homeop.Client |
| 22 | Console *console.Client |
| 23 | // Public is the client for the team instances' own origins |
| 24 | // (/api/version, /api/team). |
| 25 | Public *http.Client |
| 26 | HomeCfg HomeConfig |
| 27 | Account string |
| 28 | // CallsZone is CALLS_ZONE for a team's Calls. |
| 29 | CallsZone string |
| 30 | Now func() time.Time |
| 31 | Logger *slog.Logger |
| 32 | // AfterAct, when set, runs after every act has taken effect remotely |
| 33 | // and before Alta records it. A test returns an error from it to |
| 34 | // simulate a crash at exactly that point (§12). |
| 35 | AfterAct func(key string) error |
| 36 | // Debug, when set, sees errors that are neither a park nor a fail |
| 37 | // (tests only: they may carry text the logs must not). |
| 38 | Debug func(error) |
| 39 | // Observer re-observes an adopted app before its activation |
| 40 | // (existing-team-adoption.md). The served alta has none, so it never |
| 41 | // activates an adopted app. |
| 42 | Observer Observer |
| 43 | } |
| 44 | |
| 45 | // Engine runs §6's state machine. Every step is probe → act → verify → |
| 46 | // record; a crash resumes by probing; nothing is inferred from a timeout; |
| 47 | // nothing is deleted to "clean up". |
| 48 | type Engine struct{ cfg Config } |
| 49 | |
| 50 | func New(cfg Config) *Engine { |
| 51 | if cfg.Now == nil { |
| 52 | cfg.Now = time.Now |
| 53 | } |
| 54 | if cfg.Logger == nil { |
| 55 | cfg.Logger = slog.Default() |
| 56 | } |
| 57 | if cfg.Public == nil { |
| 58 | cfg.Public = &http.Client{Timeout: 15 * time.Second} |
| 59 | } |
| 60 | if cfg.CallsZone == "" { |
| 61 | cfg.CallsZone = "UTC" |
| 62 | } |
| 63 | return &Engine{cfg} |
| 64 | } |
| 65 | |
| 66 | func (e *Engine) Store() *Store { return e.cfg.Store } |
| 67 | func (e *Engine) now() time.Time { return e.cfg.Now() } |
| 68 | |
| 69 | // Park is a step that cannot finish yet: it will be retried. Code is a |
| 70 | // fixed word, safe for logs and pages. |
| 71 | type Park struct{ Code string } |
| 72 | |
| 73 | func (p *Park) Error() string { return "parked: " + p.Code } |
| 74 | |
| 75 | // Fail is a step that needs Paul: Alta will not retry it on its own. |
| 76 | type Fail struct{ Code string } |
| 77 | |
| 78 | func (f *Fail) Error() string { return "failed: " + f.Code } |
| 79 | |
| 80 | func park(code string) error { return &Park{code} } |
| 81 | func fail(code string) error { return &Fail{code} } |
| 82 | |
| 83 | // errCrash marks an AfterAct hook's simulated crash. |
| 84 | var errCrash = errors.New("provision: simulated crash") |
| 85 | |
| 86 | func (e *Engine) acted(key string) error { |
| 87 | if e.cfg.AfterAct != nil { |
| 88 | if err := e.cfg.AfterAct(key); err != nil { |
| 89 | return fmt.Errorf("%w at %s: %v", errCrash, key, err) |
| 90 | } |
| 91 | } |
| 92 | return nil |
| 93 | } |
| 94 | |
| 95 | // log carries step keys and fixed codes only (§8): never a label, an |
| 96 | // address, a key or a platform value. App slugs are compiled constants. |
| 97 | func (e *Engine) log(run int64, app, step, outcome string) { |
| 98 | e.cfg.Logger.Info("alta step", "run", run, "app", app, "step", step, "outcome", outcome) |
| 99 | } |
| 100 | |
| 101 | // ---- starting runs (§6 steps 0 and 2) ---- |
| 102 | |
| 103 | // InitializeAttestation is the sentence Paul types to give amendment |
| 104 | // §12's baseline confirmation. Alta then signs Home's fixed |
| 105 | // baseline_attestation value in directory.initialize. |
| 106 | const InitializeAttestation = "This directory has never issued a roster generation or consumer record" |
| 107 | |
| 108 | // StartInitialize opens Alta's first production run: a directory-only |
| 109 | // initialize plan (§6 step 1). |
| 110 | func (e *Engine) StartInitialize(ctx context.Context, typed string) (int64, error) { |
| 111 | if strings.TrimSpace(typed) != InitializeAttestation { |
| 112 | return 0, fail("attestation-mismatch") |
| 113 | } |
| 114 | ins, o, _ := e.cfg.Home.Inspect(ctx, homeop.Directory) |
| 115 | if o != homeop.OK { |
| 116 | return 0, fail("home-" + o.String()) |
| 117 | } |
| 118 | if ins.Generation != nil { |
| 119 | return 0, fail("already-initialized") |
| 120 | } |
| 121 | id, err := e.cfg.Store.NewRun(ctx, homeop.KindInitialize, "", nil, RunOptions{}) |
| 122 | if err != nil { |
| 123 | return 0, err |
| 124 | } |
| 125 | e.cfg.Store.Audit(ctx, id, "", "", "run-start", homeop.KindInitialize) |
| 126 | return id, e.submitPlans(ctx, id, "", "", "", homeop.KindInitialize, nil, "") |
| 127 | } |
| 128 | |
| 129 | // NewTeam is the New team form. |
| 130 | type NewTeam struct { |
| 131 | Label, Name, Owner string |
| 132 | Apps []string |
| 133 | // Forked: the team moves an existing stopgap whose environments Paul |
| 134 | // forked to <label>-team (§6, "Moving the lagged stopgap"). |
| 135 | Forked bool |
| 136 | // Options is the run's profile (zero: outside) and samples choice. |
| 137 | Options RunOptions |
| 138 | } |
| 139 | |
| 140 | // EnvironmentName is a team's owned environment's name. |
| 141 | func EnvironmentName(label string, forked bool) string { |
| 142 | if forked { |
| 143 | return label + "-team" |
| 144 | } |
| 145 | return label |
| 146 | } |
| 147 | |
| 148 | // validEnvironment is CARLOS's environment name rule. |
| 149 | func validEnvironment(s string) bool { |
| 150 | if len(s) == 0 || len(s) > 32 || s == "default" { |
| 151 | return false |
| 152 | } |
| 153 | for _, c := range s { |
| 154 | if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') { |
| 155 | return false |
| 156 | } |
| 157 | } |
| 158 | return true |
| 159 | } |
| 160 | |
| 161 | // CreateTeam runs step 0 for a new team and, if it passes, records the |
| 162 | // label (for good) and submits the plans. |
| 163 | func (e *Engine) CreateTeam(ctx context.Context, in NewTeam) (int64, error) { |
| 164 | opt, okOpt := in.Options.Normal() |
| 165 | if okOpt { |
| 166 | if r := AppsRefusal(in.Label, in.Apps, nil, opt.Profile); r != "" { |
| 167 | return 0, fail(r) |
| 168 | } |
| 169 | } |
| 170 | in.Apps = SortApps(in.Apps) |
| 171 | env := EnvironmentName(in.Label, in.Forked) |
| 172 | switch { |
| 173 | case LabelRefusal(in.Label) != "": |
| 174 | return 0, fail(LabelRefusal(in.Label)) |
| 175 | case !okOpt: |
| 176 | return 0, fail("profile-unknown") |
| 177 | case !homeop.TeamName(in.Name): |
| 178 | return 0, fail("name-shape") |
| 179 | case !homeop.OwnerAddress(in.Owner): |
| 180 | return 0, fail("owner-shape") |
| 181 | case len(in.Apps) == 0: |
| 182 | return 0, fail("no-apps") |
| 183 | case !validEnvironment(env): |
| 184 | return 0, fail("environment-shape") |
| 185 | } |
| 186 | if a, err := mail.ParseAddress(in.Owner); err != nil || a.Address != in.Owner { |
| 187 | return 0, fail("owner-shape") |
| 188 | } |
| 189 | used, err := e.cfg.Store.LabelUsed(ctx, in.Label) |
| 190 | if err != nil { |
| 191 | return 0, err |
| 192 | } |
| 193 | if used { |
| 194 | return 0, fail("label-used") |
| 195 | } |
| 196 | if err := e.preflight(withProposal(ctx, in.Label, env, in.Apps), in.Label, env, in.Forked, in.Apps, true); err != nil { |
| 197 | return 0, err |
| 198 | } |
| 199 | if err := e.cfg.Store.CreateTeam(ctx, in.Label, in.Name, env, in.Forked, in.Owner, in.Apps); err != nil { |
| 200 | return 0, err |
| 201 | } |
| 202 | id, err := e.cfg.Store.NewRun(ctx, homeop.KindCreateTeam, in.Label, in.Apps, opt) |
| 203 | if err != nil { |
| 204 | return 0, err |
| 205 | } |
| 206 | e.cfg.Store.Audit(ctx, id, in.Label, "", "run-start", homeop.KindCreateTeam) |
| 207 | e.auditOptions(ctx, id, in.Label, opt) |
| 208 | return id, e.submitPlans(ctx, id, in.Label, in.Name, in.Owner, homeop.KindCreateTeam, in.Apps, "") |
| 209 | } |
| 210 | |
| 211 | // AddApps starts an add-apps run: new apps for a team, or a parked run's |
| 212 | // apps resumed under a fresh plan (§6: "A run that parks resumes under a |
| 213 | // new plan of kind add-apps"). opt with no profile continues each app |
| 214 | // with its own choice (ContinuedOptions); a profile names a fresh one. |
| 215 | func (e *Engine) AddApps(ctx context.Context, label string, apps []string, opt RunOptions) (int64, error) { |
| 216 | apps = SortApps(apps) |
| 217 | // Home's adoption of the canonical apps is its own signed scope |
| 218 | // (existing_team on the plan, Home discussion 103); an ordinary |
| 219 | // add-apps under the reserved label is refused there, so it is refused |
| 220 | // here before anything is planned or recorded. |
| 221 | if ReservedLabels[label] { |
| 222 | return 0, fail("label-reserved") |
| 223 | } |
| 224 | t, err := e.cfg.Store.Team(ctx, label) |
| 225 | if err != nil { |
| 226 | return 0, fail("no-team") |
| 227 | } |
| 228 | if opt.Profile == "" { |
| 229 | if opt, err = e.ContinuedOptions(ctx, label, apps); err != nil { |
| 230 | return 0, err |
| 231 | } |
| 232 | } |
| 233 | opt, ok := opt.Normal() |
| 234 | if !ok { |
| 235 | return 0, fail("profile-unknown") |
| 236 | } |
| 237 | active := map[string]bool{} |
| 238 | for a, st := range t.Apps { |
| 239 | active[a] = st == "active" |
| 240 | } |
| 241 | if r := AppsRefusal(label, apps, active, opt.Profile); r != "" { |
| 242 | return 0, fail(r) |
| 243 | } |
| 244 | if err := e.ownOnlyFits(ctx, t, apps); err != nil { |
| 245 | return 0, err |
| 246 | } |
| 247 | // An environment already written keeps its choice: step 7 is done and |
| 248 | // never rewrites it, so a run under another choice would finish while |
| 249 | // changing nothing. Refused, naming the app. |
| 250 | for _, a := range apps { |
| 251 | written, ok, err := e.cfg.Store.WrittenOptions(ctx, label, a) |
| 252 | if err != nil { |
| 253 | return 0, err |
| 254 | } |
| 255 | if ok && written != opt { |
| 256 | return 0, fail("profile-differs-" + a) |
| 257 | } |
| 258 | } |
| 259 | if t.TeamSQID == "" { |
| 260 | // The team was never seeded: only a create-team plan admits |
| 261 | // owner-seed and seed-team. Resume that instead. |
| 262 | return e.resumeCreate(ctx, t, apps, opt) |
| 263 | } |
| 264 | if len(apps) == 0 { |
| 265 | return 0, fail("no-apps") |
| 266 | } |
| 267 | var fresh []string |
| 268 | for _, a := range apps { |
| 269 | switch t.Apps[a] { |
| 270 | case "retired": |
| 271 | return 0, fail("app-retired") |
| 272 | case "": |
| 273 | fresh = append(fresh, a) |
| 274 | } |
| 275 | } |
| 276 | if err := e.preflight(withProposal(ctx, label, t.Environment, fresh), label, t.Environment, t.Forked, apps, false); err != nil { |
| 277 | return 0, err |
| 278 | } |
| 279 | if err := e.cfg.Store.AddApps(ctx, label, fresh); err != nil { |
| 280 | return 0, err |
| 281 | } |
| 282 | id, err := e.cfg.Store.NewRun(ctx, homeop.KindAddApps, label, apps, opt) |
| 283 | if err != nil { |
| 284 | return 0, err |
| 285 | } |
| 286 | e.cfg.Store.Audit(ctx, id, label, "", "run-start", homeop.KindAddApps) |
| 287 | e.auditOptions(ctx, id, label, opt) |
| 288 | return id, e.submitPlans(ctx, id, label, "", "", homeop.KindAddApps, apps, "") |
| 289 | } |
| 290 | |
| 291 | // ContinueApps is what "Continue under a new plan" takes: the team's |
| 292 | // active apps with steps still to do (step 13 not done). With none, |
| 293 | // finished is true and apps is every active app, as before. |
| 294 | func (e *Engine) ContinueApps(ctx context.Context, label string) (apps []string, finished bool, err error) { |
| 295 | t, err := e.cfg.Store.Team(ctx, label) |
| 296 | if err != nil { |
| 297 | return nil, false, fail("no-team") |
| 298 | } |
| 299 | var active, open []string |
| 300 | for _, a := range Slugs() { |
| 301 | if t.Apps[a] != "active" { |
| 302 | continue |
| 303 | } |
| 304 | active = append(active, a) |
| 305 | if _, done, err := e.cfg.Store.Done(ctx, label, a, StepAudit); err != nil { |
| 306 | return nil, false, err |
| 307 | } else if !done { |
| 308 | open = append(open, a) |
| 309 | } |
| 310 | } |
| 311 | if len(open) == 0 { |
| 312 | return active, true, nil |
| 313 | } |
| 314 | return open, false, nil |
| 315 | } |
| 316 | |
| 317 | // ContinuedOptions is a run's choice when Paul made none (Continue): each |
| 318 | // app's own (Store.AppOptions: written, else the newest run naming it), |
| 319 | // which must agree; an app that disagrees with the first is refused by |
| 320 | // name. No apps: the team's last run's. |
| 321 | func (e *Engine) ContinuedOptions(ctx context.Context, label string, apps []string) (RunOptions, error) { |
| 322 | if len(apps) == 0 { |
| 323 | return e.cfg.Store.LastOptions(ctx, label) |
| 324 | } |
| 325 | var first RunOptions |
| 326 | for i, a := range SortApps(apps) { |
| 327 | opt, err := e.cfg.Store.AppOptions(ctx, label, a) |
| 328 | if err != nil { |
| 329 | return RunOptions{}, err |
| 330 | } |
| 331 | if i == 0 { |
| 332 | first = opt |
| 333 | } else if opt != first { |
| 334 | return RunOptions{}, fail("profile-differs-" + a) |
| 335 | } |
| 336 | } |
| 337 | return first, nil |
| 338 | } |
| 339 | |
| 340 | // auditOptions records a provisioning run's choice in the audit: fixed |
| 341 | // words only. |
| 342 | func (e *Engine) auditOptions(ctx context.Context, run int64, label string, opt RunOptions) { |
| 343 | detail := string(opt.Profile) |
| 344 | if opt.Samples { |
| 345 | detail += "+samples" |
| 346 | } |
| 347 | e.cfg.Store.Audit(ctx, run, label, "", "run-profile", detail) |
| 348 | } |
| 349 | |
| 350 | // resumeCreate is a fresh create-team plan for a team whose seed has not |
| 351 | // committed: its owner must still be held (it is, until step 13). |
| 352 | func (e *Engine) resumeCreate(ctx context.Context, t Team, apps []string, opt RunOptions) (int64, error) { |
| 353 | owner, ok, err := e.cfg.Store.Owner(ctx, t.Label) |
| 354 | if err != nil { |
| 355 | return 0, err |
| 356 | } |
| 357 | if !ok { |
| 358 | return 0, fail("owner-needed") |
| 359 | } |
| 360 | if len(apps) == 0 { |
| 361 | for a, st := range t.Apps { |
| 362 | if st == "active" { |
| 363 | apps = append(apps, a) |
| 364 | } |
| 365 | } |
| 366 | apps = SortApps(apps) |
| 367 | } |
| 368 | id, err := e.cfg.Store.NewRun(ctx, homeop.KindCreateTeam, t.Label, apps, opt) |
| 369 | if err != nil { |
| 370 | return 0, err |
| 371 | } |
| 372 | e.cfg.Store.Audit(ctx, id, t.Label, "", "run-start", homeop.KindCreateTeam) |
| 373 | e.auditOptions(ctx, id, t.Label, opt) |
| 374 | return id, e.submitPlans(ctx, id, t.Label, t.Name, owner, homeop.KindCreateTeam, apps, "") |
| 375 | } |
| 376 | |
| 377 | // RetireApps starts a deprovision run (§9). typed must equal the label. |
| 378 | func (e *Engine) RetireApps(ctx context.Context, label string, apps []string, typed string) (int64, error) { |
| 379 | apps = SortApps(apps) |
| 380 | if ReservedLabels[label] { |
| 381 | return 0, fail("label-reserved") |
| 382 | } |
| 383 | if typed != label { |
| 384 | return 0, fail("label-mismatch") |
| 385 | } |
| 386 | t, err := e.cfg.Store.Team(ctx, label) |
| 387 | if err != nil { |
| 388 | return 0, fail("no-team") |
| 389 | } |
| 390 | if t.TeamSQID == "" { |
| 391 | return 0, fail("team-not-seeded") |
| 392 | } |
| 393 | if len(apps) == 0 { |
| 394 | return 0, fail("no-apps") |
| 395 | } |
| 396 | for _, a := range apps { |
| 397 | if t.Apps[a] != "active" { |
| 398 | return 0, fail("app-not-active") |
| 399 | } |
| 400 | } |
| 401 | id, err := e.cfg.Store.NewRun(ctx, homeop.KindRetireApps, label, apps, RunOptions{}) |
| 402 | if err != nil { |
| 403 | return 0, err |
| 404 | } |
| 405 | e.cfg.Store.Audit(ctx, id, label, "", "run-start", homeop.KindRetireApps) |
| 406 | return id, e.submitPlans(ctx, id, label, "", "", homeop.KindRetireApps, apps, "") |
| 407 | } |
| 408 | |
| 409 | // Resubmit signs a fresh plan for a run whose plan expired unconfirmed. |
| 410 | func (e *Engine) Resubmit(ctx context.Context, runID int64) error { |
| 411 | r, err := e.cfg.Store.Run(ctx, runID) |
| 412 | if err != nil { |
| 413 | return err |
| 414 | } |
| 415 | // A run Home refused at plan time (an owner who never signed in, say) |
| 416 | // takes a new plan once Paul has corrected what Home refused. |
| 417 | refused := r.State == "failed" && strings.HasPrefix(r.Code, "plan-refused-") |
| 418 | if r.State == "done" || r.State == "superseded" || (r.State == "failed" && !refused) { |
| 419 | return fail("run-finished") |
| 420 | } |
| 421 | name, owner := "", "" |
| 422 | if r.Kind == homeop.KindCreateTeam { |
| 423 | t, err := e.cfg.Store.Team(ctx, r.Label) |
| 424 | if err != nil { |
| 425 | return err |
| 426 | } |
| 427 | if t.TeamSQID != "" { |
| 428 | if r.Adoption { |
| 429 | // Seeded: the rest of Plan A takes an add-apps window |
| 430 | // (ContinueAdoption), never a second create-team. |
| 431 | return fail("use-continue-adoption") |
| 432 | } |
| 433 | return fail("use-add-apps") |
| 434 | } |
| 435 | name = t.Name |
| 436 | var ok bool |
| 437 | if owner, ok, err = e.cfg.Store.Owner(ctx, r.Label); err != nil || !ok { |
| 438 | return fail("owner-needed") |
| 439 | } |
| 440 | } |
| 441 | existing := "" |
| 442 | if r.Adoption { |
| 443 | if existing, err = e.adoptedTeam(ctx, r); err != nil { |
| 444 | return err |
| 445 | } |
| 446 | } |
| 447 | return e.submitPlans(ctx, runID, r.Label, name, owner, r.Kind, r.Apps, existing) |
| 448 | } |
| 449 | |
| 450 | // preflight is §6 step 0's console and Home half. |
| 451 | func (e *Engine) preflight(ctx context.Context, label, env string, forked bool, apps []string, creating bool) error { |
| 452 | for _, a := range apps { |
| 453 | if _, ok := AppBySlug(a); !ok { |
| 454 | return fail("unknown-app") |
| 455 | } |
| 456 | if e.cfg.Console.Tokens[a] == "" { |
| 457 | return fail("no-credential-" + a) |
| 458 | } |
| 459 | } |
| 460 | for _, role := range []string{homeop.Directory, homeop.Credential} { |
| 461 | ins, o, _ := e.cfg.Home.Inspect(ctx, role) |
| 462 | if o != homeop.OK { |
| 463 | return fail("home-" + role + "-" + o.String()) |
| 464 | } |
| 465 | if role == homeop.Directory && ins.Generation == nil { |
| 466 | return fail("home-not-initialized") |
| 467 | } |
| 468 | } |
| 469 | for _, a := range apps { |
| 470 | app, _ := AppBySlug(a) |
| 471 | cfg, found, err := e.cfg.Console.GetConfig(ctx, a, env) |
| 472 | if err != nil { |
| 473 | return fail("console-" + a) |
| 474 | } |
| 475 | if found { |
| 476 | if creating && !forked { |
| 477 | // Owned by scope alta already, but not a fork Paul made for |
| 478 | // this label: a name Alta does not hold. Refuse rather than |
| 479 | // adopt it. |
| 480 | return fail("environment-exists-" + a) |
| 481 | } |
| 482 | present := map[string]bool{} |
| 483 | for _, v := range cfg.Vars { |
| 484 | present[v.Key] = true |
| 485 | } |
| 486 | if st := PlatformKeys(app, present); st.WrongPrefix != "" { |
| 487 | return fail("mail-prefix-" + a) |
| 488 | } |
| 489 | } else if forked { |
| 490 | return fail("fork-missing-" + a) |
| 491 | } |
| 492 | inst, found, err := e.cfg.Console.GetInstance(ctx, a, RouteHost(label, a, e.cfg.Account)) |
| 493 | if err != nil { |
| 494 | return fail("console-" + a) |
| 495 | } |
| 496 | if found && inst.Environment != env { |
| 497 | return fail("instance-bound-elsewhere-" + a) |
| 498 | } |
| 499 | } |
| 500 | return nil |
| 501 | } |
| 502 | |
| 503 | // submitPlans is §6 step 2: one plan per role with one shared plan_id. |
| 504 | // The directory's carries the label and display name, the credential's |
| 505 | // the owner; Home keeps its own copy and Paul confirms that copy. An |
| 506 | // adoption plan carries the team's SQID, existing, on both roles. |
| 507 | func (e *Engine) submitPlans(ctx context.Context, runID int64, label, name, owner, kind string, apps []string, existing string) error { |
| 508 | planID := homeop.Token() |
| 509 | issued := e.now().Add(-homeop.Skew * time.Second) |
| 510 | roles := []string{homeop.Directory, homeop.Credential} |
| 511 | // Initialize is the directory's alone, and so is disabling an adopted |
| 512 | // app: an ordinary retire-apps window under oficina may disable a |
| 513 | // directory binding and never retires an env-manifest consumer, so the |
| 514 | // credential role has nothing to confirm. |
| 515 | if kind == homeop.KindInitialize || (kind == homeop.KindRetireApps && label == AdoptionLabel) { |
| 516 | roles = roles[:1] |
| 517 | } |
| 518 | signed := map[string][]byte{} |
| 519 | var expires int64 |
| 520 | for _, role := range roles { |
| 521 | p, err := e.cfg.Home.NewPlan(role, planID, kind, apps, issued) |
| 522 | if err != nil { |
| 523 | return err |
| 524 | } |
| 525 | if role == homeop.Directory && kind != homeop.KindInitialize { |
| 526 | p.Label = label |
| 527 | if kind == homeop.KindCreateTeam { |
| 528 | p.DisplayName = name |
| 529 | } |
| 530 | } |
| 531 | if role == homeop.Credential && kind == homeop.KindCreateTeam { |
| 532 | p.Owner = owner |
| 533 | } |
| 534 | p.ExistingTeam = existing |
| 535 | raw, err := homeop.SignPlan(e.cfg.Home.Key, p) |
| 536 | if err != nil { |
| 537 | return err |
| 538 | } |
| 539 | if err := e.cfg.Store.SavePlan(ctx, planID, role, raw, p.Expires); err != nil { |
| 540 | return err |
| 541 | } |
| 542 | signed[role], expires = raw, p.Expires |
| 543 | } |
| 544 | if err := e.cfg.Store.SetRunPlan(ctx, runID, planID, expires); err != nil { |
| 545 | return err |
| 546 | } |
| 547 | e.cfg.Store.Audit(ctx, runID, label, "", "plan-signed", homeop.PlanPrefix(planID)) |
| 548 | for _, role := range roles { |
| 549 | switch o := e.cfg.Home.SubmitPlan(ctx, role, signed[role]); o { |
| 550 | case homeop.OK: |
| 551 | _ = e.cfg.Store.MarkPlan(ctx, planID, role, "pending", 0) |
| 552 | e.cfg.Store.Audit(ctx, runID, label, "", "plan-pending", role) |
| 553 | case homeop.Refused: |
| 554 | _ = e.cfg.Store.SetRunState(ctx, runID, "failed", "plan-refused-"+role) |
| 555 | e.cfg.Store.Audit(ctx, runID, label, "", "plan-refused", role) |
| 556 | return fail("plan-refused-" + role) |
| 557 | default: |
| 558 | // Busy, unavailable or lost: Advance retries with the same |
| 559 | // signed plan until it expires. |
| 560 | e.cfg.Store.Audit(ctx, runID, label, "", "plan-"+o.String(), role) |
| 561 | } |
| 562 | } |
| 563 | return nil |
| 564 | } |
| 565 | |
| 566 | // ---- advancing ---- |
| 567 | |
| 568 | // pass is one Advance's view of Home. |
| 569 | type pass struct { |
| 570 | run Run |
| 571 | team Team |
| 572 | ins map[string]homeop.Inspection |
| 573 | open map[string]int64 // role -> window expiry, when this run's window is open |
| 574 | closed map[string]string |
| 575 | } |
| 576 | |
| 577 | func (p *pass) windowOpen(role string, now time.Time) bool { |
| 578 | return p.open[role] > now.Unix()+20 |
| 579 | } |
| 580 | |
| 581 | // Advance takes run as far as it can go now. Only one run advances at a |
| 582 | // time (§8). |
| 583 | func (e *Engine) Advance(ctx context.Context, runID int64) error { |
| 584 | st := e.cfg.Store |
| 585 | if err := st.Lock(ctx, runID, 10*time.Minute); err != nil { |
| 586 | return err |
| 587 | } |
| 588 | defer st.Unlock(ctx, runID) |
| 589 | r, err := st.Run(ctx, runID) |
| 590 | if err != nil { |
| 591 | return err |
| 592 | } |
| 593 | if r.State == "done" || r.State == "superseded" || r.State == "failed" { |
| 594 | return nil |
| 595 | } |
| 596 | _ = st.DropExpiredPlans(ctx) |
| 597 | p := &pass{run: r, ins: map[string]homeop.Inspection{}, open: map[string]int64{}, closed: map[string]string{}} |
| 598 | // The adoption label is the adoption runs' alone, and an adoption run |
| 599 | // has no other: neither ever reaches the other's steps. |
| 600 | if (r.Label == AdoptionLabel) != r.Adoption { |
| 601 | return e.settle(ctx, p, fail("label-reserved")) |
| 602 | } |
| 603 | if r.Label != "" { |
| 604 | if p.team, err = st.Team(ctx, r.Label); err != nil { |
| 605 | return err |
| 606 | } |
| 607 | } |
| 608 | if err := e.windows(ctx, p); err != nil { |
| 609 | return e.settle(ctx, p, err) |
| 610 | } |
| 611 | switch { |
| 612 | case r.Adoption: |
| 613 | return e.settle(ctx, p, e.adoption(ctx, p)) |
| 614 | case r.Kind == homeop.KindInitialize: |
| 615 | return e.settle(ctx, p, e.initialize(ctx, p)) |
| 616 | case r.Kind == homeop.KindRetireApps: |
| 617 | return e.settle(ctx, p, e.retire(ctx, p)) |
| 618 | default: |
| 619 | return e.settle(ctx, p, e.provision(ctx, p)) |
| 620 | } |
| 621 | } |
| 622 | |
| 623 | // settle records the run's state from the pass's outcome. |
| 624 | func (e *Engine) settle(ctx context.Context, p *pass, err error) error { |
| 625 | st := e.cfg.Store |
| 626 | var pk *Park |
| 627 | var fl *Fail |
| 628 | switch { |
| 629 | case err == nil: |
| 630 | code := "" |
| 631 | if p.run.Adoption && p.run.Kind == homeop.KindCreateTeam { |
| 632 | // Plan A ends here: configure (CARLOS) comes next, then Plan B. |
| 633 | code = "awaiting-configuration" |
| 634 | } |
| 635 | _ = st.SetRunState(ctx, p.run.ID, "done", code) |
| 636 | st.Audit(ctx, p.run.ID, p.run.Label, "", "run-done", p.run.Kind) |
| 637 | return nil |
| 638 | case errors.Is(err, errCrash): |
| 639 | return err |
| 640 | case errors.As(err, &fl): |
| 641 | _ = st.SetRunState(ctx, p.run.ID, "failed", fl.Code) |
| 642 | st.Audit(ctx, p.run.ID, p.run.Label, "", "run-failed", fl.Code) |
| 643 | return err |
| 644 | case errors.As(err, &pk): |
| 645 | state := "parked" |
| 646 | if pk.Code == "awaiting-confirm" { |
| 647 | state = "planned" |
| 648 | } |
| 649 | _ = st.SetRunState(ctx, p.run.ID, state, pk.Code) |
| 650 | return nil |
| 651 | default: |
| 652 | if errors.Is(err, console.ErrGuard) { |
| 653 | _ = st.SetRunState(ctx, p.run.ID, "failed", "guard") |
| 654 | st.Audit(ctx, p.run.ID, p.run.Label, "", "guard-refused", "") |
| 655 | return err |
| 656 | } |
| 657 | _ = st.SetRunState(ctx, p.run.ID, "parked", "transient") |
| 658 | e.cfg.Logger.Warn("alta advance", "run", p.run.ID, "outcome", "transient") |
| 659 | if e.cfg.Debug != nil { |
| 660 | e.cfg.Debug(err) |
| 661 | } |
| 662 | return nil |
| 663 | } |
| 664 | } |
| 665 | |
| 666 | // windows reads both roles' plan state for this run: open, pending, or |
| 667 | // gone. A busy role is retried with the same signed plan while it lives. |
| 668 | func (e *Engine) windows(ctx context.Context, p *pass) error { |
| 669 | st := e.cfg.Store |
| 670 | if p.run.PlanID == "" { |
| 671 | return fail("no-plan") |
| 672 | } |
| 673 | subs, err := st.Plans(ctx, p.run.PlanID) |
| 674 | if err != nil { |
| 675 | return err |
| 676 | } |
| 677 | now := e.now().Unix() |
| 678 | pending := false |
| 679 | for role, sub := range subs { |
| 680 | ins, o, _ := e.cfg.Home.Inspect(ctx, role) |
| 681 | if o != homeop.OK { |
| 682 | return park("home-unavailable") |
| 683 | } |
| 684 | p.ins[role] = ins |
| 685 | switch { |
| 686 | case ins.OpenPlan == p.run.PlanID && ins.WindowExpires > now: |
| 687 | p.open[role] = ins.WindowExpires |
| 688 | if sub.State != "open" { |
| 689 | _ = st.MarkPlan(ctx, p.run.PlanID, role, "open", ins.WindowExpires) |
| 690 | st.Audit(ctx, p.run.ID, p.run.Label, "", "window-open", role) |
| 691 | } |
| 692 | case ins.PendingPlan == p.run.PlanID: |
| 693 | pending = true |
| 694 | if sub.State == "signed" { |
| 695 | _ = st.MarkPlan(ctx, p.run.PlanID, role, "pending", 0) |
| 696 | } |
| 697 | case sub.State == "signed" && now < sub.Expires && sub.Signed != nil: |
| 698 | switch e.cfg.Home.SubmitPlan(ctx, role, sub.Signed) { |
| 699 | case homeop.OK: |
| 700 | _ = st.MarkPlan(ctx, p.run.PlanID, role, "pending", 0) |
| 701 | pending = true |
| 702 | case homeop.Refused: |
| 703 | return fail("plan-refused-" + role) |
| 704 | default: |
| 705 | p.closed[role] = "home-busy" |
| 706 | pending = true |
| 707 | } |
| 708 | default: |
| 709 | if sub.State != "closed" { |
| 710 | _ = st.MarkPlan(ctx, p.run.PlanID, role, "closed", 0) |
| 711 | } |
| 712 | if sub.State == "open" || sub.Window > 0 { |
| 713 | p.closed[role] = "window-expired" |
| 714 | } else { |
| 715 | p.closed[role] = "plan-expired" |
| 716 | } |
| 717 | } |
| 718 | } |
| 719 | // Nothing open yet and something still waiting on Paul: the run is |
| 720 | // planned, not parked. |
| 721 | if len(p.open) == 0 && pending { |
| 722 | return park("awaiting-confirm") |
| 723 | } |
| 724 | return nil |
| 725 | } |
| 726 | |
| 727 | func (e *Engine) needWindow(p *pass, role string) error { |
| 728 | if p.windowOpen(role, e.now()) { |
| 729 | return nil |
| 730 | } |
| 731 | if c := p.closed[role]; c != "" { |
| 732 | return park(c) |
| 733 | } |
| 734 | return park("awaiting-confirm-" + role) |
| 735 | } |
| 736 | |
| 737 | // ---- the operator stream ---- |
| 738 | |
| 739 | type opSpec struct { |
| 740 | role, action, label, app, purpose string |
| 741 | // reuse: replay a committed request for this purpose instead of |
| 742 | // signing a new one (its result is the step's result). |
| 743 | reuse bool |
| 744 | build func(base homeop.InputBase) any |
| 745 | } |
| 746 | |
| 747 | var errOpRefused = errors.New("provision: Home refused the operation") |
| 748 | |
| 749 | // replayHeld replays the request Alta holds for s's purpose, if any: a |
| 750 | // signed one whose answer was lost, or (with reuse) a committed one whose |
| 751 | // result the step needs again. handled is false when there is nothing to |
| 752 | // replay, or the held request never committed (then it is marked refused |
| 753 | // and a new one may be signed). |
| 754 | func (e *Engine) replayHeld(ctx context.Context, s opSpec) (homeop.Result, bool, error) { |
| 755 | st := e.cfg.Store |
| 756 | prev, ok, err := st.LastRequest(ctx, s.label, s.app, s.purpose) |
| 757 | if err != nil { |
| 758 | return homeop.Result{}, true, err |
| 759 | } |
| 760 | if !ok || !(prev.State == "signed" || (prev.State == "committed" && s.reuse)) { |
| 761 | return homeop.Result{}, false, nil |
| 762 | } |
| 763 | res, _, o := e.cfg.Home.Execute(ctx, s.role, prev.Bytes) |
| 764 | switch o { |
| 765 | case homeop.OK: |
| 766 | if prev.State == "signed" { |
| 767 | if err := e.acted(s.purpose + "/replayed"); err != nil { |
| 768 | return homeop.Result{}, true, err |
| 769 | } |
| 770 | if err := st.Commit(ctx, prev); err != nil { |
| 771 | return homeop.Result{}, true, err |
| 772 | } |
| 773 | st.Audit(ctx, 0, s.label, s.app, "home-recovered", s.action) |
| 774 | } |
| 775 | return res, true, nil |
| 776 | case homeop.Refused: |
| 777 | if prev.State == "committed" { |
| 778 | return homeop.Result{}, true, fail("replay-refused") |
| 779 | } |
| 780 | // Never committed: it expired before Home saw it, or was refused. |
| 781 | _ = st.MarkRequest(ctx, prev.ID, "refused") |
| 782 | return homeop.Result{}, false, nil |
| 783 | default: |
| 784 | return homeop.Result{}, true, park("home-unavailable") |
| 785 | } |
| 786 | } |
| 787 | |
| 788 | // op runs one Home operation: replay what Alta already signed for this |
| 789 | // purpose (a lost result is recovered by exact replay), else sign the |
| 790 | // next sequence, store it sealed, send it, and record it. |
| 791 | func (e *Engine) op(ctx context.Context, s opSpec) (homeop.Result, error) { |
| 792 | if res, handled, err := e.replayHeld(ctx, s); handled { |
| 793 | return res, err |
| 794 | } |
| 795 | for attempt := 0; attempt < 2; attempt++ { |
| 796 | res, err := e.signAndSend(ctx, s) |
| 797 | if !errors.Is(err, errResync) { |
| 798 | return res, err |
| 799 | } |
| 800 | } |
| 801 | return homeop.Result{}, fail("stream-diverged") |
| 802 | } |
| 803 | |
| 804 | var errResync = errors.New("provision: stream resynchronised") |
| 805 | |
| 806 | func (e *Engine) signAndSend(ctx context.Context, s opSpec) (homeop.Result, error) { |
| 807 | st := e.cfg.Store |
| 808 | seq, head, ok, err := st.Stream(ctx, s.role) |
| 809 | if err != nil { |
| 810 | return homeop.Result{}, err |
| 811 | } |
| 812 | if !ok { |
| 813 | // No stream on record (a fresh Alta, or a lost DB): Home's head is |
| 814 | // the arbiter; read it through a signed inspect. |
| 815 | ins, o, _ := e.cfg.Home.Inspect(ctx, s.role) |
| 816 | if o != homeop.OK { |
| 817 | return homeop.Result{}, park("home-unavailable") |
| 818 | } |
| 819 | if err := st.SetStream(ctx, s.role, ins.Sequence, ins.Head); err != nil { |
| 820 | return homeop.Result{}, err |
| 821 | } |
| 822 | st.Audit(ctx, 0, s.label, s.app, "stream-adopted", s.role) |
| 823 | seq, head = ins.Sequence, ins.Head |
| 824 | } |
| 825 | a, err := e.cfg.Home.NewAuthorization(s.role) |
| 826 | if err != nil { |
| 827 | return homeop.Result{}, err |
| 828 | } |
| 829 | journal, err := st.NextJournal(ctx) |
| 830 | if err != nil { |
| 831 | return homeop.Result{}, err |
| 832 | } |
| 833 | now := e.now().Unix() - homeop.Skew |
| 834 | a.Sequence, a.Previous, a.JournalSequence = seq+1, head, journal |
| 835 | a.OperationID, a.Action = homeop.Token(), s.action |
| 836 | a.Issued, a.Expires = now, now+homeop.RequestLifetime |
| 837 | req, err := homeop.SignRequest(e.cfg.Home.Key, a, s.build(homeop.InputBase{Version: 1, Operation: s.action, OperationID: a.OperationID})) |
| 838 | if err != nil { |
| 839 | return homeop.Result{}, err |
| 840 | } |
| 841 | row := OpRequest{ID: journal, Role: s.role, Sequence: a.Sequence, OperationID: a.OperationID, Action: s.action, Label: s.label, App: s.app, Purpose: s.purpose, Head: req.Head, Expires: a.Expires, Bytes: req.Bytes} |
| 842 | // Stored before it is sent: whatever happens next, a resume holds the |
| 843 | // exact bytes to replay. |
| 844 | if err := st.SaveRequest(ctx, row); err != nil { |
| 845 | return homeop.Result{}, err |
| 846 | } |
| 847 | res, _, o := e.cfg.Home.Execute(ctx, s.role, req.Bytes) |
| 848 | switch o { |
| 849 | case homeop.OK: |
| 850 | if err := e.acted(s.purpose); err != nil { |
| 851 | return homeop.Result{}, err |
| 852 | } |
| 853 | if err := st.Commit(ctx, row); err != nil { |
| 854 | return homeop.Result{}, err |
| 855 | } |
| 856 | st.Audit(ctx, 0, s.label, s.app, "home-committed", s.action) |
| 857 | return res, nil |
| 858 | case homeop.Refused: |
| 859 | _ = st.MarkRequest(ctx, row.ID, "refused") |
| 860 | ins, io, _ := e.cfg.Home.Inspect(ctx, s.role) |
| 861 | if io != homeop.OK { |
| 862 | return homeop.Result{}, park("home-unavailable") |
| 863 | } |
| 864 | if ins.Sequence != seq || ins.Head != head { |
| 865 | // Home's head moved without Alta: Alta's DB is behind (lost, |
| 866 | // or restored). Adopt Home's position; if Home's head is a |
| 867 | // request Alta holds, that request committed. |
| 868 | if held, ok, _ := st.RequestByHead(ctx, s.role, ins.Head); ok { |
| 869 | _ = st.Commit(ctx, held) |
| 870 | } |
| 871 | if err := st.SetStream(ctx, s.role, ins.Sequence, ins.Head); err != nil { |
| 872 | return homeop.Result{}, err |
| 873 | } |
| 874 | st.Audit(ctx, 0, s.label, s.app, "stream-resync", s.role) |
| 875 | return homeop.Result{}, errResync |
| 876 | } |
| 877 | st.Audit(ctx, 0, s.label, s.app, "home-refused", s.action) |
| 878 | if ins.OpenPlan == "" || ins.WindowExpires <= e.now().Unix() { |
| 879 | // No window: a request whose answer was lost, replayed after |
| 880 | // the window closed, found never committed and re-signed. Not |
| 881 | // Home refusing the operation, so not a failure. |
| 882 | return homeop.Result{}, park("window-expired") |
| 883 | } |
| 884 | return homeop.Result{}, errOpRefused |
| 885 | default: |
| 886 | // Unavailable or lost: the request may have committed. Only an |
| 887 | // exact replay says; the row stays "signed" for the next pass. |
| 888 | return homeop.Result{}, park("home-unavailable") |
| 889 | } |
| 890 | } |
| 891 | |
| 892 | // ---- initialize ---- |
| 893 | |
| 894 | func (e *Engine) initialize(ctx context.Context, p *pass) error { |
| 895 | if _, ok, _ := e.cfg.Store.Done(ctx, "", "", "initialize"); ok { |
| 896 | return nil |
| 897 | } |
| 898 | if ins := p.ins[homeop.Directory]; ins.Generation != nil { |
| 899 | // Initialized: by this run (a result lost to a crash, recovered by |
| 900 | // replay below), or by nobody Alta knows of. |
| 901 | if _, held, _ := e.cfg.Store.LastRequest(ctx, "", "", "initialize"); !held { |
| 902 | return fail("initialized-elsewhere") |
| 903 | } |
| 904 | } else if err := e.needWindow(p, homeop.Directory); err != nil { |
| 905 | return err |
| 906 | } |
| 907 | gen := homeop.Token() |
| 908 | res, err := e.op(ctx, opSpec{role: homeop.Directory, action: homeop.DirectoryInitialize, purpose: "initialize", reuse: true, |
| 909 | build: func(b homeop.InputBase) any { |
| 910 | return homeop.InitializeInput{InputBase: b, Generation: gen, Baseline: homeop.Baseline} |
| 911 | }}) |
| 912 | if errors.Is(err, errOpRefused) { |
| 913 | return fail("initialize-refused") |
| 914 | } |
| 915 | if err != nil { |
| 916 | return err |
| 917 | } |
| 918 | e.log(p.run.ID, "", "initialize", "done") |
| 919 | return e.cfg.Store.SetStep(ctx, "", "", "initialize", "done", "", map[string]any{"generation": res.Generation}) |
| 920 | } |
| 921 | |
| 922 | // ---- helpers ---- |
| 923 | |
| 924 | func str(d map[string]any, k string) string { |
| 925 | s, _ := d[k].(string) |
| 926 | return s |
| 927 | } |
| 928 | |
| 929 | func num(d map[string]any, k string) int64 { |
| 930 | switch v := d[k].(type) { |
| 931 | case float64: |
| 932 | return int64(v) |
| 933 | case int64: |
| 934 | return v |
| 935 | case int: |
| 936 | return int64(v) |
| 937 | } |
| 938 | return 0 |
| 939 | } |
| 940 | |
| 941 | func contains(list []string, s string) bool { return slices.Contains(list, s) } |
| 942 | |
| 943 | // ownOnlyFits is add-apps' half of the own-only rule (team-bundle spec |
| 944 | // §5.1 rule 3) beyond the run's own profile: |
| 945 | // - an own-only app joins only a team whose every written app is own |
| 946 | // (app-own-only), so an outside team never gains one by an own run; |
| 947 | // - a seeded app whose environment is not yet written needs the owner's |
| 948 | // address Home confirmed at create-team, still held: once Alta has |
| 949 | // forgotten it, a retyped address (checked for shape only) would |
| 950 | // become the app's owner (owner-forgotten-seeded). Such a team takes |
| 951 | // Equipo and Base by creating them with the team. |
| 952 | func (e *Engine) ownOnlyFits(ctx context.Context, t Team, apps []string) error { |
| 953 | var seeded []string |
| 954 | own := false |
| 955 | for _, slug := range apps { |
| 956 | if app, ok := AppBySlug(slug); ok && app.OwnOnly { |
| 957 | own = true |
| 958 | if NeedsOwner(app) { |
| 959 | seeded = append(seeded, slug) |
| 960 | } |
| 961 | } |
| 962 | } |
| 963 | if !own { |
| 964 | return nil |
| 965 | } |
| 966 | for a := range t.Apps { |
| 967 | written, ok, err := e.cfg.Store.WrittenOptions(ctx, t.Label, a) |
| 968 | if err != nil { |
| 969 | return err |
| 970 | } |
| 971 | if ok && written.Profile != ProfileOwn { |
| 972 | return fail("app-own-only") |
| 973 | } |
| 974 | } |
| 975 | if _, held, err := e.cfg.Store.Owner(ctx, t.Label); err != nil { |
| 976 | return err |
| 977 | } else if held { |
| 978 | return nil |
| 979 | } |
| 980 | for _, slug := range seeded { |
| 981 | if _, written, err := e.cfg.Store.WrittenOptions(ctx, t.Label, slug); err != nil { |
| 982 | return err |
| 983 | } else if !written { |
| 984 | return fail("owner-forgotten-seeded") |
| 985 | } |
| 986 | } |
| 987 | return nil |
| 988 | } |
| 989 | |