Backtestshugorun-20260917-015623#15068

Issue #15068 Merged fix PR # Run 17 Sep 2026 · run-20260917-015623 gohugoio/hugo

Add encoding.HexDecode/Encode

Better

Our patch was judged better than the merged fix.

In this judgment, Patch A = our agent, Patch B = the merged fix.

The issue's substantive request (body + linked comment) is explicit: 'It's clumsy that you need to create a resource... to get a SRI hash. I suggest we add crypto.Fingerprint with a signature like hash.Fingerprint [ALGORITHM] any -> string' returning 'sha256-...'. Patch A implements exactly that root-cause fix: hash.Fingerprint(value) / hash.Fingerprint(algo, value) returning the SRI form 'sha256-HY1v...nw4='. It correctly matches the requested signature and pipe ergonomics (with two args, algo is args[0] and value args[1], so `value | hash.Fingerprint "sha256"` works), unwraps both hugio.ReadSeekCloserProvider and resource.ContentProvider so `any` can be a string OR a Resource as the issue calls for, defaults to sha256, and returns clear errors for bad algo/arity. It also acts on the implementer note about 'obvious code reuse potential' by hoisting NewHash into common/hashing and having integrity.go delegate to it — a scoped, motivated refactor that removes duplication rather than incidental churn. Its test fails before/passes after and covers default, explicit sha256, sha512 prefix, unsupported algo, and arity errors. Patch B instead implements encoding.HexDecode/HexEncode (matching only the issue *title*), which does NOT resolve the core complaint: to get an SRI hash the user must still chain `$s | crypto.SHA256 | encoding.HexDecode | encoding.Base64Encode` and manually build the `sha256-` prefix — precisely the clumsy, multi-step workaround the issue asks to eliminate. Patch B's tests (including a nice end-to-end integration test) are well-crafted and correct, but they verify a symptom-level workaround rather than the requested primitive. On the top-weighted criterion (correctness / root-cause resolution) Patch A clearly wins; both have solid, non-tautological tests and reasonable scope/craft, so A is the better fix overall.

The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.

Solve

20m 56s5 turns

Wall-clock time in the container

Full test suite

No new failures

3,661 passed · 93 skipped · 3,767 total

Contamination audit

Unknown

See the audit notes for this run

Patch size

148vs 137 merged

Changed lines, ours vs merged

See https://github.com/gohugoio/hugo/issues/15060#issuecomment-4790405347

It's clumsy that you need to create a resource (making up an unique filename) to get a SRI hash.

I suggest we add crypto.Fingerprint with a similar signature to https://gohugo.io/functions/resources/fingerprint/

hash.Fingerprint [ALGORITHM] any -> string

The function name is a little clumsy, but we need to keep the two very similar functions in line.

Where any typically is a string (but can also be a Resource -- we have similar unwrappers elsewhere).

It would then return e.g. sha256-Yuh...rfE=.

Note to implementer: There's some obvious code reuse potential here.

The two patches

Our patch+132 −16
common/hashing/hashing.goindex ad28bbce2..d5fe8b888 100644@@ -16,7 +16,12 @@ package hashing  import ( 	"crypto/md5"+	"crypto/sha256"+	"crypto/sha512"+	"encoding/base64" 	"encoding/hex"+	"fmt"+	"hash" 	"io" 	"strconv" 	"sync"@@ -105,6 +110,37 @@ func MD5FromStringHexEncoded(f string) string { 	return hex.EncodeToString(h.Sum(nil)) } +// NewHash returns a new hash.Hash for the given algorithm.+// The supported algorithms are md5, sha256, sha384 and sha512.+func NewHash(algo string) (hash.Hash, error) {+	switch algo {+	case "md5":+		return md5.New(), nil+	case "sha256":+		return sha256.New(), nil+	case "sha384":+		return sha512.New384(), nil+	case "sha512":+		return sha512.New(), nil+	default:+		return nil, fmt.Errorf("unsupported hash algorithm: %q, use either md5, sha256, sha384 or sha512", algo)+	}+}++// Fingerprint calculates the Subresource Integrity (SRI) hash for the content+// read from r using the given algorithm, returned in the form "algo-base64".+// See https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity+func Fingerprint(r io.Reader, algo string) (string, error) {+	h, err := NewHash(algo)+	if err != nil {+		return "", err+	}+	if _, err := io.Copy(h, r); err != nil {+		return "", err+	}+	return algo + "-" + base64.StdEncoding.EncodeToString(h.Sum(nil)), nil+}+ // HashString returns a hash from the given elements. // It will panic if the hash cannot be calculated. // Note that this hash should be used primarily for identity, not for change detection asresources/resource_transformers/integrity/integrity.goindex aef744443..ae4459033 100644@@ -14,16 +14,13 @@ package integrity  import (-	"crypto/md5"-	"crypto/sha256"-	"crypto/sha512" 	"encoding/base64" 	"encoding/hex"-	"fmt" 	"hash" 	"io"  	"github.com/gohugoio/hugo/common/constants"+	"github.com/gohugoio/hugo/common/hashing" 	"github.com/gohugoio/hugo/resources/internal"  	"github.com/gohugoio/hugo/resources"@@ -81,18 +78,7 @@ func (t *fingerprintTransformation) Transform(ctx *resources.ResourceTransformat }  func newHash(algo string) (hash.Hash, error) {-	switch algo {-	case "md5":-		return md5.New(), nil-	case "sha256":-		return sha256.New(), nil-	case "sha384":-		return sha512.New384(), nil-	case "sha512":-		return sha512.New(), nil-	default:-		return nil, fmt.Errorf("unsupported hash algorithm: %q, use either md5, sha256, sha384 or sha512", algo)-	}+	return hashing.NewHash(algo) }  // Fingerprint applies fingerprinting of the given resource and hash algorithm.tpl/hash/hash.goindex b82fc3679..df9488e33 100644@@ -16,10 +16,14 @@ package hash  import ( 	"context"+	"errors" 	"hash/fnv"+	"strings"  	"github.com/gohugoio/hugo/common/hashing"+	"github.com/gohugoio/hugo/common/hugio" 	"github.com/gohugoio/hugo/deps"+	"github.com/gohugoio/hugo/resources/resource" 	"github.com/gohugoio/hugo/tpl/internal" 	"github.com/spf13/cast" )@@ -32,6 +36,8 @@ func New() *Namespace { // Namespace provides template functions for the "hash" namespace. type Namespace struct{} +const defaultFingerprintAlgo = "sha256"+ // FNV32a hashes v using fnv32a algorithm. func (ns *Namespace) FNV32a(v any) (int, error) { 	conv, err := cast.ToStringE(v)@@ -53,6 +59,55 @@ func (ns *Namespace) XxHash(v any) (string, error) { 	return hashing.XxHashFromStringHexEncoded(conv), nil } +// Fingerprint returns the Subresource Integrity (SRI) hash for the given value+// using the given hash algorithm, e.g. "sha256-Yuh...rfE=".+// The value is typically a string, but can also be a Resource.+// The algorithm is optional and defaults to "sha256"; the supported+// algorithms are md5, sha256, sha384 and sha512.+func (ns *Namespace) Fingerprint(ctx context.Context, args ...any) (string, error) {+	if len(args) < 1 || len(args) > 2 {+		return "", errors.New("must provide a value and an optional hash algorithm")+	}++	algo := defaultFingerprintAlgo+	v := args[0]++	if len(args) == 2 {+		var err error+		algo, err = cast.ToStringE(args[0])+		if err != nil {+			return "", err+		}+		v = args[1]+	}++	switch r := v.(type) {+	case hugio.ReadSeekCloserProvider:+		rsc, err := r.ReadSeekCloser()+		if err != nil {+			return "", err+		}+		defer rsc.Close()+		return hashing.Fingerprint(rsc, algo)+	case resource.ContentProvider:+		content, err := r.Content(ctx)+		if err != nil {+			return "", err+		}+		s, err := cast.ToStringE(content)+		if err != nil {+			return "", err+		}+		return hashing.Fingerprint(strings.NewReader(s), algo)+	default:+		s, err := cast.ToStringE(v)+		if err != nil {+			return "", err+		}+		return hashing.Fingerprint(strings.NewReader(s), algo)+	}+}+ const name = "hash"  func init() {@@ -78,6 +133,13 @@ func init() { 			}, 		) +		ns.AddMethodMapping(ctx.Fingerprint,+			nil,+			[][2]string{+				{`{{ hash.Fingerprint "Hugo Rocks!!" }}`, `sha256-HY1vydSfD6fYTcQTNT2nickqsoRP3iuEz45C9FZsnw4=`},+			},+		)+ 		return ns 	} tpl/hash/hash_test.goindex d493aa16e..f5910aa2c 100644@@ -15,6 +15,7 @@ package hash  import (+	"context" 	"crypto/md5" 	"encoding/hex" 	"fmt"@@ -37,6 +38,37 @@ func TestXxHash(t *testing.T) { 	c.Assert(h, qt.Equals, "0b242d361fda71bc") } +func TestFingerprint(t *testing.T) {+	t.Parallel()+	c := qt.New(t)++	ns := New()+	ctx := context.Background()++	// Default algorithm (single string arg) is sha256.+	h, err := ns.Fingerprint(ctx, "Hugo Rocks!!")+	c.Assert(err, qt.IsNil)+	c.Assert(h, qt.Equals, "sha256-HY1vydSfD6fYTcQTNT2nickqsoRP3iuEz45C9FZsnw4=")++	// Explicit sha256 (two args) matches the default.+	h, err = ns.Fingerprint(ctx, "sha256", "Hugo Rocks!!")+	c.Assert(err, qt.IsNil)+	c.Assert(h, qt.Equals, "sha256-HY1vydSfD6fYTcQTNT2nickqsoRP3iuEz45C9FZsnw4=")++	// Explicit sha512 produces a sha512-prefixed hash.+	h, err = ns.Fingerprint(ctx, "sha512", "Hugo Rocks!!")+	c.Assert(err, qt.IsNil)+	c.Assert(strings.HasPrefix(h, "sha512-"), qt.IsTrue)++	// Unsupported algorithm returns an error.+	_, err = ns.Fingerprint(ctx, "nope", "Hugo Rocks!!")+	c.Assert(err, qt.IsNotNil)++	// Wrong number of args (zero) returns an error.+	_, err = ns.Fingerprint(ctx)+	c.Assert(err, qt.IsNotNil)+}+ func BenchmarkXxHash(b *testing.B) { 	const inputSmall = "The quick brown fox jumps over the lazy dog" 	inputLarge := strings.Repeat(inputSmall, 100) 
Merged fix · PR #+137 −0
tpl/encoding/encoding.goindex 6ac0e4f1e..1f7cf7b79 100644@@ -16,6 +16,7 @@ package encoding  import ( 	"encoding/base64"+	"encoding/hex" 	"encoding/json" 	"errors" 	"html/template"@@ -56,6 +57,28 @@ func (ns *Namespace) Base64Encode(content any) (string, error) { 	return base64.StdEncoding.EncodeToString([]byte(conv)), nil } +// HexDecode returns the hex decoding of the given content.+func (ns *Namespace) HexDecode(content any) (string, error) {+	conv, err := cast.ToStringE(content)+	if err != nil {+		return "", err+	}+	b, err := hex.DecodeString(conv)+	if err != nil {+		return "", err+	}+	return string(b), nil+}++// HexEncode returns the hex encoding of the given content.+func (ns *Namespace) HexEncode(content any) (string, error) {+	conv, err := cast.ToStringE(content)+	if err != nil {+		return "", err+	}+	return hex.EncodeToString([]byte(conv)), nil+}+ // Jsonify encodes a given object to JSON.  To pretty print the JSON, pass a map // or dictionary of options as the first value in args.  Supported options are // "prefix" and "indent".  Each JSON element in the output will begin on a newtpl/encoding/encoding_test.goindex 8e6e2da48..116bef408 100644@@ -77,6 +77,60 @@ func TestBase64Encode(t *testing.T) { 	} } +func TestHexDecode(t *testing.T) {+	t.Parallel()+	c := qt.New(t)++	ns := New()++	for _, test := range []struct {+		v      any+		expect any+	}{+		{"616263313233213f242a2628292d3d407e", "abc123!?$*&()-=@~"},+		// errors+		{t, false},+	} {++		result, err := ns.HexDecode(test.v)++		if b, ok := test.expect.(bool); ok && !b {+			c.Assert(err, qt.Not(qt.IsNil))+			continue+		}++		c.Assert(err, qt.IsNil)+		c.Assert(result, qt.Equals, test.expect)+	}+}++func TestHexEncode(t *testing.T) {+	t.Parallel()+	c := qt.New(t)++	ns := New()++	for _, test := range []struct {+		v      any+		expect any+	}{+		{"abc123!?$*&()-=@~", "616263313233213f242a2628292d3d407e"},+		// errors+		{t, false},+	} {++		result, err := ns.HexEncode(test.v)++		if b, ok := test.expect.(bool); ok && !b {+			c.Assert(err, qt.Not(qt.IsNil))+			continue+		}++		c.Assert(err, qt.IsNil)+		c.Assert(result, qt.Equals, test.expect)+	}+}+ func TestJsonify(t *testing.T) { 	t.Parallel() 	c := qt.New(t)tpl/encoding/init.goindex 1c3322d6e..aab411e4d 100644@@ -46,6 +46,20 @@ func init() { 			}, 		) +		ns.AddMethodMapping(ctx.HexDecode,+			nil,+			[][2]string{+				{`{{ "48656c6c6f20776f726c64" | encoding.HexDecode }}`, `Hello world`},+			},+		)++		ns.AddMethodMapping(ctx.HexEncode,+			nil,+			[][2]string{+				{`{{ "Hello world" | encoding.HexEncode }}`, `48656c6c6f20776f726c64`},+			},+		)+ 		ns.AddMethodMapping(ctx.Jsonify, 			[]string{"jsonify"}, 			[][2]string{tpl/templates/decorator_integration_test.goindex 253a09316..e671c446c 100644@@ -453,3 +453,49 @@ Home. {{ partial "a" }}:Done. 		} 	} }++func TestDecoratorFingerprintScript(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+baseURL = "https://example.org/"+[outputs]+home = ["html", "headers"]+[mediaTypes]+[mediaTypes."text/netlify"]+delimiter = ""+[outputFormats]+[outputFormats.headers]+baseName       = "_headers"+isPlainText    = true+mediatype      = "text/netlify"+notAlternative = true+-- layouts/_partials/script.html --+{{ $s := (templates.Inner .) }}+{{ $r := resources.FromString ($s | xxhash) $s | fingerprint }}+{{ $hash := $s | crypto.SHA256 | encoding.HexDecode | encoding.Base64Encode }}+{{ $sri := (printf "sha256-%s" $hash) }}+{{ if ne $sri $r.Data.Integrity }}+	{{ errorf "SRI hash mismatch: %s != %s" $sri $r.Data.Integrity }}+{{ end }}+{{ hugo.Store.SetInMap "srihashes" $sri true }}+<script>{{ $s | safeJS }}</script>+-- layouts/home.html --+Home.+{{ with partial "script.html" . }}+console.log("Hello world");+{{ end }}+{{ with partial "script.html" . }}+console.log("Hugo rocks!");+{{ end }}+-- layouts/home.headers --+{{ $hashes := hugo.Store.Get "srihashes" -}}+Content-Security-Policy: script-src 'self'{{ range $k, $v := $hashes }} '{{ $k }}'{{ end }};+`++	b := hugolib.Test(t, files)++	b.AssertFileContentExact("public/index.html", "<script>\nconsole.log(\"Hello world\");\n</script>")+	b.AssertFileContentExact("public/_headers", "Content-Security-Policy: script-src 'self' 'sha256-t6z9j4/CagmaDDbn6nHbntzt8PRk8HZ1TwrgdYuZjbE=' 'sha256-wVbS8f78ttoSSGU80KghGoPcTO8DXqT0Uc/87a7zMdk=';")+} 

What the agent reported

The gate is still running (empty output so far). I'll wait for the completion notification before parsing results.