Skip to content

Commit

Permalink
feat(api): enable cors on codegen asset bucket
Browse files Browse the repository at this point in the history
  • Loading branch information
sundersc committed Mar 18, 2024
1 parent affdb98 commit 5513930
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 2 deletions.
30 changes: 30 additions & 0 deletions packages/amplify-e2e-core/src/utils/sdk-calls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,3 +205,33 @@ export const listAttachedRolePolicies = async (roleName: string, region: string)
const service = new IAM({ region });
return (await service.listAttachedRolePolicies({ RoleName: roleName }).promise()).AttachedPolicies;
};

export const getBucketNameFromModelSchemaS3Uri = (uri: string | null): string => {
const pattern = /(s3:\/\/)(.*)(\/.*)/;
const matches = uri.match(pattern);
// Sample Input Uri looks like 's3://bucket-name/model-schema.graphql'.
// The output of string.match returns an array which looks like the below. The third element is the bucket name.
// [
// "s3://bucket-name/model-schema.graphql",
// "s3://",
// "bucket-name",
// "/model-schema.graphql"
// ]
const HOST_INDEX = 2;
if (!matches) {
return null;
}
if (matches.length && matches.length > 2) {
return matches[HOST_INDEX];
}
return null;
};

export const getBucketCorsPolicy = async (bucketName: string, region: string): Promise<Record<string, any>[]> => {
const service = new S3({ region });
const params = {
Bucket: bucketName,
};
const corsPolicy = await service.getBucketCors(params).promise();
return corsPolicy.CORSRules;
};
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as path from 'path';
import { createNewProjectDir, deleteProjectDir } from 'amplify-category-api-e2e-core';
import { createNewProjectDir, deleteProjectDir, getBucketNameFromModelSchemaS3Uri, getBucketCorsPolicy } from 'amplify-category-api-e2e-core';
import { initCDKProject, cdkDeploy, cdkDestroy } from '../commands';
import { graphql } from '../graphql-request';

Expand Down Expand Up @@ -29,6 +29,21 @@ describe('CDK GraphQL Transformer', () => {
const templatePath = path.resolve(path.join(__dirname, 'backends', 'base-cdk'));
const name = await initCDKProject(projRoot, templatePath, { cdkVersion });
const outputs = await cdkDeploy(projRoot, '--all');

// Console requires CORS enabled on codegen asset bucket.
const { awsAppsyncRegion: region, amplifyApiModelSchemaS3Uri: codegenModelSchemaS3Uri } = outputs[name];
const codegenBucketName = getBucketNameFromModelSchemaS3Uri(codegenModelSchemaS3Uri);
const corsPolicy = await getBucketCorsPolicy(codegenBucketName, region);
expect(corsPolicy).toMatchObject(
expect.arrayContaining([
expect.objectContaining({
'AllowedHeaders': expect.arrayContaining(['*']),
'AllowedMethods': expect.arrayContaining(['GET', 'HEAD']),
'AllowedOrigins': expect.arrayContaining(['https://*.console.aws.amazon.com/amplify']),
}),
]),
);

const { awsAppsyncApiEndpoint: apiEndpoint, awsAppsyncApiKey: apiKey } = outputs[name];

const result = await graphql(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { RemovalPolicy } from 'aws-cdk-lib';
import { Bucket, IBucket } from 'aws-cdk-lib/aws-s3';
import { Bucket, HttpMethods, IBucket } from 'aws-cdk-lib/aws-s3';
import { BucketDeployment, Source } from 'aws-cdk-lib/aws-s3-deployment';
import { Construct } from 'constructs';

Expand All @@ -8,6 +8,7 @@ export type CodegenAssetsProps = {
};

const MODEL_SCHEMA_KEY = 'model-schema.graphql';
const CONSOLE_SERVICE_ENDPOINT = 'https://*.console.aws.amazon.com/amplify';

/**
* Construct an S3 URI string for a given bucket and key.
Expand All @@ -30,6 +31,12 @@ export class CodegenAssets extends Construct {
const bucket = new Bucket(this, `${id}Bucket`, {
removalPolicy: RemovalPolicy.DESTROY,
autoDeleteObjects: true,
// Enabling CORS to allow console to access the codegen assets.
cors: [{
allowedMethods: [HttpMethods.GET, HttpMethods.HEAD],
allowedHeaders: ['*'],
allowedOrigins: [ CONSOLE_SERVICE_ENDPOINT ],
}],
});

const deployment = new BucketDeployment(this, `${id}Deployment`, {
Expand Down

0 comments on commit 5513930

Please sign in to comment.