Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: added @default schema validations #2541

Merged
merged 2 commits into from
May 16, 2024
Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
type Post {
id: ID!
title: Boolean! @default(value: false)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
type Test @model {
id: ID!
student: Student @default(value: "{'name':'FooBar'}")
}

type Student {
name: String
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
type Post @model {
id: ID!
title: Boolean! @default(value: "false", name: "test")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
type Post @model {
id: ID!
title: Boolean! @default(value: false)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
type Inicio
@model
@auth(
rules: [{ allow: owner, operations: [create, delete, update, read], provider: userPools, ownerField: autores, groups: ["MeuCPD"] }]
) {
Name: String!
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
type Post @model {
id: ID!
title: Boolean! @default(value: "false")
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
type Inicio
@model
@auth(
rules: [{ allow: owner, operations: [create, delete, update, read], provider: userPools, ownerField: "autores", groups: ["MeuCPD"] }]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you intentionally added groups for owner rule? Are there any validations in transformers to stop this?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, one of our customers had this schema. So just used the same schema for our test. The validation on our end only checks for ownerField type
I'm not sure if any validations exists on the data side to stop this.

) {
Name: String!
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { validateSchema } from '..';
import { readSchema } from './helpers/readSchema';

describe('Validate Schema', () => {
it('fails validation when @default directive is not added to object definitions annotated with @model', () => {
const schema = readSchema('invalid-default-directive1.graphql');
const errorRegex = 'InvalidDirectiveError - The @default directive may only be added to object definitions annotated with @model.';
expect(() => validateSchema(schema)).toThrow(errorRegex);
});

it('fails validation when @default directive is not added to scalar or enum field types', () => {
const schema = readSchema('invalid-default-directive2.graphql');
const errorRegex = 'InvalidDirectiveError - The @default directive may only be added to scalar or enum field types.';
expect(() => validateSchema(schema)).toThrow(errorRegex);
});

it('fails validation when @default directive has more than a value property', () => {
const schema = readSchema('invalid-default-directive3.graphql');
const errorRegex = 'InvalidDirectiveError - The @default directive only takes a value property';
expect(() => validateSchema(schema)).toThrow(errorRegex);
});

it('fails validation when @default directives value property does not have a string value', () => {
const schema = readSchema('invalid-default-directive4.graphql');
const errorRegex = 'InvalidDirectiveError - String cannot represent a non string value: the @default directive has a non String value';
expect(() => validateSchema(schema)).toThrow(errorRegex);
});

it('passes @default directive validations', () => {
const schema = readSchema('valid-default-directive.graphql');
expect(() => validateSchema(schema)).not.toThrow();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { validateSchema } from '..';
import { readSchema } from './helpers/readSchema';

describe('Validate Schema', () => {
it('fails validation when ownerfield does not have a string value', () => {
const schema = readSchema('invalid-owner-field-type-string.graphql');
const errorRegex = 'String cannot represent a non string value';
expect(() => validateSchema(schema)).toThrow(errorRegex);
});

it('passes validation when ownerfield has a string value', () => {
const schema = readSchema('valid-owner-field-type-string.graphql');
expect(() => validateSchema(schema)).not.toThrow();
});
});
4 changes: 4 additions & 0 deletions packages/amplify-schema-validator/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import { validateHasOneNotUsedWithLists } from './validators/hasOne-cannot-be-us
import { validateHasManyIsUsedWithLists } from './validators/hasMany-must-be-used-with-lists';
import { validateObjectIsAnnotatedWithModel } from './validators/object-must-be-annotated-with-model';
import { validateRelationshipNamesAreNotInverseOfRelationName } from './validators/relationshipname-not-inverseof-relationname';
import { validateOwnerFieldTypeString } from './validators/owner-field-type-string';
import { validateDefaultDirective } from './validators/default-directive-validation';

const allValidators = [
validateIndexScalarTypes,
Expand All @@ -55,6 +57,8 @@ const allValidators = [
validateHasManyIsUsedWithLists,
validateObjectIsAnnotatedWithModel,
validateRelationshipNamesAreNotInverseOfRelationName,
validateOwnerFieldTypeString,
validateDefaultDirective,
];

const allValidatorsWithContext = [
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { DocumentNode, Kind, ObjectTypeDefinitionNode, EnumTypeDefinitionNode } from 'graphql';
import { InvalidDirectiveError } from '../exceptions/invalid-directive-error';
import { isScalarOrEnum } from '../helpers/is-scalar-or-enum';
import { getTypeDefinitionsOfKind } from '../helpers/get-type-definitions-of-kind';

/**
* Validates all the @default directive validations
*
* @param schema graphql schema
* @returns true if @default directive validations are satsified
*/

export const validateDefaultDirective = (schema: DocumentNode): Error[] => {
const errors: Error[] = [];
const objectTypeDefinitions = schema.definitions.filter(
(defintion) => defintion.kind === Kind.OBJECT_TYPE_DEFINITION,
) as ObjectTypeDefinitionNode[];

objectTypeDefinitions.forEach((objectTypeDefinition) => {
const directives = objectTypeDefinition.directives?.map((directive) => directive.name.value);

const defaultDirectiveFields = objectTypeDefinition.fields?.filter((objectField) =>
objectField.directives?.find((directive) => directive.name.value === 'default'),
);

if (defaultDirectiveFields && defaultDirectiveFields?.length > 0 && !directives?.includes('model')) {
errors.push(new InvalidDirectiveError('The @default directive may only be added to object definitions annotated with @model.'));
return errors;
}

defaultDirectiveFields?.forEach((defaultDirectiveField) => {
const defaultDirectiveArgs = defaultDirectiveField.directives?.filter(
(defaultDirective) => defaultDirective.arguments && defaultDirective.arguments.length > 0,
);

const enums = getTypeDefinitionsOfKind(schema, Kind.ENUM_TYPE_DEFINITION) as EnumTypeDefinitionNode[];
if (!isScalarOrEnum(defaultDirectiveField.type, enums)) {
errors.push(new InvalidDirectiveError('The @default directive may only be added to scalar or enum field types.'));
return errors;
}

defaultDirectiveArgs?.forEach((defaultDirectiveArg) => {
if (defaultDirectiveArg.name.value === 'default') {
if (defaultDirectiveArg.arguments && defaultDirectiveArg?.arguments?.length > 1) {
errors.push(new InvalidDirectiveError('The @default directive only takes a value property'));
return errors;
}

const fieldsArg = defaultDirectiveArg?.arguments?.find((arg) => arg.name.value === 'value');
if (!fieldsArg) {
/* istanbul ignore next */
return;
}

if (fieldsArg.value.kind !== 'StringValue') {
errors.push(
new InvalidDirectiveError('String cannot represent a non string value: the @default directive has a non String value'),
);
return errors;
}
}
});
});
});
return errors;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { DocumentNode, Kind, ListValueNode, ObjectTypeDefinitionNode, ObjectValueNode } from 'graphql';
import { ValidationError } from '../exceptions/validation-error';

/**
* Types annotated with @auth must also be annotated with @model.
*
* @param schema graphql schema
* @returns true if types annotated with @auth are also be annotated with @model.
*/

export const validateOwnerFieldTypeString = (schema: DocumentNode): Error[] => {
const errors: Error[] = [];
const objectTypeDefinitions = schema.definitions.filter(
(defintion) => defintion.kind === Kind.OBJECT_TYPE_DEFINITION,
) as ObjectTypeDefinitionNode[];
objectTypeDefinitions.forEach((objectTypeDefinition) => {
const directives = objectTypeDefinition.directives;
directives?.forEach((directive) => {
if (directive.name.value === 'auth') {
const directiveArgs = directive.arguments;
directiveArgs?.forEach((directiveArg) => {
if (directiveArg.name.value === 'rules') {
const authArgs = (directiveArg.value as ListValueNode).values.find((elem) => elem.kind);
const authFields = (authArgs as ObjectValueNode).fields;
authFields.forEach((authField) => {
if (authField.name.value === 'ownerField' && authField.value.kind !== 'StringValue') {
errors.push(new ValidationError('String cannot represent a non string value'));
return errors;
}
});
}
});
}
});
});
return errors;
};
Loading