asset integrity
This commit is contained in:
@@ -32,12 +32,14 @@ func NewTemplates() *Templates {
|
||||
type Page struct {
|
||||
Boxes []boxes.Box
|
||||
BuildNumber string
|
||||
Integrity *util.AssetIntegrity
|
||||
}
|
||||
|
||||
func newPage(boxes []boxes.Box) Page {
|
||||
return Page{
|
||||
Boxes: boxes,
|
||||
BuildNumber: util.GetBuildNumber(),
|
||||
Integrity: util.CalculateAssetIntegrities(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,6 +60,7 @@ func main() {
|
||||
e.GET("/health", func(c echo.Context) error {
|
||||
return c.Render(200, "health", Page{
|
||||
BuildNumber: util.GetBuildNumber(),
|
||||
Integrity: util.CalculateAssetIntegrities(),
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
@@ -11,3 +15,52 @@ func GetBuildNumber() string {
|
||||
func IsProd() bool {
|
||||
return len(GetBuildNumber()) > 0
|
||||
}
|
||||
|
||||
// CalculateFileIntegrity calculates SHA256 hash for SRI
|
||||
func CalculateFileIntegrity(filePath string) (string, error) {
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
hasher := sha256.New()
|
||||
if _, err := io.Copy(hasher, file); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
hash := hasher.Sum(nil)
|
||||
return fmt.Sprintf("sha256-%s", base64.StdEncoding.EncodeToString(hash)), nil
|
||||
}
|
||||
|
||||
// AssetIntegrity holds file integrity information
|
||||
type AssetIntegrity struct {
|
||||
CSS map[string]string
|
||||
JS map[string]string
|
||||
}
|
||||
|
||||
// CalculateAssetIntegrities calculates hashes for all assets
|
||||
func CalculateAssetIntegrities() *AssetIntegrity {
|
||||
integrity := &AssetIntegrity{
|
||||
CSS: make(map[string]string),
|
||||
JS: make(map[string]string),
|
||||
}
|
||||
|
||||
// CSS files
|
||||
cssFiles := []string{"main.css", "boxes.css"}
|
||||
for _, file := range cssFiles {
|
||||
if hash, err := CalculateFileIntegrity("css/" + file); err == nil {
|
||||
integrity.CSS[file] = hash
|
||||
}
|
||||
}
|
||||
|
||||
// JS files
|
||||
jsFiles := []string{"ws.js", "boxes.js", "draw.js"}
|
||||
for _, file := range jsFiles {
|
||||
if hash, err := CalculateFileIntegrity("js/" + file); err == nil {
|
||||
integrity.JS[file] = hash
|
||||
}
|
||||
}
|
||||
|
||||
return integrity
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user