a73x

internal/server/web/csp_test.go

Ref:   Size: 2.1 KiB   History

package web

import (
	"testing"
	"testing/fstest"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestScanInlineScriptsHashesOnlyInlineCode(t *testing.T) {
	fsys := fstest.MapFS{"index.html": &fstest.MapFile{Data: []byte(
		`<html><head><script src="/app.js"></script></head>` +
			`<body><script>console.log("hi")</script></body></html>`)}}
	got := scanInlineScripts(fsys, "index.html")
	// sha256 of `console.log("hi")`, base64 — verified with openssl, which is the
	// same computation a browser makes.
	require.Len(t, got, 1, "the src= script must not be hashed")
	assert.Equal(t, "sha256-TMFma7PHrBUjZEUKY/MwBLuX3/HrQe2+A1FmjMS7ppA=", got[0])
}

func TestScanInlineScriptsMissingIndexYieldsNone(t *testing.T) {
	assert.Empty(t, scanInlineScripts(fstest.MapFS{}, "index.html"))
}

// TestInlineScriptHashesCoversBuiltSPA guards the real embedded asset: if the
// console ships with an inline entry point, it must be hashed, or a strict
// script-src would blank the page.
func TestInlineScriptHashesCoversBuiltSPA(t *testing.T) {
	if !fileExists(dist, "dist/index.html") {
		t.Skip("UI not built")
	}
	assert.NotEmpty(t, InlineScriptHashes(), "built SPA has an inline entry point")
}

func TestScanInlineScriptsSkipsEmptyBlock(t *testing.T) {
	// An empty <script></script> hashes to the digest of nothing, which would be
	// a source token that permits an empty script and confuses the policy.
	fsys := fstest.MapFS{"index.html": &fstest.MapFile{
		Data: []byte(`<html><body><script></script></body></html>`)}}
	assert.Empty(t, scanInlineScripts(fsys, "index.html"))
}

func TestScanInlineScriptsHandlesAttributedScript(t *testing.T) {
	// SvelteKit writes a bare <script>, but a build that emits type="module"
	// must still be covered — a missed hash blanks the console.
	fsys := fstest.MapFS{"index.html": &fstest.MapFile{
		Data: []byte(`<html><body><script type="module">console.log("hi")</script></body></html>`)}}
	got := scanInlineScripts(fsys, "index.html")
	require.Len(t, got, 1)
	assert.Equal(t, "sha256-TMFma7PHrBUjZEUKY/MwBLuX3/HrQe2+A1FmjMS7ppA=", got[0])
}