package isolatedjob import ( "fmt" "strings" ) // maxAttemptIDLen bounds an attempt ID. The ID becomes the provider's client // token (AWS takes 1 to 128 characters), so 64 leaves room. const maxAttemptIDLen = 64 // Validate checks s against the provider limits l before any provider call. // // - AttemptID: 1 to 64 characters, each an ASCII letter, digit or '-'. // - Image: "sha256:" and 64 lower-case hex digits. // - Size: SizeSmall or SizeLarge. // - MaxLifetime: above zero and no more than the smaller of l.MaxLifetime // and HardMaxLifetime. // - Bootstrap: 1 to l.MaxBootstrapBytes bytes. // // Every failure wraps ErrInvalid, except an oversized bootstrap, which wraps // ErrBootstrapTooLarge. func (s LaunchSpec) Validate(l Limits) error { if !validAttemptID(s.AttemptID) { return fmt.Errorf("%w: attempt id must be 1 to %d letters, digits or '-'", ErrInvalid, maxAttemptIDLen) } if !validDigest(s.Image) { return fmt.Errorf("%w: image must be sha256: and 64 lower-case hex digits", ErrInvalid) } if s.Size.MemoryMiB() == 0 { return fmt.Errorf("%w: size %q is not %q or %q", ErrInvalid, s.Size, SizeSmall, SizeLarge) } limit := min(l.MaxLifetime, HardMaxLifetime) if s.MaxLifetime <= 0 || s.MaxLifetime > limit { return fmt.Errorf("%w: lifetime %v must be above zero and at most %v", ErrInvalid, s.MaxLifetime, limit) } if len(s.Bootstrap) == 0 { return fmt.Errorf("%w: bootstrap is empty", ErrInvalid) } if len(s.Bootstrap) > l.MaxBootstrapBytes { return fmt.Errorf("%w: bootstrap is %d bytes, limit %d", ErrBootstrapTooLarge, len(s.Bootstrap), l.MaxBootstrapBytes) } return nil } func validAttemptID(id string) bool { if len(id) == 0 || len(id) > maxAttemptIDLen { return false } for i := 0; i < len(id); i++ { c := id[i] if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-') { return false } } return true } func validDigest(d ImageDigest) bool { hex, ok := strings.CutPrefix(string(d), "sha256:") if !ok || len(hex) != 64 { return false } for i := 0; i < len(hex); i++ { c := hex[i] if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') { return false } } return true }