Skip to content

Commit

Permalink
Merge branch 'csp-trusted-types' into 'main'
Browse files Browse the repository at this point in the history
Add CSP trusted types

See merge request reportcreator/reportcreator!716
  • Loading branch information
MWedl committed Sep 24, 2024
2 parents 2722bd3 + ddaec26 commit 8c591c1
Show file tree
Hide file tree
Showing 10 changed files with 143 additions and 33 deletions.
12 changes: 7 additions & 5 deletions api/poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion api/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ djangorestframework = "~3.15.0"
weasyprint = "~62.3"

django-phonenumber-field = { version = "^8.0.0", extras = ["phonenumberslite"] }
django-csp = "^3.7"
django-csp = "^4.0b2"
django-storages = "^1.13.2"
drf-nested-routers = "^0.94.1"
django-filter = "^24.1"
Expand Down
47 changes: 30 additions & 17 deletions api/src/reportcreator_api/conf/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import fido2.features
import redis
from csp.constants import NONE, SELF, UNSAFE_INLINE
from decouple import Csv, config
from kombu import Queue

Expand Down Expand Up @@ -407,22 +408,34 @@
SECURE_REFERRER_POLICY = 'same-origin'
X_FRAME_OPTIONS = 'SAMEORIGIN'

CSP_DEFAULT_SRC = ["'none'"]
CSP_IMG_SRC = ["'self'", "data:"]
CSP_FONT_SRC = ["'self'"]
CSP_WORKER_SRC = ["'self'"]
CSP_CONNECT_SRC = ["'self'", "data:"]
CSP_FRAME_SRC = ["'self'"]
CSP_FRAME_ANCESTORS = ["'self'"]
CSP_FORM_ACTION = ["'self'"]
# nuxt, vuetify and markdown preview use inline styles
CSP_STYLE_SRC = ["'self'", "'unsafe-inline'"]
# unsafe-inline:

CSP_SCRIPT_SRC = [
"'self'",
"'sha256-vfPLwqW0BNyGGLG6upxgxsXF+K7Jp/V2hJGlbPt7NJY='", # hash of nuxt inline script injected in index.html
]
CONTENT_SECURITY_POLICY = {
'DIRECTIVES': {
'default-src': [NONE],
'img-src': [SELF, 'data:'],
'font-src': [SELF],
'worker-src': [SELF],
'connect-src': [SELF, 'data:'],
'frame-src': [SELF],
'frame-ancestors': [SELF],
'form-action': [SELF],
# nuxt, vuetify and markdown preview use inline styles
'style-src': [SELF, UNSAFE_INLINE],
# hash of nuxt inline script injected in index.html
'script-src': [SELF, "'sha256-vfPLwqW0BNyGGLG6upxgxsXF+K7Jp/V2hJGlbPt7NJY='"],
'require-trusted-types-for': ["'script'"],
'trusted-types': [
'default', # required for vuetify, unhead, mermaid
'worker-url', # load web workers via import URL
'vue', # used by vue and markdown
'dompurify', # used by mermaid
"'allow-duplicates'", # dompurify is used twice as dependency
# monaco-editor policies
'defaultWorkerFactory', 'tokenizeToString', 'standaloneColorizer',
'editorViewLayer', 'domLineBreaksComputer', 'domLineBreaksComputer',
'diffEditorWidget', 'editorGhostText', 'diffReview', 'stickyScrollViewLayer',
],
},
}

PERMISSIONS_POLICY = {
'publickey-credentials-get': '(self)',
Expand Down Expand Up @@ -689,7 +702,7 @@ def __bool__(self):
'serviceVersion': 'dev',
}
if ELASTIC_APM_RUM_ENABLED:
CSP_CONNECT_SRC.append(ELASTIC_APM_RUM_CONFIG['serverUrl'])
CONTENT_SECURITY_POLICY['DIRECTIVES']['connect-src'].append(ELASTIC_APM_RUM_CONFIG['serverUrl'])


if DEBUG:
Expand Down
50 changes: 50 additions & 0 deletions frontend/NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -7638,6 +7638,31 @@ MIT
SOFTWARE


@types/dompurify 3.0.5
MIT
MIT License

Copyright (c) Microsoft Corporation.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE


@types/estree 1.0.5
MIT
MIT License
Expand Down Expand Up @@ -7938,6 +7963,31 @@ MIT
SOFTWARE


@types/trusted-types 2.0.7
MIT
MIT License

Copyright (c) Microsoft Corporation.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE


@types/unist 2.0.11
MIT
MIT License
Expand Down
23 changes: 22 additions & 1 deletion frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@
"zxcvbn": "^4.4.2",
"@github/webauthn-json": "^2.1.1",
"@elastic/apm-rum-vue": "^2.1.5",
"date-fns": "^4.1.0"
"date-fns": "^4.1.0",
"dompurify": "^3.1.6"
},
"devDependencies": {
"@nuxt/eslint": "^0.5.5",
Expand All @@ -46,6 +47,7 @@
"@types/zxcvbn": "^4.4.2",
"@types/lodash-es": "^4.17.0",
"@types/uuid": "^10.0.0",
"@types/dompurify": "^3.0.5",
"sass": "^1.69.3",
"eslint": "^9.0.0",
"license-checker-rseidelsohn": "^4.2.8",
Expand Down
15 changes: 8 additions & 7 deletions frontend/src/components/Design/CodeEditor.vue
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,20 @@

<script lang="ts">
import * as monaco from 'monaco-editor';
import cssWorkerUrl from 'monaco-editor/esm/vs/language/css/css.worker?worker&url';
import htmlWorkerUrl from 'monaco-editor/esm/vs/language/html/html.worker?worker&url';
import editorWorkerUrl from 'monaco-editor/esm/vs/editor/editor.worker?worker&url';
self.MonacoEnvironment = {
async getWorker(_: any, label: string) {
let worker: typeof import('*?worker');
getWorkerUrl(_: string, label: string) {
if (label === 'css') {
worker = await import('monaco-editor/esm/vs/language/css/css.worker?worker');
return cssWorkerUrl;
} else if (label === 'html') {
worker = await import('monaco-editor/esm/vs/language/html/html.worker?worker');
return htmlWorkerUrl;
} else {
worker = await import('monaco-editor/esm/vs/editor/editor.worker?worker');
return editorWorkerUrl;
}
return new worker.default();
}
},
};
monaco.languages.html.htmlDefaults.setOptions({
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/components/DynamicInputField.vue
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,7 @@ import Draggable from 'vuedraggable';
import { pick, uniq } from 'lodash-es';
import regexWorkerUrl from '~/workers/regexWorker?worker&url';
import { collabSubpath, type MarkdownEditorMode, FieldDataType, type MarkdownProps, type FieldDefinition, type UserShortInfo } from '#imports';
import { workerUrlPolicy } from '~/plugins/trustedtypes';
defineOptions({
inheritAttrs: false,
Expand Down Expand Up @@ -436,7 +437,7 @@ async function validateRegexPattern(value: string) {
const pattern = new RegExp(props.definition.pattern);
if (!regexWorker.value) {
regexWorker.value = new Worker(regexWorkerUrl, { type: 'module' });
regexWorker.value = new Worker(workerUrlPolicy.createScriptURL!(regexWorkerUrl) as string, { type: 'module' });
}
const threadedRegexMatch = new Promise((resolve) => {
Expand Down
1 change: 1 addition & 0 deletions frontend/src/components/Markdown/Preview.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<template>
<div>
<!-- Rendered markdown gets sanitized in renderMarkdownToHtml -->
<!-- eslint-disable-next-line vue/no-v-html -->
<div ref="previewRef" v-html="renderedMarkdown" @click.stop class="preview" />
<markdown-image-preview-dialog v-model="previewImageSrc" :images="previewImagesAll" />
Expand Down
19 changes: 19 additions & 0 deletions frontend/src/plugins/trustedtypes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import DOMPurify from 'dompurify';

export const trustedTypes = window.trustedTypes || {
createPolicy: (_name: string, options: TrustedTypePolicyOptions) => options,
};


export const workerUrlPolicy = trustedTypes.createPolicy('worker-url', {
createScriptURL: (url: string) => url,
});


export const defaultPolicy = trustedTypes.createPolicy('default', {
createHTML: (html: string) => DOMPurify.sanitize(html, { RETURN_TRUSTED_TYPE: false }),
createScript: () => { throw new Error('Script execution is disabled'); },
});


export default defineNuxtPlugin(() => {});

0 comments on commit 8c591c1

Please sign in to comment.