@lenne.tech/nest-server 11.46.5 → 11.46.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,127 @@
1
1
  import { Plugin } from '@nestjs/apollo';
2
2
  import { GraphQLSchemaHost } from '@nestjs/graphql';
3
3
  import type { ApolloServerPlugin, BaseContext, GraphQLRequestListener } from '@apollo/server';
4
- import { GraphQLError } from 'graphql';
5
- import { fieldExtensionsEstimator, getComplexity, simpleEstimator } from 'graphql-query-complexity';
4
+ import { getVariableValues, GraphQLError, Kind, TypeInfo, ValidationContext, visit, visitWithTypeInfo } from 'graphql';
5
+ import type {
6
+ ASTVisitor,
7
+ DefinitionNode,
8
+ DocumentNode,
9
+ FragmentDefinitionNode,
10
+ GraphQLSchema,
11
+ OperationDefinitionNode,
12
+ SelectionSetNode,
13
+ } from 'graphql';
14
+ import { createComplexityRule, fieldExtensionsEstimator, simpleEstimator } from 'graphql-query-complexity';
6
15
 
7
16
  import { ConfigService } from '../services/config.service';
8
17
 
18
+ /**
19
+ * Most variable coercion errors the pre-check collects before it stops. It only needs to know WHETHER the variables
20
+ * coerce, and one error answers that. Every error graphql creates for a variable computes its line and column by
21
+ * scanning the query up to the variable's definition: with execution's cap of 50 the pre-check cost 550 ms for a
22
+ * 959 KiB multipart request whose definitions stood after 490,000 line breaks (11.46.6).
23
+ */
24
+ const VARIABLE_COERCION_MAX_ERRORS = 1;
25
+
26
+ /**
27
+ * Most visits × declared variables the complexity analysis may cost (11.46.6, SEC-4). graphql-query-complexity runs
28
+ * `Object.keys()` over the operation's variables at every field and every `@skip` / `@include` it visits — measured on
29
+ * Node 24 at 12–90 ns per variable and visit, so the limit is reached after at most about 23 ms. 38,000 declared
30
+ * variables and 4,900 visits blocked the event loop for 17 s before. With the default cost of 1 per field, a query
31
+ * `maxComplexity: 1000` accepts has at most 1,000 fields; with 30 variables that is at most 30,000.
32
+ */
33
+ const COMPLEXITY_ANALYSIS_MAX_VARIABLE_WORK = 250_000;
34
+
35
+ /** The visitor graphql-query-complexity builds (the class itself is not exported). */
36
+ type ComplexityVisitor = ReturnType<ReturnType<typeof createComplexityRule>>;
37
+
38
+ /** Fields and `@skip` / `@include` directives in the selection sets — each one a visit with the variables walked. */
39
+ function variableVisits(definitions: readonly (FragmentDefinitionNode | OperationDefinitionNode)[]): number {
40
+ let visits = 0;
41
+ const pending: SelectionSetNode[] = definitions.map((definition) => definition.selectionSet);
42
+ while (pending.length) {
43
+ const selectionSet = pending.pop()!;
44
+ for (const selection of selectionSet.selections) {
45
+ for (const directive of selection.directives ?? []) {
46
+ if (directive.name.value === 'include' || directive.name.value === 'skip') {
47
+ visits++;
48
+ }
49
+ }
50
+ if (selection.kind === Kind.FIELD) {
51
+ visits++;
52
+ }
53
+ if (selection.kind !== Kind.FRAGMENT_SPREAD && selection.selectionSet) {
54
+ pending.push(selection.selectionSet);
55
+ }
56
+ }
57
+ }
58
+ return visits;
59
+ }
60
+
61
+ /**
62
+ * The complexity graphql-query-complexity's `getComplexity()` computes, with each fragment evaluated once (11.46.6,
63
+ * SEC-4).
64
+ *
65
+ * The library evaluates a fragment again at EVERY spread, without caching, and at every visit coerces the field's
66
+ * literal arguments again. Its node cap (10,000 visits) bounds the visits, not their cost:
67
+ * `{...F ×3300} fragment F on Query { findUsers(filter: { … value: [0,0,…41,667 items] }) }` blocked the event loop
68
+ * for 2.2 s from a 100 KB JSON POST and for 22.5 s from a 990 KB multipart request — before any guard, with variables
69
+ * that coerce.
70
+ *
71
+ * A fragment's complexity depends on the fragment alone: its type is its type condition, and the variables and the
72
+ * estimators are the same for every spread. So the first spread evaluates it, every further spread reuses the result
73
+ * and adds the nodes the evaluation visited to the library's node count, so a query over 10,000 nodes is refused as
74
+ * before. The number this returns is the one `getComplexity()` returns; the work is that of the document, each
75
+ * fragment once. A field's `complexity` extension (read by `fieldExtensionsEstimator`) must therefore depend only on its
76
+ * arguments and `childComplexity` — as a function it runs once per fragment, not once per spread.
77
+ *
78
+ * The analysis stops at the first error it reports. The library catches the coercion error of every field's arguments
79
+ * and goes on, and `getComplexity()` throws the last one at the end — but every error with a node computes its line and
80
+ * column by scanning the query up to it. `query($x: String = "a") { a: getUser(id: $x) { id } b: … }` with
81
+ * `{"x": null}` is valid, passes the variable check and fails at every one of up to 9,999 fields: 1.4 s from a 98 KiB
82
+ * JSON POST, 86 s from a 993 KiB multipart request with the fields after 395,000 line breaks (11.46.6). The request is
83
+ * refused either way; now with the first error instead of the last.
84
+ *
85
+ * Built like `getComplexity()` (graphql-query-complexity 2.0.0, `QueryComplexity.js`), through the public
86
+ * `createComplexityRule()`; the cache wraps `nodeComplexity` of this one visitor, which the library calls through
87
+ * `this` for every fragment spread.
88
+ */
89
+ function computeComplexity(schema: GraphQLSchema, query: DocumentNode, variables: Record<string, unknown>): number {
90
+ const typeInfo = new TypeInfo(schema);
91
+ const context = new ValidationContext(schema, query, typeInfo, (error) => {
92
+ throw error;
93
+ });
94
+ const visitor: ComplexityVisitor = createComplexityRule({
95
+ estimators: [fieldExtensionsEstimator(), simpleEstimator({ defaultComplexity: 1 })],
96
+ // The maximum is checked by the plugin; the visitor only computes.
97
+ maximumComplexity: Infinity,
98
+ variables,
99
+ })(context);
100
+
101
+ const evaluate = visitor.nodeComplexity.bind(visitor);
102
+ const fragments = new Map<string, { complexity: number; nodes: number }>();
103
+ visitor.nodeComplexity = (node, typeDef, activeFragments) => {
104
+ if (node.kind !== Kind.FRAGMENT_DEFINITION) {
105
+ return evaluate(node, typeDef, activeFragments);
106
+ }
107
+ const known = fragments.get(node.name.value);
108
+ if (known) {
109
+ visitor.evaluatedNodes += known.nodes;
110
+ if (visitor.evaluatedNodes >= visitor.maxQueryNodes) {
111
+ throw new GraphQLError('Query exceeds the maximum allowed number of nodes.');
112
+ }
113
+ return known.complexity;
114
+ }
115
+ const before = visitor.evaluatedNodes;
116
+ const complexity = evaluate(node, typeDef, activeFragments);
117
+ fragments.set(node.name.value, { complexity, nodes: visitor.evaluatedNodes - before });
118
+ return complexity;
119
+ };
120
+
121
+ visit(query, visitWithTypeInfo(typeInfo, visitor as unknown as ASTVisitor));
122
+ return visitor.complexity;
123
+ }
124
+
9
125
  @Plugin()
10
126
  export class ComplexityPlugin implements ApolloServerPlugin {
11
127
  constructor(
@@ -18,14 +134,39 @@ export class ComplexityPlugin implements ApolloServerPlugin {
18
134
  const { schema } = this.gqlSchemaHost;
19
135
 
20
136
  return {
21
- async didResolveOperation({ document, request }) {
22
- const complexity = getComplexity({
23
- estimators: [fieldExtensionsEstimator(), simpleEstimator({ defaultComplexity: 1 })],
24
- operationName: request.operationName,
25
- query: document,
26
- schema,
27
- variables: request.variables,
137
+ async didResolveOperation({ document, operation, request }) {
138
+ // No operation resolved: several operations and no `operationName` naming one of them. Apollo still calls this
139
+ // hook, and graphql's `execute()` refuses the request afterwards, before it coerces a single variable.
140
+ // getComplexity() instead evaluated EVERY operation of such a document and coerced the variables for each
141
+ // (11.46.6, SEC-3): 860 operations sharing one 16,000-item variable blocked the event loop for 5.9 s from a
142
+ // 100 KB JSON POST, 1,720 operations for 25.5 s from 200 KB.
143
+ if (!operation) {
144
+ return;
145
+ }
146
+
147
+ // Invalid variables (11.46.6, SEC-2): getComplexity() coerces without an error cap, so a list of invalid items
148
+ // created one error per item — 1.5 s and 300 MB for 100 KB, 15 s and 2 GB for 1 MB. Execution refuses such
149
+ // variables itself, with graphql's cap of 50, before any resolver runs, so there is no complexity to compute.
150
+ const { errors } = getVariableValues(schema, operation.variableDefinitions ?? [], request.variables ?? {}, {
151
+ maxErrors: VARIABLE_COERCION_MAX_ERRORS,
28
152
  });
153
+ if (errors?.length) {
154
+ return;
155
+ }
156
+
157
+ // The resolved operation alone, with the fragments it may spread: the analysis evaluates exactly the operation
158
+ // execution runs, and coerces its variables once.
159
+ const fragments = document.definitions.filter(
160
+ (definition: DefinitionNode): definition is FragmentDefinitionNode =>
161
+ definition.kind === Kind.FRAGMENT_DEFINITION,
162
+ );
163
+ const variableCount = operation.variableDefinitions?.length ?? 0;
164
+ if (variableVisits([operation, ...fragments]) * variableCount > COMPLEXITY_ANALYSIS_MAX_VARIABLE_WORK) {
165
+ throw new GraphQLError('Query is too complex: too many fields for its number of variables');
166
+ }
167
+
168
+ const query: DocumentNode = { definitions: [operation, ...fragments], kind: Kind.DOCUMENT };
169
+ const complexity = computeComplexity(schema, query, request.variables ?? {});
29
170
  if (maxComplexity !== undefined && complexity > maxComplexity) {
30
171
  throw new GraphQLError(`Query is too complex: ${complexity}. Maximum allowed complexity: ${maxComplexity}`);
31
172
  }
@@ -30,6 +30,15 @@ const SECRET_KEY_PATTERN =
30
30
  */
31
31
  const URI_CREDENTIAL_PATTERN = /^([a-z][a-z0-9+.-]*:\/\/[^/@:\s]*:)([^@/\s]+)(@)/i;
32
32
 
33
+ /**
34
+ * Value-shape heuristic: a PEM block holding a private key — `-----BEGIN PRIVATE KEY-----` and its `RSA`, `EC`,
35
+ * `ENCRYPTED`, `OPENSSH` variants, and PGP's `-----BEGIN PGP PRIVATE KEY BLOCK-----`. Checked in every string and
36
+ * `Buffer`, whatever its key is called (11.46.6): a certificate login keeps certificate and key in ONE PEM, usually
37
+ * under a name such as `certificate` that no key heuristic may call secret — a certificate alone is public. Until
38
+ * 11.46.6 such a key reached the Hub config panel in clear text. The whole value is masked.
39
+ */
40
+ const PRIVATE_KEY_PEM_PATTERN = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY[A-Z ]*-----/i;
41
+
33
42
  const MASK = '***';
34
43
 
35
44
  /**
@@ -37,7 +46,7 @@ const MASK = '***';
37
46
  *
38
47
  * A value is masked when its key matches {@link SECRET_KEY_PATTERN} or appears in `extraSecretKeys`.
39
48
  * Additionally, any string that looks like a credentialed connection URI has its password segment
40
- * masked regardless of key name.
49
+ * masked regardless of key name, and a string or `Buffer` holding a PEM private key is masked as a whole.
41
50
  *
42
51
  * @param value - the object/value to mask (not mutated)
43
52
  * @param extraSecretKeys - additional exact key names to always mask (e.g. `security.secretFields`)
@@ -69,6 +78,9 @@ function maskValue(value: unknown, keyIsSecret: boolean, extra: Set<string>): un
69
78
  if (keyIsSecret) {
70
79
  return MASK;
71
80
  }
81
+ if (typeof value === 'string' && PRIVATE_KEY_PEM_PATTERN.test(value)) {
82
+ return MASK;
83
+ }
72
84
  return typeof value === 'string' ? maskString(value) : value;
73
85
  }
74
86
 
@@ -78,9 +90,10 @@ function maskValue(value: unknown, keyIsSecret: boolean, extra: Set<string>): un
78
90
  }
79
91
 
80
92
  // Preserve non-plain objects verbatim (Date, Buffer, etc.) — cloning would lose their type and
81
- // they never carry framework secrets.
93
+ // they never carry framework secrets — unless a Buffer holds a PEM private key (`readFileSync('key.pem')`
94
+ // without an encoding, which JSON would print byte by byte).
82
95
  if (value instanceof Date || Buffer.isBuffer(value)) {
83
- return value;
96
+ return Buffer.isBuffer(value) && PRIVATE_KEY_PEM_PATTERN.test(value.toString('latin1')) ? MASK : value;
84
97
  }
85
98
 
86
99
  if (Array.isArray(value)) {
@@ -8,14 +8,14 @@
8
8
 
9
9
  ## Do You Need This Checklist?
10
10
 
11
- | Scenario | Action Needed |
12
- | ---------------------------------------------------- | ----------------------------------------------- |
13
- | Local development / e2e suites (`local`, `ci`, `e2e`) | None - the init endpoint is open there by default |
14
- | A deployed stage needs its first admin (11.46.0+) | Set ENV variables (Step 1) - the HTTP init is closed there by default |
15
- | A deployed stage must be set up through a UI form | Step 1b (setup token) |
16
- | Automated deployment (Docker/CI) needs auto-creation | Set ENV variables (Step 1) |
17
- | Want to disable system setup | Set `systemSetup: { enabled: false }` in config |
18
- | Custom setup logic (extra fields, notifications) | Step 2 (Custom Controller) |
11
+ | Scenario | Action Needed |
12
+ | ----------------------------------------------------- | --------------------------------------------------------------------- |
13
+ | Local development / e2e suites (`local`, `ci`, `e2e`) | None - the init endpoint is open there by default |
14
+ | A deployed stage needs its first admin (11.46.0+) | Set ENV variables (Step 1) - the HTTP init is closed there by default |
15
+ | A deployed stage must be set up through a UI form | Step 1b (setup token) |
16
+ | Automated deployment (Docker/CI) needs auto-creation | Set ENV variables (Step 1) |
17
+ | Want to disable system setup | Set `systemSetup: { enabled: false }` in config |
18
+ | Custom setup logic (extra fields, notifications) | Step 2 (Custom Controller) |
19
19
 
20
20
  ---
21
21
 
@@ -197,12 +197,12 @@ NEST_SERVER_CONFIG='{ "systemSetup": { "initialAdmin": { "email": "admin@example
197
197
  Since 11.46.0 (backport of 12.4.0) the anonymous init is fail-closed outside the local environments: whoever reaches
198
198
  an API without users through it would become its administrator.
199
199
 
200
- | `systemSetup.httpInit` | `local` / `ci` / `e2e` | every other environment |
201
- |---|---|---|
202
- | not set | open | **closed** — 403 `LTNS_0053` |
203
- | `true` (`NSC__SYSTEM_SETUP__HTTP_INIT=true`) | open | open, without a token |
204
- | `{ token }` (`NSC__SYSTEM_SETUP__HTTP_INIT__TOKEN`, at least 16 characters) | open, token required | open, token required |
205
- | `false` / `{ enabled: false }` | closed | closed |
200
+ | `systemSetup.httpInit` | `local` / `ci` / `e2e` | every other environment |
201
+ | --------------------------------------------------------------------------- | ---------------------- | ---------------------------- |
202
+ | not set | open | **closed** — 403 `LTNS_0053` |
203
+ | `true` (`NSC__SYSTEM_SETUP__HTTP_INIT=true`) | open | open, without a token |
204
+ | `{ token }` (`NSC__SYSTEM_SETUP__HTTP_INIT__TOKEN`, at least 16 characters) | open, token required | open, token required |
205
+ | `false` / `{ enabled: false }` | closed | closed |
206
206
 
207
207
  The environment is the configured `env`, but where that is local only because 11.x fell back to the `local` block (a
208
208
  `NODE_ENV` without a block of its own, or an empty one), `NODE_ENV` decides — such a stage counts as deployed
@@ -17,6 +17,7 @@ import mongoose from 'mongoose';
17
17
 
18
18
  import { MongooseCastErrorFilter } from './core/common/filters/mongoose-cast-error.filter';
19
19
  import { merge } from './core/common/helpers/config.helper';
20
+ import { processGraphQlUploadRequest } from './core/common/helpers/graphql-upload.helper';
20
21
  import { registerWsConnection } from './core/common/helpers/graphql-ws-connection.helper';
21
22
  import {
22
23
  buildRequestContextAwareExecute,
@@ -111,7 +112,10 @@ export class CoreModule implements NestModule {
111
112
  // config read here and the values there.
112
113
  consumer.apply(SecurityHeadersMiddleware).forRoutes('*');
113
114
  if (CoreModule.graphQlEnabled) {
114
- consumer.apply(graphqlUploadExpress()).forRoutes('graphql');
115
+ // The framework's processRequest, never graphql-upload's default: the default (graphql-upload < 18.0.2) lets
116
+ // one anonymous multipart request crash the process (GHSA-5vm7-vc2x-p3w2) and leaks temporary files on
117
+ // duplicate file fields (GHSA-qwwm-252j-9whw). This middleware runs before any authentication.
118
+ consumer.apply(graphqlUploadExpress({ processRequest: processGraphQlUploadRequest })).forRoutes('graphql');
115
119
  }
116
120
  }
117
121
 
package/src/index.ts CHANGED
@@ -43,6 +43,7 @@ export * from './core/common/helpers/execution-context-request.helper';
43
43
  export * from './core/common/helpers/file.helper';
44
44
  export * from './core/common/helpers/filter.helper';
45
45
  export * from './core/common/helpers/graphql.helper';
46
+ export * from './core/common/helpers/graphql-upload.helper';
46
47
  export * from './core/common/helpers/graphql-ws-connection.helper';
47
48
  export * from './core/common/helpers/graphql-ws-context.helper';
48
49
  export * from './core/common/helpers/interceptor.helper';
@@ -5,17 +5,51 @@
5
5
 
6
6
  declare module 'graphql-upload/graphqlUploadExpress.js' {
7
7
  import { RequestHandler } from 'express';
8
+ import type { IncomingMessage, ServerResponse } from 'node:http';
8
9
 
9
- interface GraphQLUploadOptions {
10
+ interface GraphQLUploadProcessRequestOptions {
11
+ maxFieldSize?: number;
10
12
  maxFiles?: number;
11
13
  maxFileSize?: number;
12
14
  }
13
15
 
16
+ interface GraphQLUploadOptions extends GraphQLUploadProcessRequestOptions {
17
+ /**
18
+ * The function that parses the multipart request. graphql-upload's default is its own `processRequest`, which is
19
+ * vulnerable to GHSA-5vm7-vc2x-p3w2 and GHSA-qwwm-252j-9whw below 18.0.2 — pass the framework's
20
+ * `processGraphQlUploadRequest`.
21
+ */
22
+ processRequest?: (
23
+ request: IncomingMessage,
24
+ response: ServerResponse,
25
+ options?: GraphQLUploadProcessRequestOptions,
26
+ ) => Promise<unknown>;
27
+ }
28
+
14
29
  function graphqlUploadExpress(options?: GraphQLUploadOptions): RequestHandler;
15
30
 
16
31
  export = graphqlUploadExpress;
17
32
  }
18
33
 
34
+ declare module 'graphql-upload/Upload.js' {
35
+ /**
36
+ * A file expected in a GraphQL multipart request, placed in the operations wherever the `map` names it. The
37
+ * `GraphQLUpload` scalar accepts a value only if it is `instanceof` this class, of the same graphql-upload copy.
38
+ */
39
+ class Upload {
40
+ /** The file's details once it streamed in (set by `resolve`). */
41
+ file?: unknown;
42
+ /** Resolves with the file's details; the scalar hands it to the resolver. */
43
+ promise: Promise<unknown>;
44
+ /** Rejects the upload (missing file, aborted request). */
45
+ reject: (error: Error) => void;
46
+ /** Resolves the upload with the file's details. */
47
+ resolve: (file: unknown) => void;
48
+ }
49
+
50
+ export = Upload;
51
+ }
52
+
19
53
  declare module 'graphql-upload/GraphQLUpload.js' {
20
54
  import { GraphQLScalarType } from 'graphql';
21
55