package release import ( "os" "path/filepath" "testing" "time" ) func seedRootBake(t *testing.T, h *RootHistory, b HistoryBinding, at time.Time) { t.Helper() r := rootBakeRecord{Schema: 1, Revision: 1, Observed: at, Complete: map[string]uint64{prodKey(b.Account, b.App): 1}, Clock: FirstSeen{Channels: map[string]map[string]time.Time{}}} if err := h.writeBake(r); err != nil { t.Fatal(err) } } func TestPlan14RootBakeRetainsHistory(t *testing.T) { h, _, b := rootHistoryFixture(t) start := time.Now().UTC().Add(-time.Hour) seedRootBake(t, h, b, start) clock, err := h.LoadBake([]HistoryBinding{b}, start) if err != nil { t.Fatal(err) } clock.Observe(b.Account, b.App, "stable", "new", start) clock.Production = map[string]*prodMemory{prodKey(b.Account, b.App): {WasProduction: true}} clock.Holds = map[string]*holdMemory{channelClockKey(b.Account, b.App, "stable"): {Window: 96 * time.Hour, SetAt: start}} if err := clock.Save(); err != nil { t.Fatal(err) } legacy := t.TempDir() if err := os.WriteFile(FirstSeenPath(legacy), []byte(`{"jitter":0,"channels":{},"production":{},"holds":{}}`), 0600); err != nil { t.Fatal(err) } if err := os.Rename(legacy, legacy+"-moved"); err != nil { t.Fatal(err) } t.Cleanup(func() { _ = os.RemoveAll(legacy + "-moved") }) clock, err = h.LoadBake([]HistoryBinding{b}, start.Add(time.Hour)) if err != nil { t.Fatal(err) } if !clock.Production[prodKey(b.Account, b.App)].WasProduction || clock.Holds[channelClockKey(b.Account, b.App, "stable")].Window != 96*time.Hour { t.Fatal("legacy replacement removed root ratchets") } holds := map[string]time.Duration{"stable": 96 * time.Hour} if Hold(clock, b.Account, b.App, "stable", "new", holds, false, start.Add(time.Hour)) == "" { t.Fatal("hold shortened") } if Hold(clock, b.Account, b.App, "stable", "new", holds, false, start.Add(121*time.Hour)) != "" { t.Fatal("root interval never elapsed") } } func TestPlan14RootBakeUnknownAndDurability(t *testing.T) { for _, attack := range []string{"missing", "malformed", "wrong-app", "sync", "backward"} { t.Run(attack, func(t *testing.T) { h, s, b := rootHistoryFixture(t) now := time.Now().UTC() seedRootBake(t, h, b, now) switch attack { case "missing": if err := os.Remove(filepath.Join(s.dir, rootBakeKey)); err != nil { t.Fatal(err) } case "malformed": if err := s.Write(rootBakeKey, []byte(`{}`)); err != nil { t.Fatal(err) } case "wrong-app": b.App = "other" case "sync": s.fail = 1 case "backward": now = now.Add(-time.Hour) } if _, err := h.LoadBake([]HistoryBinding{b}, now); err == nil { t.Fatal("unavailable bake history granted adoption") } }) } }