forked from bcgov/common-hosted-form-service
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice.js
More file actions
296 lines (253 loc) · 8.75 KB
/
Copy pathservice.js
File metadata and controls
296 lines (253 loc) · 8.75 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
const config = require('config');
const uuid = require('uuid');
const path = require('path');
const { FileStorage } = require('../common/models');
const { StorageTypes } = require('../common/constants');
const log = require('../../components/log')(module.filename);
const storageService = require('./storage/storageService');
const uploadCleanup = require('./uploadCleanup');
const PERMANENT_STORAGE = config.get('files.permanent');
const BLOCKED_EXTENSIONS = [
'.exe',
'.bat',
'.scr',
'.com',
'.pif',
'.cmd',
'.jar',
'.app',
'.deb',
'.dmg',
'.msi',
'.run',
'.bin',
'.sh',
'.ps1',
'.vbs',
'.js',
'.html',
'.php',
'.py',
'.rb',
'.jsp',
'.asp',
'.aspx',
];
/**
* CRITICAL SECURITY: File validation at service layer
*/
const validateFileSecurity = (file) => {
if (!file || !file.originalname) {
throw new Error('No file provided for upload');
}
const fileName = file.originalname.toLowerCase();
const fileExtension = path.extname(fileName);
if (BLOCKED_EXTENSIONS.some((ext) => fileName.endsWith(ext))) {
throw new Error(`File type ${fileExtension} is not allowed for security reasons`);
}
if (fileName.includes('..') || fileName.includes('/') || fileName.includes('\\')) {
throw new Error('Filename contains dangerous characters');
}
return true;
};
const service = {
create: async (data, currentUser, folder = 'uploads') => {
const tempPath = data?.path;
let trx;
let uploadResult;
let obj;
// Once the transaction commits, the file record and its stored object are
// durable and reference each other. Anything that fails after this point
// (e.g. the read-back below) must NOT trigger compensation, or we would roll
// back an already-committed transaction and delete the object that a
// committed row still points at - orphaning the record.
let committed = false;
try {
validateFileSecurity(data);
trx = await FileStorage.startTransaction();
obj = {};
obj.id = uuid.v4();
obj.storage = folder;
obj.originalName = data.originalname;
obj.mimeType = data.mimetype;
obj.size = data.size;
obj.path = data.path;
obj.createdBy = currentUser?.usernameIdp || 'public';
uploadResult = await storageService.upload(obj);
obj.path = uploadResult.path;
obj.storage = uploadResult.storage;
await FileStorage.query(trx).insert(obj);
await trx.commit();
committed = true;
if (uploadResult.storage === StorageTypes.OBJECT_STORAGE) {
await uploadCleanup.removeUploadedFile(tempPath, 'object-storage-upload-success');
}
const result = await service.read(obj.id);
return result;
} catch (err) {
// Compensation only applies while the work is still undoable. After a
// successful commit the object is legitimately referenced (and for local
// storage the temp file IS that object), so leave everything in place.
if (!committed) {
if (trx) await trx.rollback();
if (uploadResult && obj?.id) {
await service.deleteStorageObject({
id: obj.id,
path: uploadResult.path,
storage: uploadResult.storage,
});
}
await uploadCleanup.removeUploadedFile(tempPath, 'create-failure');
}
throw err;
}
},
read: async (id) => {
return FileStorage.query().findById(id).throwIfNotFound();
},
delete: async (id) => {
let trx;
try {
trx = await FileStorage.startTransaction();
const obj = await service.read(id);
await FileStorage.query(trx).deleteById(id).throwIfNotFound();
const result = await storageService.delete(obj);
if (!result) {
// error?
}
await trx.commit();
return result;
} catch (err) {
if (trx) await trx.rollback();
throw err;
}
},
deleteFiles: async (ids) => {
let trx;
try {
trx = await FileStorage.startTransaction();
for (const id of ids) {
const obj = await service.read(id);
await FileStorage.query(trx).deleteById(id).throwIfNotFound();
const result = await storageService.delete(obj);
if (!result) {
throw new Error(`Failed to delete file with id ${id}`);
}
}
await trx.commit();
} catch (err) {
if (trx) await trx.rollback();
throw err;
}
},
/**
* Best-effort deletion of the stored object for a file, without touching the
* database record. Used to remove the original object after a submission file
* has been copied to permanent storage, and to purge orphaned objects once the
* DB rows are gone. Storage failures are logged and swallowed so they can't
* undo work that has already been committed.
*
* @param {FileStorage} fileStorage the file storage object to remove.
* @returns {Promise<boolean>} true if the object was removed.
*/
deleteStorageObject: async (fileStorage) => {
try {
return await storageService.delete(fileStorage);
} catch (err) {
log.error(`Failed to delete stored object for file ${fileStorage?.id}`, err);
return false;
}
},
/**
* Move a submission file from the "upload" storage location to the
* "submission" location. This is used when a submission is either saved as
* draft or submitted, and makes the uploaded files permanent.
*
* When an existing transaction is supplied the database update runs inside it
* and the caller owns both the commit and the cleanup of the original object
* (which must happen only after the commit). This avoids opening a second
* transaction that would deadlock against the caller's row lock. Without a
* transaction this manages its own and cleans up the original itself.
*
* @param {uuidv4} submissionId the id of the submission that holds the file.
* @param {FileStorage} fileStorage the file storage object for the file.
* @param {string} updatedBy the user who is saving the submission.
* @param {*} [etrx] an optional existing transaction to run within.
* @returns {Promise<FileStorage>} the original file storage object (pre-move),
* so the caller can clean up the source object after committing.
*/
moveSubmissionFile: async (submissionId, fileStorage, updatedBy, etrx = undefined) => {
let trx;
try {
trx = etrx || (await FileStorage.startTransaction());
// Copy the file from its current directory to the "submissions" subdirectory.
const path = await storageService.move(fileStorage, 'submissions', submissionId);
if (!path) {
throw new Error('Error moving files for submission');
}
await FileStorage.query(trx).patchAndFetchById(fileStorage.id, {
formSubmissionId: submissionId,
path: path,
storage: PERMANENT_STORAGE,
updatedBy: updatedBy,
});
// Only manage commit/cleanup when we own the transaction.
if (!etrx) {
await trx.commit();
await service.deleteStorageObject(fileStorage);
}
return fileStorage;
} catch (err) {
if (!etrx && trx) await trx.rollback();
throw err;
}
},
moveSubmissionFiles: async (submissionId, currentUser) => {
let trx;
try {
trx = await FileStorage.startTransaction();
// fetch all the File Storage records for a submission id
// move them to permanent storage
// update their new paths.
const items = await FileStorage.query(trx).where('formSubmissionId', submissionId);
for (const item of items) {
// move the files under a sub directory for this submission
const newPath = await storageService.move(item, 'submissions', submissionId);
if (!newPath) {
throw new Error('Error moving files for submission');
}
await FileStorage.query(trx).patchAndFetchById(item.id, {
storage: PERMANENT_STORAGE,
path: newPath,
updatedBy: currentUser.usernameIdp,
});
}
await trx.commit();
} catch (err) {
if (trx) await trx.rollback();
throw err;
}
},
clone: async (data, currentUser) => {
let trx;
try {
trx = await FileStorage.startTransaction();
const file = await FileStorage.query().findById(data).throwIfNotFound();
// Remove the ID to avoid conflicts when inserting
const obj = { ...file };
const uploadResult = await storageService.clone(obj);
obj.id = uploadResult.id;
obj.path = uploadResult.path;
obj.storage = uploadResult.storage;
obj.createdBy = currentUser.usernameIdp;
await FileStorage.query(trx).insert(obj);
await trx.commit();
const result = await service.read(obj.id);
return result;
} catch (err) {
if (trx) await trx.rollback();
throw err;
}
},
};
module.exports = service;