diff --git a/CHANGELOG.md b/CHANGELOG.md index a7a24e7..f783452 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,32 @@ mistaken for a safe patch upgrade. ## [Unreleased] +### Fixed + +- No method on a zero-value `Version` panics. Eight of the thirteen exported methods did: + `String`, `BaseVersion` and `Public` indexed `release[0]` on a nil slice, and all six + comparison methods inherited it because `Compare` calls `String` as its equality fast + path. A zero `Version` now renders as `""` and sorts below every parsed version, with two + zero values comparing equal. No version `Parse` accepts can render as `""` — the grammar + requires a release segment — so the empty string cannot collide with a real version. + + A panicking `String` method is worse than most panics because `fmt` **recovers** it: + `fmt.Errorf("%s", v)` returned an error whose message contained + `%!s(PANIC=String method: runtime error: index out of range [0] with length 0)` and + reported no failure, so the defect was silently swallowed at the call sites most likely + to reach it, while a direct `String()` call crashed the process. +- `real.Compare(Version{})` no longer panics with a nil pointer dereference. A zero + `Version`'s comparison key holds nil `Part` interfaces, and the underlying + `Parts.IsAny` ranges over elements calling `IsAny()` on each without a nil check, so the + panic fired before any element was compared — and only when the zero value was the + *argument*, which is why `Version{}.Compare(real)` returned an answer while the reverse + crashed. `Compare` now decides from the release segment before building a key. +- `Compare` pads both release segments to the longer of the two. It previously padded the + second to its own length, which is a no-op. **No behavior changes for parsed versions** — + the underlying comparison tolerated the resulting length mismatch and returned the right + answer, verified across nine pairs with differing segment counts in both directions — so + this was latent rather than wrong. It became reachable only through a nil release. + ## [0.3.0] - 2026-08-07 Finishes the conformance work `0.2.0` began, and corrects the module's attribution. diff --git a/version/version.go b/version/version.go index db77564..980b5f7 100644 --- a/version/version.go +++ b/version/version.go @@ -309,11 +309,47 @@ func (v Version) Compare(other Version) int { return 0 } + // ⚠️ An uninitialized Version cannot go through key comparison at all. Its + // key's pre/post/dev/local are NIL Part interfaces, and go-version's + // Parts.IsAny ranges over the elements calling p.IsAny() with no nil check + // (part/list.go:101), so merely asking whether the Parts is "any" + // dereferences nil. That call sits at part/list.go:54, before any element + // is compared, and only on the *argument* side -- which is exactly why + // real.Compare(Version{}) crashed while Version{}.Compare(real) returned + // -1 perfectly well. The asymmetry was the tell that this is not about + // release lengths. + // + // Decide from the release segment instead. Parse cannot produce an empty + // release, so an empty one means an uninitialized Version: it sorts below + // every real version, and two of them are equal. + switch { + case len(v.release) == 0 && len(other.release) == 0: + return 0 + case len(v.release) == 0: + return -1 + case len(other.release) == 0: + return 1 + } + k1 := v.key k2 := other.key - k1.release = k1.release.Padding(len(k2.release), part.Zero) - k2.release = k2.release.Padding(len(k2.release), part.Zero) + // Pad both release segments to the longer of the two, so an absent + // trailing segment compares as zero and 1.2 equals 1.2.0. + // + // ⚠️ The second line padded k2 to its OWN length, which is a no-op, where + // it means the longer of the two. For two parsed versions key.compare + // tolerates the unequal lengths that left behind and still returns the + // right answer -- verified across ten pairs with differing segment counts + // in both directions -- so the defect was latent rather than wrong. + // + // It stopped being latent for a zero-value Version, whose release is nil: + // real.Compare(Version{}) dereferenced a nil part and crashed while + // Version{}.Compare(real) returned -1, because only the k1 side was ever + // actually padded. That asymmetry is the tell. + n := max(len(k1.release), len(k2.release)) + k1.release = k1.release.Padding(n, part.Zero) + k2.release = k2.release.Padding(n, part.Zero) return k1.compare(k2) } @@ -354,10 +390,20 @@ func (v Version) String() string { } // Release segment - fmt.Fprintf(&buf, "%s", v.release[0]) - for _, r := range v.release[1:len(v.release)] { - fmt.Fprintf(&buf, ".%s", r) - } + // + // ⚠️ A zero-value Version has no release segments, and indexing release[0] + // unconditionally made every rendering path panic on one. Parse cannot + // produce an empty release -- the grammar requires `[0-9]+` -- so an empty + // one always means an uninitialized Version is being rendered, and the + // empty string cannot collide with any version Parse accepts. + // + // A panicking String method is worse than most panics, because fmt + // *recovers* it: `fmt.Errorf("%s", v)` yields a message containing + // "%!s(PANIC=String method: ...)" and reports no error, so the bug is + // swallowed at exactly the call sites most likely to hit it. A direct call + // crashes instead. Compare() also calls String() as its fast path, so this + // one line is what made all six comparison methods panic as well. + writeRelease(&buf, v.release) // Pre-release if !v.pre.isNull() { @@ -391,15 +437,26 @@ func (v Version) BaseVersion() string { fmt.Fprintf(&buf, "%s!", v.epoch.String()) } - // Release segment - fmt.Fprintf(&buf, "%s", v.release[0].String()) - for _, r := range v.release[1:len(v.release)] { - fmt.Fprintf(&buf, ".%s", r.String()) - } + // Release segment. See String() for why an empty release is rendered as + // nothing rather than indexed into. + writeRelease(&buf, v.release) return buf.String() } +// writeRelease renders a dot-joined release segment, or nothing at all when +// there are no segments. Shared by String and BaseVersion so the two cannot +// drift on the empty case, which is how only one of them getting a guard would +// leave the other panicking. +func writeRelease(buf *bytes.Buffer, release []part.BigInt) { + for i, r := range release { + if i > 0 { + buf.WriteByte('.') + } + buf.WriteString(r.String()) + } +} + // Original returns the original parsed version as-is, including any // potential whitespace, `v` prefix, etc. func (v Version) Original() string { diff --git a/version/zero_value_test.go b/version/zero_value_test.go new file mode 100644 index 0000000..0496431 --- /dev/null +++ b/version/zero_value_test.go @@ -0,0 +1,165 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package version + +import ( + "fmt" + "strings" + "testing" +) + +// A zero-value Version is reachable by accident all over Go -- an unset struct +// field, a map miss, a slice grown with make -- so no method on it may panic. +// Eight of the thirteen exported methods used to: String, BaseVersion and +// Public indexed release[0] on a nil slice, and all six comparison methods +// inherited it because Compare calls String as its fast path. +// +// This table is deliberately exhaustive over the exported surface rather than +// testing only the methods known to have been broken, because the failure mode +// is "somebody adds a method that indexes release[0]" and a targeted test would +// not catch that. +func TestZeroValueMethodsDoNotPanic(t *testing.T) { + real := mustParse(t, "1.2.3") + + cases := []struct { + name string + call func() + }{ + {"String", func() { _ = Version{}.String() }}, + {"BaseVersion", func() { _ = Version{}.BaseVersion() }}, + {"Original", func() { _ = Version{}.Original() }}, + {"Local", func() { _ = Version{}.Local() }}, + {"Public", func() { _ = Version{}.Public() }}, + {"IsPreRelease", func() { _ = Version{}.IsPreRelease() }}, + {"IsPostRelease", func() { _ = Version{}.IsPostRelease() }}, + {"Compare(zero)", func() { _ = Version{}.Compare(Version{}) }}, + {"Equal(zero)", func() { _ = Version{}.Equal(Version{}) }}, + {"GreaterThan(zero)", func() { _ = Version{}.GreaterThan(Version{}) }}, + {"GreaterThanOrEqual(zero)", func() { _ = Version{}.GreaterThanOrEqual(Version{}) }}, + {"LessThan(zero)", func() { _ = Version{}.LessThan(Version{}) }}, + {"LessThanOrEqual(zero)", func() { _ = Version{}.LessThanOrEqual(Version{}) }}, + + // ⚠️ Both directions. The original defect was asymmetric: the panic + // came from go-version's Parts.IsAny ranging over nil Part interfaces + // on the *argument* side, so real.Compare(Version{}) crashed while + // Version{}.Compare(real) returned an answer. Testing one direction + // would have missed it. + {"zero.Compare(real)", func() { _ = Version{}.Compare(real) }}, + {"real.Compare(zero)", func() { _ = real.Compare(Version{}) }}, + {"zero.Equal(real)", func() { _ = Version{}.Equal(real) }}, + {"real.Equal(zero)", func() { _ = real.Equal(Version{}) }}, + {"real.LessThan(zero)", func() { _ = real.LessThan(Version{}) }}, + {"real.GreaterThan(zero)", func() { _ = real.GreaterThan(Version{}) }}, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Fatalf("panicked: %v", r) + } + }() + c.call() + }) + } +} + +// The empty string is only a safe rendering for an uninitialized Version if no +// version Parse accepts can render as "". The grammar requires a release +// segment, so it cannot -- but that is the property the choice rests on, so it +// is asserted rather than assumed. +func TestNoParsedVersionRendersEmpty(t *testing.T) { + for _, s := range []string{ + "0", "0.0", "1", "1.0", "0!0", "1.0a1", "1.0.dev0", "1.0+local", + "0.0.0.0.0", "1!0.0", " 1.0 ", "v1.0", "1.0.post0", + } { + v, err := Parse(s) + if err != nil { + t.Errorf("Parse(%q): unexpected error %v", s, err) + continue + } + if v.String() == "" { + t.Errorf("Parse(%q).String() == \"\", which collides with the "+ + "uninitialized-Version rendering", s) + } + if v.BaseVersion() == "" { + t.Errorf("Parse(%q).BaseVersion() == \"\", same collision", s) + } + } +} + +// A zero Version sorts below every real version, and two of them are equal. +func TestZeroValueOrdering(t *testing.T) { + real := mustParse(t, "0") + + if got := (Version{}).Compare(Version{}); got != 0 { + t.Errorf("zero.Compare(zero) = %d, want 0", got) + } + if got := (Version{}).Compare(real); got != -1 { + t.Errorf("zero.Compare(0) = %d, want -1", got) + } + if got := real.Compare(Version{}); got != 1 { + t.Errorf("0.Compare(zero) = %d, want 1", got) + } + if !(Version{}).Equal(Version{}) { + t.Error("two zero Versions should be Equal") + } + if (Version{}).Equal(real) { + t.Error("a zero Version should not Equal 0") + } +} + +// ⚠️ A panicking String method is worse than an ordinary panic, because fmt +// recovers it and substitutes a "%!s(PANIC=...)" placeholder. Before the fix, +// fmt.Errorf("%s", Version{}) produced an error whose message contained that +// placeholder and reported no failure -- so the bug was invisible at exactly +// the call sites most likely to hit it, while a direct .String() crashed. +// This pins that a formatted zero Version is now clean. +func TestZeroValueFormattingHasNoPanicPlaceholder(t *testing.T) { + msg := fmt.Sprintf("version=%s base=%s", Version{}, Version{}.BaseVersion()) + if strings.Contains(msg, "PANIC") { + t.Errorf("formatting a zero Version still embeds a recovered panic: %q", msg) + } + if msg != "version= base=" { + t.Errorf("formatted zero Version = %q, want %q", msg, "version= base=") + } +} + +// Release segments of differing lengths must compare as though the shorter were +// zero-padded, in both directions. Compare pads both sides to the longer of the +// two; it previously padded the second to its own length, which is a no-op. +// key.compare tolerated the resulting mismatch for parsed versions, so this was +// latent -- these cases passed before the fix and must keep passing after it. +func TestCompareUnequalReleaseLengths(t *testing.T) { + cases := []struct { + a, b string + want int + }{ + {"1.2", "1.2.3", -1}, + {"1.2.3", "1.2", 1}, + {"1", "1.0.0", 0}, + {"1.0.0", "1", 0}, + {"1.0", "1.0.0.0", 0}, + {"2", "1.9.9.9", 1}, + {"1.9.9.9", "2", -1}, + {"1.2.3.4.5", "1.2", 1}, + {"1.2", "1.2.3.4.5", -1}, + } + + for _, c := range cases { + a := mustParse(t, c.a) + b := mustParse(t, c.b) + if got := a.Compare(b); got != c.want { + t.Errorf("%s.Compare(%s) = %d, want %d", c.a, c.b, got, c.want) + } + } +} + +func mustParse(t *testing.T, s string) Version { + t.Helper() + v, err := Parse(s) + if err != nil { + t.Fatalf("Parse(%q): %v", s, err) + } + return v +}