Merge pull request #14654 from strapi/fix/S3-DO-file-url-check-protocol

fix(aws-provider): add https protocol when missing in file url
This commit is contained in:
Nathan Pichon 2022-10-24 11:35:08 +02:00 committed by GitHub
commit bf890beab6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 81 additions and 1 deletions

View File

@ -0,0 +1,10 @@
'use strict';
const baseConfig = require('../../../jest.base-config');
const pkg = require('./package.json');
module.exports = {
...baseConfig,
displayName: pkg.name,
roots: [__dirname],
};

View File

@ -0,0 +1,60 @@
'use strict';
const AWS = require('aws-sdk');
const awsProvider = require('../index');
jest.mock('aws-sdk');
const S3InstanceMock = {
upload: jest.fn((params, callback) => callback(null, {})),
};
AWS.S3.mockReturnValue(S3InstanceMock);
describe('AWS-S3 provider', () => {
const providerInstance = awsProvider.init({});
beforeEach(() => {
jest.clearAllMocks();
});
describe('upload', () => {
test('Should add url to file object', async () => {
S3InstanceMock.upload.mockImplementationOnce((params, callback) =>
callback(null, { Location: 'https://validurl.test' })
);
const file = {
path: '/tmp/',
hash: 'test',
ext: 'json',
mime: 'application/json',
buffer: '',
};
await providerInstance.upload(file);
expect(S3InstanceMock.upload).toBeCalled();
expect(file.url).toBeDefined();
expect(file.url).toEqual('https://validurl.test');
});
test('Should add to the url the https protocol as it is missing', async () => {
S3InstanceMock.upload.mockImplementationOnce((params, callback) =>
callback(null, { Location: 'uri.test' })
);
const file = {
path: '/tmp/',
hash: 'test',
ext: 'json',
mime: 'application/json',
buffer: '',
};
await providerInstance.upload(file);
expect(S3InstanceMock.upload).toBeCalled();
expect(file.url).toBeDefined();
expect(file.url).toEqual('https://uri.test');
});
});
});

View File

@ -9,6 +9,11 @@
const _ = require('lodash');
const AWS = require('aws-sdk');
function assertUrlProtocol(url) {
// Regex to test protocol like "http://", "https://"
return /^\w*:\/\//.test(url);
}
module.exports = {
init(config) {
const S3 = new AWS.S3({
@ -34,7 +39,12 @@ module.exports = {
}
// set the bucket file url
if (assertUrlProtocol(data.Location)) {
file.url = data.Location;
} else {
// Default protocol to https protocol
file.url = `https://${data.Location}`;
}
resolve();
}