diff --git a/spec/ProtectedFields.spec.js b/spec/ProtectedFields.spec.js index e3a9cbda3d..828afd73d8 100644 --- a/spec/ProtectedFields.spec.js +++ b/spec/ProtectedFields.spec.js @@ -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']; @@ -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 () { diff --git a/spec/Schema.spec.js b/spec/Schema.spec.js index 03c68276f8..63a3c89492 100644 --- a/spec/Schema.spec.js +++ b/spec/Schema.spec.js @@ -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(); + }); +}); diff --git a/src/Adapters/Cache/SchemaCache.js b/src/Adapters/Cache/SchemaCache.js index f55edf0635..9e5f9375f4 100644 --- a/src/Adapters/Cache/SchemaCache.js +++ b/src/Adapters/Cache/SchemaCache.js @@ -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) { diff --git a/src/Controllers/DatabaseController.js b/src/Controllers/DatabaseController.js index b1cd1aa79b..9efc777f53 100644 --- a/src/Controllers/DatabaseController.js +++ b/src/Controllers/DatabaseController.js @@ -252,7 +252,8 @@ const filterSensitiveData = ( className: string, protectedFields: null | Array, object: any, - protectedFieldsOwnerExempt: ?boolean + protectedFieldsOwnerExempt: ?boolean, + temporaryKeys: ?Array ) => { let userId = null; if (auth && auth.user) { userId = auth.user.id; } @@ -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) { @@ -1644,7 +1645,8 @@ class DatabaseController { className, protectedFields, object, - this.options.protectedFieldsOwnerExempt + this.options.protectedFieldsOwnerExempt, + queryOptions.temporaryKeys ); }) ) @@ -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) => { @@ -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; } diff --git a/src/Controllers/SchemaController.js b/src/Controllers/SchemaController.js index b178ac7850..50b946c022 100644 --- a/src/Controllers/SchemaController.js +++ b/src/Controllers/SchemaController.js @@ -615,6 +615,38 @@ class SchemaData { } } +// SchemaData per schema snapshot; SchemaCache.put stores a new array on schema +// changes, which invalidates the entry. The cached instance is shared by all +// SchemaController instances, so the fields, class-level permissions and indexes +// it returns must not be mutated. +const schemaDataCache: WeakMap, { protectedFields: any, schemaData: SchemaData }> = + new WeakMap(); + +const sameSchemas = (a: Array, b: Array) => { + if (a === b) { + return true; + } + if (a.length !== b.length) { + return false; + } + return a.every((schema, index) => schema === b[index]); +}; + +const getSchemaData = (allSchemas: Array, protectedFields: any) => { + const cachedSchemas = SchemaCache.raw(); + if (!cachedSchemas || !sameSchemas(cachedSchemas, allSchemas)) { + // Snapshot mismatch, e.g. a concurrent schema change; derive without caching + return new SchemaData(allSchemas, protectedFields); + } + const cached = schemaDataCache.get(cachedSchemas); + if (cached && cached.protectedFields === protectedFields) { + return cached.schemaData; + } + const schemaData = new SchemaData(allSchemas, protectedFields); + schemaDataCache.set(cachedSchemas, { protectedFields, schemaData }); + return schemaData; +}; + const injectDefaultSchema = ({ className, fields, classLevelPermissions, indexes }: Schema) => { const defaultSchema: Schema = { className, @@ -720,8 +752,11 @@ export default class SchemaController { constructor(databaseAdapter: StorageAdapter) { this._dbAdapter = databaseAdapter; const config = Config.get(Parse.applicationId); - this.schemaData = new SchemaData(SchemaCache.all(), this.protectedFields); this.protectedFields = config.protectedFields; + const cachedSchemas = SchemaCache.raw(); + this.schemaData = cachedSchemas + ? getSchemaData(cachedSchemas, this.protectedFields) + : new SchemaData(); const customIds = config.allowCustomObjectId; @@ -757,7 +792,7 @@ export default class SchemaController { this.reloadDataPromise = this.getAllClasses(options) .then( allSchemas => { - this.schemaData = new SchemaData(allSchemas, this.protectedFields); + this.schemaData = getSchemaData(allSchemas, this.protectedFields); delete this.reloadDataPromise; }, err => { @@ -804,7 +839,8 @@ export default class SchemaController { const data = this.schemaData[className]; return Promise.resolve({ className, - fields: data.fields, + // A copy, as storage adapters change the fields of the schema they get + fields: { ...data.fields }, classLevelPermissions: data.classLevelPermissions, indexes: data.indexes, }); @@ -1102,6 +1138,8 @@ export default class SchemaController { const cached = SchemaCache.get(className); if (cached) { cached.classLevelPermissions = perms; + // Re-put under a new array identity so cached derived data is discarded. + SchemaCache.put(SchemaCache.all()); } } diff --git a/src/ParseServer.ts b/src/ParseServer.ts index 65d537ae68..118a83a7ae 100644 --- a/src/ParseServer.ts +++ b/src/ParseServer.ts @@ -628,6 +628,10 @@ function injectDefaults(options: ParseServerOptions) { } } + // Merge into a copy, so that neither the configured nor the default protected fields + // change; schema controllers cache data per protected fields object + options.protectedFields = structuredClone(options.protectedFields); + // Backwards compatibility if (options.userSensitiveFields) { /* eslint-disable no-console */ @@ -658,7 +662,7 @@ function injectDefaults(options: ParseServerOptions) { Object.keys(defaults.protectedFields).forEach(c => { const cur = options.protectedFields[c]; if (!cur) { - options.protectedFields[c] = defaults.protectedFields[c]; + options.protectedFields[c] = structuredClone(defaults.protectedFields[c]); } else { Object.keys(defaults.protectedFields[c]).forEach(r => { if (options.protectedFields[c][r] && options.protectedFieldsOwnerExempt === false) {