Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions lib/api/initiateMultipartUpload.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const getMetaHeaders = s3middleware.userMetadata.getMetaHeaders;
const convertToXml = s3middleware.convertToXml;
const { pushMetric } = require('../utapi/utilities');
const collectCorsHeaders = require('../utilities/collectCorsHeaders');
const aclUtils = require('../utilities/aclUtils');
const { hasNonPrintables } = require('../utilities/stringChecks');
const { cleanUpBucket } = require('./apiUtils/bucket/bucketCreation');
const constants = require('../../constants');
Expand Down Expand Up @@ -88,6 +89,11 @@ function initiateMultipartUpload(authInfo, request, log, callback) {
log.debug(`invalid x-amz-website-redirect-location value ${websiteRedirectHeader}`, { error: err });
return callback(err);
}
if (!aclUtils.checkGrantHeaderValidity(request.headers)) {
log.trace('invalid acl header');
monitoring.promMetrics('PUT', bucketName, 400, 'initiateMultipartUpload');
return callback(errors.InvalidArgument);
}
const checksumConfig = areChecksumsEnabled() ? getChecksumDataFromMPUHeaders(request.headers) : null;
if (checksumConfig && checksumConfig.error) {
const checksumErr = arsenalErrorFromChecksumError(checksumConfig);
Expand Down
8 changes: 8 additions & 0 deletions lib/api/objectCopy.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const validateHeaders = s3middleware.validateConditionalHeaders;

const constants = require('../../constants');
const collectCorsHeaders = require('../utilities/collectCorsHeaders');
const aclUtils = require('../utilities/aclUtils');
const locationConstraintCheck = require('./apiUtils/object/locationConstraintCheck');
const { checkQueryVersionId, versioningPreprocessing, decodeVID } = require('./apiUtils/object/versioning');
const getReplicationInfo = require('./apiUtils/object/getReplicationInfo');
Expand Down Expand Up @@ -569,6 +570,13 @@ function objectCopy(authInfo, request, sourceBucket, sourceObject, sourceVersion
monitoring.promMetrics('PUT', destBucketName, err.code, 'copyObject');
return callback(err);
}
// We check the grant headers before we copy the data. The ACL is parsed
// only when we store the metadata, after the copy.
if (!aclUtils.checkGrantHeaderValidity(request.headers)) {
log.trace('invalid acl header');
monitoring.promMetrics('PUT', destBucketName, 400, 'copyObject');
return callback(errors.InvalidArgument);
}
const { error: checksumAlgoErr, algorithm: requestedAlgo } = areChecksumsEnabled()
? getCopyObjectChecksumAlgorithm(request.headers)
: { error: null, algorithm: null };
Expand Down
4 changes: 4 additions & 0 deletions lib/metadata/acl.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,10 @@ const acl = {
return cb(errors.InvalidArgument);
}

if (!aclUtils.checkGrantHeaderValidity(headers)) {
return cb(errors.InvalidArgument);
}

// parse grant headers
const grantReadHeader = aclUtils.parseGrant(headers['x-amz-grant-read'], 'READ');
let grantWriteHeader = [];
Expand Down
65 changes: 43 additions & 22 deletions lib/utilities/aclUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,27 +165,48 @@ aclUtils.getPermissionType = function getPermissionType(identifier, resourceACL,
return permission;
};

/**
* splitGrant - splits one grant of an x-amz-grant-* header into its type and
* its identifier, and removes the quotes around the identifier.
* Example: 'uri="http://acs.amazonaws.com/groups/global/AllUsers"' gives
* { userIDType: 'uri', identifier: 'http://acs.amazonaws.com/groups/global/AllUsers' }.
* We return null when the grant is not one type=identifier pair.
* Example: 'x', '' or 'id=a=b'.
* @param {string} grant - one grant, as found between the commas of the header
* @returns {object|null} the type and the identifier, or null if malformed
*/
function splitGrant(grant) {
const parts = grant.split('=');
if (parts.length !== 2) {
return null;
}
const userIDType = parts[0].trim();
let identifier = parts[1].trim();
if (identifier.length >= 2 && identifier.startsWith('"') && identifier.endsWith('"')) {
identifier = identifier.slice(1, -1);
}
// AWS accepts a canonical id in upper case and stores it in lower case.
// The permission checks compare ids in lower case, so we do the same.
if (userIDType.toLowerCase() === 'id') {
identifier = identifier.toLowerCase();
}
return { userIDType, identifier };
}

aclUtils.parseGrant = function parseGrant(grantHeader, grantType) {
if (grantHeader === undefined) {
// AWS ignores an empty grant header, so we treat it as a missing one.
if (grantHeader === undefined || grantHeader === '') {
return undefined;
}
const grantArray = grantHeader.split(',');
let itemArray;
let userIDType;
let identifier;
return grantArray.map(item => {
itemArray = item.split('=');
userIDType = itemArray[0].trim();
identifier = itemArray[1].trim();
if (identifier[0] === '"') {
identifier = identifier.substr(1, identifier.length - 2);
}
return {
userIDType,
identifier,
grantType,
};
});
// We skip a malformed grant instead of throwing: some APIs parse the
// headers before they check them, and a throw there kills the worker.
// checkGrantHeaderValidity refuses the request later, so a skipped grant
// is never stored.
return grantHeader
.split(',')
.map(splitGrant)
.filter(grant => grant !== null)
.map(({ userIDType, identifier }) => ({ userIDType, identifier, grantType }));
};

aclUtils.isValidCanonicalId = function isValidCanonicalId(canonicalID) {
Expand Down Expand Up @@ -282,12 +303,12 @@ aclUtils.checkGrantHeaderValidity = function checkGrantHeaderValidity(headers) {
if (grantHeader) {
const grantHeaderArr = grantHeader.split(',');
for (let j = 0; j < grantHeaderArr.length; j++) {
const singleGrantArr = grantHeaderArr[j].split('=');
if (singleGrantArr.length !== 2) {
const grant = splitGrant(grantHeaderArr[j]);
if (grant === null) {
return false;
}
const identifier = singleGrantArr[0].trim().toLowerCase();
const value = singleGrantArr[1].trim();
const identifier = grant.userIDType.toLowerCase();
const value = grant.identifier;
if (identifier === 'uri') {
if (
value !== constants.publicId &&
Expand Down
128 changes: 128 additions & 0 deletions tests/functional/raw-node/test/aclGrantHeaders.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
const assert = require('assert');

const { makeS3Request } = require('../utils/makeRequest');

const authCredentials = {
accessKey: 'accessKey1',
secretKey: 'verySecretKey1',
};
const bucket = 'rawnode-acl-grant-headers';
const allUsers = 'http://acs.amazonaws.com/groups/global/AllUsers';
// The canonical id of accessKey2.
const otherId = '79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2bf';

// We use raw requests because an SDK refuses to send most of these headers.
// A worker that crashes closes the socket, so the request fails with no
// status code.
function request(params) {
const headers = { 'content-length': Buffer.byteLength(params.requestBody || ''), ...params.headers };
return new Promise(resolve => {
makeS3Request({ authCredentials, bucket, ...params, headers }, (err, res) => resolve({ err, res }));
});
}

function assertError({ err, res }, statusCode, code) {
assert(res, `expected a ${statusCode} ${code}, got ${err && err.message}`);
assert.strictEqual(res.statusCode, statusCode);
assert.strictEqual(err && err.code, code);
}

function assertOk({ err, res }) {
assert(res, `expected a 200, got ${err && err.message}`);
assert.strictEqual(res.statusCode, 200, err && err.code);
}

const apis = [
{ name: 'PutBucketAcl', params: { method: 'PUT', queryObj: { acl: '' } } },
{ name: 'PutObject', params: { method: 'PUT', objectKey: 'put' } },
{ name: 'PutObjectAcl', params: { method: 'PUT', objectKey: 'src', queryObj: { acl: '' } } },
{
name: 'CopyObject',
params: { method: 'PUT', objectKey: 'copy', headers: { 'x-amz-copy-source': `/${bucket}/src` } },
},
{ name: 'CreateMultipartUpload', params: { method: 'POST', objectKey: 'mpu', queryObj: { uploads: '' } } },
];

function withGrant(params, value) {
return { ...params, headers: { ...params.headers, 'x-amz-grant-read': value } };
}

describe('grant headers that are not type=identifier pairs', () => {
before(async () => {
assertOk(await request({ method: 'PUT' }));
assertOk(await request({ method: 'PUT', objectKey: 'src', requestBody: 'body' }));
});

after(async () => {
const list = await request({ method: 'GET', queryObj: { uploads: '' } });
const uploads = [...list.res.body.matchAll(/<Key>([^<]*)<\/Key><UploadId>([^<]*)<\/UploadId>/g)];
for (const [, key, uploadId] of uploads) {
await request({ method: 'DELETE', objectKey: key, queryObj: { uploadId } });
}
for (const key of ['src', 'put', 'copy']) {
await request({ method: 'DELETE', objectKey: key });
}
await request({ method: 'DELETE' });
});

const malformed = {
'no equal sign': 'x',
'two equal signs': 'id=a=b',
'a trailing comma': `uri=${allUsers},`,
};
Object.entries(malformed).forEach(([name, value]) => {
apis.forEach(api => {
it(`should return InvalidArgument on ${api.name} for a grant with ${name}`, async () => {
assertError(await request(withGrant(api.params, value)), 400, 'InvalidArgument');
});
});

it(`should answer an anonymous PutBucketAcl with ${name} on a missing bucket`, async () => {
const result = await new Promise(resolve => {
makeS3Request(
{
method: 'PUT',
bucket: 'rawnode-acl-grant-headers-missing',
queryObj: { acl: '' },
headers: { 'x-amz-grant-read': value },
},
(err, res) => resolve({ err, res }),
);
});
assert(result.res, `expected an error response, got ${result.err && result.err.message}`);
assert(result.res.statusCode >= 400 && result.res.statusCode < 500, `${result.res.statusCode}`);
});
});

['CopyObject', 'CreateMultipartUpload'].forEach(name => {
it(`should return InvalidArgument on ${name} for a grant to id=123`, async () => {
const api = apis.find(a => a.name === name);
assertError(await request(withGrant(api.params, 'id=123')), 400, 'InvalidArgument');
});
});

it('should ignore an empty grant header on PutObject', async () => {
assertOk(await request(withGrant(apis[1].params, '')));
});

// An empty header is no ACL at all, so PutObjectAcl has nothing to apply.
it('should return MalformedXML on PutObjectAcl with only an empty grant header', async () => {
assertError(await request(withGrant(apis[2].params, '')), 400, 'MalformedXML');
});

it('should accept a quoted identifier on PutObject', async () => {
assertOk(await request(withGrant(apis[1].params, `uri="${allUsers}"`)));
});

apis.forEach(api => {
it(`should accept a canonical id in upper case on ${api.name}`, async () => {
assertOk(await request(withGrant(api.params, `id=${otherId.toUpperCase()}`)));
});
});

it('should store a canonical id given in upper case in lower case on CopyObject', async () => {
assertOk(await request(withGrant(apis[3].params, `id=${otherId.toUpperCase()}`)));
const { res } = await request({ method: 'GET', objectKey: 'copy', queryObj: { acl: '' } });
assert(res.body.includes(`<ID>${otherId}</ID>`), res.body);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Prefer assert.match over includes so a failure shows the body and the expected pattern.

Suggested change
assert(res.body.includes(`<ID>${otherId}</ID>`), res.body);
assert.match(res.body, new RegExp(`<ID>${otherId}</ID>`));

});
});
Loading
Loading