oficina / alta Public

Clone
git clone https://amadan.net/oficina/alta

Plain git — no account needed to clone.

Download

Download this file

1package provision
2
3import (
4 "context"
5 "errors"
6 "strings"
7
8 "amadan.net/oficina/alta/homeop"
9)
10
11// Observation is what an adopted app's activation evidence takes from the
12// CARLOS half: the delivered version, the reviewed artifact's digest and
13// the environment binding. EnvironmentBinding is never printed or logged.
14type Observation struct {
15 AppVersion, ArtifactDigest, EnvironmentBinding string
16}
17
18// Observer re-observes one adopted app immediately before its activation
19// and answers its evidence, or refuses with a fixed code. The engine
20// never activates an adopted app without it. The served alta has none.
21type Observer interface {
22 Observe(ctx context.Context, app, teamSQID string) (Observation, error)
23}
24
25// ObserverRefusal is an Observer's refusal (adopt.Refusal): fixed codes,
26// which the activation parks with. Any other Observer error is a failed
27// read, retried on the next pass.
28type ObserverRefusal interface {
29 error
30 RefusalCodes() []string
31}
32
33// adoptionName is the existing team's display name (Paul, 2026-11-16).
34const adoptionName = "Oficina"
35
36// Existing-team adoption (Home implementation/existing-team-adoption.md)
37// runs in three plans, all under label oficina and the canonical tuple
38// (ConsumerID, PublicOrigin and PublicHost answer it for AdoptionLabel):
39//
40// - Plan A (StartAdoption): create-team with existing_team, owner-seed
41// and seed-team at that SQID, then each app's provision and register
42// (verified, nothing inserted). It ends done, awaiting-configuration.
43// - Plans B and C (ActivateAdopted): add-apps with existing_team, each
44// app's verify and activate under the existing-app policy, its
45// evidence from the Observer.
46// - DisableAdopted: an ordinary retire-apps window on the directory
47// alone, directory.disable-consumer and nothing else.
48//
49// None of them touches the console or an instance: the existing instances,
50// their environments and their keys are not Alta's.
51
52// adoptionSteps is an adoption run's per-app pipeline: Plan A, a
53// disable, or Plans B and C.
54func adoptionSteps(kind string) []string {
55 switch kind {
56 case homeop.KindCreateTeam:
57 return []string{StepConsumer, StepRegister}
58 case homeop.KindRetireApps:
59 return []string{StepDisable}
60 }
61 return []string{StepVerify, StepActivate}
62}
63
64// StartAdoption opens Plan A for the canonical apps. existing_team is
65// the SQID the directory proposes now, read here; Home seeds the team at
66// it or not at all.
67func (e *Engine) StartAdoption(ctx context.Context, name, owner string) (int64, error) {
68 if name != adoptionName {
69 return 0, fail("name-not-oficina")
70 }
71 if !homeop.OwnerAddress(owner) {
72 return 0, fail("owner-shape")
73 }
74 used, err := e.cfg.Store.LabelUsed(ctx, AdoptionLabel)
75 if err != nil {
76 return 0, err
77 }
78 if used {
79 return 0, fail("label-used")
80 }
81 if _, o, _ := e.cfg.Home.Inspect(ctx, homeop.Credential); o != homeop.OK {
82 return 0, fail("home-" + homeop.Credential + "-" + o.String())
83 }
84 ins, o, _ := e.cfg.Home.Inspect(ctx, homeop.Directory)
85 if o != homeop.OK {
86 return 0, fail("home-" + homeop.Directory + "-" + o.String())
87 }
88 if ins.Generation == nil || ins.TeamSQID == "" {
89 return 0, fail("home-not-initialized")
90 }
91 apps := Slugs()
92 if err := e.cfg.Store.CreateAdoption(ctx, name, owner, apps); err != nil {
93 return 0, err
94 }
95 id, err := e.cfg.Store.NewAdoptionRun(ctx, homeop.KindCreateTeam, apps)
96 if err != nil {
97 return 0, err
98 }
99 e.cfg.Store.Audit(ctx, id, AdoptionLabel, "", "run-start", homeop.KindCreateTeam)
100 return id, e.submitPlans(ctx, id, AdoptionLabel, name, owner, homeop.KindCreateTeam, apps, ins.TeamSQID)
101}
102
103// ContinueAdoption completes a Plan A whose team is seeded but whose
104// window closed before every app's consumer and register steps were done.
105// Home admits seeding under create-team alone, and provision and register
106// under add-apps too (internal/operator plan.go windowAdmits), so the
107// continuation's plan is add-apps on both roles, existing_team the stored
108// SQID, no owner, for exactly the apps still unregistered. The run is
109// Plan A's phase (create-team in Alta, no seed since the team is seeded):
110// done steps are skipped, a held request is replayed exactly, and it ends
111// awaiting-configuration.
112func (e *Engine) ContinueAdoption(ctx context.Context) (int64, error) {
113 t, err := e.cfg.Store.Team(ctx, AdoptionLabel)
114 if err != nil {
115 return 0, fail("no-team")
116 }
117 if t.TeamSQID == "" {
118 // Unseeded: Resubmit the Plan A run, whose create-team plan seeds.
119 return 0, fail("team-not-seeded")
120 }
121 var missing []string
122 for _, a := range Slugs() {
123 if _, ok, err := e.cfg.Store.Done(ctx, AdoptionLabel, a, StepRegister); err != nil {
124 return 0, err
125 } else if !ok {
126 missing = append(missing, a)
127 }
128 }
129 if len(missing) == 0 {
130 return 0, fail("plan-a-complete")
131 }
132 // A newly supported app may not have been in the original Plan A.
133 // Record it locally too; AddAdoptionApps is idempotent on existing bindings.
134 if err := e.cfg.Store.AddAdoptionApps(ctx, missing); err != nil {
135 return 0, err
136 }
137 id, err := e.cfg.Store.NewAdoptionRun(ctx, homeop.KindCreateTeam, missing)
138 if err != nil {
139 return 0, err
140 }
141 e.cfg.Store.Audit(ctx, id, AdoptionLabel, "", "run-start", "continue-adoption")
142 return id, e.submitPlans(ctx, id, AdoptionLabel, "", "", homeop.KindAddApps, missing, t.TeamSQID)
143}
144
145// ActivateAdopted opens Plan B or C: add-apps on both roles for apps
146// whose Plan A is done, existing_team the seeded team's SQID, no owner.
147func (e *Engine) ActivateAdopted(ctx context.Context, apps []string) (int64, error) {
148 if e.cfg.Observer == nil {
149 return 0, fail("no-observer")
150 }
151 if len(apps) == 0 {
152 return 0, fail("no-apps")
153 }
154 sorted := SortApps(apps)
155 if len(sorted) != len(apps) {
156 return 0, fail("unknown-app")
157 }
158 t, err := e.cfg.Store.Team(ctx, AdoptionLabel)
159 if err != nil {
160 return 0, fail("no-team")
161 }
162 if t.TeamSQID == "" {
163 return 0, fail("team-not-seeded")
164 }
165 for _, a := range sorted {
166 if _, ok, err := e.cfg.Store.Done(ctx, AdoptionLabel, a, StepRegister); err != nil {
167 return 0, err
168 } else if !ok {
169 return 0, fail("not-registered")
170 }
171 if _, ok, err := e.cfg.Store.Done(ctx, AdoptionLabel, a, StepDisable); err != nil {
172 return 0, err
173 } else if ok {
174 return 0, fail("app-disabled")
175 }
176 if _, ok, err := e.cfg.Store.Done(ctx, AdoptionLabel, a, StepActivate); err != nil {
177 return 0, err
178 } else if ok {
179 return 0, fail("app-active")
180 }
181 }
182 id, err := e.cfg.Store.NewAdoptionRun(ctx, homeop.KindAddApps, sorted)
183 if err != nil {
184 return 0, err
185 }
186 e.cfg.Store.Audit(ctx, id, AdoptionLabel, "", "run-start", homeop.KindAddApps)
187 return id, e.submitPlans(ctx, id, AdoptionLabel, "", "", homeop.KindAddApps, sorted, t.TeamSQID)
188}
189
190// DisableAdopted opens a retire-apps window on the directory alone for one
191// adopted app: directory.disable-consumer, the immediate incident response.
192// Its env-manifest consumer, instance and environment are untouched.
193// typed must equal the label.
194func (e *Engine) DisableAdopted(ctx context.Context, app, typed string) (int64, error) {
195 if typed != AdoptionLabel {
196 return 0, fail("label-mismatch")
197 }
198 if _, ok := AppBySlug(app); !ok {
199 return 0, fail("unknown-app")
200 }
201 t, err := e.cfg.Store.Team(ctx, AdoptionLabel)
202 if err != nil {
203 return 0, fail("no-team")
204 }
205 if t.TeamSQID == "" {
206 return 0, fail("team-not-seeded")
207 }
208 if _, ok, err := e.cfg.Store.Done(ctx, AdoptionLabel, app, StepConsumer); err != nil {
209 return 0, err
210 } else if !ok {
211 return 0, fail("not-provisioned")
212 }
213 // Marked an adoption, so Advance takes it to the disable step alone,
214 // never §9's retire, detach and delete.
215 id, err := e.cfg.Store.newRun(ctx, homeop.KindRetireApps, AdoptionLabel, []string{app}, RunOptions{Profile: ProfileOutside}, true)
216 if err != nil {
217 return 0, err
218 }
219 e.cfg.Store.Audit(ctx, id, AdoptionLabel, "", "run-start", homeop.KindRetireApps)
220 return id, e.submitPlans(ctx, id, AdoptionLabel, "", "", homeop.KindRetireApps, []string{app}, "")
221}
222
223// adoptedTeam is the SQID a fresh plan for adoption run r binds: the
224// directory's proposal for Plan A (unseeded), the seeded team's for
225// Plans B and C, none for a disable.
226func (e *Engine) adoptedTeam(ctx context.Context, r Run) (string, error) {
227 switch r.Kind {
228 case homeop.KindCreateTeam:
229 ins, o, _ := e.cfg.Home.Inspect(ctx, homeop.Directory)
230 if o != homeop.OK || ins.TeamSQID == "" {
231 return "", fail("no-proposed-team")
232 }
233 return ins.TeamSQID, nil
234 case homeop.KindAddApps:
235 t, err := e.cfg.Store.Team(ctx, AdoptionLabel)
236 return t.TeamSQID, err
237 }
238 return "", nil
239}
240
241// planExisting is the existing_team of the plan this run's window opened
242// for, from Alta's own signed copy of the directory's plan.
243func (e *Engine) planExisting(ctx context.Context, p *pass) (string, error) {
244 subs, err := e.cfg.Store.Plans(ctx, p.run.PlanID)
245 if err != nil {
246 return "", err
247 }
248 // An absent row or dropped bytes read as no payload.
249 raw, err := homeop.EnvelopePayload(subs[homeop.Directory].Signed)
250 var plan homeop.Plan
251 if err != nil || homeop.Decode(raw, &plan) != nil {
252 return "", fail("plan-unreadable")
253 }
254 return plan.ExistingTeam, nil
255}
256
257// adoption is one Advance of an adoption run: the team's seed (Plan A
258// only), then each app's steps. A parked app does not hold the others
259// back; a failed one stops the run.
260func (e *Engine) adoption(ctx context.Context, p *pass) error {
261 st := e.cfg.Store
262 if p.team.TeamSQID == "" {
263 // seed admits create-team only: Plans B and C need a seeded team.
264 if err := e.seed(ctx, p); err != nil {
265 return err
266 }
267 t, err := st.Team(ctx, p.run.Label)
268 if err != nil {
269 return err
270 }
271 p.team = t
272 }
273 // No recipe ever holds the owner here: the seed was the address's
274 // last use.
275 if _, held, err := st.Owner(ctx, p.run.Label); err != nil {
276 return err
277 } else if held {
278 if err := st.ForgetOwner(ctx, p.run.Label); err != nil {
279 return err
280 }
281 st.Audit(ctx, p.run.ID, p.run.Label, "", "owner-forgotten", "")
282 }
283 var first error
284 for _, slug := range p.run.Apps {
285 app, _ := AppBySlug(slug)
286 if err := e.pipeline(ctx, p, app, adoptionSteps(p.run.Kind)); err != nil {
287 if errors.Is(err, errCrash) {
288 return err
289 }
290 var fl *Fail
291 if errors.As(err, &fl) {
292 return err
293 }
294 if first == nil {
295 first = err
296 }
297 }
298 }
299 return first
300}
301
302// stepActivateAdopted is step 12 for an adopted app: the existing-app
303// policy, the canonical consumer and audience, the Observer's evidence,
304// started_at the recorded issued_at and completed_at now − Skew. A
305// request Alta already signed is replayed exactly and never rebuilt: its
306// observation was made once.
307func (e *Engine) stepActivateAdopted(ctx context.Context, p *pass, app App) error {
308 st, label := e.cfg.Store, p.run.Label
309 if e.cfg.Observer == nil {
310 return fail("no-observer")
311 }
312 spec := opSpec{role: homeop.Directory, action: homeop.DirectoryActivate, label: label, app: app.Slug, purpose: "activate", reuse: true}
313 if _, handled, err := e.replayHeld(ctx, spec); handled {
314 if err != nil {
315 return err
316 }
317 return e.record(ctx, p, app.Slug, StepActivate, map[string]any{"replayed": true})
318 }
319 if err := e.needWindow(p, homeop.Directory); err != nil {
320 return err
321 }
322 v, _, _ := st.Done(ctx, label, app.Slug, StepVerify)
323 reg, _, _ := st.Done(ctx, label, app.Slug, StepRegister)
324 _, cd, err := e.consumerData(ctx, p, app)
325 if err != nil {
326 return err
327 }
328 if num(v, "expires_at") <= e.now().Unix()+10 {
329 // The attempt lapsed: verify again.
330 _ = st.SetStep(ctx, label, app.Slug, StepVerify, "parked", "attempt-expired", nil)
331 return park("attempt-expired")
332 }
333 obs, err := e.cfg.Observer.Observe(ctx, app.Slug, p.team.TeamSQID)
334 if err != nil {
335 var r ObserverRefusal
336 if errors.As(err, &r) {
337 return park("observe-" + strings.Join(r.RefusalCodes(), ","))
338 }
339 if e.cfg.Debug != nil {
340 e.cfg.Debug(err)
341 }
342 return park("observer-unavailable")
343 }
344 // What Home would refuse is never signed.
345 if !activationVersion.MatchString(obs.AppVersion) || !homeop.CanonicalToken(obs.ArtifactDigest) || !homeop.CanonicalToken(obs.EnvironmentBinding) {
346 return fail("observation-shape")
347 }
348 ev := homeop.ActivationEvidence{Version: 1, Policy: homeop.ExistingActivationPolicy, Attempt: str(v, "attempt"), Consumer: ConsumerID(label, app.Slug), TeamSQID: p.team.TeamSQID, App: app.Slug,
349 Audience: PublicOrigin(label, app.Slug), Generation: str(cd, "generation"), RecordSequence: 1, RecordDigest: str(cd, "record_digest"), Epoch: num(cd, "epoch"), Owner: p.team.OwnerRef,
350 AppVersion: obs.AppVersion, ArtifactDigest: obs.ArtifactDigest, EnvironmentBinding: obs.EnvironmentBinding, ManifestDigest: str(reg, "manifest_digest"),
351 AliasHost: PublicHost(label, app.Slug), Started: num(v, "issued_at"), Completed: e.now().Unix() - homeop.Skew}
352 spec.build = func(b homeop.InputBase) any { return homeop.ActivationInput{InputBase: b, Evidence: ev} }
353 if _, err := e.op(ctx, spec); err != nil {
354 if errors.Is(err, errOpRefused) {
355 return fail("activate-refused")
356 }
357 return err
358 }
359 return e.record(ctx, p, app.Slug, StepActivate, map[string]any{"app_version": obs.AppVersion})
360}
361