diff --git a/spec/DefinedSchemas.spec.js b/spec/DefinedSchemas.spec.js index a2bbb2167c..9218e67c2f 100644 --- a/spec/DefinedSchemas.spec.js +++ b/spec/DefinedSchemas.spec.js @@ -1,5 +1,6 @@ const { DefinedSchemas } = require('../lib/SchemaMigrations/DefinedSchemas'); const Config = require('../lib/Config'); +const SchemaController = require('../lib/Controllers/SchemaController').default; const cleanUpIndexes = schema => { if (schema.indexes) { @@ -675,6 +676,274 @@ describe('DefinedSchemas', () => { }); }); + describe('Unchanged schemas', () => { + const definition = () => ({ + className: 'Test', + fields: { + aString: { type: 'String' }, + aNumber: { type: 'Number', required: true, defaultValue: 1 }, + aPointer: { type: 'Pointer', targetClass: '_User' }, + }, + indexes: { aString_1: { aString: 1 } }, + classLevelPermissions: { + find: { requiresAuthentication: true }, + get: { requiresAuthentication: true }, + protectedFields: { '*': ['aNumber'] }, + }, + }); + + let updatedClasses; + beforeEach(() => { + updatedClasses = null; + const updateClass = SchemaController.prototype.updateClass; + spyOn(SchemaController.prototype, 'updateClass').and.callFake(function (className, ...args) { + if (updatedClasses) { + updatedClasses.push(className); + } + return updateClass.call(this, className, ...args); + }); + }); + + // Runs the migrations and resolves with the classes that have been updated + const migrate = async (schemaOptions, server) => { + updatedClasses = []; + await new DefinedSchemas(schemaOptions, server.config).execute(); + const result = updatedClasses; + updatedClasses = null; + return result; + }; + + const optionCombinations = [ + {}, + { strict: true }, + { deleteExtraFields: true }, + { recreateModifiedFields: true }, + { deleteExtraFields: true, recreateModifiedFields: true, strict: true }, + ]; + + optionCombinations.forEach(options => { + it(`should not update an unchanged schema with options ${JSON.stringify(options)}`, async () => { + const server = await reconfigureServer(); + const schemaOptions = { ...options, definitions: [definition()] }; + await new DefinedSchemas(schemaOptions, server.config).execute(); + const before = await new Parse.Schema('Test').get(); + + expect(await migrate(schemaOptions, server)).toEqual([]); + expect(await new Parse.Schema('Test').get()).toEqual(before); + }); + }); + + it('should not update an unchanged schema without class-level permissions', async () => { + const server = await reconfigureServer(); + const schemaOptions = { + deleteExtraFields: true, + recreateModifiedFields: true, + definitions: [{ className: 'Test', fields: { aString: { type: 'String' } } }], + }; + await new DefinedSchemas(schemaOptions, server.config).execute(); + + expect(await migrate(schemaOptions, server)).toEqual([]); + }); + + it('should not update unchanged classes that are not in the schema', async () => { + const server = await reconfigureServer(); + await new Parse.Schema('Other').save(); + const schemaOptions = { definitions: [definition()] }; + + expect(await migrate(schemaOptions, server)).toContain('Other'); + const other = await new Parse.Schema('Other').get(); + expect(other.classLevelPermissions.addField).toEqual({}); + + expect(await migrate(schemaOptions, server)).toEqual([]); + }); + + it('should not update a class with unknown indexes kept by keepUnknownIndexes', async () => { + const server = await reconfigureServer(); + await new DefinedSchemas({ definitions: [definition()] }, server.config).execute(); + const schemaOptions = { + keepUnknownIndexes: true, + definitions: [{ ...definition(), indexes: {} }], + }; + + expect(await migrate(schemaOptions, server)).toEqual([]); + const schema = await new Parse.Schema('Test').get(); + expect(schema.indexes.aString_1).toEqual({ aString: 1 }); + }); + + it('should update changed class-level permissions', async () => { + const server = await reconfigureServer(); + await new DefinedSchemas({ definitions: [definition()] }, server.config).execute(); + const changed = definition(); + changed.classLevelPermissions.count = { requiresAuthentication: true }; + + expect(await migrate({ definitions: [changed] }, server)).toEqual(['Test']); + const schema = await new Parse.Schema('Test').get(); + expect(schema.classLevelPermissions.count).toEqual({ requiresAuthentication: true }); + }); + + it('should update class-level permissions with a removed operation', async () => { + const server = await reconfigureServer(); + await new DefinedSchemas({ definitions: [definition()] }, server.config).execute(); + const changed = definition(); + delete changed.classLevelPermissions.find; + + expect(await migrate({ definitions: [changed] }, server)).toEqual(['Test']); + const schema = await new Parse.Schema('Test').get(); + expect(schema.classLevelPermissions.find).toEqual({}); + }); + + it('should compare class-level permissions as returned by the storage adapters', () => { + const definedSchemas = new DefinedSchemas({}, {}); + const stored = { + find: { requiresAuthentication: true }, + count: {}, + get: {}, + create: {}, + update: {}, + delete: {}, + addField: {}, + protectedFields: { '*': ['aField'] }, + readUserFields: ['owner'], + }; + expect( + definedSchemas.clpAreEquals( + { + readUserFields: ['owner'], + protectedFields: { '*': ['aField'] }, + addField: {}, + find: { requiresAuthentication: true }, + }, + stored + ) + ).toBeTrue(); + expect( + definedSchemas.clpAreEquals( + { + find: { requiresAuthentication: true }, + addField: {}, + protectedFields: { '*': ['aField'] }, + readUserFields: [], + }, + stored + ) + ).toBeFalse(); + expect( + definedSchemas.clpAreEquals( + { find: {}, addField: {}, protectedFields: { '*': ['aField'] }, readUserFields: ['owner'] }, + stored + ) + ).toBeFalse(); + expect( + definedSchemas.clpAreEquals( + { + find: { requiresAuthentication: true }, + addField: {}, + protectedFields: { '*': ['aField'] }, + readUserFields: ['owner'], + writeUserFields: ['owner'], + }, + stored + ) + ).toBeFalse(); + expect(definedSchemas.clpAreEquals({ addField: {} }, undefined)).toBeFalse(); + }); + + it('should update class-level permissions changed outside of the schema', async () => { + const server = await reconfigureServer(); + const schemaOptions = { definitions: [definition()] }; + await new DefinedSchemas(schemaOptions, server.config).execute(); + const adapter = Config.get(server.config.appId).database.adapter; + await adapter.setClassLevelPermissions('Test', { + ...definition().classLevelPermissions, + addField: { '*': true }, + }); + Config.get(server.config.appId).schemaCache.clear(); + + expect(await migrate(schemaOptions, server)).toEqual(['Test']); + const schema = await new Parse.Schema('Test').get(); + expect(schema.classLevelPermissions.addField).toEqual({}); + }); + + it('should update an added field', async () => { + const server = await reconfigureServer(); + await new DefinedSchemas({ definitions: [definition()] }, server.config).execute(); + const changed = definition(); + changed.fields.anotherString = { type: 'String' }; + + expect(await migrate({ definitions: [changed] }, server)).toEqual(['Test']); + const schema = await new Parse.Schema('Test').get(); + expect(schema.fields.anotherString).toEqual({ type: 'String' }); + }); + + it('should update a field with changed params', async () => { + const server = await reconfigureServer(); + await new DefinedSchemas({ definitions: [definition()] }, server.config).execute(); + const changed = definition(); + changed.fields.aString = { type: 'String', required: true }; + + expect(await migrate({ definitions: [changed] }, server)).toEqual(['Test']); + const schema = await new Parse.Schema('Test').get(); + expect(schema.fields.aString).toEqual({ type: 'String', required: true }); + }); + + it('should update a removed field when "deleteExtraFields" is true', async () => { + const server = await reconfigureServer(); + await new DefinedSchemas({ definitions: [definition()] }, server.config).execute(); + const changed = definition(); + delete changed.fields.aPointer; + + const updatedClasses = await migrate( + { deleteExtraFields: true, recreateModifiedFields: true, definitions: [changed] }, + server + ); + // The class-level permissions are applied again after the deletion + expect(updatedClasses).toEqual(['Test', 'Test']); + const schema = await new Parse.Schema('Test').get(); + expect(schema.fields.aPointer).toBeUndefined(); + }); + + it('should update a field with changed type when "recreateModifiedFields" is true', async () => { + const server = await reconfigureServer(); + await new DefinedSchemas({ definitions: [definition()] }, server.config).execute(); + const changed = definition(); + changed.fields.aString = { type: 'Number' }; + + const updatedClasses = await migrate( + { deleteExtraFields: true, recreateModifiedFields: true, definitions: [changed] }, + server + ); + expect(updatedClasses).toEqual(['Test', 'Test']); + const schema = await new Parse.Schema('Test').get(); + expect(schema.fields.aString).toEqual({ type: 'Number' }); + }); + + it('should update an added, removed or changed index', async () => { + const server = await reconfigureServer(); + await new DefinedSchemas({ definitions: [definition()] }, server.config).execute(); + + const added = definition(); + added.indexes.aNumber_1 = { aNumber: 1 }; + expect(await migrate({ definitions: [added] }, server)).toEqual(['Test']); + let schema = await new Parse.Schema('Test').get(); + cleanUpIndexes(schema); + expect(schema.indexes).toEqual(added.indexes); + + const changed = definition(); + changed.indexes.aString_1 = { aString: -1 }; + // The changed index is deleted, then created again + expect(await migrate({ definitions: [changed] }, server)).toEqual(['Test', 'Test']); + schema = await new Parse.Schema('Test').get(); + cleanUpIndexes(schema); + expect(schema.indexes).toEqual(changed.indexes); + + const removed = { ...definition(), indexes: {} }; + expect(await migrate({ definitions: [removed] }, server)).toEqual(['Test']); + schema = await new Parse.Schema('Test').get(); + cleanUpIndexes(schema); + expect(schema.indexes).toBeUndefined(); + }); + }); + it('should not delete classes automatically', async () => { await reconfigureServer({ schema: { definitions: [{ className: '_User' }, { className: 'Test' }] }, diff --git a/src/SchemaMigrations/DefinedSchemas.js b/src/SchemaMigrations/DefinedSchemas.js index e67f5a003e..fd886e3db3 100644 --- a/src/SchemaMigrations/DefinedSchemas.js +++ b/src/SchemaMigrations/DefinedSchemas.js @@ -1,6 +1,7 @@ // @flow // @flow-disable-next Cannot resolve module `parse/node`. const Parse = require('parse/node'); +import { isDeepStrictEqual } from 'util'; import { logger } from '../logger'; import Config from '../Config'; import { internalCreateSchema, internalUpdateSchema } from '../Routers/SchemasRouter'; @@ -10,6 +11,19 @@ import * as Migrations from './Migrations'; import Auth from '../Auth'; import rest from '../rest'; +// Operations that the storage adapters always return in the class-level permissions of a +// class, with an empty value when they were not stored. +const clpOperations = [ + 'find', + 'count', + 'get', + 'create', + 'update', + 'delete', + 'addField', + 'protectedFields', +]; + export class DefinedSchemas { config: ParseServerOptions; schemaOptions: Migrations.SchemaOptions; @@ -53,7 +67,12 @@ export class DefinedSchemas { // Simulate update like the SDK // We cannot use SDK since routes are disabled - async updateSchemaToDB(schema: Parse.Schema) { + // If `cloudSchema` is provided, the update is skipped when it would not change the class. + // Resolves with whether the update has been sent to the database. + async updateSchemaToDB(schema: Parse.Schema, cloudSchema?: Parse.Schema): Promise { + if (this.isUnchangedUpdate(schema, cloudSchema)) { + return false; + } const payload = { className: schema.className, fields: schema._fields, @@ -62,6 +81,38 @@ export class DefinedSchemas { }; await internalUpdateSchema(schema.className, payload, this.config); this.resetSchemaOps(schema); + return true; + } + + // An update without field and index operations can only change the class-level permissions, + // so it changes nothing if it sets none or sets the ones the class already has. + isUnchangedUpdate(schema: Parse.Schema, cloudSchema?: Parse.Schema): boolean { + if (!cloudSchema) { + return false; + } + if (Object.keys(schema._fields || {}).length || Object.keys(schema._indexes || {}).length) { + return false; + } + return ( + schema._clp === undefined || + this.clpAreEquals(schema._clp, cloudSchema.classLevelPermissions) + ); + } + + clpAreEquals(clpA: ?Parse.CLP.PermissionsMap, clpB: ?Parse.CLP.PermissionsMap): boolean { + if (!clpA || !clpB) { + return false; + } + const normalize = (clp: Parse.CLP.PermissionsMap) => { + const normalized = { ...clp }; + clpOperations.forEach(operation => { + if (normalized[operation] === undefined) { + normalized[operation] = {}; + } + }); + return normalized; + }; + return isDeepStrictEqual(normalize(clpA), normalize(clpB)); } async execute() { @@ -166,7 +217,7 @@ export class DefinedSchemas { nonProvidedClasses.map(async schema => { const parseSchema = new Parse.Schema(schema.className); this.handleCLP(schema, parseSchema); - await this.updateSchemaToDB(parseSchema); + await this.updateSchemaToDB(parseSchema, schema); }) ); } @@ -224,6 +275,8 @@ export class DefinedSchemas { async updateSchema(localSchema: Migrations.JSONSchema, cloudSchema: Parse.Schema) { const newLocalSchema = new Parse.Schema(localSchema.className); + // Whether a previous step of this update has changed the class + let updated = false; // Handle fields // Check addition @@ -285,7 +338,7 @@ export class DefinedSchemas { }); // Delete fields from the schema then apply changes - await this.updateSchemaToDB(newLocalSchema); + updated = (await this.updateSchemaToDB(newLocalSchema, cloudSchema)) || updated; } else if (this.schemaOptions.strict === true && fieldsToDelete.length) { logger.warn( `The following fields exist in the database for "${ @@ -300,7 +353,7 @@ export class DefinedSchemas { }); // Delete fields from the schema then apply changes - await this.updateSchemaToDB(newLocalSchema); + updated = (await this.updateSchemaToDB(newLocalSchema, cloudSchema)) || updated; fieldsToRecreate.forEach(fieldInfo => { if (localSchema.fields) { @@ -369,8 +422,9 @@ export class DefinedSchemas { } this.handleCLP(localSchema, newLocalSchema, cloudSchema); - // Apply changes - await this.updateSchemaToDB(newLocalSchema); + // Apply changes; if a previous step changed the class, always apply the class-level + // permissions so that they are validated against the changed fields + await this.updateSchemaToDB(newLocalSchema, updated ? undefined : cloudSchema); // Apply new/changed indexes if (indexesToAdd.length) { logger.debug(