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

apigateway: Can't set default authorization scopes when adding a proxy to a resource #29781

Closed
David-Jacobsen opened this issue Apr 10, 2024 · 4 comments · Fixed by #30035
Closed
Assignees
Labels
@aws-cdk/aws-apigateway Related to Amazon API Gateway @aws-cdk/aws-lambda Related to AWS Lambda bug This issue is a bug. effort/medium Medium work item – several days of effort p1

Comments

@David-Jacobsen
Copy link

David-Jacobsen commented Apr 10, 2024

Describe the bug

When trying to add a Proxy to a Resource, you can't set the default authorization scopes because it attempts to set the authorization scopes to the OPTIONS method despite the OPTIONS method intentionally not having any authorizer.

    const api = new apigw.RestApi(this, "Actions-ApiGateway", {
        defaultCorsPreflightOptions: {
          allowOrigins: apigw.Cors.ALL_ORIGINS,
          maxAge: Duration.days(10)
        },        
      });
    const root = api.root;
    const sendResource = root.addResource(`InitiateAction`)
    const sendLambdaIntegration = new apigw.LambdaIntegration(this.initiateAction.lambda);
    const sendProxy = sendResource.addProxy({
      defaultIntegration: sendLambdaIntegration,
      anyMethod: true,
      defaultMethodOptions: {
        authorizer: this.authorizer,
        authorizationType: apigw.AuthorizationType.COGNITO,
        // authorizationScopes: [`scopes`],
    },
      defaultCorsPreflightOptions: {
        allowOrigins: apigw.Cors.ALL_ORIGINS,
        allowMethods: apigw.Cors.ALL_METHODS
      }
    })

This works, and creates an InitiateAction resource with a proxy using the Cognito Authorizer as the authorizer. But if I uncomment the authorizationScopes line then it fails because it tries to assign the authorizationScopes to the OPTIONS method.

Expected Behavior

default authorization scopes are only applied to non-OPTIONS methods

Current Behavior

default authorization scopes are applied to all methods, including OPTIONS, which causing the deployment to fail.

Reproduction Steps

   const authorizer = authorizer = new apigw.CognitoUserPoolsAuthorizer(this, "Authorizer", {
        cognitoUserPools: [props.userPool],
      });
    const api = new apigw.RestApi(this, "Actions-ApiGateway", {
        defaultCorsPreflightOptions: {
          allowOrigins: apigw.Cors.ALL_ORIGINS,
          maxAge: Duration.days(10)
        },        
      });
    const root = api.root;
    const sendResource = root.addResource(`InitiateAction`)
    const sendLambdaIntegration = new apigw.LambdaIntegration(this.initiateAction.lambda);
    const sendProxy = sendResource.addProxy({
      defaultIntegration: sendLambdaIntegration,
      anyMethod: true,
      defaultMethodOptions: {
        authorizer: authorizer,
        authorizationType: apigw.AuthorizationType.COGNITO,
        // authorizationScopes: [`scope`],
    },
      defaultCorsPreflightOptions: {
        allowOrigins: apigw.Cors.ALL_ORIGINS,
        allowMethods: apigw.Cors.ALL_METHODS
      }
    })

Possible Solution

The generated cloud formation template shouldn't attempt to apply authorization scopes to the OPTIONS method.

Additional Information/Context

No response

CDK CLI Version

2.134.0 (build 265d769)

Framework Version

No response

Node.js Version

v18.19

OS

Mac OS 13.5.2 (22G91)

Language

TypeScript

Language Version

No response

Other information

No response

@David-Jacobsen David-Jacobsen added bug This issue is a bug. needs-triage This issue or PR still needs to be triaged. labels Apr 10, 2024
@github-actions github-actions bot added the @aws-cdk/aws-lambda Related to AWS Lambda label Apr 10, 2024
@pahud pahud changed the title aws-cdk-lib/aws-apigateway: Can't set default authorization scopes when adding a proxy to a resource apigateway: Can't set default authorization scopes when adding a proxy to a resource Apr 12, 2024
@github-actions github-actions bot added the @aws-cdk/aws-apigateway Related to Amazon API Gateway label Apr 12, 2024
@pahud
Copy link
Contributor

pahud commented Apr 12, 2024

I was not able to deploy this stack

export class DummyStack extends Stack {
  constructor(scope: Construct, id: string, props: StackProps) {
    super(scope, id, props);

    // create a cognito user pool
    const userPool = new cognito.UserPool(this, "UserPool", {
      selfSignUpEnabled: true,
      signInAliases: {
        email: true,
      },
    });

    const authorizer = new agw.CognitoUserPoolsAuthorizer(this, "Authorizer", {
      cognitoUserPools: [userPool],
    });

  const api = new agw.RestApi(this, "Actions-ApiGateway", {
      defaultCorsPreflightOptions: {
        allowOrigins: agw.Cors.ALL_ORIGINS,
        maxAge: Duration.days(10)
      },        
    });
  const root = api.root;
  const sendResource = root.addResource(`InitiateAction`)

  // prepare a dummy lambda function
  const dummyhandler = getLambdaFunction(this);

  const sendLambdaIntegration = new agw.LambdaIntegration(dummyhandler);
  const sendProxy = sendResource.addProxy({
    defaultIntegration: sendLambdaIntegration,
    anyMethod: true,
    defaultMethodOptions: {
      authorizer: authorizer,
      authorizationType: agw.AuthorizationType.COGNITO,
      authorizationScopes: [`scope`],
  },
    defaultCorsPreflightOptions: {
      allowOrigins: agw.Cors.ALL_ORIGINS,
      allowMethods: agw.Cors.ALL_METHODS
    }
  })
  }
}

Error msg:

12:52:11 PM | CREATE_FAILED | AWS::ApiGateway::Method | ActionsApiGatewayI...oxyOPTIONS041B022A
Resource handler returned message: "Invalid Method authorization type specified. Authorization Scopes are only valid for COGNITO_USER_POOLS authorization type (Servic
e: ApiGateway, Status Code: 400, Request ID: f9c6357b-428e-42a8-884c-07b77939d165)" (RequestToken: bb8de2e9-37b7-ca15-9bd8-547bc7eea134, HandlerErrorCode: InvalidRequ
est)

The synthesized template is having the resource which I believe is the root cause

 "ActionsApiGatewayInitiateActionproxyOPTIONS041B022A": {
   "Type": "AWS::ApiGateway::Method",
   "Properties": {
    "ApiKeyRequired": false,
    "AuthorizationScopes": [
     "scope"
    ],
    "AuthorizationType": "NONE",
    "HttpMethod": "OPTIONS",
    "Integration": {
     "IntegrationResponses": [
      {
       "ResponseParameters": {
        "method.response.header.Access-Control-Allow-Headers": "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'",
        "method.response.header.Access-Control-Allow-Origin": "'*'",
        "method.response.header.Access-Control-Allow-Methods": "'OPTIONS,GET,PUT,POST,DELETE,PATCH,HEAD'",
        "method.response.header.Access-Control-Max-Age": "'864000'"
       },
       "StatusCode": "204"
      }
     ],
     "RequestTemplates": {
      "application/json": "{ statusCode: 200 }"
     },
     "Type": "MOCK"
    },
    "MethodResponses": [
     {
      "ResponseParameters": {
       "method.response.header.Access-Control-Allow-Headers": true,
       "method.response.header.Access-Control-Allow-Origin": true,
       "method.response.header.Access-Control-Allow-Methods": true,
       "method.response.header.Access-Control-Max-Age": true
      },
      "StatusCode": "204"
     }
    ],
    "ResourceId": {
     "Ref": "ActionsApiGatewayInitiateActionproxyDD433460"
    },
    "RestApiId": {
     "Ref": "ActionsApiGatewayF80386B7"
    }
   },
   "Metadata": {
    "aws:cdk:path": "dummy-stack/Actions-ApiGateway/Default/InitiateAction/{proxy+}/OPTIONS/Resource"
   }
  },

For some reasons, cdk is adding AuthorizationScopes even AuthorizationType is NONE. I guess we probably need to check and fix the logic here.

It's not easy to work it around. Making this a p1 bug.

@pahud pahud added p1 effort/medium Medium work item – several days of effort and removed needs-triage This issue or PR still needs to be triaged. labels Apr 12, 2024
@GavinZZ GavinZZ self-assigned this May 1, 2024
@mergify mergify bot closed this as completed in #30035 May 10, 2024
mergify bot pushed a commit that referenced this issue May 10, 2024
…ognito (#30035)

### Issue # (if applicable)

Closes #29781

### Reason for this change

Authorization scope is set even when the auth type is None. This will cause deployment failure 
>12:52:11 PM | CREATE_FAILED | AWS::ApiGateway::Method | ActionsApiGatewayI...oxyOPTIONS041B022A
Resource handler returned message: "Invalid Method authorization type specified. Authorization Scopes are only valid for COGNITO_USER_POOLS authorization type (Servic
e: ApiGateway, Status Code: 400, Request ID: f9c6357b-428e-42a8-884c-07b77939d165)" (RequestToken: bb8de2e9-37b7-ca15-9bd8-547bc7eea134, HandlerErrorCode: InvalidRequ
est)

### Description of changes

Check when auth type is not Cognito, set auth scope to none. Not a breaking change because original templates cannot deploy.

### Description of how you validated changes

All existing and new tests pass.

### Checklist
- [ ] My code adheres to the [CONTRIBUTING GUIDE](https://github.com/aws/aws-cdk/blob/main/CONTRIBUTING.md) and [DESIGN GUIDELINES](https://github.com/aws/aws-cdk/blob/main/docs/DESIGN_GUIDELINES.md)

----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
Copy link

⚠️COMMENT VISIBILITY WARNING⚠️

Comments on closed issues are hard for our team to see.
If you need more assistance, please either tag a team member or open a new issue that references this one.
If you wish to keep having a conversation with other community members under this issue feel free to do so.

@aws-cdk-automation
Copy link
Collaborator

Comments on closed issues and PRs are hard for our team to see. If you need help, please open a new issue that references this one.

@aws aws locked as resolved and limited conversation to collaborators Jul 25, 2024
@GavinZZ
Copy link
Contributor

GavinZZ commented Jul 26, 2024

The original PR to fix this issue caused a regression issue. We've now managed to roll-forward with a fix in v2.148.1. If you have any questions/concerns, feel free to cut CDK another issue and reference this issue.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
@aws-cdk/aws-apigateway Related to Amazon API Gateway @aws-cdk/aws-lambda Related to AWS Lambda bug This issue is a bug. effort/medium Medium work item – several days of effort p1
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants