本記事で検証した内容は実験的なものですので、実環境へ導入する際は自己責任でお願いします。
はじめに
VPC Endpoint を設定している環境で、API Gateway の Regional API または Edge API にアクセスすると 403 エラーが発生することがあります。
これは VPC Endpoint の Private DNS が以下のように機能して発生します。
※以降の図で、波線矢印は名前解決の流れを表しています
これを解消するには、カスタムドメインで Regional / Edge API にアクセスするか、
Private DNS を無効にして、Private API と VPC Endpoint を関連付けすることで生成される以下のようなURLを介して Private API にアクセスする必要があります。
https://{rest-api-id}-{vpce-id}.execute-api.{region}.amazonaws.com/{stage}
VPC から API Gateway API に接続するときに HTTP 403 Forbidden エラーが発生するのは何故ですか?
プライベート API を呼び出す方法
しかし、
- Regional / Edge API にカスタムドメインを用意するのは難しいが (外部システムなど)
- VPC Endpoint ID が含まれないシンプルな URL で Private API にアクセスしたい
という場合を考慮して、Route53 Resolver の Outbound Rule を使ってこれを実現できないか検証してみました。
検証に利用した CloudFormation テンプレートは、本記事の末尾に載せました。
検証してみた
VPC Endpoint と Route53 Resolver Outbound Rule の有無でフェーズ1, 2, 3 に分けました。
フェーズ1
フェーズ1 は、VPC Endpoint も Outbound Rule も無い状態です。
図中の VPC Lambda は各 API にアクセスし、API が使っているIPアドレスと API のレスポンスを表示します。
VPC Lambda をテスト実行すると以下のようになりました。
フェーズ1の図の通り、
- Regional / Edge API に Public IP でアクセスし、
- Private API のエンドポイントの名前解決が出来ていない
ということが分かります。
フェーズ2
フェーズ2には、Private DNS が有効化された VPC Endpoint が配置されています。
VPC Lambda をテスト実行すると以下のようになりました。
フェーズ2の図の通り、
- 全ての API に Private IP でアクセスし、
- Regional / Edge API へのアクセスは Forbidden となっている
ということが分かります。
フェーズ3
こちらが本記事のキモです。
フェーズ3は、フェーズ2に Route53 Resolver Outbound Rule を追加した形になっています。
Outbound Rule により Regional / Edge API のドメイン名の名前解決を 8.8.8.8 (Google Public DNS) に転送します。
VPC Lambda をテスト実行すると以下のようになりました。
フェーズ3の図の通り、
- Regional / Edge API へ Public IP でアクセスし、
- Private API へ Private IP でアクセスしている
- いずれの API にもアクセス出来ている
という結果になりました。
CloudFormationテンプレート
VPC Lambda が利用しているレイヤーの関係で、本テンプレートそのままだと東京リージョンでしか動作しません。
別リージョンへ展開する場合はこちらを参考に該当部分を適宜修正ください。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 |
AWSTemplateFormatVersion: 2010-09-09 Transform: AWS::Serverless-2016-10-31 Parameters: ResourcePrefix: Type: String Default: "api-r53" Phase: Type: String Default: "1" AllowedValues: - "1" - "2" - "3" Conditions: Phase2: !Equals - !Ref Phase - "2" Phase3: !Equals - !Ref Phase - "3" AfterPhase2: !Or - !Condition Phase2 - !Condition Phase3 Resources: # ------------------------------------------------------------# # Networking # ------------------------------------------------------------# VPC: Type: AWS::EC2::VPC Properties: CidrBlock: 10.0.0.0/16 EnableDnsSupport: true EnableDnsHostnames: true Tags: - Key: Name Value: !Sub ${ResourcePrefix}-vpc-{{resolve:ssm:${RandomIdParameter}}} PublicSubnet: Type: AWS::EC2::Subnet Properties: CidrBlock: 10.0.0.0/24 MapPublicIpOnLaunch: false VpcId: !Ref VPC AvailabilityZone: ap-northeast-1a Tags: - Key: Name Value: !Sub ${ResourcePrefix}-public-subnet-{{resolve:ssm:${RandomIdParameter}}} PrivateSubnet: Type: AWS::EC2::Subnet Properties: CidrBlock: 10.0.1.0/24 MapPublicIpOnLaunch: false VpcId: !Ref VPC AvailabilityZone: ap-northeast-1a Tags: - Key: Name Value: !Sub ${ResourcePrefix}-private-subnet-{{resolve:ssm:${RandomIdParameter}}} InternetGateway: Type: AWS::EC2::InternetGateway Properties: Tags: - Key: Name Value: !Sub ${ResourcePrefix}-igw-{{resolve:ssm:${RandomIdParameter}}} InternetGatewayAttachment: Type: AWS::EC2::VPCGatewayAttachment Properties: InternetGatewayId : !Ref InternetGateway VpcId: !Ref VPC RouteTableForPublicSubnet: Type: AWS::EC2::RouteTable Properties: VpcId: !Ref VPC Tags: - Key: Name Value: !Sub ${ResourcePrefix}-public-route-table-{{resolve:ssm:${RandomIdParameter}}} RouteForPublicSubnet: Type: AWS::EC2::Route Properties: RouteTableId: !Ref RouteTableForPublicSubnet DestinationCidrBlock: 0.0.0.0/0 GatewayId: !Ref InternetGateway AssocciateRouteTableForPublicSubnet: Type: AWS::EC2::SubnetRouteTableAssociation Properties: RouteTableId: !Ref RouteTableForPublicSubnet SubnetId: !Ref PublicSubnet Eip: Type: AWS::EC2::EIP Properties: Domain: vpc Tags: - Key: Name Value: !Sub ${ResourcePrefix}-eip-{{resolve:ssm:${RandomIdParameter}}} NatGateway: Type: AWS::EC2::NatGateway Properties: AllocationId: !GetAtt Eip.AllocationId SubnetId: !Ref PublicSubnet Tags: - Key: Name Value: !Sub ${ResourcePrefix}-nat-gateway-{{resolve:ssm:${RandomIdParameter}}} RouteTableForPrivateSubnet: Type: AWS::EC2::RouteTable Properties: VpcId: !Ref VPC Tags: - Key: Name Value: !Sub ${ResourcePrefix}-private-route-table-{{resolve:ssm:${RandomIdParameter}}} RouteForPrivateSubnet: Type: AWS::EC2::Route Properties: RouteTableId: !Ref RouteTableForPrivateSubnet DestinationCidrBlock: 0.0.0.0/0 NatGatewayId: !Ref NatGateway AssocciateRouteTableForPrivateSubnet: Type: AWS::EC2::SubnetRouteTableAssociation Properties: RouteTableId: !Ref RouteTableForPrivateSubnet SubnetId: !Ref PrivateSubnet # ------------------------------------------------------------# # VPC Endpoint for API Gateway # ------------------------------------------------------------# VpcEndpoint: Type: AWS::EC2::VPCEndpoint Condition: AfterPhase2 Properties: ServiceName: !Sub "com.amazonaws.${AWS::Region}.execute-api" VpcEndpointType: Interface PrivateDnsEnabled: true VpcId: !Ref VPC SubnetIds: - !Ref PrivateSubnet SecurityGroupIds: - !Ref VpcEndpointSecurityGroup VpcEndpointSecurityGroup: Type: AWS::EC2::SecurityGroup Condition: AfterPhase2 Properties: GroupName: !Sub ${ResourcePrefix}-vpc-endpoint-sg-{{resolve:ssm:${RandomIdParameter}}} GroupDescription: security group for vpc endpoint of api gateway VpcId: !Ref VPC SecurityGroupIngress: - IpProtocol: tcp FromPort: 443 ToPort: 443 CidrIp: !GetAtt VPC.CidrBlock SecurityGroupEgress: - IpProtocol: "-1" CidrIp: 0.0.0.0/0 # ------------------------------------------------------------# # Route53 Resolver # ------------------------------------------------------------# ResolverRuleForEdgeApi: Type: AWS::Route53Resolver::ResolverRule Condition: Phase3 Properties: DomainName: !Sub ${EdgeApi}.execute-api.${AWS::Region}.amazonaws.com Name: !Sub ${ResourcePrefix}-edge-api-resolver-rule-{{resolve:ssm:${RandomIdParameter}}} ResolverEndpointId: !Ref ResolverEndpoint RuleType: FORWARD TargetIps: - Ip: 8.8.8.8 Port: 53 ResolverRuleAssociationForEdgeApi: Type: AWS::Route53Resolver::ResolverRuleAssociation Condition: Phase3 Properties: Name: !Sub ${ResourcePrefix}-edge-api-resolver-rule-association-{{resolve:ssm:${RandomIdParameter}}} ResolverRuleId: !GetAtt ResolverRuleForEdgeApi.ResolverRuleId VPCId: !Ref VPC ResolverRuleForRegionalApi: Type: AWS::Route53Resolver::ResolverRule Condition: Phase3 Properties: DomainName: !Sub ${RegionalApi}.execute-api.${AWS::Region}.amazonaws.com Name: !Sub ${ResourcePrefix}-regional-api-resolver-rule-{{resolve:ssm:${RandomIdParameter}}} ResolverEndpointId: !Ref ResolverEndpoint RuleType: FORWARD TargetIps: - Ip: 8.8.8.8 Port: 53 ResolverRuleAssociationForRegionalApi: Type: AWS::Route53Resolver::ResolverRuleAssociation Condition: Phase3 Properties: Name: !Sub ${ResourcePrefix}-regional-api-resolver-rule-association-{{resolve:ssm:${RandomIdParameter}}} ResolverRuleId: !GetAtt ResolverRuleForRegionalApi.ResolverRuleId VPCId: !Ref VPC ResolverEndpoint: Type: AWS::Route53Resolver::ResolverEndpoint Condition: Phase3 Properties: Direction: OUTBOUND IpAddresses: # 2つ以上指定が必要 - SubnetId: !Ref PrivateSubnet - SubnetId: !Ref PrivateSubnet Name: !Sub ${ResourcePrefix}-resolver-endpoint-{{resolve:ssm:${RandomIdParameter}}} SecurityGroupIds: - !Ref ResolverEndpointSecurityGroup ResolverEndpointSecurityGroup: Type: AWS::EC2::SecurityGroup Condition: Phase3 Properties: GroupName: !Sub ${ResourcePrefix}-resolver-endpoint-sg-{{resolve:ssm:${RandomIdParameter}}} GroupDescription: security group for route53 resolver endpoint VpcId: !Ref VPC SecurityGroupIngress: - IpProtocol: tcp FromPort: 53 ToPort: 53 CidrIp: !GetAtt VPC.CidrBlock - IpProtocol: udp FromPort: 53 ToPort: 53 CidrIp: !GetAtt VPC.CidrBlock SecurityGroupEgress: - IpProtocol: "-1" CidrIp: 0.0.0.0/0 # ------------------------------------------------------------# # VPC Lambda # ------------------------------------------------------------# VpcLambda: Type: AWS::Serverless::Function DependsOn: VpcLambdaLog Properties: FunctionName: !Sub ${ResourcePrefix}-vpc-function-{{resolve:ssm:${RandomIdParameter}}} InlineCode: | import logging import os import socket import requests logger = logging.getLogger() logger.setLevel(os.environ['LOG_LEVEL']) def lambda_handler(event, context): logger.info('\n'.join([ '', '# Edge API', get_output(url=os.environ['EDGE_API_URL']), '', '# Regional API Response', get_output(url=os.environ['REGIONAL_API_URL']), '', '# Private API Response', get_output(url=os.environ['PRIVATE_API_URL']), ])) def get_output(url:str) -> str: domain_name = url.split('/')[2] output = '\n'.join([ f'IP: {get_ip(domain_name)}', f'Response: {requests_get(url)}', ]) return output def get_ip(domain_name:str) -> str: try: return socket.gethostbyname(domain_name) except Exception as e: return str(e) def requests_get(url:str) -> str: try: return requests.get(url).content.decode('ascii') except requests.exceptions.RequestException as e: return str(e) Handler: index.lambda_handler Environment: Variables: LOG_LEVEL: INFO EDGE_API_URL: !Sub https://${EdgeApi}.execute-api.${AWS::Region}.amazonaws.com/prod REGIONAL_API_URL: !Sub https://${RegionalApi}.execute-api.${AWS::Region}.amazonaws.com/prod PRIVATE_API_URL: !Sub https://${PrivateApi}.execute-api.${AWS::Region}.amazonaws.com/prod Runtime: python3.8 Timeout: 10 MemorySize: 128 VpcConfig: SecurityGroupIds: - !Ref VpcLambdaSecurityGroup SubnetIds: - !Ref PrivateSubnet Layers: # "Python Toolkit" on https://github.com/mthenw/awesome-layers - arn:aws:lambda:ap-northeast-1:770693421928:layer:Klayers-python38-requests:24 Policies: - Version: 2012-10-17 Statement: - Effect: Allow Action: - logs:CreateLogGroup Resource: !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:* - Effect: Allow Action: - logs:CreateLogStream - logs:PutLogEvents Resource: !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/${ResourcePrefix}-vpc-function-{{resolve:ssm:${RandomIdParameter}}}:* VpcLambdaSecurityGroup: Type: AWS::EC2::SecurityGroup Properties: GroupName: !Sub ${ResourcePrefix}-vpc-function-sg-{{resolve:ssm:${RandomIdParameter}}} GroupDescription: security group for vpc lambda function VpcId: !Ref VPC SecurityGroupEgress: - IpProtocol: "-1" CidrIp: 0.0.0.0/0 VpcLambdaLog: Type: AWS::Logs::LogGroup Properties: LogGroupName: !Sub /aws/lambda/${ResourcePrefix}-vpc-function-{{resolve:ssm:${RandomIdParameter}}} RetentionInDays: 7 # ------------------------------------------------------------# # API Gateway + Lambda # ------------------------------------------------------------# EdgeApi: Type: AWS::Serverless::Api Properties: Name: !Sub ${ResourcePrefix}-edge-api-{{resolve:ssm:${RandomIdParameter}}} StageName: prod EndpointConfiguration: Type: EDGE RegionalApi: Type: AWS::Serverless::Api Properties: Name: !Sub ${ResourcePrefix}-regional-api-{{resolve:ssm:${RandomIdParameter}}} StageName: prod EndpointConfiguration: Type: REGIONAL PrivateApi: Type: AWS::Serverless::Api Properties: Name: !Sub ${ResourcePrefix}-private-api-{{resolve:ssm:${RandomIdParameter}}} StageName: prod EndpointConfiguration: Type: PRIVATE Auth: ResourcePolicy: IntrinsicVpcWhitelist: - !Ref VPC ApiLambda: Type: AWS::Serverless::Function DependsOn: ApiLambdaLog Properties: FunctionName: !Sub ${ResourcePrefix}-api-function-{{resolve:ssm:${RandomIdParameter}}} InlineCode: | def lambda_handler(event, context): return { 'isBase64Encoded': False, 'statusCode': 200, 'headers': {}, 'body': '{"message": "Hello from AWS Lambda"}' } Handler: index.lambda_handler Runtime: python3.8 Timeout: 10 MemorySize: 128 Events: EdgeApiEvent: Type: Api Properties: Path: / Method: get RestApiId: !Ref EdgeApi RegionalApiEvent: Type: Api Properties: Path: / Method: get RestApiId: !Ref RegionalApi PrivateApiEvent: Type: Api Properties: Path: / Method: get RestApiId: !Ref PrivateApi Policies: - Version: 2012-10-17 Statement: - Effect: Allow Action: - logs:CreateLogGroup Resource: !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:* - Effect: Allow Action: - logs:CreateLogStream - logs:PutLogEvents Resource: !Sub arn:aws:logs:${AWS::Region}:${AWS::AccountId}:log-group:/aws/lambda/${ResourcePrefix}-api-function-{{resolve:ssm:${RandomIdParameter}}}:* ApiLambdaLog: Type: AWS::Logs::LogGroup Properties: LogGroupName: !Sub /aws/lambda/${ResourcePrefix}-api-function-{{resolve:ssm:${RandomIdParameter}}} RetentionInDays: 7 # ------------------------------------------------------------# # Supplemental Resources # ------------------------------------------------------------# RandomIdParameter: Type: AWS::SSM::Parameter Properties: Name: !Join - '/' - - !Sub /${ResourcePrefix} - !Select [ '0', !Split [ '-', !Select [ '2', !Split [ '/', !Ref AWS::StackId ] ] ] ] - random-id Type: String Value: !Select [ '0', !Split [ '-', !Select [ '2', !Split [ '/', !Ref AWS::StackId ] ] ] ] |
投稿者プロフィール
- 2015年8月入社。弊社はインフラ屋ですが、アプリも作ってみたいです。