Skip to content

Commit 1dd58b7

Browse files
authored
Adds support for read-only masterKey (#4297)
* Adds support for read-only masterKey * Adds tests to make sure all endpoints are properly protected * Updates readme * nits
1 parent 87b79ce commit 1dd58b7

13 files changed

+194
-6
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,7 @@ The client keys used with Parse are no longer necessary with Parse Server. If yo
225225
* `customPages` - A hash with urls to override email verification links, password reset links and specify frame url for masking user-facing pages. Available keys: `parseFrameURL`, `invalidLink`, `choosePassword`, `passwordResetSuccess`, `verifyEmailSuccess`.
226226
* `middleware` - (CLI only), a module name, function that is an express middleware. When using the CLI, the express app will load it just **before** mounting parse-server on the mount path. This option is useful for injecting a monitoring middleware.
227227
* `masterKeyIps` - The array of ip addresses where masterKey usage will be restricted to only these ips. (Default to [] which means allow all ips). If you're using this feature and have `useMasterKey: true` in cloudcode, make sure that you put your own ip in this list.
228+
* `readOnlyMasterKey` - A masterKey that has full read access to the data, but no write access. This key should be treated the same way as your masterKey, keeping it private.
228229

229230
##### Logging
230231

spec/helper.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ var defaultConfiguration = {
9090
restAPIKey: 'rest',
9191
webhookKey: 'hook',
9292
masterKey: 'test',
93+
readOnlyMasterKey: 'read-only-test',
9394
fileKey: 'test',
9495
silent,
9596
logLevel,

spec/rest.spec.js

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ var auth = require('../src/Auth');
44
var Config = require('../src/Config');
55
var Parse = require('parse/node').Parse;
66
var rest = require('../src/rest');
7+
var RestWrite = require('../src/RestWrite');
78
var request = require('request');
89
var rp = require('request-promise');
910

@@ -623,5 +624,139 @@ describe('rest update', () => {
623624
done();
624625
});
625626
});
627+
});
628+
629+
describe('read-only masterKey', () => {
630+
it('properly throws on rest.create, rest.update and rest.del', () => {
631+
const config = Config.get('test');
632+
const readOnly = auth.readOnly(config);
633+
expect(() => {
634+
rest.create(config, readOnly, 'AnObject', {})
635+
}).toThrow(new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, `read-only masterKey isn't allowed to perform the create operation.`));
636+
expect(() => {
637+
rest.update(config, readOnly, 'AnObject', {})
638+
}).toThrow();
639+
expect(() => {
640+
rest.del(config, readOnly, 'AnObject', {})
641+
}).toThrow();
642+
});
643+
644+
it('properly blocks writes', (done) => {
645+
reconfigureServer({
646+
readOnlyMasterKey: 'yolo-read-only'
647+
}).then(() => {
648+
return rp.post(`${Parse.serverURL}/classes/MyYolo`, {
649+
headers: {
650+
'X-Parse-Application-Id': Parse.applicationId,
651+
'X-Parse-Master-Key': 'yolo-read-only',
652+
},
653+
json: { foo: 'bar' }
654+
});
655+
}).then(done.fail).catch((res) => {
656+
expect(res.error.code).toBe(Parse.Error.OPERATION_FORBIDDEN);
657+
expect(res.error.error).toBe('read-only masterKey isn\'t allowed to perform the create operation.');
658+
done();
659+
});
660+
});
626661

662+
it('should throw when masterKey and readOnlyMasterKey are the same', (done) => {
663+
reconfigureServer({
664+
masterKey: 'yolo',
665+
readOnlyMasterKey: 'yolo'
666+
}).then(done.fail).catch((err) => {
667+
expect(err).toEqual(new Error('masterKey and readOnlyMasterKey should be different'));
668+
done();
669+
});
670+
});
671+
672+
it('should throw when trying to create RestWrite', () => {
673+
const config = Config.get('test');
674+
expect(() => {
675+
new RestWrite(config, auth.readOnly(config));
676+
}).toThrow(new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, 'Cannot perform a write operation when using readOnlyMasterKey'));
677+
});
678+
679+
it('should throw when trying to create schema', (done) => {
680+
return rp.post(`${Parse.serverURL}/schemas`, {
681+
headers: {
682+
'X-Parse-Application-Id': Parse.applicationId,
683+
'X-Parse-Master-Key': 'read-only-test',
684+
},
685+
json: {}
686+
}).then(done.fail).catch((res) => {
687+
expect(res.error.code).toBe(Parse.Error.OPERATION_FORBIDDEN);
688+
expect(res.error.error).toBe('read-only masterKey isn\'t allowed to create a schema.');
689+
done();
690+
});
691+
});
692+
693+
it('should throw when trying to create schema with a name', (done) => {
694+
return rp.post(`${Parse.serverURL}/schemas/MyClass`, {
695+
headers: {
696+
'X-Parse-Application-Id': Parse.applicationId,
697+
'X-Parse-Master-Key': 'read-only-test',
698+
},
699+
json: {}
700+
}).then(done.fail).catch((res) => {
701+
expect(res.error.code).toBe(Parse.Error.OPERATION_FORBIDDEN);
702+
expect(res.error.error).toBe('read-only masterKey isn\'t allowed to create a schema.');
703+
done();
704+
});
705+
});
706+
707+
it('should throw when trying to update schema', (done) => {
708+
return rp.put(`${Parse.serverURL}/schemas/MyClass`, {
709+
headers: {
710+
'X-Parse-Application-Id': Parse.applicationId,
711+
'X-Parse-Master-Key': 'read-only-test',
712+
},
713+
json: {}
714+
}).then(done.fail).catch((res) => {
715+
expect(res.error.code).toBe(Parse.Error.OPERATION_FORBIDDEN);
716+
expect(res.error.error).toBe('read-only masterKey isn\'t allowed to update a schema.');
717+
done();
718+
});
719+
});
720+
721+
it('should throw when trying to delete schema', (done) => {
722+
return rp.del(`${Parse.serverURL}/schemas/MyClass`, {
723+
headers: {
724+
'X-Parse-Application-Id': Parse.applicationId,
725+
'X-Parse-Master-Key': 'read-only-test',
726+
},
727+
json: {}
728+
}).then(done.fail).catch((res) => {
729+
expect(res.error.code).toBe(Parse.Error.OPERATION_FORBIDDEN);
730+
expect(res.error.error).toBe('read-only masterKey isn\'t allowed to delete a schema.');
731+
done();
732+
});
733+
});
734+
735+
it('should throw when trying to update the global config', (done) => {
736+
return rp.put(`${Parse.serverURL}/config`, {
737+
headers: {
738+
'X-Parse-Application-Id': Parse.applicationId,
739+
'X-Parse-Master-Key': 'read-only-test',
740+
},
741+
json: {}
742+
}).then(done.fail).catch((res) => {
743+
expect(res.error.code).toBe(Parse.Error.OPERATION_FORBIDDEN);
744+
expect(res.error.error).toBe('read-only masterKey isn\'t allowed to update the config.');
745+
done();
746+
});
747+
});
748+
749+
it('should throw when trying to send push', (done) => {
750+
return rp.post(`${Parse.serverURL}/push`, {
751+
headers: {
752+
'X-Parse-Application-Id': Parse.applicationId,
753+
'X-Parse-Master-Key': 'read-only-test',
754+
},
755+
json: {}
756+
}).then(done.fail).catch((res) => {
757+
expect(res.error.code).toBe(Parse.Error.OPERATION_FORBIDDEN);
758+
expect(res.error.error).toBe('read-only masterKey isn\'t allowed to send push notifications.');
759+
done();
760+
});
761+
});
627762
});

src/Auth.js

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,12 @@ var RestQuery = require('./RestQuery');
44
// An Auth object tells you who is requesting something and whether
55
// the master key was used.
66
// userObject is a Parse.User and can be null if there's no user.
7-
function Auth({ config, isMaster = false, user, installationId } = {}) {
7+
function Auth({ config, isMaster = false, isReadOnly = false, user, installationId } = {}) {
88
this.config = config;
99
this.installationId = installationId;
1010
this.isMaster = isMaster;
1111
this.user = user;
12+
this.isReadOnly = isReadOnly;
1213

1314
// Assuming a users roles won't change during a single request, we'll
1415
// only load them once.
@@ -34,6 +35,11 @@ function master(config) {
3435
return new Auth({ config, isMaster: true });
3536
}
3637

38+
// A helper to get a master-level Auth object
39+
function readOnly(config) {
40+
return new Auth({ config, isMaster: true, isReadOnly: true });
41+
}
42+
3743
// A helper to get a nobody-level Auth object
3844
function nobody(config) {
3945
return new Auth({ config, isMaster: false });
@@ -207,9 +213,10 @@ Auth.prototype._getAllRolesNamesForRoleIds = function(roleIDs, names = [], queri
207213
}
208214

209215
module.exports = {
210-
Auth: Auth,
211-
master: master,
212-
nobody: nobody,
216+
Auth,
217+
master,
218+
nobody,
219+
readOnly,
213220
getAuthForSessionToken,
214221
getAuthForLegacySessionToken
215222
};

src/Config.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,15 @@ export class Config {
6060
emailVerifyTokenValidityDuration,
6161
accountLockout,
6262
passwordPolicy,
63-
masterKeyIps
63+
masterKeyIps,
64+
masterKey,
65+
readOnlyMasterKey,
6466
}) {
67+
68+
if (masterKey === readOnlyMasterKey) {
69+
throw new Error('masterKey and readOnlyMasterKey should be different');
70+
}
71+
6572
const emailAdapter = userController.adapter;
6673
if (verifyUserEmails) {
6774
this.validateEmailConfiguration({emailAdapter, appName, publicServerURL, emailVerifyTokenValidityDuration});

src/Options/Definitions.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,10 @@ module.exports.ParseServerOptions = {
123123
"env": "PARSE_SERVER_REST_API_KEY",
124124
"help": "Key for REST calls"
125125
},
126+
"readOnlyMasterKey": {
127+
"env": "PARSE_SERVER_READ_ONLY_MASTER_KEY",
128+
"help": "Read-only key, which has the same capabilities as MasterKey without writes"
129+
},
126130
"webhookKey": {
127131
"env": "PARSE_SERVER_WEBHOOK_KEY",
128132
"help": "Key sent with outgoing webhook calls"

src/Options/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ export interface ParseServerOptions {
5858
/* Key for REST calls
5959
:ENV: PARSE_SERVER_REST_API_KEY */
6060
restAPIKey: ?string;
61+
/* Read-only key, which has the same capabilities as MasterKey without writes */
62+
readOnlyMasterKey: ?string;
6163
/* Key sent with outgoing webhook calls */
6264
webhookKey: ?string;
6365
/* Key for your files */

src/RestWrite.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@ import logger from './logger';
2525
// everything. It also knows to use triggers and special modifications
2626
// for the _User class.
2727
function RestWrite(config, auth, className, query, data, originalData, clientSDK) {
28+
if (auth.isReadOnly) {
29+
throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, 'Cannot perform a write operation when using readOnlyMasterKey');
30+
}
2831
this.config = config;
2932
this.auth = auth;
3033
this.className = className;

src/Routers/GlobalConfigRouter.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// global_config.js
2-
2+
import Parse from 'parse/node';
33
import PromiseRouter from '../PromiseRouter';
44
import * as middleware from "../middlewares";
55

@@ -16,6 +16,9 @@ export class GlobalConfigRouter extends PromiseRouter {
1616
}
1717

1818
updateGlobalConfig(req) {
19+
if (req.auth.isReadOnly) {
20+
throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, 'read-only masterKey isn\'t allowed to update the config.');
21+
}
1922
const params = req.body.params;
2023
// Transform in dot notation to make sure it works
2124
const update = Object.keys(params).reduce((acc, key) => {

src/Routers/PushRouter.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ export class PushRouter extends PromiseRouter {
99
}
1010

1111
static handlePOST(req) {
12+
if (req.auth.isReadOnly) {
13+
throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, 'read-only masterKey isn\'t allowed to send push notifications.');
14+
}
1215
const pushController = req.config.pushController;
1316
if (!pushController) {
1417
throw new Parse.Error(Parse.Error.PUSH_MISCONFIGURED, 'Push controller is not set');

src/Routers/SchemasRouter.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ function getOneSchema(req) {
3434
}
3535

3636
function createSchema(req) {
37+
if (req.auth.isReadOnly) {
38+
throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, 'read-only masterKey isn\'t allowed to create a schema.');
39+
}
3740
if (req.params.className && req.body.className) {
3841
if (req.params.className != req.body.className) {
3942
return classNameMismatchResponse(req.body.className, req.params.className);
@@ -51,6 +54,9 @@ function createSchema(req) {
5154
}
5255

5356
function modifySchema(req) {
57+
if (req.auth.isReadOnly) {
58+
throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, 'read-only masterKey isn\'t allowed to update a schema.');
59+
}
5460
if (req.body.className && req.body.className != req.params.className) {
5561
return classNameMismatchResponse(req.body.className, req.params.className);
5662
}
@@ -64,6 +70,9 @@ function modifySchema(req) {
6470
}
6571

6672
const deleteSchema = req => {
73+
if (req.auth.isReadOnly) {
74+
throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, 'read-only masterKey isn\'t allowed to delete a schema.');
75+
}
6776
if (!SchemaController.classNameIsValid(req.params.className)) {
6877
throw new Parse.Error(Parse.Error.INVALID_CLASS_NAME, SchemaController.invalidClassNameMessage(req.params.className));
6978
}

src/middlewares.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,13 @@ export function handleParseHeaders(req, res, next) {
126126
return;
127127
}
128128

129+
var isReadOnlyMaster = (info.masterKey === req.config.readOnlyMasterKey);
130+
if (typeof req.config.readOnlyMasterKey != 'undefined' && req.config.readOnlyMasterKey && isReadOnlyMaster) {
131+
req.auth = new auth.Auth({ config: req.config, installationId: info.installationId, isMaster: true, isReadOnly: true });
132+
next();
133+
return;
134+
}
135+
129136
// Client keys are not required in parse-server, but if any have been configured in the server, validate them
130137
// to preserve original behavior.
131138
const keys = ["clientKey", "javascriptKey", "dotNetKey", "restAPIKey"];

src/rest.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,12 @@ function enforceRoleSecurity(method, className, auth) {
159159
const error = `Clients aren't allowed to perform the ${method} operation on the ${className} collection.`
160160
throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, error);
161161
}
162+
163+
// readOnly masterKey is not allowed
164+
if (auth.isReadOnly && (method === 'delete' || method === 'create' || method === 'update')) {
165+
const error = `read-only masterKey isn't allowed to perform the ${method} operation.`
166+
throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN, error);
167+
}
162168
}
163169

164170
module.exports = {

0 commit comments

Comments
 (0)