| 1 | // This file holds the 522 Plan 1 snapshots, the preservation check and |
| 2 | // the CARLOS preflight that runs before any configuration write. |
| 3 | package adopt |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "net/http" |
| 10 | "sort" |
| 11 | "strings" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/alta/carlosop" |
| 15 | "amadan.net/oficina/alta/provision" |
| 16 | ) |
| 17 | |
| 18 | // HomeIssuerOrigin is the Home issuer the canonical apps trust: Home's |
| 19 | // credential role. An app trusting another issuer is not one this |
| 20 | // adoption's directory team can speak for. |
| 21 | const HomeIssuerOrigin = "https://id.oficina.works" |
| 22 | |
| 23 | // The effective view's layer names, lowest first. A higher layer covers a |
| 24 | // lower one for the keys it sets. |
| 25 | var layerRank = map[string]int{"default": 0, "environment": 1, "overlay": 2} |
| 26 | |
| 27 | // layerName is the effective view's name for a write layer: "default" |
| 28 | // for "", else "environment". |
| 29 | func layerName(writeLayer string) string { |
| 30 | if writeLayer == "" { |
| 31 | return "default" |
| 32 | } |
| 33 | return "environment" |
| 34 | } |
| 35 | |
| 36 | func findVar(vars []carlosop.EffectiveVar, key string) *carlosop.EffectiveVar { |
| 37 | for i := range vars { |
| 38 | if vars[i].Key == key { |
| 39 | return &vars[i] |
| 40 | } |
| 41 | } |
| 42 | return nil |
| 43 | } |
| 44 | |
| 45 | // plainValue is key's value in a stored layer, if the layer holds it as a |
| 46 | // plain var with exactly the digest the effective view reports. "" for a |
| 47 | // secret, an absent key or a digest that disagrees. |
| 48 | func plainValue(l carlosop.Layer, ev *carlosop.EffectiveVar) string { |
| 49 | if ev == nil || ev.Kind != "env" { |
| 50 | return "" |
| 51 | } |
| 52 | for _, v := range l.Vars { |
| 53 | if v.Key == ev.Key && v.Kind == "env" && v.Digest == ev.Digest { |
| 54 | return v.Value |
| 55 | } |
| 56 | } |
| 57 | return "" |
| 58 | } |
| 59 | |
| 60 | // canonicalRecord resolves app's canonical host as the platform routes |
| 61 | // it: the canonical name is a domain claim, routed to one instance |
| 62 | // record. It answers exactly one claim on the app whose host is host, and |
| 63 | // exactly one record whose host is that claim's route, or the code that |
| 64 | // refuses: domain-missing (no claim), domain-ambiguous (more than one), |
| 65 | // instance-missing (no record at the route). A name a catch-all derives |
| 66 | // (Via) and a catch-all's own row are not claims. Nothing else is tried: |
| 67 | // a record whose own host is the canonical one, with no claim, is not |
| 68 | // read as the canonical record. |
| 69 | func canonicalRecord(host string, ds []carlosop.Domain, all []carlosop.Instance) (carlosop.Domain, *carlosop.Instance, string, error) { |
| 70 | var claims []carlosop.Domain |
| 71 | for _, d := range ds { |
| 72 | if d.Host == host && d.Via == "" && !d.Instances { |
| 73 | claims = append(claims, d) |
| 74 | } |
| 75 | } |
| 76 | switch len(claims) { |
| 77 | case 0: |
| 78 | return carlosop.Domain{}, nil, "domain-missing", nil |
| 79 | case 1: |
| 80 | default: |
| 81 | return carlosop.Domain{}, nil, "domain-ambiguous", nil |
| 82 | } |
| 83 | d := claims[0] |
| 84 | var rec *carlosop.Instance |
| 85 | for i := range all { |
| 86 | if d.Route != "" && all[i].Host == d.Route { |
| 87 | if rec != nil { |
| 88 | return carlosop.Domain{}, nil, "", errors.New("adopt: more than one instance record answers for the canonical domain's route") |
| 89 | } |
| 90 | rec = &all[i] |
| 91 | } |
| 92 | } |
| 93 | if rec == nil { |
| 94 | return carlosop.Domain{}, nil, "instance-missing", nil |
| 95 | } |
| 96 | return d, rec, "", nil |
| 97 | } |
| 98 | |
| 99 | // storedSecret reports whether a stored layer holds key as a secret with |
| 100 | // exactly the digest the effective view reports. |
| 101 | func storedSecret(l carlosop.Layer, ev *carlosop.EffectiveVar) bool { |
| 102 | if ev == nil || ev.Kind != "secret" { |
| 103 | return false |
| 104 | } |
| 105 | for _, v := range l.Vars { |
| 106 | if v.Key == ev.Key && v.Kind == "secret" && v.Digest == ev.Digest { |
| 107 | return true |
| 108 | } |
| 109 | } |
| 110 | return false |
| 111 | } |
| 112 | |
| 113 | // homeCodes lists how snap's Home issuer and consumer differ from the |
| 114 | // ones app must trust. |
| 115 | func homeCodes(app provision.App, snap Snapshot) []string { |
| 116 | var codes []string |
| 117 | if snap.HomeIssuer != HomeIssuerOrigin { |
| 118 | codes = append(codes, "home-issuer-mismatch") |
| 119 | } |
| 120 | if snap.HomeConsumer != provision.ConsumerID(provision.AdoptionLabel, app.Slug) { |
| 121 | codes = append(codes, "home-consumer-mismatch") |
| 122 | } |
| 123 | return codes |
| 124 | } |
| 125 | |
| 126 | // observe reads one snapshot of app's canonical host, and the app's |
| 127 | // instance list it found that host's record in. The codes are the |
| 128 | // refusals that leave no snapshot to check: domain-missing, |
| 129 | // domain-ambiguous, instance-missing, layer-overlay, and |
| 130 | // home-issuer-mismatch when the host has no Home issuer to locate the |
| 131 | // write layer by. domain-not-live, a claim that is not live, comes with |
| 132 | // the complete snapshot but no delivery probe: the binding is known, and |
| 133 | // a probe of a name not served would say nothing. With h nil it makes no |
| 134 | // delivery probe, and the snapshot's Delivery is empty: the config and |
| 135 | // identity alone. |
| 136 | // |
| 137 | // The Home issuer and consumer are a plain var's own value. Only a value |
| 138 | // stored as a secret, which the console never returns, is taken from the |
| 139 | // app's live sign-in redirect (signInIdentity), and so only with h: a plain |
| 140 | // value that mismatches is never rescued by the redirect. |
| 141 | func observe(ctx context.Context, c *carlosop.Client, h *http.Client, app provision.App) (Snapshot, []carlosop.Instance, []string, error) { |
| 142 | ds, err := c.Domains(ctx, app.Slug) |
| 143 | if err != nil { |
| 144 | return Snapshot{}, nil, nil, err |
| 145 | } |
| 146 | all, err := c.Instances(ctx, app.Slug) |
| 147 | if err != nil { |
| 148 | return Snapshot{}, nil, nil, err |
| 149 | } |
| 150 | d, rec, code, err := canonicalRecord(CanonicalHost(app), ds, all) |
| 151 | switch { |
| 152 | case err != nil: |
| 153 | return Snapshot{}, nil, nil, err |
| 154 | case code != "": |
| 155 | return Snapshot{}, all, []string{code}, nil |
| 156 | } |
| 157 | live := d.State == "live" |
| 158 | if !live { |
| 159 | h = nil |
| 160 | } |
| 161 | snap, codes, err := observeRecord(ctx, c, h, app, d, *rec) |
| 162 | if err != nil { |
| 163 | return Snapshot{}, nil, nil, err |
| 164 | } |
| 165 | if !live { |
| 166 | codes = sortedSet(append(codes, "domain-not-live")) |
| 167 | } |
| 168 | return snap, all, codes, nil |
| 169 | } |
| 170 | |
| 171 | // observeRecord is observe once the canonical record is resolved: rec, |
| 172 | // served at d. |
| 173 | func observeRecord(ctx context.Context, c *carlosop.Client, h *http.Client, app provision.App, d carlosop.Domain, rec carlosop.Instance) (Snapshot, []string, error) { |
| 174 | eff, err := c.Effective(ctx, app.Slug, rec.Host) |
| 175 | if err != nil { |
| 176 | return Snapshot{}, nil, err |
| 177 | } |
| 178 | snap := Snapshot{Identity: IdentityOf(d, rec, eff), Layers: map[string]string{}, Vars: eff.Vars, At: time.Now().UTC()} |
| 179 | for k, v := range eff.Layers { |
| 180 | snap.Layers[k] = v |
| 181 | } |
| 182 | iss := findVar(eff.Vars, app.Prefix+"_HOME_ISSUER") |
| 183 | switch { |
| 184 | case iss == nil: |
| 185 | return snap, []string{"home-issuer-mismatch"}, nil |
| 186 | case iss.From == "overlay": |
| 187 | return snap, []string{"layer-overlay"}, nil |
| 188 | case iss.From == "environment": |
| 189 | snap.WriteLayer = eff.Environment |
| 190 | } |
| 191 | read := func(name string) (carlosop.Layer, error) { |
| 192 | env := "" |
| 193 | if name == "environment" { |
| 194 | env = eff.Environment |
| 195 | } |
| 196 | l, err := c.Config(ctx, app.Slug, env) |
| 197 | if err != nil { |
| 198 | return carlosop.Layer{}, err |
| 199 | } |
| 200 | // Two reads of one layer: if it moved between them, the |
| 201 | // snapshot would describe no single moment. |
| 202 | if l.Version != eff.Layers[name] { |
| 203 | return carlosop.Layer{}, errors.New("adopt: the config changed while it was being read; read it again") |
| 204 | } |
| 205 | return l, nil |
| 206 | } |
| 207 | if snap.Layer, err = read(layerName(snap.WriteLayer)); err != nil { |
| 208 | return Snapshot{}, nil, err |
| 209 | } |
| 210 | snap.HomeIssuer = plainValue(snap.Layer, iss) |
| 211 | secretIssuer, secretConsumer := storedSecret(snap.Layer, iss), false |
| 212 | // The overlay's plain values are not readable, so a consumer ID that |
| 213 | // comes from it stays "" and is refused. |
| 214 | if cons := findVar(eff.Vars, app.Prefix+"_HOME_CONSUMER_ID"); cons != nil && cons.From != "overlay" { |
| 215 | src := snap.Layer |
| 216 | if cons.From != layerName(snap.WriteLayer) { |
| 217 | if src, err = read(cons.From); err != nil { |
| 218 | return Snapshot{}, nil, err |
| 219 | } |
| 220 | } |
| 221 | snap.HomeConsumer = plainValue(src, cons) |
| 222 | secretConsumer = storedSecret(src, cons) |
| 223 | } |
| 224 | if h == nil { |
| 225 | return snap, nil, nil |
| 226 | } |
| 227 | origin := provision.PublicOrigin(provision.AdoptionLabel, app.Slug) |
| 228 | if secretIssuer || secretConsumer { |
| 229 | issuer, consumer := signInIdentity(ctx, h, origin) |
| 230 | if secretIssuer { |
| 231 | snap.HomeIssuer = issuer |
| 232 | } |
| 233 | if secretConsumer { |
| 234 | snap.HomeConsumer = consumer |
| 235 | } |
| 236 | } |
| 237 | if snap.Delivery, err = Probe(ctx, h, origin); err != nil { |
| 238 | return Snapshot{}, nil, err |
| 239 | } |
| 240 | return snap, nil, nil |
| 241 | } |
| 242 | |
| 243 | // Observe reads one snapshot of app's canonical host: its instance |
| 244 | // identity, the write layer and its stored vars, every layer's version, |
| 245 | // the complete effective config by digest, the Home issuer and consumer |
| 246 | // ID, and a delivery probe. A host whose write layer cannot be located is |
| 247 | // an error naming the code. |
| 248 | func Observe(ctx context.Context, c *carlosop.Client, h *http.Client, app provision.App) (Snapshot, error) { |
| 249 | if h == nil { |
| 250 | return Snapshot{}, errors.New("adopt: Observe needs a client for the delivery probe") |
| 251 | } |
| 252 | snap, _, codes, err := observe(ctx, c, h, app) |
| 253 | if err != nil { |
| 254 | return Snapshot{}, err |
| 255 | } |
| 256 | if len(codes) > 0 { |
| 257 | return Snapshot{}, fmt.Errorf("adopt: cannot observe %s: %s", app.Slug, strings.Join(codes, ", ")) |
| 258 | } |
| 259 | return snap, nil |
| 260 | } |
| 261 | |
| 262 | // TeamModeKeys names the team-mode keys among vars, sorted: those |
| 263 | // provision.TeamKeyNames lists and any other <P>_TEAM_ key. <P>_TEAM |
| 264 | // itself (Memoria's) is not one. |
| 265 | func TeamModeKeys(app provision.App, vars []carlosop.EffectiveVar) []string { |
| 266 | named := map[string]bool{} |
| 267 | for _, k := range provision.TeamKeyNames(app) { |
| 268 | named[k] = true |
| 269 | } |
| 270 | var out []string |
| 271 | for _, v := range vars { |
| 272 | if named[v.Key] || strings.HasPrefix(v.Key, app.Prefix+"_TEAM_") { |
| 273 | out = append(out, v.Key) |
| 274 | } |
| 275 | } |
| 276 | return sortedSet(out) |
| 277 | } |
| 278 | |
| 279 | // inherits reports whether host eff would receive any of keys from a |
| 280 | // write to writeLayer: the layer is in its chain, and nothing above it |
| 281 | // in that chain already sets the key. What else the host overrides is |
| 282 | // irrelevant. |
| 283 | func inherits(eff carlosop.Effective, writeLayer string, keys [2]string) bool { |
| 284 | switch { |
| 285 | case writeLayer == "" && eff.Owned: |
| 286 | return false // an owned environment never folds the default in |
| 287 | case writeLayer != "" && eff.Environment != writeLayer: |
| 288 | return false |
| 289 | } |
| 290 | at := layerRank[layerName(writeLayer)] |
| 291 | for _, k := range keys { |
| 292 | if v := findVar(eff.Vars, k); v == nil || layerRank[v.From] <= at { |
| 293 | return true |
| 294 | } |
| 295 | } |
| 296 | return false |
| 297 | } |
| 298 | |
| 299 | // Preflight observes app and lists every reason its configuration may |
| 300 | // not be written, as fixed codes carrying key names and hosts only: |
| 301 | // |
| 302 | // - domain-missing, domain-ambiguous, domain-not-live, instance-missing |
| 303 | // (the canonical domain is not one live claim routed to a record); |
| 304 | // - instance-moving, owned-environment, layer-overlay; |
| 305 | // - home-issuer-mismatch, home-consumer-mismatch: a plain var's value, |
| 306 | // or for a secret the app's live sign-in redirect (observe); |
| 307 | // - team-mode-<KEY>; |
| 308 | // - agent-keys-present, unless each present key is a plain var in the |
| 309 | // write layer whose digest is EnvDigest(mine[key]) (the journal's own |
| 310 | // sent values, on a resume); |
| 311 | // - inherits-<host>, for every other instance a write would reach; |
| 312 | // - version-header-mismatch, healthz; |
| 313 | // - operations-<shape>, unless the operations door answers as |
| 314 | // BaselineOps(app) says, or, on a resume, both agent keys are the |
| 315 | // journal's own (as above) and the door gives agent-access's answer: |
| 316 | // a baseline Delivered could never move on is refused before it is |
| 317 | // journalled. The resume exemption never applies to a held door |
| 318 | // (Base's): it must still give the challenge, never a 200. |
| 319 | // |
| 320 | // An error is a read that failed; it is not a refusal to guess past. |
| 321 | func Preflight(ctx context.Context, c *carlosop.Client, h *http.Client, app provision.App, mine map[string]string) (Snapshot, []string, error) { |
| 322 | if h == nil { |
| 323 | return Snapshot{}, nil, errors.New("adopt: Preflight needs a client for the delivery probe") |
| 324 | } |
| 325 | snap, all, codes, err := observe(ctx, c, h, app) |
| 326 | if err != nil || len(codes) > 0 { |
| 327 | return snap, codes, err |
| 328 | } |
| 329 | add := func(code string) { codes = append(codes, code) } |
| 330 | if snap.Identity.Moving { |
| 331 | add("instance-moving") |
| 332 | } |
| 333 | if snap.Identity.Owned { |
| 334 | add("owned-environment") |
| 335 | } |
| 336 | codes = append(codes, homeCodes(app, snap)...) |
| 337 | for _, k := range TeamModeKeys(app, snap.Vars) { |
| 338 | add("team-mode-" + k) |
| 339 | } |
| 340 | keys := AgentKeys(app) |
| 341 | bothOurs := true |
| 342 | for _, k := range keys { |
| 343 | v := findVar(snap.Vars, k) |
| 344 | if v == nil { |
| 345 | bothOurs = false |
| 346 | continue |
| 347 | } |
| 348 | ours := mine[k] != "" && v.Kind == "env" && v.From == layerName(snap.WriteLayer) && v.Digest == carlosop.EnvDigest(mine[k]) |
| 349 | if !ours { |
| 350 | add("agent-keys-present") |
| 351 | bothOurs = false |
| 352 | break |
| 353 | } |
| 354 | } |
| 355 | for _, in := range all { |
| 356 | if in.Host == snap.Identity.RecordHost { |
| 357 | continue |
| 358 | } |
| 359 | eff, err := c.Effective(ctx, app.Slug, in.Host) |
| 360 | if err != nil { |
| 361 | return snap, nil, err |
| 362 | } |
| 363 | if inherits(eff, snap.WriteLayer, keys) { |
| 364 | add("inherits-" + in.Host) |
| 365 | } |
| 366 | } |
| 367 | d := snap.Delivery |
| 368 | if d.Redirected || d.Version == "" || !SameRelease(d.Version, d.Header) { |
| 369 | add("version-header-mismatch") |
| 370 | } |
| 371 | if d.Health != http.StatusOK { |
| 372 | add("healthz") |
| 373 | } |
| 374 | // The resume exemption is for a door that moves. A held door (Base's |
| 375 | // agent-401 baseline) never moves, so it must still answer as before. |
| 376 | moved := bothOurs && d.Ops.agentShaped() && !BaselineOps(app).agentShaped() |
| 377 | if d.Ops != BaselineOps(app) && !moved { |
| 378 | add("operations-" + string(d.Ops)) |
| 379 | } |
| 380 | return snap, sortedSet(codes), nil |
| 381 | } |
| 382 | |
| 383 | // Preserved lists how after fails to preserve before, every key but the |
| 384 | // two added: changed:<KEY> (digest), gone:<KEY>, kind:<KEY> and |
| 385 | // from:<KEY> (the layer it comes from) in the effective config, the same |
| 386 | // for the write layer's stored vars (which covers a stored key a higher |
| 387 | // layer shadows), layer:<name> when a layer the write does not touch |
| 388 | // moved, and SameIdentity's codes. Empty means preserved. A new key is |
| 389 | // not a violation; NewKeys reports it. |
| 390 | func Preserved(before, after Snapshot, added [2]string) []string { |
| 391 | skip := map[string]bool{added[0]: true, added[1]: true} |
| 392 | var out []string |
| 393 | effAfter := map[string]carlosop.EffectiveVar{} |
| 394 | for _, v := range after.Vars { |
| 395 | effAfter[v.Key] = v |
| 396 | } |
| 397 | for _, b := range before.Vars { |
| 398 | if skip[b.Key] { |
| 399 | continue |
| 400 | } |
| 401 | a, ok := effAfter[b.Key] |
| 402 | if !ok { |
| 403 | out = append(out, "gone:"+b.Key) |
| 404 | continue |
| 405 | } |
| 406 | if a.Kind != b.Kind { |
| 407 | out = append(out, "kind:"+b.Key) |
| 408 | } |
| 409 | if a.Digest != b.Digest { |
| 410 | out = append(out, "changed:"+b.Key) |
| 411 | } |
| 412 | if a.From != b.From { |
| 413 | out = append(out, "from:"+b.Key) |
| 414 | } |
| 415 | } |
| 416 | touched := layerName(before.WriteLayer) |
| 417 | if before.WriteLayer != after.WriteLayer || before.Layer.Bundle != after.Layer.Bundle { |
| 418 | out = append(out, "layer:"+touched) |
| 419 | } else { |
| 420 | stored := map[string]carlosop.Var{} |
| 421 | for _, v := range after.Layer.Vars { |
| 422 | stored[v.Key] = v |
| 423 | } |
| 424 | for _, b := range before.Layer.Vars { |
| 425 | if skip[b.Key] { |
| 426 | continue |
| 427 | } |
| 428 | a, ok := stored[b.Key] |
| 429 | switch { |
| 430 | case !ok: |
| 431 | out = append(out, "gone:"+b.Key) |
| 432 | continue |
| 433 | case a.Kind != b.Kind: |
| 434 | out = append(out, "kind:"+b.Key) |
| 435 | } |
| 436 | if a.Digest != b.Digest { |
| 437 | out = append(out, "changed:"+b.Key) |
| 438 | } |
| 439 | } |
| 440 | } |
| 441 | for _, m := range []map[string]string{before.Layers, after.Layers} { |
| 442 | for name := range m { |
| 443 | if name == touched { |
| 444 | continue |
| 445 | } |
| 446 | bv, bok := before.Layers[name] |
| 447 | av, aok := after.Layers[name] |
| 448 | if bok != aok || bv != av { |
| 449 | out = append(out, "layer:"+name) |
| 450 | } |
| 451 | } |
| 452 | } |
| 453 | out = append(out, SameIdentity(before.Identity, after.Identity)...) |
| 454 | return sortedSet(out) |
| 455 | } |
| 456 | |
| 457 | // NewKeys lists the keys after holds that before did not, other than the |
| 458 | // two added, as added:<KEY>, sorted. A platform writer's new key is |
| 459 | // reported, never fatal. |
| 460 | func NewKeys(before, after Snapshot, added [2]string) []string { |
| 461 | had := map[string]bool{added[0]: true, added[1]: true} |
| 462 | for _, v := range before.Vars { |
| 463 | had[v.Key] = true |
| 464 | } |
| 465 | for _, v := range before.Layer.Vars { |
| 466 | had[v.Key] = true |
| 467 | } |
| 468 | var out []string |
| 469 | for _, v := range after.Vars { |
| 470 | if !had[v.Key] { |
| 471 | out = append(out, "added:"+v.Key) |
| 472 | } |
| 473 | } |
| 474 | for _, v := range after.Layer.Vars { |
| 475 | if !had[v.Key] { |
| 476 | out = append(out, "added:"+v.Key) |
| 477 | } |
| 478 | } |
| 479 | return sortedSet(out) |
| 480 | } |
| 481 | |
| 482 | // sortedSet sorts s and drops repeats; nil for none. |
| 483 | func sortedSet(s []string) []string { |
| 484 | if len(s) == 0 { |
| 485 | return nil |
| 486 | } |
| 487 | sort.Strings(s) |
| 488 | out := s[:1] |
| 489 | for _, v := range s[1:] { |
| 490 | if v != out[len(out)-1] { |
| 491 | out = append(out, v) |
| 492 | } |
| 493 | } |
| 494 | return out |
| 495 | } |
| 496 | |