-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathobjectLockHelpers.js
More file actions
348 lines (316 loc) · 12.7 KB
/
objectLockHelpers.js
File metadata and controls
348 lines (316 loc) · 12.7 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
const { errors, auth, policies } = require('arsenal');
const moment = require('moment');
const { config } = require('../../../Config');
const vault = require('../../../auth/vault');
const { evaluateBucketPolicyWithIAM } = require('../authorization/permissionChecks');
/**
* Calculates retain until date for the locked object version
* @param {object} retention - includes days or years retention period
* @return {object} the date until the object version remains locked
*/
function calculateRetainUntilDate(retention) {
const { days, years } = retention;
if (!days && !years) {
return undefined;
}
const date = moment();
// Calculate the number of days to retain the lock on the object
const retainUntilDays = days || years * 365;
const retainUntilDate
= date.add(retainUntilDays, 'days');
return retainUntilDate.toISOString();
}
/**
* Validates object lock headers
* @param {object} bucket - bucket metadata
* @param {object} headers - request headers
* @param {object} log - the log request
* @return {object} - object with error if validation fails
*/
function validateHeaders(bucket, headers, log) {
const bucketObjectLockEnabled = bucket.isObjectLockEnabled();
const objectLegalHold = headers['x-amz-object-lock-legal-hold'];
const objectLockDate = headers['x-amz-object-lock-retain-until-date'];
const objectLockMode = headers['x-amz-object-lock-mode'];
// If retention headers or legal hold header present but
// object lock is not enabled on the bucket return error
if ((objectLockDate || objectLockMode || objectLegalHold)
&& !bucketObjectLockEnabled) {
log.trace('bucket is missing ObjectLockConfiguration');
return errors.InvalidRequest.customizeDescription(
'Bucket is missing ObjectLockConfiguration');
}
if ((objectLockMode || objectLockDate) &&
!(objectLockMode && objectLockDate)) {
return errors.InvalidArgument.customizeDescription(
'x-amz-object-lock-retain-until-date and ' +
'x-amz-object-lock-mode must both be supplied',
);
}
const validModes = new Set(['GOVERNANCE', 'COMPLIANCE']);
if (objectLockMode && !validModes.has(objectLockMode)) {
return errors.InvalidArgument.customizeDescription(
'Unknown wormMode directive');
}
const validLegalHolds = new Set(['ON', 'OFF']);
if (objectLegalHold && !validLegalHolds.has(objectLegalHold)) {
return errors.InvalidArgument.customizeDescription(
'Legal hold status must be one of "ON", "OFF"');
}
const currentDate = new Date().toISOString();
if (objectLockMode && objectLockDate <= currentDate) {
return errors.InvalidArgument.customizeDescription(
'The retain until date must be in the future!');
}
return null;
}
/**
* Compares new object retention to bucket default retention
* @param {object} headers - request headers
* @param {object} defaultRetention - bucket retention configuration
* @return {object} - final object lock information to set on object
*/
function compareObjectLockInformation(headers, defaultRetention) {
const objectLockInfoToSave = {};
if (defaultRetention && defaultRetention.rule) {
const defaultMode = defaultRetention.rule.mode;
const defaultTime = calculateRetainUntilDate(defaultRetention.rule);
if (defaultMode && defaultTime) {
objectLockInfoToSave.retentionInfo = {
mode: defaultMode,
date: defaultTime,
};
}
}
if (headers) {
const headerMode = headers['x-amz-object-lock-mode'];
const headerDate = headers['x-amz-object-lock-retain-until-date'];
if (headerMode && headerDate) {
objectLockInfoToSave.retentionInfo = {
mode: headerMode,
date: headerDate,
};
}
const headerLegalHold = headers['x-amz-object-lock-legal-hold'];
if (headerLegalHold) {
const legalHold = headerLegalHold === 'ON';
objectLockInfoToSave.legalHold = legalHold;
}
}
return objectLockInfoToSave;
}
/**
* Sets object retention ond/or legal hold information on object's metadata
* @param {object} headers - request headers
* @param {object} md - object metadata
* @param {(object|null)} defaultRetention - bucket retention configuration if
* bucket has any configuration set
* @return {undefined}
*/
function setObjectLockInformation(headers, md, defaultRetention) {
// Stores retention information if object either has its own retention
// configuration or default retention configuration from its bucket
const finalObjectLockInfo =
compareObjectLockInformation(headers, defaultRetention);
if (finalObjectLockInfo.retentionInfo) {
md.setRetentionMode(finalObjectLockInfo.retentionInfo.mode);
md.setRetentionDate(finalObjectLockInfo.retentionInfo.date);
}
if (finalObjectLockInfo.legalHold || finalObjectLockInfo.legalHold === false) {
md.setLegalHold(finalObjectLockInfo.legalHold);
}
}
/**
* Helper class for check object lock state checks
*/
class ObjectLockInfo {
/**
*
* @param {object} retentionInfo - The object lock retention policy
* @param {"GOVERNANCE" | "COMPLIANCE" | null} retentionInfo.mode - Retention policy mode.
* @param {string} retentionInfo.date - Expiration date of retention policy. A string in ISO-8601 format
* @param {bool} retentionInfo.legalHold - Whether a legal hold is enable for the object
*/
constructor(retentionInfo) {
this.mode = retentionInfo.mode || null;
this.date = retentionInfo.date || null;
this.legalHold = retentionInfo.legalHold || false;
}
/**
* ObjectLockInfo.isLocked
* @returns {bool} - Whether the retention policy is active and protecting the object
*/
isLocked() {
if (this.legalHold) {
return true;
}
if (!this.mode || !this.date) {
return false;
}
return !this.isExpired();
}
/**
* ObjectLockInfo.isGovernanceMode
* @returns {bool} - true if retention mode is GOVERNANCE
*/
isGovernanceMode() {
return this.mode === 'GOVERNANCE';
}
/**
* ObjectLockInfo.isComplianceMode
* @returns {bool} - True if retention mode is COMPLIANCE
*/
isComplianceMode() {
return this.mode === 'COMPLIANCE';
}
/**
* ObjectLockInfo.isExpired
* @returns {bool} - True if the retention policy has expired
*/
isExpired() {
const now = moment();
return this.date === null || now.isSameOrAfter(this.date);
}
/**
* ObjectLockInfo.isExtended
* @param {string} timestamp - Timestamp in ISO-8601 format
* @returns {bool} - True if the given timestamp is after the policy expiration date or if no expiration date is set
*/
isExtended(timestamp) {
return timestamp !== undefined && (this.date === null || moment(timestamp).isSameOrAfter(this.date));
}
/**
* ObjectLockInfo.canModifyObject
* @param {bool} hasGovernanceBypass - Whether to bypass governance retention policies
* @returns {bool} - True if the retention policy allows the objects data to be modified (overwritten/deleted)
*/
canModifyObject(hasGovernanceBypass) {
// can modify object if object is not locked
// cannot modify object in any cases if legal hold is enabled
// if no legal hold, can only modify object if bypassing governance when locked
if (!this.isLocked()) {
return true;
}
return !this.legalHold && this.isGovernanceMode() && !!hasGovernanceBypass;
}
/**
* ObjectLockInfo.canModifyPolicy
* @param {object} policyChanges - Proposed changes to the retention policy
* @param {"GOVERNANCE" | "COMPLIANCE" | undefined} policyChanges.mode - Retention policy mode.
* @param {string} policyChanges.date - Expiration date of retention policy. A string in ISO-8601 format
* @param {bool} hasGovernanceBypass - Whether to bypass governance retention policies
* @returns {bool} - True if the changes are allowed to be applied to the retention policy
*/
canModifyPolicy(policyChanges, hasGovernanceBypass) {
// If an object does not have a retention policy or it is expired then all changes are allowed
if (!this.isLocked()) {
return true;
}
// The only allowed change in compliance mode is extending the retention period
if (this.isComplianceMode()) {
if (policyChanges.mode === 'COMPLIANCE' && this.isExtended(policyChanges.date)) {
return true;
}
}
if (this.isGovernanceMode()) {
// Extensions are always allowed in governance mode
if (policyChanges.mode === 'GOVERNANCE' && this.isExtended(policyChanges.date)) {
return true;
}
// All other changes in governance mode require a bypass
if (hasGovernanceBypass) {
return true;
}
}
return false;
}
}
/**
*
* @param {object} headers - s3 request headers
* @returns {bool} - True if the headers is present and === "true"
*/
function hasGovernanceBypassHeader(headers) {
const bypassHeader = headers['x-amz-bypass-governance-retention'] || '';
return bypassHeader.toLowerCase() === 'true';
}
/**
* checkUserGovernanceBypass
*
* Checks for the presence of the s3:BypassGovernanceRetention permission for a given user
*
* @param {object} request - Incoming s3 request
* @param {object} authInfo - s3 authentication info
* @param {object} bucketMD - bucket metadata
* @param {string} objectKey - object key
* @param {object} log - Werelogs logger
* @param {function} cb - callback returns errors.AccessDenied if the authorization fails
* @returns {undefined} -
*/
function checkUserGovernanceBypass(request, authInfo, bucketMD, objectKey, log, cb) {
log.trace(
'object in GOVERNANCE mode and is user, checking for attached policies',
{ method: 'checkUserPolicyGovernanceBypass' },
);
const authParams = auth.server.extractParams(request, log, 's3', request.query);
const ip = policies.requestUtils.getClientIp(request, config);
const requestContextParams = {
constantParams: {
headers: request.headers,
query: request.query,
generalResource: bucketMD.getName(),
specificResource: { key: objectKey },
requesterIp: ip,
sslEnabled: request.connection.encrypted,
apiMethod: 'bypassGovernanceRetention',
awsService: 's3',
locationConstraint: bucketMD.getLocationConstraint(),
requesterInfo: authInfo,
signatureVersion: authParams.params.data.signatureVersion,
authType: authParams.params.data.authType,
signatureAge: authParams.params.data.signatureAge,
},
};
return vault.checkPolicies(requestContextParams,
authInfo.getArn(), log, (err, authorizationResults) => {
if (err) {
return cb(err);
}
// Deny immediately if there is any explicit deny
const explicitDenyExists = authorizationResults.some(
authzResult => authzResult.isAllowed === false && authzResult.isImplicit === false);
if (explicitDenyExists) {
log.trace('authorization check failed for user',
{
'method': 'checkUserPolicyGovernanceBypass',
's3:BypassGovernanceRetention': false,
});
return cb(errors.AccessDenied);
}
// Convert authorization results into an easier to handle format
const iamAuthzResults = authorizationResults.reduce((acc, curr, idx) => {
// eslint-disable-next-line no-param-reassign
acc[requestContextParams[idx].apiMethod] = curr.isImplicit;
return acc;
}, {});
// Evaluate against the bucket policies
const areAllActionsAllowed = evaluateBucketPolicyWithIAM(
bucketMD,
Object.keys(iamAuthzResults),
authInfo.getCanonicalID(),
authInfo,
iamAuthzResults,
log,
request);
return cb(areAllActionsAllowed ? null : errors.AccessDenied);
});
}
module.exports = {
calculateRetainUntilDate,
compareObjectLockInformation,
setObjectLockInformation,
validateHeaders,
hasGovernanceBypassHeader,
checkUserGovernanceBypass,
ObjectLockInfo,
};