Skip to content

Commit

Permalink
Merge pull request #5963 from MacondoExpress/validation-refactor
Browse files Browse the repository at this point in the history
Validation rules refactor and included new errors for when the directive node is expected but missing
  • Loading branch information
MacondoExpress authored Jan 29, 2025
2 parents 0f47f28 + d260966 commit b1698b8
Show file tree
Hide file tree
Showing 37 changed files with 2,108 additions and 953 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@
*/

import { astFromDirective, astFromInputObjectType } from "@graphql-tools/utils";
import type { TypeDefinitionNode, DirectiveDefinitionNode } from "graphql";
import type { DirectiveDefinitionNode, TypeDefinitionNode } from "graphql";
import {
GraphQLString,
GraphQLSchema,
DirectiveLocation,
GraphQLBoolean,
GraphQLDirective,
GraphQLInputObjectType,
GraphQLList,
GraphQLBoolean,
DirectiveLocation,
GraphQLSchema,
GraphQLString,
} from "graphql";
import {
AUTHORIZATION_FILTER_OPERATION,
Expand Down
5 changes: 0 additions & 5 deletions packages/graphql/src/graphql/directives/vector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,6 @@ export const vectorDirective = new GraphQLDirective({
provider: {
type: VectorProviderEnum,
},
// callback: {
// description:
// "The name of the callback function that will be used to populate the fields values.",
// type: GraphQLString,
// },
},
})
)
Expand Down
95 changes: 95 additions & 0 deletions packages/graphql/src/schema/validation/Neo4jValidationContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import type { Maybe } from "@graphql-tools/utils";
import type {
DefinitionNode,
DocumentNode,
EnumTypeDefinitionNode,
GraphQLError,
GraphQLSchema,
InterfaceTypeDefinitionNode,
InterfaceTypeExtensionNode,
ObjectTypeDefinitionNode,
ObjectTypeExtensionNode,
UnionTypeDefinitionNode,
UnionTypeExtensionNode,
} from "graphql";
import { Kind } from "graphql";
import { SDLValidationContext } from "graphql/validation/ValidationContext";

export type TypeMapWithExtensions = Record<
string,
{
extensions: (ObjectTypeExtensionNode | InterfaceTypeExtensionNode | UnionTypeExtensionNode)[];
definition:
| ObjectTypeDefinitionNode
| InterfaceTypeDefinitionNode
| UnionTypeDefinitionNode
| EnumTypeDefinitionNode;
}
>;
export class Neo4jValidationContext extends SDLValidationContext {
public readonly typeMapWithExtensions?: TypeMapWithExtensions;
public readonly callbacks?: any;
constructor(
ast: DocumentNode,
schema: Maybe<GraphQLSchema>,
onError: (error: GraphQLError) => void,
callbacks?: any
) {
super(ast, schema, onError);
this.callbacks = callbacks;
this.typeMapWithExtensions = buildTypeMapWithExtensions(ast.definitions);
}
}

// build a type map to access specific types and their extensions
function buildTypeMapWithExtensions(definitions: Readonly<DefinitionNode[]>): TypeMapWithExtensions {
return definitions.reduce((acc, def): TypeMapWithExtensions => {
if (
def.kind === Kind.OBJECT_TYPE_DEFINITION ||
def.kind === Kind.INTERFACE_TYPE_DEFINITION ||
def.kind === Kind.UNION_TYPE_DEFINITION ||
def.kind === Kind.ENUM_TYPE_DEFINITION ||
def.kind === Kind.OBJECT_TYPE_EXTENSION ||
def.kind === Kind.INTERFACE_TYPE_EXTENSION ||
def.kind === Kind.UNION_TYPE_EXTENSION
) {
const typeName = def.name.value;
if (!acc[typeName]) {
acc[typeName] = { extensions: [], definition: undefined };
}
if (
def.kind === Kind.OBJECT_TYPE_EXTENSION ||
def.kind === Kind.INTERFACE_TYPE_EXTENSION ||
def.kind === Kind.UNION_TYPE_EXTENSION
) {
if (acc[typeName].extensions) {
acc[typeName].extensions.push(def);
} else {
acc[typeName].extensions = [def];
}
} else {
acc[typeName].definition = def;
}
}
return acc;
}, {});
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import type { ASTVisitor, FieldDefinitionNode, ObjectTypeDefinitionNode } from "graphql";
import { authenticationDirectiveScaffold } from "../../../../graphql/directives/type-dependant-directives/authentication";
import { isRootType } from "../../../../utils/is-root-type";
import { asArray } from "../../../../utils/utils";
import type { Neo4jValidationContext } from "../../Neo4jValidationContext";
import { assertValid, createGraphQLError, DocumentValidationError } from "../utils/document-validation-error";
import { fieldIsInNodeType } from "../utils/location-helpers/is-in-node-type";
import { fieldIsInRootType } from "../utils/location-helpers/is-in-root-type";
import { fieldIsInSubscriptionType } from "../utils/location-helpers/is-in-subscription-type";
import { typeIsANodeType } from "../utils/location-helpers/is-node-type";
import { getPathToNode } from "../utils/path-parser";

export function validateAuthenticationDirective(context: Neo4jValidationContext): ASTVisitor {
const typeMapWithExtensions = context.typeMapWithExtensions;
if (!typeMapWithExtensions) {
throw new Error("No typeMapWithExtensions found in the context");
}
return {
FieldDefinition(fieldDefinitionNode: FieldDefinitionNode, _key, _parent, path, ancestors) {
if (
!fieldDefinitionNode.directives?.find(
(directive) => directive.name.value === authenticationDirectiveScaffold.name
)
) {
return;
}

const isValidLocation =
(fieldIsInNodeType({ path, ancestors, typeMapWithExtensions }) ||
fieldIsInRootType({ path, ancestors, typeMapWithExtensions })) &&
!fieldIsInSubscriptionType({ path, ancestors, typeMapWithExtensions });

const { isValid, errorMsg } = assertValid(() => {
if (!isValidLocation) {
throw new DocumentValidationError(
`Directive "${authenticationDirectiveScaffold.name}" requires in a type with "@node" or in root types: Query, and Mutation`,
[]
);
}
});
const pathToNode = getPathToNode(path, ancestors);

if (!isValid) {
context.reportError(
createGraphQLError({
nodes: [fieldDefinitionNode],
path: [...pathToNode[0], `@${authenticationDirectiveScaffold.name}`],
errorMsg,
})
);
}
},
ObjectTypeDefinition(objectTypeDefinitionNode: ObjectTypeDefinitionNode, _key, _parent, path, ancestors) {
const { directives } = objectTypeDefinitionNode;
const objectTypeExtensionNodes = typeMapWithExtensions[objectTypeDefinitionNode.name.value]?.extensions;
const extensionsDirectives = asArray(objectTypeExtensionNodes).flatMap((extensionNode) => {
return extensionNode.directives ?? [];
});
const allDirectives = [...(directives ?? []), ...extensionsDirectives];
if (!allDirectives.find((directive) => directive.name.value === authenticationDirectiveScaffold.name)) {
return;
}
const isValidLocation =
(typeIsANodeType({ objectTypeDefinitionNode, typeMapWithExtensions }) ||
isRootType(objectTypeDefinitionNode)) &&
objectTypeDefinitionNode.name.value !== "Subscription";
const { isValid, errorMsg } = assertValid(() => {
if (!isValidLocation) {
throw new DocumentValidationError(
`Directive "${authenticationDirectiveScaffold.name}" requires in a type with "@node" or in root types: Query, and Mutation`,
[]
);
}
});
const pathToNode = getPathToNode(path, ancestors);
if (!isValid) {
context.reportError(
createGraphQLError({
nodes: [objectTypeDefinitionNode],
path: [...pathToNode[0], `@${authenticationDirectiveScaffold.name}`],
errorMsg,
})
);
}
},
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,21 +16,107 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { DirectiveNode } from "graphql";
import { AuthorizationAnnotationArguments } from "../../../../schema-model/annotation/AuthorizationAnnotation";
import { DocumentValidationError } from "../utils/document-validation-error";

export function verifyAuthorization() {
return function ({ directiveNode }: { directiveNode: DirectiveNode }) {
for (const arg of AuthorizationAnnotationArguments) {
if (directiveNode.arguments?.find((a) => a.name.value === arg)) {
import type { ASTVisitor, FieldDefinitionNode, ObjectTypeDefinitionNode } from "graphql";
import { authenticationDirectiveScaffold } from "../../../../graphql/directives/type-dependant-directives/authentication";
import { authorizationDirectiveScaffold } from "../../../../graphql/directives/type-dependant-directives/authorization";
import { asArray } from "../../../../utils/utils";
import type { Neo4jValidationContext } from "../../Neo4jValidationContext";
import { assertValid, createGraphQLError, DocumentValidationError } from "../utils/document-validation-error";
import { fieldIsInNodeType } from "../utils/location-helpers/is-in-node-type";
import { fieldIsInRootType } from "../utils/location-helpers/is-in-root-type";
import { typeIsANodeType } from "../utils/location-helpers/is-node-type";
import { getPathToNode } from "../utils/path-parser";

export function validateAuthorizationDirective(context: Neo4jValidationContext): ASTVisitor {
const typeMapWithExtensions = context.typeMapWithExtensions;
if (!typeMapWithExtensions) {
throw new Error("No typeMapWithExtensions found in the context");
}
return {
FieldDefinition(fieldDefinitionNode: FieldDefinitionNode, _key, _parent, path, ancestors) {
const authorizationDirective = fieldDefinitionNode.directives?.find(
(directive) => directive.name.value === authorizationDirectiveScaffold.name
);

if (!authorizationDirective) {
return;
}
}

throw new DocumentValidationError(
`@authorization requires at least one of ${AuthorizationAnnotationArguments.join(", ")} arguments`,
[]
);
const isValidLocation = fieldIsInNodeType({ path, ancestors, typeMapWithExtensions });

const { isValid, errorMsg } = assertValid(() => {
if (!isValidLocation) {
// add specific error message for Root types usage
if (fieldIsInRootType({ path, ancestors, typeMapWithExtensions })) {
throw new DocumentValidationError(
`Directive @${authorizationDirectiveScaffold.name} is not supported on fields of the Query type. Did you mean to use @${authenticationDirectiveScaffold.name}?`,
[]
);
}

throw new DocumentValidationError(
`Directive "@${authorizationDirectiveScaffold.name}" requires in a type with "@node"`,
[]
);
}
if (authorizationDirective.arguments?.length === 0) {
throw new DocumentValidationError(
`@${authorizationDirectiveScaffold.name} requires at least one of ${[...authorizationDirectiveScaffold.args.map((arg) => arg.name)].join(", ")} arguments`,
[]
);
}
});
const pathToNode = getPathToNode(path, ancestors);

if (!isValid) {
context.reportError(
createGraphQLError({
nodes: [fieldDefinitionNode],
path: [...pathToNode[0], `@${authorizationDirectiveScaffold.name}`],
errorMsg,
})
);
}
},
ObjectTypeDefinition(objectTypeDefinitionNode: ObjectTypeDefinitionNode, _key, _parent, path, ancestors) {
const { directives } = objectTypeDefinitionNode;
const objectTypeExtensionNodes = typeMapWithExtensions[objectTypeDefinitionNode.name.value]?.extensions;
const extensionsDirectives = asArray(objectTypeExtensionNodes).flatMap((extensionNode) => {
return extensionNode.directives ?? [];
});
const allDirectives = [...(directives ?? []), ...extensionsDirectives];
const authorizationDirective = allDirectives.find(
(directive) => directive.name.value === authorizationDirectiveScaffold.name
);
if (!authorizationDirective) {
return;
}
const isValidLocation = typeIsANodeType({ objectTypeDefinitionNode, typeMapWithExtensions });
const { isValid, errorMsg } = assertValid(() => {
if (!isValidLocation) {
throw new DocumentValidationError(
`Directive "@${authorizationDirectiveScaffold.name}" requires in a type with "@node"`,
[]
);
}
if (authorizationDirective.arguments?.length === 0) {
throw new DocumentValidationError(
`@${authorizationDirectiveScaffold.name} requires at least one of ${authorizationDirectiveScaffold.args.join(", ")} arguments`,
[]
);
}
});
const pathToNode = getPathToNode(path, ancestors);
if (!isValid) {
context.reportError(
createGraphQLError({
nodes: [objectTypeDefinitionNode],
path: [...pathToNode[0], `@${authorizationDirectiveScaffold.name}`],
errorMsg,
})
);
}
},
};
}
Loading

0 comments on commit b1698b8

Please sign in to comment.