diff --git a/lib/api/bucketPutACL.js b/lib/api/bucketPutACL.js
index 2a2134c6ef..f5ee30cc55 100644
--- a/lib/api/bucketPutACL.js
+++ b/lib/api/bucketPutACL.js
@@ -139,7 +139,6 @@ 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
@@ -147,45 +146,12 @@ function bucketPutACL(authInfo, request, log, callback) {
*/
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
diff --git a/lib/api/objectPutACL.js b/lib/api/objectPutACL.js
index a53c8314ce..03f28c7fb4 100644
--- a/lib/api/objectPutACL.js
+++ b/lib/api/objectPutACL.js
@@ -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']) {
@@ -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
diff --git a/lib/utilities/aclUtils.js b/lib/utilities/aclUtils.js
index 796a2129cc..d631d93b6e 100644
--- a/lib/utilities/aclUtils.js
+++ b/lib/utilities/aclUtils.js
@@ -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: 79a5... gives ['79a5...'], so we return '79a5...'.
+ * We return undefined when the element is missing, or when it is not plain
+ * text. Example: 79a5... 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 http://acs.amazonaws.com/groups/global/AllUsers
+ * READ 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;
diff --git a/tests/functional/raw-node/test/aclXmlGrants.js b/tests/functional/raw-node/test/aclXmlGrants.js
new file mode 100644
index 0000000000..42c560fd2b
--- /dev/null
+++ b/tests/functional/raw-node/test/aclXmlGrants.js
@@ -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 (
+ '' +
+ `${ownerId}` +
+ `${grants}` +
+ ''
+ );
+}
+
+function groupGrant(uri) {
+ return `${uri}READ`;
+}
+
+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': 'READ',
+ 'a Grant without Permission': `${ownerId}`,
+ 'a CanonicalUser without ID': `READ`,
+ 'a Group without URI': `READ`,
+};
+
+const outsideSchema = {
+ 'an unknown grantee type': `${ownerId}READ`,
+ 'the grantee type __proto__': `${ownerId}READ`,
+ 'an unknown permission': `${ownerId}BOGUS`,
+};
+
+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(`${allUsers}`), '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' }));
+ });
+ });
+ });
+});
diff --git a/tests/unit/api/aclXmlGrants.js b/tests/unit/api/aclXmlGrants.js
new file mode 100644
index 0000000000..13ddfd92d4
--- /dev/null
+++ b/tests/unit/api/aclXmlGrants.js
@@ -0,0 +1,127 @@
+const assert = require('assert');
+
+const { bucketPut } = require('../../../lib/api/bucketPut');
+const bucketPutACL = require('../../../lib/api/bucketPutACL');
+const objectPut = require('../../../lib/api/objectPut');
+const objectPutACL = require('../../../lib/api/objectPutACL');
+const metadata = require('../metadataswitch');
+const DummyRequest = require('../DummyRequest');
+const { cleanup, DummyRequestLogger, makeAuthInfo } = require('../helpers');
+
+const log = new DummyRequestLogger();
+const authInfo = makeAuthInfo('accessKey1');
+const ownerId = authInfo.getCanonicalID();
+const namespace = 'default';
+const bucketName = 'bucketname';
+const objectKey = 'objectname';
+const xsi = 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"';
+
+function aclXml(grants) {
+ return (
+ '' +
+ `${ownerId}` +
+ `${grants}` +
+ ''
+ );
+}
+
+function groupGrant(uri) {
+ return `${uri}READ`;
+}
+
+const malformedGrants = {
+ 'a Grant without Grantee': 'READ',
+ 'a Grant without Permission': `${ownerId}`,
+ 'a CanonicalUser without ID': `READ`,
+ 'a Group without URI': `READ`,
+ 'an unknown grantee type': `${ownerId}READ`,
+ 'the grantee type __proto__': `${ownerId}READ`,
+ 'an unknown permission': `${ownerId}BOGUS`,
+};
+
+function aclRequest(body, key) {
+ return new DummyRequest({
+ bucketName,
+ namespace,
+ objectKey: key,
+ headers: { host: `${bucketName}.s3.amazonaws.com` },
+ url: key ? `/${bucketName}/${key}?acl` : '/?acl',
+ query: { acl: '' },
+ post: body,
+ });
+}
+
+function getBucketReadAcl(cb) {
+ metadata.getBucket(bucketName, log, (err, bucket) => cb(err, bucket && bucket.getAcl().READ));
+}
+
+function getObjectReadAcl(cb) {
+ metadata.getObjectMD(bucketName, objectKey, {}, log, (err, md) => cb(err, md && md.acl.READ));
+}
+
+const apis = [
+ {
+ name: 'PutBucketAcl',
+ put: (body, cb) => bucketPutACL(authInfo, aclRequest(body), log, cb),
+ getReadAcl: getBucketReadAcl,
+ },
+ {
+ name: 'PutObjectAcl',
+ put: (body, cb) => objectPutACL(authInfo, aclRequest(body, objectKey), log, cb),
+ getReadAcl: getObjectReadAcl,
+ },
+];
+
+describe('ACL XML bodies with bad grants', () => {
+ beforeEach(done => {
+ cleanup();
+ const bucketRequest = new DummyRequest({
+ bucketName,
+ namespace,
+ headers: { host: `${bucketName}.s3.amazonaws.com` },
+ url: '/',
+ });
+ const objectRequest = new DummyRequest(
+ {
+ bucketName,
+ namespace,
+ objectKey,
+ headers: { host: `${bucketName}.s3.amazonaws.com` },
+ url: `/${bucketName}/${objectKey}`,
+ },
+ Buffer.from('body', 'utf8'),
+ );
+ bucketPut(authInfo, bucketRequest, log, err => {
+ if (err) {
+ return done(err);
+ }
+ return objectPut(authInfo, objectRequest, undefined, log, done);
+ });
+ });
+
+ after(() => cleanup());
+
+ apis.forEach(api => {
+ Object.entries(malformedGrants).forEach(([name, grant]) => {
+ it(`${api.name} returns MalformedACLError for ${name} and keeps the ACL`, done => {
+ api.put(aclXml(grant), err => {
+ assert(err && err.is.MalformedACLError, `expected MalformedACLError, got ${err}`);
+ api.getReadAcl((err, readAcl) => {
+ assert.ifError(err);
+ assert.deepStrictEqual(readAcl, []);
+ done();
+ });
+ });
+ });
+ });
+
+ it(`${api.name} answers once with InvalidArgument for two invalid group URIs`, done => {
+ const body = aclXml(groupGrant('http://bad/1') + groupGrant('http://bad/2'));
+ api.put(body, err => {
+ assert(err && err.is.InvalidArgument, `expected InvalidArgument, got ${err}`);
+ // Mocha fails the test if done is called twice.
+ setImmediate(done);
+ });
+ });
+ });
+});