Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
56d6516
feat: add Parse Server config to standard request object
Moumouls Jun 24, 2022
d85f37f
wip
Moumouls Mar 12, 2023
5926924
Merge remote-tracking branch 'origin/moumouls/addConfigUnderRequest' …
Moumouls Mar 12, 2023
65f83c1
feat: requestContextMiddleware and config in hooks
Moumouls Mar 12, 2023
8340f5b
fix: restore lock
Moumouls Mar 12, 2023
8c8e1eb
fix: defs
Moumouls Mar 12, 2023
748f68f
fix: import
Moumouls Mar 12, 2023
c98199c
Merge branch 'upstream/alpha' into moumouls/requestContextMiddleWare
Moumouls Oct 8, 2025
fbe389b
fix: lint
Moumouls Oct 8, 2025
344116a
test: fix
Moumouls Oct 8, 2025
9bbc7df
fix: ai suggestion
Moumouls Oct 8, 2025
98b1287
test: use pure fetch
Moumouls Oct 9, 2025
099d109
test: try to fix
Moumouls Oct 9, 2025
d08b157
test: try to fix
Moumouls Oct 9, 2025
29a0d90
test: try again
Moumouls Oct 9, 2025
264b1fa
fix: describe name
Moumouls Oct 9, 2025
1841072
fix: use scoped path
Moumouls Oct 9, 2025
03bc937
test: use single test
Moumouls Oct 9, 2025
5804a19
test: split
Moumouls Oct 9, 2025
3b99da0
Merge branch 'alpha' into moumouls/requestContextMiddleWare
Moumouls Oct 9, 2025
481a5e4
test: avoid race
Moumouls Oct 9, 2025
41aa216
Merge branch 'moumouls/requestContextMiddleWare' of github.com:Moumou…
Moumouls Oct 9, 2025
4d42d53
Merge branch 'alpha' into moumouls/requestContextMiddleWare
mtrezza Oct 9, 2025
cedb2d2
Update spec/ParseGraphQLServer.spec.js
mtrezza Oct 9, 2025
29feaf0
Merge branch 'alpha' into moumouls/requestContextMiddleWare
Moumouls Oct 14, 2025
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
86 changes: 86 additions & 0 deletions spec/CloudCode.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -2014,6 +2014,14 @@ describe('cloud functions', () => {

Parse.Cloud.run('myFunction', {}).then(() => done());
});

it('should have request config', async () => {
Parse.Cloud.define('myConfigFunction', req => {
expect(req.config).toBeDefined();
return 'success';
});
await Parse.Cloud.run('myConfigFunction', {});
});
});

describe('beforeSave hooks', () => {
Expand All @@ -2037,6 +2045,16 @@ describe('beforeSave hooks', () => {
myObject.save().then(() => done());
});

it('should have request config', async () => {
Parse.Cloud.beforeSave('MyObject', req => {
expect(req.config).toBeDefined();
});

const MyObject = Parse.Object.extend('MyObject');
const myObject = new MyObject();
await myObject.save();
});

it('should respect custom object ids (#6733)', async () => {
Parse.Cloud.beforeSave('TestObject', req => {
expect(req.object.id).toEqual('test_6733');
Expand Down Expand Up @@ -2092,6 +2110,16 @@ describe('afterSave hooks', () => {
myObject.save().then(() => done());
});

it('should have request config', async () => {
Parse.Cloud.afterSave('MyObject', req => {
expect(req.config).toBeDefined();
});

const MyObject = Parse.Object.extend('MyObject');
const myObject = new MyObject();
await myObject.save();
});

it('should unset in afterSave', async () => {
Parse.Cloud.afterSave(
'MyObject',
Expand Down Expand Up @@ -2149,6 +2177,17 @@ describe('beforeDelete hooks', () => {
.then(myObj => myObj.destroy())
.then(() => done());
});

it('should have request config', async () => {
Parse.Cloud.beforeDelete('MyObject', req => {
expect(req.config).toBeDefined();
});

const MyObject = Parse.Object.extend('MyObject');
const myObject = new MyObject();
await myObject.save();
await myObject.destroy();
});
});

describe('afterDelete hooks', () => {
Expand Down Expand Up @@ -2177,6 +2216,17 @@ describe('afterDelete hooks', () => {
.then(myObj => myObj.destroy())
.then(() => done());
});

it('should have request config', async () => {
Parse.Cloud.afterDelete('MyObject', req => {
expect(req.ip).toBeDefined();
});

const MyObject = Parse.Object.extend('MyObject');
const myObject = new MyObject();
await myObject.save();
await myObject.destroy();
});
});

describe('beforeFind hooks', () => {
Expand Down Expand Up @@ -2484,6 +2534,18 @@ describe('beforeFind hooks', () => {
.then(() => done());
});

it('should have request config', async () => {
Parse.Cloud.beforeFind('MyObject', req => {
expect(req.config).toBeDefined();
});

const MyObject = Parse.Object.extend('MyObject');
const myObject = new MyObject();
await myObject.save();
const query = new Parse.Query('MyObject');
query.equalTo('objectId', myObject.id);
await Promise.all([query.get(myObject.id), query.first(), query.find()]);
})
it('should run beforeFind on pointers and array of pointers from an object', async () => {
const obj1 = new Parse.Object('TestObject');
const obj2 = new Parse.Object('TestObject2');
Expand Down Expand Up @@ -2868,6 +2930,19 @@ describe('afterFind hooks', () => {
.catch(done.fail);
});

it('should have request config', async () => {
Parse.Cloud.afterFind('MyObject', req => {
expect(req.ip).toBeDefined();
});

const MyObject = Parse.Object.extend('MyObject');
const myObject = new MyObject();
await myObject.save();
const query = new Parse.Query('MyObject');
query.equalTo('objectId', myObject.id);
await Promise.all([query.get(myObject.id), query.first(), query.find()]);
});

it('should validate triggers correctly', () => {
expect(() => {
Parse.Cloud.beforeSave('_Session', () => {});
Expand Down Expand Up @@ -3355,6 +3430,7 @@ describe('beforeLogin hook', () => {
expect(req.ip).toBeDefined();
expect(req.installationId).toBeDefined();
expect(req.context).toBeDefined();
expect(req.config).toBeDefined();
});

await Parse.User.signUp('tupac', 'shakur');
Expand Down Expand Up @@ -3472,6 +3548,7 @@ describe('afterLogin hook', () => {
expect(req.ip).toBeDefined();
expect(req.installationId).toBeDefined();
expect(req.context).toBeDefined();
expect(req.config).toBeDefined();
});

await Parse.User.signUp('testuser', 'p@ssword');
Expand Down Expand Up @@ -3674,6 +3751,15 @@ describe('saveFile hooks', () => {
}
});

it('beforeSaveFile should have config', async () => {
await reconfigureServer({ filesAdapter: mockAdapter });
Parse.Cloud.beforeSave(Parse.File, req => {
expect(req.config).toBeDefined();
});
const file = new Parse.File('popeye.txt', [1, 2, 3], 'text/plain');
await file.save({ useMasterKey: true });
});

it('beforeSave(Parse.File) should change values of uploaded file by editing fileObject directly', async () => {
await reconfigureServer({ filesAdapter: mockAdapter });
const createFileSpy = spyOn(mockAdapter, 'createFile').and.callThrough();
Expand Down
56 changes: 56 additions & 0 deletions spec/requestContextMiddleware.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const { ApolloClient, gql, InMemoryCache } = require('@apollo/client/core');
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
describe('requestContextMiddleware', () => {
const requestContextMiddleware = (req, res, next) => {
req.config.aCustomController = 'aCustomController';
next();
};

it('should support dependency injection on rest api', async () => {
let called;
Parse.Cloud.beforeSave('_User', request => {
expect(request.config.aCustomController).toEqual('aCustomController');
called = true;
});
await reconfigureServer({ requestContextMiddleware });
const user = new Parse.User();
user.setUsername('test');
user.setPassword('test');
await user.signUp();
expect(called).toBeTruthy();
});
it('should support dependency injection on graphql api', async () => {
let called = false;
Parse.Cloud.beforeSave('_User', request => {
expect(request.config.aCustomController).toEqual('aCustomController');
called = true;
});
await reconfigureServer({
requestContextMiddleware,
mountGraphQL: true,
graphQLPath: '/graphql',
});
const client = new ApolloClient({
uri: 'http://localhost:8378/graphql',
cache: new InMemoryCache(),
fetch,
headers: {
'X-Parse-Application-Id': 'test',
'X-Parse-Master-Key': 'test',
},
});

await client.mutate({
mutation: gql`
mutation {
createUser(input: { fields: { username: "test", password: "test" } }) {
user {
objectId
}
}
}
`,
});
expect(called).toBeTruthy();
});
});
2 changes: 2 additions & 0 deletions src/Controllers/HooksController.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,8 @@ function wrapToHTTPRequest(hook, key) {
return req => {
const jsonBody = {};
for (var i in req) {
// Parse Server config is not serializable
if (i === 'config') { continue; }
jsonBody[i] = req[i];
}
if (req.object) {
Expand Down
14 changes: 14 additions & 0 deletions src/GraphQL/ParseGraphQLServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,13 +128,27 @@ class ParseGraphQLServer {
);
}

/**
* @static
* Allow developers to customize each request with inversion of control/dependency injection
*/
applyRequestContextMiddleware(api, options) {
if (options.requestContextMiddleware) {
if (typeof options.requestContextMiddleware !== 'function') {
throw new Error('requestContextMiddleware must be a function');
}
api.use(options.requestContextMiddleware);
}
}

applyGraphQL(app) {
if (!app || !app.use) {
requiredParameter('You must provide an Express.js app instance!');
}
app.use(this.config.graphQLPath, corsMiddleware());
app.use(this.config.graphQLPath, handleParseHeaders);
app.use(this.config.graphQLPath, handleParseSession);
this.applyRequestContextMiddleware(app, this.parseServer.config);
app.use(this.config.graphQLPath, handleParseErrors);
app.use(
this.config.graphQLPath,
Expand Down
5 changes: 5 additions & 0 deletions src/Options/Definitions.js
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,11 @@ module.exports.ParseServerOptions = {
env: 'PARSE_SERVER_READ_ONLY_MASTER_KEY',
help: 'Read-only key, which has the same capabilities as MasterKey without writes',
},
requestContextMiddleware: {
env: 'PARSE_SERVER_REQUEST_CONTEXT_MIDDLEWARE',
help:
'Options to customize the request context using inversion of control/dependency injection.',
},
requestKeywordDenylist: {
env: 'PARSE_SERVER_REQUEST_KEYWORD_DENYLIST',
help:
Expand Down
1 change: 1 addition & 0 deletions src/Options/docs.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions src/Options/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,8 @@ export interface ParseServerOptions {
/* Options to limit repeated requests to Parse Server APIs. This can be used to protect sensitive endpoints such as `/requestPasswordReset` from brute-force attacks or Parse Server as a whole from denial-of-service (DoS) attacks.<br><br>ℹ️ Mind the following limitations:<br>- rate limits applied per IP address; this limits protection against distributed denial-of-service (DDoS) attacks where many requests are coming from various IP addresses<br>- if multiple Parse Server instances are behind a load balancer or ran in a cluster, each instance will calculate it's own request rates, independent from other instances; this limits the applicability of this feature when using a load balancer and another rate limiting solution that takes requests across all instances into account may be more suitable<br>- this feature provides basic protection against denial-of-service attacks, but a more sophisticated solution works earlier in the request flow and prevents a malicious requests to even reach a server instance; it's therefore recommended to implement a solution according to architecture and user case.
:DEFAULT: [] */
rateLimit: ?(RateLimitOptions[]);
/* Options to customize the request context using inversion of control/dependency injection.*/
requestContextMiddleware: ?(req: any, res: any, next: any) => void;
}

export interface RateLimitOptions {
Expand Down
14 changes: 13 additions & 1 deletion src/ParseServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,18 @@ class ParseServer {
}
}

/**
* @static
* Allow developers to customize each request with inversion of control/dependency injection
*/
static applyRequestContextMiddleware(api, options) {
if (options.requestContextMiddleware) {
if (typeof options.requestContextMiddleware !== 'function') {
throw new Error('requestContextMiddleware must be a function');
}
api.use(options.requestContextMiddleware);
}
}
/**
* @static
* Create an express app for the parse server
Expand Down Expand Up @@ -326,7 +338,7 @@ class ParseServer {
middlewares.addRateLimit(route, options);
}
api.use(middlewares.handleParseSession);

this.applyRequestContextMiddleware(api, options);
const appRouter = ParseServer.promiseRouter({ appId });
api.use(appRouter.expressRouter());

Expand Down
2 changes: 2 additions & 0 deletions src/Routers/FunctionsRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ export class FunctionsRouter extends PromiseRouter {
headers: req.config.headers,
ip: req.config.ip,
jobName,
config: req.config,
message: jobHandler.setMessage.bind(jobHandler),
};

Expand Down Expand Up @@ -129,6 +130,7 @@ export class FunctionsRouter extends PromiseRouter {
params = parseParams(params, req.config);
const request = {
params: params,
config: req.config,
master: req.auth && req.auth.isMaster,
user: req.auth && req.auth.user,
installationId: req.info.installationId,
Expand Down
6 changes: 6 additions & 0 deletions src/cloud-code/Parse.Cloud.js
Original file line number Diff line number Diff line change
Expand Up @@ -670,6 +670,7 @@ module.exports = ParseCloud;
* @property {String} triggerName The name of the trigger (`beforeSave`, `afterSave`, ...)
* @property {Object} log The current logger inside Parse Server.
* @property {Parse.Object} original If set, the object, as currently stored.
* @property {Object} config The Parse Server config.
*/

/**
Expand All @@ -684,6 +685,7 @@ module.exports = ParseCloud;
* @property {Object} headers The original HTTP headers for the request.
* @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.
*/

/**
Expand Down Expand Up @@ -721,6 +723,7 @@ module.exports = ParseCloud;
* @property {String} triggerName The name of the trigger (`beforeSave`, `afterSave`, ...)
* @property {Object} log The current logger inside Parse Server.
* @property {Boolean} isGet wether the query a `get` or a `find`
* @property {Object} config The Parse Server config.
*/

/**
Expand All @@ -734,6 +737,7 @@ module.exports = ParseCloud;
* @property {Object} headers The original HTTP headers for the request.
* @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.
*/

/**
Expand All @@ -742,12 +746,14 @@ module.exports = ParseCloud;
* @property {Boolean} master If true, means the master key was used.
* @property {Parse.User} user If set, the user that made the request.
* @property {Object} params The params passed to the cloud function.
* @property {Object} config The Parse Server config.
*/

/**
* @interface Parse.Cloud.JobRequest
* @property {Object} params The params passed to the background job.
* @property {function} message If message is called with a string argument, will update the current message to be stored in the job status.
* @property {Object} config The Parse Server config.
*/

/**
Expand Down
3 changes: 3 additions & 0 deletions src/triggers.js
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,7 @@ export function getRequestObject(
log: config.loggerController,
headers: config.headers,
ip: config.ip,
config,
};

if (originalParseObject) {
Expand Down Expand Up @@ -312,6 +313,7 @@ export function getRequestQueryObject(triggerType, auth, query, count, config, c
headers: config.headers,
ip: config.ip,
context: context || {},
config,
};

if (!auth) {
Expand Down Expand Up @@ -976,6 +978,7 @@ export function getRequestFileObject(triggerType, auth, fileObject, config) {
log: config.loggerController,
headers: config.headers,
ip: config.ip,
config,
};

if (!auth) {
Expand Down
Loading