Files
pages/internal/server/html_projection_csp.go
T
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

108 lines
3.3 KiB
Go

package server
import (
"crypto/rand"
"encoding/base64"
"html/template"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
)
var trustedScriptTagRE = regexp.MustCompile(`(?i)<script([\s>])`)
// Only application-owned template files are processed here, before any request
// data or authored HTML exists. Never add nonces by rewriting rendered HTML.
func parseTrustedTemplates(t *template.Template) (*template.Template, error) {
paths, err := filepath.Glob("templates/**/*.gohtml")
if err != nil {
return nil, err
}
for _, path := range paths {
body, err := os.ReadFile(path)
if err != nil {
return nil, err
}
body = trustedScriptTagRE.ReplaceAll(body, []byte(`<script nonce="{{ cspNonce }}"$1`))
if _, err = t.New(filepath.Base(path)).Parse(string(body)); err != nil {
return nil, err
}
}
return t, nil
}
func safeProjectionTemplate(name string) bool {
switch name {
case "periodical.gohtml", "public_periodical.gohtml", "periodical_new.gohtml":
return true
case "city_map.gohtml", "public_tree.gohtml", "anonymous_view.gohtml", "page.gohtml", "home.gohtml", "search_home.gohtml", "object_view.gohtml", "revision_view.gohtml", "preview.gohtml", "print.gohtml", "profile.gohtml", "editor.gohtml", "object_editor.gohtml":
return true
}
return false
}
func externalResourceCSPSources(policy externalResourcePolicy) (scriptHashes, styleOrigins, imageOrigins []string) {
styles := map[string]bool{}
images := map[string]bool{}
hashes := map[string]bool{}
for _, item := range policy.items {
u, err := url.Parse(item.URL)
if err != nil || u.Scheme != "https" || u.Host == "" {
continue
}
origin := "https://" + u.Host
switch item.Kind {
case "script":
hashes["'"+item.Integrity+"'"] = true
case "stylesheet":
styles[origin] = true
case "image":
images[origin] = true
}
}
for value := range hashes {
scriptHashes = append(scriptHashes, value)
}
for value := range styles {
styleOrigins = append(styleOrigins, value)
}
for value := range images {
imageOrigins = append(imageOrigins, value)
}
sort.Strings(scriptHashes)
sort.Strings(styleOrigins)
sort.Strings(imageOrigins)
return
}
func setProjectionCSP(w http.ResponseWriter, policy externalResourcePolicy) (string, error) {
var token [24]byte
if _, err := rand.Read(token[:]); err != nil {
return "", err
}
nonce := base64.RawStdEncoding.EncodeToString(token[:])
scriptHashes, styleOrigins, imageOrigins := externalResourceCSPSources(policy)
csp := "default-src 'self'; script-src 'nonce-" + nonce + "' 'strict-dynamic'"
if len(scriptHashes) > 0 {
csp += " " + strings.Join(scriptHashes, " ")
}
csp += "; script-src-attr 'none'; object-src 'none'; base-uri 'none'; frame-ancestors 'self'; frame-src 'self'; form-action 'self'; style-src 'self' 'unsafe-inline'"
if len(styleOrigins) > 0 {
csp += " " + strings.Join(styleOrigins, " ")
}
csp += "; img-src 'self' data: blob:"
if len(imageOrigins) > 0 {
csp += " " + strings.Join(imageOrigins, " ")
}
csp += "; media-src 'self' blob:; font-src 'self'; connect-src 'self'; worker-src 'self' blob:"
w.Header().Set("Content-Security-Policy", csp)
w.Header().Set("Referrer-Policy", "no-referrer")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-PagesWiki-HTML-Policy", htmlProjectionVersion)
return nonce, nil
}