Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
161 changes: 161 additions & 0 deletions private-apigw-public-custom-domain/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
# Amazon Private API Gateway with VPC Endpoints and Public Domain

This pattern creates an Amazon Private API Gateway that is only accessible through VPC endpoints, with public custom domain name resolution for internal only access through an Amazon internal Application Load Balancer.

This architecture is intended for use cases which require private APIs, which are only accessible from on-premises via VPN or Direct Connect, while the DNS can be resolved publicly.

Learn more about this pattern at Serverless Land Patterns: [https://serverlessland.com/patterns/private-apigw-custom-domain](https://serverlessland.com/patterns/private-apigw-custom-domain)

Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example.

## Project Structure

```
├── app.py # CDK app entry point
├── cdk.json # CDK configuration
├── requirements.txt # Python dependencies
├── private_api_gateway/
│ ├── __init__.py
│ └── private_api_gateway_stack.py # Main stack definition
└── README.md # This file
```
## Architecture

- **VPC**: 10.0.0.0/16 with DNS support
- **Subnets**: 2 public + 2 private subnets across 2 AZs
- **NAT Gateway**: Managed by CDK in public subnets
- **Private API Gateway**: PetStore sample API with VPC endpoint restriction
- **Application Load Balancer**: Internal ALB for SSL termination
- **Lambda Automation**: Custom resource for VPC endpoint target registration

![image](architecture/architecture.png)

## Requirements
Create an AWS account if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.

* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
* [AWS Cloud Development Kit](https://docs.aws.amazon.com/cdk/v2/guide/getting-started.html) (AWS CDK) installed
* [Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-configuring.html) configured as DNS service and public hosted zone created
* [Public Certificate](https://docs.aws.amazon.com/acm/latest/userguide/acm-public-certificates.html) requested in Amazon Certificate Manager (ACM)
* [Python 3.12+](https://www.python.org/downloads/) installed


## Deployment Instructions

### 1. Install Dependencies
```bash
# Create virtual environment
python3 -m venv .venv

# Activate virtual environment
source .venv/bin/activate # or your venv activation command

# Install CDK dependencies
pip install -r requirements.txt
```

### 2. Get Parameters

You must provide both context parameters:

1. **domain_name**: Your custom domain name (e.g., api.example.com)
2. **certificate_arn**: ARN of your ACM certificate that covers the domain

### 3. CDK Deployment

```bash
# Deploy with both required parameters
cdk deploy \
-c domain_name=api.example.com \
-c certificate_arn=arn:aws:acm:region:account:certificate/certificate-id

# Example with subdomain
cdk deploy \
-c domain_name=privateapi.mycompany.com \
-c certificate_arn=arn:aws:acm:region:account:certificate/certificate-id
```

#### CDK Output

The stack provides this output:
- **ALBDNSName**: ALB DNS name for CNAME record


### 4. DNS Configuration

After deployment, you must create a DNS record in your domain's hosted zone:

1. **Get ALB DNS name** from CDK output
2. **Create CNAME record**:
```
api.example.com -> internal-alb-xxx.region.elb.amazonaws.com
```

## Testing

Test from within the VPC (EC2 instance or Client VPN):
```bash
curl https://api.example.com/pets
curl https://api.example.com/pets/2
```

### Expected Responses
```json
# GET /pets
[
{"id": 1, "type": "dog", "price": 249.99},
{"id": 2, "type": "cat", "price": 124.99},
{"id": 3, "type": "fish", "price": 0.99}
]

# GET /pets/2
{
"id": 2,
"type": "cat",
"price": 124.99
}
```

## Security Features

- API only accessible through VPC endpoint
- Security groups restrict access to VPC and Client VPN ranges
- ALB provides SSL termination with your certificate
- Resource policies enforce VPC endpoint access only

## Troubleshooting

### Certificate Issues
- Ensure certificate is in the same region
- Verify certificate covers your domain name
- Check certificate validation status

### DNS Issues
- Verify CNAME or ALIAS record points to ALB DNS name
- Check DNS propagation with `nslookup your-domain.com`

### Target Registration
- Manually check target group health in AWS Console
- Verify VPC endpoint has network interfaces created

## Cleanup

### Delete manually created Resources
- delete Amazon Route 53 Hosted Zone record
- delete Amazon Route 53 Public Hosted Zone
- delete Certificate in AWS Certificate Manager

### Delete CDK Deployment
```bash
cdk destroy -c domain_name=api.example.com -c certificate_arn=YOUR-CERT-ARN
```

-

----
Copyright 2025 Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: MIT-0

28 changes: 28 additions & 0 deletions private-apigw-public-custom-domain/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#!/usr/bin/env python3
import aws_cdk as cdk
from private_api_gateway.private_api_gateway_stack import PrivateApiGatewayStack

app = cdk.App()

# Get required context parameters
domain_name = app.node.try_get_context("domain_name")
certificate_arn = app.node.try_get_context("certificate_arn")

if not domain_name:
raise ValueError("domain_name context parameter is required. Use: cdk deploy -c domain_name=api.example.com")

if not certificate_arn:
raise ValueError("certificate_arn context parameter is required. Use: cdk deploy -c certificate_arn=arn:aws:acm:...")

PrivateApiGatewayStack(
app,
"PrivateApiGatewayStack",
domain_name=domain_name,
certificate_arn=certificate_arn,
env=cdk.Environment(
account=app.account,
region=app.region
)
)

app.synth()
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
56 changes: 56 additions & 0 deletions private-apigw-public-custom-domain/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
{
"app": "python app.py",
"watch": {
"include": [
"**"
],
"exclude": [
"README.md",
"cdk*.json",
"requirements*.txt",
"source.bat",
"**/__pycache__",
"**/*.pyc"
]
},
"context": {
"@aws-cdk/aws-lambda:recognizeLayerVersion": true,
"@aws-cdk/core:checkSecretUsage": true,
"@aws-cdk/core:target-partitions": [
"aws",
"aws-cn"
],
"@aws-cdk-containers/ecs-service-extensions:enableDefaultLogDriver": true,
"@aws-cdk/aws-ec2:uniqueImdsv2TemplateName": true,
"@aws-cdk/aws-ecs:arnFormatIncludesClusterName": true,
"@aws-cdk/aws-iam:minimizePolicies": true,
"@aws-cdk/core:validateSnapshotRemovalPolicy": true,
"@aws-cdk/aws-codepipeline:crossAccountKeyAliasStackSafeResourceName": true,
"@aws-cdk/aws-s3:createDefaultLoggingPolicy": true,
"@aws-cdk/aws-sns-subscriptions:restrictSqsDescryption": true,
"@aws-cdk/aws-apigateway:disableCloudWatchRole": false,
"@aws-cdk/core:enablePartitionLiterals": true,
"@aws-cdk/aws-events:eventsTargetQueueSameAccount": true,
"@aws-cdk/aws-iam:standardizedServicePrincipals": true,
"@aws-cdk/aws-ecs:disableExplicitDeploymentControllerForCircuitBreaker": true,
"@aws-cdk/aws-iam:importedRoleStackSafeDefaultPolicyName": true,
"@aws-cdk/aws-s3:serverAccessLogsUseBucketPolicy": true,
"@aws-cdk/aws-route53-patters:useCertificate": true,
"@aws-cdk/customresources:installLatestAwsSdkDefault": false,
"@aws-cdk/aws-rds:databaseProxyUniqueResourceName": true,
"@aws-cdk/aws-codedeploy:removeAlarmsFromDeploymentGroup": true,
"@aws-cdk/aws-apigateway:authorizerChangeDeploymentLogicalId": true,
"@aws-cdk/aws-ec2:launchTemplateDefaultUserData": true,
"@aws-cdk/aws-secretsmanager:useAttachedSecretResourcePolicyForSecretTargetAttachments": true,
"@aws-cdk/aws-redshift:columnId": true,
"@aws-cdk/aws-stepfunctions-tasks:enableLoggingConfiguration": true,
"@aws-cdk/aws-ec2:restrictDefaultSecurityGroup": true,
"@aws-cdk/aws-apigateway:requestValidatorUniqueId": true,
"@aws-cdk/aws-kms:aliasNameRef": true,
"@aws-cdk/aws-autoscaling:generateLaunchTemplateInsteadOfLaunchConfig": true,
"@aws-cdk/core:includePrefixInUniqueNameGeneration": true,
"@aws-cdk/aws-efs:denyAnonymousAccess": true,
"@aws-cdk/aws-opensearchservice:enableLogging": true,
"@aws-cdk/aws-lambda:useLatestRuntimeVersion": true
}
}
63 changes: 63 additions & 0 deletions private-apigw-public-custom-domain/example-pattern.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
{
"title": "Private API Gateway with a public custom domain",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"title": "Private API Gateway with a public custom domain",
"title": "Amazon Private API Gateway with a public custom domain",

"description": "Create a Amazon Private API Gateway with a public custom domain.",
"language": "Python",
"level": "200",
"framework": "AWS CDK",
"introBox": {
"headline": "How it works",
"text": [
"This pattern creates an Amazon Private API Gateway that is only accessible through VPC endpoints, with public custom domain name resolution for internal only access through an Amazon internal Application Load Balancer.",
"This architecture is intended for use cases which require private APIs, which are only accessible from on-premises via VPN or Direct Connect, while the DNS can be resolved publicly."
]
},
"gitHub": {
"template": {
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/private-apigw-public-custom-domain",
"templateURL": "serverless-patterns/private-apigw-public-custom-domain",
"projectFolder": "private-apigw-public-custom-domain",
"templateFile": "private_api_gateway/private_api_gateway_stack.py"
}
},
"resources": {
"bullets": [
{
"text": "Private REST APIs in API Gateway",
"link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-apis.html"
},
{
"text": "Working with public hosted zones",
"link": "https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/AboutHZWorkingWith.html"
},
{
"text": "Create an Application Load Balancer",
"link": "https://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-application-load-balancer.html"
}
]
},
"deploy": {
"text": [
"cdk deploy"
]
},
"testing": {
"text": [
"See the GitHub repo for detailed testing instructions."
]
},
"cleanup": {
"text": [
"Delete the stack: <code>cdk destroy</code>."
]
},
"authors": [
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please include the bio field for all authors

{
"name": "Nils Brandes",
"linkedin": "nils-brandes"
},
{
"name": "Bruno Quintas",
"linkedin": "brunoquintas"
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

Loading