Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
chore: generate csp inline script hashes on build (#17767)
p0ny74f2e70019e9
diff --git a/backend/server/echo_routes.go b/backend/server/echo_routes.goindex ce408d063a..6c60b76e23 100644--- a/backend/server/echo_routes.go+++ b/backend/server/echo_routes.go@@ -3,6 +3,7 @@ package serverimport ("log/slog""net/http"+ "strings""github.com/labstack/echo-contrib/prometheus""github.com/labstack/echo/v4"@@ -96,6 +97,26 @@ func recoverMiddleware(next echo.HandlerFunc) echo.HandlerFunc {}func securityHeadersMiddleware(next echo.HandlerFunc) echo.HandlerFunc {+ // Content Security Policy+ // Note: style-src allows 'unsafe-inline' temporarily due to inline styles in Vue components+ // TODO: Migrate inline styles to CSS classes and remove 'unsafe-inline'+ // Note: script-src uses SHA-256 hashes for @vitejs/plugin-legacy inline scripts+ // Hashes are loaded from dist/csp-hashes.json (generated by frontend build)+ // Note: script-src allows 'wasm-unsafe-eval' for Monaco Editor WebAssembly modules+ // Monaco's TextMate service embeds WASM that requires runtime compilation+ // Note: connect-src allows 'data:' for Monaco Editor language definitions+ scriptHashes := loadCSPHashes()+ csp := "default-src 'self'; " ++ "script-src 'self' " + strings.Join(scriptHashes, " ") + " 'wasm-unsafe-eval'; " ++ "style-src 'self' 'unsafe-inline'; " ++ "img-src 'self' data: blob:; " ++ "connect-src 'self' data: ws: wss:; " ++ "font-src 'self'; " ++ "object-src 'none'; " ++ "base-uri 'self'; " ++ "form-action 'self'; " ++ "frame-ancestors 'self'"+return func(c echo.Context) error {// Allow popups to maintain window.opener for OAuth flowsc.Response().Header().Set("Cross-Origin-Opener-Policy", "same-origin-allow-popups")@@ -108,22 +129,6 @@ func securityHeadersMiddleware(next echo.HandlerFunc) echo.HandlerFunc {// max-age=31536000 (1 year), includeSubDomains for all subdomainsc.Response().Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")}- // Content Security Policy- // Note: style-src allows 'unsafe-inline' temporarily due to inline styles in Vue components- // TODO: Migrate inline styles to CSS classes and remove 'unsafe-inline'- // Note: script-src allows 'unsafe-inline' for Vite legacy plugin feature detection- // Note: script-src allows 'wasm-unsafe-eval' for Monaco Editor WebAssembly modules- // Note: connect-src allows 'data:' for Monaco Editor language definitions- csp := "default-src 'self'; " +- "script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; " +- "style-src 'self' 'unsafe-inline'; " +- "img-src 'self' data: blob:; " +- "connect-src 'self' data: ws: wss:; " +- "font-src 'self'; " +- "object-src 'none'; " +- "base-uri 'self'; " +- "form-action 'self'; " +- "frame-ancestors 'self'"c.Response().Header().Set("Content-Security-Policy", csp)return next(c)}diff --git a/backend/server/server_frontend_embed.go b/backend/server/server_frontend_embed.goindex 3a2f59d665..fdfe6d29fd 100644--- a/backend/server/server_frontend_embed.go+++ b/backend/server/server_frontend_embed.go@@ -4,8 +4,11 @@ package serverimport ("embed"+ "encoding/json""io/fs"+ "log/slog""net/http"+ "sync""github.com/labstack/echo/v4""github.com/labstack/echo/v4/middleware"@@ -17,6 +20,51 @@ import (//go:embed distvar embeddedFiles embed.FS+var (+ cspHashesCache []string+ cspHashesOnce sync.Once+)++// loadCSPHashes loads CSP hashes from the embedded frontend build output.+// Uses sync.Once to ensure hashes are loaded only once.+func loadCSPHashes() []string {+ cspHashesOnce.Do(func() {+ hashFilePath := "dist/csp-hashes.json"+ data, err := embeddedFiles.ReadFile(hashFilePath)+ if err != nil {+ slog.Error("Failed to read CSP hashes from embedded assets",+ "path", hashFilePath,+ "error", err)+ panic("CSP hashes file not found in embedded build - this is a build error")+ }++ var hashes struct {+ ScriptHashes []string `json:"scriptHashes"`+ GeneratedAt string `json:"generatedAt"`+ PluginVersion string `json:"pluginVersion"`+ }+ if err := json.Unmarshal(data, &hashes); err != nil {+ slog.Error("Failed to unmarshal CSP hashes",+ "path", hashFilePath,+ "error", err)+ panic("Invalid CSP hashes file format - this is a build error")+ }++ if len(hashes.ScriptHashes) == 0 {+ slog.Error("CSP hashes file contains no hashes", "path", hashFilePath)+ panic("Empty CSP hashes - this is a build error")+ }++ cspHashesCache = hashes.ScriptHashes+ slog.Info("Loaded CSP hashes from embedded frontend build",+ "path", hashFilePath,+ "plugin_version", hashes.PluginVersion,+ "hash_count", len(hashes.ScriptHashes))+ })++ return cspHashesCache+}+func getFileSystem(path string) http.FileSystem {fs, err := fs.Sub(embeddedFiles, path)if err != nil {diff --git a/backend/server/server_frontend_not_embed.go b/backend/server/server_frontend_not_embed.goindex 0d8c9b59e7..18be0ca799 100644--- a/backend/server/server_frontend_not_embed.go+++ b/backend/server/server_frontend_not_embed.go@@ -9,6 +9,11 @@ import ("github.com/labstack/echo/v4")+// loadCSPHashes returns empty hashes in dev mode since frontend is served separately.+func loadCSPHashes() []string {+ return []string{}+}+func embedFrontend(e *echo.Echo) {slog.Info("Skip embedding frontend, build with 'embed_frontend' tag if you want embedded frontend.")diff --git a/frontend/package.json b/frontend/package.jsonindex 66a0647064..1f74ff53ff 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -112,7 +112,7 @@"@types/slug": "5.0.9","@types/splitpanes": "2.2.6","@types/uuid": "11.0.0",- "@vitejs/plugin-legacy": "^7.0.0",+ "@vitejs/plugin-legacy": "~7.2.1","@vitejs/plugin-vue": "6.0.1","@vitejs/plugin-vue-jsx": "5.1.1","@vue/compiler-sfc": "3.5.22",diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 3630b144d5..06bb98a065 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -294,7 +294,7 @@ importers:specifier: 11.0.0version: 11.0.0'@vitejs/plugin-legacy':- specifier: ^7.0.0+ specifier: ~7.2.1version: 7.2.1([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected]))'@vitejs/plugin-vue':specifier: 6.0.1diff --git a/frontend/tsconfig.node.json b/frontend/tsconfig.node.jsonindex c0fcb23752..6476de0cf4 100644--- a/frontend/tsconfig.node.json+++ b/frontend/tsconfig.node.json@@ -1,6 +1,6 @@{"extends": "@tsconfig/node22/tsconfig.json",- "include": ["vite.config.*", "vitest.config.*"],+ "include": ["vite.config.*", "vitest.config.*", "vite-plugin-*.ts"],"compilerOptions": {"composite": true,"noEmit": true,diff --git a/frontend/vite-plugin-export-csp-hashes.ts b/frontend/vite-plugin-export-csp-hashes.tsnew file mode 100644index 0000000000..2238187308--- /dev/null+++ b/frontend/vite-plugin-export-csp-hashes.ts@@ -0,0 +1,183 @@+import { createHash } from "crypto";+import { writeFileSync, readFileSync, readdirSync, statSync } from "fs";+import { resolve, dirname, join } from "path";+import { fileURLToPath } from "url";+import type { Plugin } from "vite";++const __filename = fileURLToPath(import.meta.url);+const __dirname = dirname(__filename);++/**+ * Extract inline script content from HTML+ */+function extractInlineScripts(html: string): string[] {+ const scripts: string[] = [];+ // Match <script>...</script> but NOT <script src="...">+ // This regex matches script tags without src attribute+ const scriptRegex = /<script(?![^>]*\ssrc=)([^>]*)>([\s\S]*?)<\/script>/gi;++ let match;+ while ((match = scriptRegex.exec(html)) !== null) {+ const scriptContent = match[2].trim();+ if (scriptContent) {+ scripts.push(scriptContent);+ }+ }++ return scripts;+}++/**+ * Recursively find all HTML files in a directory+ */+function findHtmlFiles(dir: string): string[] {+ const files: string[] = [];++ try {+ const entries = readdirSync(dir);++ for (const entry of entries) {+ const fullPath = join(dir, entry);+ const stat = statSync(fullPath);++ if (stat.isDirectory()) {+ files.push(...findHtmlFiles(fullPath));+ } else if (entry.endsWith(".html")) {+ files.push(fullPath);+ }+ }+ } catch (error) {+ // Ignore errors (e.g., permission denied)+ }++ return files;+}++/**+ * Compute SHA-256 hash of a string+ */+function computeSha256(content: string): string {+ return createHash("sha256").update(content).digest("base64");+}++/**+ * Vite plugin to export CSP hashes from @vitejs/plugin-legacy and inline scripts+ *+ * This plugin runs after the build and:+ * 1. Collects CSP hashes from @vitejs/plugin-legacy+ * 2. Scans built HTML files for inline scripts+ * 3. Generates SHA-256 hashes for all inline scripts+ * 4. Exports everything to a JSON file that the backend reads+ */+export function exportCspHashes(): Plugin {+ let outDir = "";++ return {+ name: "export-csp-hashes",+ apply: "build",+ enforce: "post", // Run after other plugins including @vitejs/plugin-legacy++ configResolved(config) {+ outDir = config.build.outDir;+ },++ async closeBundle() {+ try {+ const allHashes = new Set<string>();+ const inlineScriptSources: Array<{+ file: string;+ content: string;+ hash: string;+ }> = [];++ // 1. Get CSP hashes from @vitejs/plugin-legacy+ try {+ const legacyPlugin = await import("@vitejs/plugin-legacy");+ const cspHashes = legacyPlugin.cspHashes;++ if (cspHashes && cspHashes.length > 0) {+ cspHashes.forEach((hash: string) => {+ allHashes.add(`'sha256-${hash}'`);+ });+ console.log(+ `✓ Loaded ${cspHashes.length} hashes from @vitejs/plugin-legacy`+ );+ }+ } catch (error) {+ console.warn(+ "⚠️ Could not load hashes from @vitejs/plugin-legacy:",+ error+ );+ }++ // 2. Scan built HTML files for inline scripts+ const htmlFiles = findHtmlFiles(outDir);+ console.log(+ `✓ Scanning ${htmlFiles.length} HTML files for inline scripts...`+ );++ for (const htmlFile of htmlFiles) {+ const html = readFileSync(htmlFile, "utf-8");+ const inlineScripts = extractInlineScripts(html);++ for (const scriptContent of inlineScripts) {+ const hash = computeSha256(scriptContent);+ const cspHash = `'sha256-${hash}'`;++ allHashes.add(cspHash);+ inlineScriptSources.push({+ file: htmlFile.replace(outDir, "").replace(/\\/g, "/"),+ content:+ scriptContent.length > 60+ ? scriptContent.substring(0, 60) + "..."+ : scriptContent,+ hash: cspHash,+ });+ }+ }++ // Get plugin version+ let pluginVersion = "unknown";+ try {+ const pkgPath = resolve(+ __dirname,+ "node_modules/@vitejs/plugin-legacy/package.json"+ );+ const pkgData = readFileSync(pkgPath, "utf-8");+ const pkg = JSON.parse(pkgData);+ pluginVersion = pkg.version;+ } catch {+ pluginVersion = "unknown";+ }++ // Prepare the output+ const output = {+ scriptHashes: Array.from(allHashes),+ generatedAt: new Date().toISOString(),+ pluginVersion,+ sources: inlineScriptSources,+ };++ // Write to backend server directory+ const outputPath = join(outDir, "csp-hashes.json");+ writeFileSync(outputPath, JSON.stringify(output, null, 2));++ console.log("✓ CSP hashes exported to:", outputPath);+ console.log(` Total script hashes: ${output.scriptHashes.length}`);+ console.log(` Inline scripts found: ${inlineScriptSources.length}`);++ if (inlineScriptSources.length > 0) {+ console.log("\n Inline script sources:");+ inlineScriptSources.forEach((src, i) => {+ console.log(` ${i + 1}. ${src.file}`);+ console.log(` Content: ${src.content}`);+ console.log(` Hash: ${src.hash}`);+ });+ }+ } catch (error) {+ console.error("❌ Failed to export CSP hashes:", error);+ // Don't fail the build, just warn+ }+ },+ };+}diff --git a/frontend/vite.config.ts b/frontend/vite.config.tsindex f9f7acb2b6..682fcd50c0 100644--- a/frontend/vite.config.ts+++ b/frontend/vite.config.ts@@ -11,6 +11,7 @@ import IconsResolver from "unplugin-icons/resolver";import Icons from "unplugin-icons/vite";import Components from "unplugin-vue-components/vite";import { defineConfig } from "vite";+import { exportCspHashes } from "./vite-plugin-export-csp-hashes";const SERVER_PORT = parseInt(process.env.PORT ?? "3000", 10) ?? 3000;const LOCAL_ENDPOINT = "http://localhost:8080";@@ -49,6 +50,8 @@ export default defineConfig({CodeInspectorPlugin({bundler: "vite",}),+ // Export CSP hashes from @vitejs/plugin-legacy for backend to use+ exportCspHashes(),],build: {chunkSizeWarningLimit: 1000,