Compare commits

...

6 Commits

Author SHA1 Message Date
Maha Benzekri dc38f54a54
Function name change to standard instead of new 2023-11-21 11:49:46 +01:00
Maha Benzekri 0131eabb97
Fix on skip conditions tests 2023-11-21 09:13:18 +01:00
Maha Benzekri 78ec4b8c14
CLDSRV-428: put apis updated for implicit deny
(cherry picked from commit 402078a55a0c6f010653f4b36ce599db1b018792)
(cherry picked from commit fd691c6493)
2023-11-20 11:52:01 +01:00
Will Toozs 62e15fae7a
CLDSRV-428: put apis updated for implicit deny
(cherry picked from commit 8878814e836d1ac8b4f65367f3c3ded9bdb34615)
(cherry picked from commit 4b3983fb78)
2023-11-20 11:52:01 +01:00
Taylor McKinnon dc35938ae1
possible => unsupported 2023-11-20 11:52:01 +01:00
Taylor McKinnon d7e000128e
bf(CLDSRV-463): Strictly validate checksum algorithm headers 2023-11-20 11:52:00 +01:00
42 changed files with 1695 additions and 1235 deletions

View File

@ -153,6 +153,8 @@ const constants = {
'objectDeleteTagging', 'objectDeleteTagging',
'objectGetTagging', 'objectGetTagging',
'objectPutTagging', 'objectPutTagging',
'objectPutLegalHold',
'objectPutRetention',
], ],
// response header to be sent when there are invalid // response header to be sent when there are invalid
// user metadata in the object's metadata // user metadata in the object's metadata
@ -184,6 +186,16 @@ const constants = {
assumedRoleArnResourceType: 'assumed-role', assumedRoleArnResourceType: 'assumed-role',
// Session name of the backbeat lifecycle assumed role session. // Session name of the backbeat lifecycle assumed role session.
backbeatLifecycleSessionName: 'backbeat-lifecycle', backbeatLifecycleSessionName: 'backbeat-lifecycle',
unsupportedSignatureChecksums: new Set([
'STREAMING-UNSIGNED-PAYLOAD-TRAILER',
'STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER',
'STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD',
'STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD-TRAILER',
]),
supportedSignatureChecksums: new Set([
'UNSIGNED-PAYLOAD',
'STREAMING-AWS4-HMAC-SHA256-PAYLOAD',
]),
}; };
module.exports = constants; module.exports = constants;

View File

@ -0,0 +1,32 @@
const { errors } = require('arsenal');
const { unsupportedSignatureChecksums, supportedSignatureChecksums } = require('../../../../constants');
function validateChecksumHeaders(headers) {
// If the x-amz-trailer header is present the request is using one of the
// trailing checksum algorithms, which are not supported.
if (headers['x-amz-trailer'] !== undefined) {
return errors.BadRequest.customizeDescription('trailing checksum is not supported');
}
const signatureChecksum = headers['x-amz-content-sha256'];
if (signatureChecksum === undefined) {
return null;
}
if (supportedSignatureChecksums.has(signatureChecksum)) {
return null;
}
// If the value is not one of the possible checksum algorithms
// the only other valid value is the actual sha256 checksum of the payload.
// Do a simple sanity check of the length to guard against future algos.
// If the value is an unknown algo, then it will fail checksum validation.
if (!unsupportedSignatureChecksums.has(signatureChecksum) && signatureChecksum.length === 64) {
return null;
}
return errors.BadRequest.customizeDescription('unsupported checksum algorithm');
}
module.exports = validateChecksumHeaders;

View File

@ -6,7 +6,7 @@ const aclUtils = require('../utilities/aclUtils');
const { cleanUpBucket } = require('./apiUtils/bucket/bucketCreation'); const { cleanUpBucket } = require('./apiUtils/bucket/bucketCreation');
const collectCorsHeaders = require('../utilities/collectCorsHeaders'); const collectCorsHeaders = require('../utilities/collectCorsHeaders');
const constants = require('../../constants'); const constants = require('../../constants');
const { metadataValidateBucket } = require('../metadata/metadataUtils'); const { standardMetadataValidateBucket } = require('../metadata/metadataUtils');
const vault = require('../auth/vault'); const vault = require('../auth/vault');
const { pushMetric } = require('../utapi/utilities'); const { pushMetric } = require('../utapi/utilities');
@ -43,7 +43,7 @@ const { pushMetric } = require('../utapi/utilities');
function bucketPutACL(authInfo, request, log, callback) { function bucketPutACL(authInfo, request, log, callback) {
log.debug('processing request', { method: 'bucketPutACL' }); log.debug('processing request', { method: 'bucketPutACL' });
const bucketName = request.bucketName; const { bucketName } = request;
const canonicalID = authInfo.getCanonicalID(); const canonicalID = authInfo.getCanonicalID();
const newCannedACL = request.headers['x-amz-acl']; const newCannedACL = request.headers['x-amz-acl'];
const possibleCannedACL = [ const possibleCannedACL = [
@ -53,17 +53,6 @@ function bucketPutACL(authInfo, request, log, callback) {
'authenticated-read', 'authenticated-read',
'log-delivery-write', 'log-delivery-write',
]; ];
if (newCannedACL && possibleCannedACL.indexOf(newCannedACL) === -1) {
log.trace('invalid canned acl argument', {
acl: newCannedACL,
method: 'bucketPutACL',
});
return callback(errors.InvalidArgument);
}
if (!aclUtils.checkGrantHeaderValidity(request.headers)) {
log.trace('invalid acl header');
return callback(errors.InvalidArgument);
}
const possibleGroups = [constants.allAuthedUsersId, const possibleGroups = [constants.allAuthedUsersId,
constants.publicId, constants.publicId,
constants.logId, constants.logId,
@ -71,7 +60,7 @@ function bucketPutACL(authInfo, request, log, callback) {
const metadataValParams = { const metadataValParams = {
authInfo, authInfo,
bucketName, bucketName,
requestType: 'bucketPutACL', requestType: request.apiMethods || 'bucketPutACL',
request, request,
}; };
const possibleGrants = ['FULL_CONTROL', 'WRITE', const possibleGrants = ['FULL_CONTROL', 'WRITE',
@ -85,24 +74,19 @@ function bucketPutACL(authInfo, request, log, callback) {
READ_ACP: [], READ_ACP: [],
}; };
const grantReadHeader = const grantReadHeader = aclUtils.parseGrant(request.headers[
aclUtils.parseGrant(request.headers[
'x-amz-grant-read'], 'READ'); 'x-amz-grant-read'], 'READ');
const grantWriteHeader = const grantWriteHeader = aclUtils.parseGrant(request.headers['x-amz-grant-write'], 'WRITE');
aclUtils.parseGrant(request.headers['x-amz-grant-write'], 'WRITE'); const grantReadACPHeader = aclUtils.parseGrant(request.headers['x-amz-grant-read-acp'],
const grantReadACPHeader =
aclUtils.parseGrant(request.headers['x-amz-grant-read-acp'],
'READ_ACP'); 'READ_ACP');
const grantWriteACPHeader = const grantWriteACPHeader = aclUtils.parseGrant(request.headers['x-amz-grant-write-acp'],
aclUtils.parseGrant(request.headers['x-amz-grant-write-acp'],
'WRITE_ACP'); 'WRITE_ACP');
const grantFullControlHeader = const grantFullControlHeader = aclUtils.parseGrant(request.headers['x-amz-grant-full-control'],
aclUtils.parseGrant(request.headers['x-amz-grant-full-control'],
'FULL_CONTROL'); 'FULL_CONTROL');
return async.waterfall([ return async.waterfall([
function waterfall1(next) { function waterfall1(next) {
metadataValidateBucket(metadataValParams, log, standardMetadataValidateBucket(metadataValParams, request.actionImplicitDenies, log,
(err, bucket) => { (err, bucket) => {
if (err) { if (err) {
log.trace('request authorization failed', { log.trace('request authorization failed', {
@ -111,6 +95,18 @@ function bucketPutACL(authInfo, request, log, callback) {
}); });
return next(err, bucket); return next(err, bucket);
} }
// if the API call is allowed, ensure that the parameters are valid
if (newCannedACL && possibleCannedACL.indexOf(newCannedACL) === -1) {
log.trace('invalid canned acl argument', {
acl: newCannedACL,
method: 'bucketPutACL',
});
return next(errors.InvalidArgument);
}
if (!aclUtils.checkGrantHeaderValidity(request.headers)) {
log.trace('invalid acl header');
return next(errors.InvalidArgument);
}
return next(null, bucket); return next(null, bucket);
}); });
}, },
@ -193,13 +189,12 @@ function bucketPutACL(authInfo, request, log, callback) {
} else { } else {
// If no canned ACL and no parsed xml, loop // If no canned ACL and no parsed xml, loop
// through the access headers // through the access headers
const allGrantHeaders = const allGrantHeaders = [].concat(grantReadHeader, grantWriteHeader,
[].concat(grantReadHeader, grantWriteHeader,
grantReadACPHeader, grantWriteACPHeader, grantReadACPHeader, grantWriteACPHeader,
grantFullControlHeader); grantFullControlHeader);
usersIdentifiedByEmail = allGrantHeaders.filter(item => usersIdentifiedByEmail = allGrantHeaders.filter(item => item
item && item.userIDType.toLowerCase() === 'emailaddress'); && item.userIDType.toLowerCase() === 'emailaddress');
usersIdentifiedByGroup = allGrantHeaders usersIdentifiedByGroup = allGrantHeaders
.filter(itm => itm && itm.userIDType .filter(itm => itm && itm.userIDType
@ -207,8 +202,10 @@ function bucketPutACL(authInfo, request, log, callback) {
for (let i = 0; i < usersIdentifiedByGroup.length; i++) { for (let i = 0; i < usersIdentifiedByGroup.length; i++) {
const userGroup = usersIdentifiedByGroup[i].identifier; const userGroup = usersIdentifiedByGroup[i].identifier;
if (possibleGroups.indexOf(userGroup) < 0) { if (possibleGroups.indexOf(userGroup) < 0) {
log.trace('invalid user group', { userGroup, log.trace('invalid user group', {
method: 'bucketPutACL' }); userGroup,
method: 'bucketPutACL',
});
return next(errors.InvalidArgument, bucket); return next(errors.InvalidArgument, bucket);
} }
} }
@ -241,8 +238,8 @@ function bucketPutACL(authInfo, request, log, callback) {
return vault.getCanonicalIds(justEmails, log, return vault.getCanonicalIds(justEmails, log,
(err, results) => { (err, results) => {
if (err) { if (err) {
log.trace('error looking up canonical ids', { log.trace('error looking up canonical ids',
error: err, method: 'vault.getCanonicalIDs' }); { error: err, method: 'vault.getCanonicalIDs' });
return next(err, bucket); return next(err, bucket);
} }
const reconstructedUsersIdentifiedByEmail = aclUtils const reconstructedUsersIdentifiedByEmail = aclUtils
@ -251,7 +248,8 @@ function bucketPutACL(authInfo, request, log, callback) {
const allUsers = [].concat( const allUsers = [].concat(
reconstructedUsersIdentifiedByEmail, reconstructedUsersIdentifiedByEmail,
usersIdentifiedByID, usersIdentifiedByID,
usersIdentifiedByGroup); usersIdentifiedByGroup,
);
const revisedAddACLParams = aclUtils const revisedAddACLParams = aclUtils
.sortHeaderGrants(allUsers, addACLParams); .sortHeaderGrants(allUsers, addACLParams);
return next(null, bucket, revisedAddACLParams); return next(null, bucket, revisedAddACLParams);
@ -259,9 +257,9 @@ function bucketPutACL(authInfo, request, log, callback) {
} }
const allUsers = [].concat( const allUsers = [].concat(
usersIdentifiedByID, usersIdentifiedByID,
usersIdentifiedByGroup); usersIdentifiedByGroup,
const revisedAddACLParams = );
aclUtils.sortHeaderGrants(allUsers, addACLParams); const revisedAddACLParams = aclUtils.sortHeaderGrants(allUsers, addACLParams);
return next(null, bucket, revisedAddACLParams); return next(null, bucket, revisedAddACLParams);
}, },
function waterfall4(bucket, addACLParams, next) { function waterfall4(bucket, addACLParams, next) {
@ -272,12 +270,10 @@ function bucketPutACL(authInfo, request, log, callback) {
if (bucket.hasTransientFlag() || bucket.hasDeletedFlag()) { if (bucket.hasTransientFlag() || bucket.hasDeletedFlag()) {
log.trace('transient or deleted flag so cleaning up bucket'); log.trace('transient or deleted flag so cleaning up bucket');
bucket.setFullAcl(addACLParams); bucket.setFullAcl(addACLParams);
return cleanUpBucket(bucket, canonicalID, log, err => return cleanUpBucket(bucket, canonicalID, log, err => next(err, bucket));
next(err, bucket));
} }
// If no bucket flags, just add acl's to bucket metadata // If no bucket flags, just add acl's to bucket metadata
return acl.addACL(bucket, addACLParams, log, err => return acl.addACL(bucket, addACLParams, log, err => next(err, bucket));
next(err, bucket));
}, },
], (err, bucket) => { ], (err, bucket) => {
const corsHeaders = collectCorsHeaders(request.headers.origin, const corsHeaders = collectCorsHeaders(request.headers.origin,

View File

@ -4,8 +4,7 @@ const { errors } = require('arsenal');
const bucketShield = require('./apiUtils/bucket/bucketShield'); const bucketShield = require('./apiUtils/bucket/bucketShield');
const collectCorsHeaders = require('../utilities/collectCorsHeaders'); const collectCorsHeaders = require('../utilities/collectCorsHeaders');
const { isBucketAuthorized } = const { isBucketAuthorized } = require('./apiUtils/authorization/permissionChecks');
require('./apiUtils/authorization/permissionChecks');
const metadata = require('../metadata/wrapper'); const metadata = require('../metadata/wrapper');
const { parseCorsXml } = require('./apiUtils/bucket/bucketCors'); const { parseCorsXml } = require('./apiUtils/bucket/bucketCors');
const { pushMetric } = require('../utapi/utilities'); const { pushMetric } = require('../utapi/utilities');
@ -22,7 +21,7 @@ const requestType = 'bucketPutCors';
*/ */
function bucketPutCors(authInfo, request, log, callback) { function bucketPutCors(authInfo, request, log, callback) {
log.debug('processing request', { method: 'bucketPutCors' }); log.debug('processing request', { method: 'bucketPutCors' });
const bucketName = request.bucketName; const { bucketName } = request;
const canonicalID = authInfo.getCanonicalID(); const canonicalID = authInfo.getCanonicalID();
if (!request.post) { if (!request.post) {
@ -66,7 +65,8 @@ function bucketPutCors(authInfo, request, log, callback) {
}); });
}, },
function validateBucketAuthorization(bucket, rules, corsHeaders, next) { function validateBucketAuthorization(bucket, rules, corsHeaders, next) {
if (!isBucketAuthorized(bucket, requestType, canonicalID, authInfo, log, request)) { if (!isBucketAuthorized(bucket, request.apiMethods || requestType, canonicalID, authInfo,
log, request, request.actionImplicitDenies)) {
log.debug('access denied for account on bucket', { log.debug('access denied for account on bucket', {
requestType, requestType,
}); });
@ -77,8 +77,7 @@ function bucketPutCors(authInfo, request, log, callback) {
function updateBucketMetadata(bucket, rules, corsHeaders, next) { function updateBucketMetadata(bucket, rules, corsHeaders, next) {
log.trace('updating bucket cors rules in metadata'); log.trace('updating bucket cors rules in metadata');
bucket.setCors(rules); bucket.setCors(rules);
metadata.updateBucket(bucketName, bucket, log, err => metadata.updateBucket(bucketName, bucket, log, err => next(err, corsHeaders));
next(err, corsHeaders));
}, },
], (err, corsHeaders) => { ], (err, corsHeaders) => {
if (err) { if (err) {

View File

@ -3,7 +3,7 @@ const async = require('async');
const { parseEncryptionXml } = require('./apiUtils/bucket/bucketEncryption'); const { parseEncryptionXml } = require('./apiUtils/bucket/bucketEncryption');
const { checkExpectedBucketOwner } = require('./apiUtils/authorization/bucketOwner'); const { checkExpectedBucketOwner } = require('./apiUtils/authorization/bucketOwner');
const metadata = require('../metadata/wrapper'); const metadata = require('../metadata/wrapper');
const { metadataValidateBucket } = require('../metadata/metadataUtils'); const { standardMetadataValidateBucket } = require('../metadata/metadataUtils');
const kms = require('../kms/wrapper'); const kms = require('../kms/wrapper');
const { pushMetric } = require('../utapi/utilities'); const { pushMetric } = require('../utapi/utilities');
const collectCorsHeaders = require('../utilities/collectCorsHeaders'); const collectCorsHeaders = require('../utilities/collectCorsHeaders');
@ -18,17 +18,17 @@ const collectCorsHeaders = require('../utilities/collectCorsHeaders');
*/ */
function bucketPutEncryption(authInfo, request, log, callback) { function bucketPutEncryption(authInfo, request, log, callback) {
const bucketName = request.bucketName; const { bucketName } = request;
const metadataValParams = { const metadataValParams = {
authInfo, authInfo,
bucketName, bucketName,
requestType: 'bucketPutEncryption', requestType: request.apiMethods || 'bucketPutEncryption',
request, request,
}; };
return async.waterfall([ return async.waterfall([
next => metadataValidateBucket(metadataValParams, log, next), next => standardMetadataValidateBucket(metadataValParams, request.actionImplicitDenies, log, next),
(bucket, next) => checkExpectedBucketOwner(request.headers, bucket, log, err => next(err, bucket)), (bucket, next) => checkExpectedBucketOwner(request.headers, bucket, log, err => next(err, bucket)),
(bucket, next) => { (bucket, next) => {
log.trace('parsing encryption config', { method: 'bucketPutEncryption' }); log.trace('parsing encryption config', { method: 'bucketPutEncryption' });

View File

@ -1,12 +1,11 @@
const { waterfall } = require('async'); const { waterfall } = require('async');
const uuid = require('uuid/v4'); const uuid = require('uuid/v4');
const LifecycleConfiguration = const { LifecycleConfiguration } = require('arsenal').models;
require('arsenal').models.LifecycleConfiguration;
const parseXML = require('../utilities/parseXML'); const parseXML = require('../utilities/parseXML');
const collectCorsHeaders = require('../utilities/collectCorsHeaders'); const collectCorsHeaders = require('../utilities/collectCorsHeaders');
const metadata = require('../metadata/wrapper'); const metadata = require('../metadata/wrapper');
const { metadataValidateBucket } = require('../metadata/metadataUtils'); const { standardMetadataValidateBucket } = require('../metadata/metadataUtils');
const { pushMetric } = require('../utapi/utilities'); const { pushMetric } = require('../utapi/utilities');
/** /**
@ -21,11 +20,11 @@ const { pushMetric } = require('../utapi/utilities');
function bucketPutLifecycle(authInfo, request, log, callback) { function bucketPutLifecycle(authInfo, request, log, callback) {
log.debug('processing request', { method: 'bucketPutLifecycle' }); log.debug('processing request', { method: 'bucketPutLifecycle' });
const bucketName = request.bucketName; const { bucketName } = request;
const metadataValParams = { const metadataValParams = {
authInfo, authInfo,
bucketName, bucketName,
requestType: 'bucketPutLifecycle', requestType: request.apiMethods || 'bucketPutLifecycle',
request, request,
}; };
return waterfall([ return waterfall([
@ -42,7 +41,7 @@ function bucketPutLifecycle(authInfo, request, log, callback) {
return next(null, configObj); return next(null, configObj);
}); });
}, },
(lcConfig, next) => metadataValidateBucket(metadataValParams, log, (lcConfig, next) => standardMetadataValidateBucket(metadataValParams, request.actionImplicitDenies, log,
(err, bucket) => { (err, bucket) => {
if (err) { if (err) {
return next(err, bucket); return next(err, bucket);
@ -54,8 +53,7 @@ function bucketPutLifecycle(authInfo, request, log, callback) {
bucket.setUid(uuid()); bucket.setUid(uuid());
} }
bucket.setLifecycleConfiguration(lcConfig); bucket.setLifecycleConfiguration(lcConfig);
metadata.updateBucket(bucket.getName(), bucket, log, err => metadata.updateBucket(bucket.getName(), bucket, log, err => next(err, bucket));
next(err, bucket));
}, },
], (err, bucket) => { ], (err, bucket) => {
const corsHeaders = collectCorsHeaders(request.headers.origin, const corsHeaders = collectCorsHeaders(request.headers.origin,

View File

@ -4,7 +4,7 @@ const parseXML = require('../utilities/parseXML');
const collectCorsHeaders = require('../utilities/collectCorsHeaders'); const collectCorsHeaders = require('../utilities/collectCorsHeaders');
const getNotificationConfiguration = require('./apiUtils/bucket/getNotificationConfiguration'); const getNotificationConfiguration = require('./apiUtils/bucket/getNotificationConfiguration');
const metadata = require('../metadata/wrapper'); const metadata = require('../metadata/wrapper');
const { metadataValidateBucket } = require('../metadata/metadataUtils'); const { standardMetadataValidateBucket } = require('../metadata/metadataUtils');
const { pushMetric } = require('../utapi/utilities'); const { pushMetric } = require('../utapi/utilities');
/** /**
@ -19,11 +19,11 @@ const { pushMetric } = require('../utapi/utilities');
function bucketPutNotification(authInfo, request, log, callback) { function bucketPutNotification(authInfo, request, log, callback) {
log.debug('processing request', { method: 'bucketPutNotification' }); log.debug('processing request', { method: 'bucketPutNotification' });
const bucketName = request.bucketName; const { bucketName } = request;
const metadataValParams = { const metadataValParams = {
authInfo, authInfo,
bucketName, bucketName,
requestType: 'bucketPutNotification', requestType: request.apiMethods || 'bucketPutNotification',
request, request,
}; };
@ -34,7 +34,7 @@ function bucketPutNotification(authInfo, request, log, callback) {
const notifConfig = notificationConfig.error ? undefined : notificationConfig; const notifConfig = notificationConfig.error ? undefined : notificationConfig;
process.nextTick(() => next(notificationConfig.error, notifConfig)); process.nextTick(() => next(notificationConfig.error, notifConfig));
}, },
(notifConfig, next) => metadataValidateBucket(metadataValParams, log, (notifConfig, next) => standardMetadataValidateBucket(metadataValParams, request.actionImplicitDenies, log,
(err, bucket) => next(err, bucket, notifConfig)), (err, bucket) => next(err, bucket, notifConfig)),
(bucket, notifConfig, next) => { (bucket, notifConfig, next) => {
bucket.setNotificationConfiguration(notifConfig); bucket.setNotificationConfiguration(notifConfig);
@ -45,8 +45,10 @@ function bucketPutNotification(authInfo, request, log, callback) {
const corsHeaders = collectCorsHeaders(request.headers.origin, const corsHeaders = collectCorsHeaders(request.headers.origin,
request.method, bucket); request.method, bucket);
if (err) { if (err) {
log.trace('error processing request', { error: err, log.trace('error processing request', {
method: 'bucketPutNotification' }); error: err,
method: 'bucketPutNotification',
});
return callback(err, corsHeaders); return callback(err, corsHeaders);
} }
pushMetric('putBucketNotification', log, { pushMetric('putBucketNotification', log, {

View File

@ -1,13 +1,13 @@
const { waterfall } = require('async'); const { waterfall } = require('async');
const arsenal = require('arsenal'); const arsenal = require('arsenal');
const errors = arsenal.errors; const { errors } = arsenal;
const ObjectLockConfiguration = arsenal.models.ObjectLockConfiguration; const { ObjectLockConfiguration } = arsenal.models;
const parseXML = require('../utilities/parseXML'); const parseXML = require('../utilities/parseXML');
const collectCorsHeaders = require('../utilities/collectCorsHeaders'); const collectCorsHeaders = require('../utilities/collectCorsHeaders');
const metadata = require('../metadata/wrapper'); const metadata = require('../metadata/wrapper');
const { metadataValidateBucket } = require('../metadata/metadataUtils'); const { standardMetadataValidateBucket } = require('../metadata/metadataUtils');
const { pushMetric } = require('../utapi/utilities'); const { pushMetric } = require('../utapi/utilities');
/** /**
@ -22,11 +22,11 @@ const { pushMetric } = require('../utapi/utilities');
function bucketPutObjectLock(authInfo, request, log, callback) { function bucketPutObjectLock(authInfo, request, log, callback) {
log.debug('processing request', { method: 'bucketPutObjectLock' }); log.debug('processing request', { method: 'bucketPutObjectLock' });
const bucketName = request.bucketName; const { bucketName } = request;
const metadataValParams = { const metadataValParams = {
authInfo, authInfo,
bucketName, bucketName,
requestType: 'bucketPutObjectLock', requestType: request.apiMethods || 'bucketPutObjectLock',
request, request,
}; };
return waterfall([ return waterfall([
@ -36,12 +36,12 @@ function bucketPutObjectLock(authInfo, request, log, callback) {
// if there was an error getting object lock configuration, // if there was an error getting object lock configuration,
// returned configObj will contain 'error' key // returned configObj will contain 'error' key
process.nextTick(() => { process.nextTick(() => {
const configObj = lockConfigClass. const configObj = lockConfigClass
getValidatedObjectLockConfiguration(); .getValidatedObjectLockConfiguration();
return next(configObj.error || null, configObj); return next(configObj.error || null, configObj);
}); });
}, },
(objectLockConfig, next) => metadataValidateBucket(metadataValParams, (objectLockConfig, next) => standardMetadataValidateBucket(metadataValParams, request.actionImplicitDenies,
log, (err, bucket) => { log, (err, bucket) => {
if (err) { if (err) {
return next(err, bucket); return next(err, bucket);
@ -53,23 +53,25 @@ function bucketPutObjectLock(authInfo, request, log, callback) {
process.nextTick(() => { process.nextTick(() => {
if (!isObjectLockEnabled) { if (!isObjectLockEnabled) {
return next(errors.InvalidBucketState.customizeDescription( return next(errors.InvalidBucketState.customizeDescription(
'Object Lock configuration cannot be enabled on ' + 'Object Lock configuration cannot be enabled on '
'existing buckets'), bucket); + 'existing buckets',
), bucket);
} }
return next(null, bucket, objectLockConfig); return next(null, bucket, objectLockConfig);
}); });
}, },
(bucket, objectLockConfig, next) => { (bucket, objectLockConfig, next) => {
bucket.setObjectLockConfiguration(objectLockConfig); bucket.setObjectLockConfiguration(objectLockConfig);
metadata.updateBucket(bucket.getName(), bucket, log, err => metadata.updateBucket(bucket.getName(), bucket, log, err => next(err, bucket));
next(err, bucket));
}, },
], (err, bucket) => { ], (err, bucket) => {
const corsHeaders = collectCorsHeaders(request.headers.origin, const corsHeaders = collectCorsHeaders(request.headers.origin,
request.method, bucket); request.method, bucket);
if (err) { if (err) {
log.trace('error processing request', { error: err, log.trace('error processing request', {
method: 'bucketPutObjectLock' }); error: err,
method: 'bucketPutObjectLock',
});
return callback(err, corsHeaders); return callback(err, corsHeaders);
} }
pushMetric('putBucketObjectLock', log, { pushMetric('putBucketObjectLock', log, {

View File

@ -3,7 +3,7 @@ const { errors, models } = require('arsenal');
const collectCorsHeaders = require('../utilities/collectCorsHeaders'); const collectCorsHeaders = require('../utilities/collectCorsHeaders');
const metadata = require('../metadata/wrapper'); const metadata = require('../metadata/wrapper');
const { metadataValidateBucket } = require('../metadata/metadataUtils'); const { standardMetadataValidateBucket } = require('../metadata/metadataUtils');
const { validatePolicyResource } = const { validatePolicyResource } =
require('./apiUtils/authorization/permissionChecks'); require('./apiUtils/authorization/permissionChecks');
const { BucketPolicy } = models; const { BucketPolicy } = models;
@ -37,7 +37,7 @@ function bucketPutPolicy(authInfo, request, log, callback) {
const metadataValParams = { const metadataValParams = {
authInfo, authInfo,
bucketName, bucketName,
requestType: 'bucketPutPolicy', requestType: request.apiMethods || 'bucketPutPolicy',
request, request,
}; };
@ -45,7 +45,7 @@ function bucketPutPolicy(authInfo, request, log, callback) {
next => { next => {
const bucketPolicy = new BucketPolicy(request.post); const bucketPolicy = new BucketPolicy(request.post);
// if there was an error getting bucket policy, // if there was an error getting bucket policy,
// returned policyObj will contain 'error' key // returned policyObj will contain 'error' keys
process.nextTick(() => { process.nextTick(() => {
const policyObj = bucketPolicy.getBucketPolicy(); const policyObj = bucketPolicy.getBucketPolicy();
if (_checkNotImplementedPolicy(request.post)) { if (_checkNotImplementedPolicy(request.post)) {
@ -70,7 +70,7 @@ function bucketPutPolicy(authInfo, request, log, callback) {
return next(null, bucketPolicy); return next(null, bucketPolicy);
}); });
}, },
(bucketPolicy, next) => metadataValidateBucket(metadataValParams, log, (bucketPolicy, next) => standardMetadataValidateBucket(metadataValParams, request.actionImplicitDenies, log,
(err, bucket) => { (err, bucket) => {
if (err) { if (err) {
return next(err, bucket); return next(err, bucket);

View File

@ -2,7 +2,7 @@ const { waterfall } = require('async');
const { errors } = require('arsenal'); const { errors } = require('arsenal');
const metadata = require('../metadata/wrapper'); const metadata = require('../metadata/wrapper');
const { metadataValidateBucket } = require('../metadata/metadataUtils'); const { standardMetadataValidateBucket } = require('../metadata/metadataUtils');
const { pushMetric } = require('../utapi/utilities'); const { pushMetric } = require('../utapi/utilities');
const { getReplicationConfiguration } = const { getReplicationConfiguration } =
require('./apiUtils/bucket/getReplicationConfiguration'); require('./apiUtils/bucket/getReplicationConfiguration');
@ -27,7 +27,7 @@ function bucketPutReplication(authInfo, request, log, callback) {
const metadataValParams = { const metadataValParams = {
authInfo, authInfo,
bucketName, bucketName,
requestType: 'bucketPutReplication', requestType: request.apiMethods || 'bucketPutReplication',
request, request,
}; };
return waterfall([ return waterfall([
@ -36,7 +36,7 @@ function bucketPutReplication(authInfo, request, log, callback) {
// Check bucket user privileges and ensure versioning is 'Enabled'. // Check bucket user privileges and ensure versioning is 'Enabled'.
(config, next) => (config, next) =>
// TODO: Validate that destination bucket exists and has versioning. // TODO: Validate that destination bucket exists and has versioning.
metadataValidateBucket(metadataValParams, log, (err, bucket) => { standardMetadataValidateBucket(metadataValParams, request.actionImplicitDenies, log, (err, bucket) => {
if (err) { if (err) {
return next(err); return next(err);
} }

View File

@ -4,7 +4,7 @@ const { errors } = require('arsenal');
const collectCorsHeaders = require('../utilities/collectCorsHeaders'); const collectCorsHeaders = require('../utilities/collectCorsHeaders');
const metadata = require('../metadata/wrapper'); const metadata = require('../metadata/wrapper');
const { metadataValidateBucket } = require('../metadata/metadataUtils'); const { standardMetadataValidateBucket } = require('../metadata/metadataUtils');
const { pushMetric } = require('../utapi/utilities'); const { pushMetric } = require('../utapi/utilities');
const versioningNotImplBackends = const versioningNotImplBackends =
require('../../constants').versioningNotImplBackends; require('../../constants').versioningNotImplBackends;
@ -87,13 +87,13 @@ function bucketPutVersioning(authInfo, request, log, callback) {
const metadataValParams = { const metadataValParams = {
authInfo, authInfo,
bucketName, bucketName,
requestType: 'bucketPutVersioning', requestType: request.apiMethods || 'bucketPutVersioning',
request, request,
}; };
return waterfall([ return waterfall([
next => _parseXML(request, log, next), next => _parseXML(request, log, next),
next => metadataValidateBucket(metadataValParams, log, next => standardMetadataValidateBucket(metadataValParams, request.actionImplicitDenies, log,
(err, bucket) => next(err, bucket)), // ignore extra null object, (err, bucket) => next(err, bucket)), // ignore extra null object,
(bucket, next) => parseString(request.post, (err, result) => { (bucket, next) => parseString(request.post, (err, result) => {
// just for linting; there should not be any parsing error here // just for linting; there should not be any parsing error here

View File

@ -46,7 +46,8 @@ function bucketPutWebsite(authInfo, request, log, callback) {
}); });
}, },
function validateBucketAuthorization(bucket, config, next) { function validateBucketAuthorization(bucket, config, next) {
if (!isBucketAuthorized(bucket, requestType, canonicalID, authInfo, log, request)) { if (!isBucketAuthorized(bucket, request.apiMethods || requestType, canonicalID, authInfo,
log, request, request.actionImplicitDenies)) {
log.debug('access denied for user on bucket', { log.debug('access denied for user on bucket', {
requestType, requestType,
method: 'bucketPutWebsite', method: 'bucketPutWebsite',

View File

@ -7,13 +7,14 @@ const { getObjectSSEConfiguration } = require('./apiUtils/bucket/bucketEncryptio
const collectCorsHeaders = require('../utilities/collectCorsHeaders'); const collectCorsHeaders = require('../utilities/collectCorsHeaders');
const createAndStoreObject = require('./apiUtils/object/createAndStoreObject'); const createAndStoreObject = require('./apiUtils/object/createAndStoreObject');
const { checkQueryVersionId } = require('./apiUtils/object/versioning'); const { checkQueryVersionId } = require('./apiUtils/object/versioning');
const { metadataValidateBucketAndObj } = require('../metadata/metadataUtils'); const { standardMetadataValidateBucketAndObj } = require('../metadata/metadataUtils');
const { pushMetric } = require('../utapi/utilities'); const { pushMetric } = require('../utapi/utilities');
const { validateHeaders } = require('./apiUtils/object/objectLockHelpers'); const { validateHeaders } = require('./apiUtils/object/objectLockHelpers');
const { hasNonPrintables } = require('../utilities/stringChecks'); const { hasNonPrintables } = require('../utilities/stringChecks');
const kms = require('../kms/wrapper'); const kms = require('../kms/wrapper');
const { config } = require('../Config'); const { config } = require('../Config');
const { setExpirationHeaders } = require('./apiUtils/object/expirationHeaders'); const { setExpirationHeaders } = require('./apiUtils/object/expirationHeaders');
const validateChecksumHeaders = require('./apiUtils/object/validateChecksumHeaders');
const writeContinue = require('../utilities/writeContinue'); const writeContinue = require('../utilities/writeContinue');
const versionIdUtils = versioning.VersionID; const versionIdUtils = versioning.VersionID;
@ -57,7 +58,7 @@ function objectPut(authInfo, request, streamingV4Params, log, callback) {
} }
const invalidSSEError = errors.InvalidArgument.customizeDescription( const invalidSSEError = errors.InvalidArgument.customizeDescription(
'The encryption method specified is not supported'); 'The encryption method specified is not supported');
const requestType = 'objectPut'; const requestType = request.apiMethods || 'objectPut';
const valParams = { authInfo, bucketName, objectKey, requestType, request }; const valParams = { authInfo, bucketName, objectKey, requestType, request };
const canonicalID = authInfo.getCanonicalID(); const canonicalID = authInfo.getCanonicalID();
@ -67,9 +68,13 @@ function objectPut(authInfo, request, streamingV4Params, log, callback) {
)); ));
} }
log.trace('owner canonicalID to send to data', { canonicalID }); const checksumHeaderErr = validateChecksumHeaders(headers);
if (checksumHeaderErr) {
return callback(checksumHeaderErr);
}
return metadataValidateBucketAndObj(valParams, log, log.trace('owner canonicalID to send to data', { canonicalID });
return standardMetadataValidateBucketAndObj(valParams, request.actionImplicitDenies, log,
(err, bucket, objMD) => { (err, bucket, objMD) => {
const responseHeaders = collectCorsHeaders(headers.origin, const responseHeaders = collectCorsHeaders(headers.origin,
method, bucket); method, bucket);

View File

@ -7,9 +7,8 @@ const { pushMetric } = require('../utapi/utilities');
const collectCorsHeaders = require('../utilities/collectCorsHeaders'); const collectCorsHeaders = require('../utilities/collectCorsHeaders');
const constants = require('../../constants'); const constants = require('../../constants');
const vault = require('../auth/vault'); const vault = require('../auth/vault');
const { decodeVersionId, getVersionIdResHeader } const { decodeVersionId, getVersionIdResHeader } = require('./apiUtils/object/versioning');
= require('./apiUtils/object/versioning'); const { standardMetadataValidateBucketAndObj } = require('../metadata/metadataUtils');
const { metadataValidateBucketAndObj } = require('../metadata/metadataUtils');
/* /*
Format of xml request: Format of xml request:
@ -43,8 +42,8 @@ const { metadataValidateBucketAndObj } = require('../metadata/metadataUtils');
*/ */
function objectPutACL(authInfo, request, log, cb) { function objectPutACL(authInfo, request, log, cb) {
log.debug('processing request', { method: 'objectPutACL' }); log.debug('processing request', { method: 'objectPutACL' });
const bucketName = request.bucketName; const { bucketName } = request;
const objectKey = request.objectKey; const { objectKey } = request;
const newCannedACL = request.headers['x-amz-acl']; const newCannedACL = request.headers['x-amz-acl'];
const possibleCannedACL = [ const possibleCannedACL = [
'private', 'private',
@ -82,8 +81,8 @@ function objectPutACL(authInfo, request, log, cb) {
authInfo, authInfo,
bucketName, bucketName,
objectKey, objectKey,
requestType: 'objectPutACL',
versionId: reqVersionId, versionId: reqVersionId,
requestType: request.apiMethods || 'objectPutACL',
}; };
const possibleGrants = ['FULL_CONTROL', 'WRITE_ACP', 'READ', 'READ_ACP']; const possibleGrants = ['FULL_CONTROL', 'WRITE_ACP', 'READ', 'READ_ACP'];
@ -95,26 +94,26 @@ function objectPutACL(authInfo, request, log, cb) {
READ_ACP: [], READ_ACP: [],
}; };
const grantReadHeader = const grantReadHeader = aclUtils.parseGrant(request.headers['x-amz-grant-read'], 'READ');
aclUtils.parseGrant(request.headers['x-amz-grant-read'], 'READ'); const grantReadACPHeader = aclUtils.parseGrant(request.headers['x-amz-grant-read-acp'],
const grantReadACPHeader =
aclUtils.parseGrant(request.headers['x-amz-grant-read-acp'],
'READ_ACP'); 'READ_ACP');
const grantWriteACPHeader = aclUtils.parseGrant( const grantWriteACPHeader = aclUtils.parseGrant(
request.headers['x-amz-grant-write-acp'], 'WRITE_ACP'); request.headers['x-amz-grant-write-acp'], 'WRITE_ACP',
);
const grantFullControlHeader = aclUtils.parseGrant( const grantFullControlHeader = aclUtils.parseGrant(
request.headers['x-amz-grant-full-control'], 'FULL_CONTROL'); request.headers['x-amz-grant-full-control'], 'FULL_CONTROL',
);
return async.waterfall([ return async.waterfall([
function validateBucketAndObj(next) { function validateBucketAndObj(next) {
return metadataValidateBucketAndObj(metadataValParams, log, return standardMetadataValidateBucketAndObj(metadataValParams, request.actionImplicitDenies, log,
(err, bucket, objectMD) => { (err, bucket, objectMD) => {
if (err) { if (err) {
return next(err); return next(err);
} }
if (!objectMD) { if (!objectMD) {
const err = reqVersionId ? errors.NoSuchVersion : const err = reqVersionId ? errors.NoSuchVersion
errors.NoSuchKey; : errors.NoSuchKey;
return next(err, bucket); return next(err, bucket);
} }
if (objectMD.isDeleteMarker) { if (objectMD.isDeleteMarker) {
@ -216,22 +215,24 @@ function objectPutACL(authInfo, request, log, cb) {
} else { } else {
// If no canned ACL and no parsed xml, loop // If no canned ACL and no parsed xml, loop
// through the access headers // through the access headers
const allGrantHeaders = const allGrantHeaders = [].concat(grantReadHeader,
[].concat(grantReadHeader,
grantReadACPHeader, grantWriteACPHeader, grantReadACPHeader, grantWriteACPHeader,
grantFullControlHeader); grantFullControlHeader);
usersIdentifiedByEmail = allGrantHeaders.filter(item => usersIdentifiedByEmail = allGrantHeaders.filter(item => item
item && item.userIDType.toLowerCase() === 'emailaddress'); && item.userIDType.toLowerCase() === 'emailaddress');
usersIdentifiedByGroup = allGrantHeaders usersIdentifiedByGroup = allGrantHeaders
.filter(itm => itm && itm.userIDType .filter(itm => itm && itm.userIDType
.toLowerCase() === 'uri'); .toLowerCase() === 'uri');
for (let i = 0; i < usersIdentifiedByGroup.length; i++) { for (let i = 0; i < usersIdentifiedByGroup.length; i += 1) {
if (possibleGroups.indexOf( if (possibleGroups.indexOf(
usersIdentifiedByGroup[i].identifier) < 0) { usersIdentifiedByGroup[i].identifier,
) < 0) {
log.trace('invalid user group', log.trace('invalid user group',
{ userGroup: usersIdentifiedByGroup[i] {
.identifier }); userGroup: usersIdentifiedByGroup[i]
.identifier,
});
return next(errors.InvalidArgument, bucket); return next(errors.InvalidArgument, bucket);
} }
} }
@ -259,18 +260,20 @@ function objectPutACL(authInfo, request, log, cb) {
const allUsers = [].concat( const allUsers = [].concat(
reconstructedUsersIdentifiedByEmail, reconstructedUsersIdentifiedByEmail,
usersIdentifiedByID, usersIdentifiedByID,
usersIdentifiedByGroup); usersIdentifiedByGroup,
);
const revisedAddACLParams = aclUtils const revisedAddACLParams = aclUtils
.sortHeaderGrants(allUsers, addACLParams); .sortHeaderGrants(allUsers, addACLParams);
return next(null, bucket, objectMD, return next(null, bucket, objectMD,
revisedAddACLParams); revisedAddACLParams);
}); },
);
} }
const allUsers = [].concat( const allUsers = [].concat(
usersIdentifiedByID, usersIdentifiedByID,
usersIdentifiedByGroup); usersIdentifiedByGroup,
const revisedAddACLParams = );
aclUtils.sortHeaderGrants(allUsers, addACLParams); const revisedAddACLParams = aclUtils.sortHeaderGrants(allUsers, addACLParams);
return next(null, bucket, objectMD, revisedAddACLParams); return next(null, bucket, objectMD, revisedAddACLParams);
}, },
function addAclsToObjMD(bucket, objectMD, ACLParams, next) { function addAclsToObjMD(bucket, objectMD, ACLParams, next) {
@ -292,8 +295,7 @@ function objectPutACL(authInfo, request, log, cb) {
} }
const verCfg = bucket.getVersioningConfiguration(); const verCfg = bucket.getVersioningConfiguration();
resHeaders['x-amz-version-id'] = resHeaders['x-amz-version-id'] = getVersionIdResHeader(verCfg, objectMD);
getVersionIdResHeader(verCfg, objectMD);
log.trace('processed request successfully in object put acl api'); log.trace('processed request successfully in object put acl api');
pushMetric('putObjectAcl', log, { pushMetric('putObjectAcl', log, {

View File

@ -1,18 +1,18 @@
const async = require('async'); const async = require('async');
const { errors, versioning, s3middleware } = require('arsenal'); const { errors, versioning, s3middleware } = require('arsenal');
const validateHeaders = s3middleware.validateConditionalHeaders; const validateHeaders = s3middleware.validateConditionalHeaders;
const collectCorsHeaders = require('../utilities/collectCorsHeaders'); const collectCorsHeaders = require('../utilities/collectCorsHeaders');
const constants = require('../../constants'); const constants = require('../../constants');
const { data } = require('../data/wrapper'); const { data } = require('../data/wrapper');
const locationConstraintCheck = const locationConstraintCheck = require('./apiUtils/object/locationConstraintCheck');
require('./apiUtils/object/locationConstraintCheck');
const metadata = require('../metadata/wrapper'); const metadata = require('../metadata/wrapper');
const { pushMetric } = require('../utapi/utilities'); const { pushMetric } = require('../utapi/utilities');
const logger = require('../utilities/logger'); const logger = require('../utilities/logger');
const services = require('../services'); const services = require('../services');
const setUpCopyLocator = require('./apiUtils/object/setUpCopyLocator'); const setUpCopyLocator = require('./apiUtils/object/setUpCopyLocator');
const { metadataValidateBucketAndObj } = require('../metadata/metadataUtils'); const { standardMetadataValidateBucketAndObj } = require('../metadata/metadataUtils');
const versionIdUtils = versioning.VersionID; const versionIdUtils = versioning.VersionID;
const { config } = require('../Config'); const { config } = require('../Config');
@ -58,8 +58,7 @@ function objectPutCopyPart(authInfo, request, sourceBucket,
// Note that keys in the query object retain their case, so // Note that keys in the query object retain their case, so
// request.query.uploadId must be called with that exact // request.query.uploadId must be called with that exact
// capitalization // capitalization
const uploadId = request.query.uploadId; const { uploadId } = request.query;
const valPutParams = { const valPutParams = {
authInfo, authInfo,
bucketName: destBucketName, bucketName: destBucketName,
@ -89,26 +88,26 @@ function objectPutCopyPart(authInfo, request, sourceBucket,
return async.waterfall([ return async.waterfall([
function checkDestAuth(next) { function checkDestAuth(next) {
return metadataValidateBucketAndObj(valPutParams, log, return standardMetadataValidateBucketAndObj(valPutParams, request.actionImplicitDenies, log,
(err, destBucketMD) => { (err, destBucketMD) => {
if (err) { if (err) {
log.debug('error validating authorization for ' + log.debug('error validating authorization for '
'destination bucket', + 'destination bucket',
{ error: err }); { error: err });
return next(err, destBucketMD); return next(err, destBucketMD);
} }
const flag = destBucketMD.hasDeletedFlag() const flag = destBucketMD.hasDeletedFlag()
|| destBucketMD.hasTransientFlag(); || destBucketMD.hasTransientFlag();
if (flag) { if (flag) {
log.trace('deleted flag or transient flag ' + log.trace('deleted flag or transient flag '
'on destination bucket', { flag }); + 'on destination bucket', { flag });
return next(errors.NoSuchBucket); return next(errors.NoSuchBucket);
} }
return next(null, destBucketMD); return next(null, destBucketMD);
}); });
}, },
function checkSourceAuthorization(destBucketMD, next) { function checkSourceAuthorization(destBucketMD, next) {
return metadataValidateBucketAndObj(valGetParams, log, return standardMetadataValidateBucketAndObj(valGetParams, request.actionImplicitDenies, log,
(err, sourceBucketMD, sourceObjMD) => { (err, sourceBucketMD, sourceObjMD) => {
if (err) { if (err) {
log.debug('error validating get part of request', log.debug('error validating get part of request',
@ -117,28 +116,26 @@ function objectPutCopyPart(authInfo, request, sourceBucket,
} }
if (!sourceObjMD) { if (!sourceObjMD) {
log.debug('no source object', { sourceObject }); log.debug('no source object', { sourceObject });
const err = reqVersionId ? errors.NoSuchVersion : const err = reqVersionId ? errors.NoSuchVersion
errors.NoSuchKey; : errors.NoSuchKey;
return next(err, destBucketMD); return next(err, destBucketMD);
} }
let sourceLocationConstraintName = let sourceLocationConstraintName = sourceObjMD.dataStoreName;
sourceObjMD.dataStoreName;
// for backwards compatibility before storing dataStoreName // for backwards compatibility before storing dataStoreName
// TODO: handle in objectMD class // TODO: handle in objectMD class
if (!sourceLocationConstraintName && if (!sourceLocationConstraintName
sourceObjMD.location[0] && && sourceObjMD.location[0]
sourceObjMD.location[0].dataStoreName) { && sourceObjMD.location[0].dataStoreName) {
sourceLocationConstraintName = sourceLocationConstraintName = sourceObjMD.location[0].dataStoreName;
sourceObjMD.location[0].dataStoreName;
} }
if (sourceObjMD.isDeleteMarker) { if (sourceObjMD.isDeleteMarker) {
log.debug('delete marker on source object', log.debug('delete marker on source object',
{ sourceObject }); { sourceObject });
if (reqVersionId) { if (reqVersionId) {
const err = errors.InvalidRequest const err = errors.InvalidRequest
.customizeDescription('The source of a copy ' + .customizeDescription('The source of a copy '
'request may not specifically refer to a delete' + + 'request may not specifically refer to a delete'
'marker by version id.'); + 'marker by version id.');
return next(err, destBucketMD); return next(err, destBucketMD);
} }
// if user specifies a key in a versioned source bucket // if user specifies a key in a versioned source bucket
@ -146,8 +143,7 @@ function objectPutCopyPart(authInfo, request, sourceBucket,
// delete marker, return NoSuchKey // delete marker, return NoSuchKey
return next(errors.NoSuchKey, destBucketMD); return next(errors.NoSuchKey, destBucketMD);
} }
const headerValResult = const headerValResult = validateHeaders(request.headers,
validateHeaders(request.headers,
sourceObjMD['last-modified'], sourceObjMD['last-modified'],
sourceObjMD['content-md5']); sourceObjMD['content-md5']);
if (headerValResult.error) { if (headerValResult.error) {
@ -162,15 +158,15 @@ function objectPutCopyPart(authInfo, request, sourceBucket,
// If specific version requested, include copy source // If specific version requested, include copy source
// version id in response. Include in request by default // version id in response. Include in request by default
// if versioning is enabled or suspended. // if versioning is enabled or suspended.
if (sourceBucketMD.getVersioningConfiguration() || if (sourceBucketMD.getVersioningConfiguration()
reqVersionId) { || reqVersionId) {
if (sourceObjMD.isNull || !sourceObjMD.versionId) { if (sourceObjMD.isNull || !sourceObjMD.versionId) {
sourceVerId = 'null'; sourceVerId = 'null';
} else { } else {
sourceVerId = sourceVerId = versionIdUtils.encode(
versionIdUtils.encode(
sourceObjMD.versionId, sourceObjMD.versionId,
config.versionIdEncodingType); config.versionIdEncodingType,
);
} }
} }
return next(null, copyLocator.dataLocator, destBucketMD, return next(null, copyLocator.dataLocator, destBucketMD,
@ -195,7 +191,7 @@ function objectPutCopyPart(authInfo, request, sourceBucket,
}); });
return next(err); return next(err);
} }
let splitter = constants.splitter; let { splitter } = constants;
if (mpuBucket.getMdBucketModelVersion() < 2) { if (mpuBucket.getMdBucketModelVersion() < 2) {
splitter = constants.oldSplitter; splitter = constants.oldSplitter;
} }
@ -209,8 +205,7 @@ function objectPutCopyPart(authInfo, request, sourceBucket,
function getMpuOverviewObject(dataLocator, destBucketMD, function getMpuOverviewObject(dataLocator, destBucketMD,
copyObjectSize, sourceVerId, splitter, copyObjectSize, sourceVerId, splitter,
sourceLocationConstraintName, next) { sourceLocationConstraintName, next) {
const mpuOverviewKey = const mpuOverviewKey = `overview${splitter}${destObjectKey}${splitter}${uploadId}`;
`overview${splitter}${destObjectKey}${splitter}${uploadId}`;
return metadata.getObjectMD(mpuBucketName, mpuOverviewKey, return metadata.getObjectMD(mpuBucketName, mpuOverviewKey,
null, log, (err, res) => { null, log, (err, res) => {
if (err) { if (err) {
@ -218,22 +213,21 @@ function objectPutCopyPart(authInfo, request, sourceBucket,
if (err.NoSuchKey) { if (err.NoSuchKey) {
return next(errors.NoSuchUpload); return next(errors.NoSuchUpload);
} }
log.error('error getting overview object from ' + log.error('error getting overview object from '
'mpu bucket', { + 'mpu bucket', {
error: err, error: err,
method: 'objectPutCopyPart::' + method: 'objectPutCopyPart::'
'metadata.getObjectMD', + 'metadata.getObjectMD',
}); });
return next(err); return next(err);
} }
const initiatorID = res.initiator.ID; const initiatorID = res.initiator.ID;
const requesterID = authInfo.isRequesterAnIAMUser() ? const requesterID = authInfo.isRequesterAnIAMUser()
authInfo.getArn() : authInfo.getCanonicalID(); ? authInfo.getArn() : authInfo.getCanonicalID();
if (initiatorID !== requesterID) { if (initiatorID !== requesterID) {
return next(errors.AccessDenied); return next(errors.AccessDenied);
} }
const destObjLocationConstraint = const destObjLocationConstraint = res.controllingLocationConstraint;
res.controllingLocationConstraint;
return next(null, dataLocator, destBucketMD, return next(null, dataLocator, destBucketMD,
destObjLocationConstraint, copyObjectSize, destObjLocationConstraint, copyObjectSize,
sourceVerId, sourceLocationConstraintName, splitter); sourceVerId, sourceLocationConstraintName, splitter);
@ -249,6 +243,9 @@ function objectPutCopyPart(authInfo, request, sourceBucket,
splitter, splitter,
next, next,
) { ) {
const originalIdentityAuthzResults = request.actionImplicitDenies;
// eslint-disable-next-line no-param-reassign
delete request.actionImplicitDenies;
data.uploadPartCopy( data.uploadPartCopy(
request, request,
log, log,
@ -259,6 +256,8 @@ function objectPutCopyPart(authInfo, request, sourceBucket,
dataStoreContext, dataStoreContext,
locationConstraintCheck, locationConstraintCheck,
(error, eTag, lastModified, serverSideEncryption, locations) => { (error, eTag, lastModified, serverSideEncryption, locations) => {
// eslint-disable-next-line no-param-reassign
request.actionImplicitDenies = originalIdentityAuthzResults;
if (error) { if (error) {
if (error.message === 'skip') { if (error.message === 'skip') {
return next(skipError, destBucketMD, eTag, return next(skipError, destBucketMD, eTag,
@ -270,13 +269,13 @@ function objectPutCopyPart(authInfo, request, sourceBucket,
return next(null, destBucketMD, locations, eTag, return next(null, destBucketMD, locations, eTag,
copyObjectSize, sourceVerId, serverSideEncryption, copyObjectSize, sourceVerId, serverSideEncryption,
lastModified, splitter); lastModified, splitter);
}); },
);
}, },
function getExistingPartInfo(destBucketMD, locations, totalHash, function getExistingPartInfo(destBucketMD, locations, totalHash,
copyObjectSize, sourceVerId, serverSideEncryption, lastModified, copyObjectSize, sourceVerId, serverSideEncryption, lastModified,
splitter, next) { splitter, next) {
const partKey = const partKey = `${uploadId}${constants.splitter}${paddedPartNumber}`;
`${uploadId}${constants.splitter}${paddedPartNumber}`;
metadata.getObjectMD(mpuBucketName, partKey, {}, log, metadata.getObjectMD(mpuBucketName, partKey, {}, log,
(err, result) => { (err, result) => {
// If there is nothing being overwritten just move on // If there is nothing being overwritten just move on
@ -294,8 +293,8 @@ function objectPutCopyPart(authInfo, request, sourceBucket,
// Pull locations to clean up any potential orphans // Pull locations to clean up any potential orphans
// in data if object put is an overwrite of // in data if object put is an overwrite of
// already existing object with same key and part number // already existing object with same key and part number
oldLocations = Array.isArray(oldLocations) ? oldLocations = Array.isArray(oldLocations)
oldLocations : [oldLocations]; ? oldLocations : [oldLocations];
} }
return next(null, destBucketMD, locations, totalHash, return next(null, destBucketMD, locations, totalHash,
prevObjectSize, copyObjectSize, sourceVerId, prevObjectSize, copyObjectSize, sourceVerId,
@ -370,7 +369,8 @@ function objectPutCopyPart(authInfo, request, sourceBucket,
// data locations) has been stored // data locations) has been stored
if (oldLocationsToDelete) { if (oldLocationsToDelete) {
const delLog = logger.newRequestLoggerFromSerializedUids( const delLog = logger.newRequestLoggerFromSerializedUids(
log.getSerializedUids()); log.getSerializedUids(),
);
return data.batchDelete(oldLocationsToDelete, request.method, null, return data.batchDelete(oldLocationsToDelete, request.method, null,
delLog, err => { delLog, err => {
if (err) { if (err) {
@ -409,11 +409,9 @@ function objectPutCopyPart(authInfo, request, sourceBucket,
const additionalHeaders = corsHeaders || {}; const additionalHeaders = corsHeaders || {};
if (serverSideEncryption) { if (serverSideEncryption) {
additionalHeaders['x-amz-server-side-encryption'] = additionalHeaders['x-amz-server-side-encryption'] = serverSideEncryption.algorithm;
serverSideEncryption.algorithm;
if (serverSideEncryption.algorithm === 'aws:kms') { if (serverSideEncryption.algorithm === 'aws:kms') {
additionalHeaders['x-amz-server-side-encryption-aws-kms-key-id'] additionalHeaders['x-amz-server-side-encryption-aws-kms-key-id'] = serverSideEncryption.masterKeyId;
= serverSideEncryption.masterKeyId;
} }
} }
additionalHeaders['x-amz-copy-source-version-id'] = sourceVerId; additionalHeaders['x-amz-copy-source-version-id'] = sourceVerId;

View File

@ -6,7 +6,7 @@ const { decodeVersionId, getVersionIdResHeader } =
require('./apiUtils/object/versioning'); require('./apiUtils/object/versioning');
const getReplicationInfo = require('./apiUtils/object/getReplicationInfo'); const getReplicationInfo = require('./apiUtils/object/getReplicationInfo');
const metadata = require('../metadata/wrapper'); const metadata = require('../metadata/wrapper');
const { metadataValidateBucketAndObj } = require('../metadata/metadataUtils'); const { standardMetadataValidateBucketAndObj } = require('../metadata/metadataUtils');
const { pushMetric } = require('../utapi/utilities'); const { pushMetric } = require('../utapi/utilities');
const { parseLegalHoldXml } = s3middleware.objectLegalHold; const { parseLegalHoldXml } = s3middleware.objectLegalHold;
@ -40,13 +40,13 @@ function objectPutLegalHold(authInfo, request, log, callback) {
authInfo, authInfo,
bucketName, bucketName,
objectKey, objectKey,
requestType: 'objectPutLegalHold',
versionId, versionId,
requestType: request.apiMethods || 'objectPutLegalHold',
request, request,
}; };
return async.waterfall([ return async.waterfall([
next => metadataValidateBucketAndObj(metadataValParams, log, next => standardMetadataValidateBucketAndObj(metadataValParams, request.actionImplicitDenies, log,
(err, bucket, objectMD) => { (err, bucket, objectMD) => {
if (err) { if (err) {
log.trace('request authorization failed', log.trace('request authorization failed',

View File

@ -18,6 +18,8 @@ const locationConstraintCheck
= require('./apiUtils/object/locationConstraintCheck'); = require('./apiUtils/object/locationConstraintCheck');
const writeContinue = require('../utilities/writeContinue'); const writeContinue = require('../utilities/writeContinue');
const { getObjectSSEConfiguration } = require('./apiUtils/bucket/bucketEncryption'); const { getObjectSSEConfiguration } = require('./apiUtils/bucket/bucketEncryption');
const validateChecksumHeaders = require('./apiUtils/object/validateChecksumHeaders');
const skipError = new Error('skip'); const skipError = new Error('skip');
// We pad the partNumbers so that the parts will be sorted in numerical order. // We pad the partNumbers so that the parts will be sorted in numerical order.
@ -61,6 +63,11 @@ function objectPutPart(authInfo, request, streamingV4Params, log,
return cb(errors.EntityTooLarge); return cb(errors.EntityTooLarge);
} }
const checksumHeaderErr = validateChecksumHeaders(request.headers);
if (checksumHeaderErr) {
return cb(checksumHeaderErr);
}
// Note: Part sizes cannot be less than 5MB in size except for the last. // Note: Part sizes cannot be less than 5MB in size except for the last.
// However, we do not check this value here because we cannot know which // However, we do not check this value here because we cannot know which
// part will be the last until a complete MPU request is made. Thus, we let // part will be the last until a complete MPU request is made. Thus, we let
@ -87,6 +94,7 @@ function objectPutPart(authInfo, request, streamingV4Params, log,
const uploadId = request.query.uploadId; const uploadId = request.query.uploadId;
const mpuBucketName = `${constants.mpuBucketPrefix}${bucketName}`; const mpuBucketName = `${constants.mpuBucketPrefix}${bucketName}`;
const objectKey = request.objectKey; const objectKey = request.objectKey;
const originalIdentityAuthzResults = request.actionImplicitDenies;
return async.waterfall([ return async.waterfall([
// Get the destination bucket. // Get the destination bucket.
@ -109,7 +117,8 @@ function objectPutPart(authInfo, request, streamingV4Params, log,
// For validating the request at the destinationBucket level the // For validating the request at the destinationBucket level the
// `requestType` is the general 'objectPut'. // `requestType` is the general 'objectPut'.
const requestType = 'objectPut'; const requestType = 'objectPut';
if (!isBucketAuthorized(destinationBucket, requestType, canonicalID, authInfo, log, request)) { if (!isBucketAuthorized(destinationBucket, request.apiMethods || requestType, canonicalID, authInfo,
log, request, request.actionImplicitDenies)) {
log.debug('access denied for user on bucket', { requestType }); log.debug('access denied for user on bucket', { requestType });
return next(errors.AccessDenied, destinationBucket); return next(errors.AccessDenied, destinationBucket);
} }
@ -196,6 +205,8 @@ function objectPutPart(authInfo, request, streamingV4Params, log,
partNumber, partNumber,
bucketName, bucketName,
}; };
// eslint-disable-next-line no-param-reassign
delete request.actionImplicitDenies;
writeContinue(request, request._response); writeContinue(request, request._response);
return data.putPart(request, mpuInfo, streamingV4Params, return data.putPart(request, mpuInfo, streamingV4Params,
objectLocationConstraint, locationConstraintCheck, log, objectLocationConstraint, locationConstraintCheck, log,
@ -378,6 +389,8 @@ function objectPutPart(authInfo, request, streamingV4Params, log,
], (err, destinationBucket, hexDigest, prevObjectSize) => { ], (err, destinationBucket, hexDigest, prevObjectSize) => {
const corsHeaders = collectCorsHeaders(request.headers.origin, const corsHeaders = collectCorsHeaders(request.headers.origin,
request.method, destinationBucket); request.method, destinationBucket);
// eslint-disable-next-line no-param-reassign
request.actionImplicitDenies = originalIdentityAuthzResults;
if (err) { if (err) {
if (err === skipError) { if (err === skipError) {
return cb(null, hexDigest, corsHeaders); return cb(null, hexDigest, corsHeaders);

View File

@ -5,7 +5,7 @@ const { decodeVersionId, getVersionIdResHeader } =
require('./apiUtils/object/versioning'); require('./apiUtils/object/versioning');
const { ObjectLockInfo, checkUserGovernanceBypass, hasGovernanceBypassHeader } = const { ObjectLockInfo, checkUserGovernanceBypass, hasGovernanceBypassHeader } =
require('./apiUtils/object/objectLockHelpers'); require('./apiUtils/object/objectLockHelpers');
const { metadataValidateBucketAndObj } = require('../metadata/metadataUtils'); const { standardMetadataValidateBucketAndObj } = require('../metadata/metadataUtils');
const { pushMetric } = require('../utapi/utilities'); const { pushMetric } = require('../utapi/utilities');
const getReplicationInfo = require('./apiUtils/object/getReplicationInfo'); const getReplicationInfo = require('./apiUtils/object/getReplicationInfo');
const collectCorsHeaders = require('../utilities/collectCorsHeaders'); const collectCorsHeaders = require('../utilities/collectCorsHeaders');
@ -41,14 +41,29 @@ function objectPutRetention(authInfo, request, log, callback) {
authInfo, authInfo,
bucketName, bucketName,
objectKey, objectKey,
requestType: 'objectPutRetention',
versionId: reqVersionId, versionId: reqVersionId,
requestType: request.apiMethods || 'objectPutRetention',
request, request,
}; };
return async.waterfall([ return async.waterfall([
next => metadataValidateBucketAndObj(metadataValParams, log, next => {
(err, bucket, objectMD) => { log.trace('parsing retention information');
parseRetentionXml(request.post, log,
(err, retentionInfo) => {
if (err) {
log.trace('error parsing retention information',
{ error: err });
return next(err);
}
const remainingDays = Math.ceil(
(new Date(retentionInfo.date) - Date.now()) / (1000 * 3600 * 24));
metadataValParams.request.objectLockRetentionDays = remainingDays;
return next(null, retentionInfo);
});
},
(retentionInfo, next) => standardMetadataValidateBucketAndObj(metadataValParams, request.actionImplicitDenies,
log, (err, bucket, objectMD) => {
if (err) { if (err) {
log.trace('request authorization failed', log.trace('request authorization failed',
{ method: 'objectPutRetention', error: err }); { method: 'objectPutRetention', error: err });
@ -64,6 +79,8 @@ function objectPutRetention(authInfo, request, log, callback) {
if (objectMD.isDeleteMarker) { if (objectMD.isDeleteMarker) {
log.trace('version is a delete marker', log.trace('version is a delete marker',
{ method: 'objectPutRetention' }); { method: 'objectPutRetention' });
// FIXME we should return a `x-amz-delete-marker: true` header,
// see S3C-7592
return next(errors.MethodNotAllowed, bucket); return next(errors.MethodNotAllowed, bucket);
} }
if (!bucket.isObjectLockEnabled()) { if (!bucket.isObjectLockEnabled()) {
@ -73,13 +90,8 @@ function objectPutRetention(authInfo, request, log, callback) {
'Bucket is missing Object Lock Configuration' 'Bucket is missing Object Lock Configuration'
), bucket); ), bucket);
} }
return next(null, bucket, objectMD); return next(null, bucket, retentionInfo, objectMD);
}), }),
(bucket, objectMD, next) => {
log.trace('parsing retention information');
parseRetentionXml(request.post, log,
(err, retentionInfo) => next(err, bucket, retentionInfo, objectMD));
},
(bucket, retentionInfo, objectMD, next) => { (bucket, retentionInfo, objectMD, next) => {
const hasGovernanceBypass = hasGovernanceBypassHeader(request.headers); const hasGovernanceBypass = hasGovernanceBypassHeader(request.headers);
if (hasGovernanceBypass && authInfo.isRequesterAnIAMUser()) { if (hasGovernanceBypass && authInfo.isRequesterAnIAMUser()) {

View File

@ -1,15 +1,15 @@
const async = require('async'); const async = require('async');
const { errors, s3middleware } = require('arsenal'); const { errors, s3middleware } = require('arsenal');
const { decodeVersionId, getVersionIdResHeader } = const { decodeVersionId, getVersionIdResHeader } = require('./apiUtils/object/versioning');
require('./apiUtils/object/versioning');
const { metadataValidateBucketAndObj } = require('../metadata/metadataUtils'); const { standardMetadataValidateBucketAndObj } = require('../metadata/metadataUtils');
const { pushMetric } = require('../utapi/utilities'); const { pushMetric } = require('../utapi/utilities');
const getReplicationInfo = require('./apiUtils/object/getReplicationInfo'); const getReplicationInfo = require('./apiUtils/object/getReplicationInfo');
const collectCorsHeaders = require('../utilities/collectCorsHeaders'); const collectCorsHeaders = require('../utilities/collectCorsHeaders');
const metadata = require('../metadata/wrapper'); const metadata = require('../metadata/wrapper');
const { data } = require('../data/wrapper'); const { data } = require('../data/wrapper');
const { parseTagXml } = s3middleware.tagging; const { parseTagXml } = s3middleware.tagging;
const REPLICATION_ACTION = 'PUT_TAGGING'; const REPLICATION_ACTION = 'PUT_TAGGING';
@ -24,8 +24,8 @@ const REPLICATION_ACTION = 'PUT_TAGGING';
function objectPutTagging(authInfo, request, log, callback) { function objectPutTagging(authInfo, request, log, callback) {
log.debug('processing request', { method: 'objectPutTagging' }); log.debug('processing request', { method: 'objectPutTagging' });
const bucketName = request.bucketName; const { bucketName } = request;
const objectKey = request.objectKey; const { objectKey } = request;
const decodedVidResult = decodeVersionId(request.query); const decodedVidResult = decodeVersionId(request.query);
if (decodedVidResult instanceof Error) { if (decodedVidResult instanceof Error) {
@ -41,13 +41,13 @@ function objectPutTagging(authInfo, request, log, callback) {
authInfo, authInfo,
bucketName, bucketName,
objectKey, objectKey,
requestType: 'objectPutTagging',
versionId: reqVersionId, versionId: reqVersionId,
requestType: request.apiMethods || 'objectPutTagging',
request, request,
}; };
return async.waterfall([ return async.waterfall([
next => metadataValidateBucketAndObj(metadataValParams, log, next => standardMetadataValidateBucketAndObj(metadataValParams, request.actionImplicitDenies, log,
(err, bucket, objectMD) => { (err, bucket, objectMD) => {
if (err) { if (err) {
log.trace('request authorization failed', log.trace('request authorization failed',
@ -70,8 +70,7 @@ function objectPutTagging(authInfo, request, log, callback) {
}), }),
(bucket, objectMD, next) => { (bucket, objectMD, next) => {
log.trace('parsing tag(s)'); log.trace('parsing tag(s)');
parseTagXml(request.post, log, (err, tags) => parseTagXml(request.post, log, (err, tags) => next(err, bucket, tags, objectMD));
next(err, bucket, tags, objectMD));
}, },
(bucket, tags, objectMD, next) => { (bucket, tags, objectMD, next) => {
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
@ -88,12 +87,10 @@ function objectPutTagging(authInfo, request, log, callback) {
// eslint-disable-next-line no-param-reassign // eslint-disable-next-line no-param-reassign
objectMD.originOp = 's3:ObjectTagging:Put'; objectMD.originOp = 's3:ObjectTagging:Put';
metadata.putObjectMD(bucket.getName(), objectKey, objectMD, params, metadata.putObjectMD(bucket.getName(), objectKey, objectMD, params,
log, err => log, err => next(err, bucket, objectMD));
next(err, bucket, objectMD));
}, },
(bucket, objectMD, next) =>
// if external backend handles tagging // if external backend handles tagging
data.objectTagging('Put', objectKey, bucket, objectMD, (bucket, objectMD, next) => data.objectTagging('Put', objectKey, bucket, objectMD,
log, err => next(err, bucket, objectMD)), log, err => next(err, bucket, objectMD)),
], (err, bucket, objectMD) => { ], (err, bucket, objectMD) => {
const additionalResHeaders = collectCorsHeaders(request.headers.origin, const additionalResHeaders = collectCorsHeaders(request.headers.origin,
@ -110,8 +107,7 @@ function objectPutTagging(authInfo, request, log, callback) {
location: objectMD ? objectMD.dataStoreName : undefined, location: objectMD ? objectMD.dataStoreName : undefined,
}); });
const verCfg = bucket.getVersioningConfiguration(); const verCfg = bucket.getVersioningConfiguration();
additionalResHeaders['x-amz-version-id'] = additionalResHeaders['x-amz-version-id'] = getVersionIdResHeader(verCfg, objectMD);
getVersionIdResHeader(verCfg, objectMD);
} }
return callback(err, additionalResHeaders); return callback(err, additionalResHeaders);
}); });

View File

@ -42,7 +42,6 @@ function getNullVersion(objMD, bucketName, objectKey, log, cb) {
* NOTE: If the value of `versionId` param is 'null', this function returns the * NOTE: If the value of `versionId` param is 'null', this function returns the
* master version objMD. The null version object md must be retrieved in a * master version objMD. The null version object md must be retrieved in a
* separate step using the master object md: see getNullVersion(). * separate step using the master object md: see getNullVersion().
* @param {string} requestType - type of request
* @param {string} bucketName - name of bucket * @param {string} bucketName - name of bucket
* @param {string} objectKey - name of object key * @param {string} objectKey - name of object key
* @param {string} [versionId] - version of object to retrieve * @param {string} [versionId] - version of object to retrieve
@ -50,7 +49,7 @@ function getNullVersion(objMD, bucketName, objectKey, log, cb) {
* @param {function} cb - callback * @param {function} cb - callback
* @return {undefined} - and call callback with err, bucket md and object md * @return {undefined} - and call callback with err, bucket md and object md
*/ */
function metadataGetBucketAndObject(requestType, bucketName, objectKey, function metadataGetBucketAndObject(bucketName, objectKey,
versionId, log, cb) { versionId, log, cb) {
const options = { const options = {
// if attempting to get 'null' version, must retrieve null version id // if attempting to get 'null' version, must retrieve null version id
@ -73,13 +72,6 @@ function metadataGetBucketAndObject(requestType, bucketName, objectKey,
}); });
return cb(errors.NoSuchBucket); return cb(errors.NoSuchBucket);
} }
if (bucketShield(bucket, requestType)) {
log.debug('bucket is shielded from request', {
requestType,
method: 'metadataGetBucketAndObject',
});
return cb(errors.NoSuchBucket);
}
log.trace('found bucket in metadata'); log.trace('found bucket in metadata');
return cb(null, bucket, obj); return cb(null, bucket, obj);
}); });
@ -117,6 +109,53 @@ function metadataGetObject(bucketName, objectKey, versionId, log, cb) {
return cb(null, objMD); return cb(null, objMD);
}); });
} }
/**
* Validate that a bucket is accessible and authorized to the user,
* return a specific error code otherwise
*
* @param {BucketInfo} bucket - bucket info
* @param {object} params - function parameters
* @param {AuthInfo} params.authInfo - AuthInfo class instance, requester's info
* @param {string} params.requestType - type of request
* @param {string} [params.preciseRequestType] - precise type of request
* @param {object} params.request - http request object
* @param {RequestLogger} log - request logger
* @param {object} actionImplicitDenies - identity authorization results
* @return {ArsenalError|null} returns a validation error, or null if validation OK
* The following errors may be returned:
* - NoSuchBucket: bucket is shielded
* - MethodNotAllowed: requester is not bucket owner and asking for a
* bucket policy operation
* - AccessDenied: bucket is not authorized
*/
function validateBucket(bucket, params, log, actionImplicitDenies = {}) {
const { authInfo, preciseRequestType, request } = params;
let requestType = params.requestType;
if (bucketShield(bucket, requestType)) {
log.debug('bucket is shielded from request', {
requestType,
method: 'validateBucket',
});
return errors.NoSuchBucket;
}
// if requester is not bucket owner, bucket policy actions should be denied with
// MethodNotAllowed error
const onlyOwnerAllowed = ['bucketDeletePolicy', 'bucketGetPolicy', 'bucketPutPolicy'];
const canonicalID = authInfo.getCanonicalID();
if (!Array.isArray(requestType)) {
requestType = [requestType];
}
if (bucket.getOwner() !== canonicalID && requestType.some(type => onlyOwnerAllowed.includes(type))) {
return errors.MethodNotAllowed;
}
if (!isBucketAuthorized(bucket, (preciseRequestType || requestType), canonicalID,
authInfo, log, request, actionImplicitDenies)) {
log.debug('access denied for user on bucket', { requestType });
return errors.AccessDenied;
}
return null;
}
/** metadataValidateBucketAndObj - retrieve bucket and object md from metadata /** metadataValidateBucketAndObj - retrieve bucket and object md from metadata
* and check if user is authorized to access them. * and check if user is authorized to access them.
@ -127,41 +166,86 @@ function metadataGetObject(bucketName, objectKey, versionId, log, cb) {
* @param {string} [params.versionId] - version id if getting specific version * @param {string} [params.versionId] - version id if getting specific version
* @param {string} params.requestType - type of request * @param {string} params.requestType - type of request
* @param {object} params.request - http request object * @param {object} params.request - http request object
* @param {boolean} actionImplicitDenies - identity authorization results
* @param {RequestLogger} log - request logger * @param {RequestLogger} log - request logger
* @param {function} callback - callback * @param {function} callback - callback
* @return {undefined} - and call callback with params err, bucket md * @return {undefined} - and call callback with params err, bucket md
*/ */
function metadataValidateBucketAndObj(params, log, callback) { function standardMetadataValidateBucketAndObj(params, actionImplicitDenies, log, callback) {
const { authInfo, bucketName, objectKey, versionId, requestType, preciseRequestType, request } = params; const { authInfo, bucketName, objectKey, versionId, request } = params;
const canonicalID = authInfo.getCanonicalID(); let requestType = params.requestType;
async.waterfall([ if (!Array.isArray(requestType)) {
function getBucketAndObjectMD(next) { requestType = [requestType];
return metadataGetBucketAndObject(requestType, bucketName,
objectKey, versionId, log, next);
},
function checkBucketAuth(bucket, objMD, next) {
// if requester is not bucket owner, bucket policy actions should be denied with
// MethodNotAllowed error
const onlyOwnerAllowed = ['bucketDeletePolicy', 'bucketGetPolicy', 'bucketPutPolicy'];
if (bucket.getOwner() !== canonicalID && onlyOwnerAllowed.includes(requestType)) {
return next(errors.MethodNotAllowed, bucket);
} }
if (!isBucketAuthorized(bucket, (preciseRequestType || requestType), canonicalID, async.waterfall([
authInfo, log, request)) { next => metadataGetBucketAndObject(bucketName,
log.debug('access denied for user on bucket', { requestType }); objectKey, versionId, log, (err, bucket, objMD) => {
return next(errors.AccessDenied, bucket); if (err) {
if (actionImplicitDenies && Object.values(actionImplicitDenies).some(v => v === true)) {
return next(errors.AccessDenied);
}
return next(err);
} }
return next(null, bucket, objMD); return next(null, bucket, objMD);
}, }),
function handleNullVersionGet(bucket, objMD, next) { (bucket, objMD, next) => {
const validationError = validateBucket(bucket, params, log, actionImplicitDenies);
if (validationError) {
return next(validationError, bucket);
}
if (objMD && versionId === 'null') { if (objMD && versionId === 'null') {
return getNullVersion(objMD, bucketName, objectKey, log, return getNullVersion(objMD, bucketName, objectKey, log,
(err, nullVer) => next(err, bucket, nullVer)); (err, nullVer) => next(err, bucket, nullVer));
} }
return next(null, bucket, objMD); return next(null, bucket, objMD);
}, },
function checkObjectAuth(bucket, objMD, next) { (bucket, objMD, next) => {
if (!isObjAuthorized(bucket, objMD, requestType, canonicalID, authInfo, log, request)) { const canonicalID = authInfo.getCanonicalID();
if (!isObjAuthorized(bucket, objMD, requestType, canonicalID, authInfo,
log, request, actionImplicitDenies)) {
log.debug('access denied for user on object', { requestType });
return next(errors.AccessDenied, bucket);
}
return next(null, bucket, objMD);
},
], (err, bucket, objMD) => {
if (err) {
return callback(err, bucket);
}
return callback(null, bucket, objMD);
});
}
function metadataValidateBucketAndObj(params, log, callback) {
const { authInfo, bucketName, objectKey, versionId, request } = params;
let requestType = params.requestType;
if (!Array.isArray(requestType)) {
requestType = [requestType];
}
async.waterfall([
next => metadataGetBucketAndObject(bucketName,
objectKey, versionId, log, (err, bucket, objMD) => {
if (err) {
return next(err);
}
return next(null, bucket, objMD);
}),
(bucket, objMD, next) => {
const validationError = validateBucket(bucket, params, log);
if (validationError) {
return next(validationError, bucket);
}
if (objMD && versionId === 'null') {
return getNullVersion(objMD, bucketName, objectKey, log,
(err, nullVer) => next(err, bucket, nullVer));
}
return next(null, bucket, objMD);
},
(bucket, objMD, next) => {
const canonicalID = authInfo.getCanonicalID();
if (!isObjAuthorized(bucket, objMD, requestType, canonicalID, authInfo,
log, request)) {
log.debug('access denied for user on object', { requestType }); log.debug('access denied for user on object', { requestType });
return next(errors.AccessDenied, bucket); return next(errors.AccessDenied, bucket);
} }
@ -175,7 +259,6 @@ function metadataValidateBucketAndObj(params, log, callback) {
return callback(null, bucket, objMD); return callback(null, bucket, objMD);
}); });
} }
/** metadataGetBucket - retrieves bucket from metadata, returning error if /** metadataGetBucket - retrieves bucket from metadata, returning error if
* bucket is shielded * bucket is shielded
* @param {string} requestType - type of request * @param {string} requestType - type of request
@ -209,34 +292,38 @@ function metadataGetBucket(requestType, bucketName, log, cb) {
* @param {string} params.bucketName - name of bucket * @param {string} params.bucketName - name of bucket
* @param {string} params.requestType - type of request * @param {string} params.requestType - type of request
* @param {string} params.request - http request object * @param {string} params.request - http request object
* @param {boolean} actionImplicitDenies - identity authorization results
* @param {RequestLogger} log - request logger * @param {RequestLogger} log - request logger
* @param {function} callback - callback * @param {function} callback - callback
* @return {undefined} - and call callback with params err, bucket md * @return {undefined} - and call callback with params err, bucket md
*/ */
function metadataValidateBucket(params, log, callback) { function standardMetadataValidateBucket(params, actionImplicitDenies, log, callback) {
const { authInfo, bucketName, requestType, preciseRequestType, request } = params; const { bucketName, requestType } = params;
const canonicalID = authInfo.getCanonicalID();
return metadataGetBucket(requestType, bucketName, log, (err, bucket) => { return metadataGetBucket(requestType, bucketName, log, (err, bucket) => {
if (err) { if (err) {
return callback(err); return callback(err);
} }
// if requester is not bucket owner, bucket policy actions should be denied with const validationError = validateBucket(bucket, params, log, actionImplicitDenies);
// MethodNotAllowed error return callback(validationError, bucket);
const onlyOwnerAllowed = ['bucketDeletePolicy', 'bucketGetPolicy', 'bucketPutPolicy']; });
if (bucket.getOwner() !== canonicalID && onlyOwnerAllowed.includes(requestType)) { }
return callback(errors.MethodNotAllowed, bucket);
function metadataValidateBucket(params, log, callback) {
const { bucketName, requestType } = params;
return metadataGetBucket(requestType, bucketName, log, (err, bucket) => {
if (err) {
return callback(err);
} }
// still return bucket for cors headers const validationError = validateBucket(bucket, params, log);
if (!isBucketAuthorized(bucket, (preciseRequestType || requestType), canonicalID, authInfo, log, request)) { return callback(validationError, bucket);
log.debug('access denied for user on bucket', { requestType });
return callback(errors.AccessDenied, bucket);
}
return callback(null, bucket);
}); });
} }
module.exports = { module.exports = {
metadataGetObject, metadataGetObject,
validateBucket,
metadataValidateBucketAndObj, metadataValidateBucketAndObj,
standardMetadataValidateBucketAndObj,
metadataValidateBucket, metadataValidateBucket,
standardMetadataValidateBucket,
}; };

View File

@ -0,0 +1,70 @@
const assert = require('assert');
const { makeS3Request } = require('../utils/makeRequest');
const HttpRequestAuthV4 = require('../utils/HttpRequestAuthV4');
const bucket = 'testunsupportedchecksumsbucket';
const objectKey = 'key';
const objData = Buffer.alloc(1024, 'a');
const authCredentials = {
accessKey: 'accessKey1',
secretKey: 'verySecretKey1',
};
const itSkipIfAWS = process.env.AWS_ON_AIR ? it.skip : it;
describe('unsupported checksum requests:', () => {
before(done => {
makeS3Request({
method: 'PUT',
authCredentials,
bucket,
}, err => {
assert.ifError(err);
done();
});
});
after(done => {
makeS3Request({
method: 'DELETE',
authCredentials,
bucket,
}, err => {
assert.ifError(err);
done();
});
});
itSkipIfAWS('should respond with BadRequest for trailing checksum', done => {
const req = new HttpRequestAuthV4(
`http://localhost:8000/${bucket}/${objectKey}`,
Object.assign(
{
method: 'PUT',
headers: {
'content-length': objData.length,
'x-amz-content-sha256': 'STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER',
'x-amz-trailer': 'x-amz-checksum-sha256',
},
},
authCredentials
),
res => {
assert.strictEqual(res.statusCode, 400);
res.on('data', () => {});
res.on('end', done);
}
);
req.on('error', err => {
assert.ifError(err);
});
req.write(objData);
req.once('drain', () => {
req.end();
});
});
});

View File

@ -3,21 +3,19 @@ const async = require('async');
const { parseString } = require('xml2js'); const { parseString } = require('xml2js');
const AWS = require('aws-sdk'); const AWS = require('aws-sdk');
const { cleanup, DummyRequestLogger, makeAuthInfo } const { metadata } = require('arsenal').storage.metadata.inMemory.metadata;
= require('../unit/helpers'); const { cleanup, DummyRequestLogger, makeAuthInfo } = require('../unit/helpers');
const { ds } = require('arsenal').storage.data.inMemory.datastore; const { ds } = require('arsenal').storage.data.inMemory.datastore;
const { bucketPut } = require('../../lib/api/bucketPut'); const { bucketPut } = require('../../lib/api/bucketPut');
const initiateMultipartUpload const initiateMultipartUpload = require('../../lib/api/initiateMultipartUpload');
= require('../../lib/api/initiateMultipartUpload');
const objectPut = require('../../lib/api/objectPut'); const objectPut = require('../../lib/api/objectPut');
const objectPutCopyPart = require('../../lib/api/objectPutCopyPart'); const objectPutCopyPart = require('../../lib/api/objectPutCopyPart');
const DummyRequest = require('../unit/DummyRequest'); const DummyRequest = require('../unit/DummyRequest');
const { metadata } = require('arsenal').storage.metadata.inMemory.metadata;
const constants = require('../../constants'); const constants = require('../../constants');
const s3 = new AWS.S3(); const s3 = new AWS.S3();
const splitter = constants.splitter; const { splitter } = constants;
const log = new DummyRequestLogger(); const log = new DummyRequestLogger();
const canonicalID = 'accessKey1'; const canonicalID = 'accessKey1';
const authInfo = makeAuthInfo(canonicalID); const authInfo = makeAuthInfo(canonicalID);
@ -56,14 +54,14 @@ function getAwsParamsBucketMismatch(destObjName, uploadId) {
} }
function copyPutPart(bucketLoc, mpuLoc, srcObjLoc, requestHost, cb, function copyPutPart(bucketLoc, mpuLoc, srcObjLoc, requestHost, cb,
errorPutCopyPart) { errorPutCopyPart) {
const keys = getSourceAndDestKeys(); const keys = getSourceAndDestKeys();
const { sourceObjName, destObjName } = keys; const { sourceObjName, destObjName } = keys;
const post = bucketLoc ? '<?xml version="1.0" encoding="UTF-8"?>' + const post = bucketLoc ? '<?xml version="1.0" encoding="UTF-8"?>'
'<CreateBucketConfiguration ' + + '<CreateBucketConfiguration '
'xmlns="http://s3.amazonaws.com/doc/2006-03-01/">' + + 'xmlns="http://s3.amazonaws.com/doc/2006-03-01/">'
`<LocationConstraint>${bucketLoc}</LocationConstraint>` + + `<LocationConstraint>${bucketLoc}</LocationConstraint>`
'</CreateBucketConfiguration>' : ''; + '</CreateBucketConfiguration>' : '';
const bucketPutReq = new DummyRequest({ const bucketPutReq = new DummyRequest({
bucketName, bucketName,
namespace, namespace,
@ -80,10 +78,13 @@ errorPutCopyPart) {
objectKey: destObjName, objectKey: destObjName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
url: `/${destObjName}?uploads`, url: `/${destObjName}?uploads`,
actionImplicitDenies: false,
}; };
if (mpuLoc) { if (mpuLoc) {
initiateReq.headers = { 'host': `${bucketName}.s3.amazonaws.com`, initiateReq.headers = {
'x-amz-meta-scal-location-constraint': `${mpuLoc}` }; 'host': `${bucketName}.s3.amazonaws.com`,
'x-amz-meta-scal-location-constraint': `${mpuLoc}`,
};
} }
if (requestHost) { if (requestHost) {
initiateReq.parsedHost = requestHost; initiateReq.parsedHost = requestHost;
@ -94,10 +95,13 @@ errorPutCopyPart) {
objectKey: sourceObjName, objectKey: sourceObjName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
url: '/', url: '/',
actionImplicitDenies: false,
}; };
if (srcObjLoc) { if (srcObjLoc) {
sourceObjPutParams.headers = { 'host': `${bucketName}.s3.amazonaws.com`, sourceObjPutParams.headers = {
'x-amz-meta-scal-location-constraint': `${srcObjLoc}` }; 'host': `${bucketName}.s3.amazonaws.com`,
'x-amz-meta-scal-location-constraint': `${srcObjLoc}`,
};
} }
const sourceObjPutReq = new DummyRequest(sourceObjPutParams, body); const sourceObjPutReq = new DummyRequest(sourceObjPutParams, body);
if (requestHost) { if (requestHost) {
@ -112,8 +116,7 @@ errorPutCopyPart) {
}); });
}, },
next => { next => {
objectPut(authInfo, sourceObjPutReq, undefined, log, err => objectPut(authInfo, sourceObjPutReq, undefined, log, err => next(err));
next(err));
}, },
next => { next => {
initiateMultipartUpload(authInfo, initiateReq, log, next); initiateMultipartUpload(authInfo, initiateReq, log, next);
@ -130,8 +133,8 @@ errorPutCopyPart) {
// Need to build request in here since do not have // Need to build request in here since do not have
// uploadId until here // uploadId until here
assert.ifError(err, 'Error putting source object or initiate MPU'); assert.ifError(err, 'Error putting source object or initiate MPU');
const testUploadId = json.InitiateMultipartUploadResult. const testUploadId = json.InitiateMultipartUploadResult
UploadId[0]; .UploadId[0];
const copyPartParams = { const copyPartParams = {
bucketName, bucketName,
namespace, namespace,
@ -172,7 +175,7 @@ function assertPartList(partList, uploadId) {
} }
describeSkipIfE2E('ObjectCopyPutPart API with multiple backends', describeSkipIfE2E('ObjectCopyPutPart API with multiple backends',
function testSuite() { function testSuite() {
this.timeout(60000); this.timeout(60000);
beforeEach(() => { beforeEach(() => {
@ -205,8 +208,8 @@ function testSuite() {
s3.listParts(awsReq, (err, partList) => { s3.listParts(awsReq, (err, partList) => {
assertPartList(partList, uploadId); assertPartList(partList, uploadId);
s3.abortMultipartUpload(awsReq, err => { s3.abortMultipartUpload(awsReq, err => {
assert.equal(err, null, `Error aborting MPU: ${err}. ` + assert.equal(err, null, `Error aborting MPU: ${err}. `
`You must abort MPU with upload ID ${uploadId} manually.`); + `You must abort MPU with upload ID ${uploadId} manually.`);
done(); done();
}); });
}); });
@ -247,16 +250,16 @@ function testSuite() {
s3.listParts(awsReq, (err, partList) => { s3.listParts(awsReq, (err, partList) => {
assertPartList(partList, uploadId); assertPartList(partList, uploadId);
s3.abortMultipartUpload(awsReq, err => { s3.abortMultipartUpload(awsReq, err => {
assert.equal(err, null, `Error aborting MPU: ${err}. ` + assert.equal(err, null, `Error aborting MPU: ${err}. `
`You must abort MPU with upload ID ${uploadId} manually.`); + `You must abort MPU with upload ID ${uploadId} manually.`);
done(); done();
}); });
}); });
}); });
}); });
it('should copy part an object on AWS location that has bucketMatch ' + it('should copy part an object on AWS location that has bucketMatch '
'equals false to a mpu with a different AWS location', done => { + 'equals false to a mpu with a different AWS location', done => {
copyPutPart(null, awsLocation, awsLocationMismatch, 'localhost', copyPutPart(null, awsLocation, awsLocationMismatch, 'localhost',
(keys, uploadId) => { (keys, uploadId) => {
assert.deepStrictEqual(ds, []); assert.deepStrictEqual(ds, []);
@ -264,16 +267,16 @@ function testSuite() {
s3.listParts(awsReq, (err, partList) => { s3.listParts(awsReq, (err, partList) => {
assertPartList(partList, uploadId); assertPartList(partList, uploadId);
s3.abortMultipartUpload(awsReq, err => { s3.abortMultipartUpload(awsReq, err => {
assert.equal(err, null, `Error aborting MPU: ${err}. ` + assert.equal(err, null, `Error aborting MPU: ${err}. `
`You must abort MPU with upload ID ${uploadId} manually.`); + `You must abort MPU with upload ID ${uploadId} manually.`);
done(); done();
}); });
}); });
}); });
}); });
it('should copy part an object on AWS to a mpu with a different ' + it('should copy part an object on AWS to a mpu with a different '
'AWS location that has bucketMatch equals false', done => { + 'AWS location that has bucketMatch equals false', done => {
copyPutPart(null, awsLocationMismatch, awsLocation, 'localhost', copyPutPart(null, awsLocationMismatch, awsLocation, 'localhost',
(keys, uploadId) => { (keys, uploadId) => {
assert.deepStrictEqual(ds, []); assert.deepStrictEqual(ds, []);
@ -282,16 +285,16 @@ function testSuite() {
s3.listParts(awsReq, (err, partList) => { s3.listParts(awsReq, (err, partList) => {
assertPartList(partList, uploadId); assertPartList(partList, uploadId);
s3.abortMultipartUpload(awsReq, err => { s3.abortMultipartUpload(awsReq, err => {
assert.equal(err, null, `Error aborting MPU: ${err}. ` + assert.equal(err, null, `Error aborting MPU: ${err}. `
`You must abort MPU with upload ID ${uploadId} manually.`); + `You must abort MPU with upload ID ${uploadId} manually.`);
done(); done();
}); });
}); });
}); });
}); });
it('should return error 403 AccessDenied copying part to a ' + it('should return error 403 AccessDenied copying part to a '
'different AWS location without object READ access', + 'different AWS location without object READ access',
done => { done => {
const errorPutCopyPart = { code: 'AccessDenied', statusCode: 403 }; const errorPutCopyPart = { code: 'AccessDenied', statusCode: 403 };
copyPutPart(null, awsLocation, awsLocation2, 'localhost', done, copyPutPart(null, awsLocation, awsLocation2, 'localhost', done,
@ -305,4 +308,4 @@ function testSuite() {
done(); done();
}); });
}); });
}); });

View File

@ -3,20 +3,17 @@ const async = require('async');
const crypto = require('crypto'); const crypto = require('crypto');
const { parseString } = require('xml2js'); const { parseString } = require('xml2js');
const AWS = require('aws-sdk'); const AWS = require('aws-sdk');
const { metadata } = require('arsenal').storage.metadata.inMemory.metadata;
const { config } = require('../../lib/Config'); const { config } = require('../../lib/Config');
const { cleanup, DummyRequestLogger, makeAuthInfo } const { cleanup, DummyRequestLogger, makeAuthInfo } = require('../unit/helpers');
= require('../unit/helpers');
const { ds } = require('arsenal').storage.data.inMemory.datastore; const { ds } = require('arsenal').storage.data.inMemory.datastore;
const { bucketPut } = require('../../lib/api/bucketPut'); const { bucketPut } = require('../../lib/api/bucketPut');
const initiateMultipartUpload const initiateMultipartUpload = require('../../lib/api/initiateMultipartUpload');
= require('../../lib/api/initiateMultipartUpload');
const objectPutPart = require('../../lib/api/objectPutPart'); const objectPutPart = require('../../lib/api/objectPutPart');
const DummyRequest = require('../unit/DummyRequest'); const DummyRequest = require('../unit/DummyRequest');
const { metadata } = require('arsenal').storage.metadata.inMemory.metadata;
const mdWrapper = require('../../lib/metadata/wrapper'); const mdWrapper = require('../../lib/metadata/wrapper');
const constants = require('../../constants'); const constants = require('../../constants');
const { getRealAwsConfig } = const { getRealAwsConfig } = require('../functional/aws-node-sdk/test/support/awsConfig');
require('../functional/aws-node-sdk/test/support/awsConfig');
const memLocation = 'scality-internal-mem'; const memLocation = 'scality-internal-mem';
const fileLocation = 'scality-internal-file'; const fileLocation = 'scality-internal-file';
@ -25,7 +22,7 @@ const awsLocationMismatch = 'awsbackendmismatch';
const awsConfig = getRealAwsConfig(awsLocation); const awsConfig = getRealAwsConfig(awsLocation);
const s3 = new AWS.S3(awsConfig); const s3 = new AWS.S3(awsConfig);
const splitter = constants.splitter; const { splitter } = constants;
const log = new DummyRequestLogger(); const log = new DummyRequestLogger();
const canonicalID = 'accessKey1'; const canonicalID = 'accessKey1';
const authInfo = makeAuthInfo(canonicalID); const authInfo = makeAuthInfo(canonicalID);
@ -47,13 +44,13 @@ function _getOverviewKey(objectKey, uploadId) {
} }
function putPart(bucketLoc, mpuLoc, requestHost, cb, function putPart(bucketLoc, mpuLoc, requestHost, cb,
errorDescription) { errorDescription) {
const objectName = `objectName-${Date.now()}`; const objectName = `objectName-${Date.now()}`;
const post = bucketLoc ? '<?xml version="1.0" encoding="UTF-8"?>' + const post = bucketLoc ? '<?xml version="1.0" encoding="UTF-8"?>'
'<CreateBucketConfiguration ' + + '<CreateBucketConfiguration '
'xmlns="http://s3.amazonaws.com/doc/2006-03-01/">' + + 'xmlns="http://s3.amazonaws.com/doc/2006-03-01/">'
`<LocationConstraint>${bucketLoc}</LocationConstraint>` + + `<LocationConstraint>${bucketLoc}</LocationConstraint>`
'</CreateBucketConfiguration>' : ''; + '</CreateBucketConfiguration>' : '';
const bucketPutReq = { const bucketPutReq = {
bucketName, bucketName,
namespace, namespace,
@ -70,10 +67,13 @@ errorDescription) {
objectKey: objectName, objectKey: objectName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
url: `/${objectName}?uploads`, url: `/${objectName}?uploads`,
actionImplicitDenies: false,
}; };
if (mpuLoc) { if (mpuLoc) {
initiateReq.headers = { 'host': `${bucketName}.s3.amazonaws.com`, initiateReq.headers = {
'x-amz-meta-scal-location-constraint': `${mpuLoc}` }; 'host': `${bucketName}.s3.amazonaws.com`,
'x-amz-meta-scal-location-constraint': `${mpuLoc}`,
};
} }
if (requestHost) { if (requestHost) {
initiateReq.parsedHost = requestHost; initiateReq.parsedHost = requestHost;
@ -123,9 +123,9 @@ errorDescription) {
const partReq = new DummyRequest(partReqParams, body1); const partReq = new DummyRequest(partReqParams, body1);
return objectPutPart(authInfo, partReq, undefined, log, err => { return objectPutPart(authInfo, partReq, undefined, log, err => {
assert.strictEqual(err, null); assert.strictEqual(err, null);
if (bucketLoc !== awsLocation && mpuLoc !== awsLocation && if (bucketLoc !== awsLocation && mpuLoc !== awsLocation
bucketLoc !== awsLocationMismatch && && bucketLoc !== awsLocationMismatch
mpuLoc !== awsLocationMismatch) { && mpuLoc !== awsLocationMismatch) {
const keysInMPUkeyMap = []; const keysInMPUkeyMap = [];
metadata.keyMaps.get(mpuBucket).forEach((val, key) => { metadata.keyMaps.get(mpuBucket).forEach((val, key) => {
keysInMPUkeyMap.push(key); keysInMPUkeyMap.push(key);
@ -148,8 +148,8 @@ errorDescription) {
} }
function listAndAbort(uploadId, calculatedHash2, objectName, done) { function listAndAbort(uploadId, calculatedHash2, objectName, done) {
const awsBucket = config.locationConstraints[awsLocation]. const awsBucket = config.locationConstraints[awsLocation]
details.bucketName; .details.bucketName;
const params = { const params = {
Bucket: awsBucket, Bucket: awsBucket,
Key: objectName, Key: objectName,
@ -162,15 +162,15 @@ function listAndAbort(uploadId, calculatedHash2, objectName, done) {
assert.strictEqual(`"${calculatedHash2}"`, data.Parts[0].ETag); assert.strictEqual(`"${calculatedHash2}"`, data.Parts[0].ETag);
} }
s3.abortMultipartUpload(params, err => { s3.abortMultipartUpload(params, err => {
assert.equal(err, null, `Error aborting MPU: ${err}. ` + assert.equal(err, null, `Error aborting MPU: ${err}. `
`You must abort MPU with upload ID ${uploadId} manually.`); + `You must abort MPU with upload ID ${uploadId} manually.`);
done(); done();
}); });
}); });
} }
describeSkipIfE2E('objectPutPart API with multiple backends', describeSkipIfE2E('objectPutPart API with multiple backends',
function testSuite() { function testSuite() {
this.timeout(5000); this.timeout(5000);
beforeEach(() => { beforeEach(() => {
@ -211,8 +211,10 @@ function testSuite() {
bucketName, bucketName,
namespace, namespace,
objectKey: objectName, objectKey: objectName,
headers: { 'host': `${bucketName}.s3.amazonaws.com`, headers: {
'x-amz-meta-scal-location-constraint': awsLocation }, 'host': `${bucketName}.s3.amazonaws.com`,
'x-amz-meta-scal-location-constraint': awsLocation,
},
url: `/${objectName}?partNumber=1&uploadId=${uploadId}`, url: `/${objectName}?partNumber=1&uploadId=${uploadId}`,
query: { query: {
partNumber: '1', uploadId, partNumber: '1', uploadId,
@ -226,8 +228,8 @@ function testSuite() {
}); });
}); });
it('should upload part based on mpu location even if part ' + it('should upload part based on mpu location even if part '
'location constraint is specified ', done => { + 'location constraint is specified ', done => {
putPart(fileLocation, memLocation, 'localhost', () => { putPart(fileLocation, memLocation, 'localhost', () => {
assert.deepStrictEqual(ds[1].value, body1); assert.deepStrictEqual(ds[1].value, body1);
done(); done();
@ -256,8 +258,8 @@ function testSuite() {
}); });
}); });
it('should put a part to AWS based on bucket location with bucketMatch ' + it('should put a part to AWS based on bucket location with bucketMatch '
'set to true', done => { + 'set to true', done => {
putPart(null, awsLocation, 'localhost', putPart(null, awsLocation, 'localhost',
(objectName, uploadId) => { (objectName, uploadId) => {
assert.deepStrictEqual(ds, []); assert.deepStrictEqual(ds, []);
@ -265,8 +267,8 @@ function testSuite() {
}); });
}); });
it('should put a part to AWS based on bucket location with bucketMatch ' + it('should put a part to AWS based on bucket location with bucketMatch '
'set to false', done => { + 'set to false', done => {
putPart(null, awsLocationMismatch, 'localhost', putPart(null, awsLocationMismatch, 'localhost',
(objectName, uploadId) => { (objectName, uploadId) => {
assert.deepStrictEqual(ds, []); assert.deepStrictEqual(ds, []);
@ -325,4 +327,4 @@ function testSuite() {
}); });
}); });
}); });
}); });

View File

@ -16,7 +16,7 @@ class DummyRequest extends http.IncomingMessage {
this.parsedContentLength = 0; this.parsedContentLength = 0;
} }
} }
this.actionImplicitDenies = false;
if (Array.isArray(msg)) { if (Array.isArray(msg)) {
msg.forEach(part => { msg.forEach(part => {
this.push(part); this.push(part);

View File

@ -24,6 +24,7 @@ const bucketPutReq = {
bucketName, bucketName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
url: '/', url: '/',
actionImplicitDenies: false,
}; };
const taggingUtil = new TaggingConfigTester(); const taggingUtil = new TaggingConfigTester();

View File

@ -0,0 +1,75 @@
const assert = require('assert');
const validateChecksumHeaders = require('../../../../lib/api/apiUtils/object/validateChecksumHeaders');
const { unsupportedSignatureChecksums, supportedSignatureChecksums } = require('../../../../constants');
const passingCases = [
{
description: 'should return null if no checksum headers are present',
headers: {},
},
{
description: 'should return null if UNSIGNED-PAYLOAD is used',
headers: {
'x-amz-content-sha256': 'UNSIGNED-PAYLOAD',
},
},
{
description: 'should return null if a sha256 checksum is used',
headers: {
'x-amz-content-sha256': 'thisIs64CharactersLongAndThatsAllWeCheckFor1234567890abcdefghijk',
},
},
];
supportedSignatureChecksums.forEach(checksum => {
passingCases.push({
description: `should return null if ${checksum} is used`,
headers: {
'x-amz-content-sha256': checksum,
},
});
});
const failingCases = [
{
description: 'should return BadRequest if a trailing checksum is used',
headers: {
'x-amz-trailer': 'test',
},
},
{
description: 'should return BadRequest if an unknown algo is used',
headers: {
'x-amz-content-sha256': 'UNSUPPORTED-CHECKSUM',
},
},
];
unsupportedSignatureChecksums.forEach(checksum => {
failingCases.push({
description: `should return BadRequest if ${checksum} is used`,
headers: {
'x-amz-content-sha256': checksum,
},
});
});
describe('validateChecksumHeaders', () => {
passingCases.forEach(testCase => {
it(testCase.description, () => {
const result = validateChecksumHeaders(testCase.headers);
assert.ifError(result);
});
});
failingCases.forEach(testCase => {
it(testCase.description, () => {
const result = validateChecksumHeaders(testCase.headers);
assert(result instanceof Error, 'Expected an error to be returned');
assert.strictEqual(result.is.BadRequest, true);
assert.strictEqual(result.code, 400);
});
});
});

View File

@ -244,7 +244,7 @@ describe('bucket policy authorization', () => {
describe('isBucketAuthorized with no policy set', () => { describe('isBucketAuthorized with no policy set', () => {
it('should allow access to bucket owner', done => { it('should allow access to bucket owner', done => {
const allowed = isBucketAuthorized(bucket, 'bucketPut', const allowed = isBucketAuthorized(bucket, 'bucketPut',
bucketOwnerCanonicalId, null, log); bucketOwnerCanonicalId, null, false, log);
assert.equal(allowed, true); assert.equal(allowed, true);
done(); done();
}); });
@ -252,7 +252,7 @@ describe('bucket policy authorization', () => {
it('should deny access to non-bucket owner', it('should deny access to non-bucket owner',
done => { done => {
const allowed = isBucketAuthorized(bucket, 'bucketPut', const allowed = isBucketAuthorized(bucket, 'bucketPut',
altAcctCanonicalId, null, log); altAcctCanonicalId, null, false, log);
assert.equal(allowed, false); assert.equal(allowed, false);
done(); done();
}); });
@ -268,7 +268,7 @@ describe('bucket policy authorization', () => {
it('should allow access to non-bucket owner if principal is set to "*"', it('should allow access to non-bucket owner if principal is set to "*"',
done => { done => {
const allowed = isBucketAuthorized(bucket, bucAction, const allowed = isBucketAuthorized(bucket, bucAction,
altAcctCanonicalId, null, log); altAcctCanonicalId, null, log, null, false);
assert.equal(allowed, true); assert.equal(allowed, true);
done(); done();
}); });
@ -276,7 +276,7 @@ describe('bucket policy authorization', () => {
it('should allow access to public user if principal is set to "*"', it('should allow access to public user if principal is set to "*"',
done => { done => {
const allowed = isBucketAuthorized(bucket, bucAction, const allowed = isBucketAuthorized(bucket, bucAction,
constants.publicId, null, log); constants.publicId, null, log, null, false);
assert.equal(allowed, true); assert.equal(allowed, true);
done(); done();
}); });
@ -287,7 +287,7 @@ describe('bucket policy authorization', () => {
newPolicy.Statement[0][t.keyToChange] = t.bucketValue; newPolicy.Statement[0][t.keyToChange] = t.bucketValue;
bucket.setBucketPolicy(newPolicy); bucket.setBucketPolicy(newPolicy);
const allowed = isBucketAuthorized(bucket, bucAction, const allowed = isBucketAuthorized(bucket, bucAction,
t.bucketId, t.bucketAuthInfo, log); t.bucketId, t.bucketAuthInfo, log, null, false);
assert.equal(allowed, t.expected); assert.equal(allowed, t.expected);
done(); done();
}); });
@ -304,7 +304,7 @@ describe('bucket policy authorization', () => {
}; };
bucket.setBucketPolicy(newPolicy); bucket.setBucketPolicy(newPolicy);
const allowed = isBucketAuthorized(bucket, bucAction, const allowed = isBucketAuthorized(bucket, bucAction,
altAcctCanonicalId, null, log); altAcctCanonicalId, null, log, null, false);
assert.equal(allowed, false); assert.equal(allowed, false);
done(); done();
}); });
@ -312,7 +312,7 @@ describe('bucket policy authorization', () => {
it('should deny access to non-bucket owner with an unsupported action type', it('should deny access to non-bucket owner with an unsupported action type',
done => { done => {
const allowed = isBucketAuthorized(bucket, 'unsupportedAction', const allowed = isBucketAuthorized(bucket, 'unsupportedAction',
altAcctCanonicalId, null, log); altAcctCanonicalId, null, log, null, false);
assert.equal(allowed, false); assert.equal(allowed, false);
done(); done();
}); });
@ -325,7 +325,7 @@ describe('bucket policy authorization', () => {
it('should allow access to object owner', done => { it('should allow access to object owner', done => {
const allowed = isObjAuthorized(bucket, object, objAction, const allowed = isObjAuthorized(bucket, object, objAction,
objectOwnerCanonicalId, null, log); objectOwnerCanonicalId, null, log, null, false);
assert.equal(allowed, true); assert.equal(allowed, true);
done(); done();
}); });
@ -333,7 +333,7 @@ describe('bucket policy authorization', () => {
it('should deny access to non-object owner', it('should deny access to non-object owner',
done => { done => {
const allowed = isObjAuthorized(bucket, object, objAction, const allowed = isObjAuthorized(bucket, object, objAction,
altAcctCanonicalId, null, log); altAcctCanonicalId, null, log, null, false);
assert.equal(allowed, false); assert.equal(allowed, false);
done(); done();
}); });
@ -352,7 +352,7 @@ describe('bucket policy authorization', () => {
it('should allow access to non-object owner if principal is set to "*"', it('should allow access to non-object owner if principal is set to "*"',
done => { done => {
const allowed = isObjAuthorized(bucket, object, objAction, const allowed = isObjAuthorized(bucket, object, objAction,
altAcctCanonicalId, null, log); altAcctCanonicalId, null, log, null, false);
assert.equal(allowed, true); assert.equal(allowed, true);
done(); done();
}); });
@ -360,7 +360,7 @@ describe('bucket policy authorization', () => {
it('should allow access to public user if principal is set to "*"', it('should allow access to public user if principal is set to "*"',
done => { done => {
const allowed = isObjAuthorized(bucket, object, objAction, const allowed = isObjAuthorized(bucket, object, objAction,
constants.publicId, null, log); constants.publicId, null, log, null, false);
assert.equal(allowed, true); assert.equal(allowed, true);
done(); done();
}); });
@ -371,7 +371,7 @@ describe('bucket policy authorization', () => {
newPolicy.Statement[0][t.keyToChange] = t.objectValue; newPolicy.Statement[0][t.keyToChange] = t.objectValue;
bucket.setBucketPolicy(newPolicy); bucket.setBucketPolicy(newPolicy);
const allowed = isObjAuthorized(bucket, object, objAction, const allowed = isObjAuthorized(bucket, object, objAction,
t.objectId, t.objectAuthInfo, log); t.objectId, t.objectAuthInfo, log, null, false);
assert.equal(allowed, t.expected); assert.equal(allowed, t.expected);
done(); done();
}); });
@ -383,7 +383,7 @@ describe('bucket policy authorization', () => {
newPolicy.Statement[0].Action = ['s3:GetObject']; newPolicy.Statement[0].Action = ['s3:GetObject'];
bucket.setBucketPolicy(newPolicy); bucket.setBucketPolicy(newPolicy);
const allowed = isObjAuthorized(bucket, object, 'objectHead', const allowed = isObjAuthorized(bucket, object, 'objectHead',
altAcctCanonicalId, altAcctAuthInfo, log); altAcctCanonicalId, altAcctAuthInfo, log, null, false);
assert.equal(allowed, true); assert.equal(allowed, true);
done(); done();
}); });
@ -393,7 +393,7 @@ describe('bucket policy authorization', () => {
newPolicy.Statement[0].Action = ['s3:PutObject']; newPolicy.Statement[0].Action = ['s3:PutObject'];
bucket.setBucketPolicy(newPolicy); bucket.setBucketPolicy(newPolicy);
const allowed = isObjAuthorized(bucket, object, 'objectHead', const allowed = isObjAuthorized(bucket, object, 'objectHead',
altAcctCanonicalId, altAcctAuthInfo, log); altAcctCanonicalId, altAcctAuthInfo, log, null, false);
assert.equal(allowed, false); assert.equal(allowed, false);
done(); done();
}); });
@ -408,7 +408,7 @@ describe('bucket policy authorization', () => {
}; };
bucket.setBucketPolicy(newPolicy); bucket.setBucketPolicy(newPolicy);
const allowed = isObjAuthorized(bucket, object, objAction, const allowed = isObjAuthorized(bucket, object, objAction,
altAcctCanonicalId, null, log); altAcctCanonicalId, null, log, null, false);
assert.equal(allowed, false); assert.equal(allowed, false);
done(); done();
}); });
@ -416,7 +416,7 @@ describe('bucket policy authorization', () => {
it('should deny access to non-object owner with an unsupported action type', it('should deny access to non-object owner with an unsupported action type',
done => { done => {
const allowed = isObjAuthorized(bucket, object, 'unsupportedAction', const allowed = isObjAuthorized(bucket, object, 'unsupportedAction',
altAcctCanonicalId, null, log); altAcctCanonicalId, null, log, null, false);
assert.equal(allowed, false); assert.equal(allowed, false);
done(); done();
}); });

View File

@ -18,11 +18,10 @@ const testBucketPutRequest = {
namespace, namespace,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
url: '/', url: '/',
actionImplicitDenies: false,
}; };
const canonicalIDforSample1 = const canonicalIDforSample1 = '79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be';
'79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be'; const canonicalIDforSample2 = '79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2bf';
const canonicalIDforSample2 =
'79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2bf';
const invalidIds = { const invalidIds = {
'too short': 'id="invalid_id"', 'too short': 'id="invalid_id"',
@ -42,11 +41,10 @@ describe('putBucketACL API', () => {
afterEach(() => cleanup()); afterEach(() => cleanup());
it('should parse a grantheader', () => { it('should parse a grantheader', () => {
const grantRead = const grantRead = `uri=${constants.logId}, `
`uri=${constants.logId}, ` + + 'emailAddress="test@testing.com", '
'emailAddress="test@testing.com", ' + + 'emailAddress="test2@testly.com", '
'emailAddress="test2@testly.com", ' + + 'id="sdfsdfsfwwiieohefs"';
'id="sdfsdfsfwwiieohefs"';
const grantReadHeader = aclUtils.parseGrant(grantRead, 'read'); const grantReadHeader = aclUtils.parseGrant(grantRead, 'read');
const firstIdentifier = grantReadHeader[0].identifier; const firstIdentifier = grantReadHeader[0].identifier;
assert.strictEqual(firstIdentifier, constants.logId); assert.strictEqual(firstIdentifier, constants.logId);
@ -58,7 +56,7 @@ describe('putBucketACL API', () => {
assert.strictEqual(fourthIdentifier, 'sdfsdfsfwwiieohefs'); assert.strictEqual(fourthIdentifier, 'sdfsdfsfwwiieohefs');
const fourthType = grantReadHeader[3].userIDType; const fourthType = grantReadHeader[3].userIDType;
assert.strictEqual(fourthType, 'id'); assert.strictEqual(fourthType, 'id');
const grantType = grantReadHeader[3].grantType; const { grantType } = grantReadHeader[3];
assert.strictEqual(grantType, 'read'); assert.strictEqual(grantType, 'read');
}); });
@ -72,6 +70,7 @@ describe('putBucketACL API', () => {
}, },
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPutACL(authInfo, testACLRequest, log, err => { bucketPutACL(authInfo, testACLRequest, log, err => {
@ -90,6 +89,7 @@ describe('putBucketACL API', () => {
}, },
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPutACL(authInfo, testACLRequest, log, err => { bucketPutACL(authInfo, testACLRequest, log, err => {
assert.strictEqual(err, undefined); assert.strictEqual(err, undefined);
@ -111,6 +111,7 @@ describe('putBucketACL API', () => {
}, },
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
const testACLRequest2 = { const testACLRequest2 = {
bucketName, bucketName,
@ -121,6 +122,7 @@ describe('putBucketACL API', () => {
}, },
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPutACL(authInfo, testACLRequest, log, err => { bucketPutACL(authInfo, testACLRequest, log, err => {
assert.strictEqual(err, undefined); assert.strictEqual(err, undefined);
@ -138,8 +140,8 @@ describe('putBucketACL API', () => {
}); });
}); });
it('should set a canned private ACL ' + it('should set a canned private ACL '
'followed by a log-delivery-write ACL', done => { + 'followed by a log-delivery-write ACL', done => {
const testACLRequest = { const testACLRequest = {
bucketName, bucketName,
namespace, namespace,
@ -149,6 +151,7 @@ describe('putBucketACL API', () => {
}, },
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
const testACLRequest2 = { const testACLRequest2 = {
bucketName, bucketName,
@ -159,6 +162,7 @@ describe('putBucketACL API', () => {
}, },
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPutACL(authInfo, testACLRequest, log, err => { bucketPutACL(authInfo, testACLRequest, log, err => {
@ -184,19 +188,20 @@ describe('putBucketACL API', () => {
headers: { headers: {
'host': `${bucketName}.s3.amazonaws.com`, 'host': `${bucketName}.s3.amazonaws.com`,
'x-amz-grant-full-control': 'x-amz-grant-full-control':
'emailaddress="sampleaccount1@sampling.com"' + 'emailaddress="sampleaccount1@sampling.com"'
',emailaddress="sampleaccount2@sampling.com"', + ',emailaddress="sampleaccount2@sampling.com"',
'x-amz-grant-read': `uri=${constants.logId}`, 'x-amz-grant-read': `uri=${constants.logId}`,
'x-amz-grant-write': `uri=${constants.publicId}`, 'x-amz-grant-write': `uri=${constants.publicId}`,
'x-amz-grant-read-acp': 'x-amz-grant-read-acp':
'id=79a59df900b949e55d96a1e698fbacedfd6e09d98eac' + 'id=79a59df900b949e55d96a1e698fbacedfd6e09d98eac'
'f8f8d5218e7cd47ef2be', + 'f8f8d5218e7cd47ef2be',
'x-amz-grant-write-acp': 'x-amz-grant-write-acp':
'id=79a59df900b949e55d96a1e698fbacedfd6e09d98eac' + 'id=79a59df900b949e55d96a1e698fbacedfd6e09d98eac'
'f8f8d5218e7cd47ef2bf', + 'f8f8d5218e7cd47ef2bf',
}, },
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPutACL(authInfo, testACLRequest, log, err => { bucketPutACL(authInfo, testACLRequest, log, err => {
assert.strictEqual(err, undefined); assert.strictEqual(err, undefined);
@ -223,21 +228,22 @@ describe('putBucketACL API', () => {
headers: { headers: {
'host': `${bucketName}.s3.amazonaws.com`, 'host': `${bucketName}.s3.amazonaws.com`,
'x-amz-grant-full-control': 'x-amz-grant-full-control':
'emailaddress="sampleaccount1@sampling.com"' + 'emailaddress="sampleaccount1@sampling.com"'
',emailaddress="sampleaccount2@sampling.com"', + ',emailaddress="sampleaccount2@sampling.com"',
'x-amz-grant-read': 'x-amz-grant-read':
'emailaddress="sampleaccount1@sampling.com"', 'emailaddress="sampleaccount1@sampling.com"',
'x-amz-grant-write': 'x-amz-grant-write':
'emailaddress="sampleaccount1@sampling.com"', 'emailaddress="sampleaccount1@sampling.com"',
'x-amz-grant-read-acp': 'x-amz-grant-read-acp':
'id=79a59df900b949e55d96a1e698fbacedfd6e09d98eac' + 'id=79a59df900b949e55d96a1e698fbacedfd6e09d98eac'
'f8f8d5218e7cd47ef2be', + 'f8f8d5218e7cd47ef2be',
'x-amz-grant-write-acp': 'x-amz-grant-write-acp':
'id=79a59df900b949e55d96a1e698fbacedfd6e09d98eac' + 'id=79a59df900b949e55d96a1e698fbacedfd6e09d98eac'
'f8f8d5218e7cd47ef2bf', + 'f8f8d5218e7cd47ef2bf',
}, },
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPutACL(authInfo, testACLRequest, log, err => { bucketPutACL(authInfo, testACLRequest, log, err => {
assert.strictEqual(err, undefined); assert.strictEqual(err, undefined);
@ -260,8 +266,8 @@ describe('putBucketACL API', () => {
}); });
Object.keys(invalidIds).forEach(idType => { Object.keys(invalidIds).forEach(idType => {
it('should return an error if grantee canonical ID provided in ACL ' + it('should return an error if grantee canonical ID provided in ACL '
`request invalid because ${idType}`, done => { + `request invalid because ${idType}`, done => {
const testACLRequest = { const testACLRequest = {
bucketName, bucketName,
namespace, namespace,
@ -271,6 +277,7 @@ describe('putBucketACL API', () => {
}, },
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
return bucketPutACL(authInfo, testACLRequest, log, err => { return bucketPutACL(authInfo, testACLRequest, log, err => {
assert.deepStrictEqual(err, errors.InvalidArgument); assert.deepStrictEqual(err, errors.InvalidArgument);
@ -279,19 +286,20 @@ describe('putBucketACL API', () => {
}); });
}); });
it('should return an error if invalid email ' + it('should return an error if invalid email '
'provided in ACL header request', done => { + 'provided in ACL header request', done => {
const testACLRequest = { const testACLRequest = {
bucketName, bucketName,
namespace, namespace,
headers: { headers: {
'host': `${bucketName}.s3.amazonaws.com`, 'host': `${bucketName}.s3.amazonaws.com`,
'x-amz-grant-full-control': 'x-amz-grant-full-control':
'emailaddress="sampleaccount1@sampling.com"' + 'emailaddress="sampleaccount1@sampling.com"'
',emailaddress="nonexistentEmail@sampling.com"', + ',emailaddress="nonexistentEmail@sampling.com"',
}, },
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPutACL(authInfo, testACLRequest, log, err => { bucketPutACL(authInfo, testACLRequest, log, err => {
@ -305,52 +313,53 @@ describe('putBucketACL API', () => {
bucketName, bucketName,
namespace, namespace,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
post: '<AccessControlPolicy xmlns=' + post: '<AccessControlPolicy xmlns='
'"http://s3.amazonaws.com/doc/2006-03-01/">' + + '"http://s3.amazonaws.com/doc/2006-03-01/">'
'<Owner>' + + '<Owner>'
'<ID>79a59df900b949e55d96a1e698fbaced' + + '<ID>79a59df900b949e55d96a1e698fbaced'
'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>' + + 'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>'
'<DisplayName>OwnerDisplayName</DisplayName>' + + '<DisplayName>OwnerDisplayName</DisplayName>'
'</Owner>' + + '</Owner>'
'<AccessControlList>' + + '<AccessControlList>'
'<Grant>' + + '<Grant>'
'<Grantee xsi:type="CanonicalUser">' + + '<Grantee xsi:type="CanonicalUser">'
'<ID>79a59df900b949e55d96a1e698fbaced' + + '<ID>79a59df900b949e55d96a1e698fbaced'
'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>' + + 'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>'
'<DisplayName>OwnerDisplayName</DisplayName>' + + '<DisplayName>OwnerDisplayName</DisplayName>'
'</Grantee>' + + '</Grantee>'
'<Permission>FULL_CONTROL</Permission>' + + '<Permission>FULL_CONTROL</Permission>'
'</Grant>' + + '</Grant>'
'<Grant>' + + '<Grant>'
'<Grantee xsi:type="Group">' + + '<Grantee xsi:type="Group">'
`<URI>${constants.publicId}</URI>` + + `<URI>${constants.publicId}</URI>`
'</Grantee>' + + '</Grantee>'
'<Permission>READ</Permission>' + + '<Permission>READ</Permission>'
'</Grant>' + + '</Grant>'
'<Grant>' + + '<Grant>'
'<Grantee xsi:type="Group">' + + '<Grantee xsi:type="Group">'
`<URI>${constants.logId}</URI>` + + `<URI>${constants.logId}</URI>`
'</Grantee>' + + '</Grantee>'
'<Permission>WRITE</Permission>' + + '<Permission>WRITE</Permission>'
'</Grant>' + + '</Grant>'
'<Grant>' + + '<Grant>'
'<Grantee xsi:type="AmazonCustomerByEmail">' + + '<Grantee xsi:type="AmazonCustomerByEmail">'
'<EmailAddress>sampleaccount1@sampling.com' + + '<EmailAddress>sampleaccount1@sampling.com'
'</EmailAddress>' + + '</EmailAddress>'
'</Grantee>' + + '</Grantee>'
'<Permission>WRITE_ACP</Permission>' + + '<Permission>WRITE_ACP</Permission>'
'</Grant>' + + '</Grant>'
'<Grant>' + + '<Grant>'
'<Grantee xsi:type="CanonicalUser">' + + '<Grantee xsi:type="CanonicalUser">'
'<ID>79a59df900b949e55d96a1e698fbacedfd' + + '<ID>79a59df900b949e55d96a1e698fbacedfd'
'6e09d98eacf8f8d5218e7cd47ef2bf</ID>' + + '6e09d98eacf8f8d5218e7cd47ef2bf</ID>'
'</Grantee>' + + '</Grantee>'
'<Permission>READ_ACP</Permission>' + + '<Permission>READ_ACP</Permission>'
'</Grant>' + + '</Grant>'
'</AccessControlList>' + + '</AccessControlList>'
'</AccessControlPolicy>', + '</AccessControlPolicy>',
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPutACL(authInfo, testACLRequest, log, err => { bucketPutACL(authInfo, testACLRequest, log, err => {
@ -375,17 +384,18 @@ describe('putBucketACL API', () => {
bucketName, bucketName,
namespace, namespace,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
post: '<AccessControlPolicy xmlns=' + post: '<AccessControlPolicy xmlns='
'"http://s3.amazonaws.com/doc/2006-03-01/">' + + '"http://s3.amazonaws.com/doc/2006-03-01/">'
'<Owner>' + + '<Owner>'
'<ID>79a59df900b949e55d96a1e698fbaced' + + '<ID>79a59df900b949e55d96a1e698fbaced'
'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>' + + 'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>'
'<DisplayName>OwnerDisplayName</DisplayName>' + + '<DisplayName>OwnerDisplayName</DisplayName>'
'</Owner>' + + '</Owner>'
'<AccessControlList></AccessControlList>' + + '<AccessControlList></AccessControlList>'
'</AccessControlPolicy>', + '</AccessControlPolicy>',
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPutACL(authInfo, testACLRequest, log, err => { bucketPutACL(authInfo, testACLRequest, log, err => {
@ -408,16 +418,17 @@ describe('putBucketACL API', () => {
bucketName, bucketName,
namespace, namespace,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
post: '<AccessControlPolicy xmlns=' + post: '<AccessControlPolicy xmlns='
'"http://s3.amazonaws.com/doc/2006-03-01/">' + + '"http://s3.amazonaws.com/doc/2006-03-01/">'
'<Owner>' + + '<Owner>'
'<ID>79a59df900b949e55d96a1e698fbaced' + + '<ID>79a59df900b949e55d96a1e698fbaced'
'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>' + + 'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>'
'<DisplayName>OwnerDisplayName</DisplayName>' + + '<DisplayName>OwnerDisplayName</DisplayName>'
'</Owner>' + + '</Owner>'
'</AccessControlPolicy>', + '</AccessControlPolicy>',
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPutACL(authInfo, testACLRequest, log, err => { bucketPutACL(authInfo, testACLRequest, log, err => {
@ -431,36 +442,37 @@ describe('putBucketACL API', () => {
bucketName, bucketName,
namespace, namespace,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
post: '<AccessControlPolicy xmlns=' + post: '<AccessControlPolicy xmlns='
'"http://s3.amazonaws.com/doc/2006-03-01/">' + + '"http://s3.amazonaws.com/doc/2006-03-01/">'
'<Owner>' + + '<Owner>'
'<ID>79a59df900b949e55d96a1e698fbaced' + + '<ID>79a59df900b949e55d96a1e698fbaced'
'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>' + + 'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>'
'<DisplayName>OwnerDisplayName</DisplayName>' + + '<DisplayName>OwnerDisplayName</DisplayName>'
'</Owner>' + + '</Owner>'
'<AccessControlList>' + + '<AccessControlList>'
'<Grant>' + + '<Grant>'
'<Grantee xsi:type="CanonicalUser">' + + '<Grantee xsi:type="CanonicalUser">'
'<ID>79a59df900b949e55d96a1e698fbaced' + + '<ID>79a59df900b949e55d96a1e698fbaced'
'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>' + + 'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>'
'<DisplayName>OwnerDisplayName</DisplayName>' + + '<DisplayName>OwnerDisplayName</DisplayName>'
'</Grantee>' + + '</Grantee>'
'<Permission>FULL_CONTROL</Permission>' + + '<Permission>FULL_CONTROL</Permission>'
'</Grant>' + + '</Grant>'
'</AccessControlList>' + + '</AccessControlList>'
'<AccessControlList>' + + '<AccessControlList>'
'<Grant>' + + '<Grant>'
'<Grantee xsi:type="CanonicalUser">' + + '<Grantee xsi:type="CanonicalUser">'
'<ID>79a59df900b949e55d96a1e698fbaced' + + '<ID>79a59df900b949e55d96a1e698fbaced'
'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>' + + 'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>'
'<DisplayName>OwnerDisplayName</DisplayName>' + + '<DisplayName>OwnerDisplayName</DisplayName>'
'</Grantee>' + + '</Grantee>'
'<Permission>READ</Permission>' + + '<Permission>READ</Permission>'
'</Grant>' + + '</Grant>'
'</AccessControlList>' + + '</AccessControlList>'
'</AccessControlPolicy>', + '</AccessControlPolicy>',
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPutACL(authInfo, testACLRequest, log, err => { bucketPutACL(authInfo, testACLRequest, log, err => {
@ -469,30 +481,31 @@ describe('putBucketACL API', () => {
}); });
}); });
it('should return an error if invalid grantee user ID ' + it('should return an error if invalid grantee user ID '
'provided in ACL request body', done => { + 'provided in ACL request body', done => {
const testACLRequest = { const testACLRequest = {
bucketName, bucketName,
namespace, namespace,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
post: '<AccessControlPolicy xmlns=' + post: '<AccessControlPolicy xmlns='
'"http://s3.amazonaws.com/doc/2006-03-01/">' + + '"http://s3.amazonaws.com/doc/2006-03-01/">'
'<Owner>' + + '<Owner>'
'<ID>79a59df900b949e55d96a1e698fbaced' + + '<ID>79a59df900b949e55d96a1e698fbaced'
'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>' + + 'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>'
'<DisplayName>OwnerDisplayName</DisplayName>' + + '<DisplayName>OwnerDisplayName</DisplayName>'
'</Owner>' + + '</Owner>'
'<AccessControlList>' + + '<AccessControlList>'
'<Grant>' + + '<Grant>'
'<Grantee xsi:type="CanonicalUser">' + + '<Grantee xsi:type="CanonicalUser">'
'<ID>invalid_id</ID>' + + '<ID>invalid_id</ID>'
'</Grantee>' + + '</Grantee>'
'<Permission>READ_ACP</Permission>' + + '<Permission>READ_ACP</Permission>'
'</Grant>' + + '</Grant>'
'</AccessControlList>' + + '</AccessControlList>'
'</AccessControlPolicy>', + '</AccessControlPolicy>',
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
return bucketPutACL(authInfo, testACLRequest, log, err => { return bucketPutACL(authInfo, testACLRequest, log, err => {
@ -501,30 +514,31 @@ describe('putBucketACL API', () => {
}); });
}); });
it('should return an error if invalid email ' + it('should return an error if invalid email '
'address provided in ACLs set out in request body', done => { + 'address provided in ACLs set out in request body', done => {
const testACLRequest = { const testACLRequest = {
bucketName, bucketName,
namespace, namespace,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
post: '<AccessControlPolicy xmlns=' + post: '<AccessControlPolicy xmlns='
'"http://s3.amazonaws.com/doc/2006-03-01/">' + + '"http://s3.amazonaws.com/doc/2006-03-01/">'
'<Owner>' + + '<Owner>'
'<ID>79a59df900b949e55d96a1e698fbaced' + + '<ID>79a59df900b949e55d96a1e698fbaced'
'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>' + + 'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>'
'<DisplayName>OwnerDisplayName</DisplayName>' + + '<DisplayName>OwnerDisplayName</DisplayName>'
'</Owner>' + + '</Owner>'
'<AccessControlList>' + + '<AccessControlList>'
'<Grant>' + + '<Grant>'
'<Grantee xsi:type="AmazonCustomerByEmail">' + + '<Grantee xsi:type="AmazonCustomerByEmail">'
'<EmailAddress>xyz@amazon.com</EmailAddress>' + + '<EmailAddress>xyz@amazon.com</EmailAddress>'
'</Grantee>' + + '</Grantee>'
'<Permission>WRITE_ACP</Permission>' + + '<Permission>WRITE_ACP</Permission>'
'</Grant>' + + '</Grant>'
'</AccessControlList>' + + '</AccessControlList>'
'</AccessControlPolicy>', + '</AccessControlPolicy>',
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPutACL(authInfo, testACLRequest, log, err => { bucketPutACL(authInfo, testACLRequest, log, err => {
assert.deepStrictEqual(err, errors.UnresolvableGrantByEmailAddress); assert.deepStrictEqual(err, errors.UnresolvableGrantByEmailAddress);
@ -542,24 +556,25 @@ describe('putBucketACL API', () => {
* "Grant" which is part of the s3 xml scheme for ACLs * "Grant" which is part of the s3 xml scheme for ACLs
* so an error should be returned * so an error should be returned
*/ */
post: '<AccessControlPolicy xmlns=' + post: '<AccessControlPolicy xmlns='
'"http://s3.amazonaws.com/doc/2006-03-01/">' + + '"http://s3.amazonaws.com/doc/2006-03-01/">'
'<Owner>' + + '<Owner>'
'<ID>79a59df900b949e55d96a1e698fbaced' + + '<ID>79a59df900b949e55d96a1e698fbaced'
'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>' + + 'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>'
'<DisplayName>OwnerDisplayName</DisplayName>' + + '<DisplayName>OwnerDisplayName</DisplayName>'
'</Owner>' + + '</Owner>'
'<AccessControlList>' + + '<AccessControlList>'
'<PowerGrant>' + + '<PowerGrant>'
'<Grantee xsi:type="AmazonCustomerByEmail">' + + '<Grantee xsi:type="AmazonCustomerByEmail">'
'<EmailAddress>xyz@amazon.com</EmailAddress>' + + '<EmailAddress>xyz@amazon.com</EmailAddress>'
'</Grantee>' + + '</Grantee>'
'<Permission>WRITE_ACP</Permission>' + + '<Permission>WRITE_ACP</Permission>'
'</PowerGrant>' + + '</PowerGrant>'
'</AccessControlList>' + + '</AccessControlList>'
'</AccessControlPolicy>', + '</AccessControlPolicy>',
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPutACL(authInfo, testACLRequest, log, err => { bucketPutACL(authInfo, testACLRequest, log, err => {
@ -579,32 +594,33 @@ describe('putBucketACL API', () => {
* "Grant" which is part of the s3 xml scheme for ACLs * "Grant" which is part of the s3 xml scheme for ACLs
* so an error should be returned * so an error should be returned
*/ */
post: '<AccessControlPolicy xmlns=' + post: '<AccessControlPolicy xmlns='
'"http://s3.amazonaws.com/doc/2006-03-01/">' + + '"http://s3.amazonaws.com/doc/2006-03-01/">'
'<Owner>' + + '<Owner>'
'<ID>79a59df900b949e55d96a1e698fbaced' + + '<ID>79a59df900b949e55d96a1e698fbaced'
'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>' + + 'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>'
'<DisplayName>OwnerDisplayName</DisplayName>' + + '<DisplayName>OwnerDisplayName</DisplayName>'
'</Owner>' + + '</Owner>'
'<AccessControlList>' + + '<AccessControlList>'
'<Grant>' + + '<Grant>'
'<Grantee xsi:type="CanonicalUser">' + + '<Grantee xsi:type="CanonicalUser">'
'<ID>79a59df900b949e55d96a1e698fbaced' + + '<ID>79a59df900b949e55d96a1e698fbaced'
'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>' + + 'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>'
'<DisplayName>OwnerDisplayName</DisplayName>' + + '<DisplayName>OwnerDisplayName</DisplayName>'
'</Grantee>' + + '</Grantee>'
'<Permission>FULL_CONTROL</Permission>' + + '<Permission>FULL_CONTROL</Permission>'
'</Grant>' + + '</Grant>'
'<PowerGrant>' + + '<PowerGrant>'
'<Grantee xsi:type="AmazonCustomerByEmail">' + + '<Grantee xsi:type="AmazonCustomerByEmail">'
'<EmailAddress>xyz@amazon.com</EmailAddress>' + + '<EmailAddress>xyz@amazon.com</EmailAddress>'
'</Grantee>' + + '</Grantee>'
'<Permission>WRITE_ACP</Permission>' + + '<Permission>WRITE_ACP</Permission>'
'</PowerGrant>' + + '</PowerGrant>'
'</AccessControlList>' + + '</AccessControlList>'
'</AccessControlPolicy>', + '</AccessControlPolicy>',
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPutACL(authInfo, testACLRequest, log, err => { bucketPutACL(authInfo, testACLRequest, log, err => {
@ -622,24 +638,25 @@ describe('putBucketACL API', () => {
// so an error should be returned // so an error should be returned
post: { post: {
'<AccessControlPolicy xmlns': '<AccessControlPolicy xmlns':
'"http://s3.amazonaws.com/doc/2006-03-01/">' + '"http://s3.amazonaws.com/doc/2006-03-01/">'
'<Owner>' + + '<Owner>'
'<ID>79a59df900b949e55d96a1e698fbaced' + + '<ID>79a59df900b949e55d96a1e698fbaced'
'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>' + + 'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>'
'<DisplayName>OwnerDisplayName</DisplayName>' + + '<DisplayName>OwnerDisplayName</DisplayName>'
'<Owner>' + + '<Owner>'
'<AccessControlList>' + + '<AccessControlList>'
'<Grant>' + + '<Grant>'
'<Grantee xsi:type="AmazonCustomerByEmail">' + + '<Grantee xsi:type="AmazonCustomerByEmail">'
'<EmailAddress>xyz@amazon.com</EmailAddress>' + + '<EmailAddress>xyz@amazon.com</EmailAddress>'
'<Grantee>' + + '<Grantee>'
'<Permission>WRITE_ACP</Permission>' + + '<Permission>WRITE_ACP</Permission>'
'<Grant>' + + '<Grant>'
'<AccessControlList>' + + '<AccessControlList>'
'<AccessControlPolicy>', + '<AccessControlPolicy>',
}, },
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPutACL(authInfo, testACLRequest, log, err => { bucketPutACL(authInfo, testACLRequest, log, err => {
@ -648,32 +665,33 @@ describe('putBucketACL API', () => {
}); });
}); });
it('should return an error if invalid group ' + it('should return an error if invalid group '
'uri provided in ACLs set out in request body', done => { + 'uri provided in ACLs set out in request body', done => {
const testACLRequest = { const testACLRequest = {
bucketName, bucketName,
namespace, namespace,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
// URI in grant below is not valid group URI for s3 // URI in grant below is not valid group URI for s3
post: '<AccessControlPolicy xmlns=' + post: '<AccessControlPolicy xmlns='
'"http://s3.amazonaws.com/doc/2006-03-01/">' + + '"http://s3.amazonaws.com/doc/2006-03-01/">'
'<Owner>' + + '<Owner>'
'<ID>79a59df900b949e55d96a1e698fbaced' + + '<ID>79a59df900b949e55d96a1e698fbaced'
'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>' + + 'fd6e09d98eacf8f8d5218e7cd47ef2be</ID>'
'<DisplayName>OwnerDisplayName</DisplayName>' + + '<DisplayName>OwnerDisplayName</DisplayName>'
'</Owner>' + + '</Owner>'
'<AccessControlList>' + + '<AccessControlList>'
'<Grant>' + + '<Grant>'
'<Grantee xsi:type="Group">' + + '<Grantee xsi:type="Group">'
'<URI>http://acs.amazonaws.com/groups/' + + '<URI>http://acs.amazonaws.com/groups/'
'global/NOTAVALIDGROUP</URI>' + + 'global/NOTAVALIDGROUP</URI>'
'</Grantee>' + + '</Grantee>'
'<Permission>READ</Permission>' + + '<Permission>READ</Permission>'
'</Grant>' + + '</Grant>'
'</AccessControlList>' + + '</AccessControlList>'
'</AccessControlPolicy>', + '</AccessControlPolicy>',
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPutACL(authInfo, testACLRequest, log, err => { bucketPutACL(authInfo, testACLRequest, log, err => {
@ -682,19 +700,20 @@ describe('putBucketACL API', () => {
}); });
}); });
it('should return an error if invalid group uri' + it('should return an error if invalid group uri'
'provided in ACL header request', done => { + 'provided in ACL header request', done => {
const testACLRequest = { const testACLRequest = {
bucketName, bucketName,
namespace, namespace,
headers: { headers: {
'host': `${bucketName}.s3.amazonaws.com`, 'host': `${bucketName}.s3.amazonaws.com`,
'x-amz-grant-full-control': 'x-amz-grant-full-control':
'uri="http://acs.amazonaws.com/groups/' + 'uri="http://acs.amazonaws.com/groups/'
'global/NOTAVALIDGROUP"', + 'global/NOTAVALIDGROUP"',
}, },
url: '/?acl', url: '/?acl',
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPutACL(authInfo, testACLRequest, log, err => { bucketPutACL(authInfo, testACLRequest, log, err => {

View File

@ -3,13 +3,13 @@ const { errors } = require('arsenal');
const { bucketPut } = require('../../../lib/api/bucketPut'); const { bucketPut } = require('../../../lib/api/bucketPut');
const bucketPutCors = require('../../../lib/api/bucketPutCors'); const bucketPutCors = require('../../../lib/api/bucketPutCors');
const { _validator, parseCorsXml } const { _validator, parseCorsXml } = require('../../../lib/api/apiUtils/bucket/bucketCors');
= require('../../../lib/api/apiUtils/bucket/bucketCors'); const {
const { cleanup, cleanup,
DummyRequestLogger, DummyRequestLogger,
makeAuthInfo, makeAuthInfo,
CorsConfigTester } CorsConfigTester,
= require('../helpers'); } = require('../helpers');
const metadata = require('../../../lib/metadata/wrapper'); const metadata = require('../../../lib/metadata/wrapper');
const log = new DummyRequestLogger(); const log = new DummyRequestLogger();
@ -19,6 +19,7 @@ const testBucketPutRequest = {
bucketName, bucketName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
url: '/', url: '/',
actionImplicitDenies: false,
}; };
function _testPutBucketCors(authInfo, request, log, errCode, cb) { function _testPutBucketCors(authInfo, request, log, errCode, cb) {
@ -30,13 +31,13 @@ function _testPutBucketCors(authInfo, request, log, errCode, cb) {
} }
function _generateSampleXml(value) { function _generateSampleXml(value) {
const xml = '<CORSConfiguration>' + const xml = '<CORSConfiguration>'
'<CORSRule>' + + '<CORSRule>'
'<AllowedMethod>PUT</AllowedMethod>' + + '<AllowedMethod>PUT</AllowedMethod>'
'<AllowedOrigin>www.example.com</AllowedOrigin>' + + '<AllowedOrigin>www.example.com</AllowedOrigin>'
`${value}` + + `${value}`
'</CORSRule>' + + '</CORSRule>'
'</CORSConfiguration>'; + '</CORSConfiguration>';
return xml; return xml;
} }
@ -125,8 +126,8 @@ describe('PUT bucket cors :: helper validation functions ', () => {
it('should return MalformedXML if more than one ID per rule', done => { it('should return MalformedXML if more than one ID per rule', done => {
const testValue = 'testid'; const testValue = 'testid';
const xml = _generateSampleXml(`<ID>${testValue}</ID>` + const xml = _generateSampleXml(`<ID>${testValue}</ID>`
`<ID>${testValue}</ID>`); + `<ID>${testValue}</ID>`);
parseCorsXml(xml, log, err => { parseCorsXml(xml, log, err => {
assert(err, 'Expected error but found none'); assert(err, 'Expected error but found none');
assert.deepStrictEqual(err, errors.MalformedXML); assert.deepStrictEqual(err, errors.MalformedXML);
@ -157,8 +158,8 @@ describe('PUT bucket cors :: helper validation functions ', () => {
describe('validateMaxAgeSeconds ', () => { describe('validateMaxAgeSeconds ', () => {
it('should validate successfully for valid value', done => { it('should validate successfully for valid value', done => {
const testValue = 60; const testValue = 60;
const xml = _generateSampleXml(`<MaxAgeSeconds>${testValue}` + const xml = _generateSampleXml(`<MaxAgeSeconds>${testValue}`
'</MaxAgeSeconds>'); + '</MaxAgeSeconds>');
parseCorsXml(xml, log, (err, result) => { parseCorsXml(xml, log, (err, result) => {
assert.strictEqual(err, null, `Found unexpected err ${err}`); assert.strictEqual(err, null, `Found unexpected err ${err}`);
assert.strictEqual(typeof result[0].maxAgeSeconds, 'number'); assert.strictEqual(typeof result[0].maxAgeSeconds, 'number');
@ -167,12 +168,13 @@ describe('PUT bucket cors :: helper validation functions ', () => {
}); });
}); });
it('should return MalformedXML if more than one MaxAgeSeconds ' + it('should return MalformedXML if more than one MaxAgeSeconds '
'per rule', done => { + 'per rule', done => {
const testValue = '60'; const testValue = '60';
const xml = _generateSampleXml( const xml = _generateSampleXml(
`<MaxAgeSeconds>${testValue}</MaxAgeSeconds>` + `<MaxAgeSeconds>${testValue}</MaxAgeSeconds>`
`<MaxAgeSeconds>${testValue}</MaxAgeSeconds>`); + `<MaxAgeSeconds>${testValue}</MaxAgeSeconds>`,
);
parseCorsXml(xml, log, err => { parseCorsXml(xml, log, err => {
assert(err, 'Expected error but found none'); assert(err, 'Expected error but found none');
assert.deepStrictEqual(err, errors.MalformedXML); assert.deepStrictEqual(err, errors.MalformedXML);
@ -182,8 +184,8 @@ describe('PUT bucket cors :: helper validation functions ', () => {
it('should validate & return undefined if empty value', done => { it('should validate & return undefined if empty value', done => {
const testValue = ''; const testValue = '';
const xml = _generateSampleXml(`<MaxAgeSeconds>${testValue}` + const xml = _generateSampleXml(`<MaxAgeSeconds>${testValue}`
'</MaxAgeSeconds>'); + '</MaxAgeSeconds>');
parseCorsXml(xml, log, (err, result) => { parseCorsXml(xml, log, (err, result) => {
assert.strictEqual(err, null, `Found unexpected err ${err}`); assert.strictEqual(err, null, `Found unexpected err ${err}`);
assert.strictEqual(result[0].MaxAgeSeconds, undefined); assert.strictEqual(result[0].MaxAgeSeconds, undefined);

View File

@ -14,6 +14,7 @@ const bucketPutRequest = {
bucketName, bucketName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
url: '/', url: '/',
actionImplicitDenies: false,
}; };
describe('bucketPutEncryption API', () => { describe('bucketPutEncryption API', () => {
@ -32,7 +33,8 @@ describe('bucketPutEncryption API', () => {
it('should reject a config with no Rule', done => { it('should reject a config with no Rule', done => {
bucketPutEncryption(authInfo, templateRequest(bucketName, bucketPutEncryption(authInfo, templateRequest(bucketName,
{ post: `<?xml version="1.0" encoding="UTF-8"?> {
post: `<?xml version="1.0" encoding="UTF-8"?>
<ServerSideEncryptionConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <ServerSideEncryptionConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
</ServerSideEncryptionConfiguration>`, </ServerSideEncryptionConfiguration>`,
}), log, err => { }), log, err => {
@ -43,7 +45,8 @@ describe('bucketPutEncryption API', () => {
it('should reject a config with no ApplyServerSideEncryptionByDefault section', done => { it('should reject a config with no ApplyServerSideEncryptionByDefault section', done => {
bucketPutEncryption(authInfo, templateRequest(bucketName, bucketPutEncryption(authInfo, templateRequest(bucketName,
{ post: `<?xml version="1.0" encoding="UTF-8"?> {
post: `<?xml version="1.0" encoding="UTF-8"?>
<ServerSideEncryptionConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <ServerSideEncryptionConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Rule></Rule> <Rule></Rule>
</ServerSideEncryptionConfiguration>`, </ServerSideEncryptionConfiguration>`,
@ -155,8 +158,8 @@ describe('bucketPutEncryption API', () => {
}); });
}); });
it('should update SSEAlgorithm if existing SSEAlgorithm is AES256, ' + it('should update SSEAlgorithm if existing SSEAlgorithm is AES256, '
'new SSEAlgorithm is aws:kms and no KMSMasterKeyID is provided', + 'new SSEAlgorithm is aws:kms and no KMSMasterKeyID is provided',
done => { done => {
const post = templateSSEConfig({ algorithm: 'AES256' }); const post = templateSSEConfig({ algorithm: 'AES256' });
bucketPutEncryption(authInfo, templateRequest(bucketName, { post }), log, err => { bucketPutEncryption(authInfo, templateRequest(bucketName, { post }), log, err => {
@ -177,8 +180,7 @@ describe('bucketPutEncryption API', () => {
}); });
done(); done();
}); });
} });
);
}); });
}); });
}); });

View File

@ -17,6 +17,7 @@ const testBucketPutRequest = {
bucketName, bucketName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
url: '/', url: '/',
actionImplicitDenies: false,
}; };
const expectedLifecycleConfig = { const expectedLifecycleConfig = {

View File

@ -15,6 +15,7 @@ const bucketPutRequest = {
bucketName, bucketName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
url: '/', url: '/',
actionImplicitDenies: false,
}; };
const expectedNotifConfig = { const expectedNotifConfig = {
@ -52,6 +53,7 @@ function getNotifRequest(empty) {
host: `${bucketName}.s3.amazonaws.com`, host: `${bucketName}.s3.amazonaws.com`,
}, },
post: notifXml, post: notifXml,
actionImplicitDenies: false,
}; };
return putNotifConfigRequest; return putNotifConfigRequest;
} }

View File

@ -15,6 +15,7 @@ const bucketPutRequest = {
bucketName, bucketName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
url: '/', url: '/',
actionImplicitDenies: false,
}; };
const objectLockXml = '<ObjectLockConfiguration ' + const objectLockXml = '<ObjectLockConfiguration ' +
@ -30,6 +31,7 @@ const putObjLockRequest = {
bucketName, bucketName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
post: objectLockXml, post: objectLockXml,
actionImplicitDenies: false,
}; };
const expectedObjectLockConfig = { const expectedObjectLockConfig = {

View File

@ -15,6 +15,7 @@ const testBucketPutRequest = {
bucketName, bucketName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
url: '/', url: '/',
actionImplicitDenies: false,
}; };
let expectedBucketPolicy = {}; let expectedBucketPolicy = {};
@ -25,6 +26,7 @@ function getPolicyRequest(policy) {
host: `${bucketName}.s3.amazonaws.com`, host: `${bucketName}.s3.amazonaws.com`,
}, },
post: JSON.stringify(policy), post: JSON.stringify(policy),
actionImplicitDenies: false,
}; };
} }

View File

@ -19,6 +19,7 @@ const testBucketPutRequest = {
bucketName, bucketName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
url: '/', url: '/',
actionImplicitDenies: false,
}; };
function _getPutWebsiteRequest(xml) { function _getPutWebsiteRequest(xml) {
@ -29,6 +30,7 @@ function _getPutWebsiteRequest(xml) {
}, },
url: '/?website', url: '/?website',
query: { website: '' }, query: { website: '' },
actionImplicitDenies: false,
}; };
request.post = xml; request.post = xml;
return request; return request;

View File

@ -4,14 +4,16 @@ const moment = require('moment');
const { errors, s3middleware } = require('arsenal'); const { errors, s3middleware } = require('arsenal');
const sinon = require('sinon'); const sinon = require('sinon');
const { ds } = require('arsenal').storage.data.inMemory.datastore;
const { bucketPut } = require('../../../lib/api/bucketPut'); const { bucketPut } = require('../../../lib/api/bucketPut');
const bucketPutObjectLock = require('../../../lib/api/bucketPutObjectLock'); const bucketPutObjectLock = require('../../../lib/api/bucketPutObjectLock');
const bucketPutACL = require('../../../lib/api/bucketPutACL'); const bucketPutACL = require('../../../lib/api/bucketPutACL');
const bucketPutVersioning = require('../../../lib/api/bucketPutVersioning'); const bucketPutVersioning = require('../../../lib/api/bucketPutVersioning');
const { parseTagFromQuery } = s3middleware.tagging; const { parseTagFromQuery } = s3middleware.tagging;
const { cleanup, DummyRequestLogger, makeAuthInfo, versioningTestUtils } const {
= require('../helpers'); cleanup, DummyRequestLogger, makeAuthInfo, versioningTestUtils,
const { ds } = require('arsenal').storage.data.inMemory.datastore; } = require('../helpers');
const metadata = require('../metadataswitch'); const metadata = require('../metadataswitch');
const objectPut = require('../../../lib/api/objectPut'); const objectPut = require('../../../lib/api/objectPut');
const { objectLockTestUtils } = require('../helpers'); const { objectLockTestUtils } = require('../helpers');
@ -19,7 +21,7 @@ const DummyRequest = require('../DummyRequest');
const mpuUtils = require('../utils/mpuUtils'); const mpuUtils = require('../utils/mpuUtils');
const { lastModifiedHeader } = require('../../../constants'); const { lastModifiedHeader } = require('../../../constants');
const any = sinon.match.any; const { any } = sinon.match;
const log = new DummyRequestLogger(); const log = new DummyRequestLogger();
const canonicalID = 'accessKey1'; const canonicalID = 'accessKey1';
@ -49,10 +51,8 @@ const originalputObjectMD = metadata.putObjectMD;
const objectName = 'objectName'; const objectName = 'objectName';
let testPutObjectRequest; let testPutObjectRequest;
const enableVersioningRequest = const enableVersioningRequest = versioningTestUtils.createBucketPutVersioningReq(bucketName, 'Enabled');
versioningTestUtils.createBucketPutVersioningReq(bucketName, 'Enabled'); const suspendVersioningRequest = versioningTestUtils.createBucketPutVersioningReq(bucketName, 'Suspended');
const suspendVersioningRequest =
versioningTestUtils.createBucketPutVersioningReq(bucketName, 'Suspended');
function testAuth(bucketOwner, authUser, bucketPutReq, log, cb) { function testAuth(bucketOwner, authUser, bucketPutReq, log, cb) {
bucketPut(bucketOwner, bucketPutReq, log, () => { bucketPut(bucketOwner, bucketPutReq, log, () => {
@ -74,8 +74,10 @@ describe('parseTagFromQuery', () => {
const allowedChar = '+- =._:/'; const allowedChar = '+- =._:/';
const tests = [ const tests = [
{ tagging: 'key1=value1', result: { key1: 'value1' } }, { tagging: 'key1=value1', result: { key1: 'value1' } },
{ tagging: `key1=${encodeURIComponent(allowedChar)}`, {
result: { key1: allowedChar } }, tagging: `key1=${encodeURIComponent(allowedChar)}`,
result: { key1: allowedChar },
},
{ tagging: 'key1=value1=value2', error: invalidArgument }, { tagging: 'key1=value1=value2', error: invalidArgument },
{ tagging: '=value1', error: invalidArgument }, { tagging: '=value1', error: invalidArgument },
{ tagging: 'key1%=value1', error: invalidArgument }, { tagging: 'key1%=value1', error: invalidArgument },
@ -143,16 +145,14 @@ describe('objectPut API', () => {
it('should put object if user has FULL_CONTROL grant on bucket', done => { it('should put object if user has FULL_CONTROL grant on bucket', done => {
const bucketOwner = makeAuthInfo('accessKey2'); const bucketOwner = makeAuthInfo('accessKey2');
const authUser = makeAuthInfo('accessKey3'); const authUser = makeAuthInfo('accessKey3');
testPutBucketRequest.headers['x-amz-grant-full-control'] = testPutBucketRequest.headers['x-amz-grant-full-control'] = `id=${authUser.getCanonicalID()}`;
`id=${authUser.getCanonicalID()}`;
testAuth(bucketOwner, authUser, testPutBucketRequest, log, done); testAuth(bucketOwner, authUser, testPutBucketRequest, log, done);
}); });
it('should put object if user has WRITE grant on bucket', done => { it('should put object if user has WRITE grant on bucket', done => {
const bucketOwner = makeAuthInfo('accessKey2'); const bucketOwner = makeAuthInfo('accessKey2');
const authUser = makeAuthInfo('accessKey3'); const authUser = makeAuthInfo('accessKey3');
testPutBucketRequest.headers['x-amz-grant-write'] = testPutBucketRequest.headers['x-amz-grant-write'] = `id=${authUser.getCanonicalID()}`;
`id=${authUser.getCanonicalID()}`;
testAuth(bucketOwner, authUser, testPutBucketRequest, log, done); testAuth(bucketOwner, authUser, testPutBucketRequest, log, done);
}); });
@ -240,8 +240,8 @@ describe('objectPut API', () => {
]; ];
testObjectLockConfigs.forEach(config => { testObjectLockConfigs.forEach(config => {
const { testMode, type, val } = config; const { testMode, type, val } = config;
it('should put an object with default retention if object does not ' + it('should put an object with default retention if object does not '
'have retention configuration but bucket has', done => { + 'have retention configuration but bucket has', done => {
const testPutObjectRequest = new DummyRequest({ const testPutObjectRequest = new DummyRequest({
bucketName, bucketName,
namespace, namespace,
@ -255,6 +255,7 @@ describe('objectPut API', () => {
bucketName, bucketName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
post: objectLockTestUtils.generateXml(testMode, val, type), post: objectLockTestUtils.generateXml(testMode, val, type),
actionImplicitDenies: false,
}; };
bucketPut(authInfo, testPutBucketRequestLock, log, () => { bucketPut(authInfo, testPutBucketRequestLock, log, () => {
@ -268,10 +269,8 @@ describe('objectPut API', () => {
const mode = md.retentionMode; const mode = md.retentionMode;
const retainDate = md.retentionDate; const retainDate = md.retentionDate;
const date = moment(); const date = moment();
const days const days = type === 'Days' ? val : val * 365;
= type === 'Days' ? val : val * 365; const expectedDate = date.add(days, 'days');
const expectedDate
= date.add(days, 'days');
assert.ifError(err); assert.ifError(err);
assert.strictEqual(mode, testMode); assert.strictEqual(mode, testMode);
assert.strictEqual(formatTime(retainDate), assert.strictEqual(formatTime(retainDate),
@ -534,8 +533,8 @@ describe('objectPut API', () => {
}); });
}); });
it('should not put object with retention configuration if object lock ' + it('should not put object with retention configuration if object lock '
'is not enabled on the bucket', done => { + 'is not enabled on the bucket', done => {
const testPutObjectRequest = new DummyRequest({ const testPutObjectRequest = new DummyRequest({
bucketName, bucketName,
namespace, namespace,
@ -552,15 +551,14 @@ describe('objectPut API', () => {
objectPut(authInfo, testPutObjectRequest, undefined, log, err => { objectPut(authInfo, testPutObjectRequest, undefined, log, err => {
assert.deepStrictEqual(err, errors.InvalidRequest assert.deepStrictEqual(err, errors.InvalidRequest
.customizeDescription( .customizeDescription(
'Bucket is missing ObjectLockConfiguration')); 'Bucket is missing ObjectLockConfiguration',
));
done(); done();
}); });
}); });
}); });
it('should forward a 400 back to client on metadata 408 response', () => { it('should forward a 400 back to client on metadata 408 response', () => {
metadata.putObjectMD = metadata.putObjectMD = (bucketName, objName, objVal, params, log, cb) => cb({ httpCode: 408 });
(bucketName, objName, objVal, params, log, cb) =>
cb({ httpCode: 408 });
bucketPut(authInfo, testPutBucketRequest, log, () => { bucketPut(authInfo, testPutBucketRequest, log, () => {
objectPut(authInfo, testPutObjectRequest, undefined, log, objectPut(authInfo, testPutObjectRequest, undefined, log,
@ -571,9 +569,7 @@ describe('objectPut API', () => {
}); });
it('should forward a 502 to the client for 4xx != 408', () => { it('should forward a 502 to the client for 4xx != 408', () => {
metadata.putObjectMD = metadata.putObjectMD = (bucketName, objName, objVal, params, log, cb) => cb({ httpCode: 412 });
(bucketName, objName, objVal, params, log, cb) =>
cb({ httpCode: 412 });
bucketPut(authInfo, testPutBucketRequest, log, () => { bucketPut(authInfo, testPutBucketRequest, log, () => {
objectPut(authInfo, testPutObjectRequest, undefined, log, objectPut(authInfo, testPutObjectRequest, undefined, log,
@ -589,13 +585,12 @@ describe('objectPut API with versioning', () => {
cleanup(); cleanup();
}); });
const objData = ['foo0', 'foo1', 'foo2'].map(str => const objData = ['foo0', 'foo1', 'foo2'].map(str => Buffer.from(str, 'utf8'));
Buffer.from(str, 'utf8'));
const testPutObjectRequests = objData.map(data => versioningTestUtils const testPutObjectRequests = objData.map(data => versioningTestUtils
.createPutObjectRequest(bucketName, objectName, data)); .createPutObjectRequest(bucketName, objectName, data));
it('should delete latest version when creating new null version ' + it('should delete latest version when creating new null version '
'if latest version is null version', done => { + 'if latest version is null version', done => {
async.series([ async.series([
callback => bucketPut(authInfo, testPutBucketRequest, log, callback => bucketPut(authInfo, testPutBucketRequest, log,
callback), callback),
@ -633,8 +628,7 @@ describe('objectPut API with versioning', () => {
}); });
describe('when null version is not the latest version', () => { describe('when null version is not the latest version', () => {
const objData = ['foo0', 'foo1', 'foo2'].map(str => const objData = ['foo0', 'foo1', 'foo2'].map(str => Buffer.from(str, 'utf8'));
Buffer.from(str, 'utf8'));
const testPutObjectRequests = objData.map(data => versioningTestUtils const testPutObjectRequests = objData.map(data => versioningTestUtils
.createPutObjectRequest(bucketName, objectName, data)); .createPutObjectRequest(bucketName, objectName, data));
beforeEach(done => { beforeEach(done => {
@ -677,8 +671,8 @@ describe('objectPut API with versioning', () => {
}); });
}); });
it('should return BadDigest error and not leave orphans in data when ' + it('should return BadDigest error and not leave orphans in data when '
'contentMD5 and completedHash do not match', done => { + 'contentMD5 and completedHash do not match', done => {
const testPutObjectRequest = new DummyRequest({ const testPutObjectRequest = new DummyRequest({
bucketName, bucketName,
namespace, namespace,

View File

@ -3,11 +3,12 @@ const { errors } = require('arsenal');
const { bucketPut } = require('../../../lib/api/bucketPut'); const { bucketPut } = require('../../../lib/api/bucketPut');
const constants = require('../../../constants'); const constants = require('../../../constants');
const { cleanup, const {
cleanup,
DummyRequestLogger, DummyRequestLogger,
makeAuthInfo, makeAuthInfo,
AccessControlPolicy } AccessControlPolicy,
= require('../helpers'); } = require('../helpers');
const metadata = require('../metadataswitch'); const metadata = require('../metadataswitch');
const objectPut = require('../../../lib/api/objectPut'); const objectPut = require('../../../lib/api/objectPut');
const objectPutACL = require('../../../lib/api/objectPutACL'); const objectPutACL = require('../../../lib/api/objectPutACL');
@ -17,8 +18,8 @@ const log = new DummyRequestLogger();
const canonicalID = 'accessKey1'; const canonicalID = 'accessKey1';
const authInfo = makeAuthInfo(canonicalID); const authInfo = makeAuthInfo(canonicalID);
const ownerID = authInfo.getCanonicalID(); const ownerID = authInfo.getCanonicalID();
const anotherID = '79a59df900b949e55d96a1e698fba' + const anotherID = '79a59df900b949e55d96a1e698fba'
'cedfd6e09d98eacf8f8d5218e7cd47ef2bf'; + 'cedfd6e09d98eacf8f8d5218e7cd47ef2bf';
const defaultAcpParams = { const defaultAcpParams = {
ownerID, ownerID,
ownerDisplayName: 'OwnerDisplayName', ownerDisplayName: 'OwnerDisplayName',
@ -56,6 +57,7 @@ describe('putObjectACL API', () => {
headers: { 'x-amz-acl': 'invalid-option' }, headers: { 'x-amz-acl': 'invalid-option' },
url: `/${bucketName}/${objectName}?acl`, url: `/${bucketName}/${objectName}?acl`,
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPut(authInfo, testPutBucketRequest, log, () => { bucketPut(authInfo, testPutBucketRequest, log, () => {
@ -79,6 +81,7 @@ describe('putObjectACL API', () => {
headers: { 'x-amz-acl': 'public-read-write' }, headers: { 'x-amz-acl': 'public-read-write' },
url: `/${bucketName}/${objectName}?acl`, url: `/${bucketName}/${objectName}?acl`,
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPut(authInfo, testPutBucketRequest, log, () => { bucketPut(authInfo, testPutBucketRequest, log, () => {
@ -108,6 +111,7 @@ describe('putObjectACL API', () => {
headers: { 'x-amz-acl': 'public-read' }, headers: { 'x-amz-acl': 'public-read' },
url: `/${bucketName}/${objectName}?acl`, url: `/${bucketName}/${objectName}?acl`,
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
const testObjACLRequest2 = { const testObjACLRequest2 = {
@ -117,6 +121,7 @@ describe('putObjectACL API', () => {
headers: { 'x-amz-acl': 'authenticated-read' }, headers: { 'x-amz-acl': 'authenticated-read' },
url: `/${bucketName}/${objectName}?acl`, url: `/${bucketName}/${objectName}?acl`,
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPut(authInfo, testPutBucketRequest, log, () => { bucketPut(authInfo, testPutBucketRequest, log, () => {
@ -154,14 +159,15 @@ describe('putObjectACL API', () => {
objectKey: objectName, objectKey: objectName,
headers: { headers: {
'x-amz-grant-full-control': 'x-amz-grant-full-control':
'emailaddress="sampleaccount1@sampling.com"' + 'emailaddress="sampleaccount1@sampling.com"'
',emailaddress="sampleaccount2@sampling.com"', + ',emailaddress="sampleaccount2@sampling.com"',
'x-amz-grant-read': `uri=${constants.logId}`, 'x-amz-grant-read': `uri=${constants.logId}`,
'x-amz-grant-read-acp': `id=${ownerID}`, 'x-amz-grant-read-acp': `id=${ownerID}`,
'x-amz-grant-write-acp': `id=${anotherID}`, 'x-amz-grant-write-acp': `id=${anotherID}`,
}, },
url: `/${bucketName}/${objectName}?acl`, url: `/${bucketName}/${objectName}?acl`,
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPut(authInfo, testPutBucketRequest, log, () => { bucketPut(authInfo, testPutBucketRequest, log, () => {
objectPut(authInfo, testPutObjectRequest, undefined, log, objectPut(authInfo, testPutObjectRequest, undefined, log,
@ -191,19 +197,20 @@ describe('putObjectACL API', () => {
}); });
}); });
it('should return an error if invalid email ' + it('should return an error if invalid email '
'provided in ACL header request', done => { + 'provided in ACL header request', done => {
const testObjACLRequest = { const testObjACLRequest = {
bucketName, bucketName,
namespace, namespace,
objectKey: objectName, objectKey: objectName,
headers: { headers: {
'x-amz-grant-full-control': 'x-amz-grant-full-control':
'emailaddress="sampleaccount1@sampling.com"' + 'emailaddress="sampleaccount1@sampling.com"'
',emailaddress="nonexistentemail@sampling.com"', + ',emailaddress="nonexistentemail@sampling.com"',
}, },
url: `/${bucketName}/${objectName}?acl`, url: `/${bucketName}/${objectName}?acl`,
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPut(authInfo, testPutBucketRequest, log, () => { bucketPut(authInfo, testPutBucketRequest, log, () => {
@ -234,6 +241,7 @@ describe('putObjectACL API', () => {
url: `/${bucketName}/${objectName}?acl`, url: `/${bucketName}/${objectName}?acl`,
post: [Buffer.from(acp.getXml(), 'utf8')], post: [Buffer.from(acp.getXml(), 'utf8')],
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPut(authInfo, testPutBucketRequest, log, () => { bucketPut(authInfo, testPutBucketRequest, log, () => {
@ -260,8 +268,8 @@ describe('putObjectACL API', () => {
}); });
}); });
it('should return an error if wrong owner ID ' + it('should return an error if wrong owner ID '
'provided in ACLs set out in request body', done => { + 'provided in ACLs set out in request body', done => {
const acp = new AccessControlPolicy({ ownerID: anotherID }); const acp = new AccessControlPolicy({ ownerID: anotherID });
const testObjACLRequest = { const testObjACLRequest = {
bucketName, bucketName,
@ -271,6 +279,7 @@ describe('putObjectACL API', () => {
url: `/${bucketName}/${objectName}?acl`, url: `/${bucketName}/${objectName}?acl`,
post: [Buffer.from(acp.getXml(), 'utf8')], post: [Buffer.from(acp.getXml(), 'utf8')],
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPut(authInfo, testPutBucketRequest, log, () => { bucketPut(authInfo, testPutBucketRequest, log, () => {
@ -285,8 +294,8 @@ describe('putObjectACL API', () => {
}); });
}); });
it('should ignore if WRITE ACL permission is ' + it('should ignore if WRITE ACL permission is '
'provided in request body', done => { + 'provided in request body', done => {
const acp = new AccessControlPolicy(defaultAcpParams); const acp = new AccessControlPolicy(defaultAcpParams);
acp.addGrantee('CanonicalUser', ownerID, 'FULL_CONTROL', acp.addGrantee('CanonicalUser', ownerID, 'FULL_CONTROL',
'OwnerDisplayName'); 'OwnerDisplayName');
@ -299,6 +308,7 @@ describe('putObjectACL API', () => {
url: `/${bucketName}/${objectName}?acl`, url: `/${bucketName}/${objectName}?acl`,
post: [Buffer.from(acp.getXml(), 'utf8')], post: [Buffer.from(acp.getXml(), 'utf8')],
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPut(authInfo, testPutBucketRequest, log, () => { bucketPut(authInfo, testPutBucketRequest, log, () => {
@ -325,8 +335,8 @@ describe('putObjectACL API', () => {
}); });
}); });
it('should return an error if invalid email ' + it('should return an error if invalid email '
'address provided in ACLs set out in request body', done => { + 'address provided in ACLs set out in request body', done => {
const acp = new AccessControlPolicy(defaultAcpParams); const acp = new AccessControlPolicy(defaultAcpParams);
acp.addGrantee('AmazonCustomerByEmail', 'xyz@amazon.com', 'WRITE_ACP'); acp.addGrantee('AmazonCustomerByEmail', 'xyz@amazon.com', 'WRITE_ACP');
const testObjACLRequest = { const testObjACLRequest = {
@ -337,6 +347,7 @@ describe('putObjectACL API', () => {
url: `/${bucketName}/${objectName}?acl`, url: `/${bucketName}/${objectName}?acl`,
post: [Buffer.from(acp.getXml(), 'utf8')], post: [Buffer.from(acp.getXml(), 'utf8')],
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
@ -352,8 +363,8 @@ describe('putObjectACL API', () => {
}); });
}); });
it('should return an error if xml provided does not match s3 ' + it('should return an error if xml provided does not match s3 '
'scheme for setting ACLs', done => { + 'scheme for setting ACLs', done => {
const acp = new AccessControlPolicy(defaultAcpParams); const acp = new AccessControlPolicy(defaultAcpParams);
acp.addGrantee('AmazonCustomerByEmail', 'xyz@amazon.com', 'WRITE_ACP'); acp.addGrantee('AmazonCustomerByEmail', 'xyz@amazon.com', 'WRITE_ACP');
const originalXml = acp.getXml(); const originalXml = acp.getXml();
@ -366,6 +377,7 @@ describe('putObjectACL API', () => {
url: `/${bucketName}/${objectName}?acl`, url: `/${bucketName}/${objectName}?acl`,
post: [Buffer.from(modifiedXml, 'utf8')], post: [Buffer.from(modifiedXml, 'utf8')],
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPut(authInfo, testPutBucketRequest, log, () => { bucketPut(authInfo, testPutBucketRequest, log, () => {
@ -394,6 +406,7 @@ describe('putObjectACL API', () => {
url: `/${bucketName}/${objectName}?acl`, url: `/${bucketName}/${objectName}?acl`,
post: [Buffer.from(modifiedXml, 'utf8')], post: [Buffer.from(modifiedXml, 'utf8')],
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
@ -409,11 +422,11 @@ describe('putObjectACL API', () => {
}); });
}); });
it('should return an error if invalid group ' + it('should return an error if invalid group '
'uri provided in ACLs set out in request body', done => { + 'uri provided in ACLs set out in request body', done => {
const acp = new AccessControlPolicy(defaultAcpParams); const acp = new AccessControlPolicy(defaultAcpParams);
acp.addGrantee('Group', 'http://acs.amazonaws.com/groups/' + acp.addGrantee('Group', 'http://acs.amazonaws.com/groups/'
'global/NOTAVALIDGROUP', 'WRITE_ACP'); + 'global/NOTAVALIDGROUP', 'WRITE_ACP');
const testObjACLRequest = { const testObjACLRequest = {
bucketName, bucketName,
namespace, namespace,
@ -422,6 +435,7 @@ describe('putObjectACL API', () => {
url: `/${bucketName}/${objectName}?acl`, url: `/${bucketName}/${objectName}?acl`,
post: [Buffer.from(acp.getXml(), 'utf8')], post: [Buffer.from(acp.getXml(), 'utf8')],
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPut(authInfo, testPutBucketRequest, log, () => { bucketPut(authInfo, testPutBucketRequest, log, () => {
@ -436,8 +450,8 @@ describe('putObjectACL API', () => {
}); });
}); });
it('should return an error if invalid group uri ' + it('should return an error if invalid group uri '
'provided in ACL header request', done => { + 'provided in ACL header request', done => {
const testObjACLRequest = { const testObjACLRequest = {
bucketName, bucketName,
namespace, namespace,
@ -445,11 +459,12 @@ describe('putObjectACL API', () => {
headers: { headers: {
'host': 's3.amazonaws.com', 'host': 's3.amazonaws.com',
'x-amz-grant-full-control': 'x-amz-grant-full-control':
'uri="http://acs.amazonaws.com/groups/' + 'uri="http://acs.amazonaws.com/groups/'
'global/NOTAVALIDGROUP"', + 'global/NOTAVALIDGROUP"',
}, },
url: `/${bucketName}/${objectName}?acl`, url: `/${bucketName}/${objectName}?acl`,
query: { acl: '' }, query: { acl: '' },
actionImplicitDenies: false,
}; };
bucketPut(authInfo, testPutBucketRequest, log, () => { bucketPut(authInfo, testPutBucketRequest, log, () => {

View File

@ -19,6 +19,7 @@ const putBucketRequest = {
bucketName, bucketName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
url: '/', url: '/',
actionImplicitDenies: false,
}; };
const putObjectRequest = new DummyRequest({ const putObjectRequest = new DummyRequest({
@ -29,16 +30,17 @@ const putObjectRequest = new DummyRequest({
url: `/${bucketName}/${objectName}`, url: `/${bucketName}/${objectName}`,
}, postBody); }, postBody);
const objectLegalHoldXml = status => '<LegalHold ' + const objectLegalHoldXml = status => '<LegalHold '
'xmlns="http://s3.amazonaws.com/doc/2006-03-01/">' + + 'xmlns="http://s3.amazonaws.com/doc/2006-03-01/">'
`<Status>${status}</Status>` + + `<Status>${status}</Status>`
'</LegalHold>'; + '</LegalHold>';
const putLegalHoldReq = status => ({ const putLegalHoldReq = status => ({
bucketName, bucketName,
objectKey: objectName, objectKey: objectName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
post: objectLegalHoldXml(status), post: objectLegalHoldXml(status),
actionImplicitDenies: false,
}); });
describe('putObjectLegalHold API', () => { describe('putObjectLegalHold API', () => {

View File

@ -23,6 +23,7 @@ const bucketPutRequest = {
bucketName, bucketName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
url: '/', url: '/',
actionImplicitDenies: false,
}; };
const putObjectRequest = new DummyRequest({ const putObjectRequest = new DummyRequest({
@ -33,41 +34,42 @@ const putObjectRequest = new DummyRequest({
url: `/${bucketName}/${objectName}`, url: `/${bucketName}/${objectName}`,
}, postBody); }, postBody);
const objectRetentionXmlGovernance = '<Retention ' + const objectRetentionXmlGovernance = '<Retention '
'xmlns="http://s3.amazonaws.com/doc/2006-03-01/">' + + 'xmlns="http://s3.amazonaws.com/doc/2006-03-01/">'
'<Mode>GOVERNANCE</Mode>' + + '<Mode>GOVERNANCE</Mode>'
`<RetainUntilDate>${expectedDate}</RetainUntilDate>` + + `<RetainUntilDate>${expectedDate}</RetainUntilDate>`
'</Retention>'; + '</Retention>';
const objectRetentionXmlCompliance = '<Retention ' + const objectRetentionXmlCompliance = '<Retention '
'xmlns="http://s3.amazonaws.com/doc/2006-03-01/">' + + 'xmlns="http://s3.amazonaws.com/doc/2006-03-01/">'
'<Mode>COMPLIANCE</Mode>' + + '<Mode>COMPLIANCE</Mode>'
`<RetainUntilDate>${expectedDate}</RetainUntilDate>` + + `<RetainUntilDate>${expectedDate}</RetainUntilDate>`
'</Retention>'; + '</Retention>';
const objectRetentionXmlGovernanceLonger = '<Retention ' + const objectRetentionXmlGovernanceLonger = '<Retention '
'xmlns="http://s3.amazonaws.com/doc/2006-03-01/">' + + 'xmlns="http://s3.amazonaws.com/doc/2006-03-01/">'
'<Mode>GOVERNANCE</Mode>' + + '<Mode>GOVERNANCE</Mode>'
`<RetainUntilDate>${moment().add(5, 'days').toISOString()}</RetainUntilDate>` + + `<RetainUntilDate>${moment().add(5, 'days').toISOString()}</RetainUntilDate>`
'</Retention>'; + '</Retention>';
const objectRetentionXmlGovernanceShorter = '<Retention ' + const objectRetentionXmlGovernanceShorter = '<Retention '
'xmlns="http://s3.amazonaws.com/doc/2006-03-01/">' + + 'xmlns="http://s3.amazonaws.com/doc/2006-03-01/">'
'<Mode>GOVERNANCE</Mode>' + + '<Mode>GOVERNANCE</Mode>'
`<RetainUntilDate>${moment().add(1, 'days').toISOString()}</RetainUntilDate>` + + `<RetainUntilDate>${moment().add(1, 'days').toISOString()}</RetainUntilDate>`
'</Retention>'; + '</Retention>';
const objectRetentionXmlComplianceShorter = '<Retention ' + const objectRetentionXmlComplianceShorter = '<Retention '
'xmlns="http://s3.amazonaws.com/doc/2006-03-01/">' + + 'xmlns="http://s3.amazonaws.com/doc/2006-03-01/">'
'<Mode>COMPLIANCE</Mode>' + + '<Mode>COMPLIANCE</Mode>'
`<RetainUntilDate>${moment().add(1, 'days').toISOString()}</RetainUntilDate>` + + `<RetainUntilDate>${moment().add(1, 'days').toISOString()}</RetainUntilDate>`
'</Retention>'; + '</Retention>';
const putObjRetRequestGovernance = { const putObjRetRequestGovernance = {
bucketName, bucketName,
objectKey: objectName, objectKey: objectName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
post: objectRetentionXmlGovernance, post: objectRetentionXmlGovernance,
actionImplicitDenies: false,
}; };
const putObjRetRequestGovernanceWithHeader = { const putObjRetRequestGovernanceWithHeader = {
@ -78,6 +80,7 @@ const putObjRetRequestGovernanceWithHeader = {
'x-amz-bypass-governance-retention': 'true', 'x-amz-bypass-governance-retention': 'true',
}, },
post: objectRetentionXmlGovernance, post: objectRetentionXmlGovernance,
actionImplicitDenies: false,
}; };
const putObjRetRequestCompliance = { const putObjRetRequestCompliance = {
@ -85,6 +88,7 @@ const putObjRetRequestCompliance = {
objectKey: objectName, objectKey: objectName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
post: objectRetentionXmlCompliance, post: objectRetentionXmlCompliance,
actionImplicitDenies: false,
}; };
const putObjRetRequestComplianceShorter = { const putObjRetRequestComplianceShorter = {
@ -92,6 +96,7 @@ const putObjRetRequestComplianceShorter = {
objectKey: objectName, objectKey: objectName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
post: objectRetentionXmlComplianceShorter, post: objectRetentionXmlComplianceShorter,
actionImplicitDenies: false,
}; };
const putObjRetRequestGovernanceLonger = { const putObjRetRequestGovernanceLonger = {
@ -99,6 +104,7 @@ const putObjRetRequestGovernanceLonger = {
objectKey: objectName, objectKey: objectName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
post: objectRetentionXmlGovernanceLonger, post: objectRetentionXmlGovernanceLonger,
actionImplicitDenies: false,
}; };
const putObjRetRequestGovernanceShorter = { const putObjRetRequestGovernanceShorter = {
@ -106,6 +112,7 @@ const putObjRetRequestGovernanceShorter = {
objectKey: objectName, objectKey: objectName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
post: objectRetentionXmlGovernanceShorter, post: objectRetentionXmlGovernanceShorter,
actionImplicitDenies: false,
}; };
describe('putObjectRetention API', () => { describe('putObjectRetention API', () => {

View File

@ -3,16 +3,15 @@ const assert = require('assert');
const { bucketPut } = require('../../../lib/api/bucketPut'); const { bucketPut } = require('../../../lib/api/bucketPut');
const objectPut = require('../../../lib/api/objectPut'); const objectPut = require('../../../lib/api/objectPut');
const objectPutTagging = require('../../../lib/api/objectPutTagging'); const objectPutTagging = require('../../../lib/api/objectPutTagging');
const { _validator, parseTagXml } const { _validator, parseTagXml } = require('arsenal').s3middleware.tagging;
= require('arsenal').s3middleware.tagging; const {
const { cleanup, cleanup,
DummyRequestLogger, DummyRequestLogger,
makeAuthInfo, makeAuthInfo,
TaggingConfigTester } TaggingConfigTester,
= require('../helpers'); } = require('../helpers');
const metadata = require('../../../lib/metadata/wrapper'); const metadata = require('../../../lib/metadata/wrapper');
const { taggingTests } const { taggingTests } = require('../../functional/aws-node-sdk/lib/utility/tagging.js');
= require('../../functional/aws-node-sdk/lib/utility/tagging.js');
const DummyRequest = require('../DummyRequest'); const DummyRequest = require('../DummyRequest');
const log = new DummyRequestLogger(); const log = new DummyRequestLogger();
@ -25,6 +24,7 @@ const testBucketPutRequest = {
bucketName, bucketName,
headers: { host: `${bucketName}.s3.amazonaws.com` }, headers: { host: `${bucketName}.s3.amazonaws.com` },
url: '/', url: '/',
actionImplicitDenies: false,
}; };
const testPutObjectRequest = new DummyRequest({ const testPutObjectRequest = new DummyRequest({
@ -42,14 +42,14 @@ function _checkError(err, code, errorName) {
} }
function _generateSampleXml(key, value) { function _generateSampleXml(key, value) {
const xml = '<Tagging>' + const xml = '<Tagging>'
'<TagSet>' + + '<TagSet>'
'<Tag>' + + '<Tag>'
`<Key>${key}</Key>` + + `<Key>${key}</Key>`
`<Value>${value}</Value>` + + `<Value>${value}</Value>`
'</Tag>' + + '</Tag>'
'</TagSet>' + + '</TagSet>'
'</Tagging>'; + '</Tagging>';
return xml; return xml;
} }
@ -101,12 +101,18 @@ describe('PUT object tagging :: helper validation functions ', () => {
{ tagTest: { Key: ['foo'] }, isValid: false }, { tagTest: { Key: ['foo'] }, isValid: false },
{ tagTest: { Value: ['bar'] }, isValid: false }, { tagTest: { Value: ['bar'] }, isValid: false },
{ tagTest: { Keys: ['foo'], Value: ['bar'] }, isValid: false }, { tagTest: { Keys: ['foo'], Value: ['bar'] }, isValid: false },
{ tagTest: { Key: ['foo', 'boo'], Value: ['bar'] }, {
isValid: false }, tagTest: { Key: ['foo', 'boo'], Value: ['bar'] },
{ tagTest: { Key: ['foo'], Value: ['bar', 'boo'] }, isValid: false,
isValid: false }, },
{ tagTest: { Key: ['foo', 'boo'], Value: ['bar', 'boo'] }, {
isValid: false }, tagTest: { Key: ['foo'], Value: ['bar', 'boo'] },
isValid: false,
},
{
tagTest: { Key: ['foo', 'boo'], Value: ['bar', 'boo'] },
isValid: false,
},
{ tagTest: { Key: ['foo'], Values: ['bar'] }, isValid: false }, { tagTest: { Key: ['foo'], Values: ['bar'] }, isValid: false },
{ tagTest: { Keys: ['foo'], Values: ['bar'] }, isValid: false }, { tagTest: { Keys: ['foo'], Values: ['bar'] }, isValid: false },
]; ];
@ -124,26 +130,66 @@ describe('PUT object tagging :: helper validation functions ', () => {
}); });
describe('validateXMLStructure ', () => { describe('validateXMLStructure ', () => {
it('should return expected true if tag is valid false/undefined ' + it('should return expected true if tag is valid false/undefined '
'if not', done => { + 'if not', done => {
const tags = [ const tags = [
{ tagging: { Tagging: { TagSet: [{ Tag: [] }] } }, isValid: {
true }, tagging: { Tagging: { TagSet: [{ Tag: [] }] } },
isValid:
true,
},
{ tagging: { Tagging: { TagSet: [''] } }, isValid: true }, { tagging: { Tagging: { TagSet: [''] } }, isValid: true },
{ tagging: { Tagging: { TagSet: [] } }, isValid: false }, { tagging: { Tagging: { TagSet: [] } }, isValid: false },
{ tagging: { Tagging: { TagSet: [{}] } }, isValid: false }, { tagging: { Tagging: { TagSet: [{}] } }, isValid: false },
{ tagging: { Tagging: { Tagset: [{ Tag: [] }] } }, isValid: {
false }, tagging: { Tagging: { Tagset: [{ Tag: [] }] } },
{ tagging: { Tagging: { Tagset: [{ Tag: [] }] }, isValid:
ExtraTagging: 'extratagging' }, isValid: false }, false,
{ tagging: { Tagging: { Tagset: [{ Tag: [] }], ExtraTagset: },
'extratagset' } }, isValid: false }, {
{ tagging: { Tagging: { Tagset: [{ Tag: [] }], ExtraTagset: tagging: {
'extratagset' } }, isValid: false }, Tagging: { Tagset: [{ Tag: [] }] },
{ tagging: { Tagging: { Tagset: [{ Tag: [], ExtraTag: ExtraTagging: 'extratagging',
'extratag' }] } }, isValid: false }, },
{ tagging: { Tagging: { Tagset: [{ Tag: {} }] } }, isValid: isValid: false,
false }, },
{
tagging: {
Tagging: {
Tagset: [{ Tag: [] }],
ExtraTagset:
'extratagset',
},
},
isValid: false,
},
{
tagging: {
Tagging: {
Tagset: [{ Tag: [] }],
ExtraTagset:
'extratagset',
},
},
isValid: false,
},
{
tagging: {
Tagging: {
Tagset: [{
Tag: [],
ExtraTag:
'extratag',
}],
},
},
isValid: false,
},
{
tagging: { Tagging: { Tagset: [{ Tag: {} }] } },
isValid:
false,
},
]; ];
for (let i = 0; i < tags.length; i++) { for (let i = 0; i < tags.length; i++) {
@ -172,8 +218,8 @@ describe('PUT object tagging :: helper validation functions ', () => {
taggingTests.forEach(taggingTest => { taggingTests.forEach(taggingTest => {
it(taggingTest.it, done => { it(taggingTest.it, done => {
const key = taggingTest.tag.key; const { key } = taggingTest.tag;
const value = taggingTest.tag.value; const { value } = taggingTest.tag;
const xml = _generateSampleXml(key, value); const xml = _generateSampleXml(key, value);
parseTagXml(xml, log, (err, result) => { parseTagXml(xml, log, (err, result) => {
if (taggingTest.error) { if (taggingTest.error) {

View File

@ -340,6 +340,7 @@ class CorsConfigTester {
}, },
url: '/?cors', url: '/?cors',
query: { cors: '' }, query: { cors: '' },
actionImplicitDenies: false,
}; };
if (method === 'PUT') { if (method === 'PUT') {
request.post = body || this.constructXml(); request.post = body || this.constructXml();
@ -381,6 +382,7 @@ const versioningTestUtils = {
}, },
url: '/?versioning', url: '/?versioning',
query: { versioning: '' }, query: { versioning: '' },
actionImplicitDenies: false,
}; };
const xml = '<VersioningConfiguration ' + const xml = '<VersioningConfiguration ' +
'xmlns="http://s3.amazonaws.com/doc/2006-03-01/">' + 'xmlns="http://s3.amazonaws.com/doc/2006-03-01/">' +
@ -431,6 +433,7 @@ class TaggingConfigTester {
objectKey: objectName, objectKey: objectName,
url: '/?tagging', url: '/?tagging',
query: { tagging: '' }, query: { tagging: '' },
actionImplicitDenies: false,
}; };
if (method === 'PUT') { if (method === 'PUT') {
request.post = body || this.constructXml(); request.post = body || this.constructXml();

View File

@ -0,0 +1,55 @@
const assert = require('assert');
const { models } = require('arsenal');
const { BucketInfo } = models;
const { DummyRequestLogger, makeAuthInfo } = require('../helpers');
const creationDate = new Date().toJSON();
const authInfo = makeAuthInfo('accessKey');
const otherAuthInfo = makeAuthInfo('otherAccessKey');
const ownerCanonicalId = authInfo.getCanonicalID();
const bucket = new BucketInfo('niftyBucket', ownerCanonicalId,
authInfo.getAccountDisplayName(), creationDate);
const log = new DummyRequestLogger();
const { validateBucket } = require('../../../lib/metadata/metadataUtils');
describe('validateBucket', () => {
it('action bucketPutPolicy by bucket owner', () => {
const validationResult = validateBucket(bucket, {
authInfo,
requestType: 'bucketPutPolicy',
request: null,
}, log, false);
assert.ifError(validationResult);
});
it('action bucketPutPolicy by other than bucket owner', () => {
const validationResult = validateBucket(bucket, {
authInfo: otherAuthInfo,
requestType: 'bucketPutPolicy',
request: null,
}, log, false);
assert(validationResult);
assert(validationResult.is.MethodNotAllowed);
});
it('action bucketGet by bucket owner', () => {
const validationResult = validateBucket(bucket, {
authInfo,
requestType: 'bucketGet',
request: null,
}, log, false);
assert.ifError(validationResult);
});
it('action bucketGet by other than bucket owner', () => {
const validationResult = validateBucket(bucket, {
authInfo: otherAuthInfo,
requestType: 'bucketGet',
request: null,
}, log, false);
assert(validationResult);
assert(validationResult.is.AccessDenied);
});
});