Skip to content

Fixes for cdk-cloudfront-authorization #212

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

Open
wants to merge 3 commits into
base: cdk2
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
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,8 @@ Object {
Object {
"Ref": "SpaAuthorizationSecretGeneratorCustomResource7B87C244",
},
"\\"
"\\",
\\"httpHeaders\\": []
}",
],
],
Expand Down Expand Up @@ -419,7 +420,8 @@ Object {
Object {
"Ref": "SpaAuthorizationSecretGeneratorCustomResource7B87C244",
},
"\\"
"\\",
\\"httpHeaders\\": []
}",
],
],
Expand Down Expand Up @@ -498,7 +500,8 @@ Object {
Object {
"Ref": "SpaAuthorizationSecretGeneratorCustomResource7B87C244",
},
"\\"
"\\",
\\"httpHeaders\\": []
}",
],
],
Expand Down Expand Up @@ -577,7 +580,8 @@ Object {
Object {
"Ref": "SpaAuthorizationSecretGeneratorCustomResource7B87C244",
},
"\\"
"\\",
\\"httpHeaders\\": []
}",
],
],
Expand Down Expand Up @@ -1325,7 +1329,8 @@ Object {
"UserPoolClient.ClientSecret",
],
},
"\\"
"\\",
\\"httpHeaders\\": []
}",
],
],
Expand Down Expand Up @@ -1412,7 +1417,8 @@ Object {
"UserPoolClient.ClientSecret",
],
},
"\\"
"\\",
\\"httpHeaders\\": []
}",
],
],
Expand Down Expand Up @@ -1499,7 +1505,8 @@ Object {
"UserPoolClient.ClientSecret",
],
},
"\\"
"\\",
\\"httpHeaders\\": []
}",
],
],
Expand Down Expand Up @@ -1586,7 +1593,8 @@ Object {
"UserPoolClient.ClientSecret",
],
},
"\\"
"\\",
\\"httpHeaders\\": []
}",
],
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,8 @@ Object {
Object {
"Ref": "SpaAuthorizationSecretGeneratorCustomResource7B87C244",
},
"\\"
"\\",
\\"httpHeaders\\": []
}",
],
],
Expand Down Expand Up @@ -472,7 +473,8 @@ Object {
Object {
"Ref": "SpaAuthorizationSecretGeneratorCustomResource7B87C244",
},
"\\"
"\\",
\\"httpHeaders\\": []
}",
],
],
Expand Down Expand Up @@ -551,7 +553,8 @@ Object {
Object {
"Ref": "SpaAuthorizationSecretGeneratorCustomResource7B87C244",
},
"\\"
"\\",
\\"httpHeaders\\": []
}",
],
],
Expand Down Expand Up @@ -630,7 +633,8 @@ Object {
Object {
"Ref": "SpaAuthorizationSecretGeneratorCustomResource7B87C244",
},
"\\"
"\\",
\\"httpHeaders\\": []
}",
],
],
Expand Down Expand Up @@ -1788,7 +1792,8 @@ Object {
"UserPoolClient.ClientSecret",
],
},
"\\"
"\\",
\\"httpHeaders\\": []
}",
],
],
Expand Down Expand Up @@ -1875,7 +1880,8 @@ Object {
"UserPoolClient.ClientSecret",
],
},
"\\"
"\\",
\\"httpHeaders\\": []
}",
],
],
Expand Down Expand Up @@ -1962,7 +1968,8 @@ Object {
"UserPoolClient.ClientSecret",
],
},
"\\"
"\\",
\\"httpHeaders\\": []
}",
],
],
Expand Down Expand Up @@ -2049,7 +2056,8 @@ Object {
"UserPoolClient.ClientSecret",
],
},
"\\"
"\\",
\\"httpHeaders\\": []
}",
],
],
Expand Down
2 changes: 2 additions & 0 deletions packages/cdk-cloudfront-authorization/src/auth-flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export interface AuthFlowProps {
readonly cookieSettings: Record<string, string>;
readonly nonceSigningSecret: string;
readonly clientSecret?: string;
readonly httpHeaders?: Record<string, string>;
}

export class AuthFlow extends Construct {
Expand All @@ -44,6 +45,7 @@ export class AuthFlow extends Construct {
cookieSettings: props.cookieSettings,
nonceSigningSecret: props.nonceSigningSecret,
clientSecret: props.clientSecret,
httpHeaders: props.httpHeaders ?? [],
};

this.checkAuth = new EdgeFunction(this, 'CheckAuth', {
Expand Down
5 changes: 5 additions & 0 deletions packages/cdk-cloudfront-authorization/src/authorizations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export interface AuthorizationProps {
readonly oauthScopes?: aws_cognito.OAuthScope[];
readonly cookieSettings?: Record<string, string>;
readonly identityProviders?: aws_cognito.UserPoolClientIdentityProvider[];
readonly httpHeaders?: Record<string, string> | undefined;
}

export abstract class Authorization extends Construct {
Expand All @@ -59,6 +60,7 @@ export abstract class Authorization extends Construct {
protected readonly cognitoAuthDomain: string;
protected readonly identityProviders: aws_cognito.UserPoolClientIdentityProvider[];
protected readonly responseHeaderPolicy: aws_cloudfront.IResponseHeadersPolicy;
protected readonly httpHeaders: Record<string, string> | undefined;

constructor(scope: Construct, id: string, props: AuthorizationProps) {
super(scope, id);
Expand Down Expand Up @@ -126,6 +128,8 @@ export abstract class Authorization extends Construct {

this.cognitoAuthDomain = this.retrieveCognitoAuthDomain();

this.httpHeaders = props.httpHeaders;

this.authFlow = this.createAuthFlow(props.logLevel ?? LogLevel.WARN);
}

Expand Down Expand Up @@ -297,6 +301,7 @@ export class StaticSiteAuthorization extends Authorization implements IStaticSit
refreshToken: 'Path=/; Secure; HttpOnly; SameSite=Lax',
nonce: 'Path=/; Secure; HttpOnly; SameSite=Lax',
},
httpHeaders: this.httpHeaders,
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ import type {
} from 'aws-lambda';
import axios from 'axios';

const awsRegion = process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION;
const COGNITO_CLIENT = new CognitoIdentityProvider({
region: process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION,
region: awsRegion,
});

async function ensureCognitoUserPoolDomain(userPoolId: string): Promise<string> {
Expand All @@ -28,7 +29,7 @@ async function ensureCognitoUserPoolDomain(userPoolId: string): Promise<string>
throw new Error('Cognito auth domain is missing! Either a domain prefix or a custom domain must be configured.');
}

return userPool.CustomDomain ?? `${userPool.Domain}.auth.${COGNITO_CLIENT.config.region}.amazoncognito.com`;
return userPool.CustomDomain ?? `${userPool.Domain}.auth.${awsRegion}.amazoncognito.com`;
}

export const handler: CloudFormationCustomResourceHandler = async (event) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { mkdtempSync, writeFileSync } from 'fs';
import { resolve } from 'path';
import { GetFunctionCommand, LambdaClient, UpdateFunctionCodeCommand } from '@aws-sdk/client-lambda';
import { GetFunctionCommand, LambdaClient, UpdateFunctionCodeCommand, waitUntilFunctionActiveV2 } from '@aws-sdk/client-lambda';
import Zip from 'adm-zip';
import type {
CloudFormationCustomResourceCreateEvent,
Expand All @@ -26,6 +26,7 @@ interface WithConfiguration {
const updateLambdaCode = async (
event: CloudFormationCustomResourceCreateEvent | CloudFormationCustomResourceUpdateEvent,
): Promise<ResourceHandlerReturn> => {
console.log(`Recieved event: ${event}`);
const { region, functionName, configuration } = camelizeKeys<
WithConfiguration,
CloudFormationCustomResourceEventCommon['ResourceProperties']
Expand Down Expand Up @@ -72,15 +73,48 @@ const updateLambdaCode = async (
Publish: true,
}),
);

return {

let responseDetails = {
responseStatus: 'FAILED',
reason: 'Internal Error',
physicalResourceId: functionName,
responseData: {
CodeSha256: codeSha256,
Version: version,
FunctionArn: functionArn,
},
responseData: {},
};

// wait for functions to go active before proceeding because if an edge function isn't active updates to the
// related distribution fail
console.log(`Waiting for ${functionName} to go active...`);
waitUntilFunctionActiveV2(
{client: lambda, maxWaitTime: 60},
{FunctionName: functionName}
)
.then((result=>{
console.log(`Lambda function ${functionName} is active. Result: ${result}`);
responseDetails = {
physicalResourceId: functionName,
responseStatus: 'SUCCESS',
reason: `Lambda function ${functionName} is active.`,
responseData: {
CodeSha256: codeSha256,
Version: version,
FunctionArn: functionArn,
},
};
setTimeout(()=>{
console.log(`Waiting 5s for lambda status propagation...`);
}, 5000);
}))
.catch((err=>{
console.log(`Error waiting for ${functionName} to go active: ${err}`);
responseDetails = {
responseStatus: 'FAILED',
physicalResourceId: functionName,
reason: `Encountered error while waiting for ${functionName} to go active: ${err}`,
responseData: {}
};
}));

return responseDetails;
};

const handleCreate: OnCreateHandler = async (event): Promise<ResourceHandlerReturn> => updateLambdaCode(event);
Expand Down