| 1 | package provision |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "encoding/base64" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "io" |
| 10 | "net/http" |
| 11 | "regexp" |
| 12 | "strings" |
| 13 | "time" |
| 14 | |
| 15 | "amadan.net/oficina/alta/console" |
| 16 | "amadan.net/oficina/alta/homeop" |
| 17 | "amadan.net/oficina/home/roster" |
| 18 | ) |
| 19 | |
| 20 | // Step names, in order. Team-level steps have app "". |
| 21 | const ( |
| 22 | StepOwner = "owner" // 3 |
| 23 | StepTeam = "team" // 4 |
| 24 | StepConsumer = "consumer" // 5 |
| 25 | StepRegister = "register" // 6 |
| 26 | StepEnv = "env" // 7 |
| 27 | StepInstance = "instance" // 8 |
| 28 | StepDomain = "domain" // 9 |
| 29 | StepServing = "serving" // 10 |
| 30 | StepVerify = "verify" // 11 |
| 31 | StepActivate = "activate" // 12 |
| 32 | StepAudit = "audit" // 13 |
| 33 | |
| 34 | StepDisable = "disable" // §9 |
| 35 | StepRetire = "retire" |
| 36 | StepDetach = "detach" |
| 37 | StepDelete = "delete" |
| 38 | ) |
| 39 | |
| 40 | // AppSteps is the pipeline for app, in order. |
| 41 | func AppSteps(app App) []string { |
| 42 | s := []string{StepConsumer, StepRegister, StepEnv, StepInstance, StepDomain, StepServing} |
| 43 | if app.Roster || app.Seeded { |
| 44 | s = append(s, StepVerify, StepActivate) |
| 45 | } |
| 46 | return append(s, StepAudit) |
| 47 | } |
| 48 | |
| 49 | // RetireSteps is §9's order. |
| 50 | var RetireSteps = []string{StepDisable, StepRetire, StepDetach, StepDelete} |
| 51 | |
| 52 | // DomainPatience is how long step 9 polls before it says so (§6: ≤ 30 |
| 53 | // min, then park). |
| 54 | const DomainPatience = 30 * time.Minute |
| 55 | |
| 56 | func (e *Engine) record(ctx context.Context, p *pass, app, step string, data map[string]any) error { |
| 57 | e.log(p.run.ID, app, step, "done") |
| 58 | e.cfg.Store.Audit(ctx, p.run.ID, p.run.Label, app, "step-done", step) |
| 59 | return e.cfg.Store.SetStep(ctx, p.run.Label, app, step, "done", "", data) |
| 60 | } |
| 61 | |
| 62 | func (e *Engine) note(ctx context.Context, p *pass, app, step string, err error, data map[string]any) { |
| 63 | var pk *Park |
| 64 | var fl *Fail |
| 65 | state, code := "parked", "transient" |
| 66 | switch { |
| 67 | case errors.As(err, &pk): |
| 68 | code = pk.Code |
| 69 | case errors.As(err, &fl): |
| 70 | state, code = "failed", fl.Code |
| 71 | case errors.Is(err, console.ErrGuard): |
| 72 | state, code = "failed", "guard" |
| 73 | } |
| 74 | prev, ok, _ := e.cfg.Store.Step(ctx, p.run.Label, app, step) |
| 75 | if ok && prev.State == state && prev.Code == code && data == nil { |
| 76 | return |
| 77 | } |
| 78 | if data == nil && ok { |
| 79 | data = prev.Data |
| 80 | } |
| 81 | e.log(p.run.ID, app, step, state+":"+code) |
| 82 | _ = e.cfg.Store.SetStep(ctx, p.run.Label, app, step, state, code, data) |
| 83 | } |
| 84 | |
| 85 | // provision is a create-team or add-apps run: steps 3–4 for the team, |
| 86 | // then each app's pipeline. A parked app does not hold the others back: |
| 87 | // domains issue and instances start in parallel. |
| 88 | func (e *Engine) provision(ctx context.Context, p *pass) error { |
| 89 | if p.team.TeamSQID == "" { |
| 90 | if err := e.seed(ctx, p); err != nil { |
| 91 | return err |
| 92 | } |
| 93 | t, err := e.cfg.Store.Team(ctx, p.run.Label) |
| 94 | if err != nil { |
| 95 | return err |
| 96 | } |
| 97 | p.team = t |
| 98 | } else if _, ok, _ := e.cfg.Store.Done(ctx, p.run.Label, "", StepTeam); !ok { |
| 99 | // A team row seeded before SetSeeded was one transaction, with its |
| 100 | // step lost to a crash: the sqid is Home's answer, so record it. |
| 101 | if err := e.record(ctx, p, "", StepTeam, map[string]any{"team_sqid": p.team.TeamSQID, "epoch": p.team.Epoch}); err != nil { |
| 102 | return err |
| 103 | } |
| 104 | } |
| 105 | // Before any app step: when no recipe holds the owner, the seed was |
| 106 | // the address's last use, and an app that fails must not keep it. |
| 107 | if err := e.forgetOwnerWhenWritten(ctx, p); err != nil { |
| 108 | return err |
| 109 | } |
| 110 | var first error |
| 111 | for _, slug := range p.run.Apps { |
| 112 | app, _ := AppBySlug(slug) |
| 113 | if err := e.appPipeline(ctx, p, app); err != nil { |
| 114 | if errors.Is(err, errCrash) { |
| 115 | return err |
| 116 | } |
| 117 | var fl *Fail |
| 118 | if errors.As(err, &fl) || errors.Is(err, console.ErrGuard) { |
| 119 | return err |
| 120 | } |
| 121 | if first == nil { |
| 122 | first = err |
| 123 | } |
| 124 | } |
| 125 | } |
| 126 | // The address goes once the seed has committed and every allowlist is |
| 127 | // written, whatever else is still parked: an app waiting on a |
| 128 | // certificate or a roster must not keep it at rest. |
| 129 | if err := e.forgetOwnerWhenWritten(ctx, p); err != nil { |
| 130 | return err |
| 131 | } |
| 132 | return first |
| 133 | } |
| 134 | |
| 135 | func (e *Engine) appPipeline(ctx context.Context, p *pass, app App) error { |
| 136 | return e.pipeline(ctx, p, app, AppSteps(app)) |
| 137 | } |
| 138 | |
| 139 | // pipeline runs app's steps in order, skipping those already done. |
| 140 | func (e *Engine) pipeline(ctx context.Context, p *pass, app App, steps []string) error { |
| 141 | for _, step := range steps { |
| 142 | if _, ok, err := e.cfg.Store.Done(ctx, p.run.Label, app.Slug, step); err != nil { |
| 143 | return err |
| 144 | } else if ok { |
| 145 | continue |
| 146 | } |
| 147 | err := e.runStep(ctx, p, app, step) |
| 148 | if err != nil { |
| 149 | if !errors.Is(err, errCrash) { |
| 150 | e.note(ctx, p, app.Slug, step, err, nil) |
| 151 | } |
| 152 | return err |
| 153 | } |
| 154 | } |
| 155 | return nil |
| 156 | } |
| 157 | |
| 158 | func (e *Engine) runStep(ctx context.Context, p *pass, app App, step string) error { |
| 159 | switch step { |
| 160 | case StepConsumer: |
| 161 | return e.stepConsumer(ctx, p, app) |
| 162 | case StepRegister: |
| 163 | return e.stepRegister(ctx, p, app) |
| 164 | case StepEnv: |
| 165 | return e.stepEnv(ctx, p, app) |
| 166 | case StepInstance: |
| 167 | return e.stepInstance(ctx, p, app) |
| 168 | case StepDomain: |
| 169 | return e.stepDomain(ctx, p, app) |
| 170 | case StepServing: |
| 171 | return e.stepServing(ctx, p, app) |
| 172 | case StepVerify: |
| 173 | return e.stepVerify(ctx, p, app) |
| 174 | case StepActivate: |
| 175 | return e.stepActivate(ctx, p, app) |
| 176 | case StepAudit: |
| 177 | return e.stepAudit(ctx, p, app) |
| 178 | case StepDisable: |
| 179 | // An adopted app's disable (DisableAdopted); §9's runs use |
| 180 | // retireApp's own order. |
| 181 | return e.stepDisable(ctx, p, app) |
| 182 | } |
| 183 | return fail("unknown-step") |
| 184 | } |
| 185 | |
| 186 | // ---- steps 3 and 4: owner and team ---- |
| 187 | |
| 188 | func (e *Engine) seed(ctx context.Context, p *pass) error { |
| 189 | if p.run.Kind != homeop.KindCreateTeam { |
| 190 | return fail("team-not-seeded") |
| 191 | } |
| 192 | label := p.run.Label |
| 193 | // A seed that committed and whose result was lost: replay recovers |
| 194 | // it, no window needed. |
| 195 | if res, handled, err := e.replayHeld(ctx, opSpec{role: homeop.Directory, action: homeop.DirectorySeedTeam, label: label, purpose: "seed-team", reuse: true}); handled { |
| 196 | if err != nil { |
| 197 | return err |
| 198 | } |
| 199 | return e.seeded(ctx, p, res) |
| 200 | } |
| 201 | for _, role := range []string{homeop.Credential, homeop.Directory} { |
| 202 | if err := e.needWindow(p, role); err != nil { |
| 203 | e.note(ctx, p, "", StepTeam, err, nil) |
| 204 | return err |
| 205 | } |
| 206 | } |
| 207 | gen := p.ins[homeop.Directory].Generation |
| 208 | if gen == nil { |
| 209 | return fail("home-not-initialized") |
| 210 | } |
| 211 | receipt, owner, err := e.ownerReceipt(ctx, p) |
| 212 | if err != nil { |
| 213 | e.note(ctx, p, "", StepOwner, err, nil) |
| 214 | return err |
| 215 | } |
| 216 | res, err := e.op(ctx, opSpec{role: homeop.Directory, action: homeop.DirectorySeedTeam, label: label, purpose: "seed-team", |
| 217 | build: func(b homeop.InputBase) any { |
| 218 | return homeop.SeedInput{InputBase: b, Generation: *gen, TeamID: owner.TeamID, TeamSQID: owner.TeamSQID, Label: label, Name: p.team.Name, Receipt: receipt} |
| 219 | }}) |
| 220 | if errors.Is(err, errOpRefused) { |
| 221 | // The receipt may have aged out or another team taken the |
| 222 | // proposed id: both mean a new owner-seed next pass. Otherwise |
| 223 | // the label is taken at Home, or the name differs from the plan. |
| 224 | ins, o, _ := e.cfg.Home.Inspect(ctx, homeop.Directory) |
| 225 | if o == homeop.OK && (ins.TeamID != owner.TeamID || owner.Expires <= e.now().Unix()+5) { |
| 226 | _ = e.cfg.Store.SetStep(ctx, label, "", StepOwner, "parked", "receipt-stale", nil) |
| 227 | return park("receipt-stale") |
| 228 | } |
| 229 | err = fail("seed-refused") |
| 230 | } |
| 231 | if err != nil { |
| 232 | e.note(ctx, p, "", StepTeam, err, nil) |
| 233 | return err |
| 234 | } |
| 235 | return e.seeded(ctx, p, res) |
| 236 | } |
| 237 | |
| 238 | func (e *Engine) seeded(ctx context.Context, p *pass, res homeop.Result) error { |
| 239 | if res.TeamID <= 0 || res.TeamSQID == "" || res.Epoch <= 0 { |
| 240 | return fail("seed-result") |
| 241 | } |
| 242 | owner := str(mustDone(ctx, e.cfg.Store, p.run.Label, "", StepOwner), "owner_ref") |
| 243 | if owner == "" { |
| 244 | return fail("seed-owner-unknown") |
| 245 | } |
| 246 | if err := e.cfg.Store.SetSeeded(ctx, p.run.Label, res.TeamID, res.TeamSQID, res.Epoch, res.Generation, owner, map[string]any{"team_sqid": res.TeamSQID, "epoch": res.Epoch}); err != nil { |
| 247 | return err |
| 248 | } |
| 249 | e.log(p.run.ID, "", StepTeam, "done") |
| 250 | e.cfg.Store.Audit(ctx, p.run.ID, p.run.Label, "", "step-done", StepTeam) |
| 251 | return nil |
| 252 | } |
| 253 | |
| 254 | func mustDone(ctx context.Context, s *Store, label, app, step string) map[string]any { |
| 255 | st, ok, _ := s.Step(ctx, label, app, step) |
| 256 | if !ok { |
| 257 | return map[string]any{} |
| 258 | } |
| 259 | return st.Data |
| 260 | } |
| 261 | |
| 262 | // ownerReceipt is step 3: a receipt whose expiry is still ahead, for the |
| 263 | // team id the directory proposes now. An expired receipt is never renewed |
| 264 | // by replay (Home returns the same expired receipt by design): it takes a |
| 265 | // new owner-seed operation. |
| 266 | func (e *Engine) ownerReceipt(ctx context.Context, p *pass) ([]byte, homeop.OwnerReceipt, error) { |
| 267 | label := p.run.Label |
| 268 | proposed := p.ins[homeop.Directory] |
| 269 | now := e.now().Unix() |
| 270 | if p.run.Adoption { |
| 271 | // Adoption seeds at the SQID Paul confirmed on both roles and no |
| 272 | // other: if the directory now proposes another, nothing is signed. |
| 273 | existing, err := e.planExisting(ctx, p) |
| 274 | if err != nil { |
| 275 | return nil, homeop.OwnerReceipt{}, err |
| 276 | } |
| 277 | if existing != proposed.TeamSQID { |
| 278 | return nil, homeop.OwnerReceipt{}, fail("proposal-moved") |
| 279 | } |
| 280 | } |
| 281 | if d, ok, _ := e.cfg.Store.Done(ctx, label, "", StepOwner); ok { |
| 282 | raw, _ := base64.RawURLEncoding.DecodeString(str(d, "receipt")) |
| 283 | if r, err := homeop.ReadReceipt(raw); err == nil && r.Expires > now+30 && r.TeamID == proposed.TeamID { |
| 284 | return raw, r, nil |
| 285 | } |
| 286 | } |
| 287 | addr, ok, err := e.cfg.Store.Owner(ctx, label) |
| 288 | if err != nil { |
| 289 | return nil, homeop.OwnerReceipt{}, err |
| 290 | } |
| 291 | if !ok { |
| 292 | return nil, homeop.OwnerReceipt{}, fail("owner-needed") |
| 293 | } |
| 294 | // A request signed but never answered may still hold a live receipt; |
| 295 | // a committed one is never replayed here (its receipt may be dead). |
| 296 | res, err := e.op(ctx, opSpec{role: homeop.Credential, action: homeop.CredentialOwnerSeed, label: label, purpose: "owner-seed", |
| 297 | build: func(b homeop.InputBase) any { |
| 298 | return homeop.OwnerInput{InputBase: b, Directory: e.cfg.HomeCfg.Directory, TeamID: proposed.TeamID, TeamSQID: proposed.TeamSQID, Address: addr, ExistingOnly: true} |
| 299 | }}) |
| 300 | if errors.Is(err, errOpRefused) { |
| 301 | return nil, homeop.OwnerReceipt{}, fail("owner-refused") |
| 302 | } |
| 303 | if err != nil { |
| 304 | return nil, homeop.OwnerReceipt{}, err |
| 305 | } |
| 306 | r, err := homeop.ReadReceipt(res.Receipt) |
| 307 | if err != nil { |
| 308 | return nil, homeop.OwnerReceipt{}, fail("receipt-unreadable") |
| 309 | } |
| 310 | if r.Expires <= e.now().Unix()+5 || r.TeamID != proposed.TeamID { |
| 311 | return nil, homeop.OwnerReceipt{}, park("receipt-stale") |
| 312 | } |
| 313 | if err := e.record(ctx, p, "", StepOwner, map[string]any{"receipt": base64.RawURLEncoding.EncodeToString(res.Receipt), "owner_ref": r.PersonRef, "expires_at": r.Expires}); err != nil { |
| 314 | return nil, homeop.OwnerReceipt{}, err |
| 315 | } |
| 316 | return res.Receipt, r, nil |
| 317 | } |
| 318 | |
| 319 | // ---- step 5: directory consumer ---- |
| 320 | |
| 321 | func (e *Engine) expectedBindings(p *pass, app App) roster.Bindings { |
| 322 | return roster.Bindings{Issuer: e.cfg.HomeCfg.Issuer, Directory: e.cfg.HomeCfg.Directory, Consumer: ConsumerID(p.run.Label, app.Slug), App: app.Slug, Team: p.team.TeamSQID, Audience: PublicOrigin(p.run.Label, app.Slug)} |
| 323 | } |
| 324 | |
| 325 | func (e *Engine) provisionSpec(p *pass, app App) opSpec { |
| 326 | return opSpec{role: homeop.Directory, action: homeop.DirectoryProvision, label: p.run.Label, app: app.Slug, purpose: "provision", reuse: true, |
| 327 | build: func(b homeop.InputBase) any { |
| 328 | return homeop.ProvisionInput{InputBase: b, Generation: p.team.Generation, TeamSQID: p.team.TeamSQID, App: app.Slug, Consumer: ConsumerID(p.run.Label, app.Slug), Audience: PublicOrigin(p.run.Label, app.Slug)} |
| 329 | }} |
| 330 | } |
| 331 | |
| 332 | func (e *Engine) stepConsumer(ctx context.Context, p *pass, app App) error { |
| 333 | if _, held, _ := e.cfg.Store.LastRequest(ctx, p.run.Label, app.Slug, "provision"); !held { |
| 334 | if err := e.needWindow(p, homeop.Directory); err != nil { |
| 335 | return err |
| 336 | } |
| 337 | } |
| 338 | res, err := e.op(ctx, e.provisionSpec(p, app)) |
| 339 | if errors.Is(err, errOpRefused) { |
| 340 | return fail("provision-refused") |
| 341 | } |
| 342 | if err != nil { |
| 343 | return err |
| 344 | } |
| 345 | // Alta checks the record against the directory's pinned provisioning |
| 346 | // key and the bindings it asked for before it is written anywhere. |
| 347 | if _, err := roster.VerifyProvisioning(res.Record, ProvisionerKeys(e.cfg.HomeCfg.Provisioner), e.expectedBindings(p, app)); err != nil { |
| 348 | return fail("record-unverified") |
| 349 | } |
| 350 | return e.record(ctx, p, app.Slug, StepConsumer, map[string]any{ |
| 351 | "record": base64.RawURLEncoding.EncodeToString(res.Record), |
| 352 | "record_digest": homeop.Digest(res.Record), |
| 353 | "epoch": res.Epoch, |
| 354 | "generation": res.Generation, |
| 355 | }) |
| 356 | } |
| 357 | |
| 358 | func (e *Engine) consumerData(ctx context.Context, p *pass, app App) ([]byte, map[string]any, error) { |
| 359 | d, ok, err := e.cfg.Store.Done(ctx, p.run.Label, app.Slug, StepConsumer) |
| 360 | if err != nil || !ok { |
| 361 | return nil, nil, fail("consumer-missing") |
| 362 | } |
| 363 | rec, err := base64.RawURLEncoding.DecodeString(str(d, "record")) |
| 364 | if err != nil { |
| 365 | return nil, nil, fail("consumer-missing") |
| 366 | } |
| 367 | return rec, d, nil |
| 368 | } |
| 369 | |
| 370 | // bearer re-fetches the roster bearer by exact replay of step 5: Alta |
| 371 | // never stores it (§4). |
| 372 | func (e *Engine) bearer(ctx context.Context, p *pass, app App) (string, error) { |
| 373 | prev, ok, err := e.cfg.Store.LastRequest(ctx, p.run.Label, app.Slug, "provision") |
| 374 | if err != nil || !ok || prev.State != "committed" { |
| 375 | return "", fail("bearer-unrecoverable") |
| 376 | } |
| 377 | res, _, o := e.cfg.Home.Execute(ctx, homeop.Directory, prev.Bytes) |
| 378 | if o != homeop.OK { |
| 379 | return "", park("home-unavailable") |
| 380 | } |
| 381 | if res.Bearer == "" { |
| 382 | return "", fail("bearer-unrecoverable") |
| 383 | } |
| 384 | return res.Bearer, nil |
| 385 | } |
| 386 | |
| 387 | // ---- step 6: credential consumer ---- |
| 388 | |
| 389 | func (e *Engine) stepRegister(ctx context.Context, p *pass, app App) error { |
| 390 | rec, _, err := e.consumerData(ctx, p, app) |
| 391 | if err != nil { |
| 392 | return err |
| 393 | } |
| 394 | if _, held, _ := e.cfg.Store.LastRequest(ctx, p.run.Label, app.Slug, "register"); !held { |
| 395 | if err := e.needWindow(p, homeop.Credential); err != nil { |
| 396 | return err |
| 397 | } |
| 398 | } |
| 399 | res, err := e.op(ctx, opSpec{role: homeop.Credential, action: homeop.CredentialRegister, label: p.run.Label, app: app.Slug, purpose: "register", reuse: true, |
| 400 | build: func(b homeop.InputBase) any { return homeop.RegisterInput{InputBase: b, Record: rec} }}) |
| 401 | if errors.Is(err, errOpRefused) { |
| 402 | return fail("register-refused") |
| 403 | } |
| 404 | if err != nil { |
| 405 | return err |
| 406 | } |
| 407 | if !homeop.CanonicalToken(res.Manifest) { |
| 408 | return fail("manifest-digest") |
| 409 | } |
| 410 | return e.record(ctx, p, app.Slug, StepRegister, map[string]any{"manifest_digest": res.Manifest}) |
| 411 | } |
| 412 | |
| 413 | // ---- step 7: environment ---- |
| 414 | |
| 415 | func (e *Engine) inputs(ctx context.Context, p *pass, app App) (Inputs, error) { |
| 416 | in := Inputs{Label: p.run.Label, Account: e.cfg.Account, TeamSQID: p.team.TeamSQID, Home: e.cfg.HomeCfg, CallsZone: e.cfg.CallsZone, RunOptions: p.run.Options} |
| 417 | if owner, ok, err := e.cfg.Store.Owner(ctx, p.run.Label); err != nil { |
| 418 | return in, err |
| 419 | } else if ok { |
| 420 | in.Owner = owner |
| 421 | } |
| 422 | if app.Roster { |
| 423 | rec, _, err := e.consumerData(ctx, p, app) |
| 424 | if err != nil { |
| 425 | return in, err |
| 426 | } |
| 427 | in.Record = rec |
| 428 | } |
| 429 | return in, nil |
| 430 | } |
| 431 | |
| 432 | func (e *Engine) stepEnv(ctx context.Context, p *pass, app App) error { |
| 433 | env := p.team.Environment |
| 434 | in, err := e.inputs(ctx, p, app) |
| 435 | if err != nil { |
| 436 | return err |
| 437 | } |
| 438 | keys := Recipe(app, in) |
| 439 | cfg, found, err := e.cfg.Console.GetConfig(ctx, app.Slug, env) |
| 440 | if err != nil { |
| 441 | return park("console-unavailable") |
| 442 | } |
| 443 | present := cfg.Keys() |
| 444 | set := map[string]console.SetVar{} |
| 445 | var unset []string |
| 446 | recipe := map[string]bool{} |
| 447 | // Paul's own post-run keys (an own team's Memoria AI), once he has |
| 448 | // set the whole group: Alta neither writes nor removes them. Part of |
| 449 | // one (a fork's blanked MEMORIA_AI) is any other key. |
| 450 | operator := OperatorKeys(app, in) |
| 451 | switch operatorState(operator, lookup(present)) { |
| 452 | case OperatorWhole: |
| 453 | for _, k := range operator { |
| 454 | recipe[k.Name] = true |
| 455 | } |
| 456 | case OperatorInvalid: |
| 457 | // The whole pair, but not as memoria reads it: Paul's to fix, |
| 458 | // here rather than at the audit. |
| 459 | return fail("operator-keys-invalid") |
| 460 | } |
| 461 | ownWrites := profileWrites(app, in.Label) |
| 462 | running := false // a write landed on an instance already running |
| 463 | for _, k := range keys { |
| 464 | recipe[k.Name] = true |
| 465 | if k.Class != Set { |
| 466 | continue |
| 467 | } |
| 468 | have, ok := present[k.Name] |
| 469 | if k.OwnerAddress && in.Owner == "" { |
| 470 | if ok && have.Kind == "env" && have.Value != "" { |
| 471 | continue |
| 472 | } |
| 473 | return park("owner-retype-needed") |
| 474 | } |
| 475 | if !ok || have.Kind != "env" || have.Value != k.Value { |
| 476 | set[k.Name] = console.SetVar{Kind: "env", Value: k.Value} |
| 477 | } |
| 478 | } |
| 479 | for name := range present { |
| 480 | if recipe[name] || console.PlatformManaged(name) { |
| 481 | continue |
| 482 | } |
| 483 | if v, ok := ownWrites[name]; !p.team.Forked && !(ok && present[name].Kind == "env" && present[name].Value == v) { |
| 484 | // A key exactly as Alta writes it under another run's profile |
| 485 | // or samples choice (OFICINA_DASHBOARD_TEAM=<label>, |
| 486 | // DOCS_SAMPLE_DOCUMENTS=1, written before that run parked) is |
| 487 | // Alta's own to take back out; anything else refuses. |
| 488 | return fail("extra-key") |
| 489 | } |
| 490 | // A forked environment carries Track 1's own keys: anything the |
| 491 | // recipe does not name goes (OFICINA_DASHBOARD_TEAM, MEMORIA_AI…). |
| 492 | unset = append(unset, name) |
| 493 | } |
| 494 | if len(set) > 0 || len(unset) > 0 { |
| 495 | put, err := e.cfg.Console.PutConfig(ctx, app.Slug, env, set, unset, "alta: team environment") |
| 496 | if err != nil { |
| 497 | if errors.Is(err, console.ErrGuard) { |
| 498 | return err |
| 499 | } |
| 500 | return park("console-write") |
| 501 | } |
| 502 | running = running || put.RestartsHosts() |
| 503 | if err := e.acted("env-set/" + app.Slug); err != nil { |
| 504 | return err |
| 505 | } |
| 506 | if cfg, found, err = e.cfg.Console.GetConfig(ctx, app.Slug, env); err != nil || !found { |
| 507 | return park("console-unavailable") |
| 508 | } |
| 509 | present = cfg.Keys() |
| 510 | } |
| 511 | if !found { |
| 512 | return park("environment-absent") |
| 513 | } |
| 514 | // GENERATED keys: existence is checked by name; an existing key is |
| 515 | // never regenerated (a DEK that changes under a database makes it |
| 516 | // unreadable). Values are sealed to the console's key and forgotten. |
| 517 | gen := map[string]console.SetVar{} |
| 518 | for _, k := range keys { |
| 519 | if k.Class != Generated { |
| 520 | continue |
| 521 | } |
| 522 | if _, ok := present[k.Name]; ok { |
| 523 | continue |
| 524 | } |
| 525 | value := "" |
| 526 | if k.FromHome { |
| 527 | if value, err = e.bearer(ctx, p, app); err != nil { |
| 528 | return err |
| 529 | } |
| 530 | } else { |
| 531 | value = freshKey() |
| 532 | } |
| 533 | if cfg.SecretsPubKey == "" { |
| 534 | return fail("no-secrets-pubkey") |
| 535 | } |
| 536 | envelope, err := console.Seal(cfg.SecretsPubKey, cfg.SecretsAccount, app.Slug, []byte(value)) |
| 537 | if err != nil { |
| 538 | return fail("seal") |
| 539 | } |
| 540 | gen[k.Name] = console.SetVar{Kind: "secret", Envelope: envelope} |
| 541 | } |
| 542 | if len(gen) > 0 { |
| 543 | put, err := e.cfg.Console.PutConfig(ctx, app.Slug, env, gen, nil, "alta: team keys") |
| 544 | if err != nil { |
| 545 | if errors.Is(err, console.ErrGuard) { |
| 546 | return err |
| 547 | } |
| 548 | return park("console-write") |
| 549 | } |
| 550 | running = running || put.RestartsHosts() |
| 551 | if err := e.acted("env-generate/" + app.Slug); err != nil { |
| 552 | return err |
| 553 | } |
| 554 | if cfg, found, err = e.cfg.Console.GetConfig(ctx, app.Slug, env); err != nil || !found { |
| 555 | return park("console-unavailable") |
| 556 | } |
| 557 | present = cfg.Keys() |
| 558 | } |
| 559 | if running { |
| 560 | // Config written under a running instance needs a restart (step |
| 561 | // 10 does it): a forked environment's instance, or a re-run. |
| 562 | _ = e.cfg.Store.SetStep(ctx, p.run.Label, app.Slug, "restart", "parked", "config-changed", map[string]any{"at": e.now().Unix()}) |
| 563 | } |
| 564 | names := map[string]bool{} |
| 565 | for k := range present { |
| 566 | names[k] = true |
| 567 | } |
| 568 | // PLATFORM keys arrive on the walks' cadence, not at PUT /config. |
| 569 | ps := PlatformKeys(app, names) |
| 570 | if ps.WrongPrefix != "" { |
| 571 | return fail("mail-prefix-" + app.Slug) |
| 572 | } |
| 573 | if len(ps.Missing) > 0 { |
| 574 | return park("awaiting-platform-keys") |
| 575 | } |
| 576 | return e.record(ctx, p, app.Slug, StepEnv, map[string]any{"platform": ps.Keys, "binding": EnvironmentBinding(env, keys, ps.Keys), |
| 577 | "profile": string(in.Profile), "samples": in.Samples}) |
| 578 | } |
| 579 | |
| 580 | // ---- step 8: instance ---- |
| 581 | |
| 582 | func (e *Engine) stepInstance(ctx context.Context, p *pass, app App) error { |
| 583 | env, host := p.team.Environment, RouteHost(p.run.Label, app.Slug, e.cfg.Account) |
| 584 | inst, found, err := e.cfg.Console.GetInstance(ctx, app.Slug, host) |
| 585 | if err != nil { |
| 586 | return park("console-unavailable") |
| 587 | } |
| 588 | if !found { |
| 589 | err := e.cfg.Console.CreateInstance(ctx, app.Slug, host, env, "alta: team instance") |
| 590 | if err != nil && !console.IsConflict(err) { |
| 591 | if errors.Is(err, console.ErrGuard) { |
| 592 | return err |
| 593 | } |
| 594 | return park("console-write") |
| 595 | } |
| 596 | if err == nil { |
| 597 | if err := e.acted("instance/" + app.Slug); err != nil { |
| 598 | return err |
| 599 | } |
| 600 | } |
| 601 | if inst, found, err = e.cfg.Console.GetInstance(ctx, app.Slug, host); err != nil { |
| 602 | return park("console-unavailable") |
| 603 | } |
| 604 | if !found { |
| 605 | // 409 and still not ours: the host is held outside the scope. |
| 606 | return fail("host-held") |
| 607 | } |
| 608 | } |
| 609 | if inst.Environment != env { |
| 610 | return fail("instance-bound-elsewhere") |
| 611 | } |
| 612 | return e.record(ctx, p, app.Slug, StepInstance, map[string]any{"route": host, "created_at": e.now().Unix()}) |
| 613 | } |
| 614 | |
| 615 | // ---- step 9: domain ---- |
| 616 | |
| 617 | func (e *Engine) stepDomain(ctx context.Context, p *pass, app App) error { |
| 618 | host, route := PublicHost(p.run.Label, app.Slug), RouteHost(p.run.Label, app.Slug, e.cfg.Account) |
| 619 | d, found, err := e.cfg.Console.GetDomain(ctx, app.Slug, host) |
| 620 | if err != nil { |
| 621 | return park("console-unavailable") |
| 622 | } |
| 623 | prev, _, _ := e.cfg.Store.Step(ctx, p.run.Label, app.Slug, StepDomain) |
| 624 | since := num(prev.Data, "attached_at") |
| 625 | if !found { |
| 626 | if err := e.cfg.Console.AttachDomain(ctx, app.Slug, host, route, "alta: team hostname"); err != nil && !console.IsConflict(err) { |
| 627 | if errors.Is(err, console.ErrGuard) { |
| 628 | return err |
| 629 | } |
| 630 | return park("console-write") |
| 631 | } |
| 632 | if err := e.acted("domain/" + app.Slug); err != nil { |
| 633 | return err |
| 634 | } |
| 635 | since = e.now().Unix() |
| 636 | if d, found, err = e.cfg.Console.GetDomain(ctx, app.Slug, host); err != nil || !found { |
| 637 | _ = e.cfg.Store.SetStep(ctx, p.run.Label, app.Slug, StepDomain, "parked", "domain-attaching", map[string]any{"attached_at": since}) |
| 638 | return park("domain-attaching") |
| 639 | } |
| 640 | } |
| 641 | if since == 0 { |
| 642 | since = e.now().Unix() |
| 643 | } |
| 644 | if d.Route != route { |
| 645 | return fail("domain-route") |
| 646 | } |
| 647 | if d.State == "live" { |
| 648 | return e.record(ctx, p, app.Slug, StepDomain, map[string]any{"host": host}) |
| 649 | } |
| 650 | code := "domain-" + d.State |
| 651 | if e.now().Sub(time.Unix(since, 0)) > DomainPatience { |
| 652 | code = "domain-slow-" + d.State |
| 653 | } |
| 654 | _ = e.cfg.Store.SetStep(ctx, p.run.Label, app.Slug, StepDomain, "parked", code, map[string]any{"attached_at": since, "reason": d.Reason}) |
| 655 | return park(code) |
| 656 | } |
| 657 | |
| 658 | // ---- step 10: serving ---- |
| 659 | |
| 660 | func (e *Engine) get(ctx context.Context, url string) (int, []byte, error) { |
| 661 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) |
| 662 | if err != nil { |
| 663 | return 0, nil, err |
| 664 | } |
| 665 | resp, err := e.cfg.Public.Do(req) |
| 666 | if err != nil { |
| 667 | return 0, nil, err |
| 668 | } |
| 669 | defer resp.Body.Close() |
| 670 | b, err := io.ReadAll(io.LimitReader(resp.Body, 4096)) |
| 671 | return resp.StatusCode, b, err |
| 672 | } |
| 673 | |
| 674 | func (e *Engine) stepServing(ctx context.Context, p *pass, app App) error { |
| 675 | route := RouteHost(p.run.Label, app.Slug, e.cfg.Account) |
| 676 | row, found, err := e.cfg.Console.ListedHost(ctx, app.Slug, route) |
| 677 | if err != nil || !found { |
| 678 | return park("console-unavailable") |
| 679 | } |
| 680 | restart, needs, _ := e.cfg.Store.Step(ctx, p.run.Label, app.Slug, "restart") |
| 681 | if (needs && restart.State == "parked") || (row.Rollout != nil && row.Rollout.ConfigPending) { |
| 682 | if err := e.cfg.Console.RestartHost(ctx, app.Slug, route, "alta: config changed"); err != nil { |
| 683 | if errors.Is(err, console.ErrGuard) { |
| 684 | return err |
| 685 | } |
| 686 | return park("console-write") |
| 687 | } |
| 688 | if err := e.acted("restart/" + app.Slug); err != nil { |
| 689 | return err |
| 690 | } |
| 691 | _ = e.cfg.Store.SetStep(ctx, p.run.Label, app.Slug, "restart", "done", "", map[string]any{"at": e.now().Unix()}) |
| 692 | return park("restarting") |
| 693 | } |
| 694 | // The box's report: awake, not starting or stopping, its config |
| 695 | // applied, and naming the build it runs. |
| 696 | if row.Rollout == nil || row.Rollout.Serving == "" { |
| 697 | return park("awaiting-box-report") |
| 698 | } |
| 699 | if !row.Rollout.Awake || row.Rollout.Transient { |
| 700 | return park("instance-waking") |
| 701 | } |
| 702 | status, body, err := e.get(ctx, PublicOrigin(p.run.Label, app.Slug)+"/api/version") |
| 703 | if err != nil || status != http.StatusOK { |
| 704 | return park("version-unreachable") |
| 705 | } |
| 706 | version := strings.TrimSpace(string(body)) |
| 707 | // "dev" is rastrillo's unstamped default: such a build names nothing. |
| 708 | if version == "" || version == "dev" { |
| 709 | return park("version-unstamped") |
| 710 | } |
| 711 | // Checked for every app, not only those that activate: anything else |
| 712 | // in the body (an error page, a proxy's text) is not a version. |
| 713 | if !activationVersion.MatchString(version) { |
| 714 | return park("version-unacceptable") |
| 715 | } |
| 716 | // The two names need not agree: the box's is the release version |
| 717 | // `carlos ship` recorded, /api/version is the binary's stamp (git |
| 718 | // describe). Both are recorded — app_version for the evidence, |
| 719 | // serving for artifact_digest — and a difference is only noted. |
| 720 | data := map[string]any{"app_version": version, "serving": row.Rollout.Serving} |
| 721 | if row.Rollout.Serving != version { |
| 722 | data["names_differ"] = true |
| 723 | e.cfg.Store.Audit(ctx, p.run.ID, p.run.Label, app.Slug, "serving-names-differ", "") |
| 724 | } |
| 725 | return e.record(ctx, p, app.Slug, StepServing, data) |
| 726 | } |
| 727 | |
| 728 | // ---- steps 11 and 12: verify and activate (roster-mode apps) ---- |
| 729 | |
| 730 | // TeamProbe is GET /api/team's readiness answer (team-members.md §7). |
| 731 | // |
| 732 | // A seeded app (Equipo, Base) answers team_mode false and seeded true, |
| 733 | // with roster "ok" once an owner exists and "owner-pending" before. |
| 734 | type TeamProbe struct { |
| 735 | TeamMode bool `json:"team_mode"` |
| 736 | Seeded bool `json:"seeded"` |
| 737 | Consumer string `json:"consumer"` |
| 738 | Roster string `json:"roster"` |
| 739 | } |
| 740 | |
| 741 | func (e *Engine) stepVerify(ctx context.Context, p *pass, app App) error { |
| 742 | now := e.now().Unix() |
| 743 | prev, _, _ := e.cfg.Store.Step(ctx, p.run.Label, app.Slug, StepVerify) |
| 744 | attempt, expires := str(prev.Data, "attempt"), num(prev.Data, "expires_at") |
| 745 | if attempt == "" || expires <= now+60 { |
| 746 | if err := e.needWindow(p, homeop.Directory); err != nil { |
| 747 | return err |
| 748 | } |
| 749 | _, cd, err := e.consumerData(ctx, p, app) |
| 750 | if err != nil { |
| 751 | return err |
| 752 | } |
| 753 | issued := now - homeop.Skew |
| 754 | spec := opSpec{role: homeop.Directory, action: homeop.DirectoryVerify, label: p.run.Label, app: app.Slug, purpose: "verify", reuse: true, |
| 755 | build: func(b homeop.InputBase) any { |
| 756 | return homeop.VerificationInput{InputBase: b, Consumer: ConsumerID(p.run.Label, app.Slug), TeamSQID: p.team.TeamSQID, App: app.Slug, Audience: PublicOrigin(p.run.Label, app.Slug), |
| 757 | Generation: str(cd, "generation"), RecordSequence: 1, RecordDigest: str(cd, "record_digest"), Epoch: num(cd, "epoch"), Owner: p.team.OwnerRef, Issued: issued, Expires: issued + 600} |
| 758 | }} |
| 759 | // An attempt Home already holds is used while it lives: Home |
| 760 | // refuses a second verify for the consumer until the first |
| 761 | // expires, and its answer may have been lost (then recovered by |
| 762 | // replay, or committed by a stream resync). One whose expiry has |
| 763 | // passed is replaced by a new verify, never renewed. Its own |
| 764 | // issued_at is not in the result, so a later one is recorded, |
| 765 | // which activation's started_at ≥ issued_at still admits. |
| 766 | res, held, err := e.replayHeld(ctx, spec) |
| 767 | if held && err != nil { |
| 768 | return err |
| 769 | } |
| 770 | if !held || res.Expires <= now+60 { |
| 771 | spec.reuse = false |
| 772 | res, err = e.op(ctx, spec) |
| 773 | if errors.Is(err, errOpRefused) { |
| 774 | return fail("verify-refused") |
| 775 | } |
| 776 | if err != nil { |
| 777 | return err |
| 778 | } |
| 779 | } |
| 780 | attempt, expires = res.Attempt, res.Expires |
| 781 | _ = e.cfg.Store.SetStep(ctx, p.run.Label, app.Slug, StepVerify, "parked", "awaiting-roster", map[string]any{"attempt": attempt, "issued_at": issued, "expires_at": expires}) |
| 782 | prev.Data = map[string]any{"attempt": attempt, "issued_at": issued, "expires_at": expires} |
| 783 | } |
| 784 | if p.run.Adoption { |
| 785 | // An adopted instance keeps its own access: adoption enables no team |
| 786 | // mode, so there is no /api/team readiness to wait for. The |
| 787 | // Observer's re-observation at activation stands in for it. |
| 788 | return e.record(ctx, p, app.Slug, StepVerify, prev.Data) |
| 789 | } |
| 790 | status, body, err := e.get(ctx, PublicOrigin(p.run.Label, app.Slug)+"/api/team") |
| 791 | if err != nil { |
| 792 | return park("roster-unreachable") |
| 793 | } |
| 794 | if status == http.StatusNotFound { |
| 795 | return park("no-readiness-probe") |
| 796 | } |
| 797 | var probe TeamProbe |
| 798 | if status != http.StatusOK || json.Unmarshal(body, &probe) != nil { |
| 799 | return park("roster-unreadable") |
| 800 | } |
| 801 | if probe.TeamMode == app.Seeded || probe.Seeded != app.Seeded { |
| 802 | // A roster app answering seeded, or a seeded app claiming roster |
| 803 | // mode, is not the build this recipe was written for. |
| 804 | if probe.TeamMode || probe.Seeded { |
| 805 | return park("probe-mode-mismatch") |
| 806 | } |
| 807 | return park("not-team-mode") |
| 808 | } |
| 809 | if probe.Consumer != ConsumerID(p.run.Label, app.Slug) { |
| 810 | return park("not-team-mode") |
| 811 | } |
| 812 | if probe.Roster != "ok" { |
| 813 | return park("roster-" + probe.Roster) |
| 814 | } |
| 815 | return e.record(ctx, p, app.Slug, StepVerify, prev.Data) |
| 816 | } |
| 817 | |
| 818 | func artifactDigest(serving string) string { |
| 819 | s := sha256.Sum256([]byte(serving)) |
| 820 | return base64.RawURLEncoding.EncodeToString(s[:]) |
| 821 | } |
| 822 | |
| 823 | // activationVersion is the app_version Home's directory.activate-consumer |
| 824 | // admits: an observed, opaque, printable token (Home 0cee9ba, |
| 825 | // internal/operator/verification.go observedVersion), mirrored here so a |
| 826 | // build Home would refuse parks at step 10 instead of failing activation. |
| 827 | var activationVersion = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$`) |
| 828 | |
| 829 | func (e *Engine) stepActivate(ctx context.Context, p *pass, app App) error { |
| 830 | if p.run.Adoption { |
| 831 | return e.stepActivateAdopted(ctx, p, app) |
| 832 | } |
| 833 | st := e.cfg.Store |
| 834 | label := p.run.Label |
| 835 | if prev, ok, _ := st.LastRequest(ctx, label, app.Slug, "activate"); !ok || prev.State != "committed" { |
| 836 | if err := e.needWindow(p, homeop.Directory); err != nil { |
| 837 | return err |
| 838 | } |
| 839 | } |
| 840 | v, _, _ := st.Done(ctx, label, app.Slug, StepVerify) |
| 841 | sv, _, _ := st.Done(ctx, label, app.Slug, StepServing) |
| 842 | envd, _, _ := st.Done(ctx, label, app.Slug, StepEnv) |
| 843 | reg, _, _ := st.Done(ctx, label, app.Slug, StepRegister) |
| 844 | _, cd, err := e.consumerData(ctx, p, app) |
| 845 | if err != nil { |
| 846 | return err |
| 847 | } |
| 848 | now := e.now().Unix() |
| 849 | if _, committed, _ := st.LastRequest(ctx, label, app.Slug, "activate"); !committed && num(v, "expires_at") <= now+10 { |
| 850 | // The attempt lapsed: verify again. |
| 851 | _ = st.SetStep(ctx, label, app.Slug, StepVerify, "parked", "attempt-expired", nil) |
| 852 | return park("attempt-expired") |
| 853 | } |
| 854 | version := str(sv, "app_version") |
| 855 | ev := homeop.ActivationEvidence{Version: 1, Policy: homeop.ActivationPolicy, Attempt: str(v, "attempt"), Consumer: ConsumerID(label, app.Slug), TeamSQID: p.team.TeamSQID, App: app.Slug, |
| 856 | Audience: PublicOrigin(label, app.Slug), Generation: str(cd, "generation"), RecordSequence: 1, RecordDigest: str(cd, "record_digest"), Epoch: num(cd, "epoch"), Owner: p.team.OwnerRef, |
| 857 | AppVersion: version, ArtifactDigest: artifactDigest(str(sv, "serving")), EnvironmentBinding: str(envd, "binding"), ManifestDigest: str(reg, "manifest_digest"), |
| 858 | AliasHost: PublicHost(label, app.Slug), Started: num(v, "issued_at"), Completed: now - homeop.Skew} |
| 859 | _, err = e.op(ctx, opSpec{role: homeop.Directory, action: homeop.DirectoryActivate, label: label, app: app.Slug, purpose: "activate", reuse: true, |
| 860 | build: func(b homeop.InputBase) any { return homeop.ActivationInput{InputBase: b, Evidence: ev} }}) |
| 861 | if errors.Is(err, errOpRefused) { |
| 862 | return fail("activate-refused") |
| 863 | } |
| 864 | if err != nil { |
| 865 | return err |
| 866 | } |
| 867 | return e.record(ctx, p, app.Slug, StepActivate, map[string]any{"app_version": version}) |
| 868 | } |
| 869 | |
| 870 | // ---- step 13: audit ---- |
| 871 | |
| 872 | // AuditEnvironment is §5's exact-keys rule for one app: the environment |
| 873 | // holds GENERATED ∪ SET ∪ PLATFORM and nothing else, SET values as the |
| 874 | // recipe says (owner-address values only checked present once Alta has |
| 875 | // forgotten the address). |
| 876 | func (e *Engine) AuditEnvironment(ctx context.Context, label string, app App) error { |
| 877 | t, err := e.cfg.Store.Team(ctx, label) |
| 878 | if err != nil { |
| 879 | return err |
| 880 | } |
| 881 | opt, err := e.writtenOptions(ctx, label, app) |
| 882 | if err != nil { |
| 883 | return err |
| 884 | } |
| 885 | p := &pass{run: Run{Label: label, Options: opt}, team: t} |
| 886 | in, err := e.inputs(ctx, p, app) |
| 887 | if err != nil { |
| 888 | return err |
| 889 | } |
| 890 | keys := Recipe(app, in) |
| 891 | cfg, found, err := e.cfg.Console.GetConfig(ctx, app.Slug, t.Environment) |
| 892 | if err != nil { |
| 893 | return park("console-unavailable") |
| 894 | } |
| 895 | if !found { |
| 896 | return fail("audit-environment-absent") |
| 897 | } |
| 898 | present := cfg.Keys() |
| 899 | names := map[string]bool{} |
| 900 | for k := range present { |
| 901 | names[k] = true |
| 902 | } |
| 903 | ps := PlatformKeys(app, names) |
| 904 | if ps.WrongPrefix != "" { |
| 905 | return fail("mail-prefix-" + app.Slug) |
| 906 | } |
| 907 | want := map[string]Key{} |
| 908 | for _, k := range keys { |
| 909 | want[k.Name] = k |
| 910 | } |
| 911 | for _, k := range ps.Keys { |
| 912 | want[k] = Key{Name: k, Class: Platform} |
| 913 | } |
| 914 | // The object store (Slides): CARLOS's walk delivers the whole set in |
| 915 | // one write, so it is admitted whole, each with its kind, or refused. |
| 916 | if len(ps.Store) > 0 { |
| 917 | for _, k := range StoreKeys { |
| 918 | have, ok := present[k.Name] |
| 919 | switch { |
| 920 | case !ok && !k.Optional: |
| 921 | return fail("audit-store-partial") |
| 922 | case !ok: |
| 923 | case k.Secret && have.Kind != "secret", !k.Secret && have.Kind != "env": |
| 924 | return fail("audit-kind") |
| 925 | default: |
| 926 | want[k.Name] = Key{Name: k.Name, Class: Platform} |
| 927 | } |
| 928 | } |
| 929 | } |
| 930 | // Paul's post-run group (an own team's Memoria AI) is admitted |
| 931 | // whole or not at all, never one key of it. |
| 932 | operator := OperatorKeys(app, in) |
| 933 | admitted := map[string]bool{} |
| 934 | switch operatorState(operator, lookup(present)) { |
| 935 | case OperatorPartial: |
| 936 | return fail("audit-operator-partial") |
| 937 | case OperatorInvalid: |
| 938 | return fail("operator-keys-invalid") |
| 939 | case OperatorWhole: |
| 940 | for _, k := range operator { |
| 941 | admitted[k.Name] = true |
| 942 | } |
| 943 | } |
| 944 | for name := range present { |
| 945 | if _, ok := want[name]; !ok && !admitted[name] { |
| 946 | return fail("audit-extra-key") |
| 947 | } |
| 948 | } |
| 949 | for name, k := range want { |
| 950 | have, ok := present[name] |
| 951 | if !ok { |
| 952 | if k.Class == Platform { |
| 953 | return park("awaiting-platform-keys") |
| 954 | } |
| 955 | return fail("audit-missing-key") |
| 956 | } |
| 957 | switch k.Class { |
| 958 | case Generated: |
| 959 | if have.Kind != "secret" { |
| 960 | return fail("audit-kind") |
| 961 | } |
| 962 | case Set: |
| 963 | if have.Kind != "env" { |
| 964 | return fail("audit-kind") |
| 965 | } |
| 966 | if k.OwnerAddress && in.Owner == "" { |
| 967 | if have.Value == "" { |
| 968 | return fail("audit-allowlist-empty") |
| 969 | } |
| 970 | continue |
| 971 | } |
| 972 | if have.Value != k.Value { |
| 973 | return fail("audit-value") |
| 974 | } |
| 975 | } |
| 976 | } |
| 977 | if len(ps.Missing) > 0 { |
| 978 | return park("awaiting-platform-keys") |
| 979 | } |
| 980 | return nil |
| 981 | } |
| 982 | |
| 983 | // lookup reads a console config's keys for operatorState. |
| 984 | func lookup(present map[string]console.Var) func(string) (string, string, bool) { |
| 985 | return func(name string) (string, string, bool) { |
| 986 | v, ok := present[name] |
| 987 | return v.Kind, v.Value, ok |
| 988 | } |
| 989 | } |
| 990 | |
| 991 | // writtenOptions is the run options app's environment was written with |
| 992 | // (Store.WrittenOptions); an environment not yet written has the default. |
| 993 | func (e *Engine) writtenOptions(ctx context.Context, label string, app App) (RunOptions, error) { |
| 994 | opt, ok, err := e.cfg.Store.WrittenOptions(ctx, label, app.Slug) |
| 995 | if err != nil { |
| 996 | return RunOptions{}, err |
| 997 | } |
| 998 | if !ok { |
| 999 | return RunOptions{Profile: ProfileOutside}, nil |
| 1000 | } |
| 1001 | return opt, nil |
| 1002 | } |
| 1003 | |
| 1004 | func (e *Engine) stepAudit(ctx context.Context, p *pass, app App) error { |
| 1005 | if err := e.AuditEnvironment(ctx, p.run.Label, app); err != nil { |
| 1006 | return err |
| 1007 | } |
| 1008 | pending := !app.Roster && !app.Seeded |
| 1009 | return e.record(ctx, p, app.Slug, StepAudit, map[string]any{"directory_pending": pending}) |
| 1010 | } |
| 1011 | |
| 1012 | // forgetOwnerWhenWritten deletes §4's address-bearing rows once the seed |
| 1013 | // has committed and every active app whose recipe holds the owner (a |
| 1014 | // stopgap allowlist) has its environment written. With every app in |
| 1015 | // roster mode, no recipe holds it, and the address goes as soon as the |
| 1016 | // seed commits. |
| 1017 | func (e *Engine) forgetOwnerWhenWritten(ctx context.Context, p *pass) error { |
| 1018 | st := e.cfg.Store |
| 1019 | if _, held, _ := st.Owner(ctx, p.run.Label); !held { |
| 1020 | return nil |
| 1021 | } |
| 1022 | t, err := st.Team(ctx, p.run.Label) |
| 1023 | if err != nil { |
| 1024 | return err |
| 1025 | } |
| 1026 | // Seeded: the team step done, or Home's team sqid recorded (either |
| 1027 | // alone is enough; SetSeeded writes both at once). Before the seed the |
| 1028 | // address is still owner-seed's input. |
| 1029 | if _, done, _ := st.Done(ctx, p.run.Label, "", StepTeam); !done && t.TeamSQID == "" { |
| 1030 | return nil |
| 1031 | } |
| 1032 | for app, state := range t.Apps { |
| 1033 | spec, _ := AppBySlug(app) |
| 1034 | if state != "active" || !NeedsOwner(spec) { |
| 1035 | continue |
| 1036 | } |
| 1037 | if _, ok, _ := st.Done(ctx, p.run.Label, app, StepEnv); !ok { |
| 1038 | return nil |
| 1039 | } |
| 1040 | } |
| 1041 | if err := st.ForgetOwner(ctx, p.run.Label); err != nil { |
| 1042 | return err |
| 1043 | } |
| 1044 | st.Audit(ctx, p.run.ID, p.run.Label, "", "owner-forgotten", "") |
| 1045 | return nil |
| 1046 | } |
| 1047 | |
| 1048 | // ---- deprovision (§9) ---- |
| 1049 | |
| 1050 | func (e *Engine) retire(ctx context.Context, p *pass) error { |
| 1051 | ctx = WithDeprovision(ctx, p.run.ID) |
| 1052 | var first error |
| 1053 | for _, slug := range p.run.Apps { |
| 1054 | app, _ := AppBySlug(slug) |
| 1055 | err := e.retireApp(ctx, p, app) |
| 1056 | if errors.Is(err, errCrash) { |
| 1057 | return err |
| 1058 | } |
| 1059 | var fl *Fail |
| 1060 | if errors.As(err, &fl) || errors.Is(err, console.ErrGuard) { |
| 1061 | return err |
| 1062 | } |
| 1063 | if err != nil && first == nil { |
| 1064 | first = err |
| 1065 | } |
| 1066 | } |
| 1067 | return first |
| 1068 | } |
| 1069 | |
| 1070 | func (e *Engine) retireApp(ctx context.Context, p *pass, app App) error { |
| 1071 | st := e.cfg.Store |
| 1072 | label := p.run.Label |
| 1073 | for _, step := range RetireSteps { |
| 1074 | if _, ok, err := st.Done(ctx, label, app.Slug, step); err != nil { |
| 1075 | return err |
| 1076 | } else if ok { |
| 1077 | continue |
| 1078 | } |
| 1079 | var err error |
| 1080 | switch step { |
| 1081 | case StepDisable: |
| 1082 | err = e.stepDisable(ctx, p, app) |
| 1083 | case StepRetire: |
| 1084 | err = e.stepRetireConsumer(ctx, p, app) |
| 1085 | case StepDetach: |
| 1086 | err = e.stepDetach(ctx, p, app) |
| 1087 | case StepDelete: |
| 1088 | err = e.stepDelete(ctx, p, app) |
| 1089 | } |
| 1090 | if err != nil { |
| 1091 | if !errors.Is(err, errCrash) { |
| 1092 | e.note(ctx, p, app.Slug, step, err, nil) |
| 1093 | } |
| 1094 | return err |
| 1095 | } |
| 1096 | } |
| 1097 | if err := st.RetireApp(ctx, label, app.Slug); err != nil { |
| 1098 | return err |
| 1099 | } |
| 1100 | st.Audit(ctx, p.run.ID, label, app.Slug, "app-retired", "") |
| 1101 | return nil |
| 1102 | } |
| 1103 | |
| 1104 | func (e *Engine) stepDisable(ctx context.Context, p *pass, app App) error { |
| 1105 | if _, ok, _ := e.cfg.Store.Done(ctx, p.run.Label, app.Slug, StepConsumer); !ok { |
| 1106 | return e.record(ctx, p, app.Slug, StepDisable, map[string]any{"skipped": "never-provisioned"}) |
| 1107 | } |
| 1108 | if _, held, _ := e.cfg.Store.LastRequest(ctx, p.run.Label, app.Slug, "disable"); !held { |
| 1109 | if err := e.needWindow(p, homeop.Directory); err != nil { |
| 1110 | return err |
| 1111 | } |
| 1112 | } |
| 1113 | _, err := e.op(ctx, opSpec{role: homeop.Directory, action: homeop.DirectoryDisable, label: p.run.Label, app: app.Slug, purpose: "disable", reuse: true, |
| 1114 | build: func(b homeop.InputBase) any { |
| 1115 | return homeop.DisableInput{InputBase: b, Generation: p.team.Generation, TeamSQID: p.team.TeamSQID, App: app.Slug, Consumer: ConsumerID(p.run.Label, app.Slug)} |
| 1116 | }}) |
| 1117 | if errors.Is(err, errOpRefused) { |
| 1118 | return fail("disable-refused") |
| 1119 | } |
| 1120 | if err != nil { |
| 1121 | return err |
| 1122 | } |
| 1123 | return e.record(ctx, p, app.Slug, StepDisable, nil) |
| 1124 | } |
| 1125 | |
| 1126 | func (e *Engine) stepRetireConsumer(ctx context.Context, p *pass, app App) error { |
| 1127 | if _, ok, _ := e.cfg.Store.Done(ctx, p.run.Label, app.Slug, StepRegister); !ok { |
| 1128 | return e.record(ctx, p, app.Slug, StepRetire, map[string]any{"skipped": "never-registered"}) |
| 1129 | } |
| 1130 | if _, held, _ := e.cfg.Store.LastRequest(ctx, p.run.Label, app.Slug, "retire"); !held { |
| 1131 | if err := e.needWindow(p, homeop.Credential); err != nil { |
| 1132 | return err |
| 1133 | } |
| 1134 | } |
| 1135 | _, err := e.op(ctx, opSpec{role: homeop.Credential, action: homeop.CredentialRetire, label: p.run.Label, app: app.Slug, purpose: "retire", reuse: true, |
| 1136 | build: func(b homeop.InputBase) any { |
| 1137 | return homeop.RetireInput{InputBase: b, Consumer: ConsumerID(p.run.Label, app.Slug)} |
| 1138 | }}) |
| 1139 | if errors.Is(err, errOpRefused) { |
| 1140 | return fail("retire-refused") |
| 1141 | } |
| 1142 | if err != nil { |
| 1143 | return err |
| 1144 | } |
| 1145 | return e.record(ctx, p, app.Slug, StepRetire, nil) |
| 1146 | } |
| 1147 | |
| 1148 | // stepDetach removes the claim: CARLOS does not detach a claim when its |
| 1149 | // instance goes. |
| 1150 | func (e *Engine) stepDetach(ctx context.Context, p *pass, app App) error { |
| 1151 | host := PublicHost(p.run.Label, app.Slug) |
| 1152 | if _, found, err := e.cfg.Console.GetDomain(ctx, app.Slug, host); err != nil { |
| 1153 | return park("console-unavailable") |
| 1154 | } else if found { |
| 1155 | if err := e.cfg.Console.DetachDomain(ctx, app.Slug, host); err != nil { |
| 1156 | if errors.Is(err, console.ErrGuard) { |
| 1157 | return err |
| 1158 | } |
| 1159 | return park("console-write") |
| 1160 | } |
| 1161 | if err := e.acted("detach/" + app.Slug); err != nil { |
| 1162 | return err |
| 1163 | } |
| 1164 | if _, found, err = e.cfg.Console.GetDomain(ctx, app.Slug, host); err != nil || found { |
| 1165 | return park("detach-pending") |
| 1166 | } |
| 1167 | } |
| 1168 | return e.record(ctx, p, app.Slug, StepDetach, nil) |
| 1169 | } |
| 1170 | |
| 1171 | func (e *Engine) stepDelete(ctx context.Context, p *pass, app App) error { |
| 1172 | host := RouteHost(p.run.Label, app.Slug, e.cfg.Account) |
| 1173 | if _, found, err := e.cfg.Console.GetInstance(ctx, app.Slug, host); err != nil { |
| 1174 | return park("console-unavailable") |
| 1175 | } else if found { |
| 1176 | if err := e.cfg.Console.DeleteInstance(ctx, app.Slug, host); err != nil { |
| 1177 | if errors.Is(err, console.ErrGuard) { |
| 1178 | return err |
| 1179 | } |
| 1180 | return park("console-write") |
| 1181 | } |
| 1182 | if err := e.acted("delete/" + app.Slug); err != nil { |
| 1183 | return err |
| 1184 | } |
| 1185 | if _, found, err = e.cfg.Console.GetInstance(ctx, app.Slug, host); err != nil || found { |
| 1186 | return park("delete-pending") |
| 1187 | } |
| 1188 | } |
| 1189 | return e.record(ctx, p, app.Slug, StepDelete, nil) |
| 1190 | } |
| 1191 | |