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

feat(fhir-router/graphql): fix #4567 configurable system setting for graphql max depth #4644

Closed
wants to merge 9 commits into from
3 changes: 3 additions & 0 deletions packages/fhir-router/src/fhirrouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ export type FhirRequest = {
params: Record<string, string>;
query: Record<string, string>;
headers?: IncomingHttpHeaders;
config?: {
graphqlMaxDepth?: number;
};
};

export type FhirResponse = [OperationOutcome] | [OperationOutcome, Resource];
Expand Down
71 changes: 71 additions & 0 deletions packages/fhir-router/src/graphql/graphql.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,77 @@ describe('GraphQL', () => {
expect(res3[0]).toMatchObject(allOk);
});

test('Max depth override', async () => {
// Project level settings can override the default depth
const config = {
graphqlMaxDepth: 6,
};

// 4 levels of depth is ok
const request1: FhirRequest = {
method: 'POST',
pathname: '/fhir/R4/$graphql',
query: {},
params: {},
config,
body: {
query: `
{
ServiceRequestList {
id
basedOn {
resource {
...on ServiceRequest {
id
}
}
}
}
}
`,
},
};

const fhirRouter = new FhirRouter();
const res1 = await graphqlHandler(request1, repo, fhirRouter);
expect(res1[0]).toMatchObject(allOk);

// 8 levels of nesting is too much
const request2: FhirRequest = {
method: 'POST',
pathname: '/fhir/R4/$graphql',
query: {},
params: {},
config,
body: {
query: `
{
ServiceRequestList {
id
basedOn {
resource {
...on ServiceRequest {
id
basedOn {
resource {
...on ServiceRequest {
id
}
}
}
}
}
}
}
}
`,
},
};

const res2 = await graphqlHandler(request2, repo, fhirRouter);
expect(res2[0].issue?.[0]?.details?.text).toEqual('Field "id" exceeds max depth (depth=8, max=6)');
});

test('StructureDefinition query', async () => {
const request: FhirRequest = {
method: 'POST',
Expand Down
55 changes: 29 additions & 26 deletions packages/fhir-router/src/graphql/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export async function graphqlHandler(
}

const schema = getRootSchema();
const validationRules = [...specifiedRules, MaxDepthRule];
const validationRules = [...specifiedRules, MaxDepthRule(req.config?.graphqlMaxDepth)];
const validationErrors = validate(schema, document, validationRules);
if (validationErrors.length > 0) {
return [invalidRequest(validationErrors)];
Expand Down Expand Up @@ -408,31 +408,34 @@ async function resolveByDelete(
await ctx.repo.deleteResource(resourceType, args.id);
}

const DEFAULT_MAX_DEPTH = 12;

/**
* Custom GraphQL rule that enforces max depth constraint.
* @param context - The validation context.
* @returns An ASTVisitor that validates the maximum depth rule.
* @param maxDepth - The maximum allowed depth.
* @returns A function that is an ASTVisitor that validates the maximum depth rule.
*/
const MaxDepthRule = (context: ValidationContext): ASTVisitor => ({
Field(
/** The current node being visiting. */
node: any,
/** The index or key to this node from the parent node or Array. */
_key: string | number | undefined,
/** The parent immediately above this node, which may be an Array. */
_parent: ASTNode | readonly ASTNode[] | undefined,
/** The key path to get to this node from the root node. */
path: readonly (string | number)[]
): any {
const depth = getDepth(path);
const maxDepth = 12;
if (depth > maxDepth) {
const fieldName = node.name.value;
context.reportError(
new GraphQLError(`Field "${fieldName}" exceeds max depth (depth=${depth}, max=${maxDepth})`, {
nodes: node,
})
);
}
},
});
const MaxDepthRule =
(maxDepth: number = DEFAULT_MAX_DEPTH) =>
(context: ValidationContext): ASTVisitor => ({
Field(
/** The current node being visiting. */
node: any,
/** The index or key to this node from the parent node or Array. */
_key: string | number | undefined,
/** The parent immediately above this node, which may be an Array. */
_parent: ASTNode | readonly ASTNode[] | undefined,
/** The key path to get to this node from the root node. */
path: readonly (string | number)[]
): any {
const depth = getDepth(path);
if (depth > maxDepth) {
const fieldName = node.name.value;
context.reportError(
new GraphQLError(`Field "${fieldName}" exceeds max depth (depth=${depth}, max=${maxDepth})`, {
nodes: node,
})
);
}
},
});
14 changes: 14 additions & 0 deletions packages/server/src/fhir/operations/graphql.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -639,6 +639,20 @@ describe('GraphQL', () => {
resource {
...on ServiceRequest {
id
basedOn {
resource {
...on ServiceRequest {
id
basedOn {
resource {
...on ServiceRequest {
id
}
}
}
}
}
}
}
}
}
Expand Down
7 changes: 6 additions & 1 deletion packages/server/src/fhir/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,9 @@ function getInternalFhirRouter(): FhirRouter {
* @returns A new FHIR router with all the internal operations.
*/
function initInternalFhirRouter(): FhirRouter {
const router = new FhirRouter({ introspectionEnabled: getConfig().introspectionEnabled });
const router = new FhirRouter({
introspectionEnabled: getConfig().introspectionEnabled,
});

// Project $export
router.add('GET', '/$export', bulkExportHandler);
Expand Down Expand Up @@ -286,6 +288,9 @@ protectedRoutes.use(
query: req.query as Record<string, string>,
body: req.body,
headers: req.headers,
config: {
graphqlMaxDepth: ctx.project.systemSetting?.find((s) => s.name === 'graphqlMaxDepth')?.valueInteger,
},
};

const result = await getInternalFhirRouter().handleRequest(request, ctx.repo);
Expand Down
Loading