github.com/neohugo/neohugo@v0.123.8/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  	"fmt"
    23  	"hash"
    24  	"io"
    25  
    26  	"github.com/neohugo/neohugo/common/constants"
    27  	"github.com/neohugo/neohugo/resources/internal"
    28  
    29  	"github.com/neohugo/neohugo/resources"
    30  	"github.com/neohugo/neohugo/resources/resource"
    31  )
    32  
    33  const defaultHashAlgo = "sha256"
    34  
    35  // Client contains methods to fingerprint (cachebusting) and other integrity-related
    36  // methods.
    37  type Client struct {
    38  	rs *resources.Spec
    39  }
    40  
    41  // New creates a new Client with the given specification.
    42  func New(rs *resources.Spec) *Client {
    43  	return &Client{rs: rs}
    44  }
    45  
    46  type fingerprintTransformation struct {
    47  	algo string
    48  }
    49  
    50  func (t *fingerprintTransformation) Key() internal.ResourceTransformationKey {
    51  	return internal.NewResourceTransformationKey(constants.ResourceTransformationFingerprint, t.algo)
    52  }
    53  
    54  // Transform creates a MD5 hash of the Resource content and inserts that hash before
    55  // the extension in the filename.
    56  func (t *fingerprintTransformation) Transform(ctx *resources.ResourceTransformationCtx) error {
    57  	h, err := newHash(t.algo)
    58  	if err != nil {
    59  		return err
    60  	}
    61  
    62  	var w io.Writer
    63  	if rc, ok := ctx.From.(io.ReadSeeker); ok {
    64  		// This transformation does not change the content, so try to
    65  		// avoid writing to To if we can.
    66  		// TODO may check
    67  		//nolint
    68  		defer rc.Seek(0, 0)
    69  		w = h
    70  	} else {
    71  		w = io.MultiWriter(h, ctx.To)
    72  	}
    73  
    74  	if _, err := io.Copy(w, ctx.From); err != nil {
    75  		return err
    76  	}
    77  	d, err := digest(h)
    78  	if err != nil {
    79  		return err
    80  	}
    81  
    82  	ctx.Data["Integrity"] = integrity(t.algo, d)
    83  	ctx.AddOutPathIdentifier("." + hex.EncodeToString(d[:]))
    84  	return nil
    85  }
    86  
    87  func newHash(algo string) (hash.Hash, error) {
    88  	switch algo {
    89  	case "md5":
    90  		return md5.New(), nil
    91  	case "sha256":
    92  		return sha256.New(), nil
    93  	case "sha384":
    94  		return sha512.New384(), nil
    95  	case "sha512":
    96  		return sha512.New(), nil
    97  	default:
    98  		return nil, fmt.Errorf("unsupported hash algorithm: %q, use either md5, sha256, sha384 or sha512", algo)
    99  	}
   100  }
   101  
   102  // Fingerprint applies fingerprinting of the given resource and hash algorithm.
   103  // It defaults to sha256 if none given, and the options are md5, sha256 or sha512.
   104  // The same algo is used for both the fingerprinting part (aka cache busting) and
   105  // the base64-encoded Subresource Integrity hash, so you will have to stay away from
   106  // md5 if you plan to use both.
   107  // See https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity
   108  func (c *Client) Fingerprint(res resources.ResourceTransformer, algo string) (resource.Resource, error) {
   109  	if algo == "" {
   110  		algo = defaultHashAlgo
   111  	}
   112  
   113  	return res.Transform(&fingerprintTransformation{algo: algo})
   114  }
   115  
   116  func integrity(algo string, sum []byte) string {
   117  	encoded := base64.StdEncoding.EncodeToString(sum)
   118  	return algo + "-" + encoded
   119  }
   120  
   121  func digest(h hash.Hash) ([]byte, error) {
   122  	sum := h.Sum(nil)
   123  	return sum, nil
   124  }