Skip to content
Open
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
121 changes: 121 additions & 0 deletions spec/ProtectedFields.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,44 @@ describe('ProtectedFields', function () {
expect(fetched.has('favoriteColor')).toBeTruthy();
});

describe('configuration', function () {
const defaults = require('../lib/defaults').default;

it('should not change the default protected fields', async function () {
const defaultProtectedFields = structuredClone(defaults.protectedFields);
await reconfigureServer({ userSensitiveFields: ['ssn'] });
expect(defaults.protectedFields).toEqual(defaultProtectedFields);
expect(Config.get(Parse.applicationId).protectedFields._User['*']).toEqual(
jasmine.arrayWithExactContents(['email', 'ssn'])
);
});

it('should not change the configured protected fields', async function () {
const protectedFields = { _User: { '*': ['ssn'] } };
await reconfigureServer({ protectedFields });
expect(protectedFields).toEqual({ _User: { '*': ['ssn'] } });
expect(Config.get(Parse.applicationId).protectedFields._User['*']).toEqual(
jasmine.arrayWithExactContents(['email', 'ssn'])
);
});

it('should apply the protected fields of a new server configuration', async function () {
const user = new Parse.User();
user.setUsername('Alice');
user.setPassword('sekrit');
user.set('ssn', '999-99-9999');
const acl = new Parse.ACL();
acl.setPublicReadAccess(true);
user.setACL(acl);
await user.signUp();
await Parse.User.logOut();
expect((await new Parse.Query(Parse.User).get(user.id)).get('ssn')).toBe('999-99-9999');

await reconfigureServer({ userSensitiveFields: ['ssn'] });
expect((await new Parse.Query(Parse.User).get(user.id)).has('ssn')).toBeFalse();
});
});

describe('interaction with legacy userSensitiveFields', function () {
it('should fall back on sensitive fields if protected fields are not configured', async function () {
const userSensitiveFields = ['phoneNumber', 'timeZone'];
Expand Down Expand Up @@ -1699,6 +1737,89 @@ describe('ProtectedFields', function () {
expect(object.get('owner')).toBe(undefined);
done();
});

it('should return the pointer field in a later query without keys', async () => {
await updateCLP({
get: { '*': true },
find: { '*': true },
protectedFields: {
'*': ['field', 'test'],
'userField:owner': ['test'],
},
});

// The pointer field is projected only to apply the protected fields
const { data: projected } = await request({
url: `${Parse.serverURL}/classes/${className}/${obj.id}`,
qs: { keys: 'field' },
headers,
});
expect(projected.field).toBe('field');
expect(projected.owner).toBeUndefined();

const { data: object } = await request({
url: `${Parse.serverURL}/classes/${className}/${obj.id}`,
headers,
});
expect(object.field).toBe('field');
expect(object.test).toBeUndefined();
expect(object.owner).toEqual(jasmine.objectContaining({ objectId: user1.id }));
});

it('should return the pointer field to another client after a query with keys', async () => {
await updateCLP({
get: { '*': true },
find: { '*': true },
protectedFields: {
'*': ['test'],
'userField:owner': ['test'],
},
});

await request({
url: `${Parse.serverURL}/classes/${className}`,
qs: { keys: 'field' },
headers,
});

const { data } = await request({
url: `${Parse.serverURL}/classes/${className}`,
headers: {
'X-Parse-Application-Id': Parse.applicationId,
'X-Parse-Rest-API-Key': 'rest',
},
});
expect(data.results.length).toBe(1);
expect(data.results[0].field).toBe('field');
expect(data.results[0].owner).toEqual(jasmine.objectContaining({ objectId: user1.id }));
});

it('should return the pointer field to the master key after a query with keys', async () => {
await updateCLP({
get: { '*': true },
find: { '*': true },
protectedFields: {
'*': ['test'],
'userField:owner': ['test'],
},
});

await request({
url: `${Parse.serverURL}/classes/${className}`,
qs: { keys: 'field' },
headers,
});

const { data } = await request({
url: `${Parse.serverURL}/classes/${className}`,
headers: {
'X-Parse-Application-Id': Parse.applicationId,
'X-Parse-Master-Key': Parse.masterKey,
},
});
expect(data.results.length).toBe(1);
expect(data.results[0].owner).toEqual(jasmine.objectContaining({ objectId: user1.id }));
});
});

describe('query on protected fields via logical operators', function () {
Expand Down
157 changes: 157 additions & 0 deletions spec/Schema.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1795,3 +1795,160 @@ describe('Class Level Permissions for requiredAuth', () => {
);
});
});

describe('SchemaController schema data cache', () => {
const SchemaCache = require('../lib/Adapters/Cache/SchemaCache').default;
const loadSchema = () => Config.get('test').database.loadSchema();

beforeEach(async () => {
await new Parse.Object('CacheTest').save({ name: 'value' });
await new Parse.Object('CacheTestSecond').save({ name: 'value' });
});

it('reuses the schema data across schema controllers and requests', async () => {
const first = await loadSchema();
const second = await loadSchema();
expect(second).not.toBe(first);
expect(second.schemaData).toBe(first.schemaData);

await new Parse.Query('CacheTest').find();
const third = await loadSchema();
expect(third.schemaData).toBe(first.schemaData);

// A new schema controller uses it already before loading the schema
const controller = new SchemaController.SchemaController(Config.get('test').database.adapter);
expect(controller.schemaData).toBe(first.schemaData);
});

it('rebuilds the schema data after a field is added or deleted through the schema API', async () => {
const before = await loadSchema();
const addSchema = new Parse.Schema('CacheTest');
addSchema.addString('added');
await addSchema.update();
const afterAdd = await loadSchema();
expect(afterAdd.schemaData).not.toBe(before.schemaData);
expect(afterAdd.getExpectedType('CacheTest', 'added')).toEqual({ type: 'String' });

const deleteSchema = new Parse.Schema('CacheTest');
deleteSchema.deleteField('added');
await deleteSchema.update();
const afterDelete = await loadSchema();
expect(afterDelete.schemaData).not.toBe(afterAdd.schemaData);
expect(afterDelete.getExpectedType('CacheTest', 'added')).toBeUndefined();
});

it('rebuilds the schema data after a field is added by saving an object', async () => {
const before = await loadSchema();
await new Parse.Object('CacheTest').save({ added: 1 });
const after = await loadSchema();
expect(after.schemaData).not.toBe(before.schemaData);
expect(after.getExpectedType('CacheTest', 'added')).toEqual({ type: 'Number' });
});

it('rebuilds the schema data after a class is added or deleted through the schema API', async () => {
const before = await loadSchema();
await new Parse.Schema('CacheTestOther').save();
const afterAdd = await loadSchema();
expect(afterAdd.schemaData).not.toBe(before.schemaData);
expect(before.schemaData.CacheTestOther).toBeUndefined();
expect(afterAdd.schemaData.CacheTestOther).toBeDefined();

await new Parse.Schema('CacheTestOther').delete();
const afterDelete = await loadSchema();
expect(afterDelete.schemaData).not.toBe(afterAdd.schemaData);
expect(afterDelete.schemaData.CacheTestOther).toBeUndefined();
});

it('rebuilds the schema data after the class-level permissions are set', async () => {
const before = await loadSchema();
expect(before.getClassLevelPermissions('CacheTest').find).toEqual({ '*': true });
const permissions = {
find: { requiresAuthentication: true },
count: { '*': true },
get: { '*': true },
create: { '*': true },
update: { '*': true },
delete: { '*': true },
addField: { '*': true },
protectedFields: { '*': [] },
};
await before.setPermissions('CacheTest', permissions, SchemaCache.get('CacheTest').fields);
const after = await loadSchema();
expect(after.schemaData).not.toBe(before.schemaData);
expect(after.getClassLevelPermissions('CacheTest').find).toEqual({
requiresAuthentication: true,
});
});

it('rebuilds the schema data after the schema cache is cleared or a class is removed from it', async () => {
const before = await loadSchema();
SchemaCache.clear();
const afterClear = await loadSchema();
expect(afterClear.schemaData).not.toBe(before.schemaData);
expect(afterClear.schemaData.CacheTest).toBeDefined();

SchemaCache.del('CacheTest');
const afterDel = await loadSchema();
expect(afterDel.schemaData).not.toBe(afterClear.schemaData);
expect(afterDel.schemaData.CacheTest).toBeUndefined();
expect(afterDel.schemaData.CacheTestSecond).toBeDefined();
});

it('applies the configured protected fields to the schema data built by a new schema controller', async () => {
await reconfigureServer({ protectedFields: { CacheTest: { '*': ['name'] } } });
await loadSchema();
// Store the same schemas under a new identity, so the constructor builds the schema data
SchemaCache.put(SchemaCache.all());
const controller = new SchemaController.SchemaController(Config.get('test').database.adapter);
expect(controller.getClassLevelPermissions('CacheTest').protectedFields['*']).toEqual([
'name',
]);
});

it('does not reuse the schema data for other protected fields', async () => {
const cached = await loadSchema();
const controller = await loadSchema();
controller.protectedFields = { CacheTest: { '*': ['name'] } };
await controller.reloadData();
expect(controller.schemaData).not.toBe(cached.schemaData);
expect(controller.getClassLevelPermissions('CacheTest').protectedFields['*']).toEqual([
'name',
]);
expect(cached.getClassLevelPermissions('CacheTest').protectedFields['*']).toEqual([]);
});

it('reuses the schema data for a copy of the cached schemas', async () => {
const cached = await loadSchema();
const controller = await loadSchema();
spyOn(controller, 'getAllClasses').and.resolveTo([...SchemaCache.all()]);
await controller.reloadData();
expect(controller.schemaData).toBe(cached.schemaData);
});

it('returns a copy of the fields of a volatile class', async () => {
const controller = await loadSchema();
const schema = await controller.getOneSchema('_PushStatus', true);
schema.fields._rperm = { type: 'Array' };
const next = await loadSchema();
expect(next.schemaData).toBe(controller.schemaData);
expect(next.getExpectedType('_PushStatus', '_rperm')).toBeUndefined();
});

it('builds the schema data without caching it for schemas that differ from the cached ones', async () => {
const cached = await loadSchema();
const controller = await loadSchema();
const snapshot = SchemaCache.all().map(schema =>
schema.className === 'CacheTest'
? { ...schema, fields: { ...schema.fields, added: { type: 'String' } } }
: schema
);
spyOn(controller, 'getAllClasses').and.resolveTo(snapshot);
await controller.reloadData();
expect(controller.schemaData).not.toBe(cached.schemaData);
expect(controller.getExpectedType('CacheTest', 'added')).toEqual({ type: 'String' });

const next = await loadSchema();
expect(next.schemaData).toBe(cached.schemaData);
expect(next.getExpectedType('CacheTest', 'added')).toBeUndefined();
});
});
7 changes: 6 additions & 1 deletion src/Adapters/Cache/SchemaCache.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,13 @@ export default {
return [...(SchemaCache.allClasses || [])];
},

// The stored array itself as identity key for derived caches; must not be mutated
raw() {
return SchemaCache.allClasses;
},

get(className) {
return this.all().find(cached => cached.className === className);
return (SchemaCache.allClasses || []).find(cached => cached.className === className);
},

put(allSchema) {
Expand Down
15 changes: 9 additions & 6 deletions src/Controllers/DatabaseController.js
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,8 @@ const filterSensitiveData = (
className: string,
protectedFields: null | Array<any>,
object: any,
protectedFieldsOwnerExempt: ?boolean
protectedFieldsOwnerExempt: ?boolean,
temporaryKeys: ?Array<string>
) => {
let userId = null;
if (auth && auth.user) { userId = auth.user.id; }
Expand Down Expand Up @@ -335,7 +336,7 @@ const filterSensitiveData = (

// fields not requested by client (excluded),
// but were needed to apply protectedFields
perms?.protectedFields?.temporaryKeys?.forEach(k => delete object[k]);
temporaryKeys?.forEach(k => delete object[k]);
}

for (const key in object) {
Expand Down Expand Up @@ -1644,7 +1645,8 @@ class DatabaseController {
className,
protectedFields,
object,
this.options.protectedFieldsOwnerExempt
this.options.protectedFieldsOwnerExempt,
queryOptions.temporaryKeys
);
})
)
Expand Down Expand Up @@ -1971,9 +1973,10 @@ class DatabaseController {
}
}

// preserve fields to be removed before sending response to client
// preserve fields to be removed before sending response to client; stored in the
// query options, as the class-level permissions are shared across requests
if (serverOnlyKeys.length > 0) {
perms.protectedFields.temporaryKeys = serverOnlyKeys;
queryOptions.temporaryKeys = serverOnlyKeys;
}

let protectedKeys = protectedKeysSets.reduce((acc, next) => {
Expand Down Expand Up @@ -2243,7 +2246,7 @@ class DatabaseController {
}

static _validateQuery: (any, boolean, boolean, boolean) => void;
static filterSensitiveData: (boolean, boolean, any[], any, any, any, string, any[], any, ?boolean) => void;
static filterSensitiveData: (boolean, boolean, any[], any, any, any, string, any[], any, ?boolean, ?(string[])) => void;
static validateQueryFormat: any => void;
static logicalOperatorError: (string, any) => any;
}
Expand Down
Loading