ez-agent-ruby/internal/runtimepayload/manifest_test.go
package runtimepayload
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"strings"
"testing"
)
func validManifest() Manifest {
sum := sha256.Sum256([]byte("ruby"))
return Manifest{
Schema: 1, RubyVersion: RubyVersion, Revision: Revision, Target: Target,
Files: []Entry{{Path: "bin/ruby", SHA256: hex.EncodeToString(sum[:]), Mode: 0755, Size: 4}},
}
}
func TestExactIdentity(t *testing.T) {
if err := ValidateIdentity(RubyVersion, Revision, Target); err != nil {
t.Fatal(err)
}
for _, identity := range [][3]string{
{"3.4.011", Revision, Target},
{RubyVersion, "02", Target},
{RubyVersion, Revision, "linux-x86_64"},
} {
if err := ValidateIdentity(identity[0], identity[1], identity[2]); err == nil {
t.Fatalf("accepted noncanonical identity %q", identity)
}
}
}
func TestManifestSemanticValidation(t *testing.T) {
valid := validManifest()
if err := ValidateManifest(valid); err != nil {
t.Fatal(err)
}
tests := map[string]Manifest{}
wrong := valid
wrong.Target = "linux-arm64"
tests["wrong target"] = wrong
unsafe := valid
unsafe.Files = append([]Entry(nil), valid.Files...)
unsafe.Files[0].Path = "../ruby"
tests["unsafe path"] = unsafe
upper := valid
upper.Files = append([]Entry(nil), valid.Files...)
upper.Files[0].SHA256 = strings.ToUpper(upper.Files[0].SHA256)
tests["noncanonical checksum"] = upper
unsorted := valid
unsorted.Files = []Entry{valid.Files[0], valid.Files[0]}
unsorted.Files[0].Path = "z"
unsorted.Files[1].Path = "a"
tests["unsorted paths"] = unsorted
for name, manifest := range tests {
if err := ValidateManifest(manifest); err == nil {
t.Errorf("accepted %s", name)
}
}
}
func TestDecodeRejectsDuplicateKeys(t *testing.T) {
valid := validManifest()
e := valid.Files[0]
base := `{"schema":1,"ruby_version":"%s","revision":"%s","target":"%s","files":[{"path":"%s","sha256":"%s","mode":%d,"size":%d}]}`
good := fmt.Sprintf(base, RubyVersion, Revision, Target, e.Path, e.SHA256, e.Mode, e.Size)
if _, err := DecodeManifestStrict([]byte(good)); err != nil {
t.Fatal(err)
}
duplicateTop := strings.Replace(good, `"schema":1`, `"schema":1,"schema":1`, 1)
duplicateEntry := strings.Replace(good, `"path":"bin/ruby"`, `"path":"bin/ruby","path":"bin/ruby"`, 1)
for name, input := range map[string]string{"top-level": duplicateTop, "file entry": duplicateEntry} {
if _, err := DecodeManifestStrict([]byte(input)); err == nil {
t.Errorf("accepted duplicate %s key", name)
}
}
}