2018-05-05 17:08:02 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/sha512"
|
|
|
|
"encoding/base64"
|
2021-09-26 12:49:18 +00:00
|
|
|
"sync"
|
2018-05-05 17:08:02 +00:00
|
|
|
"text/template"
|
2023-07-05 20:52:09 +00:00
|
|
|
|
|
|
|
"github.com/Masterminds/sprig/v3"
|
2018-05-05 17:08:02 +00:00
|
|
|
)
|
|
|
|
|
2021-09-26 12:49:18 +00:00
|
|
|
var (
|
|
|
|
sriCacheStore = newSRICache()
|
2023-07-05 20:52:09 +00:00
|
|
|
tplFuncs template.FuncMap
|
2021-09-26 12:49:18 +00:00
|
|
|
)
|
2018-05-05 17:08:02 +00:00
|
|
|
|
2023-07-05 20:52:09 +00:00
|
|
|
func init() {
|
|
|
|
tplFuncs = sprig.FuncMap()
|
|
|
|
tplFuncs["assetSRI"] = assetSRIHash
|
|
|
|
}
|
|
|
|
|
2018-05-05 17:08:02 +00:00
|
|
|
func assetSRIHash(assetName string) string {
|
2021-09-26 12:49:18 +00:00
|
|
|
if sri, ok := sriCacheStore.Get(assetName); ok {
|
|
|
|
return sri
|
|
|
|
}
|
|
|
|
|
2023-06-10 16:21:38 +00:00
|
|
|
data, err := assets.ReadFile(assetName)
|
2021-09-06 10:37:52 +00:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2018-05-05 17:08:02 +00:00
|
|
|
|
|
|
|
h := sha512.New384()
|
|
|
|
h.Write(data)
|
|
|
|
sum := h.Sum(nil)
|
|
|
|
|
2021-09-26 12:49:18 +00:00
|
|
|
sri := "sha384-" + base64.StdEncoding.EncodeToString(sum)
|
|
|
|
sriCacheStore.Set(assetName, sri)
|
|
|
|
return sri
|
|
|
|
}
|
|
|
|
|
|
|
|
type sriCache struct {
|
|
|
|
c map[string]string
|
|
|
|
l sync.RWMutex
|
|
|
|
}
|
|
|
|
|
|
|
|
func newSRICache() *sriCache { return &sriCache{c: map[string]string{}} }
|
|
|
|
|
|
|
|
func (s *sriCache) Get(assetName string) (string, bool) {
|
|
|
|
s.l.RLock()
|
|
|
|
defer s.l.RUnlock()
|
|
|
|
|
|
|
|
h, ok := s.c[assetName]
|
|
|
|
return h, ok
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *sriCache) Set(assetName, hash string) {
|
|
|
|
s.l.Lock()
|
|
|
|
defer s.l.Unlock()
|
|
|
|
|
|
|
|
s.c[assetName] = hash
|
2018-05-05 17:08:02 +00:00
|
|
|
}
|