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

feat(api): enable cors on codegen asset bucket #2366

Merged
Merged
Show file tree
Hide file tree
Changes from 4 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
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 | null => {
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 BUCKET_NAME_INDEX = 2;
if (!matches) {
return null;
}
if (matches.length && matches.length > BUCKET_NAME_INDEX) {
return matches[BUCKET_NAME_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;
dzhan-aws marked this conversation as resolved.
Show resolved Hide resolved
};
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
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 +34,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://${region}.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 { RemovalPolicy, Fn } from 'aws-cdk-lib';
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,11 @@ export type CodegenAssetsProps = {
};

const MODEL_SCHEMA_KEY = 'model-schema.graphql';
const CONSOLE_SERVICE_ENDPOINT = Fn.join('', [
'https://',
Fn.ref('AWS::Region'),
'.console.aws.amazon.com/amplify',
]);

/**
* Construct an S3 URI string for a given bucket and key.
Expand All @@ -30,6 +35,14 @@ 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
Loading