Backtestshugorun-20260922-141813#15068
Add encoding.HexDecode/Encode
The merged fix was judged better than our patch.
No judgment was produced for this ticket. It counts as an error in the run total.
Solve
21m 3s14 turns
Wall-clock time in the container
Full test suite
1 new failure
3,660 passed · 93 skipped · 3,767 total
Contamination audit
Unknown
See the audit notes for this run
Patch size
110vs 137 merged
Changed lines, ours vs merged
The issue
View on GitHubSee 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
resources/resource_transformers/integrity/integrity.goindex aef744443..1d7451711 100644@@ -109,6 +109,23 @@ func (c *Client) Fingerprint(res resources.ResourceTransformer, algo string) (re return res.Transform(&fingerprintTransformation{algo: algo}) } +// Fingerprint returns the Subresource Integrity (SRI) hash (e.g. "sha256-b3f...")+// of the content read from r using the given algorithm. If algo is empty, the+// default algorithm (sha256) is used.+func Fingerprint(r io.Reader, algo string) (string, error) {+ if algo == "" {+ algo = defaultHashAlgo+ }+ h, err := newHash(algo)+ if err != nil {+ return "", err+ }+ if _, err := io.Copy(h, r); err != nil {+ return "", err+ }+ return integrity(algo, h.Sum(nil)), nil+}+ func integrity(algo string, sum []byte) string { encoded := base64.StdEncoding.EncodeToString(sum) return algo + "-" + encodedtpl/crypto/crypto.goindex b2952e97e..88a67aaeb 100644@@ -15,14 +15,20 @@ package crypto import (+ "context" "crypto/hmac" "crypto/md5" "crypto/sha1" "crypto/sha256" "crypto/sha512" "encoding/hex"+ "errors" "fmt" "hash"+ "strings"++ "github.com/gohugoio/hugo/resources/resource"+ "github.com/gohugoio/hugo/resources/resource_transformers/integrity" "github.com/spf13/cast" )@@ -68,6 +74,54 @@ func (ns *Namespace) SHA256(v any) (string, error) { return hex.EncodeToString(hash[:]), nil } +// Fingerprint hashes the given value v using the given algorithm (defaulting to+// sha256) and returns its Subresource Integrity (SRI) hash, e.g.+// "sha256-b3f...". The value v is typically a string, but can also be a+// Resource, in which case its content is hashed. The algorithm must be one of+// md5, sha256, sha384 or sha512.+func (ns *Namespace) Fingerprint(ctx context.Context, args ...any) (string, error) {+ if len(args) < 1 {+ return "", errors.New("must provide a value")+ }++ if len(args) > 2 {+ return "", errors.New("must not provide more than a value and a hash algorithm")+ }++ algo := ""+ valIdx := 0++ if len(args) == 2 {+ valIdx = 1+ var err error+ algo, err = cast.ToStringE(args[0])+ if err != nil {+ return "", err+ }+ }++ var (+ conv string+ err error+ )++ if r, ok := args[valIdx].(resource.ContentProvider); ok {+ var c any+ c, err = r.Content(ctx)+ if err != nil {+ return "", err+ }+ conv, err = cast.ToStringE(c)+ } else {+ conv, err = cast.ToStringE(args[valIdx])+ }+ if err != nil {+ return "", err+ }++ return integrity.Fingerprint(strings.NewReader(conv), algo)+}+ // HMAC returns a cryptographic hash that uses a key to sign a message. func (ns *Namespace) HMAC(h any, k any, m any, e ...any) (string, error) { ha, err := cast.ToStringE(h)tpl/crypto/crypto_test.goindex b6b2a6915..73f812e84 100644@@ -14,6 +14,7 @@ package crypto import (+ "context" "testing" qt "github.com/frankban/quicktest"@@ -101,6 +102,37 @@ func TestSHA256(t *testing.T) { } } +func TestFingerprint(t *testing.T) {+ t.Parallel()+ c := qt.New(t)+ ns := New()++ for i, test := range []struct {+ args []any+ expect any+ }{+ {[]any{"Hello world, gophers!"}, "sha256-bsQ7eNqWafUOTkIldcVL+HU2lUzNWCgCGcOT8s41K0Y="},+ {[]any{"sha256", "Hello world, gophers!"}, "sha256-bsQ7eNqWafUOTkIldcVL+HU2lUzNWCgCGcOT8s41K0Y="},+ {[]any{"sha384", "Hello world, gophers!"}, "sha384-6RSwYOBvERX9mLSUJX1lJAMwW1hcKaVGNucmK15Erfxh8ZXwPUGS2JoAaygZL90l"},+ {[]any{"sha512", "Hello world, gophers!"}, "sha512-4rdFiVR9iVSkcyHhnimH/842YxfjhDvn2n6uMJCg6stGOTtSl4kzr6Zci8NlwynlWVC2EGEZo4KjtPTNWIbdzw=="},+ {[]any{"md5", "Hello world, gophers!"}, "md5-swKfdW+Y955/G38dHw3VOw=="},+ {[]any{"unsupported", "foo"}, false},+ {[]any{}, false},+ } {+ errMsg := qt.Commentf("[%d] %v", i, test.args)++ result, err := ns.Fingerprint(context.Background(), test.args...)++ if b, ok := test.expect.(bool); ok && !b {+ c.Assert(err, qt.Not(qt.IsNil), errMsg)+ continue+ }++ c.Assert(err, qt.IsNil, errMsg)+ c.Assert(result, qt.Equals, test.expect, errMsg)+ }+}+ func TestHMAC(t *testing.T) { t.Parallel() c := qt.New(t)tpl/crypto/init.goindex b31237045..68e130b65 100644@@ -60,6 +60,13 @@ func init() { }, ) + ns.AddMethodMapping(ctx.Fingerprint,+ nil,+ [][2]string{+ {`{{ crypto.Fingerprint "Hello world, gophers!" }}`, `sha256-bsQ7eNqWafUOTkIldcVL+HU2lUzNWCgCGcOT8s41K0Y=`},+ },+ )+ return ns }
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 change is complete, verified, and reviewed clean. The AGENTS.md/CLAUDE.md deletions in git status are pre-existing environment artifacts (present in the initial snapshot), not part of my work — I left them untouched.
Summary
What was reported: It's clumsy to have to create a Resource (with a made-up unique filename) just to obtain a Subresource Integrity (SRI) hash. The report asks for a crypto.Fingerprint function mirroring resources.Fingerprint — signature Fingerprint [ALGORITHM] any -> string — that accepts a string (or a Resource, unwrapped) and returns e.g. sha256-Yuh...rfE=, with a note about obvious code-reuse potential.
(The ticket title mentions encoding.HexDecode/Encode, which is unrelated to the detailed body. I treated the body — which gives a full signature and rationale — as authoritative and implemented that.)
What I changed:
resources/resource_transformers/integrity/integrity.go— added an exportedFingerprint(r io.Reader, algo string) (string, error)that reuses the existingnewHash,integrity(SRIalgo-base64formatter), anddefaultHashAlgo("sha256"). Coexists with the existing(*Client).Fingerprintmethod (no conflict). This realizes the "code reuse" note.tpl/crypto/crypto.go— added(ns *Namespace) Fingerprint(ctx context.Context, args ...any) (string, error): optional algorithm first, then the value; unwraps aresource.ContentProviderviaContent(ctx)with acast.ToStringEstring fallback; delegates hashing tointegrity.Fingerprint.tpl/crypto/init.go— registered the method (no global alias; documented example).tpl/crypto/crypto_test.go— addedTestFingerprint(test-writer).
Test evidence (./bt-test ./tpl/crypto/... ./resources/resource_transformers/integrity/..., both packages PASS):
- New
TestFingerprintPASS — covers default sha256, explicit sha256/sha384/sha512/md5 (exact SRI values), and error paths (unsupported algorithm, no arguments). This test could not compile before the change (the method didn't exist), so it directly exercises the new behavior. - All pre-existing tests still pass:
TestMD5,TestSHA1,TestSHA256,TestHMAC, and integrity'sTestHashFromAlgo/TestTransform. - Reviewer confirmed correctness, reuse, consistency, and no scope creep.
Requirements checklist:
- Add
crypto.Fingerprintreturning an SRI hash from a string without creating a Resource — Implemented;TestFingerprintassertssha256-…=output from a plain string. - Signature
[ALGORITHM] any -> string(optional algorithm first, default sha256) — Implemented; tested with and without the algorithm arg. - Accept a Resource as the value (unwrap it) — Implemented via
resource.ContentProvider.Content(ctx)with string fallback; verified by reviewer against the interface (the string path is exercised by tests). - Reuse existing code — Implemented; the new
integrity.FingerprintreusesnewHash/integrity/defaultHashAlgo. - Title's
encoding.HexDecode/Encode— Skipped; it contradicts the detailed body (which specifies the fingerprint function) and has no signature or rationale. Flagging the discrepancy rather than guessing at an unrelated feature.
All changes are left uncommitted in the working tree.