| 1 | package adopt |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "net/http/httputil" |
| 12 | "net/url" |
| 13 | "strconv" |
| 14 | "strings" |
| 15 | "sync" |
| 16 | "testing" |
| 17 | "time" |
| 18 | |
| 19 | "amadan.net/oficina/alta/carlosop" |
| 20 | ) |
| 21 | |
| 22 | // fixtureSQID is the team the fixture's writes name. |
| 23 | const fixtureSQID = "tQx7kPa" |
| 24 | |
| 25 | // writeFixture is one app on a fake console with an adoption journal. |
| 26 | type writeFixture struct { |
| 27 | *carlosFixture |
| 28 | s *Store |
| 29 | } |
| 30 | |
| 31 | func newWriteFixture(t *testing.T, slug string) *writeFixture { |
| 32 | t.Helper() |
| 33 | return &writeFixture{carlosFixture: newCarlosFixture(t, slug), s: newJournal(t)} |
| 34 | } |
| 35 | |
| 36 | func (w *writeFixture) configure(apply bool) (string, error) { |
| 37 | return WriteAgentKeys(context.Background(), w.c, w.h, w.s, w.app, fixtureSQID, sha256Hex(w.site.header), apply) |
| 38 | } |
| 39 | |
| 40 | func (w *writeFixture) rollback(apply bool) error { |
| 41 | return RollbackAgentKeys(context.Background(), w.c, w.h, w.s, w.app, apply) |
| 42 | } |
| 43 | |
| 44 | // puts is how many PUT /config requests the fake console has seen. |
| 45 | func (x *carlosFixture) puts() int { |
| 46 | n := 0 |
| 47 | for _, r := range x.f.Requests() { |
| 48 | if r == "PUT /config" { |
| 49 | n++ |
| 50 | } |
| 51 | } |
| 52 | return n |
| 53 | } |
| 54 | |
| 55 | // stored reports which of the agent keys the default bundle holds, and |
| 56 | // whether each holds what the fixture's write sends. |
| 57 | func (w *writeFixture) stored(t *testing.T) (present, ours [2]bool) { |
| 58 | t.Helper() |
| 59 | vars, _, _ := w.f.Layer(w.app.Slug, "") |
| 60 | keys := AgentKeys(w.app) |
| 61 | sent := w.sent() |
| 62 | for i, k := range keys { |
| 63 | v, ok := vars[k] |
| 64 | present[i] = ok |
| 65 | ours[i] = ok && v.Kind == "env" && v.Value == sent[k] |
| 66 | } |
| 67 | return present, ours |
| 68 | } |
| 69 | |
| 70 | func (w *writeFixture) sent() map[string]string { |
| 71 | keys := AgentKeys(w.app) |
| 72 | return map[string]string{keys[0]: Issuer, keys[1]: fixtureSQID} |
| 73 | } |
| 74 | |
| 75 | func (w *writeFixture) writeRecord(t *testing.T) (WriteRecord, bool) { |
| 76 | t.Helper() |
| 77 | r, ok, err := w.s.Write(context.Background(), w.app.Slug) |
| 78 | if err != nil { |
| 79 | t.Fatal(err) |
| 80 | } |
| 81 | return r, ok |
| 82 | } |
| 83 | |
| 84 | func (w *writeFixture) rollbackRecord(t *testing.T) (RollbackRecord, bool) { |
| 85 | t.Helper() |
| 86 | r, ok, err := w.s.Rollback(context.Background(), w.app.Slug) |
| 87 | if err != nil { |
| 88 | t.Fatal(err) |
| 89 | } |
| 90 | return r, ok |
| 91 | } |
| 92 | |
| 93 | func (w *writeFixture) baseline(t *testing.T) Snapshot { |
| 94 | t.Helper() |
| 95 | b, ok, err := w.s.Baseline(context.Background(), w.app.Slug) |
| 96 | if err != nil || !ok { |
| 97 | t.Fatalf("no baseline (ok %v, err %v)", ok, err) |
| 98 | } |
| 99 | return b |
| 100 | } |
| 101 | |
| 102 | // nothingWritten fails if the console saw a PUT, the journal holds a |
| 103 | // baseline or a write, or either agent key is stored. |
| 104 | func (w *writeFixture) nothingWritten(t *testing.T) { |
| 105 | t.Helper() |
| 106 | if n := w.puts(); n != 0 { |
| 107 | t.Fatalf("PUTs = %d, want none", n) |
| 108 | } |
| 109 | if _, ok, _ := w.s.Baseline(context.Background(), w.app.Slug); ok { |
| 110 | t.Fatal("a baseline was stored") |
| 111 | } |
| 112 | if _, ok := w.writeRecord(t); ok { |
| 113 | t.Fatal("a write was journalled") |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | // noValues fails if err's text carries a value, digest or version. |
| 118 | func noValues(t *testing.T, err error) { |
| 119 | t.Helper() |
| 120 | if err == nil { |
| 121 | return |
| 122 | } |
| 123 | for _, bad := range []string{"vd1:", "cv1:", fixtureSQID, Issuer, valueOrigin, valueVersion} { |
| 124 | if strings.Contains(err.Error(), bad) { |
| 125 | t.Fatalf("error carries %q: %v", bad, err) |
| 126 | } |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | // process models the app's process: it loads the stored agent keys when |
| 131 | // it restarts, and its operations door answers agent-access's challenge |
| 132 | // only while the config it last loaded held both. It starts as if it had |
| 133 | // loaded at the current restart count with loaded as given. |
| 134 | func (x *carlosFixture) process(loaded bool) { |
| 135 | keys := AgentKeys(x.app) |
| 136 | host := routeOf(x.app) |
| 137 | var mu sync.Mutex |
| 138 | seen := x.f.RestartCount(host) |
| 139 | x.site.ops = func(w http.ResponseWriter) { |
| 140 | mu.Lock() |
| 141 | if n := x.f.RestartCount(host); n != seen { |
| 142 | vars, _, _ := x.f.Layer(x.app.Slug, "") |
| 143 | _, a := vars[keys[0]] |
| 144 | _, b := vars[keys[1]] |
| 145 | seen, loaded = n, a && b |
| 146 | } |
| 147 | on := loaded |
| 148 | mu.Unlock() |
| 149 | switch { |
| 150 | case on: |
| 151 | agent401(w) |
| 152 | case BaselineOps(x.app) == OpsApp401: |
| 153 | app401(w) |
| 154 | default: |
| 155 | w.WriteHeader(http.StatusNotFound) |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | // configured writes the keys, restarts until Delivered and captures the |
| 161 | // after snapshot, as the configure phase does. |
| 162 | func (w *writeFixture) configured(t *testing.T) Snapshot { |
| 163 | t.Helper() |
| 164 | fastPolls(t, 5*time.Millisecond, 2*time.Second) |
| 165 | w.process(false) |
| 166 | if _, err := w.configure(true); err != nil { |
| 167 | t.Fatalf("WriteAgentKeys: %v", err) |
| 168 | } |
| 169 | base := w.baseline(t) |
| 170 | ctx := context.Background() |
| 171 | if _, err := RestartAndWait(ctx, w.c, w.h, w.app, base.Identity, func(d Delivery) error { return Delivered(w.app, base.Delivery, d) }, true); err != nil { |
| 172 | t.Fatalf("RestartAndWait: %v", err) |
| 173 | } |
| 174 | after, err := CaptureAfter(ctx, w.c, w.h, w.s, w.app) |
| 175 | if err != nil { |
| 176 | t.Fatalf("CaptureAfter: %v", err) |
| 177 | } |
| 178 | return after |
| 179 | } |
| 180 | |
| 181 | // once runs f the first time the returned hook is called. |
| 182 | func once(f func()) func(string) { |
| 183 | var o sync.Once |
| 184 | return func(string) { o.Do(f) } |
| 185 | } |
| 186 | |
| 187 | // putRewriter puts a proxy in front of the fake console that edits the |
| 188 | // receipt of every successful PUT /config answer. |
| 189 | func (x *carlosFixture) putRewriter(t *testing.T, edit func(rc map[string]any)) { |
| 190 | t.Helper() |
| 191 | x.putAnswerRewriter(t, func(raw []byte) ([]byte, error) { |
| 192 | var answer map[string]any |
| 193 | if err := json.Unmarshal(raw, &answer); err != nil { |
| 194 | return nil, err |
| 195 | } |
| 196 | edit(answer["receipt"].(map[string]any)) |
| 197 | return json.Marshal(answer) |
| 198 | }) |
| 199 | } |
| 200 | |
| 201 | // putAnswerRewriter puts a proxy in front of the fake console that |
| 202 | // replaces the body of every successful PUT /config answer with what |
| 203 | // edit makes of it. The write itself has landed by then. |
| 204 | func (x *carlosFixture) putAnswerRewriter(t *testing.T, edit func(raw []byte) ([]byte, error)) { |
| 205 | t.Helper() |
| 206 | target, err := url.Parse(x.f.URL()) |
| 207 | if err != nil { |
| 208 | t.Fatal(err) |
| 209 | } |
| 210 | rp := httputil.NewSingleHostReverseProxy(target) |
| 211 | rp.ModifyResponse = func(resp *http.Response) error { |
| 212 | if resp.Request.Method != http.MethodPut || resp.StatusCode != 200 { |
| 213 | return nil |
| 214 | } |
| 215 | raw, err := io.ReadAll(resp.Body) |
| 216 | resp.Body.Close() |
| 217 | if err != nil { |
| 218 | return err |
| 219 | } |
| 220 | if raw, err = edit(raw); err != nil { |
| 221 | return err |
| 222 | } |
| 223 | resp.Body = io.NopCloser(bytes.NewReader(raw)) |
| 224 | resp.ContentLength = int64(len(raw)) |
| 225 | resp.Header.Set("Content-Length", strconv.Itoa(len(raw))) |
| 226 | return nil |
| 227 | } |
| 228 | srv := httptest.NewServer(rp) |
| 229 | t.Cleanup(srv.Close) |
| 230 | x.c = carlosop.New(srv.URL, fixtureAccount, x.f.Token()) |
| 231 | t.Cleanup(x.c.Close) |
| 232 | } |
| 233 | |
| 234 | // ---- Configure: the preflight is enforced by the write itself ---- |
| 235 | |
| 236 | func TestConfigureCallsPreflightEvenWhenInvokedDirectly(t *testing.T) { |
| 237 | cases := map[string]func(w *writeFixture){ |
| 238 | "home issuer": func(w *writeFixture) { w.f.SetVar("docs", "", "DOCS_HOME_ISSUER", "https://id.elsewhere.example") }, |
| 239 | "healthz": func(w *writeFixture) { w.site.health = 503 }, |
| 240 | "moving": func(w *writeFixture) { |
| 241 | w.f.AddInstance(carlosop.Instance{Host: docsRoute, App: "docs", Slug: "s-docs", Channel: "stable", Region: "eu", |
| 242 | CreatedAt: time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 4, Move: json.RawMessage(`{"to":"us"}`)}) |
| 243 | }, |
| 244 | } |
| 245 | for name, edit := range cases { |
| 246 | t.Run(name, func(t *testing.T) { |
| 247 | w := newWriteFixture(t, "docs") |
| 248 | edit(w) |
| 249 | for _, apply := range []bool{false, true} { |
| 250 | _, err := w.configure(apply) |
| 251 | if err == nil || !strings.Contains(err.Error(), "configure refused") { |
| 252 | t.Fatalf("apply %v: err = %v, want a preflight refusal", apply, err) |
| 253 | } |
| 254 | noValues(t, err) |
| 255 | } |
| 256 | w.nothingWritten(t) |
| 257 | }) |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | func TestConfigureRefusesForeignAgentKeys(t *testing.T) { |
| 262 | w := newWriteFixture(t, "docs") |
| 263 | // Even the very values the runner would send: it did not write them. |
| 264 | for k, v := range w.sent() { |
| 265 | w.f.SetVar("docs", "", k, v) |
| 266 | } |
| 267 | _, err := w.configure(true) |
| 268 | if err == nil || !strings.Contains(err.Error(), "agent-keys-present") { |
| 269 | t.Fatalf("err = %v, want agent-keys-present", err) |
| 270 | } |
| 271 | noValues(t, err) |
| 272 | w.nothingWritten(t) |
| 273 | } |
| 274 | |
| 275 | func TestConfigureRefusesTeamMode(t *testing.T) { |
| 276 | w := newWriteFixture(t, "docs") |
| 277 | w.f.SetVar("docs", "", "DOCS_TEAM_ID", "team-id-value") |
| 278 | _, err := w.configure(true) |
| 279 | if err == nil || !strings.Contains(err.Error(), "team-mode-DOCS_TEAM_ID") { |
| 280 | t.Fatalf("err = %v, want team-mode-DOCS_TEAM_ID", err) |
| 281 | } |
| 282 | w.nothingWritten(t) |
| 283 | } |
| 284 | |
| 285 | func TestConfigureRefusesInheritingNeighbour(t *testing.T) { |
| 286 | w := newWriteFixture(t, "docs") |
| 287 | w.neighbour("bare.docs.example", "") |
| 288 | _, err := w.configure(true) |
| 289 | if err == nil || !strings.Contains(err.Error(), "inherits-bare.docs.example") { |
| 290 | t.Fatalf("err = %v, want inherits-bare.docs.example", err) |
| 291 | } |
| 292 | w.nothingWritten(t) |
| 293 | } |
| 294 | |
| 295 | func TestConfigureRefusesBadTeam(t *testing.T) { |
| 296 | w := newWriteFixture(t, "docs") |
| 297 | for _, sqid := range []string{"", " tQx7kPa", "t-1", "tQx7kPa\n"} { |
| 298 | if _, err := WriteAgentKeys(context.Background(), w.c, w.h, w.s, w.app, sqid, sha256Hex(w.site.header), true); err == nil { |
| 299 | t.Fatalf("sqid %q accepted", sqid) |
| 300 | } |
| 301 | } |
| 302 | w.nothingWritten(t) |
| 303 | } |
| 304 | |
| 305 | // ---- The write ---- |
| 306 | |
| 307 | func TestWriteHappyPathReceiptChecked(t *testing.T) { |
| 308 | w := newWriteFixture(t, "docs") |
| 309 | _, beforeVersion, _ := w.f.Layer("docs", "") |
| 310 | summary, err := w.configure(true) |
| 311 | if err != nil { |
| 312 | t.Fatalf("WriteAgentKeys: %v", err) |
| 313 | } |
| 314 | if summary != "set DOCS_AGENT_ISSUER, DOCS_AGENT_TEAM on default" { |
| 315 | t.Fatalf("summary = %q", summary) |
| 316 | } |
| 317 | if n := w.puts(); n != 1 { |
| 318 | t.Fatalf("PUTs = %d", n) |
| 319 | } |
| 320 | if _, ours := w.stored(t); ours != [2]bool{true, true} { |
| 321 | t.Fatalf("stored keys ours = %v", ours) |
| 322 | } |
| 323 | base := w.baseline(t) |
| 324 | if base.Layer.Version != beforeVersion || findVar(base.Vars, "DOCS_AGENT_TEAM") != nil { |
| 325 | t.Fatal("the baseline is not the layer before the write") |
| 326 | } |
| 327 | rec, ok := w.writeRecord(t) |
| 328 | if !ok || rec.State != "landed" || rec.Receipt == nil || rec.Code != "" { |
| 329 | t.Fatalf("write record %v state %q code %q", ok, rec.State, rec.Code) |
| 330 | } |
| 331 | if rec.Receipt.VersionBefore != beforeVersion || rec.Receipt.Digests["DOCS_AGENT_TEAM"] != carlosop.EnvDigest(fixtureSQID) { |
| 332 | t.Fatal("the journalled receipt is not the write's") |
| 333 | } |
| 334 | if rec.Sent["DOCS_AGENT_ISSUER"] != Issuer || rec.Sent["DOCS_AGENT_TEAM"] != fixtureSQID || len(rec.Sent) != 2 { |
| 335 | t.Fatal("the journal does not hold what was sent") |
| 336 | } |
| 337 | |
| 338 | // Landed is the end: a second call sends nothing at all. |
| 339 | n := len(w.f.Requests()) |
| 340 | if again, err := w.configure(true); err != nil || again != summary { |
| 341 | t.Fatalf("second call: %q %v", again, err) |
| 342 | } |
| 343 | if got := len(w.f.Requests()); got != n { |
| 344 | t.Fatalf("a landed write made %d more requests", got-n) |
| 345 | } |
| 346 | // A call naming another team never rides on the landed record. |
| 347 | if _, err := WriteAgentKeys(context.Background(), w.c, w.h, w.s, w.app, "tOther9", sha256Hex(w.site.header), true); err == nil { |
| 348 | t.Fatal("a landed write accepted another team") |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | // A write to a named environment says so. |
| 353 | func TestWriteSummaryNamesTheWriteLayer(t *testing.T) { |
| 354 | w := newWriteFixture(t, "docs") |
| 355 | w.f.SetVar("docs", "prod", "DOCS_HOME_ISSUER", HomeIssuerOrigin) |
| 356 | w.f.SetVar("docs", "prod", "DOCS_HOME_CONSUMER_ID", "docs") |
| 357 | w.f.AddInstance(carlosop.Instance{Host: docsRoute, App: "docs", Slug: "s-docs", Environment: "prod", Channel: "stable", Region: "eu", |
| 358 | CreatedAt: time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 4, ReplicaAssignment: json.RawMessage(`{"boxes":["b1"]}`)}) |
| 359 | summary, err := w.configure(true) |
| 360 | if err != nil { |
| 361 | t.Fatalf("WriteAgentKeys: %v", err) |
| 362 | } |
| 363 | if summary != "set DOCS_AGENT_ISSUER, DOCS_AGENT_TEAM on prod" { |
| 364 | t.Fatalf("summary = %q", summary) |
| 365 | } |
| 366 | vars, _, _ := w.f.Layer("docs", "prod") |
| 367 | if vars["DOCS_AGENT_TEAM"].Value != fixtureSQID { |
| 368 | t.Fatal("the keys were not written to the environment") |
| 369 | } |
| 370 | if dvars, _, _ := w.f.Layer("docs", ""); len(dvars) != 4 { |
| 371 | t.Fatalf("the default bundle changed: %d vars", len(dvars)) |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | func TestWriteLostAnswerLanded(t *testing.T) { |
| 376 | w := newWriteFixture(t, "docs") |
| 377 | w.f.LoseNextAnswer() |
| 378 | if _, err := w.configure(true); err != nil { |
| 379 | t.Fatalf("WriteAgentKeys: %v", err) |
| 380 | } |
| 381 | if n := w.puts(); n != 1 { |
| 382 | t.Fatalf("PUTs = %d, want exactly one", n) |
| 383 | } |
| 384 | rec, _ := w.writeRecord(t) |
| 385 | if rec.State != "landed" || rec.Receipt != nil { |
| 386 | t.Fatalf("state %q receipt %v", rec.State, rec.Receipt != nil) |
| 387 | } |
| 388 | if _, ours := w.stored(t); ours != [2]bool{true, true} { |
| 389 | t.Fatalf("ours = %v", ours) |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | // A resume after a crash between the PUT and its journal entry: the |
| 394 | // record still says sent, the keys are stored, and the resume finds the |
| 395 | // write landed by rereading, never by writing over it. |
| 396 | func TestWriteResumeAfterCrashFindsLanded(t *testing.T) { |
| 397 | w := newWriteFixture(t, "docs") |
| 398 | ctx := context.Background() |
| 399 | // The crash, as the journal and the console were left by it. |
| 400 | base, err := Observe(ctx, w.c, w.h, w.app) |
| 401 | if err != nil { |
| 402 | t.Fatal(err) |
| 403 | } |
| 404 | if err := w.s.SaveBaseline(ctx, "docs", base); err != nil { |
| 405 | t.Fatal(err) |
| 406 | } |
| 407 | if err := w.s.SaveWrite(ctx, WriteRecord{App: "docs", State: "sent", Sent: w.sent()}); err != nil { |
| 408 | t.Fatal(err) |
| 409 | } |
| 410 | for k, v := range w.sent() { |
| 411 | w.f.SetVar("docs", "", k, v) |
| 412 | } |
| 413 | _, landedVersion, _ := w.f.Layer("docs", "") |
| 414 | if _, err := w.configure(true); err != nil { |
| 415 | t.Fatalf("resume: %v", err) |
| 416 | } |
| 417 | if rec, _ := w.writeRecord(t); rec.State != "landed" { |
| 418 | t.Fatalf("state %q after resume", rec.State) |
| 419 | } |
| 420 | // The one PUT carried the baseline version and was refused. |
| 421 | if n := w.puts(); n != 1 { |
| 422 | t.Fatalf("PUTs = %d", n) |
| 423 | } |
| 424 | if _, v, _ := w.f.Layer("docs", ""); v != landedVersion { |
| 425 | t.Fatal("the resume wrote over the landed keys") |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | // The reviewed release is checked before anything is written or |
| 430 | // journalled, with --apply and without. |
| 431 | func TestWriteRefusesUnreviewedReleaseBeforeWriting(t *testing.T) { |
| 432 | for name, artifact := range map[string]string{ |
| 433 | "artifact-unreviewed": "", |
| 434 | "artifact-mismatch": sha256Hex("v1.3.9"), |
| 435 | } { |
| 436 | for _, apply := range []bool{false, true} { |
| 437 | w := newWriteFixture(t, "docs") |
| 438 | _, err := WriteAgentKeys(context.Background(), w.c, w.h, w.s, w.app, fixtureSQID, artifact, apply) |
| 439 | if err == nil || err.Error() != "adopt: configure refused: "+name { |
| 440 | t.Fatalf("%s apply %v: err = %v", name, apply, err) |
| 441 | } |
| 442 | w.nothingWritten(t) |
| 443 | } |
| 444 | } |
| 445 | // The release moved under a sent write: the resume refuses to send |
| 446 | // again. |
| 447 | w := newWriteFixture(t, "docs") |
| 448 | ctx := context.Background() |
| 449 | base, err := Observe(ctx, w.c, w.h, w.app) |
| 450 | setupOK(t, err) |
| 451 | setupOK(t, w.s.SaveBaseline(ctx, "docs", base)) |
| 452 | setupOK(t, w.s.SaveWrite(ctx, WriteRecord{App: "docs", State: "sent", Sent: w.sent()})) |
| 453 | w.site.version, w.site.header = "v1.5.0", "v1.5.0" |
| 454 | if _, err := WriteAgentKeys(ctx, w.c, w.h, w.s, w.app, fixtureSQID, sha256Hex(valueVersion), true); err == nil || !strings.Contains(err.Error(), "artifact-mismatch") { |
| 455 | t.Fatalf("resume on another release: err = %v", err) |
| 456 | } |
| 457 | if n := w.puts(); n != 0 { |
| 458 | t.Fatalf("%d PUTs", n) |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | // An app whose door answers something Delivered could never move on is |
| 463 | // refused before its baseline is journalled. |
| 464 | func TestWriteRefusesUnsupportedOperationsBaseline(t *testing.T) { |
| 465 | w := newWriteFixture(t, "docs") |
| 466 | w.site.ops = func(rw http.ResponseWriter) { rw.WriteHeader(500) } |
| 467 | if _, err := w.configure(true); err == nil || !strings.Contains(err.Error(), "operations-other") { |
| 468 | t.Fatalf("err = %v", err) |
| 469 | } |
| 470 | w.nothingWritten(t) |
| 471 | } |
| 472 | |
| 473 | func TestWriteRetriesAfterUnrelatedKeyAdded(t *testing.T) { |
| 474 | w := newWriteFixture(t, "docs") |
| 475 | _, beforeVersion, _ := w.f.Layer("docs", "") |
| 476 | w.f.BeforePut = once(func() { w.f.PlatformWrite("docs", "", "DOCS_MAIL_EVENTS_URL", "https://mail.example/hook") }) |
| 477 | if _, err := w.configure(true); err != nil { |
| 478 | t.Fatalf("WriteAgentKeys: %v", err) |
| 479 | } |
| 480 | if n := w.puts(); n != 2 { |
| 481 | t.Fatalf("PUTs = %d, want a 412 then the retry", n) |
| 482 | } |
| 483 | base := w.baseline(t) |
| 484 | if base.Layer.Version != beforeVersion || findVar(base.Vars, "DOCS_MAIL_EVENTS_URL") != nil { |
| 485 | t.Fatal("the baseline moved: it was retaken after the retry") |
| 486 | } |
| 487 | for _, v := range base.Layer.Vars { |
| 488 | if v.Key == "DOCS_MAIL_EVENTS_URL" { |
| 489 | t.Fatal("the baseline absorbed the unrelated key") |
| 490 | } |
| 491 | } |
| 492 | rec, _ := w.writeRecord(t) |
| 493 | if rec.State != "landed" || rec.Receipt == nil || rec.Receipt.VersionBefore == beforeVersion { |
| 494 | t.Fatalf("state %q: the landed receipt is not the retry's", rec.State) |
| 495 | } |
| 496 | vars, _, _ := w.f.Layer("docs", "") |
| 497 | if _, ok := vars["DOCS_MAIL_EVENTS_URL"]; !ok { |
| 498 | t.Fatal("the retry lost the platform's key") |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | // Every preflight refusal a reread can see is enforced again before a |
| 503 | // retry: a 412 caused by another writer's team-mode key, or by a new |
| 504 | // neighbour that would inherit the keys, never ends in a write. |
| 505 | func TestWriteRetryRevalidatesPreflight(t *testing.T) { |
| 506 | cases := map[string]struct { |
| 507 | edit func(w *writeFixture) |
| 508 | code string |
| 509 | }{ |
| 510 | "team mode": {func(w *writeFixture) { w.f.SetVar("docs", "", "DOCS_TEAM_ID", "team-id-value") }, "team-mode-DOCS_TEAM_ID"}, |
| 511 | "other team key": {func(w *writeFixture) { w.f.SetVar("docs", "", "DOCS_TEAM_NEW_THING", "1") }, |
| 512 | "team-mode-DOCS_TEAM_NEW_THING"}, |
| 513 | "inheriting neighbour": {func(w *writeFixture) { |
| 514 | w.neighbour("bare.docs.example", "") |
| 515 | w.f.PlatformWrite("docs", "", "DOCS_MAIL_EVENTS_URL", "https://mail.example/hook") |
| 516 | }, "inherits-bare.docs.example"}, |
| 517 | } |
| 518 | for name, tc := range cases { |
| 519 | t.Run(name, func(t *testing.T) { |
| 520 | w := newWriteFixture(t, "docs") |
| 521 | w.f.BeforePut = once(func() { tc.edit(w) }) |
| 522 | _, err := w.configure(true) |
| 523 | if err == nil || !strings.Contains(err.Error(), "configure refused") || !strings.Contains(err.Error(), tc.code) { |
| 524 | t.Fatalf("err = %v, want a refusal naming %s", err, tc.code) |
| 525 | } |
| 526 | noValues(t, err) |
| 527 | if n := w.puts(); n != 1 { |
| 528 | t.Fatalf("PUTs = %d: retried past a preflight refusal", n) |
| 529 | } |
| 530 | if present, _ := w.stored(t); present != [2]bool{} { |
| 531 | t.Fatalf("agent keys written: %v", present) |
| 532 | } |
| 533 | rec, _ := w.writeRecord(t) |
| 534 | if rec.State != "sent" || rec.Code != "preflight-refused" { |
| 535 | t.Fatalf("state %q code %q", rec.State, rec.Code) |
| 536 | } |
| 537 | // A resume meets the same refusal and sends nothing. |
| 538 | if _, err := w.configure(true); err == nil || !strings.Contains(err.Error(), tc.code) { |
| 539 | t.Fatalf("resume err = %v", err) |
| 540 | } |
| 541 | if n := w.puts(); n != 1 { |
| 542 | t.Fatalf("PUTs = %d after resume", n) |
| 543 | } |
| 544 | }) |
| 545 | } |
| 546 | } |
| 547 | |
| 548 | // A preserved key resealed after the reread that said Retry, but before |
| 549 | // the retry, is caught by classifying the admission's own read: the |
| 550 | // retry never writes past it. |
| 551 | func TestWriteRetryReclassifiesAfterAdmission(t *testing.T) { |
| 552 | w := newWriteFixture(t, "docs") |
| 553 | w.f.BeforePut = once(func() { w.f.PlatformWrite("docs", "", "DOCS_MAIL_EVENTS_URL", "https://mail.example/hook") }) |
| 554 | target, err := url.Parse(w.f.URL()) |
| 555 | if err != nil { |
| 556 | t.Fatal(err) |
| 557 | } |
| 558 | rp := httputil.NewSingleHostReverseProxy(target) |
| 559 | var mu sync.Mutex |
| 560 | refused, resealed := false, false |
| 561 | rp.ModifyResponse = func(resp *http.Response) error { |
| 562 | mu.Lock() |
| 563 | defer mu.Unlock() |
| 564 | switch { |
| 565 | case resp.Request.Method == http.MethodPut && resp.StatusCode == http.StatusPreconditionFailed: |
| 566 | refused = true |
| 567 | case refused && !resealed && resp.Request.Method == http.MethodGet && strings.HasSuffix(resp.Request.URL.Path, "/config"): |
| 568 | // The reread has been answered; the reseal lands after it. |
| 569 | resealed = true |
| 570 | w.f.SetSecret("docs", "", "DOCS_INSTANCE_KEY") |
| 571 | } |
| 572 | return nil |
| 573 | } |
| 574 | srv := httptest.NewServer(rp) |
| 575 | t.Cleanup(srv.Close) |
| 576 | w.c = carlosop.New(srv.URL, fixtureAccount, w.f.Token()) |
| 577 | t.Cleanup(w.c.Close) |
| 578 | _, err = w.configure(true) |
| 579 | mu.Lock() |
| 580 | fired := resealed |
| 581 | mu.Unlock() |
| 582 | if !fired { |
| 583 | t.Fatal("the reseal never landed between the reread and the retry") |
| 584 | } |
| 585 | if !errors.Is(err, ErrStopPreserved) { |
| 586 | t.Fatalf("err = %v, want ErrStopPreserved", err) |
| 587 | } |
| 588 | if n := w.puts(); n != 1 { |
| 589 | t.Fatalf("PUTs = %d: retried past a resealed key", n) |
| 590 | } |
| 591 | if present, _ := w.stored(t); present != [2]bool{} { |
| 592 | t.Fatal("agent keys written") |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | func TestWriteStopsWhenPreservedKeyResealed(t *testing.T) { |
| 597 | w := newWriteFixture(t, "docs") |
| 598 | w.f.BeforePut = once(func() { w.f.SetSecret("docs", "", "DOCS_INSTANCE_KEY") }) |
| 599 | _, err := w.configure(true) |
| 600 | if !errors.Is(err, ErrStopPreserved) { |
| 601 | t.Fatalf("err = %v, want ErrStopPreserved", err) |
| 602 | } |
| 603 | noValues(t, err) |
| 604 | if n := w.puts(); n != 1 { |
| 605 | t.Fatalf("PUTs = %d", n) |
| 606 | } |
| 607 | if present, _ := w.stored(t); present != [2]bool{} { |
| 608 | t.Fatalf("keys present %v", present) |
| 609 | } |
| 610 | rec, _ := w.writeRecord(t) |
| 611 | if rec.State != "stopped" || rec.Code != "preserved-changed" { |
| 612 | t.Fatalf("state %q code %q", rec.State, rec.Code) |
| 613 | } |
| 614 | // Stopped is the end: a resume refuses and sends nothing. |
| 615 | n := w.puts() |
| 616 | if _, err := w.configure(true); !errors.Is(err, ErrStopPreserved) { |
| 617 | t.Fatalf("resume err = %v", err) |
| 618 | } |
| 619 | if w.puts() != n { |
| 620 | t.Fatal("a stopped write was sent again") |
| 621 | } |
| 622 | } |
| 623 | |
| 624 | func TestWriteStopsOnPartialOrForeignAgentKeys(t *testing.T) { |
| 625 | cases := map[string]func(f *writeFixture){ |
| 626 | "partial": func(w *writeFixture) { w.f.SetVar("docs", "", "DOCS_AGENT_ISSUER", Issuer) }, |
| 627 | "foreign": func(w *writeFixture) { |
| 628 | w.f.SetVar("docs", "", "DOCS_AGENT_ISSUER", Issuer) |
| 629 | w.f.SetVar("docs", "", "DOCS_AGENT_TEAM", "tOther9") |
| 630 | }, |
| 631 | "kind": func(w *writeFixture) { |
| 632 | w.f.SetVar("docs", "", "DOCS_AGENT_ISSUER", Issuer) |
| 633 | w.f.SetSecret("docs", "", "DOCS_AGENT_TEAM") |
| 634 | }, |
| 635 | } |
| 636 | for name, edit := range cases { |
| 637 | t.Run(name, func(t *testing.T) { |
| 638 | w := newWriteFixture(t, "docs") |
| 639 | w.f.BeforePut = once(func() { edit(w) }) |
| 640 | _, err := w.configure(true) |
| 641 | if !errors.Is(err, ErrStopConflict) { |
| 642 | t.Fatalf("err = %v, want ErrStopConflict", err) |
| 643 | } |
| 644 | noValues(t, err) |
| 645 | if n := w.puts(); n != 1 { |
| 646 | t.Fatalf("PUTs = %d: the other writer's keys were overwritten", n) |
| 647 | } |
| 648 | rec, _ := w.writeRecord(t) |
| 649 | if rec.State != "stopped" || rec.Code != "agent-keys-conflict" { |
| 650 | t.Fatalf("state %q code %q", rec.State, rec.Code) |
| 651 | } |
| 652 | }) |
| 653 | } |
| 654 | } |
| 655 | |
| 656 | func TestWriteRejectsMalformedReceipts(t *testing.T) { |
| 657 | other := "cv1:" + strings.Repeat("9", 64) |
| 658 | cases := map[string]func(rc map[string]any){ |
| 659 | "extra set key": func(rc map[string]any) { rc["set"] = append(rc["set"].([]any), "DOCS_ORIGIN") }, |
| 660 | "missing digest": func(rc map[string]any) { delete(rc["digests"].(map[string]any), "DOCS_AGENT_TEAM") }, |
| 661 | "wrong digest": func(rc map[string]any) { |
| 662 | rc["digests"].(map[string]any)["DOCS_AGENT_TEAM"] = carlosop.EnvDigest("tOther9") |
| 663 | }, |
| 664 | "unset not empty": func(rc map[string]any) { rc["unset"] = []any{"DOCS_ORIGIN"} }, |
| 665 | "unset_absent set": func(rc map[string]any) { rc["unset_absent"] = []any{"DOCS_ORIGIN"} }, |
| 666 | "others moved": func(rc map[string]any) { |
| 667 | rc["others"] = map[string]any{"default": map[string]any{"before": rc["version_before"], "after": other}} |
| 668 | }, |
| 669 | "version before": func(rc map[string]any) { rc["version_before"] = other }, |
| 670 | } |
| 671 | for name, edit := range cases { |
| 672 | t.Run(name, func(t *testing.T) { |
| 673 | w := newWriteFixture(t, "docs") |
| 674 | w.putRewriter(t, edit) |
| 675 | _, err := w.configure(true) |
| 676 | if !errors.Is(err, ErrStopConflict) { |
| 677 | t.Fatalf("err = %v, want ErrStopConflict", err) |
| 678 | } |
| 679 | noValues(t, err) |
| 680 | if n := w.puts(); n != 1 { |
| 681 | t.Fatalf("PUTs = %d", n) |
| 682 | } |
| 683 | rec, _ := w.writeRecord(t) |
| 684 | if rec.State != "stopped" || rec.Code != "receipt-mismatch" || rec.Receipt == nil { |
| 685 | t.Fatalf("state %q code %q", rec.State, rec.Code) |
| 686 | } |
| 687 | }) |
| 688 | } |
| 689 | } |
| 690 | |
| 691 | // malformedAnswers are 200 answers to a PUT that carlosop.Put refuses as |
| 692 | // no receipt for the write: absent, for another bundle, with a malformed |
| 693 | // digest or version, or not JSON at all. The write landed each time; the |
| 694 | // answer is a protocol failure, not a lost one. |
| 695 | func malformedAnswers() map[string]func(raw []byte) ([]byte, error) { |
| 696 | answer := func(edit func(a map[string]any)) func([]byte) ([]byte, error) { |
| 697 | return func(raw []byte) ([]byte, error) { |
| 698 | var a map[string]any |
| 699 | if err := json.Unmarshal(raw, &a); err != nil { |
| 700 | return nil, err |
| 701 | } |
| 702 | edit(a) |
| 703 | return json.Marshal(a) |
| 704 | } |
| 705 | } |
| 706 | receipt := func(edit func(rc map[string]any)) func([]byte) ([]byte, error) { |
| 707 | return answer(func(a map[string]any) { edit(a["receipt"].(map[string]any)) }) |
| 708 | } |
| 709 | return map[string]func([]byte) ([]byte, error){ |
| 710 | "no receipt": answer(func(a map[string]any) { delete(a, "receipt") }), |
| 711 | "null receipt": answer(func(a map[string]any) { a["receipt"] = nil }), |
| 712 | "another bundle": receipt(func(rc map[string]any) { rc["bundle"] = "production" }), |
| 713 | "malformed digest": receipt(func(rc map[string]any) { |
| 714 | rc["digests"] = map[string]any{"DOCS_AGENT_TEAM": "vd1:zz"} |
| 715 | }), |
| 716 | "malformed version before": receipt(func(rc map[string]any) { rc["version_before"] = "cv1:XYZ" }), |
| 717 | "malformed version after": receipt(func(rc map[string]any) { rc["version_after"] = "v2" }), |
| 718 | "malformed others version": receipt(func(rc map[string]any) { |
| 719 | rc["others"] = map[string]any{"default": map[string]any{"before": "v1", "after": "v1"}} |
| 720 | }), |
| 721 | "unreadable answer": func([]byte) ([]byte, error) { return []byte("{not json"), nil }, |
| 722 | } |
| 723 | } |
| 724 | |
| 725 | // A malformed receipt is not a lost answer: the console answered, so a |
| 726 | // reread proves nothing about what that answer said. The write stops, |
| 727 | // and a resume refuses again without sending. |
| 728 | func TestWriteStopsOnMalformedReceipts(t *testing.T) { |
| 729 | for name, edit := range malformedAnswers() { |
| 730 | t.Run(name, func(t *testing.T) { |
| 731 | w := newWriteFixture(t, "docs") |
| 732 | w.putAnswerRewriter(t, edit) |
| 733 | _, err := w.configure(true) |
| 734 | if !errors.Is(err, ErrStopConflict) { |
| 735 | t.Fatalf("err = %v, want ErrStopConflict", err) |
| 736 | } |
| 737 | noValues(t, err) |
| 738 | if n := w.puts(); n != 1 { |
| 739 | t.Fatalf("PUTs = %d", n) |
| 740 | } |
| 741 | rec, _ := w.writeRecord(t) |
| 742 | if rec.State != "stopped" || rec.Code != "receipt-malformed" { |
| 743 | t.Fatalf("state %q code %q", rec.State, rec.Code) |
| 744 | } |
| 745 | if _, err := w.configure(true); !errors.Is(err, ErrStopConflict) { |
| 746 | t.Fatalf("resume: err = %v, want ErrStopConflict", err) |
| 747 | } |
| 748 | if n := w.puts(); n != 1 { |
| 749 | t.Fatalf("resume sent: PUTs = %d", n) |
| 750 | } |
| 751 | }) |
| 752 | } |
| 753 | } |
| 754 | |
| 755 | // Only an answer that never came is lost. A Put that was never sent |
| 756 | // (its guarding read failed) is returned as it is: no reread, no retry, |
| 757 | // no stop, the record left at sent. |
| 758 | func TestWriteNotSentIsNotLost(t *testing.T) { |
| 759 | w := newWriteFixture(t, "docs") |
| 760 | reads, drop := 0, 0 |
| 761 | target, err := url.Parse(w.f.URL()) |
| 762 | if err != nil { |
| 763 | t.Fatal(err) |
| 764 | } |
| 765 | rp := httputil.NewSingleHostReverseProxy(target) |
| 766 | srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { |
| 767 | if r.Method == http.MethodGet && r.URL.Path == "/api/cli/apps/"+fixtureAccount+"/docs/config" { |
| 768 | if reads++; reads == drop { |
| 769 | // A console answering with no version: Put refuses to send. |
| 770 | rw.Header().Set("Content-Type", "application/json") |
| 771 | _, _ = rw.Write([]byte(`{"bundle":"default","vars":[]}`)) |
| 772 | return |
| 773 | } |
| 774 | } |
| 775 | rp.ServeHTTP(rw, r) |
| 776 | })) |
| 777 | t.Cleanup(srv.Close) |
| 778 | w.c = carlosop.New(srv.URL, fixtureAccount, w.f.Token()) |
| 779 | t.Cleanup(w.c.Close) |
| 780 | // A dry run counts the preflight's reads of the layer; Put's own |
| 781 | // guarding read is the next one. Its malformed answer is not the |
| 782 | // write's receipt: nothing was sent. |
| 783 | if _, err := w.configure(false); err != nil { |
| 784 | t.Fatal(err) |
| 785 | } |
| 786 | pre := reads |
| 787 | reads, drop = 0, pre+1 |
| 788 | _, err = w.configure(true) |
| 789 | if err == nil || errors.Is(err, ErrStopConflict) || errors.Is(err, ErrStopPreserved) { |
| 790 | t.Fatalf("err = %v, want the read's own failure", err) |
| 791 | } |
| 792 | if !errors.Is(err, carlosop.ErrNotSent) { |
| 793 | t.Fatalf("err = %v, want ErrNotSent", err) |
| 794 | } |
| 795 | if n := w.puts(); n != 0 { |
| 796 | t.Fatalf("PUTs = %d", n) |
| 797 | } |
| 798 | if reads != drop { |
| 799 | t.Fatalf("reads of the layer = %d, want %d: a Put never sent was reread", reads, drop) |
| 800 | } |
| 801 | if rec, _ := w.writeRecord(t); rec.State != "sent" { |
| 802 | t.Fatalf("state %q", rec.State) |
| 803 | } |
| 804 | } |
| 805 | |
| 806 | func TestWriteRefusesWithoutConditionalSupport(t *testing.T) { |
| 807 | w := newWriteFixture(t, "docs") |
| 808 | w.f.NoConditional() |
| 809 | _, err := w.configure(true) |
| 810 | if !errors.Is(err, carlosop.ErrNoConditional) { |
| 811 | t.Fatalf("err = %v, want ErrNoConditional", err) |
| 812 | } |
| 813 | if n := w.puts(); n != 1 { |
| 814 | t.Fatalf("PUTs = %d: retried a console that refuses if_version", n) |
| 815 | } |
| 816 | if present, _ := w.stored(t); present != [2]bool{} { |
| 817 | t.Fatal("keys were written") |
| 818 | } |
| 819 | // Nothing landed, so the record stays sent, with the reason. |
| 820 | rec, _ := w.writeRecord(t) |
| 821 | if rec.State != "sent" || rec.Code != "no-conditional" { |
| 822 | t.Fatalf("state %q code %q", rec.State, rec.Code) |
| 823 | } |
| 824 | } |
| 825 | |
| 826 | func TestWriteGivesUpAfterThreeAttempts(t *testing.T) { |
| 827 | w := newWriteFixture(t, "docs") |
| 828 | n := 0 |
| 829 | w.f.BeforePut = func(string) { |
| 830 | n++ |
| 831 | w.f.PlatformWrite("docs", "", "DOCS_MAIL_EVENTS_URL", "https://mail.example/"+strconv.Itoa(n)) |
| 832 | } |
| 833 | _, err := w.configure(true) |
| 834 | if err == nil || !strings.Contains(err.Error(), "retry-exhausted") { |
| 835 | t.Fatalf("err = %v, want retry-exhausted", err) |
| 836 | } |
| 837 | if got := w.puts(); got != 3 { |
| 838 | t.Fatalf("PUTs = %d, want 3", got) |
| 839 | } |
| 840 | rec, _ := w.writeRecord(t) |
| 841 | if rec.State != "sent" || rec.Code != "retry-exhausted" { |
| 842 | t.Fatalf("state %q code %q", rec.State, rec.Code) |
| 843 | } |
| 844 | // A resume once the writer is quiet lands, still on the first baseline. |
| 845 | w.f.BeforePut = nil |
| 846 | if _, err := w.configure(true); err != nil { |
| 847 | t.Fatalf("resume: %v", err) |
| 848 | } |
| 849 | if rec, _ := w.writeRecord(t); rec.State != "landed" { |
| 850 | t.Fatalf("state %q", rec.State) |
| 851 | } |
| 852 | } |
| 853 | |
| 854 | func TestWriteDryRunSendsNothing(t *testing.T) { |
| 855 | w := newWriteFixture(t, "docs") |
| 856 | _, beforeVersion, _ := w.f.Layer("docs", "") |
| 857 | summary, err := w.configure(false) |
| 858 | if err != nil { |
| 859 | t.Fatalf("dry run: %v", err) |
| 860 | } |
| 861 | if summary != "set DOCS_AGENT_ISSUER, DOCS_AGENT_TEAM on default" { |
| 862 | t.Fatalf("summary = %q", summary) |
| 863 | } |
| 864 | w.nothingWritten(t) |
| 865 | if _, v, _ := w.f.Layer("docs", ""); v != beforeVersion { |
| 866 | t.Fatal("the layer moved") |
| 867 | } |
| 868 | for _, r := range w.f.Requests() { |
| 869 | if !strings.HasPrefix(r, "GET ") { |
| 870 | t.Fatalf("a dry run sent %q", r) |
| 871 | } |
| 872 | } |
| 873 | } |
| 874 | |
| 875 | // A resume never writes against a baseline that describes another |
| 876 | // instance or layer. |
| 877 | func TestWriteRefusesWhenBaselineNoLongerDescribesTheHost(t *testing.T) { |
| 878 | w := newWriteFixture(t, "docs") |
| 879 | ctx := context.Background() |
| 880 | snap, err := Observe(ctx, w.c, w.h, w.app) |
| 881 | if err != nil { |
| 882 | t.Fatal(err) |
| 883 | } |
| 884 | if err := w.s.SaveBaseline(ctx, "docs", snap); err != nil { |
| 885 | t.Fatal(err) |
| 886 | } |
| 887 | w.f.AddInstance(carlosop.Instance{Host: docsRoute, App: "docs", Slug: "s-docs-new", Channel: "stable", Region: "eu", |
| 888 | CreatedAt: time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 9}) |
| 889 | _, err = w.configure(true) |
| 890 | if err == nil || !strings.Contains(err.Error(), "identity-storage") { |
| 891 | t.Fatalf("err = %v, want identity-storage", err) |
| 892 | } |
| 893 | if n := w.puts(); n != 0 { |
| 894 | t.Fatalf("PUTs = %d", n) |
| 895 | } |
| 896 | } |
| 897 | |
| 898 | func TestWriteRefusedOnceRollbackRecorded(t *testing.T) { |
| 899 | w := newWriteFixture(t, "docs") |
| 900 | if err := w.s.SaveRollback(context.Background(), RollbackRecord{App: "docs", State: "restarted"}); err != nil { |
| 901 | t.Fatal(err) |
| 902 | } |
| 903 | if _, err := w.configure(true); err == nil || !strings.Contains(err.Error(), "rollback-recorded") { |
| 904 | t.Fatalf("err = %v, want rollback-recorded", err) |
| 905 | } |
| 906 | w.nothingWritten(t) |
| 907 | } |
| 908 | |
| 909 | // ---- Classification ---- |
| 910 | |
| 911 | func layerOf(vars ...carlosop.Var) carlosop.Layer { |
| 912 | return carlosop.Layer{Bundle: "default", Version: vA, Vars: vars} |
| 913 | } |
| 914 | |
| 915 | func TestWriteClassifyBranchesInOrder(t *testing.T) { |
| 916 | sent := map[string]string{"DOCS_AGENT_ISSUER": Issuer, "DOCS_AGENT_TEAM": fixtureSQID} |
| 917 | iss := carlosop.Var{Key: "DOCS_AGENT_ISSUER", Kind: "env", Value: Issuer, Digest: carlosop.EnvDigest(Issuer)} |
| 918 | team := carlosop.Var{Key: "DOCS_AGENT_TEAM", Kind: "env", Value: fixtureSQID, Digest: carlosop.EnvDigest(fixtureSQID)} |
| 919 | sec := carlosop.Var{Key: "DOCS_INSTANCE_KEY", Kind: "secret", Digest: dA} |
| 920 | org := carlosop.Var{Key: "DOCS_ORIGIN", Kind: "env", Value: "o", Digest: dB} |
| 921 | base := layerOf(sec, org) |
| 922 | resealed := sec |
| 923 | resealed.Digest = dC |
| 924 | asSecret := sec |
| 925 | asSecret.Kind = "env" |
| 926 | foreignTeam := team |
| 927 | foreignTeam.Digest = carlosop.EnvDigest("tOther9") |
| 928 | secretTeam := carlosop.Var{Key: "DOCS_AGENT_TEAM", Kind: "secret", Digest: carlosop.EnvDigest(fixtureSQID)} |
| 929 | unrelated := carlosop.Var{Key: "DOCS_MAIL_EVENTS_URL", Kind: "env", Digest: dC} |
| 930 | cases := map[string]struct { |
| 931 | read carlosop.Layer |
| 932 | want Branch |
| 933 | }{ |
| 934 | "landed": {layerOf(sec, org, iss, team), Landed}, |
| 935 | "landed beside a new key": {layerOf(sec, org, iss, team, unrelated), Landed}, |
| 936 | "absent": {layerOf(sec, org), Retry}, |
| 937 | "absent beside a new key": {layerOf(sec, org, unrelated), Retry}, |
| 938 | "resealed": {layerOf(resealed, org), StopPreservedChanged}, |
| 939 | "gone": {layerOf(org), StopPreservedChanged}, |
| 940 | "kind": {layerOf(asSecret, org), StopPreservedChanged}, |
| 941 | "preserved first": {layerOf(resealed, org, iss), StopPreservedChanged}, |
| 942 | "preserved first, landed": {layerOf(org, iss, team), StopPreservedChanged}, |
| 943 | "partial": {layerOf(sec, org, iss), StopConflict}, |
| 944 | "foreign": {layerOf(sec, org, iss, foreignTeam), StopConflict}, |
| 945 | "secret of the sent value": {layerOf(sec, org, iss, secretTeam), StopConflict}, |
| 946 | } |
| 947 | for name, tc := range cases { |
| 948 | if got := Classify(base, tc.read, sent); got != tc.want { |
| 949 | t.Errorf("%s: Classify = %d, want %d", name, got, tc.want) |
| 950 | } |
| 951 | } |
| 952 | other := layerOf(sec, org) |
| 953 | other.Bundle = "prod" |
| 954 | if got := Classify(base, other, sent); got != StopPreservedChanged { |
| 955 | t.Errorf("another bundle: %d", got) |
| 956 | } |
| 957 | if got := Classify(base, layerOf(sec, org), map[string]string{"DOCS_AGENT_ISSUER": Issuer}); got != StopConflict { |
| 958 | t.Errorf("one sent key: %d", got) |
| 959 | } |
| 960 | if Branch(0) == Landed || RollbackBranch(0) == RolledBack { |
| 961 | t.Error("a zero branch reads as done") |
| 962 | } |
| 963 | } |
| 964 | |
| 965 | func TestRollbackClassifyBranchesInOrder(t *testing.T) { |
| 966 | sent := map[string]string{"DOCS_AGENT_ISSUER": Issuer, "DOCS_AGENT_TEAM": fixtureSQID} |
| 967 | iss := carlosop.Var{Key: "DOCS_AGENT_ISSUER", Kind: "env", Value: Issuer, Digest: carlosop.EnvDigest(Issuer)} |
| 968 | team := carlosop.Var{Key: "DOCS_AGENT_TEAM", Kind: "env", Value: fixtureSQID, Digest: carlosop.EnvDigest(fixtureSQID)} |
| 969 | sec := carlosop.Var{Key: "DOCS_INSTANCE_KEY", Kind: "secret", Digest: dA} |
| 970 | base := layerOf(sec) |
| 971 | resealed := sec |
| 972 | resealed.Digest = dC |
| 973 | foreignTeam := team |
| 974 | foreignTeam.Digest = carlosop.EnvDigest("tOther9") |
| 975 | secretTeam := carlosop.Var{Key: "DOCS_AGENT_TEAM", Kind: "secret", Digest: carlosop.EnvDigest(fixtureSQID)} |
| 976 | cases := map[string]struct { |
| 977 | read carlosop.Layer |
| 978 | want RollbackBranch |
| 979 | }{ |
| 980 | "ours": {layerOf(sec, iss, team), RetryUnset}, |
| 981 | "ours, another key resealed": {layerOf(resealed, iss, team), RollbackStopPreservedChanged}, |
| 982 | "one, another key resealed": {layerOf(resealed, iss), RollbackStopPreservedChanged}, |
| 983 | "absent": {layerOf(sec), RolledBack}, |
| 984 | "one": {layerOf(sec, iss), StopForeign}, |
| 985 | "foreign": {layerOf(sec, iss, foreignTeam), StopForeign}, |
| 986 | "kind": {layerOf(sec, iss, secretTeam), StopForeign}, |
| 987 | "absent, resealed": {layerOf(resealed), RollbackStopPreservedChanged}, |
| 988 | "absent, gone": {layerOf(), RollbackStopPreservedChanged}, |
| 989 | } |
| 990 | for name, tc := range cases { |
| 991 | if got := ClassifyRollback(base, tc.read, sent); got != tc.want { |
| 992 | t.Errorf("%s: ClassifyRollback = %d, want %d", name, got, tc.want) |
| 993 | } |
| 994 | } |
| 995 | } |
| 996 | |
| 997 | // The journal's states move one way only. |
| 998 | func TestWriteJournalTransitions(t *testing.T) { |
| 999 | ctx := context.Background() |
| 1000 | sent := map[string]string{"DOCS_AGENT_ISSUER": Issuer, "DOCS_AGENT_TEAM": fixtureSQID} |
| 1001 | wr := func(state string) WriteRecord { return WriteRecord{App: "docs", State: state, Sent: sent} } |
| 1002 | for _, path := range [][]string{{"landed"}, {"stopped"}, {"sent", "landed", "sent"}, {"sent", "landed", "stopped"}, {"sent", "stopped", "sent"}, {"sent", "stopped", "landed"}} { |
| 1003 | s := newJournal(t) |
| 1004 | var err error |
| 1005 | for _, st := range path { |
| 1006 | if err = advanceWrite(ctx, s, wr(st)); err != nil { |
| 1007 | break |
| 1008 | } |
| 1009 | } |
| 1010 | if err == nil { |
| 1011 | t.Errorf("write path %v accepted", path) |
| 1012 | } |
| 1013 | } |
| 1014 | s := newJournal(t) |
| 1015 | for _, st := range []string{"sent", "sent", "landed"} { |
| 1016 | if err := advanceWrite(ctx, s, wr(st)); err != nil { |
| 1017 | t.Fatalf("write %s: %v", st, err) |
| 1018 | } |
| 1019 | } |
| 1020 | s = newJournal(t) |
| 1021 | if err := advanceWrite(ctx, s, wr("sent")); err != nil { |
| 1022 | t.Fatal(err) |
| 1023 | } |
| 1024 | if err := advanceWrite(ctx, s, WriteRecord{App: "docs", State: "sent", Sent: map[string]string{"DOCS_AGENT_ISSUER": Issuer, "DOCS_AGENT_TEAM": "tOther9"}}); err == nil { |
| 1025 | t.Error("the sent values changed under a sent record") |
| 1026 | } |
| 1027 | |
| 1028 | rb := func(state string) RollbackRecord { return RollbackRecord{App: "docs", State: state} } |
| 1029 | for _, path := range [][]string{{"restarted"}, {"sent", "restarted"}, {"unset", "sent"}, {"unset", "restarted", "unset"}, {"stopped", "sent"}, {"unset", "stopped", "restarted"}, {"unset", "restarted", "stopped"}} { |
| 1030 | s := newJournal(t) |
| 1031 | var err error |
| 1032 | for _, st := range path { |
| 1033 | if err = advanceRollback(ctx, s, rb(st)); err != nil { |
| 1034 | break |
| 1035 | } |
| 1036 | } |
| 1037 | if err == nil { |
| 1038 | t.Errorf("rollback path %v accepted", path) |
| 1039 | } |
| 1040 | } |
| 1041 | s = newJournal(t) |
| 1042 | for _, st := range []string{"sent", "sent", "unset", "unset", "restarted"} { |
| 1043 | if err := advanceRollback(ctx, s, rb(st)); err != nil { |
| 1044 | t.Fatalf("rollback %s: %v", st, err) |
| 1045 | } |
| 1046 | } |
| 1047 | // A change found before the restart stops a rollback already unset. |
| 1048 | s = newJournal(t) |
| 1049 | for _, st := range []string{"unset", "stopped"} { |
| 1050 | if err := advanceRollback(ctx, s, rb(st)); err != nil { |
| 1051 | t.Fatalf("rollback %s: %v", st, err) |
| 1052 | } |
| 1053 | } |
| 1054 | } |
| 1055 | |
| 1056 | // ---- The after snapshot ---- |
| 1057 | |
| 1058 | func TestAfterSnapshotRefusesSecretResealedBeforeCapture(t *testing.T) { |
| 1059 | cases := map[string]func(w *writeFixture){ |
| 1060 | "resealed": func(w *writeFixture) { w.f.SetSecret("docs", "", "DOCS_INSTANCE_KEY") }, |
| 1061 | "gone": func(w *writeFixture) { w.f.Unset("docs", "", "DOCS_ORIGIN") }, |
| 1062 | "agent key": func(w *writeFixture) { w.f.SetVar("docs", "", "DOCS_AGENT_TEAM", "tOther9") }, |
| 1063 | "agent gone": func(w *writeFixture) { w.f.Unset("docs", "", "DOCS_AGENT_ISSUER") }, |
| 1064 | "team mode": func(w *writeFixture) { w.f.SetVar("docs", "", "DOCS_TEAM_ID", "team-id-value") }, |
| 1065 | "overlay": func(w *writeFixture) { w.f.SetOverlay("docs", docsRoute, "DOCS_ORIGIN", "x") }, |
| 1066 | } |
| 1067 | for name, edit := range cases { |
| 1068 | t.Run(name, func(t *testing.T) { |
| 1069 | fastPolls(t, 5*time.Millisecond, 2*time.Second) |
| 1070 | w := newWriteFixture(t, "docs") |
| 1071 | w.process(false) |
| 1072 | if _, err := w.configure(true); err != nil { |
| 1073 | t.Fatalf("WriteAgentKeys: %v", err) |
| 1074 | } |
| 1075 | base := w.baseline(t) |
| 1076 | ctx := context.Background() |
| 1077 | if _, err := RestartAndWait(ctx, w.c, w.h, w.app, base.Identity, func(d Delivery) error { return Delivered(w.app, base.Delivery, d) }, true); err != nil { |
| 1078 | t.Fatalf("RestartAndWait: %v", err) |
| 1079 | } |
| 1080 | edit(w) |
| 1081 | _, err := CaptureAfter(ctx, w.c, w.h, w.s, w.app) |
| 1082 | if !errors.Is(err, ErrStopPreserved) { |
| 1083 | t.Fatalf("err = %v, want ErrStopPreserved", err) |
| 1084 | } |
| 1085 | noValues(t, err) |
| 1086 | if _, ok, _ := w.s.After(ctx, "docs"); ok { |
| 1087 | t.Fatal("an after snapshot was stored") |
| 1088 | } |
| 1089 | }) |
| 1090 | } |
| 1091 | } |
| 1092 | |
| 1093 | func TestAfterSnapshotStoredWhenPreserved(t *testing.T) { |
| 1094 | w := newWriteFixture(t, "docs") |
| 1095 | after := w.configured(t) |
| 1096 | got, ok, err := w.s.After(context.Background(), "docs") |
| 1097 | if err != nil || !ok || got.Layer.Version != after.Layer.Version { |
| 1098 | t.Fatalf("after snapshot not stored (ok %v, err %v)", ok, err) |
| 1099 | } |
| 1100 | if after.Delivery.Ops != OpsAgent401 { |
| 1101 | t.Fatalf("after ops %q", after.Delivery.Ops) |
| 1102 | } |
| 1103 | if v := findVar(after.Vars, "DOCS_AGENT_TEAM"); v == nil || v.Digest != carlosop.EnvDigest(fixtureSQID) { |
| 1104 | t.Fatal("the after snapshot lacks the sent team") |
| 1105 | } |
| 1106 | } |
| 1107 | |
| 1108 | func TestAfterSnapshotAcceptsUnrelatedNewKey(t *testing.T) { |
| 1109 | fastPolls(t, 5*time.Millisecond, 2*time.Second) |
| 1110 | w := newWriteFixture(t, "docs") |
| 1111 | w.process(false) |
| 1112 | if _, err := w.configure(true); err != nil { |
| 1113 | t.Fatal(err) |
| 1114 | } |
| 1115 | base := w.baseline(t) |
| 1116 | ctx := context.Background() |
| 1117 | if _, err := RestartAndWait(ctx, w.c, w.h, w.app, base.Identity, func(d Delivery) error { return Delivered(w.app, base.Delivery, d) }, true); err != nil { |
| 1118 | t.Fatal(err) |
| 1119 | } |
| 1120 | w.f.PlatformWrite("docs", "", "DOCS_MAIL_EVENTS_URL", "https://mail.example/hook") |
| 1121 | after, err := CaptureAfter(ctx, w.c, w.h, w.s, w.app) |
| 1122 | if err != nil { |
| 1123 | t.Fatalf("CaptureAfter: %v", err) |
| 1124 | } |
| 1125 | if got := NewKeys(base, after, AgentKeys(w.app)); len(got) != 1 || got[0] != "added:DOCS_MAIL_EVENTS_URL" { |
| 1126 | t.Fatalf("NewKeys = %q", got) |
| 1127 | } |
| 1128 | } |
| 1129 | |
| 1130 | func TestAfterSnapshotRefusesBeforeLandedOrDelivered(t *testing.T) { |
| 1131 | w := newWriteFixture(t, "docs") |
| 1132 | ctx := context.Background() |
| 1133 | if _, err := CaptureAfter(ctx, w.c, w.h, w.s, w.app); err == nil { |
| 1134 | t.Fatal("captured with no baseline or write") |
| 1135 | } |
| 1136 | if _, err := w.configure(true); err != nil { |
| 1137 | t.Fatal(err) |
| 1138 | } |
| 1139 | // Written, not restarted: the operations door has not moved. |
| 1140 | if _, err := CaptureAfter(ctx, w.c, w.h, w.s, w.app); err == nil || !strings.Contains(err.Error(), "after-not-delivered") { |
| 1141 | t.Fatalf("err = %v, want after-not-delivered", err) |
| 1142 | } |
| 1143 | if _, ok, _ := w.s.After(ctx, "docs"); ok { |
| 1144 | t.Fatal("an after snapshot was stored") |
| 1145 | } |
| 1146 | } |
| 1147 | |
| 1148 | // ---- Rollback ---- |
| 1149 | |
| 1150 | // rollbackPuts is how many PUTs the console saw after the configure phase. |
| 1151 | func (w *writeFixture) rollbackPuts(base int) int { return w.puts() - base } |
| 1152 | |
| 1153 | func TestRollbackHappyPath(t *testing.T) { |
| 1154 | w := newWriteFixture(t, "docs") |
| 1155 | w.configured(t) |
| 1156 | p, r := w.puts(), w.f.RestartCount(docsRoute) |
| 1157 | if err := w.rollback(true); err != nil { |
| 1158 | t.Fatalf("RollbackAgentKeys: %v", err) |
| 1159 | } |
| 1160 | if n := w.rollbackPuts(p); n != 1 { |
| 1161 | t.Fatalf("rollback PUTs = %d", n) |
| 1162 | } |
| 1163 | if present, _ := w.stored(t); present != [2]bool{} { |
| 1164 | t.Fatalf("keys still present %v", present) |
| 1165 | } |
| 1166 | rec, ok := w.rollbackRecord(t) |
| 1167 | if !ok || rec.State != "restarted" || rec.Receipt == nil || rec.Code != "" { |
| 1168 | t.Fatalf("rollback %v state %q code %q", ok, rec.State, rec.Code) |
| 1169 | } |
| 1170 | if got := w.f.RestartCount(docsRoute); got != r+1 { |
| 1171 | t.Fatalf("restarts %d, want one more", got-r) |
| 1172 | } |
| 1173 | // Restarted is the end: a second call sends nothing. |
| 1174 | n := len(w.f.Requests()) |
| 1175 | if err := w.rollback(true); err != nil { |
| 1176 | t.Fatal(err) |
| 1177 | } |
| 1178 | if len(w.f.Requests()) != n { |
| 1179 | t.Fatal("a finished rollback sent requests") |
| 1180 | } |
| 1181 | } |
| 1182 | |
| 1183 | func TestRollbackDryRunSendsNothing(t *testing.T) { |
| 1184 | w := newWriteFixture(t, "docs") |
| 1185 | w.configured(t) |
| 1186 | p, r := w.puts(), w.f.RestartCount(docsRoute) |
| 1187 | if err := w.rollback(false); err != nil { |
| 1188 | t.Fatalf("dry run: %v", err) |
| 1189 | } |
| 1190 | if w.rollbackPuts(p) != 0 || w.f.RestartCount(docsRoute) != r { |
| 1191 | t.Fatal("a dry run wrote or restarted") |
| 1192 | } |
| 1193 | if _, ok := w.rollbackRecord(t); ok { |
| 1194 | t.Fatal("a dry run journalled a rollback") |
| 1195 | } |
| 1196 | if _, ours := w.stored(t); ours != [2]bool{true, true} { |
| 1197 | t.Fatal("a dry run removed the keys") |
| 1198 | } |
| 1199 | } |
| 1200 | |
| 1201 | func TestRollbackLostAnswerRetryAcceptsUnsetAbsent(t *testing.T) { |
| 1202 | w := newWriteFixture(t, "docs") |
| 1203 | w.configured(t) |
| 1204 | p := w.puts() |
| 1205 | w.f.LoseNextAnswer() |
| 1206 | if err := w.rollback(true); err != nil { |
| 1207 | t.Fatalf("RollbackAgentKeys: %v", err) |
| 1208 | } |
| 1209 | if n := w.rollbackPuts(p); n != 1 { |
| 1210 | t.Fatalf("rollback PUTs = %d, want exactly one", n) |
| 1211 | } |
| 1212 | if rec, _ := w.rollbackRecord(t); rec.State != "restarted" { |
| 1213 | t.Fatalf("state %q", rec.State) |
| 1214 | } |
| 1215 | |
| 1216 | // The receipt rule itself: removed or already absent, both keys, and |
| 1217 | // nothing set. |
| 1218 | keys := AgentKeys(w.app) |
| 1219 | ok := []carlosop.Receipt{ |
| 1220 | {Unset: []string{keys[0], keys[1]}}, |
| 1221 | {Unset: []string{keys[1]}, UnsetAbsent: []string{keys[0]}}, |
| 1222 | {UnsetAbsent: []string{keys[0], keys[1]}}, |
| 1223 | } |
| 1224 | for i, rc := range ok { |
| 1225 | if !unsetReceiptOK(rc, keys) { |
| 1226 | t.Errorf("receipt %d refused", i) |
| 1227 | } |
| 1228 | } |
| 1229 | bad := []carlosop.Receipt{ |
| 1230 | {Unset: []string{keys[0]}}, |
| 1231 | {Unset: []string{keys[0], keys[1], "DOCS_ORIGIN"}}, |
| 1232 | {Unset: []string{keys[0], keys[0]}}, |
| 1233 | {Unset: []string{keys[0]}, UnsetAbsent: []string{keys[0], keys[1]}}, |
| 1234 | {Unset: []string{keys[0], keys[1]}, Set: []string{"DOCS_ORIGIN"}}, |
| 1235 | } |
| 1236 | for i, rc := range bad { |
| 1237 | if unsetReceiptOK(rc, keys) { |
| 1238 | t.Errorf("bad receipt %d accepted", i) |
| 1239 | } |
| 1240 | } |
| 1241 | } |
| 1242 | |
| 1243 | // A malformed answer to the rollback's unset stops it, as for the write: |
| 1244 | // no reread, no restart, and a resume refuses again. |
| 1245 | func TestRollbackStopsOnMalformedReceipts(t *testing.T) { |
| 1246 | for name, edit := range malformedAnswers() { |
| 1247 | t.Run(name, func(t *testing.T) { |
| 1248 | w := newWriteFixture(t, "docs") |
| 1249 | w.configured(t) |
| 1250 | w.putAnswerRewriter(t, edit) |
| 1251 | p, r := w.puts(), w.f.RestartCount(docsRoute) |
| 1252 | err := w.rollback(true) |
| 1253 | if !errors.Is(err, ErrStopConflict) { |
| 1254 | t.Fatalf("err = %v, want ErrStopConflict", err) |
| 1255 | } |
| 1256 | noValues(t, err) |
| 1257 | if n := w.rollbackPuts(p); n != 1 { |
| 1258 | t.Fatalf("rollback PUTs = %d", n) |
| 1259 | } |
| 1260 | if w.f.RestartCount(docsRoute) != r { |
| 1261 | t.Fatal("restarted after a malformed receipt") |
| 1262 | } |
| 1263 | rec, _ := w.rollbackRecord(t) |
| 1264 | if rec.State != "stopped" || rec.Code != "receipt-malformed" { |
| 1265 | t.Fatalf("state %q code %q", rec.State, rec.Code) |
| 1266 | } |
| 1267 | if err := w.rollback(true); !errors.Is(err, ErrStopConflict) { |
| 1268 | t.Fatalf("resume: err = %v, want ErrStopConflict", err) |
| 1269 | } |
| 1270 | if n := w.rollbackPuts(p); n != 1 { |
| 1271 | t.Fatalf("resume sent: rollback PUTs = %d", n) |
| 1272 | } |
| 1273 | }) |
| 1274 | } |
| 1275 | } |
| 1276 | |
| 1277 | func TestRollbackRefusesForeignValue(t *testing.T) { |
| 1278 | cases := map[string]func(w *writeFixture){ |
| 1279 | "another team": func(w *writeFixture) { w.f.SetVar("docs", "", "DOCS_AGENT_TEAM", "tOther9") }, |
| 1280 | "one key gone": func(w *writeFixture) { w.f.Unset("docs", "", "DOCS_AGENT_TEAM") }, |
| 1281 | "a secret": func(w *writeFixture) { w.f.SetSecret("docs", "", "DOCS_AGENT_ISSUER") }, |
| 1282 | } |
| 1283 | for name, edit := range cases { |
| 1284 | t.Run(name, func(t *testing.T) { |
| 1285 | w := newWriteFixture(t, "docs") |
| 1286 | w.configured(t) |
| 1287 | edit(w) |
| 1288 | p, r := w.puts(), w.f.RestartCount(docsRoute) |
| 1289 | for _, apply := range []bool{false, true} { |
| 1290 | err := w.rollback(apply) |
| 1291 | if !errors.Is(err, ErrStopForeign) { |
| 1292 | t.Fatalf("apply %v: err = %v, want ErrStopForeign", apply, err) |
| 1293 | } |
| 1294 | noValues(t, err) |
| 1295 | } |
| 1296 | if w.rollbackPuts(p) != 0 || w.f.RestartCount(docsRoute) != r { |
| 1297 | t.Fatal("a foreign value was unset or the app restarted") |
| 1298 | } |
| 1299 | rec, _ := w.rollbackRecord(t) |
| 1300 | if rec.State != "stopped" || rec.Code != "agent-keys-foreign" { |
| 1301 | t.Fatalf("state %q code %q", rec.State, rec.Code) |
| 1302 | } |
| 1303 | }) |
| 1304 | } |
| 1305 | } |
| 1306 | |
| 1307 | // Preserved keys first: a baseline secret resealed since the write stops |
| 1308 | // the rollback with our keys still in place, for a person to look at. |
| 1309 | func TestRollbackStopsWhenPreservedKeyResealed(t *testing.T) { |
| 1310 | w := newWriteFixture(t, "docs") |
| 1311 | w.configured(t) |
| 1312 | w.f.SetSecret("docs", "", "DOCS_INSTANCE_KEY") |
| 1313 | p, r := w.puts(), w.f.RestartCount(docsRoute) |
| 1314 | for _, apply := range []bool{false, true} { |
| 1315 | err := w.rollback(apply) |
| 1316 | if !errors.Is(err, ErrStopPreserved) { |
| 1317 | t.Fatalf("apply %v: err = %v, want ErrStopPreserved", apply, err) |
| 1318 | } |
| 1319 | noValues(t, err) |
| 1320 | } |
| 1321 | if w.rollbackPuts(p) != 0 || w.f.RestartCount(docsRoute) != r { |
| 1322 | t.Fatal("the rollback unset or restarted past a changed preserved key") |
| 1323 | } |
| 1324 | if _, ours := w.stored(t); ours != [2]bool{true, true} { |
| 1325 | t.Fatal("the keys were removed") |
| 1326 | } |
| 1327 | rec, _ := w.rollbackRecord(t) |
| 1328 | if rec.State != "stopped" || rec.Code != "preserved-changed" { |
| 1329 | t.Fatalf("state %q code %q", rec.State, rec.Code) |
| 1330 | } |
| 1331 | } |
| 1332 | |
| 1333 | // rollbackRefused fails unless a rollback, dry run then applied, stops |
| 1334 | // with ErrStopPreserved and journals code, having unset and restarted |
| 1335 | // nothing. The error names what differs (want), never a value. |
| 1336 | func (w *writeFixture) rollbackRefused(t *testing.T, code, want string) { |
| 1337 | t.Helper() |
| 1338 | p, r := w.puts(), w.f.RestartCount(docsRoute) |
| 1339 | for _, apply := range []bool{false, true} { |
| 1340 | err := w.rollback(apply) |
| 1341 | if !errors.Is(err, ErrStopPreserved) { |
| 1342 | t.Fatalf("apply %v: err = %v, want ErrStopPreserved", apply, err) |
| 1343 | } |
| 1344 | if !strings.Contains(err.Error(), want) { |
| 1345 | t.Fatalf("apply %v: err = %v, want it to name %s", apply, err, want) |
| 1346 | } |
| 1347 | noValues(t, err) |
| 1348 | } |
| 1349 | if w.rollbackPuts(p) != 0 || w.f.RestartCount(docsRoute) != r { |
| 1350 | t.Fatal("the rollback unset or restarted past a change") |
| 1351 | } |
| 1352 | rec, _ := w.rollbackRecord(t) |
| 1353 | if rec.State != "stopped" || rec.Code != code { |
| 1354 | t.Fatalf("state %q code %q", rec.State, rec.Code) |
| 1355 | } |
| 1356 | // Stopped is final: a resume refuses again and sends nothing. |
| 1357 | if err := w.rollback(true); !errors.Is(err, ErrStopPreserved) { |
| 1358 | t.Fatalf("resume: err = %v", err) |
| 1359 | } |
| 1360 | if w.rollbackPuts(p) != 0 { |
| 1361 | t.Fatal("a resume sent the unset") |
| 1362 | } |
| 1363 | } |
| 1364 | |
| 1365 | // bindTo rebinds the canonical host's record to the environment env. |
| 1366 | func (w *writeFixture) bindTo(env string) { |
| 1367 | in := fixtureInstance(w.app) |
| 1368 | in.Environment = env |
| 1369 | w.f.AddInstance(in) |
| 1370 | } |
| 1371 | |
| 1372 | // Preserved keys first, across the whole effective config: a preserved |
| 1373 | // key that changed in a layer other than the write layer stops the |
| 1374 | // rollback before anything is unset, as one in the write layer does. |
| 1375 | func TestRollbackStopsWhenPreservedChangedInAnotherLayer(t *testing.T) { |
| 1376 | cases := map[string]struct { |
| 1377 | edit func(w *writeFixture) |
| 1378 | want string |
| 1379 | }{ |
| 1380 | "secret resealed in the environment": {func(w *writeFixture) { w.f.SetSecret("docs", "production", "DOCS_DEK") }, "changed:DOCS_DEK"}, |
| 1381 | "secret gone from the environment": {func(w *writeFixture) { w.f.Unset("docs", "production", "DOCS_DEK") }, "gone:DOCS_DEK"}, |
| 1382 | "overlay covers a preserved key": {func(w *writeFixture) { |
| 1383 | w.f.SetOverlay("docs", docsRoute, "DOCS_INSTANCE_KEY", "covered") |
| 1384 | }, "from:DOCS_INSTANCE_KEY"}, |
| 1385 | } |
| 1386 | for name, tc := range cases { |
| 1387 | t.Run(name, func(t *testing.T) { |
| 1388 | w := newWriteFixture(t, "docs") |
| 1389 | // The host is bound to an environment that holds a secret of |
| 1390 | // its own; the keys go to the default bundle. |
| 1391 | w.f.SetSecret("docs", "production", "DOCS_DEK") |
| 1392 | w.bindTo("production") |
| 1393 | w.configured(t) |
| 1394 | if w.baseline(t).WriteLayer != "" { |
| 1395 | t.Fatal("the write layer is not the default bundle") |
| 1396 | } |
| 1397 | tc.edit(w) |
| 1398 | w.rollbackRefused(t, "preserved-changed", tc.want) |
| 1399 | if _, ours := w.stored(t); ours != [2]bool{true, true} { |
| 1400 | t.Fatal("the keys were removed") |
| 1401 | } |
| 1402 | }) |
| 1403 | } |
| 1404 | } |
| 1405 | |
| 1406 | // The instance the rollback would reach is the one the baseline |
| 1407 | // observed, or nothing is unset: a changed environment binding, storage |
| 1408 | // or record stops it. |
| 1409 | func TestRollbackStopsWhenIdentityChanged(t *testing.T) { |
| 1410 | cases := map[string]struct { |
| 1411 | edit func(in *carlosop.Instance) |
| 1412 | want string |
| 1413 | }{ |
| 1414 | "environment binding": {func(in *carlosop.Instance) { in.Environment = "staging" }, "identity-environment"}, |
| 1415 | "storage": {func(in *carlosop.Instance) { in.Slug = "s-docs-moved" }, "identity-storage"}, |
| 1416 | "instance record": {func(in *carlosop.Instance) { in.RecordSeq++ }, "identity-record"}, |
| 1417 | } |
| 1418 | for name, tc := range cases { |
| 1419 | t.Run(name, func(t *testing.T) { |
| 1420 | w := newWriteFixture(t, "docs") |
| 1421 | w.f.SetVar("docs", "staging", "DOCS_STAGE", "1") |
| 1422 | w.configured(t) |
| 1423 | in := fixtureInstance(w.app) |
| 1424 | tc.edit(&in) |
| 1425 | w.f.AddInstance(in) |
| 1426 | w.rollbackRefused(t, "identity-changed", tc.want) |
| 1427 | if _, ours := w.stored(t); ours != [2]bool{true, true} { |
| 1428 | t.Fatal("the keys were removed") |
| 1429 | } |
| 1430 | }) |
| 1431 | } |
| 1432 | } |
| 1433 | |
| 1434 | // The canonical domain no longer resolving to the baseline's record stops |
| 1435 | // a rollback as a changed identity, with nothing unset. |
| 1436 | func TestRollbackStopsWhenCanonicalDomainMoves(t *testing.T) { |
| 1437 | cases := map[string]struct { |
| 1438 | edit func(w *writeFixture) |
| 1439 | want string |
| 1440 | }{ |
| 1441 | "claim detached": {func(w *writeFixture) { w.f.DetachDomain("docs", "docs.oficina.works") }, "domain-missing"}, |
| 1442 | "claim re-pointed": {func(w *writeFixture) { |
| 1443 | in := fixtureInstance(w.app) |
| 1444 | in.Host = "docs-2.bds.oncarlos.com" |
| 1445 | w.f.AddInstance(in) |
| 1446 | w.f.AttachDomain("docs", "docs.oficina.works", in.Host, "live") |
| 1447 | }, "identity-alias"}, |
| 1448 | "route to a missing record": {func(w *writeFixture) { |
| 1449 | w.f.AttachDomain("docs", "docs.oficina.works", "gone-docs.bds.oncarlos.com", "live") |
| 1450 | }, "instance-missing"}, |
| 1451 | } |
| 1452 | for name, tc := range cases { |
| 1453 | t.Run(name, func(t *testing.T) { |
| 1454 | w := newWriteFixture(t, "docs") |
| 1455 | w.configured(t) |
| 1456 | tc.edit(w) |
| 1457 | w.rollbackRefused(t, "identity-changed", tc.want) |
| 1458 | if _, ours := w.stored(t); ours != [2]bool{true, true} { |
| 1459 | t.Fatal("the keys were removed") |
| 1460 | } |
| 1461 | }) |
| 1462 | } |
| 1463 | } |
| 1464 | |
| 1465 | // A claim that is merely not live still names the baseline's record: the |
| 1466 | // rollback goes on rather than stopping for good. |
| 1467 | func TestRollbackGoesOnWhenCanonicalDomainNotLive(t *testing.T) { |
| 1468 | w := newWriteFixture(t, "docs") |
| 1469 | w.configured(t) |
| 1470 | w.f.AttachDomain("docs", "docs.oficina.works", docsRoute, "checking") |
| 1471 | if err := w.rollback(true); err != nil { |
| 1472 | t.Fatalf("RollbackAgentKeys: %v", err) |
| 1473 | } |
| 1474 | if present, _ := w.stored(t); present != [2]bool{} { |
| 1475 | t.Fatalf("keys still present %v", present) |
| 1476 | } |
| 1477 | } |
| 1478 | |
| 1479 | // A change that lands while the unset is in flight, in a layer the unset |
| 1480 | // does not touch, is caught before the restart: the unset succeeds, the |
| 1481 | // restart never runs, and the rollback stops. |
| 1482 | func TestRollbackStopsBeforeRestartOnChangeDuringUnset(t *testing.T) { |
| 1483 | cases := map[string]struct { |
| 1484 | edit func(w *writeFixture) |
| 1485 | code, want string |
| 1486 | }{ |
| 1487 | "secret resealed in the environment": {func(w *writeFixture) { w.f.SetSecret("docs", "production", "DOCS_DEK") }, "preserved-changed", "changed:DOCS_DEK"}, |
| 1488 | "instance record replaced": {func(w *writeFixture) { |
| 1489 | in := fixtureInstance(w.app) |
| 1490 | in.Environment, in.RecordSeq = "production", in.RecordSeq+1 |
| 1491 | w.f.AddInstance(in) |
| 1492 | }, "identity-changed", "identity-record"}, |
| 1493 | } |
| 1494 | for name, tc := range cases { |
| 1495 | t.Run(name, func(t *testing.T) { |
| 1496 | w := newWriteFixture(t, "docs") |
| 1497 | w.f.SetSecret("docs", "production", "DOCS_DEK") |
| 1498 | w.bindTo("production") |
| 1499 | w.configured(t) |
| 1500 | p, r := w.puts(), w.f.RestartCount(docsRoute) |
| 1501 | w.f.BeforePut = once(func() { tc.edit(w) }) |
| 1502 | err := w.rollback(true) |
| 1503 | if !errors.Is(err, ErrStopPreserved) || !strings.Contains(err.Error(), tc.want) { |
| 1504 | t.Fatalf("err = %v, want ErrStopPreserved naming %s", err, tc.want) |
| 1505 | } |
| 1506 | noValues(t, err) |
| 1507 | if n := w.rollbackPuts(p); n != 1 { |
| 1508 | t.Fatalf("rollback PUTs = %d", n) |
| 1509 | } |
| 1510 | if present, _ := w.stored(t); present != [2]bool{} { |
| 1511 | t.Fatal("the unset did not land") |
| 1512 | } |
| 1513 | if w.f.RestartCount(docsRoute) != r { |
| 1514 | t.Fatal("restarted past a change made during the unset") |
| 1515 | } |
| 1516 | rec, _ := w.rollbackRecord(t) |
| 1517 | if rec.State != "stopped" || rec.Code != tc.code { |
| 1518 | t.Fatalf("state %q code %q", rec.State, rec.Code) |
| 1519 | } |
| 1520 | if err := w.rollback(true); !errors.Is(err, ErrStopPreserved) { |
| 1521 | t.Fatalf("resume: err = %v", err) |
| 1522 | } |
| 1523 | if w.f.RestartCount(docsRoute) != r { |
| 1524 | t.Fatal("a resume restarted") |
| 1525 | } |
| 1526 | }) |
| 1527 | } |
| 1528 | } |
| 1529 | |
| 1530 | // A rollback resumed after its unset re-observes too: the restart is a |
| 1531 | // mutation, and a preserved key that changed since stops it. |
| 1532 | func TestRollbackResumeAfterUnsetStopsOnPreservedChange(t *testing.T) { |
| 1533 | w := newWriteFixture(t, "docs") |
| 1534 | w.configured(t) |
| 1535 | for _, k := range AgentKeys(w.app) { |
| 1536 | w.f.Unset("docs", "", k) |
| 1537 | } |
| 1538 | if err := w.s.SaveRollback(context.Background(), RollbackRecord{App: "docs", State: "unset"}); err != nil { |
| 1539 | t.Fatal(err) |
| 1540 | } |
| 1541 | w.f.SetSecret("docs", "", "DOCS_INSTANCE_KEY") |
| 1542 | w.rollbackRefused(t, "preserved-changed", "changed:DOCS_INSTANCE_KEY") |
| 1543 | } |
| 1544 | |
| 1545 | // A 412 whose reread shows a preserved key resealed stops the rollback |
| 1546 | // rather than retrying the unset. |
| 1547 | func TestRollbackConflict412StopsOnResealedKey(t *testing.T) { |
| 1548 | w := newWriteFixture(t, "docs") |
| 1549 | w.configured(t) |
| 1550 | p := w.puts() |
| 1551 | w.f.BeforePut = once(func() { w.f.SetSecret("docs", "", "DOCS_INSTANCE_KEY") }) |
| 1552 | if err := w.rollback(true); !errors.Is(err, ErrStopPreserved) { |
| 1553 | t.Fatalf("err = %v, want ErrStopPreserved", err) |
| 1554 | } |
| 1555 | if n := w.rollbackPuts(p); n != 1 { |
| 1556 | t.Fatalf("rollback PUTs = %d", n) |
| 1557 | } |
| 1558 | if _, ours := w.stored(t); ours != [2]bool{true, true} { |
| 1559 | t.Fatal("the keys were removed") |
| 1560 | } |
| 1561 | } |
| 1562 | |
| 1563 | func TestRollbackConflict412Rereads(t *testing.T) { |
| 1564 | w := newWriteFixture(t, "docs") |
| 1565 | w.configured(t) |
| 1566 | p := w.puts() |
| 1567 | w.f.BeforePut = once(func() { w.f.PlatformWrite("docs", "", "DOCS_MAIL_EVENTS_URL", "https://mail.example/hook") }) |
| 1568 | if err := w.rollback(true); err != nil { |
| 1569 | t.Fatalf("RollbackAgentKeys: %v", err) |
| 1570 | } |
| 1571 | if n := w.rollbackPuts(p); n != 2 { |
| 1572 | t.Fatalf("rollback PUTs = %d, want a 412 then the retry", n) |
| 1573 | } |
| 1574 | if present, _ := w.stored(t); present != [2]bool{} { |
| 1575 | t.Fatal("keys still present") |
| 1576 | } |
| 1577 | vars, _, _ := w.f.Layer("docs", "") |
| 1578 | if _, ok := vars["DOCS_MAIL_EVENTS_URL"]; !ok { |
| 1579 | t.Fatal("the platform's key was lost") |
| 1580 | } |
| 1581 | if rec, _ := w.rollbackRecord(t); rec.State != "restarted" { |
| 1582 | t.Fatalf("state %q", rec.State) |
| 1583 | } |
| 1584 | } |
| 1585 | |
| 1586 | func TestRollbackCrashAfterUnsetResumesToRestart(t *testing.T) { |
| 1587 | w := newWriteFixture(t, "docs") |
| 1588 | w.configured(t) |
| 1589 | ctx := context.Background() |
| 1590 | // The crash: the unset landed and was journalled, the restart never ran. |
| 1591 | for _, k := range AgentKeys(w.app) { |
| 1592 | w.f.Unset("docs", "", k) |
| 1593 | } |
| 1594 | if err := w.s.SaveRollback(ctx, RollbackRecord{App: "docs", State: "unset"}); err != nil { |
| 1595 | t.Fatal(err) |
| 1596 | } |
| 1597 | p, r := w.puts(), w.f.RestartCount(docsRoute) |
| 1598 | if err := w.rollback(true); err != nil { |
| 1599 | t.Fatalf("resume: %v", err) |
| 1600 | } |
| 1601 | if w.rollbackPuts(p) != 0 { |
| 1602 | t.Fatal("the resume sent the unset again") |
| 1603 | } |
| 1604 | if w.f.RestartCount(docsRoute) != r+1 { |
| 1605 | t.Fatal("the resume did not restart") |
| 1606 | } |
| 1607 | if rec, _ := w.rollbackRecord(t); rec.State != "restarted" { |
| 1608 | t.Fatalf("state %q", rec.State) |
| 1609 | } |
| 1610 | } |
| 1611 | |
| 1612 | func TestRollbackRestartFailureLeavesUnsetState(t *testing.T) { |
| 1613 | w := newWriteFixture(t, "docs") |
| 1614 | w.configured(t) |
| 1615 | p := w.puts() |
| 1616 | w.f.FailRestart(http.StatusServiceUnavailable) |
| 1617 | if err := w.rollback(true); err == nil { |
| 1618 | t.Fatal("a failed restart reported success") |
| 1619 | } |
| 1620 | rec, _ := w.rollbackRecord(t) |
| 1621 | if rec.State != "unset" || rec.Code != "restart-failed" || rec.Receipt == nil { |
| 1622 | t.Fatalf("state %q code %q", rec.State, rec.Code) |
| 1623 | } |
| 1624 | if present, _ := w.stored(t); present != [2]bool{} { |
| 1625 | t.Fatal("keys still present") |
| 1626 | } |
| 1627 | w.f.FailRestart(0) |
| 1628 | if err := w.rollback(true); err != nil { |
| 1629 | t.Fatalf("resume: %v", err) |
| 1630 | } |
| 1631 | if n := w.rollbackPuts(p); n != 1 { |
| 1632 | t.Fatalf("rollback PUTs = %d: the resume unset again", n) |
| 1633 | } |
| 1634 | if rec, _ := w.rollbackRecord(t); rec.State != "restarted" || rec.Code != "" { |
| 1635 | t.Fatalf("state %q code %q", rec.State, rec.Code) |
| 1636 | } |
| 1637 | } |
| 1638 | |
| 1639 | func TestRollbackUsesScopedDryRun(t *testing.T) { |
| 1640 | w := newWriteFixture(t, "docs") |
| 1641 | // A neighbour on an owned environment: the write never reaches it, |
| 1642 | // and neither does the restart. |
| 1643 | w.neighbour("staging.docs.example", "acme-docs") |
| 1644 | w.f.SetVar("docs", "acme-docs", "DOCS_HOME_ISSUER", HomeIssuerOrigin) |
| 1645 | w.f.Own("docs", "acme-docs", "alta") |
| 1646 | w.configured(t) |
| 1647 | start := len(w.f.Requests()) |
| 1648 | r := w.f.RestartCount(docsRoute) |
| 1649 | if err := w.rollback(true); err != nil { |
| 1650 | t.Fatalf("RollbackAgentKeys: %v", err) |
| 1651 | } |
| 1652 | var doors []string |
| 1653 | for _, req := range w.f.Requests()[start:] { |
| 1654 | if req == "PUT /config" || strings.Contains(req, "restart") { |
| 1655 | doors = append(doors, req) |
| 1656 | } |
| 1657 | } |
| 1658 | // The unset, then the dry run, then the one real request. |
| 1659 | want := []string{"PUT /config", "POST /restart/scope", "POST /restart/scope"} |
| 1660 | if strings.Join(doors, "|") != strings.Join(want, "|") { |
| 1661 | t.Fatalf("doors %q, want %q", doors, want) |
| 1662 | } |
| 1663 | if w.f.RestartCount(docsRoute) != r+1 { |
| 1664 | t.Fatal("the canonical host did not restart once") |
| 1665 | } |
| 1666 | w.noRestarts(t, "staging.docs.example") |
| 1667 | |
| 1668 | // A dry run that resolves more than the host restarts nothing, and |
| 1669 | // the rollback stays unset for a resume. |
| 1670 | w2 := newWriteFixture(t, "docs") |
| 1671 | w2.configured(t) |
| 1672 | w2.dryRunRewriter(t, func(rt []map[string]any) []map[string]any { |
| 1673 | return append(rt, map[string]any{"host": "staging.docs.example", "hibernate": false}) |
| 1674 | }) |
| 1675 | r2 := w2.f.RestartCount(docsRoute) |
| 1676 | err := w2.rollback(true) |
| 1677 | if err == nil || !strings.Contains(err.Error(), "restart-scope-2") { |
| 1678 | t.Fatalf("err = %v, want restart-scope-2", err) |
| 1679 | } |
| 1680 | if w2.f.RestartCount(docsRoute) != r2 || w2.f.AppWideRestarts() != 0 { |
| 1681 | t.Fatal("restarted past a wider dry run") |
| 1682 | } |
| 1683 | if rec, _ := w2.rollbackRecord(t); rec.State != "unset" || rec.Code != "restart-failed" { |
| 1684 | t.Fatalf("state %q code %q", rec.State, rec.Code) |
| 1685 | } |
| 1686 | } |
| 1687 | |
| 1688 | func TestRollbackCompleteOnlyWhenReverted(t *testing.T) { |
| 1689 | w := newWriteFixture(t, "docs") |
| 1690 | w.configured(t) |
| 1691 | // The process ignores the restart: it keeps the delegated-access door. |
| 1692 | w.site.ops = agent401 |
| 1693 | fastPolls(t, 5*time.Millisecond, 100*time.Millisecond) |
| 1694 | err := w.rollback(true) |
| 1695 | if err == nil || !strings.Contains(err.Error(), "restart-timeout") { |
| 1696 | t.Fatalf("err = %v, want restart-timeout", err) |
| 1697 | } |
| 1698 | rec, _ := w.rollbackRecord(t) |
| 1699 | if rec.State != "unset" || rec.Code != "restart-failed" { |
| 1700 | t.Fatalf("state %q code %q: complete before Reverted", rec.State, rec.Code) |
| 1701 | } |
| 1702 | // The process reloads on its next restart; the resume restarts again. |
| 1703 | w.process(true) |
| 1704 | fastPolls(t, 5*time.Millisecond, 2*time.Second) |
| 1705 | if err := w.rollback(true); err != nil { |
| 1706 | t.Fatalf("resume: %v", err) |
| 1707 | } |
| 1708 | if rec, _ := w.rollbackRecord(t); rec.State != "restarted" { |
| 1709 | t.Fatalf("state %q", rec.State) |
| 1710 | } |
| 1711 | } |
| 1712 | |
| 1713 | func TestRollbackRefusesWithoutAWrite(t *testing.T) { |
| 1714 | w := newWriteFixture(t, "docs") |
| 1715 | if err := w.rollback(true); err == nil { |
| 1716 | t.Fatal("rolled back an app with no write") |
| 1717 | } |
| 1718 | if w.puts() != 0 { |
| 1719 | t.Fatal("sent a PUT") |
| 1720 | } |
| 1721 | } |
| 1722 | |