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
44 changes: 5 additions & 39 deletions lib/api/bucketPutACL.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,53 +139,19 @@ function bucketPutACL(authInfo, request, log, callback) {
let usersIdentifiedByEmail = [];
let usersIdentifiedByGroup = [];
let usersIdentifiedByID = [];
let hasError = false;
/**
* If grants set by xml, loop through the grants
* and separate grant types so parsed in same manner
* as header grants
*/
if (jsonGrants) {
log.trace('parsing acl grants');
jsonGrants.forEach(grant => {
const grantee = grant.Grantee[0];
const granteeType = grantee.$['xsi:type'];
const permission = grant.Permission[0];
let skip = false;
if (possibleGrants.indexOf(permission) < 0) {
skip = true;
}
if (!skip && granteeType === 'AmazonCustomerByEmail') {
usersIdentifiedByEmail.push({
identifier: grantee.EmailAddress[0],
grantType: permission,
userIDType: 'emailaddress',
});
}
if (!skip && granteeType === 'CanonicalUser') {
usersIdentifiedByID.push({
identifier: grantee.ID[0],
grantType: permission,
userIDType: 'id',
});
}
if (!skip && granteeType === 'Group') {
if (possibleGroups.indexOf(grantee.URI[0]) < 0) {
log.trace('invalid user group', { userGroup: grantee.URI[0] });
hasError = true;
return next(errors.InvalidArgument, bucket);
}
return usersIdentifiedByGroup.push({
identifier: grantee.URI[0],
grantType: permission,
userIDType: 'uri',
});
}
return undefined;
});
if (hasError) {
return undefined;
const parsedGrants = aclUtils.parseGrantsFromXml(jsonGrants, possibleGrants, possibleGroups);
if (parsedGrants.error) {
log.trace('invalid acl grant', { error: parsedGrants.error, method: 'bucketPutACL' });
return next(parsedGrants.error, bucket);
}
({ usersIdentifiedByEmail, usersIdentifiedByID, usersIdentifiedByGroup } = parsedGrants);
} else {
// If no canned ACL and no parsed xml, loop
// through the access headers
Expand Down
44 changes: 5 additions & 39 deletions lib/api/objectPutACL.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,6 @@ function objectPutACL(authInfo, request, log, cb) {
let usersIdentifiedByEmail = [];
let usersIdentifiedByGroup = [];
let usersIdentifiedByID = [];
let hasError = false;

// If grants set by xml and xml owner ID is incorrect
if (aclOwnerID && aclOwnerID !== objectMD['owner-id']) {
Expand All @@ -183,45 +182,12 @@ function objectPutACL(authInfo, request, log, cb) {
*/
if (jsonGrants) {
log.trace('parsing acl grants');
jsonGrants.forEach(grant => {
const grantee = grant.Grantee[0];
const granteeType = grantee.$['xsi:type'];
const permission = grant.Permission[0];
let skip = false;
if (possibleGrants.indexOf(permission) < 0) {
skip = true;
}
if (!skip && granteeType === 'AmazonCustomerByEmail') {
usersIdentifiedByEmail.push({
identifier: grantee.EmailAddress[0],
grantType: permission,
userIDType: 'emailaddress',
});
}
if (!skip && granteeType === 'CanonicalUser') {
usersIdentifiedByID.push({
identifier: grantee.ID[0],
grantType: permission,
userIDType: 'id',
});
}
if (!skip && granteeType === 'Group') {
if (possibleGroups.indexOf(grantee.URI[0]) < 0) {
log.trace('invalid user group', { userGroup: grantee.URI[0] });
hasError = true;
return next(errors.InvalidArgument, bucket);
}
return usersIdentifiedByGroup.push({
identifier: grantee.URI[0],
grantType: permission,
userIDType: 'uri',
});
}
return undefined;
});
if (hasError) {
return undefined;
const parsedGrants = aclUtils.parseGrantsFromXml(jsonGrants, possibleGrants, possibleGroups);
if (parsedGrants.error) {
log.trace('invalid acl grant', { error: parsedGrants.error, method: 'objectPutACL' });
return next(parsedGrants.error, bucket);
}
({ usersIdentifiedByEmail, usersIdentifiedByID, usersIdentifiedByGroup } = parsedGrants);
} else {
// If no canned ACL and no parsed xml, loop
// through the access headers
Expand Down
76 changes: 76 additions & 0 deletions lib/utilities/aclUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,82 @@ aclUtils.parseAclXml = function parseAclXml(toBeParsed, log, next) {
});
};

// The element that holds the identifier, for each grantee type of the S3 ACL
// schema.
const xmlGranteeElements = {
AmazonCustomerByEmail: 'EmailAddress',
CanonicalUser: 'ID',
Group: 'URI',
};
const allPermissions = ['FULL_CONTROL', 'WRITE', 'WRITE_ACP', 'READ', 'READ_ACP'];

/**
* firstText - reads the text of an element that xml2js parsed.
* Example: <ID>79a5...</ID> gives ['79a5...'], so we return '79a5...'.
* We return undefined when the element is missing, or when it is not plain
* text. Example: <ID a="b">79a5...</ID> gives [{ _: '79a5...', $: { a: 'b' } }].
* @param {array} [element] - the element, as xml2js returns it
* @returns {string|undefined} its text
*/
function firstText(element) {
if (!Array.isArray(element) || typeof element[0] !== 'string') {
return undefined;
}
return element[0];
}

/**
* parseGrantsFromXml - sorts the grants of an ACL XML body by grantee type,
* like we do for the grant headers.
* Example: one grant <Grantee xsi:type="Group"><URI>http://acs.amazonaws.com/groups/global/AllUsers</URI>
* </Grantee><Permission>READ</Permission> gives
* usersIdentifiedByGroup [{ identifier: 'http://acs.amazonaws.com/groups/global/AllUsers',
* grantType: 'READ', userIDType: 'uri' }].
* The body comes from the client, so any element can be missing. We check each
* one before we read it, and we stop at the first bad grant.
* @param {array} jsonGrants - the grants, as parseAclXml returns them
* @param {string[]} possibleGrants - the permissions of the resource type
* @param {string[]} possibleGroups - the group URIs we accept
* @returns {object} { error } for a bad grant, or the grants sorted in
* usersIdentifiedByEmail, usersIdentifiedByID and usersIdentifiedByGroup
*/
aclUtils.parseGrantsFromXml = function parseGrantsFromXml(jsonGrants, possibleGrants, possibleGroups) {
const usersIdentifiedByEmail = [];
const usersIdentifiedByID = [];
const usersIdentifiedByGroup = [];
for (const grant of jsonGrants) {
const grantee = grant && Array.isArray(grant.Grantee) ? grant.Grantee[0] : undefined;
const granteeType = grantee && grantee.$ ? grantee.$['xsi:type'] : undefined;
const permission = grant ? firstText(grant.Permission) : undefined;
// The S3 ACL schema has these three grantee types and these five
// permissions. AWS returns MalformedACLError for any other one.
if (!Object.hasOwn(xmlGranteeElements, granteeType) || !allPermissions.includes(permission)) {
return { error: errors.MalformedACLError };
}
const identifier = firstText(grantee[xmlGranteeElements[granteeType]]);
if (identifier === undefined) {
return { error: errors.MalformedACLError };
}
if (granteeType === 'Group' && !possibleGroups.includes(identifier)) {
return { error: errors.InvalidArgument };
}
// We ignore a permission the resource doesn't have. Example: WRITE in
// an object ACL. We check the grant first, so a malformed grant is
// refused even then.
if (possibleGrants.includes(permission)) {
const user = { identifier, grantType: permission };
if (granteeType === 'AmazonCustomerByEmail') {
usersIdentifiedByEmail.push({ ...user, userIDType: 'emailaddress' });
} else if (granteeType === 'CanonicalUser') {
usersIdentifiedByID.push({ ...user, userIDType: 'id' });
} else {
usersIdentifiedByGroup.push({ ...user, userIDType: 'uri' });
}
}
}
return { usersIdentifiedByEmail, usersIdentifiedByID, usersIdentifiedByGroup };
};

aclUtils.getPermissionType = function getPermissionType(identifier, resourceACL, resourceType) {
const fullControlIndex = resourceACL.FULL_CONTROL.indexOf(identifier);
let writeIndex;
Expand Down
106 changes: 106 additions & 0 deletions tests/functional/raw-node/test/aclXmlGrants.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
const assert = require('assert');

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

const authCredentials = {
accessKey: 'accessKey1',
secretKey: 'verySecretKey1',
};
const ownerId = '79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2be';
const bucket = 'rawnode-acl-xml-grants';
const objectKey = 'src';
const allUsers = 'http://acs.amazonaws.com/groups/global/AllUsers';
const xsi = 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"';

// We use raw requests so the XML body reaches the server as we wrote it. 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);
}

function aclXml(grants) {
return (
'<AccessControlPolicy>' +
`<Owner><ID>${ownerId}</ID></Owner>` +
`<AccessControlList>${grants}</AccessControlList>` +
'</AccessControlPolicy>'
);
}

function groupGrant(uri) {
return `<Grant><Grantee ${xsi} xsi:type="Group"><URI>${uri}</URI></Grantee><Permission>READ</Permission></Grant>`;
}

const apis = [
{ name: 'PutBucketAcl', params: { queryObj: { acl: '' } } },
{ name: 'PutObjectAcl', params: { objectKey, queryObj: { acl: '' } } },
];

// AWS returns MalformedACLError for each grant below.
const missingElements = {
'a Grant without Grantee': '<Grant><Permission>READ</Permission></Grant>',
'a Grant without Permission': `<Grant><Grantee ${xsi} xsi:type="CanonicalUser"><ID>${ownerId}</ID></Grantee></Grant>`,
'a CanonicalUser without ID': `<Grant><Grantee ${xsi} xsi:type="CanonicalUser"></Grantee><Permission>READ</Permission></Grant>`,
'a Group without URI': `<Grant><Grantee ${xsi} xsi:type="Group"></Grantee><Permission>READ</Permission></Grant>`,
};

const outsideSchema = {
'an unknown grantee type': `<Grant><Grantee ${xsi} xsi:type="Bogus"><ID>${ownerId}</ID></Grantee><Permission>READ</Permission></Grant>`,
'the grantee type __proto__': `<Grant><Grantee ${xsi} xsi:type="__proto__"><ID>${ownerId}</ID></Grantee><Permission>READ</Permission></Grant>`,
'an unknown permission': `<Grant><Grantee ${xsi} xsi:type="CanonicalUser"><ID>${ownerId}</ID></Grantee><Permission>BOGUS</Permission></Grant>`,
};

describe('ACL XML bodies with bad grants', () => {
before(async () => {
assertOk(await request({ method: 'PUT' }));
assertOk(await request({ method: 'PUT', objectKey, requestBody: 'body' }));
});

after(async () => {
await request({ method: 'DELETE', objectKey });
await request({ method: 'DELETE' });
});

apis.forEach(api => {
describe(api.name, () => {
// Every case starts from an ACL with one AllUsers READ grant, so we
// can check that a refused request leaves it as it was.
beforeEach(async () => {
assertOk(await request({ ...api.params, method: 'PUT', requestBody: aclXml(groupGrant(allUsers)) }));
});

afterEach(async () => {
const { res } = await request({ ...api.params, method: 'GET' });
assert(res.body.includes(`<URI>${allUsers}</URI>`), 'the ACL changed');

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 actual body.

Suggested change
assert(res.body.includes(`<URI>${allUsers}</URI>`), 'the ACL changed');
assert.match(res.body, new RegExp(`<URI>${allUsers}</URI>`), 'the ACL changed');

});

Object.entries({ ...missingElements, ...outsideSchema }).forEach(([name, grant]) => {
it(`should return MalformedACLError for ${name}`, async () => {
const result = await request({ ...api.params, method: 'PUT', requestBody: aclXml(grant) });
assertError(result, 400, 'MalformedACLError');
});
});

it('should return InvalidArgument once for two invalid group URIs', async () => {
const body = aclXml(groupGrant('http://bogus/1') + groupGrant('http://bogus/2'));
assertError(await request({ ...api.params, method: 'PUT', requestBody: body }), 400, 'InvalidArgument');
assertOk(await request({ method: 'GET' }));
});
});
});
});
Loading
Loading