-
Notifications
You must be signed in to change notification settings - Fork 243
/
Copy pathcallPostObject.js
210 lines (186 loc) · 8.15 KB
/
callPostObject.js
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
const { auth, errors } = require('arsenal');
const busboy = require('@fastify/busboy');
const writeContinue = require('../../../utilities/writeContinue');
const fs = require('fs');
const path = require('path');
const os = require('os');
/** @see doc: https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTForms.html#HTTPPOSTFormDeclaration */
const MAX_FIELD_SIZE = 20 * 1024; // 20KB
/** @see doc: https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-keys.html */
const MAX_KEY_SIZE = 1024;
const POST_OBJECT_OPTIONAL_FIELDS = [
'acl',
'awsaccesskeyid',
'bucket',
'cache-control',
'content-disposition',
'content-encoding',
'content-type',
'expires',
'policy',
'redirect',
'tagging',
'success_action_redirect',
'success_action_status',
'x-amz-meta-',
'x-amz-storage-class',
'x-amz-security-token',
'x-amz-signgnature',
'x-amz-website-redirect-location',
];
async function authenticateRequest(request, requestContexts, log) {
return new Promise(resolve => {
// TODO RING-45960 remove ignore auth check for POST object here
auth.server.doAuth(request, log, (err, userInfo, authorizationResults, streamingV4Params) =>
resolve({ userInfo, authorizationResults, streamingV4Params }), 's3', requestContexts);
});
}
async function parseFormData(request, response, requestContexts, log) {
/* eslint-disable no-param-reassign */
let formDataParser;
try {
formDataParser = busboy({ headers: request.headers });
} catch (err) {
log.trace('Error creating form data parser', { error: err.toString() });
return Promise.reject(errors.PreconditionFailed
.customizeDescription('Bucket POST must be of the enclosure-type multipart/form-data'));
}
// formDataParser = busboy({ headers: request.headers });
writeContinue(request, response);
return new Promise((resolve, reject) => {
request.formData = {};
let totalFieldSize = 0;
let fileEventData = null;
let tempFileStream;
let tempFilePath;
let authResponse;
let fileWrittenPromiseResolve;
let formParserFinishedPromiseResolve;
const fileWrittenPromise = new Promise((res) => { fileWrittenPromiseResolve = res; });
const formParserFinishedPromise = new Promise((res) => { formParserFinishedPromiseResolve = res; });
formDataParser.on('field', (fieldname, val) => {
// Check if we have exceeded the max size allowed for all fields
totalFieldSize += Buffer.byteLength(val, 'utf8');
if (totalFieldSize > MAX_FIELD_SIZE) {
return reject(errors.MaxPostPreDataLengthExceeded);
}
// validate the fieldname
const lowerFieldname = fieldname.toLowerCase();
// special handling for key field
if (lowerFieldname === 'key') {
if (val.length > MAX_KEY_SIZE) {
return reject(errors.KeyTooLong);
} else if (val.length === 0) {
return reject(errors.InvalidArgument
.customizeDescription('User key must have a length greater than 0.'));
}
request.formData[lowerFieldname] = val;
}
// add only the recognized fields to the formData object
if (POST_OBJECT_OPTIONAL_FIELDS.some(field => lowerFieldname.startsWith(field))) {
request.formData[lowerFieldname] = val;
}
return undefined;
});
formDataParser.on('file', async (fieldname, file, filename, encoding, mimetype) => {
if (fileEventData) {
file.resume(); // Resume the stream to drain and discard the file
if (tempFilePath) {
fs.unlink(tempFilePath, unlinkErr => {
if (unlinkErr) {
log.error('Failed to delete temp file', { error: unlinkErr });
}
});
}
return reject(errors.InvalidArgument
.customizeDescription('POST requires exactly one file upload per request.'));
}
fileEventData = { fieldname, file, filename, encoding, mimetype };
if (!('key' in request.formData)) {
return reject(errors.InvalidArgument
.customizeDescription('Bucket POST must contain a field named '
+ "'key'. If it is specified, please check the order of the fields."));
}
// Replace `${filename}` with the actual filename
request.formData.key = request.formData.key.replace('${filename}', filename);
try {
// Authenticate request before streaming file
// TODO RING-45960 auth to be properly implemented
authResponse = await authenticateRequest(request, requestContexts, log);
// Create a temporary file to stream the file data
// This is to finalize validation on form data before storing the file
tempFilePath = path.join(os.tmpdir(), filename);
tempFileStream = fs.createWriteStream(tempFilePath);
file.pipe(tempFileStream);
tempFileStream.on('finish', () => {
request.fileEventData = { ...fileEventData, file: tempFilePath };
fileWrittenPromiseResolve();
});
tempFileStream.on('error', (err) => {
log.trace('Error streaming file to temporary location', { error: err.toString() });
reject(errors.InternalError);
});
// Wait for both file writing and form parsing to finish
return Promise.all([fileWrittenPromise, formParserFinishedPromise])
.then(() => resolve(authResponse))
.catch(reject);
} catch (err) {
return reject(err);
}
});
formDataParser.on('finish', () => {
if (!fileEventData) {
return reject(errors.InvalidArgument
.customizeDescription('POST requires exactly one file upload per request.'));
}
return formParserFinishedPromiseResolve();
});
formDataParser.on('error', (err) => {
log.trace('Error processing form data:', { error: err.toString() });
request.unpipe(formDataParser);
// Following observed AWS behaviour
reject(errors.MalformedPOSTRequest);
});
request.pipe(formDataParser);
return undefined;
});
}
function getFileStat(filePath, log) {
return new Promise((resolve, reject) => {
fs.stat(filePath, (err, stats) => {
if (err) {
log.trace('Error getting file size', { error: err.toString() });
return reject(errors.InternalError);
}
return resolve(stats);
});
});
}
async function processPostForm(request, response, requestContexts, log, callback) {
try {
const { userInfo, authorizationResults, streamingV4Params } =
await parseFormData(request, response, requestContexts, log);
const fileStat = await getFileStat(request.fileEventData.file, log);
request.parsedContentLength = fileStat.size;
request.fileEventData.file = fs.createReadStream(request.fileEventData.file);
if (request.formData['content-type']) {
request.headers['content-type'] = request.formData['content-type'];
} else {
request.headers['content-type'] = 'binary/octet-stream';
}
const authNames = { accountName: userInfo.getAccountDisplayName() };
if (userInfo.isRequesterAnIAMUser()) {
authNames.userName = userInfo.getIAMdisplayName();
}
log.addDefaultFields(authNames);
return callback(null, userInfo, authorizationResults, streamingV4Params);
} catch (err) {
return callback(err);
}
}
module.exports = {
authenticateRequest,
parseFormData,
processPostForm,
getFileStat,
};