Skip to content

Commit

Permalink
fix: security issue with file upload path (#778)
Browse files Browse the repository at this point in the history
  • Loading branch information
goemen committed Sep 24, 2024
1 parent 6f50501 commit dbc8093
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
6 changes: 5 additions & 1 deletion backend/src/v1/middlewares/storage/upload.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ jest.mock('@aws-sdk/client-s3', () => ({
})),
}));

const realpathSyncMock = jest.fn();
jest.mock('fs', () => ({
__esModule: true,
...jest.requireActual('fs'),
default: {
createReadStream: jest.fn(),
realpathSync: (...args) => realpathSyncMock(...args),
},
}));

Expand All @@ -41,6 +43,8 @@ describe('upload', () => {
},
};

realpathSyncMock.mockReturnValue(path.join(os.tmpdir(), 'test.jpg'));

const res = {
status: jest.fn().mockReturnThis(),
json: jest.fn(),
Expand Down Expand Up @@ -83,7 +87,6 @@ describe('upload', () => {
};
await useUpload({ folder: 'app' })(req, res, jest.fn());
expect(res.status).toHaveBeenCalledWith(400);

});
});

Expand All @@ -100,6 +103,7 @@ describe('upload', () => {
},
};

realpathSyncMock.mockReturnValue(path.join(os.tmpdir(), 'test.jpg'));
const res = {
status: jest.fn().mockReturnThis(),
json: jest.fn(),
Expand Down
9 changes: 8 additions & 1 deletion backend/src/v1/middlewares/storage/upload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
import os from 'os';
import retry from 'async-retry';
import { S3_BUCKET, S3_OPTIONS } from '../../../constants/admin';

import PATH from 'path';

interface Options {
folder: string;
Expand All @@ -31,6 +31,13 @@ export const useUpload = (options: Options) => {

try {
const s3 = new S3Client(S3_OPTIONS);
const filePath = fs.realpathSync(PATH.resolve(os.tmpdir(), path));
if (!filePath.startsWith(os.tmpdir())) {
logger.error('File path is not starting with temp directory.');
res.statusCode = 403;
res.end();
return;
}
const stream = fs.createReadStream(path);
const uploadParams: PutObjectCommandInput = {
Bucket: S3_BUCKET,
Expand Down

0 comments on commit dbc8093

Please sign in to comment.