Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add file bucket encryption using fileKey #6765

Merged
merged 4 commits into from
Jul 1, 2020
Merged
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
16 changes: 16 additions & 0 deletions spec/GridFSBucketStorageAdapter.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,22 @@ describe_only_db('mongo')('GridFSBucket and GridStore interop', () => {
expect(gfsResult.toString('utf8')).toBe(originalString);
});

it('an encypted file created in GridStore should be available in GridFS', async () => {
const gsAdapter = new GridStoreAdapter(databaseURI);
const gfsAdapter = new GridFSBucketAdapter(
databaseURI,
{},
'89E4AFF1-DFE4-4603-9574-BFA16BB446FD'
);
await expectMissingFile(gfsAdapter, 'myFileName');
const originalString = 'abcdefghi';
await gfsAdapter.createFile('myFileName', originalString);
const gsResult = await gsAdapter.getFileData('myFileName');
expect(gsResult.toString('utf8')).not.toBe(originalString);
const gfsResult = await gfsAdapter.getFileData('myFileName');
expect(gfsResult.toString('utf8')).toBe(originalString);
});

it('should save metadata', async () => {
const gfsAdapter = new GridFSBucketAdapter(databaseURI);
const originalString = 'abcdefghi';
Expand Down
51 changes: 47 additions & 4 deletions src/Adapters/Files/GridFSBucketAdapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,30 @@
import { MongoClient, GridFSBucket, Db } from 'mongodb';
import { FilesAdapter, validateFilename } from './FilesAdapter';
import defaults from '../../defaults';
const crypto = require('crypto');

export class GridFSBucketAdapter extends FilesAdapter {
_databaseURI: string;
_connectionPromise: Promise<Db>;
_mongoOptions: Object;
_algorithm: string;

constructor(mongoDatabaseURI = defaults.DefaultMongoURI, mongoOptions = {}) {
constructor(
mongoDatabaseURI = defaults.DefaultMongoURI,
mongoOptions = {},
fileKey = undefined
) {
super();
this._databaseURI = mongoDatabaseURI;

this._algorithm = 'aes-256-gcm';
this._fileKey =
fileKey !== undefined
? crypto
.createHash('sha256')
.update(String(fileKey))
.digest('base64')
.substr(0, 32)
: null;
const defaultMongoOptions = {
useNewUrlParser: true,
useUnifiedTopology: true,
Expand Down Expand Up @@ -51,7 +65,19 @@ export class GridFSBucketAdapter extends FilesAdapter {
const stream = await bucket.openUploadStream(filename, {
metadata: options.metadata,
});
await stream.write(data);
if (this._fileKey !== null) {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(this._algorithm, this._fileKey, iv);
const encryptedResult = Buffer.concat([
cipher.update(data),
cipher.final(),
iv,
cipher.getAuthTag(),
]);
await stream.write(encryptedResult);
} else {
await stream.write(data);
}
stream.end();
return new Promise((resolve, reject) => {
stream.on('finish', resolve);
Expand Down Expand Up @@ -82,7 +108,24 @@ export class GridFSBucketAdapter extends FilesAdapter {
chunks.push(data);
});
stream.on('end', () => {
resolve(Buffer.concat(chunks));
const data = Buffer.concat(chunks);
if (this._fileKey !== null) {
const authTagLocation = data.length - 16;
const ivLocation = data.length - 32;
const authTag = data.slice(authTagLocation);
const iv = data.slice(ivLocation, authTagLocation);
const encrypted = data.slice(0, ivLocation);
const decipher = crypto.createDecipheriv(
this._algorithm,
this._fileKey,
iv
);
decipher.setAuthTag(authTag);
return resolve(
Buffer.concat([decipher.update(encrypted), decipher.final()])
);
}
resolve(data);
});
stream.on('error', (err) => {
reject(err);
Expand Down
3 changes: 2 additions & 1 deletion src/Controllers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -105,12 +105,13 @@ export function getFilesController(
filesAdapter,
databaseAdapter,
preserveFileName,
fileKey,
} = options;
if (!filesAdapter && databaseAdapter) {
throw 'When using an explicit database adapter, you must also use an explicit filesAdapter.';
}
const filesControllerAdapter = loadAdapter(filesAdapter, () => {
return new GridFSBucketAdapter(databaseURI);
return new GridFSBucketAdapter(databaseURI, {}, fileKey);
});
return new FilesController(filesControllerAdapter, appId, {
preserveFileName,
Expand Down