feat: add support for CSP (#72)

This commit adds support for running with CSP. CSP can be enabled
on a per page basis. If this is done, fresh will set a default CSP that
is very restrictive. Users can modify the CSP with the `useCSP` hook.
Fresh will add its own script resources to the CSP automatically.
This commit is contained in:
Luca Casonato
2021-11-01 12:58:13 +01:00
committed by GitHub
parent 95289380f3
commit 44a0d490fe
7 changed files with 276 additions and 28 deletions
+3 -1
View File
@@ -1,5 +1,5 @@
/** @jsx h */
import { h, HandlerContext, Suspense, useData } from "../deps.ts";
import { h, HandlerContext, PageConfig, Suspense, useData } from "../deps.ts";
import { getDatabase, Todo } from "../utils/database.ts";
export default function TodoListPage() {
@@ -48,3 +48,5 @@ export const handler = {
return Response.redirect(ctx.req.url, 303);
},
};
export const config: PageConfig = { csp: true };
+1
View File
@@ -4,3 +4,4 @@ export * from "./src/runtime/suspense.ts";
export * from "./src/runtime/utils.ts";
export * from "./src/runtime/hooks.ts";
export * from "./src/runtime/head.ts";
export * from "./src/runtime/csp.ts";
+139
View File
@@ -0,0 +1,139 @@
import { createContext, useContext } from "./deps.ts";
export const SELF = "'self'";
export const UNSAFE_INLINE = "'unsafe-inline'";
export const UNSAFE_EVAL = "'unsafe-eval'";
export const UNSAFE_HASHES = "'unsafe-hashes'";
export const NONE = "'none'";
export const STRICT_DYNAMIC = "'strict-dynamic'";
export function nonce(val: string) {
return `'nonce-${val}'`;
}
export interface ContentSecurityPolicy {
directives: ContentSecurityPolicyDirectives;
reportOnly: boolean;
}
export interface ContentSecurityPolicyDirectives {
// Fetch directives
/**
* Defines the valid sources for web workers and nested browsing contexts
* loaded using elements such as <frame> and <iframe>.
*/
childSrc?: string[];
/**
* Restricts the URLs which can be loaded using script interfaces.
*/
connectSrc?: string[];
/**
* Serves as a fallback for the other fetch directives.
*/
defaultSrc?: string[];
/**
* Specifies valid sources for fonts loaded using @font-face.
*/
fontSrc?: string[];
/**
* Specifies valid sources for nested browsing contexts loading using elements
* such as <frame> and <iframe>.
*/
frameSrc?: string[];
/**
* Specifies valid sources of images and favicons.
*/
imgSrc?: string[];
/**
* Specifies valid sources of application manifest files.
*/
manifestSrc?: string[];
/**
* Specifies valid sources for loading media using the <audio> , <video> and
* <track> elements.
*/
mediaSrc?: string[];
/**
* Specifies valid sources for the <object>, <embed>, and <applet> elements.
*/
objectSrc?: string[];
/**
* Specifies valid sources to be prefetched or prerendered.
*/
prefetchSrc?: string[];
/**
* Specifies valid sources for JavaScript.
*/
scriptSrc?: string[];
/**
* Specifies valid sources for JavaScript <script> elements.
*/
scriptSrcElem?: string[];
/**
* Specifies valid sources for JavaScript inline event handlers.
*/
scriptSrcAttr?: string[];
/**
* Specifies valid sources for stylesheets.
*/
styleSrc?: string[];
/**
* Specifies valid sources for stylesheets <style> elements and <link>
* elements with rel="stylesheet".
*/
styleSrcElem?: string[];
/**
* Specifies valid sources for inline styles applied to individual DOM
* elements.
*/
styleSrcAttr?: string[];
/**
* Specifies valid sources for Worker, SharedWorker, or ServiceWorker scripts.
*/
workerSrc?: string[];
// Document directives
/**
* Restricts the URLs which can be used in a document's <base> element.
*/
baseUri?: string[];
/**
* Enables a sandbox for the requested resource similar to the <iframe>
* sandbox attribute.
*/
sandbox?: string[];
// Navigation directives
/**
* Restricts the URLs which can be used as the target of a form submissions
* from a given context.
*/
formAction?: string[];
/**
* Specifies valid parents that may embed a page using <frame>, <iframe>,
* <object>, <embed>, or <applet>.
*/
frameAncestors?: string[];
/**
* Restricts the URLs to which a document can initiate navigation by any
* means, including <form> (if form-action is not specified), <a>,
* window.location, window.open, etc.
*/
navigateTo?: string[];
/**
* The URI to report CSP violations to.
*/
reportUri?: string;
}
export const CSP_CONTEXT = createContext<ContentSecurityPolicy | undefined>(
undefined,
);
export function useCSP(mutator: (csp: ContentSecurityPolicy) => void) {
const csp = useContext(CSP_CONTEXT);
if (csp) {
mutator(csp);
}
}
+8
View File
@@ -40,4 +40,12 @@ export interface PageConfig {
* The route override must be a path-to-regexp compatible route matcher.
*/
routeOverride?: string;
/**
* If Content-Security-Policy should be enabled for this page. If 'true', a
* locked down policy will be used that allows only the scripts and styles
* that are generated by fresh. Additional scripts and styles can be added
* using `useCSP` hook.
*/
csp?: boolean;
}
+54 -8
View File
@@ -19,6 +19,11 @@ import {
RendererModule,
} from "./types.ts";
import { render as internalRender } from "./render.tsx";
import {
ContentSecurityPolicy,
ContentSecurityPolicyDirectives,
SELF,
} from "../runtime/csp.ts";
export class ServerContext {
#dev: boolean;
@@ -78,6 +83,7 @@ export class ServerContext {
component,
handler,
runtimeJS: Boolean(config?.runtimeJS ?? false),
csp: Boolean(config?.csp ?? false),
};
pages.push(page);
} else if (
@@ -149,7 +155,6 @@ export class ServerContext {
params: Record<string, string | string[]>,
) => {
if (page.component === undefined) return undefined;
// deno-lint-ignore require-await
const render = async () => {
const preloads = page.runtimeJS
? this.#bundler.getPreloads(bundlePath).map(bundleAssetUrl)
@@ -162,11 +167,45 @@ export class ServerContext {
url: new URL(req.url),
params,
});
const headers: Record<string, string> = {
"content-type": "text/html; charset=utf-8",
};
let firstChunk: string;
const iterator = body[Symbol.asyncIterator]();
try {
const { value, done } = await iterator.next();
if (done) throw new Error("Body is empty.");
firstChunk = value[0];
const csp: ContentSecurityPolicy | undefined = value[1];
if (csp) {
if (this.#dev) {
csp.directives.connectSrc = [
...(csp.directives.connectSrc ?? []),
SELF,
];
}
const directive = serializeCSPDirectives(csp.directives);
if (csp.reportOnly) {
headers["content-security-policy-report-only"] = directive;
} else {
headers["content-security-policy"] = directive;
}
}
} catch (err) {
console.error("Error rendering page", err);
return new Response("500 Internal Server Error", {
status: 500,
headers: {
"content-type": "text/plain",
},
});
}
const bodyStream = new ReadableStream<Uint8Array>({
async start(controller) {
controller.enqueue(new TextEncoder().encode(firstChunk));
try {
for await (const chunk of body) {
controller.enqueue(new TextEncoder().encode(chunk));
controller.enqueue(new TextEncoder().encode(chunk as string));
}
} catch (err) {
console.log("Rendering failed:\n", err);
@@ -177,12 +216,7 @@ export class ServerContext {
controller.close();
},
});
return new Response(bodyStream, {
status: 200,
headers: {
"content-type": "text/html; charset=utf-8",
},
});
return new Response(bodyStream, { status: 200, headers });
};
return render;
};
@@ -363,3 +397,15 @@ function sanitizePathToRegex(path: string): string {
.replaceAll("\)", "\\)")
.replaceAll("\:", "\\:");
}
function serializeCSPDirectives(csp: ContentSecurityPolicyDirectives): string {
return Object.entries(csp)
.filter(([_key, value]) => value !== undefined)
.map(([k, v]: [string, string | string[]]) => {
// Turn camel case into snake case.
const key = k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
const value = Array.isArray(v) ? v.join(" ") : v;
return `${key} ${value}`;
})
.join("; ");
}
+70 -19
View File
@@ -8,6 +8,8 @@ import { PageProps } from "../runtime/types.ts";
import { SUSPENSE_CONTEXT } from "../runtime/suspense.ts";
import { HEAD_CONTEXT } from "../runtime/head.ts";
import { REFRESH_JS_URL } from "./constants.ts";
import { CSP_CONTEXT, nonce, NONE, UNSAFE_INLINE } from "../runtime/csp.ts";
import { ContentSecurityPolicy } from "../runtime/csp.ts";
export interface RenderOptions {
page: Page;
@@ -102,20 +104,31 @@ const MAX_SUSPENSE_DEPTH = 10;
* sent to the client. On the client the HTML will be slotted into the DOM
* at the location of the original `<Suspense>` node.
*/
export async function* render(opts: RenderOptions): AsyncIterable<string> {
export async function* render(
opts: RenderOptions,
): AsyncIterable<string | [string, ContentSecurityPolicy | undefined]> {
const props = { params: opts.params, url: opts.url, route: opts.page.route };
const csp: ContentSecurityPolicy | undefined = opts.page.csp
? {
directives: { defaultSrc: [NONE], styleSrc: [UNSAFE_INLINE] },
reportOnly: false,
}
: undefined;
const dataCache = new Map();
const suspenseQueue: ComponentChildren[] = [];
const headComponents: ComponentChildren[] = [];
const vnode = h(HEAD_CONTEXT.Provider, {
value: headComponents,
children: h(DATA_CONTEXT.Provider, {
value: dataCache,
children: h(SUSPENSE_CONTEXT.Provider, {
value: suspenseQueue,
children: h(opts.page.component!, props),
const vnode = h(CSP_CONTEXT.Provider, {
value: csp,
children: h(HEAD_CONTEXT.Provider, {
value: headComponents,
children: h(DATA_CONTEXT.Provider, {
value: dataCache,
children: h(SUSPENSE_CONTEXT.Provider, {
value: suspenseQueue,
children: h(opts.page.component!, props),
}),
}),
}),
});
@@ -180,27 +193,63 @@ export async function* render(opts: RenderOptions): AsyncIterable<string> {
templateProps = undefined;
}
const imports = opts.imports.map((url) => {
const randomNonce = crypto.randomUUID().replace(/-/g, "");
if (csp) {
csp.directives.scriptSrc = [
...csp.directives.scriptSrc ?? [],
nonce(randomNonce),
];
}
return [url, randomNonce] as const;
});
const html = template({
bodyHtml,
headComponents,
imports: opts.imports,
imports,
preloads: opts.preloads,
styles: ctx.styles,
props: templateProps,
lang: ctx.lang,
});
let clientStyles = [...ctx.styles];
yield html;
const suspenseNonces = suspenseQueue.map(() => {
const randomNonce = crypto.randomUUID().replace(/-/g, "");
if (csp) {
csp.directives.scriptSrc = [
...csp.directives.scriptSrc ?? [],
nonce(randomNonce),
];
}
return randomNonce;
});
let suspenseScript = "";
if (suspenseQueue.length > 0) {
const randomNonce = crypto.randomUUID().replace(/-/g, "");
if (csp) {
csp.directives.scriptSrc = [
...csp.directives.scriptSrc ?? [],
nonce(randomNonce),
];
}
// minified client-side JS
yield '<script>(()=>{window.$SR=t=>{const e=document.getElementById("S:"+t),o=document.getElementById("E:"+t),d=document.getElementById("R:"+t);for(d.parentNode.removeChild(d);e.nextSibling!==o;)e.parentNode.removeChild(e.nextSibling);for(;d.firstChild;)e.parentNode.insertBefore(d.firstChild,o);e.parentNode.removeChild(e),o.parentNode.removeChild(o)};const n=document.getElementById("__FRSH_STYLE"),r=n.childNodes[0]?.textContent.split(`\n`);if(r!==void 0){n.removeChild(n.firstChild);for(const t of r)n.append(document.createTextNode(t))}window.$ST=t=>{for(const[e,o]of t)n.insertBefore(document.createTextNode(e),n.childNodes[o])}})();\n</script>';
suspenseScript = '<script nonce="' + randomNonce +
'">(()=>{window.$SR=t=>{const e=document.getElementById("S:"+t),o=document.getElementById("E:"+t),d=document.getElementById("R:"+t);for(d.parentNode.removeChild(d);e.nextSibling!==o;)e.parentNode.removeChild(e.nextSibling);for(;d.firstChild;)e.parentNode.insertBefore(d.firstChild,o);e.parentNode.removeChild(e),o.parentNode.removeChild(o)};const n=document.getElementById("__FRSH_STYLE"),r=n.childNodes[0]?.textContent.split(`\n`);if(r!==void 0){n.removeChild(n.firstChild);for(const t of r)n.append(document.createTextNode(t))}window.$ST=t=>{for(const[e,o]of t)n.insertBefore(document.createTextNode(e),n.childNodes[o])}})();\n</script>';
}
let clientStyles = [...ctx.styles];
yield [html + suspenseScript, csp];
// TODO(lucacasonato): parallelize this
for (const [id, children] of suspenseQueue.entries()) {
const fragment = await suspenseRender(opts.renderer, ctx, id + 1, children);
let [fragment, script] = await suspenseRender(
opts.renderer,
ctx,
id + 1,
children,
);
const cssInserts: [string, number][] = [];
for (const [i, style] of ctx.styles.entries()) {
@@ -211,10 +260,10 @@ export async function* render(opts: RenderOptions): AsyncIterable<string> {
clientStyles = [...ctx.styles];
if (cssInserts.length > 0) {
yield `<script>$ST(${JSON.stringify(cssInserts)});</script>`;
script = `$ST(${JSON.stringify(cssInserts)});\n${script};`;
}
yield fragment;
yield `${fragment}<script nonce="${suspenseNonces[id]}">${script}</script>`;
}
}
@@ -223,7 +272,7 @@ export async function suspenseRender(
ctx: RenderContext,
id: number,
children: ComponentChildren,
): Promise<string> {
): Promise<[string, string]> {
const dataCache = new Map();
const vnode = h(DATA_CONTEXT.Provider, {
@@ -267,13 +316,13 @@ export async function suspenseRender(
const html = await renderWithRenderer();
return `<div hidden id="R:${id}">${html}</div><script>$SR(${id})</script>`;
return [`<div hidden id="R:${id}">${html}</div>`, `$SR(${id});`];
}
export interface TemplateOptions {
bodyHtml: string;
headComponents: ComponentChildren[];
imports: string[];
imports: (readonly [string, string])[];
styles: string[];
preloads: string[];
props: unknown;
@@ -288,7 +337,9 @@ export function template(opts: TemplateOptions): string {
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
{opts.preloads.map((src) => <link rel="modulepreload" href={src} />)}
{opts.imports.map((src) => <script src={src} type="module"></script>)}
{opts.imports.map(([src, nonce]) => (
<script src={src} nonce={nonce} type="module"></script>
))}
<style
id="__FRSH_STYLE"
dangerouslySetInnerHTML={{ __html: opts.styles.join("\n") }}
+1
View File
@@ -28,6 +28,7 @@ export interface Page {
component?: ComponentType<PageProps>;
handler: Handler | Handlers;
runtimeJS: boolean;
csp: boolean;
}
export interface RendererModule {