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

URL Signing #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
12 changes: 12 additions & 0 deletions deployment/serverless-image-handler.template
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@
"Default" : "No",
"Type" : "String",
"AllowedValues" : [ "Yes", "No" ]
},
"SignatureKey" : {
"Description" : "If you would like to use signed URLs, please specify a secret signature key here. Signature key will be used to validate base64 payloads.",
"Default" : "",
"Type" : "String"
}
},
"Metadata": {
Expand Down Expand Up @@ -391,6 +396,9 @@
"SOURCE_BUCKETS" : {
"Ref" : "SourceBuckets"
},
"SIGNATURE_KEY": {
"Ref" : "SignatureKey"
},
"REWRITE_MATCH_PATTERN" : "",
"REWRITE_SUBSTITUTION" : ""
}
Expand Down Expand Up @@ -847,6 +855,10 @@
"Description" : "Origin value returned in the Access-Control-Allow-Origin header of image handler API responses.",
"Value" : { "Ref" : "CorsOrigin" }
},
"SignatureKey" : {
"Description" : "Key used to sign URLs.",
"Value" : { "Ref" : "SignatureKey" }
},
"LogRetentionPeriod" : {
"Description" : "Number of days for event logs from Lambda to be retained in CloudWatch.",
"Value" : { "Ref" : "LogRetentionPeriod" }
Expand Down
45 changes: 44 additions & 1 deletion source/image-handler/image-request.js
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ class ImageRequest {
parseRequestType(event) {
const path = event["path"];
// ----
const matchDefault = new RegExp(/^(\/?)([0-9a-zA-Z+\/]{4})*(([0-9a-zA-Z+\/]{2}==)|([0-9a-zA-Z+\/]{3}=))?$/);
const matchDefault = new RegExp(/^(\/?)([0-9a-zA-Z+\/]{4})*(([0-9a-zA-Z+\/]{2}==)|([0-9a-zA-Z+\/]{3}=))?(--([0-9a-zA-Z]{1,}))?$/);
const matchThumbor = new RegExp(/^(\/?)((fit-in)?|(filters:.+\(.?\))?|(unsafe)?).*(.+jpg|.+png|.+webp|.+tiff|.+jpeg)$/i);
const matchCustom = new RegExp(/(\/?)(.*)(jpg|png|webp|tiff|jpeg)/i);
const definedEnvironmentVariables = (
Expand Down Expand Up @@ -242,6 +242,7 @@ class ImageRequest {
if (path !== undefined) {
const splitPath = path.split("/");
const encoded = splitPath[splitPath.length - 1];
const verifiedPath = this.verifySignature(encoded);
const toBuffer = Buffer.from(encoded, 'base64');
try {
// To support European characters, 'ascii' was removed.
Expand Down Expand Up @@ -297,6 +298,48 @@ class ImageRequest {

return null;
}

/**
* Verifies base64 signature, using SIGNATURE_KEY env var. If SIGNATURE_KEY
* isn't provided, it doesn't do anything. Returns base64 path without the
* signature part.
* @param {String} path - base64-encoded URL path.
*/
verifySignature(path) {
const signKey = process.env.SIGNATURE_KEY;
if (signKey === undefined) {
return path;
}

const crypto = require('crypto');
const bufferEq = require('buffer-equal-constant-time');

const splitPath = path.split("--");
const base64 = splitPath[0];
const providedSignature = splitPath[1];

if (providedSignature === undefined) {
throw ({
status: 400,
code: 'DecodeRequest::MissingSignature',
message: 'The signature is missing.'
});
}

const signature = crypto.createHmac("sha1", signKey).update(base64).digest("hex");
Copy link
Member

Choose a reason for hiding this comment

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

SHA1 is broken. I know this is signing, not encryption, but I question this algorithm choice. I'd expect SHA-256 at minimum. What algorithm does AWS use for its S3 URL signing? I doubt it's SHA1.

const signatureBuffer = Buffer.from(signature.toString('base64'));
const providedSignatureBuffer = Buffer.from(providedSignature);

if (bufferEq(signatureBuffer, providedSignatureBuffer)) {
return base64;
}

throw ({
status: 400,
code: 'DecodeRequest::InvalidSignature',
message: 'The signature you provided could not be verified.'
});
}
}

// Exports
Expand Down
1 change: 1 addition & 0 deletions source/image-handler/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"version": "0.0.1",
"private": true,
"dependencies": {
"buffer-equal-constant-time": "^1.0.1",
"sharp": "^0.23.4",
"color": "3.1.2",
"color-name": "1.1.4"
Expand Down
103 changes: 103 additions & 0 deletions source/image-handler/test/test-image-request.js
Original file line number Diff line number Diff line change
Expand Up @@ -641,6 +641,25 @@ describe('decodeRequest()', function() {
});
});
});
describe('004/signedPath', function() {
it(`Should throw an error if signature is invalid`, function() {
// Arrange
process.env = {
SIGNATURE_KEY : "mySecretKey"
}
const path = 'eyJlZGl0cyI6eyJncmF5c2NhbGUiOiJ0cnVlIiwicm90YXRlIjo5MCwiZmxpcCI6InRydWUifX0--invalid-signature'
// Act
const imageRequest = new ImageRequest();
// Assert
assert.throws(function() {
imageRequest.decodeRequest(event);
}, Object, {
status: 400,
code: 'DecodeRequest::CannotReadPath',
message: 'The URL path you provided could not be read. Please ensure that it is properly formed according to the solution documentation.'
Comment on lines +658 to +659
Copy link
Member

Choose a reason for hiding this comment

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

My reading of the diff makes this error message surprising. I didn't read the whole thing though.

});
});
});
});

// ----------------------------------------------------------------------------
Expand Down Expand Up @@ -755,3 +774,87 @@ describe('getOutputFormat()', function () {
});
});
});


// ----------------------------------------------------------------------------
// verifySignature()
// ----------------------------------------------------------------------------

describe('verifySignature()', function() {
describe('001/noSignatureKey', function() {
it(`Should pass if a valid base64-encoded path has been specified`, function() {
// Arrange
const path = 'eyJidWNrZXQiOiJidWNrZXQtbmFtZS1oZXJlIiwia2V5Ijoia2V5LW5hbWUtaGVyZSJ9'

// Act
const imageRequest = new ImageRequest();
const result = imageRequest.verifySignature(path);

// Assert
const expectedResult = 'eyJidWNrZXQiOiJidWNrZXQtbmFtZS1oZXJlIiwia2V5Ijoia2V5LW5hbWUtaGVyZSJ9'
assert.deepEqual(result, expectedResult);
});
});

describe('002/validSignature', function() {
it(`Should pass if a valid signature has been specified`, function() {
// Arrange
process.env = {
SIGNATURE_KEY : "mySecretKey"
}
const path = 'eyJidWNrZXQiOiJidWNrZXQtbmFtZS1oZXJlIiwia2V5Ijoia2V5LW5hbWUtaGVyZSJ9--640b43f6c1fede17c301b23338b4eb4d7d462ce6'

// Act
const imageRequest = new ImageRequest();
const result = imageRequest.verifySignature(path);

// Assert
const expectedResult = 'eyJidWNrZXQiOiJidWNrZXQtbmFtZS1oZXJlIiwia2V5Ijoia2V5LW5hbWUtaGVyZSJ9'
assert.deepEqual(result, expectedResult);
});
});

describe('003/invalidSignature', function() {
it(`Should throw an error if an invalid signature has been specified`, function() {
// Arrange
process.env = {
SIGNATURE_KEY : "mySecretKey"
}
const path = 'eyJlZGl0cyI6eyJncmF5c2NhbGUiOiJ0cnVlIiwicm90YXRlIjo5MCwiZmxpcCI6InRydWUifX0--640b43f6c1fede17c301b23338b4eb4d7d462ce6'

// Act
const imageRequest = new ImageRequest();

// Assert
assert.throws(function() {
imageRequest.verifySignature(path);
}, Object, {
status: 400,
code: 'DecodeRequest::InvalidSignature',
message: 'The signature you provided could not be verified.'
});
});
});

describe('004/noSignature', function() {
it(`Should throw an error if signature has not been specified`, function() {
// Arrange
process.env = {
SIGNATURE_KEY : "mySecretKey"
}
const path = 'eyJlZGl0cyI6eyJncmF5c2NhbGUiOiJ0cnVlIiwicm90YXRlIjo5MCwiZmxpcCI6InRydWUifX0'

// Act
const imageRequest = new ImageRequest();

// Assert
assert.throws(function() {
imageRequest.verifySignature(path);
}, Object, {
status: 400,
code: 'DecodeRequest::MissingSignature',
message: 'The signature is missing.'
});
});
});
});