package isolatedjob import ( "errors" "net/netip" "os" "strings" "testing" "time" "amadan.net/rastrillo/rastrillo/budget" ) func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } const goodDigest = ImageDigest("sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef") func goodSpec() LaunchSpec { return LaunchSpec{ AttemptID: "attempt-1", Image: goodDigest, Size: SizeSmall, MaxLifetime: time.Hour, Bootstrap: []byte("one-time-code"), } } func TestLaunchSpecValidate(t *testing.T) { limits := Limits{MaxLifetime: HardMaxLifetime, MaxBootstrapBytes: 4096} short := Limits{MaxLifetime: time.Hour, MaxBootstrapBytes: 4096} loose := Limits{MaxLifetime: 10 * time.Hour, MaxBootstrapBytes: 4096} cases := []struct { name string limits Limits edit func(*LaunchSpec) want error // nil means the spec passes field string // a word the error must name }{ {"good", limits, func(*LaunchSpec) {}, nil, ""}, {"attempt id empty", limits, func(s *LaunchSpec) { s.AttemptID = "" }, ErrInvalid, "attempt id"}, {"attempt id 65 chars", limits, func(s *LaunchSpec) { s.AttemptID = strings.Repeat("a", 65) }, ErrInvalid, "attempt id"}, {"attempt id underscore", limits, func(s *LaunchSpec) { s.AttemptID = "attempt_1" }, ErrInvalid, "attempt id"}, {"attempt id space", limits, func(s *LaunchSpec) { s.AttemptID = "attempt 1" }, ErrInvalid, "attempt id"}, {"attempt id non-ascii", limits, func(s *LaunchSpec) { s.AttemptID = "attempt-é" }, ErrInvalid, "attempt id"}, {"attempt id 64 chars at limit", limits, func(s *LaunchSpec) { s.AttemptID = strings.Repeat("A9-", 21) + "z" }, nil, ""}, {"attempt id one char", limits, func(s *LaunchSpec) { s.AttemptID = "a" }, nil, ""}, {"image empty", limits, func(s *LaunchSpec) { s.Image = "" }, ErrInvalid, "image"}, {"image no prefix", limits, func(s *LaunchSpec) { s.Image = goodDigest[len("sha256:"):] }, ErrInvalid, "image"}, {"image upper prefix", limits, func(s *LaunchSpec) { s.Image = ImageDigest(strings.ToUpper(string(goodDigest[:20]))) + goodDigest[20:] }, ErrInvalid, "image"}, {"image upper hex digit", limits, func(s *LaunchSpec) { s.Image = goodDigest[:len(goodDigest)-1] + "F" }, ErrInvalid, "image"}, {"image short", limits, func(s *LaunchSpec) { s.Image = goodDigest[:len(goodDigest)-1] }, ErrInvalid, "image"}, {"image long", limits, func(s *LaunchSpec) { s.Image = goodDigest + "0" }, ErrInvalid, "image"}, {"image other algorithm", limits, func(s *LaunchSpec) { s.Image = "sha512:" + goodDigest[len("sha256:"):] }, ErrInvalid, "image"}, {"size empty", limits, func(s *LaunchSpec) { s.Size = "" }, ErrInvalid, "size"}, {"size medium", limits, func(s *LaunchSpec) { s.Size = "medium" }, ErrInvalid, "size"}, {"size capitalised", limits, func(s *LaunchSpec) { s.Size = "Small" }, ErrInvalid, "size"}, {"size large", limits, func(s *LaunchSpec) { s.Size = SizeLarge }, nil, ""}, {"lifetime zero", limits, func(s *LaunchSpec) { s.MaxLifetime = 0 }, ErrInvalid, "lifetime"}, {"lifetime negative", limits, func(s *LaunchSpec) { s.MaxLifetime = -time.Second }, ErrInvalid, "lifetime"}, {"lifetime one nanosecond", limits, func(s *LaunchSpec) { s.MaxLifetime = 1 }, nil, ""}, {"lifetime over the provider limit", short, func(s *LaunchSpec) { s.MaxLifetime = time.Hour + time.Second }, ErrInvalid, "lifetime"}, {"lifetime at the provider limit", short, func(s *LaunchSpec) { s.MaxLifetime = time.Hour }, nil, ""}, {"lifetime 28801 s", limits, func(s *LaunchSpec) { s.MaxLifetime = 28801 * time.Second }, ErrInvalid, "lifetime"}, {"lifetime 28801 s over a looser provider", loose, func(s *LaunchSpec) { s.MaxLifetime = 28801 * time.Second }, ErrInvalid, "lifetime"}, {"lifetime 28800 s at the hard limit", limits, func(s *LaunchSpec) { s.MaxLifetime = 28800 * time.Second }, nil, ""}, {"lifetime 28800 s at the hard limit, looser provider", loose, func(s *LaunchSpec) { s.MaxLifetime = 28800 * time.Second }, nil, ""}, {"lifetime with no provider limit", Limits{MaxBootstrapBytes: 4096}, func(*LaunchSpec) {}, ErrInvalid, "lifetime"}, {"bootstrap empty", limits, func(s *LaunchSpec) { s.Bootstrap = nil }, ErrInvalid, "bootstrap"}, {"bootstrap zero length", limits, func(s *LaunchSpec) { s.Bootstrap = []byte{} }, ErrInvalid, "bootstrap"}, {"bootstrap one byte", limits, func(s *LaunchSpec) { s.Bootstrap = []byte("x") }, nil, ""}, {"bootstrap at the limit", limits, func(s *LaunchSpec) { s.Bootstrap = make([]byte, 4096) }, nil, ""}, {"bootstrap one byte over", limits, func(s *LaunchSpec) { s.Bootstrap = make([]byte, 4097) }, ErrBootstrapTooLarge, "bootstrap"}, {"bootstrap with no provider limit", Limits{MaxLifetime: HardMaxLifetime}, func(*LaunchSpec) {}, ErrBootstrapTooLarge, "bootstrap"}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { s := goodSpec() c.edit(&s) err := s.Validate(c.limits) if c.want == nil { if err != nil { t.Fatalf("Validate = %v, want nil", err) } return } if !errors.Is(err, c.want) { t.Fatalf("Validate = %v, want %v", err, c.want) } if !strings.Contains(err.Error(), c.field) { t.Fatalf("Validate = %q, want it to name %q", err, c.field) } }) } } func TestHardMaxLifetime(t *testing.T) { if HardMaxLifetime != 8*time.Hour { t.Fatalf("HardMaxLifetime = %v, want 8h", HardMaxLifetime) } } func TestSizeMemory(t *testing.T) { for _, c := range []struct { size Size mib int }{{SizeSmall, 2048}, {SizeLarge, 4096}, {"", 0}, {"medium", 0}} { if got := c.size.MemoryMiB(); got != c.mib { t.Errorf("Size(%q).MemoryMiB() = %d, want %d", c.size, got, c.mib) } } if SizeSmall != "small" || SizeLarge != "large" { t.Fatalf("sizes = %q, %q", SizeSmall, SizeLarge) } } func TestStateSets(t *testing.T) { cases := []struct { state State live, terminal bool }{ {StateStarting, true, false}, {StateRunning, true, false}, {StateSuspending, true, false}, {StateSuspended, true, false}, {StateStopping, true, false}, {StateStopped, false, true}, {StateFailed, false, true}, {StateUnknown, false, false}, // Values no adapter should produce are treated as unknown. {"", false, false}, {"TERMINATED", false, false}, {"RUNNING", false, false}, {"Stopped", false, false}, } for _, c := range cases { if got := c.state.Live(); got != c.live { t.Errorf("State(%q).Live() = %v, want %v", c.state, got, c.live) } if got := c.state.Terminal(); got != c.terminal { t.Errorf("State(%q).Terminal() = %v, want %v", c.state, got, c.terminal) } } want := map[State]string{ StateStarting: "starting", StateRunning: "running", StateSuspending: "suspending", StateSuspended: "suspended", StateStopping: "stopping", StateStopped: "stopped", StateFailed: "failed", StateUnknown: "unknown", } for s, v := range want { if string(s) != v { t.Errorf("state %q, want %q", s, v) } } } func TestNetworkAuditOK(t *testing.T) { a := netip.MustParseAddrPort("10.0.0.1:443") b := netip.MustParseAddrPort("10.0.0.2:443") c := netip.MustParseAddrPort("10.0.0.1:80") clean := func(egress ...netip.AddrPort) NetworkAudit { return NetworkAudit{ResolverDisabled: true, IngressClosed: true, RouteOutAbsent: true, EgressOnly: egress} } all := []string{"resolver", "ingress", "route out", "egress"} cases := []struct { name string audit NetworkAudit want []netip.AddrPort named []string // properties the error must name; nil means OK }{ {"exact", clean(a, b), []netip.AddrPort{a, b}, nil}, {"other order", clean(b, a), []netip.AddrPort{a, b}, nil}, {"single", clean(a), []netip.AddrPort{a}, nil}, {"none wanted none seen", clean(), nil, nil}, {"resolver on", NetworkAudit{IngressClosed: true, RouteOutAbsent: true, EgressOnly: []netip.AddrPort{a}}, []netip.AddrPort{a}, []string{"resolver"}}, {"ingress open", NetworkAudit{ResolverDisabled: true, RouteOutAbsent: true, EgressOnly: []netip.AddrPort{a}}, []netip.AddrPort{a}, []string{"ingress"}}, {"route out", NetworkAudit{ResolverDisabled: true, IngressClosed: true, EgressOnly: []netip.AddrPort{a}}, []netip.AddrPort{a}, []string{"route out"}}, {"extra egress", clean(a, b), []netip.AddrPort{a}, []string{"egress"}}, {"missing egress", clean(a), []netip.AddrPort{a, b}, []string{"egress"}}, {"same address other port", clean(c), []netip.AddrPort{a}, []string{"egress"}}, {"egress seen none wanted", clean(a), nil, []string{"egress"}}, {"nothing seen", clean(), []netip.AddrPort{a}, []string{"egress"}}, {"everything wrong", NetworkAudit{EgressOnly: []netip.AddrPort{b}}, []netip.AddrPort{a}, all}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { err := c.audit.OK(c.want) if c.named == nil { if err != nil { t.Fatalf("OK = %v, want nil", err) } return } if err == nil { t.Fatalf("OK = nil, want an error naming %v", c.named) } msg := err.Error() for _, p := range all { named := strings.Contains(msg, p) want := false for _, n := range c.named { want = want || n == p } if named != want { t.Errorf("OK = %q: names %q is %v, want %v", msg, p, named, want) } } }) } } func TestSystemClock(t *testing.T) { c := SystemClock() last := c.Mono() if last < 0 { t.Fatalf("Mono = %v, want >= 0", last) } for i := 0; i < 1000; i++ { m := c.Mono() if m < last { t.Fatalf("Mono went back: %v after %v", m, last) } last = m } w := c.Wall() if strings.Contains(w.String(), "m=") { t.Fatalf("Wall = %v carries a monotonic reading", w) } if d := time.Since(w); d < 0 || d > time.Minute { t.Fatalf("Wall = %v, %v from now", w, d) } // Mono must come from Go's monotonic reading, so the start must keep it. if start := c.(systemClock).start; !strings.Contains(start.String(), " m=") { t.Fatalf("start = %v has no monotonic reading", start) } } // TestSystemClockWallJump sets the wall clock back an hour while elapsed // time moves forward: Mono must follow elapsed time, Wall the wall clock. func TestSystemClockWallJump(t *testing.T) { wall := time.Date(2026, 11, 22, 12, 0, 0, 0, time.UTC) var elapsed time.Duration c := newSystemClock( func() time.Time { return wall }, func(time.Time) time.Duration { return elapsed }, ) steps := []struct { advance, wallShift time.Duration }{ {5 * time.Second, 5 * time.Second}, {5 * time.Second, -time.Hour}, {time.Second, 0}, {2 * time.Second, 90 * time.Minute}, } var lastMono time.Duration for i, s := range steps { elapsed += s.advance wall = wall.Add(s.wallShift) if got := c.Mono(); got != elapsed || got < lastMono { t.Fatalf("step %d: Mono = %v, want %v (last %v)", i, got, elapsed, lastMono) } lastMono = c.Mono() if got := c.Wall(); !got.Equal(wall) { t.Fatalf("step %d: Wall = %v, want %v", i, got, wall) } } }