github.com/kovansky/hugo@v0.92.3-0.20220224232819-63076e4ff19f/resources/resource_transformers/integrity/integrity.go (about)

     1  // Copyright 2018 The Hugo Authors. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  // http://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software
     9  // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package integrity
    15  
    16  import (
    17  	"crypto/md5"
    18  	"crypto/sha256"
    19  	"crypto/sha512"
    20  	"encoding/base64"
    21  	"encoding/hex"
    22  	"hash"
    23  	"html/template"
    24  	"io"
    25  
    26  	"github.com/gohugoio/hugo/resources/internal"
    27  
    28  	"github.com/pkg/errors"
    29  
    30  	"github.com/gohugoio/hugo/resources"
    31  	"github.com/gohugoio/hugo/resources/resource"
    32  )
    33  
    34  const defaultHashAlgo = "sha256"
    35  
    36  // Client contains methods to fingerprint (cachebusting) and other integrity-related
    37  // methods.
    38  type Client struct {
    39  	rs *resources.Spec
    40  }
    41  
    42  // New creates a new Client with the given specification.
    43  func New(rs *resources.Spec) *Client {
    44  	return &Client{rs: rs}
    45  }
    46  
    47  type fingerprintTransformation struct {
    48  	algo string
    49  }
    50  
    51  func (t *fingerprintTransformation) Key() internal.ResourceTransformationKey {
    52  	return internal.NewResourceTransformationKey("fingerprint", t.algo)
    53  }
    54  
    55  // Transform creates a MD5 hash of the Resource content and inserts that hash before
    56  // the extension in the filename.
    57  func (t *fingerprintTransformation) Transform(ctx *resources.ResourceTransformationCtx) error {
    58  	h, err := newHash(t.algo)
    59  	if err != nil {
    60  		return err
    61  	}
    62  
    63  	var w io.Writer
    64  	if rc, ok := ctx.From.(io.ReadSeeker); ok {
    65  		// This transformation does not change the content, so try to
    66  		// avoid writing to To if we can.
    67  		defer rc.Seek(0, 0)
    68  		w = h
    69  	} else {
    70  		w = io.MultiWriter(h, ctx.To)
    71  	}
    72  
    73  	io.Copy(w, ctx.From)
    74  	d, err := digest(h)
    75  	if err != nil {
    76  		return err
    77  	}
    78  
    79  	ctx.Data["Integrity"] = integrity(t.algo, d)
    80  	ctx.AddOutPathIdentifier("." + hex.EncodeToString(d[:]))
    81  	return nil
    82  }
    83  
    84  func newHash(algo string) (hash.Hash, error) {
    85  	switch algo {
    86  	case "md5":
    87  		return md5.New(), nil
    88  	case "sha256":
    89  		return sha256.New(), nil
    90  	case "sha384":
    91  		return sha512.New384(), nil
    92  	case "sha512":
    93  		return sha512.New(), nil
    94  	default:
    95  		return nil, errors.Errorf("unsupported crypto algo: %q, use either md5, sha256, sha384 or sha512", algo)
    96  	}
    97  }
    98  
    99  // Fingerprint applies fingerprinting of the given resource and hash algorithm.
   100  // It defaults to sha256 if none given, and the options are md5, sha256 or sha512.
   101  // The same algo is used for both the fingerprinting part (aka cache busting) and
   102  // the base64-encoded Subresource Integrity hash, so you will have to stay away from
   103  // md5 if you plan to use both.
   104  // See https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity
   105  func (c *Client) Fingerprint(res resources.ResourceTransformer, algo string) (resource.Resource, error) {
   106  	if algo == "" {
   107  		algo = defaultHashAlgo
   108  	}
   109  
   110  	return res.Transform(&fingerprintTransformation{algo: algo})
   111  }
   112  
   113  func integrity(algo string, sum []byte) template.HTMLAttr {
   114  	encoded := base64.StdEncoding.EncodeToString(sum)
   115  	return template.HTMLAttr(algo + "-" + encoded)
   116  }
   117  
   118  func digest(h hash.Hash) ([]byte, error) {
   119  	sum := h.Sum(nil)
   120  	return sum, nil
   121  }