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
15 changes: 15 additions & 0 deletions lib/api/objectPutACL.js
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,21 @@ function objectPutACL(authInfo, request, log, cb) {
item => item && item.userIDType.toLowerCase() === 'id',
);
}
// We accept only canonical ids, like PutBucketAcl. The permission
// checks read the ID http://acs.amazonaws.com/groups/global/AllUsers
// as the AllUsers group, so it would make the object public.
// AWS accepts a canonical id in upper case and stores it in lower
// case. An ID with attributes is an object, so we leave it as it is
// and the check below refuses it.
usersIdentifiedByID = usersIdentifiedByID.map(user =>
typeof user.identifier === 'string' ? { ...user, identifier: user.identifier.toLowerCase() } : user,
);
const invalidId = usersIdentifiedByID.find(user => !aclUtils.isValidCanonicalId(user.identifier));
if (invalidId) {
log.trace('invalid user id argument', { id: invalidId.identifier, method: 'objectPutACL' });
return next(errors.InvalidArgument, bucket);
}

const justEmails = usersIdentifiedByEmail.map(item => item.identifier);
// If have to lookup canonicalID's do that asynchronously
if (justEmails.length > 0) {
Expand Down
12 changes: 11 additions & 1 deletion lib/metadata/acl.js
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,14 @@ const acl = {
const grantReadACPHeader = aclUtils.parseGrant(headers['x-amz-grant-read-acp'], 'READ_ACP');
const grantWriteACPHeader = aclUtils.parseGrant(headers['x-amz-grant-write-acp'], 'WRITE_ACP');
const grantFullControlHeader = aclUtils.parseGrant(headers['x-amz-grant-full-control'], 'FULL_CONTROL');
// 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.
const allGrantHeaders = []
.concat(grantReadHeader, grantWriteHeader, grantReadACPHeader, grantWriteACPHeader, grantFullControlHeader)
.filter(item => item !== undefined);
.filter(item => item !== undefined)
.map(item =>
item.userIDType.toLowerCase() === 'id' ? { ...item, identifier: item.identifier.toLowerCase() } : item,
);
if (allGrantHeaders.length === 0) {
return cb(null, currentResourceACL);
}
Expand All @@ -160,6 +165,11 @@ const acl = {
}
}
const usersIdentifiedByID = allGrantHeaders.filter(item => item && item.userIDType.toLowerCase() === 'id');
// The permission checks read the id http://acs.amazonaws.com/groups/global/AllUsers
// as the AllUsers group, so we accept only canonical ids.
if (usersIdentifiedByID.some(user => !aclUtils.isValidCanonicalId(user.identifier))) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Upper-case canonical ids are handled differently by path. objectPutACL lowercases XML ids and accepts them (200, as the PR says AWS does). Here, header ids are not lowercased, so CopyObject/CreateMultipartUpload with x-amz-grant-read: id=<UPPERCASE canonical id> now return 400 where they returned 200 before. checkGrantHeaderValidity already rejects the same header on PutObject/PutObjectAcl. If AWS also accepts upper case in headers, lowercase identifier before this check, and in checkGrantHeaderValidity too. If it doesn't, say so in the PR so the difference is clearly on purpose.

return cb(errors.InvalidArgument);
}
// TODO: Consider whether want to verify with Vault
// whether canonicalID is associated with existing
// account before adding to ACL
Expand Down
127 changes: 127 additions & 0 deletions tests/functional/raw-node/test/aclCanonicalId.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
const assert = require('assert');

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

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

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 anonymousGet(key) {
return new Promise(resolve => {
makeS3Request({ method: 'GET', bucket, objectKey: key }, (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 canonicalUserAcl(id) {
return (
'<AccessControlPolicy>' +
`<Owner><ID>${ownerId}</ID></Owner>` +
'<AccessControlList><Grant>' +
'<Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="CanonicalUser">' +
`<ID>${id}</ID></Grantee><Permission>READ</Permission>` +
'</Grant></AccessControlList>' +
'</AccessControlPolicy>'
);
}

describe('grants to an id that is not a canonical id', () => {
before(async () => {
assertOk(await request({ method: 'PUT' }));
assertOk(await request({ method: 'PUT', objectKey, 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 [objectKey, 'copy']) {
await request({ method: 'DELETE', objectKey: key });
}
await request({ method: 'DELETE' });
});

it('should return InvalidArgument on PutObjectAcl for the AllUsers group URI as ID', async () => {
const result = await request({
method: 'PUT',
objectKey,
queryObj: { acl: '' },
requestBody: canonicalUserAcl(allUsers),
});
assertError(result, 400, 'InvalidArgument');
assertError(await anonymousGet(objectKey), 403, 'AccessDenied');
});

it('should return InvalidArgument on CopyObject for the AllUsers group URI as id', async () => {
const result = await request({
method: 'PUT',
objectKey: 'copy',
headers: { 'x-amz-copy-source': `/${bucket}/${objectKey}`, 'x-amz-grant-read': `id=${allUsers}` },
});
assertError(result, 400, 'InvalidArgument');
const head = await request({ method: 'HEAD', objectKey: 'copy' });
assert.strictEqual(head.res.statusCode, 404);
});

it('should return InvalidArgument on CreateMultipartUpload for the AllUsers group URI as id', async () => {
const result = await request({
method: 'POST',
objectKey: 'mpu',
queryObj: { uploads: '' },
headers: { 'x-amz-grant-read': `id=${allUsers}` },
});
assertError(result, 400, 'InvalidArgument');
});

it('should store a canonical id given in upper case in lower case on PutObjectAcl', async () => {
const result = await request({
method: 'PUT',
objectKey,
queryObj: { acl: '' },
requestBody: canonicalUserAcl(otherId.toUpperCase()),
});
assertOk(result);
const { res } = await request({ method: 'GET', objectKey, 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 so a failure shows a diff (same at line 128).

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

});

it('should store a canonical id given in upper case in lower case on CopyObject', async () => {
const result = await request({
method: 'PUT',
objectKey: 'copy',
headers: {
'x-amz-copy-source': `/${bucket}/${objectKey}`,
'x-amz-grant-read': `id=${otherId.toUpperCase()}`,
},
});
assertOk(result);
const { res } = await request({ method: 'GET', objectKey: 'copy', queryObj: { acl: '' } });
assert(res.body.includes(`<ID>${otherId}</ID>`), res.body);
});
});
159 changes: 159 additions & 0 deletions tests/unit/api/aclCanonicalId.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
const assert = require('assert');

const { bucketPut } = require('../../../lib/api/bucketPut');
const initiateMultipartUpload = require('../../../lib/api/initiateMultipartUpload');
const objectCopy = require('../../../lib/api/objectCopy');
const objectPut = require('../../../lib/api/objectPut');
const objectPutACL = require('../../../lib/api/objectPutACL');
const constants = require('../../../constants');
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 otherId = '79a59df900b949e55d96a1e698fbacedfd6e09d98eacf8f8d5218e7cd47ef2bf';
const namespace = 'default';
const bucketName = 'bucketname';
const objectKey = 'objectname';

function canonicalUserGrant(id) {
return (
'<Grant><Grantee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="CanonicalUser">' +
`<ID>${id}</ID></Grantee><Permission>READ</Permission></Grant>`
);
}

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

function putObjectAcl(body, cb) {
const request = new DummyRequest({
bucketName,
namespace,
objectKey,
headers: { host: `${bucketName}.s3.amazonaws.com` },
url: `/${bucketName}/${objectKey}?acl`,
query: { acl: '' },
post: body,
});
objectPutACL(authInfo, request, log, cb);
}

function getReadAcl(cb) {
metadata.getObjectMD(bucketName, objectKey, {}, log, (err, md) => cb(err, md && md.acl.READ));
}

describe('grants to an id that is not a canonical id', () => {
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());

it('PutObjectAcl returns InvalidArgument for the AllUsers group URI as ID and keeps the ACL', done => {
putObjectAcl(canonicalUserAcl(canonicalUserGrant(constants.publicId)), err => {
assert(err && err.is.InvalidArgument, `expected InvalidArgument, got ${err}`);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Compare the error message rather than using .is, so a failure shows the actual error name. Same at lines 109, 111 and 128.

Suggested change
assert(err && err.is.InvalidArgument, `expected InvalidArgument, got ${err}`);
assert.strictEqual(err?.message, 'InvalidArgument');

getReadAcl((err, readAcl) => {
assert.ifError(err);
assert.deepStrictEqual(readAcl, []);
done();
});
});
});

const allUsersHeader = { 'x-amz-grant-read': `id=${constants.publicId}` };

it('CopyObject returns InvalidArgument for the AllUsers group URI as id and stores nothing', done => {
const request = new DummyRequest({
bucketName,
namespace,
objectKey: 'copyname',
headers: { host: `${bucketName}.s3.amazonaws.com`, ...allUsersHeader },
url: `/${bucketName}/copyname`,
socket: {},
});
objectCopy(authInfo, request, bucketName, objectKey, undefined, log, err => {
assert(err && err.is.InvalidArgument, `expected InvalidArgument, got ${err}`);
metadata.getObjectMD(bucketName, 'copyname', {}, log, err => {
assert(err && err.is.NoSuchKey, `expected no copy, got ${err}`);
done();
});
});
});

it('CreateMultipartUpload returns InvalidArgument for the AllUsers group URI as id', done => {
const request = {
bucketName,
namespace,
objectKey,
headers: { host: `${bucketName}.s3.amazonaws.com`, ...allUsersHeader },
url: `/${objectKey}?uploads`,
socket: { remoteAddress: '1.1.1.1' },
actionImplicitDenies: false,
};
initiateMultipartUpload(authInfo, request, log, err => {
assert(err && err.is.InvalidArgument, `expected InvalidArgument, got ${err}`);
done();
});
});

it('CopyObject stores a canonical id given in upper case in lower case', done => {
const request = new DummyRequest({
bucketName,
namespace,
objectKey: 'copyname',
headers: { host: `${bucketName}.s3.amazonaws.com`, 'x-amz-grant-read': `id=${otherId.toUpperCase()}` },
url: `/${bucketName}/copyname`,
socket: {},
});
objectCopy(authInfo, request, bucketName, objectKey, undefined, log, err => {
assert.ifError(err);
metadata.getObjectMD(bucketName, 'copyname', {}, log, (err, md) => {
assert.ifError(err);
assert.deepStrictEqual(md.acl.READ, [otherId]);
done();
});
});
});

it('PutObjectAcl stores a canonical id given in upper case in lower case', done => {
putObjectAcl(canonicalUserAcl(canonicalUserGrant(otherId.toUpperCase())), err => {
assert.ifError(err);
getReadAcl((err, readAcl) => {
assert.ifError(err);
assert.deepStrictEqual(readAcl, [otherId]);
done();
});
});
});
});
Loading