server icon indicating copy to clipboard operation
server copied to clipboard

[Bug]: Content Security Policy (CSP) Error for preview-service-worker.js in files_sharing

Open tinus-github opened this issue 1 year ago • 10 comments

⚠️ This issue respects the following points: ⚠️

Bug description

Bug #39849 is about a problem where the Content-security-policy header does not include permission to load the right worker scripts.

In the activity your can see that the problem happens in configurations that do not include often-used addins like the Talk or Maps app and then it is fixed in the Files app. However, in the files_sharing app, the app that hosts files for external users that follow a share link, it is unfortunately not fixed.

That's rather unfortunate, as it isn't a great look if you show Nextcloud to external users and it doesn't work properly.

In the console you see messages like

Refused to load https://nextcloud.sitename/index.php/apps/files/preview-service-worker.js because it does not appear in the worker-src directive of the Content Security Policy.

I noticed this problem when I was researching why flipping through photos does not work on a share, I don't know if it would be resolved if this problem is resolved but it stands to reason. I don't really know where to add the patch from #39849 in the files_sharing app, otherwise I could try. But if someone is more knowledgeable with the source I hope it's not a hard problem.

Steps to reproduce

  1. Go to a share link (starts with https://nextcloud.sitename/s )
  2. Look in the web console

Expected behavior

No error messages

Nextcloud Server version

31

Operating system

Debian/Ubuntu

PHP engine version

PHP 8.3

Web server

Nginx

Database engine version

PostgreSQL

Is this bug present after an update or on a fresh install?

None

Are you using the Nextcloud Server Encryption module?

Encryption is Disabled

What user-backends are you using?

  • [x] Default user-backend (database)
  • [ ] LDAP/ Active Directory
  • [ ] SSO - SAML
  • [ ] Other

Configuration report

{
    "system": {
        "instanceid": "***REMOVED SENSITIVE VALUE***",
        "passwordsalt": "***REMOVED SENSITIVE VALUE***",
        "secret": "***REMOVED SENSITIVE VALUE***",
        "trusted_domains": [
            "nextcloud.***",
            "nextcloud.***2"
        ],
        "overwritehost": "nextcloud.***",
        "trusted_proxies": "***REMOVED SENSITIVE VALUE***",
        "datadirectory": "***REMOVED SENSITIVE VALUE***",
        "dbtype": "pgsql",
        "version": "31.0.9.1",
        "overwrite.cli.url": "https:\/\/nextcloud.***",
        "dbname": "***REMOVED SENSITIVE VALUE***",
        "dbhost": "***REMOVED SENSITIVE VALUE***",
        "dbport": "",
        "dbtableprefix": "oc_",
        "dbuser": "***REMOVED SENSITIVE VALUE***",
        "dbpassword": "***REMOVED SENSITIVE VALUE***",
        "default_phone_region": "NL",
        "installed": true,
       "mail_smtpmode": "smtp",
        "mail_sendmailmode": "smtp",
        "mail_from_address": "***REMOVED SENSITIVE VALUE***",
        "mail_domain": "***REMOVED SENSITIVE VALUE***",
        "mail_smtphost": "***REMOVED SENSITIVE VALUE***",
        "maintenance": false,
        "data-fingerprint": "***",
        "theme": "",
        "loglevel": 0,
        "memcache.local": "\\OC\\Memcache\\APCu",
        "mail_smtpport": "1465",
        "mail_smtpauthtype": "PLAIN",
        "mail_smtpauth": 1,
        "mail_smtpsecure": "ssl",
        "mail_smtpname": "***REMOVED SENSITIVE VALUE***",
        "mail_smtppassword": "***REMOVED SENSITIVE VALUE***",
        "filelocking.enabled": true,
        "memcache.locking": "\\OC\\Memcache\\Redis",
        "redis": {
            "host": "***REMOVED SENSITIVE VALUE***",
            "port": 0,
            "timeout": 0,
            "password": "***REMOVED SENSITIVE VALUE***"
        },
        "maintenance_window_start": 100,
        "memories.db.triggers.fcu": true,
        "memories.exiftool": "\/var\/www\/nextcloud\/apps\/memories\/bin-ext\/exiftool-amd64-glibc",
        "memories.vod.path": "\/var\/www\/nextcloud\/apps\/memories\/bin-ext\/go-vod-amd64",
        "enabledPreviewProviders": [
            "OC\\Preview\\Image",
            "OC\\Preview\\HEIC"
        ],
        "memories.gis_type": 2,
        "app_install_overwrite": [
            "gpxpod"
        ]
    }
}

List of activated Apps

Enabled:
  - activity: 4.0.0
  - app_api: 5.0.2
  - circles: 31.0.0
  - cloud_federation_api: 1.14.0
  - comments: 1.21.0
  - contacts: 7.3.2
  - contactsinteraction: 1.12.0
  - dashboard: 7.11.0
  - dav: 1.33.0
  - federatedfilesharing: 1.21.0
  - federation: 1.21.0
  - files: 2.3.1
  - files_downloadlimit: 4.0.0
  - files_pdfviewer: 4.0.0
  - files_reminders: 1.4.0
  - files_sharing: 1.23.1
  - files_trashbin: 1.21.0
  - files_versions: 1.24.0
  - firstrunwizard: 4.0.0
  - gpxpod: 7.0.4
  - logreader: 4.0.0
  - lookup_server_connector: 1.19.0
  - memories: 7.6.2
  - nextcloud_announcements: 3.0.0
  - notifications: 4.0.0
  - oauth2: 1.19.1
  - password_policy: 3.0.0
  - photos: 4.0.0
  - previewgenerator: 5.10.0
  - privacy: 3.0.0
  - profile: 1.0.0
  - provisioning_api: 1.21.0
  - recognize: 9.0.7
  - recommendations: 4.0.0
  - related_resources: 2.0.0
  - serverinfo: 3.0.0
  - settings: 1.14.0
  - sharebymail: 1.21.0
  - support: 3.0.0
  - survey_client: 3.0.0
  - systemtags: 1.21.1
  - text: 5.0.0
  - theming: 2.6.1
  - twofactor_admin: 4.8.0
  - twofactor_backupcodes: 1.20.0
  - twofactor_totp: 13.0.0-dev.0
  - updatenotification: 1.21.0
  - user_status: 1.11.0
  - viewer: 4.0.0
  - weather_status: 1.11.0
  - webhook_listeners: 1.2.0
  - workflowengine: 2.13.0
Disabled:
  - admin_audit: 1.21.0
  - bruteforcesettings: 4.0.0 (installed 2.4.0)
  - camerarawpreviews: 0.8.7 (installed 0.8.7)
  - encryption: 2.19.0
  - files_external: 1.23.0
  - files_rightclick: 0.15.1 (installed 1.6.0)
  - suspicious_login: 9.0.1
  - twofactor_nextcloud_notification: 5.0.0
  - user_ldap: 1.22.0

Nextcloud Signing status

No errors have been found.

Nextcloud Logs


Additional info

No response

tinus-github avatar Oct 03 '25 12:10 tinus-github

please assign me this issue, I'd love to contribute on it @tinus-github #hacktoberfest

pratyush2514 avatar Oct 03 '25 13:10 pratyush2514

It'd probably go right around here:

https://github.com/nextcloud/server/blob/7904644b4e81bd5577519d78f433e5acce51f77e/apps/files_sharing/lib/DefaultPublicShareTemplateProvider.php#L133-L135

I don't believe it needs to go in ShareController.php too, but I'd have to look closer.

joshtrichards avatar Oct 03 '25 19:10 joshtrichards

I can confirm that adding

                // Allow preview service worker
                $csp->addAllowedWorkerSrcDomain('\'self\'');

under line 135 fixes the error message. Unfortunately this does not fix my original problem so this was apparently not the cause.

tinus-github avatar Oct 05 '25 13:10 tinus-github

I can reproduce this on 32.0.0.

Content-Security-Policy: (Report-Only policy) The page’s settings would block a worker script (worker-src) at https://.../index.php/apps/files/preview-service-worker.js from being executed because it violates the following directive: “worker-src 'none'”

eat-correctly avatar Oct 14 '25 16:10 eat-correctly

I noticed there was an upgrade to 32.0.1 (blocked by one of my add-ons that are not updated yet) so I disabled that add-on and installed the upgrade, and now the original issue I was looking at, where you can't flip through the pictures, is fixed. The CSP error remains though.

tinus-github avatar Oct 26 '25 13:10 tinus-github

This CSP issue seems to prevent me from previewing ANYTHING, ODT files, images, etc.

ServiceWorker.js:22 Refused to create a worker from 'https://--------.com/index.php/apps/files/preview-service-worker.js' because it violates the following Content Security Policy directive: "script-src 'nonce-Pp2yQgjgUwvVST0ITk+FraUa2FISwhG0g/qYCDjVYXg='". Note that 'worker-src' was not explicitly set, so 'script-src' is used as a fallback.

ServiceWorker.js:25 [ERROR] files: SW registration failed:
{app: 'files', level: 2, error: SecurityError: Failed to register a ServiceWorker: The provided scriptURL ('https://-------…}

Viewer.vue:488 [WARN] viewer: No files provided, skipping update {app: 'viewer', level: 2}

how can i fix this temporairly while the devs address it?

kekkodance avatar Jan 04 '26 14:01 kekkodance

okay, so after adding that line on the top, the CSP issue is gone but another surfaces that doesnt allow me to preview anything:

Image Image

kekkodance avatar Jan 04 '26 14:01 kekkodance

To resolve this issue

Edit nextcloud/apps/files_sharing/lib/DefaultPublicShareTemplateProvider.php

Before:

		// CSP to allow office
		$csp = new ContentSecurityPolicy();
		$csp->addAllowedFrameDomain('\'self\'');

		$response = new PublicTemplateResponse(
			'files',
			'index',
		);
		$response->setContentSecurityPolicy($csp);

After:

		// CSP to allow office
		$csp = new ContentSecurityPolicy();
		$csp->addAllowedFrameDomain('\'self\'');

		$response = new PublicTemplateResponse(
			'files',
			'index',
		);
		$csp = $response->getContentSecurityPolicy();
		$csp->addAllowedWorkerSrcDomain('\'self\'');

		$response->setContentSecurityPolicy($csp);

Best,

maladwani avatar Jan 18 '26 17:01 maladwani

I can reproduce this on 33.0.0.

eat-correctly avatar Mar 17 '26 19:03 eat-correctly

Confirming this still reproduces on Nextcloud 35.0.0 (released 2026-09-15), and adding two related CSP warnings I observed on the same 35.0.0 install:

  1. /core/js/mimetypelist.js?v=... — fires Firefox NetUtil.sys.mjs:142 warning "blocked the loading of a resource (default-src) ... because it violates the following directive: 'default-src 'none''". Loaded via Util::addScript('core', 'mimetypelist', 'core', true) in core/Listener/BeforeTemplateRenderedListener.php:58, which goes through emit_script_tag() (lib/private/Template/functions.php:62) and does get a nonce. The warning fires anyway because script-src does not include 'self' (unset($allowedScriptDomains['\'self\'']) in lib/public/AppFramework/Http/EmptyContentSecurityPolicy.php:buildPolicy() when a nonce is present), and script-src-elem 'strict-dynamic' ignores host-source keywords per CSP spec.

  2. /dist/files_sharing-main.js?v=... — same pattern, loaded by DashboardController::index() via Util::addScript('files_sharing', 'main', 'theming') (apps/dashboard/lib/Controller/DashboardController.php). Same warning, same root cause.

  3. /apps/dashboard/ — Firefox warns when the browser fetches this URL and the response is HTTP 401 (e.g. unauthenticated request from the Notifications polling). The 401 carries EmptyContentSecurityPolicy with default-src 'none'; base-uri 'none'; manifest-src 'self'; frame-ancestors 'none' and no script-src, so any subresource load on that response would also be blocked.

All three are cosmetic on my install — every script loads successfully (the nonce validates), Firefox just also reports the policy mismatch. But the underlying problem your fix addresses (CSP too strict for some same-origin loads) clearly extends beyond just preview-service-worker.js.

If script-src-elem 'strict-dynamic' becomes mandatory (as susnux flagged on #45127), then the long-term fix needs to ensure every script load either (a) carries a nonce, (b) is loaded dynamically by an already-trusted script, or (c) comes from a host the page's CSP has explicitly allowed via a non-strict directive. Worth a unified pass through the layout's emit_script_loading_tags() and the per-app CSP listeners before 35.x stabilises.

Reference: I traced this on nextcloud:35.0.0-fpm / PHP 8.4.19 / Firefox 130+.

VIPKaiser avatar Sep 20 '26 17:09 VIPKaiser