Skip to content
Draft
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
55 changes: 45 additions & 10 deletions packages/graphql-shield/src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,24 @@ import {
import { isRuleFunction, isRuleFieldMap, isRule, isLogicRule, withDefault } from './utils.js'
import { ValidationError } from './validation.js'

interface IInternalOptions {
excludeRulesWithFragments: boolean
excludeRulesWithoutFragments: boolean
}

function shouldApplyRule(rule: ShieldRule, internalOptions: IInternalOptions) {
const hasFragment = 'extractFragment' in rule ? !!rule.extractFragment() : !!rule.extractFragments().length

if (
(internalOptions.excludeRulesWithFragments && hasFragment) ||
(internalOptions.excludeRulesWithoutFragments && !hasFragment)
) {
return false
}

return true
}

/**
*
* @param options
Expand Down Expand Up @@ -108,11 +126,20 @@ function generateFieldMiddlewareFromRule(
* Generates middleware from rule for a particular type.
*
*/
function applyRuleToType(type: GraphQLObjectType, rules: ShieldRule | IRuleFieldMap, options: IOptions): IMiddlewareFieldMap {
function applyRuleToType(
type: GraphQLObjectType,
rules: ShieldRule | IRuleFieldMap,
options: IOptions,
internalOptions: IInternalOptions,
): IMiddlewareFieldMap {
if (isRuleFunction(rules)) {
/* Apply defined rule function to every field */
const fieldMap = type.getFields()

if (!shouldApplyRule(rules, internalOptions)) {
return {}
}

const middleware = Object.keys(fieldMap).reduce<IMiddlewareFieldMap>((middleware, field) => {
return {
...middleware,
Expand Down Expand Up @@ -142,13 +169,15 @@ function applyRuleToType(type: GraphQLObjectType, rules: ShieldRule | IRuleField

/* Generation */

const middleware = Object.keys(fieldMap).reduce<IMiddlewareFieldMap>(
(middleware, field) => ({
const middleware = Object.keys(fieldMap).reduce<IMiddlewareFieldMap>((middleware, field) => {
if (!shouldApplyRule(rules[field], internalOptions)) {
return middleware
}
return {
...middleware,
[field]: generateFieldMiddlewareFromRule(withDefault(defaultTypeRule || options.fallbackRule)(rules[field]), options),
}),
{},
)
}
}, {})

return middleware
} else {
Expand Down Expand Up @@ -176,7 +205,12 @@ function applyRuleToType(type: GraphQLObjectType, rules: ShieldRule | IRuleField
* Applies the same rule over entire schema.
*
*/
function applyRuleToSchema(schema: GraphQLSchema, rule: ShieldRule, options: IOptions): IMiddlewareTypeMap {
function applyRuleToSchema(
schema: GraphQLSchema,
rule: ShieldRule,
options: IOptions,
internalOptions: IInternalOptions,
): IMiddlewareTypeMap {
const typeMap = schema.getTypeMap()

const middleware = Object.keys(typeMap)
Expand All @@ -187,7 +221,7 @@ function applyRuleToSchema(schema: GraphQLSchema, rule: ShieldRule, options: IOp
if (isObjectType(type)) {
return {
...middleware,
[typeName]: applyRuleToType(type, rule, options),
[typeName]: applyRuleToType(type, rule, options, internalOptions),
}
} else {
return middleware
Expand All @@ -209,10 +243,11 @@ export function generateMiddlewareFromSchemaAndRuleTree(
schema: GraphQLSchema,
rules: IRules,
options: IOptions,
internalOptions: IInternalOptions,
): IMiddlewareTypeMap {
if (isRuleFunction(rules)) {
/* Applies rule to entire schema. */
return applyRuleToSchema(schema, rules, options)
return applyRuleToSchema(schema, rules, options, internalOptions)
} else {
/**
* Checks type map and field map and applies rules
Expand Down Expand Up @@ -242,7 +277,7 @@ export function generateMiddlewareFromSchemaAndRuleTree(
if (isObjectType(type)) {
return {
...middleware,
[typeName]: applyRuleToType(type, rules[typeName], options),
[typeName]: applyRuleToType(type, rules[typeName], options, internalOptions),
}
} else {
return middleware
Expand Down
68 changes: 44 additions & 24 deletions packages/graphql-shield/src/shield.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { GraphQLFieldResolver, GraphQLSchema } from 'graphql'
import { buildSchema, execute, ExecutionArgs, GraphQLFieldResolver, GraphQLSchema, printSchema } from 'graphql'
import hash from 'object-hash'

import { composeResolvers, ResolversComposition } from '@graphql-tools/resolvers-composition'
import { addResolversToSchema } from '@graphql-tools/schema'
import { wrapSchema } from '@graphql-tools/wrap'

import {
IOptions,
Expand Down Expand Up @@ -97,33 +96,54 @@ function applyComposition(schema: GraphQLSchema, middleware: IMiddlewareTypeMap)
return addResolversToSchema({ schema, resolvers })
}

/**
*
* @param schema
* @param ruleTree
* @param options
*
* Validates rules and applies defined rule tree to the schema.
*
*/
export function shield(schema: GraphQLSchema, ruleTree: IRules, options: IOptionsConstructor = {}): GraphQLSchema {
type ExecuteFn = typeof execute

// TODO: process logical rules and fallback rule
export function wrapExecuteFn(
executeFn: ExecuteFn,
config: { schema: GraphQLSchema; ruleTree: IRules; options?: IOptionsConstructor },
): (executionArgs: ExecutionArgs) => ReturnType<ExecuteFn> {
const { schema, ruleTree, options = {} } = config

const normalizedOptions = normalizeOptions(options)
const ruleTreeValidity = validateRuleTree(ruleTree)

if (ruleTreeValidity.status === 'ok') {
const middleware = generateMiddlewareFromSchemaAndRuleTree(schema, ruleTree, normalizedOptions)
if (normalizedOptions.disableFragmentsAndPostExecRules) {
return applyComposition(schema, middleware)
}
if (ruleTreeValidity.status !== 'ok') {
throw new ValidationError(ruleTreeValidity.message)
}

const middleware = generateMiddlewareFromSchemaAndRuleTree(schema, ruleTree, normalizedOptions, {
excludeRulesWithFragments: true,
excludeRulesWithoutFragments: false,
})
const authSchema = applyComposition(schema, middleware)

const fragmentReplacements = getFragmentReplacements(middleware)
const postExecSchema = buildSchema(printSchema(schema))
const postExecMiddleware = generateMiddlewareFromSchemaAndRuleTree(schema, ruleTree, normalizedOptions, {
excludeRulesWithFragments: false,
excludeRulesWithoutFragments: true,
})
const postExecAuthSchema = applyComposition(postExecSchema, postExecMiddleware)

const wrappedSchema = wrapSchema({
schema,
transforms: [new ReplaceFieldWithFragment(fragmentReplacements || [])],
return async function executeWithAuth(executionArgs: ExecutionArgs) {
const result = await executeFn({ ...executionArgs, schema: authSchema })

const postExecResult = await executeFn({
...executionArgs,
schema: postExecAuthSchema,
rootValue: result.data,
})
return applyComposition(wrappedSchema, middleware)
} else {
throw new ValidationError(ruleTreeValidity.message)

const errors = [...(result.errors ?? []), ...(postExecResult.errors ?? [])]
const extensions = {
...result.extensions,
...postExecResult.extensions,
}

return {
data: postExecResult.data,
...(errors.length > 0 ? { errors } : {}),
...(Object.keys(extensions).length > 0 ? { extensions } : {}),
}
}
}
Loading