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

(API Gateway): (Authorizer must be attached to a RestApi.) #30320

Closed
awsrookie18 opened this issue May 23, 2024 · 5 comments
Closed

(API Gateway): (Authorizer must be attached to a RestApi.) #30320

awsrookie18 opened this issue May 23, 2024 · 5 comments
Assignees
Labels
@aws-cdk/aws-route53 Related to Amazon Route 53 bug This issue is a bug. closed-for-staleness This issue was automatically closed because it hadn't received any attention in a while. needs-reproduction This issue needs reproduction. response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 7 days.

Comments

@awsrookie18
Copy link

awsrookie18 commented May 23, 2024

Describe the bug

Getting the above error

const hostedZone = route53.HostedZone.fromHostedZoneAttributes(
   stack,
   `${environmentProps.environmentName}-${uniqueId}-route53-zone-${domainDetails.name}`,
   {
     zoneName: domainDetails.hostedZoneName,
     hostedZoneId: domainDetails.hostedZoneId
   }
 );
 // AWS Certificate Manager will generate a certificate for the front end domain name. Ownership
 // is validated via DNS validation method.
 const certificate = new acm.DnsValidatedCertificate(
   stack,
   `${environmentProps.environmentName}-${uniqueId}-acm-cert${domainDetails.hostedZoneName}`,
   {
     domainName,
     hostedZone,
     region: environmentProps.env?.region
   }
 );

 // Create a REST API
 const restApi = new apigateway.RestApi(
   stack,
   `${domainDetails.hostedZoneName}-${environmentProps.environmentName}-${uniqueId}-rest-api-id`,
   {
     domainName: {
       domainName,
       certificate,
       securityPolicy: apigateway.SecurityPolicy.TLS_1_2
     }
   }
 );

 // Create an A record for the domain
 new route53.ARecord(
   stack,
   `${domainDetails.hostedZoneName}-${environmentProps.environmentName}-route53-${uniqueId}-Arecord`,
   {
     recordName: domainName,
     target: route53.RecordTarget.fromAlias(new targets.ApiGateway(restApi)),
     zone: hostedZone
   }
 );
 return restApi;



 const domainName = `api.sharedservice.${guardianDetails.hostedZoneName}`.replace(/\//g, '');

 // This will create the custom api gateway based on the domain name.
 const restApi = createCustomApiGateway(guardianDetails, stack, environmentProps, domainName, 'shared-service');

 const sessionAuthorizerPropsDetails: any = {
   namespace: stage,
   isProduction: environmentProps.accountEnvProps.isProduction,
   productName: Constants.SessionTableProductName,
   region: environmentProps.accountEnvProps.env.region,
   account: environmentProps.accountEnvProps.env.account,
   cookieName: Constants.sessionToken
 };

 // New function which creates authorizer for us.
 const sessionAuthorizerDetail = createSessionAuthorizer(stack, sessionAuthorizerPropsDetails);

 // Attach the authorizer which is created in portal gateway
 /* eslint-disable camelcase */
 const authorizer = new apiGateway.RequestAuthorizer(
   stack,
   `${environmentProps.environmentName}-bffpk-authorizer-api`,
   {
     handler: sessionAuthorizerDetail.lambdaApiAuthorizer as unknown as IFunction,
     /* eslint-disable camelcase */
     identitySources: sessionAuthorizerDetail.identitySources,
     
     resultsCacheTtl: Duration.seconds(0) // Disable cache on authorizer
   }
 );

 // lambda function
 const featureFlagFunction = new CustomNodejsFunction(
   stack,
   `${environmentProps.environmentName}-lambda-feature-flag-function`,
   {
     entry: path.join(__dirname, '../../../../functions/api/sharedservices/featureflag/src/feature-flag-handler.ts'),
     architecture: Architecture.ARM_64,
     timeout: Duration.seconds(30),
     runtime: Runtime.NODEJS_18_X,
     memorySize: lambdaMemoryValue,
     ephemeralStorageSize: Size.mebibytes(lambdaEphemeralStorageValue),
     role,
     handler: 'featureflag',
     environment: { ...environment, FUNCTION_NAME: 'feature-flag-handler' }
   },
   props.envProps
 );

 // Grant decrypt permission to the lambda function
 props.launchDarklyKmsKey.grantDecrypt(featureFlagFunction);

 // Add an integration with the Lambda function
 const featureFlagResource = restApi.root.addResource('featureflag');

 // Add method along with integration lambda with api gateway
 featureFlagResource.addMethod('POST', new apiGateway.LambdaIntegration(featureFlagFunction), {
   authorizer,
   authorizationType: AuthorizationType.CUSTOM
 });

Note - createSessionAuthorizer is coming from separate package.

Error: Resolution error: Resolution error: Resolution error: Authorizer
must be attached to a RestApi.
Object creation stack:
at Execute again with CDK_DEBUG=true to capture stack traces..

Expected Behavior

Authorizer should be attached to Api gateway.

Current Behavior

It is failing with Authorizer must be attached to a RestApi.

Reproduction Steps

Provided the code above.


const hostedZone = route53.HostedZone.fromHostedZoneAttributes(
    stack,
    `${environmentProps.environmentName}-${uniqueId}-route53-zone-${domainDetails.name}`,
    {
      zoneName: domainDetails.hostedZoneName,
      hostedZoneId: domainDetails.hostedZoneId
    }
  );
  // AWS Certificate Manager will generate a certificate for the front end domain name. Ownership
  // is validated via DNS validation method.
  const certificate = new acm.DnsValidatedCertificate(
    stack,
    `${environmentProps.environmentName}-${uniqueId}-acm-cert${domainDetails.hostedZoneName}`,
    {
      domainName,
      hostedZone,
      region: environmentProps.env?.region
    }
  );

  // Create a REST API
  const restApi = new apigateway.RestApi(
    stack,
    `${domainDetails.hostedZoneName}-${environmentProps.environmentName}-${uniqueId}-rest-api-id`,
    {
      domainName: {
        domainName,
        certificate,
        securityPolicy: apigateway.SecurityPolicy.TLS_1_2
      }
    }
  );

  // Create an A record for the domain
  new route53.ARecord(
    stack,
    `${domainDetails.hostedZoneName}-${environmentProps.environmentName}-route53-${uniqueId}-Arecord`,
    {
      recordName: domainName,
      target: route53.RecordTarget.fromAlias(new targets.ApiGateway(restApi)),
      zone: hostedZone
    }
  );
  return restApi;



  const domainName = `api.sharedservice.${guardianDetails.hostedZoneName}`.replace(/\//g, '');

  // This will create the custom api gateway based on the domain name.
  const restApi = createCustomApiGateway(guardianDetails, stack, environmentProps, domainName, 'shared-service');

  const sessionAuthorizerPropsDetails: any = {
    namespace: stage,
    isProduction: environmentProps.accountEnvProps.isProduction,
    productName: Constants.SessionTableProductName,
    region: environmentProps.accountEnvProps.env.region,
    account: environmentProps.accountEnvProps.env.account,
    cookieName: Constants.sessionToken
  };

  // New function which creates authorizer for us.
  const sessionAuthorizerDetail = createSessionAuthorizer(stack, sessionAuthorizerPropsDetails);

  // Attach the authorizer which is created in portal gateway
  /* eslint-disable camelcase */
  const authorizer = new apiGateway.RequestAuthorizer(
    stack,
    `${environmentProps.environmentName}-bffpk-authorizer-api`,
    {
      handler: sessionAuthorizerDetail.lambdaApiAuthorizer as unknown as IFunction,
      /* eslint-disable camelcase */
      identitySources: sessionAuthorizerDetail.identitySources,
      
      resultsCacheTtl: Duration.seconds(0) // Disable cache on authorizer
    }
  );

  // lambda function
  const featureFlagFunction = new CustomNodejsFunction(
    stack,
    `${environmentProps.environmentName}-lambda-feature-flag-function`,
    {
      entry: path.join(__dirname, '../../../../functions/api/sharedservices/featureflag/src/feature-flag-handler.ts'),
      architecture: Architecture.ARM_64,
      timeout: Duration.seconds(30),
      runtime: Runtime.NODEJS_18_X,
      memorySize: lambdaMemoryValue,
      ephemeralStorageSize: Size.mebibytes(lambdaEphemeralStorageValue),
      role,
      handler: 'featureflag',
      environment: { ...environment, FUNCTION_NAME: 'feature-flag-handler' }
    },
    props.envProps
  );

  // Grant decrypt permission to the lambda function
  props.launchDarklyKmsKey.grantDecrypt(featureFlagFunction);

  // Add an integration with the Lambda function
  const featureFlagResource = restApi.root.addResource('featureflag');

  // Add method along with integration lambda with api gateway
  featureFlagResource.addMethod('POST', new apiGateway.LambdaIntegration(featureFlagFunction), {
    authorizer,
    authorizationType: AuthorizationType.CUSTOM
  });

Note - createSessionAuthorizer is coming from separate package.

Error: Resolution error: Resolution error: Resolution error: Authorizer
must be attached to a RestApi.
Object creation stack:
at Execute again with CDK_DEBUG=true to capture stack traces..

Possible Solution

No response

Additional Information/Context

No response

CDK CLI Version

2.118.0

Framework Version

No response

Node.js Version

18

OS

windows

Language

TypeScript

Language Version

No response

Other information

No response

@awsrookie18 awsrookie18 added bug This issue is a bug. needs-triage This issue or PR still needs to be triaged. labels May 23, 2024
@github-actions github-actions bot added the @aws-cdk/aws-route53 Related to Amazon Route 53 label May 23, 2024
@ashishdhingra ashishdhingra self-assigned this May 24, 2024
@ashishdhingra ashishdhingra added needs-reproduction This issue needs reproduction. and removed needs-triage This issue or PR still needs to be triaged. labels May 24, 2024
@typefox09
Copy link

Having this same issue.

@ashishdhingra
Copy link
Contributor

@awsrookie18 Good afternoon. Please share the following:

  • Why are you creating a separate RequestAuthorizer from your customSessionAuthorizer()? Does customSessionAuthorizer() returns an authorizer which is somehow not associated with RestApi?
    • Most likely the error is thrown at lazyRestApiId when Rest API Id is not associated with authorizer.
  • Could you please share the complete stack trace of the failure?

Found useful article API Gateway Lambda Custom Authorizer with AWS CDK for reference.

Thanks,
Ashish

@ashishdhingra ashishdhingra added the response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 7 days. label May 28, 2024
Copy link

This issue has not received a response in a while. If you want to keep this issue open, please leave a comment below and auto-close will be canceled.

@github-actions github-actions bot added the closing-soon This issue will automatically close in 4 days unless further comments are made. label May 31, 2024
@github-actions github-actions bot added closed-for-staleness This issue was automatically closed because it hadn't received any attention in a while. and removed closing-soon This issue will automatically close in 4 days unless further comments are made. labels Jun 5, 2024
@github-actions github-actions bot closed this as completed Jun 5, 2024
@bramski
Copy link

bramski commented Jul 11, 2024

Arrived here from search for this error as I'm encountering asimilar issue. Was there a resolution?

@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
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
@aws-cdk/aws-route53 Related to Amazon Route 53 bug This issue is a bug. closed-for-staleness This issue was automatically closed because it hadn't received any attention in a while. needs-reproduction This issue needs reproduction. response-requested Waiting on additional info and feedback. Will move to "closing-soon" in 7 days.
Projects
None yet
Development

No branches or pull requests

5 participants