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

Image expires header #349

Open
wants to merge 3 commits into
base: main
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
45 changes: 44 additions & 1 deletion source/image-handler/image-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
public async setup(event: ImageHandlerEvent): Promise<ImageRequestInfo> {
try {
await this.validateRequestSignature(event);
this.validateRequestExpires(event);

let imageRequestInfo: ImageRequestInfo = <ImageRequestInfo>{};

Expand Down Expand Up @@ -336,7 +337,7 @@
} else if (definedEnvironmentVariables) {
// use rewrite function then thumbor mappings
return RequestTypes.CUSTOM;
} else if (matchThumbor.test(path)) {

Check failure

Code scanning / CodeQL

Polynomial regular expression used on uncontrolled data High

This
regular expression
that depends on
library input
may run slow on strings with many repetitions of 'a()a'.
// use thumbor mappings
return RequestTypes.THUMBOR;
} else {
Expand Down Expand Up @@ -464,6 +465,19 @@
}
}

/**
* Creates a query string similar to API Gateway 2.0 payload's $.rawQueryString
* @param queryStringParameters Request's query parameters
* @returns URL encoded queryString
*/
private recreateQueryString(queryStringParameters: ImageHandlerEvent['queryStringParameters']): string {
return Object
.entries(queryStringParameters)
.filter(([key]) => key !== 'signature')
.map(([key, value]) => [key, value].join('='))
.join('&');
}

/**
* Validates the request's signature.
* @param event Lambda request body.
Expand All @@ -485,11 +499,14 @@
);
}

const queryString = this.recreateQueryString(queryStringParameters);

try {
const { signature } = queryStringParameters;
const secret = JSON.parse(await this.secretProvider.getSecret(SECRETS_MANAGER));
const key = secret[SECRET_KEY];
const hash = createHmac("sha256", key).update(path).digest("hex");
const stringToSign = queryString !== '' ? [path, queryString].join('?') : path;
const hash = createHmac('sha256', key).update(stringToSign).digest('hex');

// Signature should be made with the full path.
if (signature !== hash) {
Expand All @@ -509,4 +526,30 @@
}
}
}

private validateRequestExpires(event: ImageHandlerEvent): void {
try {
const { queryStringParameters } = event;
const expires = queryStringParameters?.expires;
if (expires !== undefined) {
const parsedDate = new Date(expires);
if (isNaN(parsedDate.getTime())) {
throw new ImageHandlerError(StatusCodes.BAD_REQUEST, 'ImageRequestExpiryFormat', 'Request has invalid expiry date.');
}
const now = new Date();
if (now > parsedDate) {
throw new ImageHandlerError(StatusCodes.FORBIDDEN, 'ImageRequestExpired', 'Request has expired.');
}
}
} catch (error) {
if (error.code === 'ImageRequestExpired') {
throw error;
}
if (error.code === 'ImageRequestExpiryFormat') {
throw error;
}
console.error('Error occurred while checking expiry.', error);
throw new ImageHandlerError(StatusCodes.INTERNAL_SERVER_ERROR, 'ExpiryDateCheckFailure', 'Expiry date check failed.');
}
}
}
3 changes: 2 additions & 1 deletion source/image-handler/lib/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import { Headers, ImageEdits } from "./types";
export interface ImageHandlerEvent {
path?: string;
queryStringParameters?: {
signature: string;
signature?: string;
expires?: string;
};
requestContext?: {
elb?: unknown;
Expand Down
50 changes: 49 additions & 1 deletion source/image-handler/test/image-request/decode-request.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import S3 from "aws-sdk/clients/s3";
import SecretsManager from "aws-sdk/clients/secretsmanager";

import { ImageRequest } from "../../image-request";
import { StatusCodes } from "../../lib";
import { ImageHandlerEvent, StatusCodes } from "../../lib";
import { SecretProvider } from "../../secret-provider";
import { mockAwsS3 } from '../mock';

describe("decodeRequest", () => {
const s3Client = new S3();
Expand Down Expand Up @@ -70,4 +71,51 @@ describe("decodeRequest", () => {
});
}
});

describe('expires', () => {
const baseRequest = {
bucket: 'test',
requestType: 'Default',
key: 'test.png',
};
const path = `/${Buffer.from(JSON.stringify(baseRequest)).toString('base64')}`;
it.each([
{
expires: 'Thu, 01 Jan 1970 00:00:00 GMT',
error: {
code: 'ImageRequestExpired',
message: 'Request has expired.',
status: StatusCodes.FORBIDDEN,
},
},
{
expires: 'invalidKey',
error: {
code: 'ImageRequestExpiryFormat',
message: 'Request has invalid expiry date.',
status: StatusCodes.BAD_REQUEST,
}
}
] as { expires: ImageHandlerEvent['queryStringParameters']['expires'], error: object, }[])(
"Should throw an error when $error.message",
(async ({ error: expectedError, expires }) => {
// Arrange
const event: ImageHandlerEvent = {
path,
queryStringParameters: {
expires,
},
};
// Mock
mockAwsS3.getObject.mockImplementationOnce(() => ({
promise() {
return Promise.resolve({ Body: Buffer.from('SampleImageContent\n') });
}
}));
// Act
const imageRequest = new ImageRequest(s3Client, secretProvider);
await expect(imageRequest.setup(event)).rejects.toMatchObject(expectedError);
})
);
});
});
Loading