Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
194 changes: 194 additions & 0 deletions spec/CloudCode.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -5433,6 +5433,200 @@ describe('Parse.File hooks', () => {
})
).toBeRejectedWith(new Parse.Error(Parse.Error.SCRIPT_FAILED, 'unauthorized'));
});

describe('find trigger return value', () => {
let file;
let otherFile;

const download = (range, url = file.url()) =>
request({ url, headers: range ? { Range: 'bytes=0-100' } : {} });

beforeEach(async () => {
const base64 = text => Buffer.from(text).toString('base64');
file = new Parse.File('popeye.txt', { base64: base64('original') }, 'text/plain');
await file.save({ useMasterKey: true });
otherFile = new Parse.File('olive.csv', { base64: base64('other') }, 'text/csv');
await otherFile.save({ useMasterKey: true });
});

for (const range of [false, true]) {
const type = range ? 'range request' : 'request';
// A range request for the stored file is streamed if the files adapter supports it
const storedFileStatus = () =>
range && Config.get('test').filesController.adapter.handleFileStream ? 206 : 200;

it(`applies response settings if afterFind returns a value that is not an object on ${type}`, async () => {
let value;
Parse.Cloud.afterFind(Parse.File, req => {
req.forceDownload = true;
req.responseHeaders['X-Custom-Header'] = 'custom-value';
return value;
});
for (value of [true, 1, 'text']) {
const response = await download(range);
expect(response.status).toBe(storedFileStatus());
expect(response.text).toBe('original');
expect(response.headers['content-disposition']).toBe(`attachment;filename=${file._name}`);
expect(response.headers['x-custom-header']).toBe('custom-value');
expect(response.headers['x-content-type-options']).toBe('nosniff');
}
});

it(`does not replace the file if afterFind returns a file on ${type}`, async () => {
Parse.Cloud.afterFind(Parse.File, req => {
req.forceDownload = true;
return otherFile;
});
const response = await download(range);
expect(response.status).toBe(storedFileStatus());
expect(response.text).toBe('original');
expect(response.headers['content-disposition']).toBe(`attachment;filename=${file._name}`);
expect(response.headers['x-content-type-options']).toBe('nosniff');
});

it(`serves the file of the object that afterFind returns on ${type}`, async () => {
Parse.Cloud.afterFind(Parse.File, () => ({ file: otherFile }));
const response = await download(range);
expect(response.status).toBe(200);
expect(response.text).toBe('other');
expect(response.headers['content-type']).toMatch(/^text\/csv/);
expect(response.headers['content-disposition']).toBeUndefined();
expect(response.headers['x-content-type-options']).toBe('nosniff');
});

it(`serves the file of the object that afterFind returns if it is created from a buffer on ${type}`, async () => {
Parse.Cloud.afterFind(Parse.File, () => ({
file: new Parse.File('olive.csv', Buffer.from('other')),
}));
const response = await download(range);
expect(response.status).toBe(200);
expect(response.text).toBe('other');
expect(response.headers['content-type']).toMatch(/^text\/csv/);
});

it(`rejects if the file of the object that afterFind returns contains no data on ${type}`, async () => {
Parse.Cloud.afterFind(Parse.File, () => ({ file: new Parse.File('olive.csv') }));
const response = await download(range).catch(e => e);
expect(response.status).toBe(403);
expect(response.data).toEqual({
code: Parse.Error.SCRIPT_FAILED,
error: 'File provided by afterFind trigger contains no data.',
});
});

it(`answers that the file is not found if afterFind returns a file for a missing file on ${type}`, async () => {
Parse.Cloud.afterFind(Parse.File, () => ({ file: otherFile }));
const url = file.url().replace(file._name, 'missing.txt');
const response = await download(range, url).catch(e => e);
expect(response.status).toBe(404);
expect(response.text).toBe('File not found.');
});

it(`applies response settings of the request that the object returned by afterFind does not set on ${type}`, async () => {
Parse.Cloud.afterFind(Parse.File, req => {
req.forceDownload = true;
req.responseHeaders['X-Custom-Header'] = 'custom-value';
return { file: otherFile };
});
const response = await download(range);
expect(response.status).toBe(200);
expect(response.text).toBe('other');
expect(response.headers['content-disposition']).toBe(
`attachment;filename=${otherFile._name}`
);
expect(response.headers['x-custom-header']).toBe('custom-value');
expect(response.headers['x-content-type-options']).toBe('nosniff');
});

it(`applies response settings of the object returned by afterFind over those of the request on ${type}`, async () => {
Parse.Cloud.afterFind(Parse.File, req => {
req.forceDownload = true;
req.responseHeaders['X-Custom-Header'] = 'request-value';
return { forceDownload: false, responseHeaders: { 'X-Custom-Header': 'returned-value' } };
});
const response = await download(range);
expect(response.status).toBe(storedFileStatus());
expect(response.text).toBe('original');
expect(response.headers['content-disposition']).toBeUndefined();
expect(response.headers['x-custom-header']).toBe('returned-value');
expect(response.headers['x-content-type-options']).toBeUndefined();
});

it(`serves the stored file if the object returned by afterFind does not set a file on ${type}`, async () => {
let value;
Parse.Cloud.afterFind(Parse.File, () => value);
for (value of [
{ forceDownload: true },
{ file: null, forceDownload: true, responseHeaders: null },
]) {
const response = await download(range);
expect(response.status).toBe(storedFileStatus());
expect(response.text).toBe('original');
expect(response.headers['content-disposition']).toBe(`attachment;filename=${file._name}`);
expect(response.headers['x-content-type-options']).toBe('nosniff');
}
});

it(`applies response settings if afterFind returns the request on ${type}`, async () => {
Parse.Cloud.afterFind(Parse.File, req => {
req.forceDownload = true;
return req;
});
const response = await download(range);
expect(response.status).toBe(storedFileStatus());
expect(response.text).toBe('original');
expect(response.headers['content-disposition']).toBe(`attachment;filename=${file._name}`);
expect(response.headers['x-content-type-options']).toBe('nosniff');
});

it(`can remove default response headers by assigning a new object in afterFind on ${type}`, async () => {
Parse.Cloud.afterFind(Parse.File, req => {
req.responseHeaders = {};
});
const response = await download(range);
expect(response.status).toBe(storedFileStatus());
expect(response.text).toBe('original');
expect(response.headers['x-content-type-options']).toBeUndefined();
});

it(`ignores a value returned by beforeFind that is not an object with a file on ${type}`, async () => {
let value;
Parse.Cloud.beforeFind(Parse.File, () => value);
const settings = {
forceDownload: true,
responseHeaders: { 'X-Custom-Header': 'custom-value' },
};
for (value of [true, 'text', otherFile, {}, settings]) {
const response = await download(range);
expect(response.status).toBe(storedFileStatus());
expect(response.text).toBe('original');
expect(response.headers['content-disposition']).toBeUndefined();
expect(response.headers['x-custom-header']).toBeUndefined();
expect(response.headers['x-content-type-options']).toBe('nosniff');
}
});

it(`serves the stored file that the object returned by beforeFind names on ${type}`, async () => {
let afterFind;
Parse.Cloud.beforeFind(Parse.File, () => ({ file: otherFile }));
Parse.Cloud.afterFind(Parse.File, req => afterFind(req));
for (afterFind of [
req => {
req.forceDownload = true;
},
() => ({ forceDownload: true }),
]) {
const response = await download(range);
expect(response.status).toBe(storedFileStatus());
expect(response.text).toBe('other');
expect(response.headers['content-type']).toMatch(/^text\/csv/);
expect(response.headers['content-disposition']).toBe(
`attachment;filename=${otherFile._name}`
);
}
});
}
});
});

describe('Cloud Config hooks', () => {
Expand Down
92 changes: 56 additions & 36 deletions src/Routers/FilesRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -235,63 +235,83 @@ export class FilesRouter {
if (triggerResult?.file?._name) {
filename = triggerResult?.file?._name;
contentType = mime.getType(filename);
file = new Parse.File(filename, { base64: '' }, contentType);
}

const defaultResponseHeaders = { 'X-Content-Type-Options': 'nosniff' };

if (isFileStreamable(req, filesController)) {
const afterFind = await triggers.maybeRunFileTrigger(
const runAfterFind = async () => {
const fileObject = {
file,
forceDownload: false,
responseHeaders: { ...defaultResponseHeaders },
};
const result = await triggers.maybeRunFileTrigger(
triggers.Types.afterFind,
{ file, forceDownload: false, responseHeaders: { ...defaultResponseHeaders } },
fileObject,
config,
fileAuth
);
if (afterFind?.forceDownload) {
res.set('Content-Disposition', `attachment;filename=${afterFind.file?._name || filename}`);
// Properties of a returned object take precedence over the request
const returned = result && typeof result === 'object' ? result : {};
return {
file: returned.file || fileObject.file,
forceDownload: returned.forceDownload ?? fileObject.forceDownload,
responseHeaders: returned.responseHeaders ?? fileObject.responseHeaders,
};
};
const setResponseHeaders = afterFind => {
if (afterFind.forceDownload) {
res.set('Content-Disposition', `attachment;filename=${afterFind.file._name || filename}`);
}
for (const [key, value] of Object.entries(afterFind?.responseHeaders ?? defaultResponseHeaders)) {
for (const [key, value] of Object.entries(afterFind.responseHeaders)) {
res.set(key, value);
}
filesController.handleFileStream(config, filename, req, res, contentType).catch(() => {
res.status(404);
res.set('Content-Type', 'text/plain');
res.end('File not found.');
});
return;
}
};
const getServedData = servedFile => {
if (servedFile._source?.format === 'buffer') {
return servedFile._source.buffer;
}
if (typeof servedFile._data === 'string') {
return Buffer.from(servedFile._data, 'base64');
}
throw new Parse.Error(
Parse.Error.SCRIPT_FAILED,
'File provided by afterFind trigger contains no data.'
);
};

let data = await filesController.getFileData(config, filename).catch(() => {
let afterFind;
if (isFileStreamable(req, filesController)) {
afterFind = await runAfterFind();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// Stream the stored file unless the trigger replaced the file
if (afterFind.file === file) {
setResponseHeaders(afterFind);
filesController.handleFileStream(config, filename, req, res, contentType).catch(() => {
res.status(404);
res.set('Content-Type', 'text/plain');
res.end('File not found.');
});
return;
}
}
const storedData = await filesController.getFileData(config, filename).catch(() => {
res.status(404);
res.set('Content-Type', 'text/plain');
res.end('File not found.');
});
if (!data) {
if (!storedData) {
return;
}
file = new Parse.File(filename, { base64: data.toString('base64') }, contentType);
const afterFind = await triggers.maybeRunFileTrigger(
triggers.Types.afterFind,
{ file, forceDownload: false, responseHeaders: { ...defaultResponseHeaders } },
config,
fileAuth
);

if (afterFind?.file) {
contentType = mime.getType(afterFind.file._name);
data = Buffer.from(afterFind.file._data, 'base64');
if (!afterFind) {
file = new Parse.File(filename, { base64: storedData.toString('base64') }, contentType);
afterFind = await runAfterFind();
}

const data = getServedData(afterFind.file);
res.status(200);
res.set('Content-Type', contentType);
res.set('Content-Type', mime.getType(afterFind.file._name));
res.set('Content-Length', data.length);
if (afterFind.forceDownload) {
res.set('Content-Disposition', `attachment;filename=${afterFind.file._name}`);
}
if (afterFind.responseHeaders) {
for (const [key, value] of Object.entries(afterFind.responseHeaders)) {
res.set(key, value);
}
}
setResponseHeaders(afterFind);
res.end(data);
} catch (e) {
const err = triggers.resolveError(e, {
Expand Down
15 changes: 11 additions & 4 deletions src/cloud-code/Parse.Cloud.js
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,8 @@ ParseCloud.afterDelete = function (parseClass, handler, validationHandler) {
* }, { ...validationObject });
*```
*
* For {@link Parse.File}, the function takes a {@link Parse.Cloud.FileTriggerRequest}. To serve a different stored file, return an object with the property `file` set to a {@link Parse.File} with the name of that stored file. Only the name of the returned file is used. Any other return value is ignored.
*
* @method beforeFind
* @name Parse.Cloud.beforeFind
* @param {(String|Parse.Object)} arg1 The Parse.Object subclass to register the before find function for. This can instead be a String that is the className of the subclass.
Expand Down Expand Up @@ -562,6 +564,11 @@ ParseCloud.beforeFind = function (parseClass, handler, validationHandler) {
* }, { ...validationObject });
*```
*
* For {@link Parse.File}, the function takes a {@link Parse.Cloud.FileTriggerRequest}. To change the response of a file download, set `forceDownload` or `responseHeaders` on the request, or return an object with any of the following properties. Any other return value is ignored.
* - `file`: A {@link Parse.File} that is served instead of the stored file. It has to contain its data, for example a file created from a base64 string or a buffer. If not set, the stored file is served.
* - `forceDownload`: Replaces `forceDownload` of the request. If not set, the value of the request is used.
* - `responseHeaders`: Replaces `responseHeaders` of the request as a whole, including the default header. If not set, the headers of the request are used.
*
* @method afterFind
* @name Parse.Cloud.afterFind
* @param {(String|Parse.Object)} arg1 The Parse.Object subclass to register the after find function for. This can instead be a String that is the className of the subclass.
Expand Down Expand Up @@ -755,16 +762,16 @@ module.exports = ParseCloud;
* @property {Boolean} master If true, means the master key or the read-only master key was used.
* @property {Boolean} isReadOnly If true, means the read-only master key was used. This is a subset of `master`, so `master` will also be true. Use `master && !isReadOnly` to check for full master key access.
* @property {Parse.User} user If set, the user that made the request, as stored, including data the user cannot read itself; to return it to the client, fetch it with the user's session token.
* @property {Parse.File} file The file that triggered the hook.
* @property {Parse.File} file The file that triggered the hook. In `beforeFind` the file contains no data. In `afterFind` the file contains no data if only the file metadata is requested, or if the file is requested with a `Range` header and the files adapter supports streaming, for example the GridFS adapter.
* @property {Integer} fileSize The size of the file in bytes.
* @property {Integer} contentLength The value from Content-Length header
* @property {String} ip The IP address of the client making the request.
* @property {Object} headers The original HTTP headers for the request.
* @property {String} triggerName The name of the trigger (`beforeSave`, `afterSave`)
* @property {String} triggerName The name of the trigger (`beforeSave`, `afterSave`, ...)
* @property {Object} log The current logger inside Parse Server.
* @property {Object} config The Parse Server config.
* @property {Boolean} forceDownload (afterFind only) If set to `true`, the file response will include a `Content-Disposition: attachment` header, prompting the browser to download the file instead of displaying it inline.
* @property {Object} responseHeaders (afterFind only) The headers that will be set on the file response. By default contains `{ 'X-Content-Type-Options': 'nosniff' }`. Modify this object to add, change, or remove response headers.
* @property {Boolean} forceDownload (afterFind of a file download only) If set to `true`, the file response will include a `Content-Disposition: attachment` header, prompting the browser to download the file instead of displaying it inline.
* @property {Object} responseHeaders (afterFind of a file download only) The headers that will be set on the file response. By default contains `{ 'X-Content-Type-Options': 'nosniff' }`. Modify this object to add, change, or remove response headers.
*/

/**
Expand Down
Loading