Skip to content

Commit

Permalink
more generic approach for s3 tempurl generation
Browse files Browse the repository at this point in the history
this version also matches non aws systems
  • Loading branch information
Schnitzel committed May 29, 2019
1 parent 6d8c3d5 commit ad491bd
Showing 1 changed file with 37 additions and 40 deletions.
77 changes: 37 additions & 40 deletions services/api/src/resources/backup/helpers.js
Expand Up @@ -5,46 +5,43 @@ const S3 = require('aws-sdk/clients/s3');

const makeS3TempLink = async (restore /* : Object */) => {
const restoreLocation = R.prop('restoreLocation', restore);
// s3.{region}.amazonaws.com/{bucket}/{key}
const s3LinkMatch = /s3\.([^.]+)\.amazonaws\.com\/([^/]+)\/([^/]+)/;

if (R.test(s3LinkMatch, restoreLocation)) {
const s3Parts = R.match(s3LinkMatch, restoreLocation);

const accessKeyId = R.propOr(
'XXXXXXXXXXXXXXXXXXXX',
'S3_BAAS_ACCESS_KEY_ID',
process.env,
);
const secretAccessKey = R.propOr(
'XXXXXXXXXXXXXXXXXXXX',
'S3_BAAS_SECRET_ACCESS_KEY',
process.env,
);

// We have to generate a new client every time because the region is parsed
// from the s3 url.
const s3Client = new S3({
accessKeyId,
secretAccessKey,
s3ForcePathStyle: true,
signatureVersion: 'v4',
region: R.prop(1, s3Parts),
});

const tempUrl = s3Client.getSignedUrl('getObject', {
Bucket: R.prop(2, s3Parts),
Key: R.prop(3, s3Parts),
Expires: 300, // 5 minutes
});

return {
...restore,
restoreLocation: tempUrl,
};
}

return restore;

const accessKeyId = R.propOr(
'XXXXXXXXXXXXXXXXXXXX',
'S3_BAAS_ACCESS_KEY_ID',
process.env,
);
const secretAccessKey = R.propOr(
'XXXXXXXXXXXXXXXXXXXX',
'S3_BAAS_SECRET_ACCESS_KEY',
process.env,
);

// https://{endpoint}/{bucket}/{key}
const s3LinkMatch = /([^/]+)\/([^/]+)\/([^/]+)/;

const s3Parts = R.match(s3LinkMatch, restoreLocation);

// We have to generate a new client every time because the endpoint is parsed
// from the s3 url.
const s3Client = new S3({
accessKeyId,
secretAccessKey,
s3ForcePathStyle: true,
signatureVersion: 'v4',
endpoint: `https://${R.prop(1, s3Parts)}`,
});

const tempUrl = s3Client.getSignedUrl('getObject', {
Bucket: R.prop(2, s3Parts),
Key: R.prop(3, s3Parts),
Expires: 300, // 5 minutes
});

return {
...restore,
restoreLocation: tempUrl,
};
};

const Helpers = {
Expand Down

0 comments on commit ad491bd

Please sign in to comment.