Skip to content

[v4]Content Security Policy issue of plugin-upload in strapi-4.0.0-beta.13 #11637

Closed

Description

@boeto

Bug report

Describe the bug

[v4]Content Security Policy issue of plugin-upload in strapi-4.0.0-beta.13

Steps to reproduce the behavior

  1. Install and change the upload provider to aws-s3

  2. Upload an image and get the issue

Expected behavior

Should be able to see the picture. The same setting runs correctly in v3.

Screenshots

screenshot

Code snippets

// ./config/plugins.js

module.exports = ({ env }) => ({
  upload: {
    config: {
      provider: "aws-s3",
      providerOptions: {
        accessKeyId: env("AWS_ACCESS_KEY_ID"),
        secretAccessKey: env("AWS_ACCESS_SECRET"),
        region: env("AWS_REGION"),
        params: {
          Bucket: env("AWS_BUCKET"),
        },
      },
    },
  },
});

System

  • Node.js version: v14.17.6
  • YARN version: 1.22.17
  • Strapi version: 4.0.0-beta.13
  • Database: PostgreSQL 13
  • Operating system: macOS 10.15

Additional context

null

Activity

  1. changed the title [-]Content Security Policy issue of plugin-upload in strapi-4.0.0-beta.13[/-] [+][v4]Content Security Policy issue of plugin-upload in strapi-4.0.0-beta.13[/+] on Nov 19, 2021
  2. grzegorzbialy commented on Nov 23, 2021

    @grzegorzbialy

    @boeto The internal middleware config change is not documented but I found out you can change default CSP settings middleware in config/middlewares.js like this:

    module.exports = ({ env }) => [
      'strapi::errors',
      {
        name: 'strapi::security',
        config: {
          contentSecurityPolicy: {
            directives: {
              'script-src': ["'self'", "'unsafe-inline'", 'cdn.jsdelivr.net'],
              'img-src': ["'self'", 'data:', 'cdn.jsdelivr.net', 'strapi.io', `${env('AWS_BUCKET')}.s3.${env('AWS_REGION')}.amazonaws.com`],
            },
          }
        },
      },
      'strapi::cors',
      'strapi::poweredBy',
      'strapi::logger',
      'strapi::query',
      'strapi::body',
      'strapi::favicon',
      'strapi::public',
    ];
  3. derrickmehaffy commented on Dec 6, 2021

    @derrickmehaffy
    Member

    Provider examples will have an example config to show how to properly modify this. Closing as it's not a bug

  4. derrickmehaffy commented on Jan 4, 2022

    @derrickmehaffy
    Member

    This issue has been mentioned on Strapi Community Forum. There might be relevant details there:

    https://forum.strapi.io/t/strapi-v4-broken-image-even-when-the-images-link-works-cloudinary/14143/4

  5. derrickmehaffy commented on Jan 5, 2022

    @derrickmehaffy
    Member

    This issue has been mentioned on Strapi Community Forum. There might be relevant details there:

    https://forum.strapi.io/t/strapi-v4-override-csp/14157/2

  6. ludovicraymond commented on Feb 2, 2022

    @ludovicraymond

    Doesn't work for me for video assets.

    It's ok for image type.

    'script-src': ["'self'", "'unsafe-inline'", 'cdn.jsdelivr.net'],
     'img-src': ["'self'", 'blob:', 'data:', 'cdn.jsdelivr.net', 'strapi.io', `${env('AWS_BUCKET')}.s3.amazonaws.com`],
     'media-src': ["'self'", 'blob:', 'data:', 'cdn.jsdelivr.net', 'strapi.io', `${env('AWS_BUCKET')}.s3.amazonaws.com`],
    

    any idea ?

  7. nsavinda commented on Feb 25, 2022

    @nsavinda
  8. strapi-bot commented on Mar 18, 2022

    @strapi-bot

    This issue has been mentioned on Strapi Community Forum. There might be relevant details there:

    https://forum.strapi.io/t/using-supabase-for-the-postgres-database/16762/2

  9. 13 remaining items

  10. kepes commented on Jan 27, 2023

    @kepes

    Based on Strapi docs I put midlewares.js into config/env/production folder. This way dev and prod environment separated.

    This is my working midlewares.js content. I put AWS_REGION into the URL

    module.exports = ({ env }) => [
      "strapi::errors",
      {
        name: "strapi::security",
        config: {
          contentSecurityPolicy: {
            useDefaults: true,
            directives: {
              "connect-src": ["'self'", "https:"],
              "img-src": [
                "'self'",
                "data:",
                "blob:",
                `https://${env("AWS_BUCKET_NAME")}.s3.${env("AWS_REGION")}.amazonaws.com`,
              ],
              "media-src": [
                "'self'",
                "data:",
                "blob:",
                `https://${env("AWS_BUCKET_NAME")}.s3.${env("AWS_REGION")}.amazonaws.com`,
              ],
              upgradeInsecureRequests: null,
            },
          },
        },
      },
      "strapi::cors",
      "strapi::poweredBy",
      "strapi::logger",
      "strapi::query",
      "strapi::body",
      "strapi::session",
      "strapi::favicon",
      "strapi::public",
    ];
    

    In S3 bucket config I had to make my bucket public. I think the Strapi - Amazon AWS - Create the bucket doc is wrong because the bucket must be public, contrary to what the documentation says.

    Based on S3 User guide I added a Bucket policy to my bucket

    {
        "Version": "2012-10-17",
        "Statement": [
            {
                "Sid": "PublicReadGetObject",
                "Effect": "Allow",
                "Principal": "*",
                "Action": [
                    "s3:GetObject"
                ],
                "Resource": [
                    "arn:aws:s3:::Bucket-Name/*"
                ]
            }
        ]
    }
    

    After configuration, you should check the images directly in a browser with the S3 Object URL. If everything went well, you can see the picture uploaded by Strapi. If the configuration failed and an error message is displayed, the Bucket is probably still not public.

    Important!
    According to the AWS user guide, creating a public S3 bucket is dangerous and should only be done if you are hosting a static website. In my opinion the uploaded images are part of a static website and in this situation it is acceptable, but I am not an AWS expert. Please consider not using the public S3 bucket if you are not comfortable with it!

    Screenshots of my S3 Bucket config

    bucket-01

    bucket-02

    bucket-03

    Another beautiful day has passed to find this bug :)

  11. nikita-fuchs commented on Mar 8, 2023

    @nikita-fuchs

    @carloshs94

    EDIT: FIXED, i had strapi::security duplicated at the end of the file, so it was being overwritten by the default one.

    Damn, that was my mistake, too, you saved me !

  12. nikantkamat commented on Mar 23, 2023

    @nikantkamat

    Is there any same fix for the plugin "strapi-uploader-provider-do" because i am getting the same error

  13. strapi-bot commented on Jun 29, 2023

    @strapi-bot

    This issue has been mentioned on Strapi Community Forum. There might be relevant details there:

    https://forum.strapi.io/t/content-security-policy-on-shared-hosting-with-two-nodejs-aps/29654/4

  14. dynamic-standard2 commented on Aug 4, 2023

    @dynamic-standard2

    If anyone has issues with the images of Strapi's Marketplace, add "market-assets.strapi.io" to the img-src and media-src directives, like this:

    export default [
      'strapi::errors',
      'strapi::security',
      'strapi::cors',
      'strapi::poweredBy',
      'strapi::logger',
      'strapi::query',
      'strapi::body',
      'strapi::session',
      'strapi::favicon',
      'strapi::public',
      {
        name: "strapi::security",
        config: {
          contentSecurityPolicy: {
            useDefaults: true,
            directives: {
              "connect-src": ["'self'", "https:"],
              "img-src": [
                "'self'", 
                "data:", 
                "blob:", 
                `https://${process.env.AWS_BUCKET}.s3.amazonaws.com`, 
                "dl.airtable.com", 
                "market-assets.strapi.io"
              ],
                "media-src": [
                "'self'", 
                "data:", 
                "blob:", 
                `https://${process.env.AWS_BUCKET}.s3.amazonaws.com`, 
                "dl.airtable.com", 
                "market-assets.strapi.io"
            ],
              upgradeInsecureRequests: null,
            },
          },
        },
      },
    ];
  15. andersonstudioa commented on Aug 11, 2023

    @andersonstudioa

    I fixed changing the file config/middlewares.ts with CDN_URL

    image

  16. brun0xff commented on Nov 22, 2023

    @brun0xff

    If anyone has issues with the images of Strapi's Marketplace, add "market-assets.strapi.io" to the img-src and media-src directives, like this:

    export default [
      'strapi::errors',
      'strapi::security',
      'strapi::cors',
      'strapi::poweredBy',
      'strapi::logger',
      'strapi::query',
      'strapi::body',
      'strapi::session',
      'strapi::favicon',
      'strapi::public',
      {
        name: "strapi::security",
        config: {
          contentSecurityPolicy: {
            useDefaults: true,
            directives: {
              "connect-src": ["'self'", "https:"],
              "img-src": [
                "'self'", 
                "data:", 
                "blob:", 
                `https://${process.env.AWS_BUCKET}.s3.amazonaws.com`, 
                "dl.airtable.com", 
                "market-assets.strapi.io"
              ],
                "media-src": [
                "'self'", 
                "data:", 
                "blob:", 
                `https://${process.env.AWS_BUCKET}.s3.amazonaws.com`, 
                "dl.airtable.com", 
                "market-assets.strapi.io"
            ],
              upgradeInsecureRequests: null,
            },
          },
        },
      },
    ];

    For god's sake thank you, you're awesome!

  17. LeNguyenMinhTuan commented on Jan 30, 2024

    @LeNguyenMinhTuan

    I'm trying to make a upload on a Strapi project with a provider (default config, I guess). But al get it response is Refused to connect to 'http://my-url/upload/' because it violates the following Content Security Policy directive: "connect-src 'self' https:".

    With a Status Code 301

    But the request url was https://my-url/upload The request go through a nginx but why does it respond on http instead of https? Everything else works in the admin panel, only the uploads dont.

    I'm stuck here too. Did you solve it ?

  18. jsphkhan commented on Feb 5, 2024

    @jsphkhan

    I fixed changing the file config/middlewares.ts with CDN_URL

    image

    This is the solution to follow if anybody is using a CDN in front of S3 bucket. I was using a Cloudfront instance on top of AWS S3.

  19. Kamarhinanton commented on Jul 4, 2024

    @Kamarhinanton

    Does enyone know, why after transferring data to prod, url is broken in reach text block? In media galery picture is ok.
    image

  20. nikita-fuchs commented on Jul 4, 2024

    @nikita-fuchs

    Does enyone know, why after transferring data to prod, url is broken in reach text block? In media galery picture is ok. image

    Because your fileURL is pointing to localhost, which is not a thing of course when you deploy things somewhere else.

  21. Kamarhinanton commented on Jul 4, 2024

    @Kamarhinanton

    How I can change this behaviour? On my local machine everything is ok with this text reach block.

  22. H3lltronik commented on Jul 9, 2024

    @H3lltronik

    I haven't been able to fix it and don't know what to do.
    My console logs this error:

    Refused to load the image 'https://s3.us-east-1.amazonaws.com/my-bucket-stuff/thumbnail_1700242274671_05530326c8.jpeg?updatedAt=2024-07-09T05%3A26%3A13.053Z' because it violates the following Content Security Policy directive: "img-src 'self' data: blob: https://s3.us-east-1.amazonaws.com/my-bucket-stuff".

    This is my config/middlewares.js

    module.exports = ({ env }) => [
      "strapi::errors",
      "strapi::cors",
      "strapi::poweredBy",
      "strapi::logger",
      "strapi::query",
      "strapi::body",
      "strapi::session",
      "strapi::favicon",
      "strapi::public",
      {
        name: "strapi::security",
        config: {
          contentSecurityPolicy: {
            useDefaults: true,
            directives: {
              "connect-src": ["'self'", "https:"],
              "img-src": [
                "'self'",
                "data:",
                "blob:",
                `https://s3.${env("AWS_REGION")}.amazonaws.com/${env(
                  "AWS_BUCKET_NAME"
                )}`,
              ],
              "media-src": [
                "'self'",
                "data:",
                "blob:",
                `https://s3.${env("AWS_REGION")}.amazonaws.com/${env(
                  "AWS_BUCKET_NAME"
                )}`,
              ],
              upgradeInsecureRequests: null,
            },
          },
        },
      },
    ];
    
    

    I tried adding a wildcard like '/*' in the S3 URL but it doesn't work the only thing that has shown to work is to directly place the entire URL in the "img-src" array but that's obviously wrong.

    Please, somebody help me, I've stuck here for days, it's the exact same start on both URLs and the wildcard seems to not be working, I'm so frustrated.

    I'm running strapi 4.25.2

  23. javdevruent commented on Sep 19, 2024

    @javdevruent

    @H3lltronik have you ever fix this issue?

  24. DannyST89 commented on Oct 8, 2024

    @DannyST89

    Thanks ,it works for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    issue: bugIssue reporting a bugseverity: mediumIf it breaks the basic use of the product but can be worked aroundsource: core:strapiSource is core/strapi packagesource: core:uploadSource is core/upload packagestatus: confirmedConfirmed by a Strapi Team member or multiple community members

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions