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

Add allowedHeaders option to allow filtering Response and Request headers #3188

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/@graphql-yoga_nestjs-3188-dependencies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@graphql-yoga/nestjs': patch
---
dependencies updates:
- Updated dependency [`graphql-yoga@^5.2.0`
↗︎](https://www.npmjs.com/package/graphql-yoga/v/5.2.0) (from `^5.1.1`, in `peerDependencies`)
10 changes: 10 additions & 0 deletions .changeset/@graphql-yoga_nestjs-federation-3188-dependencies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@graphql-yoga/nestjs-federation': patch
---
dependencies updates:
- Updated dependency [`@graphql-yoga/nestjs@3.2.0`
↗︎](https://www.npmjs.com/package/@graphql-yoga/nestjs/v/3.2.0) (from `3.1.1`, in
`dependencies`)
- Updated dependency [`@graphql-yoga/plugin-apollo-inline-trace@3.2.0`
↗︎](https://www.npmjs.com/package/@graphql-yoga/plugin-apollo-inline-trace/v/3.2.0) (from
`3.1.1`, in `dependencies`)
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@graphql-yoga/plugin-apollo-inline-trace': patch
---
dependencies updates:
- Updated dependency [`graphql-yoga@^5.2.0`
↗︎](https://www.npmjs.com/package/graphql-yoga/v/5.2.0) (from `^5.1.1`, in `peerDependencies`)
6 changes: 6 additions & 0 deletions .changeset/@graphql-yoga_plugin-apq-3188-dependencies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@graphql-yoga/plugin-apq': patch
---
dependencies updates:
- Updated dependency [`graphql-yoga@^5.2.0`
↗︎](https://www.npmjs.com/package/graphql-yoga/v/5.2.0) (from `^5.1.1`, in `peerDependencies`)
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@graphql-yoga/plugin-csrf-prevention': patch
---
dependencies updates:
- Updated dependency [`graphql-yoga@^5.2.0`
↗︎](https://www.npmjs.com/package/graphql-yoga/v/5.2.0) (from `^5.1.1`, in `peerDependencies`)
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@graphql-yoga/plugin-defer-stream': patch
---
dependencies updates:
- Updated dependency [`graphql-yoga@^5.2.0`
↗︎](https://www.npmjs.com/package/graphql-yoga/v/5.2.0) (from `^5.1.1`, in `peerDependencies`)
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@graphql-yoga/plugin-disable-introspection': patch
---
dependencies updates:
- Updated dependency [`graphql-yoga@^5.2.0`
↗︎](https://www.npmjs.com/package/graphql-yoga/v/5.2.0) (from `^5.1.1`, in `peerDependencies`)
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@graphql-yoga/plugin-graphql-sse': patch
---
dependencies updates:
- Updated dependency [`graphql-yoga@^5.2.0`
↗︎](https://www.npmjs.com/package/graphql-yoga/v/5.2.0) (from `^5.1.1`, in `peerDependencies`)
6 changes: 6 additions & 0 deletions .changeset/@graphql-yoga_plugin-jwt-3188-dependencies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@graphql-yoga/plugin-jwt': patch
---
dependencies updates:
- Updated dependency [`graphql-yoga@^5.2.0`
↗︎](https://www.npmjs.com/package/graphql-yoga/v/5.2.0) (from `^5.1.1`, in `peerDependencies`)
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@graphql-yoga/plugin-persisted-operations': patch
---
dependencies updates:
- Updated dependency [`graphql-yoga@^5.2.0`
↗︎](https://www.npmjs.com/package/graphql-yoga/v/5.2.0) (from `^5.1.1`, in `peerDependencies`)
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
'@graphql-yoga/plugin-prometheus': patch
---
dependencies updates:
- Updated dependency [`@envelop/prometheus@^9.4.0`
↗︎](https://www.npmjs.com/package/@envelop/prometheus/v/9.4.0) (from `^9.3.1`, in
`dependencies`)
- Updated dependency [`graphql-yoga@^5.2.0`
↗︎](https://www.npmjs.com/package/graphql-yoga/v/5.2.0) (from `^5.1.1`, in `peerDependencies`)
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@graphql-yoga/plugin-response-cache': patch
---
dependencies updates:
- Updated dependency [`graphql-yoga@^5.2.0`
↗︎](https://www.npmjs.com/package/graphql-yoga/v/5.2.0) (from `^5.1.1`, in `peerDependencies`)
6 changes: 6 additions & 0 deletions .changeset/@graphql-yoga_plugin-sofa-3188-dependencies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@graphql-yoga/plugin-sofa': patch
---
dependencies updates:
- Updated dependency [`graphql-yoga@^5.2.0`
↗︎](https://www.npmjs.com/package/graphql-yoga/v/5.2.0) (from `^5.1.1`, in `peerDependencies`)
6 changes: 6 additions & 0 deletions .changeset/@graphql-yoga_render-graphiql-3188-dependencies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@graphql-yoga/render-graphiql': patch
---
dependencies updates:
- Updated dependency [`graphql-yoga@^5.2.0`
↗︎](https://www.npmjs.com/package/graphql-yoga/v/5.2.0) (from `^5.1.1`, in `peerDependencies`)
5 changes: 5 additions & 0 deletions .changeset/breezy-shirts-run.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'graphql-yoga': minor
---

Add `allowedHeaders` option to allow filtering Response and Request headers
10 changes: 10 additions & 0 deletions .changeset/graphql-yoga-3188-dependencies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'graphql-yoga': patch
---
dependencies updates:
- Updated dependency [`@graphql-tools/executor@^1.2.2`
↗︎](https://www.npmjs.com/package/@graphql-tools/executor/v/1.2.2) (from `^1.0.0`, in
`dependencies`)
- Updated dependency [`@graphql-tools/utils@^10.1.0`
↗︎](https://www.npmjs.com/package/@graphql-tools/utils/v/10.1.0) (from `^10.0.0`, in
`dependencies`)
6 changes: 6 additions & 0 deletions .changeset/graphql-yoga-cloud-run-guide-3188-dependencies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'graphql-yoga-cloud-run-guide': patch
---
dependencies updates:
- Updated dependency [`graphql-yoga@^5.2.0`
↗︎](https://www.npmjs.com/package/graphql-yoga/v/5.2.0) (from `^5.1.1`, in `dependencies`)
64 changes: 64 additions & 0 deletions packages/graphql-yoga/src/plugins/allowed-headers.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { createSchema } from '../schema';
import { createYoga } from '../server';
import { useAllowedResponseHeaders } from './allowed-headers';
import { Plugin } from './types';

describe('useAllowedHeaders', () => {
it('should strip headers from responses', async () => {
const response = await query({
plugins: [
useAllowedResponseHeaders(['content-type', 'content-length', 'x-allowed-custom-header']),
],
responseHeaders: {
'x-allowed-custom-header': 'value',
// Verify that we can strip 2 headers in a row
'x-disallowed-custom-header-1': 'value',
'x-disallowed-custom-header-2': 'value',
},
});

expect(response.headers.get('x-allowed-custom-header')).toEqual('value');
expect(response.headers.get('x-disallowed-custom-header-1')).toBeNull();
expect(response.headers.get('x-disallowed-custom-header-2')).toBeNull();
});

const schema = createSchema({
typeDefs: /* GraphQL */ `
type Query {
_: String
}
`,
});

function query({
responseHeaders = {},
requestHeaders = {},
plugins = [],
}: {
requestHeaders?: Record<string, string>;
responseHeaders?: Record<string, string>;
plugins?: Plugin[];
} = {}) {
const yoga = createYoga({
schema,
plugins: [
{
onResponse: ({ response }) => {
for (const [header, value] of Object.entries(responseHeaders)) {
response.headers.set(header, value);
}
},
},
...plugins,
],
});
return yoga.fetch('/graphql', {
body: JSON.stringify({ query: '{ __typename }' }),
method: 'POST',
headers: {
'content-type': 'application/json',
...requestHeaders,
},
});
}
});
25 changes: 25 additions & 0 deletions packages/graphql-yoga/src/plugins/allowed-headers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Plugin } from './types.js';

export function useAllowedResponseHeaders(allowedHeaders: string[]): Plugin {
return {
onResponse({ response }) {
removeDisallowedHeaders(response.headers, allowedHeaders);
},
};
}

export function useAllowedRequestHeaders(allowedHeaders: string[]): Plugin {
return {
onRequest({ request }) {
removeDisallowedHeaders(request.headers, allowedHeaders);
},
};
}

function removeDisallowedHeaders(headers: Headers, allowedHeaders: string[]) {
for (const headerName of headers.keys()) {
if (!allowedHeaders.includes(headerName)) {
headers.delete(headerName);
}
}
}
75 changes: 35 additions & 40 deletions packages/graphql-yoga/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
useErrorHandling,
} from '@whatwg-node/server';
import { handleError } from './error.js';
import { useAllowedRequestHeaders, useAllowedResponseHeaders } from './plugins/allowed-headers.js';
import { isGETRequest, parseGETRequest } from './plugins/request-parser/get.js';
import {
isPOSTFormUrlEncodedRequest,
Expand Down Expand Up @@ -161,6 +162,16 @@ export type YogaServerOptions<TServerContext, TUserContext> = {
* @default false
*/
batching?: BatchingOptions | undefined;

/**
* Allowed headers. Headers not part of this list will be striped out.
*/
allowedHeaders?: {
/** Allowed headers for outgoing responses */
response?: string[] | undefined;
/** Allowed headers for ingoing requests */
request?: string[] | undefined;
};
};

export type BatchingOptions =
Expand Down Expand Up @@ -275,7 +286,8 @@ export class YogaServer<
}),
// Use the schema provided by the user
!!options?.schema && useSchema(options.schema),

options?.allowedHeaders?.request != null &&
useAllowedRequestHeaders(options.allowedHeaders.request),
options?.context != null &&
useExtendContext(initialContext => {
if (options?.context) {
Expand Down Expand Up @@ -341,45 +353,28 @@ export class YogaServer<
}),

...(options?.plugins ?? []),
// To make sure those are called at the end
{
onPluginInit({ addPlugin }) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think this ensures that those plugins are always at the end. Otherwise plugins that add new plugins come after these.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

addPlugin no longer adds plugins at the end of the plugin list. It adds the plugin in place, so this is no longer needed :-)

if (options?.parserAndValidationCache !== false) {
addPlugin(
// @ts-expect-error Add plugins has context but this hook doesn't care
useParserAndValidationCache(
!options?.parserAndValidationCache || options?.parserAndValidationCache === true
? {}
: options?.parserAndValidationCache,
),
);
}
// @ts-expect-error Add plugins has context but this hook doesn't care
addPlugin(useLimitBatching(batchingLimit));
// @ts-expect-error Add plugins has context but this hook doesn't care
addPlugin(useCheckGraphQLQueryParams());
addPlugin(
// @ts-expect-error Add plugins has context but this hook doesn't care
useUnhandledRoute({
graphqlEndpoint,
showLandingPage: options?.landingPage ?? true,
}),
);
// We check the method after user-land plugins because the plugin might support more methods (like graphql-sse).
// @ts-expect-error Add plugins has context but this hook doesn't care
addPlugin(useCheckMethodForGraphQL());
// We make sure that the user doesn't send a mutation with GET
// @ts-expect-error Add plugins has context but this hook doesn't care
addPlugin(usePreventMutationViaGET());
if (maskedErrors) {
addPlugin(useMaskedErrors(maskedErrors));
}
addPlugin(
// We handle validation errors at the end
useHTTPValidationError(),
);
},
},

options?.parserAndValidationCache !== false &&
useParserAndValidationCache(
!options?.parserAndValidationCache || options?.parserAndValidationCache === true
? {}
: options?.parserAndValidationCache,
),
useLimitBatching(batchingLimit),
useCheckGraphQLQueryParams(),
useUnhandledRoute({
graphqlEndpoint,
showLandingPage: options?.landingPage ?? true,
}),
// We check the method after user-land plugins because the plugin might support more methods (like graphql-sse).
useCheckMethodForGraphQL(),
// We make sure that the user doesn't send a mutation with GET
usePreventMutationViaGET(),
maskedErrors !== null && useMaskedErrors(maskedErrors),
options?.allowedHeaders?.response != null &&
useAllowedResponseHeaders(options.allowedHeaders.response),
// We handle validation errors at the end
useHTTPValidationError(),
];

this.getEnveloped = envelop({
Expand Down
12 changes: 6 additions & 6 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.