-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathupload.ts
More file actions
396 lines (351 loc) · 12.8 KB
/
Copy pathupload.ts
File metadata and controls
396 lines (351 loc) · 12.8 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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
import { Logger } from '@pgpmjs/logger';
import type { PgpmOptions } from '@pgpmjs/types';
import type { NextFunction, Request, RequestHandler, Response } from 'express';
import fs from 'fs';
import multer from 'multer';
import os from 'os';
import path from 'path';
import { QuoteUtils } from '@pgsql/quotes';
import type { Pool } from 'pg';
import { getPgPool } from 'pg-cache';
import pgQueryContext from 'pg-query-context';
import { streamToStorage } from 'graphile-settings';
import type { RlsModule } from '../types';
import './types';
const uploadLog = new Logger('upload');
const authLog = new Logger('upload-auth');
const envFileSize = process.env.MAX_UPLOAD_FILE_SIZE
? parseInt(process.env.MAX_UPLOAD_FILE_SIZE, 10)
: NaN;
const MAX_FILE_SIZE = envFileSize > 0 ? envFileSize : 10 * 1024 * 1024;
const BLOCKED_MIME_TYPES = new Set([
'application/x-executable',
'application/x-sharedlib',
'application/x-mach-binary',
'application/x-dosexec',
'text/html',
'application/xhtml+xml',
'application/javascript',
'text/javascript'
]);
const parseFile = multer({
storage: multer.diskStorage({
destination: os.tmpdir(),
filename: (_req, _file, cb) => {
const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;
cb(null, `upload-${uniqueSuffix}.tmp`);
},
}),
limits: { fileSize: MAX_FILE_SIZE },
}).single('file');
const parseFileWithErrors: RequestHandler = (req, res, next) => {
parseFile(req, res, (err: any) => {
if (!err) return next();
if (err.code === 'LIMIT_FILE_SIZE') {
return res.status(413).json({ error: `File exceeds maximum size of ${MAX_FILE_SIZE / (1024 * 1024)} MB` });
}
if (err.code === 'LIMIT_UNEXPECTED_FILE') {
return res.status(400).json({ error: 'Unexpected file field. Send a single file as "file".' });
}
return res.status(400).json({ error: 'File upload failed' });
});
};
const RLS_MODULE_BY_DATABASE_ID_SQL = `
SELECT am.data
FROM services_public.api_modules am
JOIN services_public.apis a ON am.api_id = a.id
WHERE am.name = 'rls_module' AND a.database_id = $1
ORDER BY a.id
LIMIT 1
`;
const RLS_MODULE_BY_API_ID_SQL = `
SELECT data
FROM services_public.api_modules
WHERE api_id = $1 AND name = 'rls_module'
LIMIT 1
`;
const RLS_MODULE_BY_DBNAME_SQL = `
SELECT am.data
FROM services_public.api_modules am
JOIN services_public.apis a ON am.api_id = a.id
WHERE am.name = 'rls_module' AND a.dbname = $1
ORDER BY a.id
LIMIT 1
`;
const RLS_SETTINGS_BY_DATABASE_ID_SQL = `
SELECT
auth_schema.schema_name AS authenticate_schema,
role_schema.schema_name AS role_schema,
auth_fn.name AS authenticate,
auth_strict_fn.name AS authenticate_strict,
role_fn.name AS current_role,
role_id_fn.name AS current_role_id,
ua_fn.name AS current_user_agent,
ip_fn.name AS current_ip_address
FROM services_public.rls_settings rs
LEFT JOIN metaschema_public.schema auth_schema ON rs.authenticate_schema_id = auth_schema.id
LEFT JOIN metaschema_public.schema role_schema ON rs.role_schema_id = role_schema.id
LEFT JOIN metaschema_public.function auth_fn ON rs.authenticate_function_id = auth_fn.id
LEFT JOIN metaschema_public.function auth_strict_fn ON rs.authenticate_strict_function_id = auth_strict_fn.id
LEFT JOIN metaschema_public.function role_fn ON rs.current_role_function_id = role_fn.id
LEFT JOIN metaschema_public.function role_id_fn ON rs.current_role_id_function_id = role_id_fn.id
LEFT JOIN metaschema_public.function ua_fn ON rs.current_user_agent_function_id = ua_fn.id
LEFT JOIN metaschema_public.function ip_fn ON rs.current_ip_address_function_id = ip_fn.id
WHERE rs.database_id = $1
LIMIT 1
`;
const RLS_SETTINGS_BY_DBNAME_SQL = `
SELECT
auth_schema.schema_name AS authenticate_schema,
role_schema.schema_name AS role_schema,
auth_fn.name AS authenticate,
auth_strict_fn.name AS authenticate_strict,
role_fn.name AS current_role,
role_id_fn.name AS current_role_id,
ua_fn.name AS current_user_agent,
ip_fn.name AS current_ip_address
FROM services_public.rls_settings rs
JOIN services_public.apis a ON rs.database_id = a.database_id
LEFT JOIN metaschema_public.schema auth_schema ON rs.authenticate_schema_id = auth_schema.id
LEFT JOIN metaschema_public.schema role_schema ON rs.role_schema_id = role_schema.id
LEFT JOIN metaschema_public.function auth_fn ON rs.authenticate_function_id = auth_fn.id
LEFT JOIN metaschema_public.function auth_strict_fn ON rs.authenticate_strict_function_id = auth_strict_fn.id
LEFT JOIN metaschema_public.function role_fn ON rs.current_role_function_id = role_fn.id
LEFT JOIN metaschema_public.function role_id_fn ON rs.current_role_id_function_id = role_id_fn.id
LEFT JOIN metaschema_public.function ua_fn ON rs.current_user_agent_function_id = ua_fn.id
LEFT JOIN metaschema_public.function ip_fn ON rs.current_ip_address_function_id = ip_fn.id
WHERE a.dbname = $1
LIMIT 1
`;
interface RlsModuleData {
authenticate: string;
authenticate_strict: string;
authenticate_schema: string;
role_schema: string;
current_role: string;
current_role_id: string;
current_ip_address: string;
current_user_agent: string;
}
interface RlsModuleRow {
data: RlsModuleData | null;
}
const toRlsModule = (row: RlsModuleRow | null): RlsModule | undefined => {
if (!row?.data) return undefined;
const d = row.data;
return {
authenticate: d.authenticate,
authenticateStrict: d.authenticate_strict,
privateSchema: { schemaName: d.authenticate_schema },
publicSchema: { schemaName: d.role_schema },
currentRole: d.current_role,
currentRoleId: d.current_role_id,
currentIpAddress: d.current_ip_address,
currentUserAgent: d.current_user_agent,
};
};
const toRlsModuleFromSettings = (row: RlsModuleData | null): RlsModule | undefined => {
if (!row) return undefined;
return {
authenticate: row.authenticate,
authenticateStrict: row.authenticate_strict,
privateSchema: { schemaName: row.authenticate_schema },
publicSchema: { schemaName: row.role_schema },
currentRole: row.current_role,
currentRoleId: row.current_role_id,
currentIpAddress: row.current_ip_address,
currentUserAgent: row.current_user_agent,
};
};
const getBearerToken = (authorization?: string): string | null => {
if (!authorization) return null;
const [authType, authToken] = authorization.split(' ');
if (authType?.toLowerCase() !== 'bearer' || !authToken) {
return null;
}
return authToken;
};
const queryRlsSettingsByDatabaseId = async (pool: Pool, databaseId: string): Promise<RlsModule | undefined> => {
try {
const result = await pool.query<RlsModuleData>(RLS_SETTINGS_BY_DATABASE_ID_SQL, [databaseId]);
return toRlsModuleFromSettings(result.rows[0] ?? null);
} catch {
return undefined;
}
};
const queryRlsSettingsByDbname = async (pool: Pool, dbname: string): Promise<RlsModule | undefined> => {
try {
const result = await pool.query<RlsModuleData>(RLS_SETTINGS_BY_DBNAME_SQL, [dbname]);
return toRlsModuleFromSettings(result.rows[0] ?? null);
} catch {
return undefined;
}
};
const queryRlsModuleByDatabaseId = async (pool: Pool, databaseId: string): Promise<RlsModule | undefined> => {
const fromSettings = await queryRlsSettingsByDatabaseId(pool, databaseId);
if (fromSettings) return fromSettings;
const result = await pool.query<RlsModuleRow>(RLS_MODULE_BY_DATABASE_ID_SQL, [databaseId]);
return toRlsModule(result.rows[0] ?? null);
};
const queryRlsModuleByApiId = async (pool: Pool, apiId: string): Promise<RlsModule | undefined> => {
const result = await pool.query<RlsModuleRow>(RLS_MODULE_BY_API_ID_SQL, [apiId]);
return toRlsModule(result.rows[0] ?? null);
};
const queryRlsModuleByDbname = async (pool: Pool, dbname: string): Promise<RlsModule | undefined> => {
const fromSettings = await queryRlsSettingsByDbname(pool, dbname);
if (fromSettings) return fromSettings;
const result = await pool.query<RlsModuleRow>(RLS_MODULE_BY_DBNAME_SQL, [dbname]);
return toRlsModule(result.rows[0] ?? null);
};
const resolveUploadRlsModule = async (opts: PgpmOptions, req: Request): Promise<RlsModule | undefined> => {
const api = req.api;
if (!api) return undefined;
// Use API-scoped RLS module when available (e.g., meta API).
if (api.rlsModule) {
return api.rlsModule;
}
const pool = getPgPool(opts.pg);
if (api.apiId) {
const byApiId = await queryRlsModuleByApiId(pool, api.apiId);
if (byApiId) return byApiId;
}
if (api.databaseId) {
const byDatabaseId = await queryRlsModuleByDatabaseId(pool, api.databaseId);
if (byDatabaseId) return byDatabaseId;
}
if (api.dbname) {
return queryRlsModuleByDbname(pool, api.dbname);
}
return undefined;
};
const authError = (res: Response): Response =>
res.status(401).json({ error: 'Authentication required' });
/**
* Upload-specific authentication middleware.
*
* This middleware enforces strict auth semantics for `POST /upload` while
* preserving existing GraphQL auth behavior for other routes.
*/
export const createUploadAuthenticateMiddleware = (
opts: PgpmOptions,
): RequestHandler => {
return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
const api = req.api;
if (!api) {
res.status(500).send('Missing API info');
return;
}
if (req.token?.user_id) {
next();
return;
}
const authToken = getBearerToken(req.headers.authorization as string | undefined);
if (!authToken) {
authError(res);
return;
}
let rlsModule: RlsModule | undefined;
try {
rlsModule = await resolveUploadRlsModule(opts, req);
} catch (error) {
authLog.error('[upload-auth] Failed to resolve RLS module for upload route', error);
authError(res);
return;
}
if (!rlsModule) {
authLog.info(`[upload-auth] No RLS module found for db=${api.dbname} databaseId=${api.databaseId ?? 'none'}`);
authError(res);
return;
}
const authFn = opts.server?.strictAuth ? rlsModule.authenticateStrict : rlsModule.authenticate;
const privateSchema = rlsModule.privateSchema?.schemaName;
if (!authFn || !privateSchema) {
authLog.warn(
`[upload-auth] Missing auth function or private schema for db=${api.dbname}; strictAuth=${opts.server?.strictAuth ?? false}`,
);
authError(res);
return;
}
const pool = getPgPool({
...opts.pg,
database: api.dbname,
});
const context: Record<string, string> = {};
if (req.clientIp) {
context['jwt.claims.ip_address'] = req.clientIp;
}
if (req.get('origin')) {
context['jwt.claims.origin'] = req.get('origin') as string;
}
if (req.get('User-Agent')) {
context['jwt.claims.user_agent'] = req.get('User-Agent') as string;
}
try {
const result = await pgQueryContext({
client: pool,
context,
query: `SELECT * FROM ${QuoteUtils.quoteQualifiedIdentifier(privateSchema, authFn)}($1)`,
variables: [authToken],
});
if (!result?.rowCount) {
authError(res);
return;
}
req.token = result.rows[0];
if (!req.token?.user_id) {
authError(res);
return;
}
next();
} catch (error) {
authLog.warn('[upload-auth] Upload authentication failed', error);
authError(res);
}
};
};
/**
* REST file upload endpoint.
*
* Accepts a single file via multipart/form-data, streams it to S3/MinIO,
* and returns file metadata. The frontend uses this in a two-step flow:
*
* 1. POST /upload -> { url, filename, mime, size }
* 2. GraphQL mutation -> patch row with the returned metadata
*/
export const uploadRoute: RequestHandler[] = [
parseFileWithErrors,
(async (req, res, next) => {
if (!req.token?.user_id) {
return res.status(401).json({ error: 'Authentication required' });
}
if (!req.file) {
return res.status(400).json({ error: 'No file provided. Send a "file" field.' });
}
if (req.file.mimetype && BLOCKED_MIME_TYPES.has(req.file.mimetype)) {
fs.unlink(req.file.path, () => {});
return res.status(415).json({ error: 'File type not allowed' });
}
try {
const readStream = fs.createReadStream(req.file.path);
const result = await streamToStorage(readStream, req.file.originalname);
uploadLog.debug(
`[upload] Uploaded file for user=${req.token.user_id} filename=${req.file.originalname} mime=${result.mime} size=${req.file.size}`,
);
res.json({
url: result.url,
filename: result.filename,
mime: result.mime,
size: req.file.size,
});
} catch (error) {
uploadLog.error('[upload] Upload processing failed', error);
if (!res.headersSent) {
res.status(500).json({ error: 'Upload processing failed' });
}
} finally {
if (req.file?.path) {
fs.unlink(req.file.path, () => {});
}
}
}) as RequestHandler,
];