1
0

initial commit

This commit is contained in:
xpk
2026-02-13 15:44:24 +08:00
parent 66be8224f4
commit 09ce4c881a
570 changed files with 61807 additions and 0 deletions
+16
View File
@@ -0,0 +1,16 @@
def lambda_handler(event, context):
# Extract query parameters from the event
params = event.get('queryStringParameters', {})
# Print all query parameters
print("Received query parameters:", params)
# Example: If you want to print a specific parameter, e.g., 'param1'
if params and 'inputValue' in params:
print("Value of 'inputValue':", params['inputValue'])
# You can return the input parameters as response if needed
return {
'statusCode': 200,
'body': f"Received parameters: {params}"
}
+74
View File
@@ -0,0 +1,74 @@
<!-- This readme file is generated with terraform-docs -->
# ApigwAuthSample
A working example which deploys HTTP api, Lambda functions, and necessary permissions.
## Testing the API
To test this in postman, put in the following settings:
URL: https://<api-id>.execute-api.ap-east-1.amazonaws.com/?inputValue=TestMessage123
Authorization: api key, key = Authorizations, value = sha256 hash, add to = Header
## Requirements
| Name | Version |
|------|---------|
| terraform | ~> 1.13.0 |
| aws | ~> 5.0 |
## Providers
| Name | Version |
|------|---------|
| archive | 2.7.1 |
| aws | 5.100.0 |
| random | 3.7.2 |
## Modules
No modules.
## Resources
| Name | Type |
|------|------|
| [aws_apigatewayv2_api.SampleHttpApi](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/apigatewayv2_api) | resource |
| [aws_apigatewayv2_deployment.deployment](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/apigatewayv2_deployment) | resource |
| [aws_apigatewayv2_stage.stage1](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/apigatewayv2_stage) | resource |
| [aws_cloudwatch_log_group.api_logging](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_log_group) | resource |
| [aws_cloudwatch_log_group.loggroups](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/cloudwatch_log_group) | resource |
| [aws_iam_role.role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role) | resource |
| [aws_iam_role_policy_attachment.role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachment) | resource |
| [aws_lambda_function.EchoFunction](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_function) | resource |
| [aws_lambda_function.SampleAuthorizer](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_function) | resource |
| [aws_lambda_permission.EchoFunction](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_permission) | resource |
| [aws_lambda_permission.SampleAuthorizer](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lambda_permission) | resource |
| [random_password.pw](https://registry.terraform.io/providers/hashicorp/random/latest/docs/resources/password) | resource |
| [archive_file.EchoFunction](https://registry.terraform.io/providers/hashicorp/archive/latest/docs/data-sources/file) | data source |
| [archive_file.SampleAuthorizer](https://registry.terraform.io/providers/hashicorp/archive/latest/docs/data-sources/file) | data source |
| [aws_caller_identity.this](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/caller_identity) | data source |
| [aws_iam_policy_document.lambda_role](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/iam_policy_document) | data source |
## Inputs
| Name | Description | Type | Default | Required |
|------|-------------|------|---------|:--------:|
| DynamicAddressGroup | n/a | `any` | n/a | yes |
| application | n/a | `any` | n/a | yes |
| aws-region | n/a | `any` | n/a | yes |
| costcenter | n/a | `any` | n/a | yes |
| customer-name | n/a | `any` | n/a | yes |
| environment | n/a | `any` | n/a | yes |
| owner | n/a | `any` | n/a | yes |
| project | n/a | `any` | n/a | yes |
## Outputs
| Name | Description |
|------|-------------|
| api\_deployment\_id | n/a |
| api\_endpoint | n/a |
| last-updated | n/a |
---
## Authorship
This module was developed by Rackspace.
+55
View File
@@ -0,0 +1,55 @@
import hashlib
import os
#region = os.environ['region']
#account_id = os.environ['account_id']
#api_id = os.environ['api_id']
pw_hash = os.environ['pw_hash']
#resource_arn = f"arn:aws:execute-api:{region}:{account_id}:{api_id}:/*/*/" # based on observed routeArn in event
def lambda_handler(event, context):
# debug
# print(f"Event received: {event}")
# print(f"resource_arn: {resource_arn}")
# Extract the token from headers
token = event['headers'].get('authorization', '')
# Check token validity
is_authorized = token == pw_hash
# Log for debugging
print(f"Authorization status: {is_authorized}. Authorization token: {'*' * len(token)}")
# Simple response
return {
"isAuthorized" : is_authorized
}
# IAM policy response, which is overkilled with no added benefit
# to use IAM policy response, your api needs to have "enableSimpleResponses" : false
# if is_authorized:
# return {
# "principalId" : "demo",
# "policyDocument": {
# "Version": "2012-10-17",
# "Statement": [{
# "Action": "execute-api:Invoke",
# "Effect": "Allow",
# "Resource": event["routeArn"]
# }]
# }
# }
# else:
# return {
# "principalId" : "demo",
# "policyDocument": {
# "Version": "2012-10-17",
# "Statement": [{
# "Action": "*",
# "Effect": "Deny",
# "Resource": "*"
# }]
# }
# }
+43
View File
@@ -0,0 +1,43 @@
{
"openapi" : "3.0.1",
"paths" : {
"/" : {
"get" : {
"responses" : {
"default" : {
"description" : "Default response for GET /"
}
},
"security" : [ {
"SampleAuthorizer" : [ ]
} ],
"x-amazon-apigateway-integration" : {
"payloadFormatVersion" : "2.0",
"type" : "aws_proxy",
"httpMethod" : "POST",
"uri" : "arn:aws:apigateway:ap-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:ap-east-1:040216112220:function:EchoFunction/invocations",
"connectionType" : "INTERNET"
}
}
}
},
"components" : {
"securitySchemes" : {
"SampleAuthorizer" : {
"type" : "apiKey",
"name" : "Authorization",
"in" : "header",
"x-amazon-apigateway-authorizer" : {
"identitySource" : "$request.header.Authorization",
"authorizerUri" : "arn:aws:apigateway:ap-east-1:lambda:path/2015-03-31/functions/arn:aws:lambda:ap-east-1:040216112220:function:SampleAuthorizer/invocations",
"authorizerPayloadFormatVersion" : "2.0",
"authorizerResultTtlInSeconds" : 0,
"type" : "request",
"enableSimpleResponses" : true
}
}
}
},
"x-amazon-apigateway-importexport-version" : "1.0"
}
+170
View File
@@ -0,0 +1,170 @@
/**
* # ApigwAuthSample
* A working example which deploys HTTP api, Lambda functions, and necessary permissions.
*
*
* ## Testing the API
* To test this in postman, put in the following settings:
*
* URL: https://<api-id>.execute-api.ap-east-1.amazonaws.com/?inputValue=TestMessage123
* Authorization: api key, key = Authorizations, value = sha256 hash, add to = Header
*
*/
# IAM role for Lambda execution
data "aws_iam_policy_document" "lambda_role" {
statement {
effect = "Allow"
principals {
type = "Service"
identifiers = ["lambda.amazonaws.com"]
}
actions = ["sts:AssumeRole"]
}
}
resource "aws_iam_role" "role" {
name = "ApiFunctionRole"
assume_role_policy = data.aws_iam_policy_document.lambda_role.json
}
resource "aws_iam_role_policy_attachment" "role" {
role = aws_iam_role.role.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}
data "archive_file" "EchoFunction" {
type = "zip"
source_file = "${path.module}/EchoFunction.py"
output_path = "${path.module}/EchoFunction.zip"
}
resource "aws_lambda_function" "EchoFunction" {
filename = data.archive_file.EchoFunction.output_path
function_name = "EchoFunction"
description = "Function that echo query parameter inputValue"
role = aws_iam_role.role.arn
handler = "EchoFunction.lambda_handler"
source_code_hash = data.archive_file.EchoFunction.output_base64sha256
architectures = ["arm64"]
runtime = "python3.13"
}
resource "aws_lambda_permission" "EchoFunction" {
statement_id = "AllowExecutionFromApi"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.EchoFunction.function_name
principal = "apigateway.amazonaws.com"
source_arn = "arn:aws:execute-api:${var.aws-region}:${data.aws_caller_identity.this.account_id}:${aws_apigatewayv2_api.SampleHttpApi.id}/*/*"
}
data "archive_file" "SampleAuthorizer" {
type = "zip"
source_file = "${path.module}/SampleAuthorizer.py"
output_path = "${path.module}/SampleAuthorizer.zip"
}
/* Test function with this input
{
"routeArn": "arn:aws:execute-api:ap-east-1:040216112220:wxzvfmiyd2/$default/GET/"
"headers": {
"authorization": "value of pw_hash"
}
}
*/
resource "random_password" "pw" {
length = 20
min_upper = 2
min_lower = 2
min_numeric = 2
min_special = 2
}
resource "aws_lambda_function" "SampleAuthorizer" {
filename = data.archive_file.SampleAuthorizer.output_path
function_name = "SampleAuthorizer"
description = "API authorizer"
role = aws_iam_role.role.arn
handler = "SampleAuthorizer.lambda_handler"
source_code_hash = data.archive_file.SampleAuthorizer.output_base64sha256
architectures = ["arm64"]
runtime = "python3.13"
environment {
variables = {
region = var.aws-region
account_id = data.aws_caller_identity.this.account_id
api_id = aws_apigatewayv2_api.SampleHttpApi.id
pw_hash = sha256(random_password.pw.result)
}
}
}
resource "aws_lambda_permission" "SampleAuthorizer" {
statement_id = "AllowExecutionFromApi"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.SampleAuthorizer.function_name
principal = "apigateway.amazonaws.com"
source_arn = "arn:aws:execute-api:${var.aws-region}:${data.aws_caller_identity.this.account_id}:${aws_apigatewayv2_api.SampleHttpApi.id}/*/*"
}
resource "aws_cloudwatch_log_group" "loggroups" {
for_each = toset(["SampleAuthorizer", "EchoFunction"])
name = "/aws/lambda/${each.value}"
retention_in_days = 1
}
# api
resource "aws_apigatewayv2_api" "SampleHttpApi" {
name = "SampleHttpApi"
protocol_type = "HTTP"
description = "Sample http api which uses Lambda integration"
ip_address_type = "ipv4"
body = file("api_body.json")
}
resource "aws_cloudwatch_log_group" "api_logging" {
name = "/aws/api/SampleHttpApi"
retention_in_days = 1
}
resource "aws_apigatewayv2_stage" "stage1" {
api_id = aws_apigatewayv2_api.SampleHttpApi.id
name = "$default"
description = "Default environment"
deployment_id = aws_apigatewayv2_deployment.deployment.id
access_log_settings {
destination_arn = aws_cloudwatch_log_group.api_logging.arn
format = jsonencode(
{
"requestId" : "$context.requestId",
"ip" : "$context.identity.sourceIp",
"requestTime" : "$context.requestTime",
"httpMethod" : "$context.httpMethod",
"routeKey" : "$context.routeKey",
"status" : "$context.status",
"protocol" : "$context.protocol",
"responseLength" : "$context.responseLength",
"AuthorizerError" : "$context.authorizer.error"
}
)
}
}
resource "aws_apigatewayv2_deployment" "deployment" {
api_id = aws_apigatewayv2_api.SampleHttpApi.id
description = "Triggered by terraform"
triggers = {
redeployment = timestamp()
}
lifecycle {
create_before_destroy = true
}
}
+7
View File
@@ -0,0 +1,7 @@
output "api_endpoint" {
value = aws_apigatewayv2_api.SampleHttpApi.api_endpoint
}
output "api_deployment_id" {
value = aws_apigatewayv2_deployment.deployment.id
}
+31
View File
@@ -0,0 +1,31 @@
provider "aws" {
region = var.aws-region
default_tags {
tags = {
ServiceProvider = "RackspaceTechnology"
Environment = var.environment
Project = var.project
Application = var.application
TerraformMode = "managed"
Owner = var.owner
CostCenter = var.costcenter
DynamicAddressGroup = var.DynamicAddressGroup
TerraformDir = "${reverse(split("/", path.cwd))[1]}/${reverse(split("/", path.cwd))[0]}"
}
}
}
output "last-updated" {
value = timestamp()
}
terraform {
required_version = "~> 1.13.0"
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
+8
View File
@@ -0,0 +1,8 @@
aws-region = "ap-east-1"
customer-name = "ken2026"
environment = "lab"
project = "iac"
application = "api"
costcenter = "undefined"
DynamicAddressGroup = "undefined"
owner = "ken2026"
+10
View File
@@ -0,0 +1,10 @@
variable "aws-region" {}
variable "customer-name" {}
variable "environment" {}
variable "project" {}
variable "application" {}
variable "owner" {}
variable "costcenter" {}
variable "DynamicAddressGroup" {}
data "aws_caller_identity" "this" {}