-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
Expand file tree
/
Copy pathParseGraphQLServer.js
More file actions
279 lines (252 loc) · 9.26 KB
/
ParseGraphQLServer.js
File metadata and controls
279 lines (252 loc) · 9.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import graphqlUploadExpress from 'graphql-upload/graphqlUploadExpress.js';
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@as-integrations/express5';
import { ApolloServerPluginCacheControlDisabled } from '@apollo/server/plugin/disabled';
import express from 'express';
import { GraphQLError, parse } from 'graphql';
import {
allowCrossDomain,
getHeaderAliases,
handleHeaderAliases,
handleParseErrors,
handleParseHeaders,
handleParseSession,
} from '../middlewares';
import requiredParameter from '../requiredParameter';
import defaultLogger from '../logger';
import { ParseGraphQLSchema } from './ParseGraphQLSchema';
import ParseGraphQLController, { ParseGraphQLConfig } from '../Controllers/ParseGraphQLController';
import { createComplexityValidationPlugin } from './helpers/queryComplexity';
const hasTypeIntrospection = (query) => {
try {
const ast = parse(query);
const checkSelections = (selections) => {
for (const selection of selections) {
if (selection.kind === 'Field' && selection.name.value === '__type') {
if (selection.arguments && selection.arguments.length > 0) {
return true;
}
}
if (selection.selectionSet) {
if (checkSelections(selection.selectionSet.selections)) {
return true;
}
}
}
return false;
};
for (const definition of ast.definitions) {
if (definition.selectionSet) {
if (checkSelections(definition.selectionSet.selections)) {
return true;
}
}
}
return false;
} catch {
return false;
}
};
const throwIntrospectionError = () => {
throw new GraphQLError('Introspection is not allowed', {
extensions: {
http: {
status: 403,
},
}
});
};
const IntrospectionControlPlugin = (publicIntrospection) => ({
requestDidStart: (requestContext) => ({
didResolveOperation: async () => {
// If public introspection is enabled, we allow all introspection queries
if (publicIntrospection) {
return;
}
const isMasterOrMaintenance = requestContext.contextValue.auth?.isMaster || requestContext.contextValue.auth?.isMaintenance
if (isMasterOrMaintenance) {
return;
}
const query = requestContext.request.query;
// Fast path: simple string check for __schema
// This avoids parsing the query in most cases
if (query?.includes('__schema')) {
return throwIntrospectionError();
}
// Smart check for __type: only parse if the string is present
// This avoids false positives (e.g., "__type" in strings or comments)
// while still being efficient for the common case
if (query?.includes('__type') && hasTypeIntrospection(query)) {
return throwIntrospectionError();
}
},
})
});
export const getCSRFRequestHeaders = headerAliases => {
return [...new Set(['X-Parse-Application-Id', ...getHeaderAliases(headerAliases, 'X-Parse-Application-Id')])];
};
class ParseGraphQLServer {
parseGraphQLController: ParseGraphQLController;
constructor(parseServer, config) {
this.parseServer = parseServer || requiredParameter('You must provide a parseServer instance!');
if (!config || !config.graphQLPath) {
requiredParameter('You must provide a config.graphQLPath!');
}
this.config = config;
this.parseGraphQLController = this.parseServer.config.parseGraphQLController;
this.log =
(this.parseServer.config && this.parseServer.config.loggerController) || defaultLogger;
this.parseGraphQLSchema = new ParseGraphQLSchema({
parseGraphQLController: this.parseGraphQLController,
databaseController: this.parseServer.config.databaseController,
log: this.log,
graphQLCustomTypeDefs: this.config.graphQLCustomTypeDefs,
appId: this.parseServer.config.appId,
});
}
async _getGraphQLOptions() {
try {
return {
schema: await this.parseGraphQLSchema.load(),
context: async ({ req }) => {
return {
info: req.info,
config: req.config,
auth: req.auth,
};
},
};
} catch (e) {
this.log.error(e.stack || (typeof e.toString === 'function' && e.toString()) || e);
throw e;
}
}
async _getServer() {
const schemaRef = this.parseGraphQLSchema.graphQLSchema;
const newSchemaRef = await this.parseGraphQLSchema.load();
if (schemaRef === newSchemaRef && this._server) {
return this._server;
}
// It means a parallel _getServer call is already in progress
if (this._schemaRefMutex === newSchemaRef) {
return this._server;
}
// Update the schema ref mutex to avoid parallel _getServer calls
this._schemaRefMutex = newSchemaRef;
const createServer = async () => {
try {
const { schema, context } = await this._getGraphQLOptions();
const csrfRequestHeaders = getCSRFRequestHeaders(this.parseServer.config.headerAliases);
const apollo = new ApolloServer({
csrfPrevention: {
// See https://www.apollographql.com/docs/router/configuration/csrf/
// needed since we use graphql upload
requestHeaders: csrfRequestHeaders,
},
// We need always true introspection because apollo server have changing behavior based on the NODE_ENV variable
// we delegate the introspection control to the IntrospectionControlPlugin
introspection: true,
plugins: [ApolloServerPluginCacheControlDisabled(), IntrospectionControlPlugin(this.config.graphQLPublicIntrospection), createComplexityValidationPlugin(() => this.parseServer.config.requestComplexity)],
schema,
});
await apollo.start();
return expressMiddleware(apollo, {
context,
});
} catch (e) {
// Reset all mutexes and forward the error
this._server = null;
this._schemaRefMutex = null;
throw e;
}
}
// Do not await so parallel request will wait the same promise ref
this._server = createServer();
return this._server;
}
_transformMaxUploadSizeToBytes(maxUploadSize) {
const unitMap = {
kb: 1,
mb: 2,
gb: 3,
};
return (
Number(maxUploadSize.slice(0, -2)) *
Math.pow(1024, unitMap[maxUploadSize.slice(-2).toLowerCase()])
);
}
/**
* @static
* Allow developers to customize each request with inversion of control/dependency injection
*/
applyRequestContextMiddleware(api, options) {
if (options.requestContextMiddleware) {
if (typeof options.requestContextMiddleware !== 'function') {
throw new Error('requestContextMiddleware must be a function');
}
api.use(this.config.graphQLPath, options.requestContextMiddleware);
}
}
applyGraphQL(app) {
if (!app || !app.use) {
requiredParameter('You must provide an Express.js app instance!');
}
app.use(this.config.graphQLPath, allowCrossDomain(this.parseServer.config.appId));
app.use(this.config.graphQLPath, handleHeaderAliases(this.parseServer.config.appId));
app.use(this.config.graphQLPath, handleParseHeaders);
app.use(this.config.graphQLPath, handleParseSession);
this.applyRequestContextMiddleware(app, this.parseServer.config);
app.use(this.config.graphQLPath, handleParseErrors);
app.use(
this.config.graphQLPath,
graphqlUploadExpress({
maxFileSize: this._transformMaxUploadSizeToBytes(
this.parseServer.config.maxUploadSize || '20mb'
),
})
);
app.use(this.config.graphQLPath, express.json(), async (req, res, next) => {
const server = await this._getServer();
return server(req, res, next);
});
}
applyPlayground(app) {
if (!app || !app.get) {
requiredParameter('You must provide an Express.js app instance!');
}
app.get(
this.config.playgroundPath ||
requiredParameter('You must provide a config.playgroundPath to applyPlayground!'),
(_req, res) => {
res.setHeader('Content-Type', 'text/html');
res.write(
`<div id="sandbox" style="position:absolute;top:0;right:0;bottom:0;left:0"></div>
<script src="https://embeddable-sandbox.cdn.apollographql.com/_latest/embeddable-sandbox.umd.production.min.js"></script>
<script>
new window.EmbeddedSandbox({
target: "#sandbox",
endpointIsEditable: false,
initialEndpoint: ${JSON.stringify(this.config.graphQLPath)},
handleRequest: (endpointUrl, options) => {
return fetch(endpointUrl, {
...options,
headers: {
...options.headers,
'X-Parse-Application-Id': ${JSON.stringify(this.parseServer.config.appId)},
'X-Parse-Master-Key': ${JSON.stringify(this.parseServer.config.masterKey)},
},
})
},
});
// advanced options: https://www.apollographql.com/docs/studio/explorer/sandbox#embedding-sandbox
</script>`
);
res.end();
}
);
}
setGraphQLConfig(graphQLConfig: ParseGraphQLConfig): Promise {
return this.parseGraphQLController.updateGraphQLConfig(graphQLConfig);
}
}
export { ParseGraphQLServer };