Skip to content

Commit

Permalink
Cloned index-html-server into client-sync lambda
Browse files Browse the repository at this point in the history
  • Loading branch information
rimutaka committed Aug 1, 2024
1 parent 2b588c8 commit 11b7752
Show file tree
Hide file tree
Showing 5 changed files with 189 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[workspace]
members = ["isbn_wasm_mod", "lambdas/index-html-server"]
members = ["isbn_wasm_mod", "lambdas/index-html-server", "lambdas/client-sync"]
resolver = "2"

[workspace.dependencies]
Expand Down
26 changes: 26 additions & 0 deletions lambdas/client-sync/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
[package]
name = "client-sync"
version = "0.2.0"
authors = ["rimutaka <[email protected]>"]
edition = "2021"
description = "Returns modified index.html from S3"
license = "AGPL-3.0"

[dependencies]
wasm_mod = { path = "../../isbn_wasm_mod" }
tokio = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
lambda_runtime = { workspace = true }
aws_lambda_events = { workspace = true }
aws-sdk-s3 = { workspace = true }
aws-config = { workspace = true }
regex = { workspace = true }
reqwest = { version = "0.12", features = [
"json",
"rustls-tls-native-roots",
"http2",
"charset",
], default-features = false }
53 changes: 53 additions & 0 deletions lambdas/client-sync/data-samples/cloudfront-req.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
{
"headers": {
"host": "jykwtit7hjvvd7tcmbrmquh62e0eetck.lambda-url.us-east-1.on.aws",
"user-agent": "Amazon CloudFront",
"via": "2.0 fc69a025b8d31536c9f86f29f3d9a032.cloudfront.net (CloudFront)",
"x-amz-cf-id": "1VDk7x451vB-j8Ws1LlqQEVp6BF_XuZwiNf-AP0YjYuda5R5Tm8JBQ==",
"x-amz-content-sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"x-amz-date": "20240708T190243Z",
"x-amz-security-token": "IQoJb3JpZ2luX2VjEFMaCXVzLWVhc3QtMSJHMEUCIHePEpt+lZ6zaFkF+sAQibTK8Z/ips4Y+crDfi/zdT/BAiEA9jlfqnXacHDdwwWaPQ45T610k2Mk8k7NOxh09iPs1kcq3wIIHBAAGgw4NTYzNjkwNTMxODEiDI0kHDMeb3r2JiMSoSq8Aqu36jbd01jlXJh4WbhsHMyBqwGzEusnKxajAxcSrwZdKKPTF75xtEoEQU67x4apvIOCXuE0UUOMwqGIP2MbQ6Ujht6Tn8Bk9t6S5HXYXtQDErk8XRHuwcGpvaUSCXfphTZKNIFP7xB+gJcgG5oYgdU8Ps+EL+nSTOZjIT5dO0yLW+MkJNL2rxG7TC6TN1B9ecuEgmI4eoQYF27VHVQwjRfwzWbbYFUvF4aXz1KRvCNtL8aYjMcnkLXSEAMT8ldOw6f788cRQxQHQESbw6aWL8oTWx+gFznUGj8Cp7Tfln46RjbKoQjuIlB34BanHVLkDpn/+aW/OvdSz5x+zpFn1HycYGrGR/+sjwnSMdeZ9lzRzpYGPWGrQwn5ILBgyOk31vYCKmUpg9Q1S0vcTl+CLGjJ0/yTdu+xOTu6KKIwruiwtAY6vwEIY/Kljvjm5MPx+nVDCJWFEkLX4cGvkJqt5pPEmHLMptlZsXBbNkeYrkJ+OMWxN897QS7Nxnly1F3ef1jpbZHh/sKOPc+2ex3jypGjOte8EQt4bkeCA9+L0bbFNr7ExTWV6zFLrHq/xDEqJlDPLw7QynBW80X/nDFxud63uPnX0H+0V6UPqfHJUtnyokCZgdhSYcaOK7gQFOblBA01EHD+zQNnhOVcQ75NNmn/NG+IyCwm1JKiUg2cWPwp9xAvog==",
"x-amz-source-account": "512295225992",
"x-amz-source-arn": "arn:aws:cloudfront::512295225992:distribution/E3FGXRC3VXQ2IF",
"x-amzn-tls-cipher-suite": "ECDHE-RSA-AES128-GCM-SHA256",
"x-amzn-tls-version": "TLSv1.2",
"x-amzn-trace-id": "Root=1-668c37d3-2f24cc6360b164e2787f34f9",
"x-forwarded-for": "222.152.186.98",
"x-forwarded-port": "443",
"x-forwarded-proto": "https"
},
"isBase64Encoded": false,
"rawPath": "/",
"rawQueryString": "",
"requestContext": {
"accountId": "856369053181",
"apiId": "jykwtit7hjvvd7tcmbrmquh62e0eetck",
"authorizer": {
"iam": {
"accessKey": "ASIA4OY4SXX6T5PPAVTL",
"accountId": "856369053181",
"callerId": "AROA4OY4SXX6VEIZRJRCJ:OriginAccessSession",
"cognitoIdentity": null,
"principalOrgId": null,
"userArn": "arn:aws:sts::856369053181:assumed-role/OriginAccessControlRole/OriginAccessSession",
"userId": "AROA4OY4SXX6VEIZRJRCJ:OriginAccessSession"
}
},
"domainName": "jykwtit7hjvvd7tcmbrmquh62e0eetck.lambda-url.us-east-1.on.aws",
"domainPrefix": "jykwtit7hjvvd7tcmbrmquh62e0eetck",
"http": {
"method": "GET",
"path": "/",
"protocol": "HTTP/1.1",
"sourceIp": "70.132.62.67",
"userAgent": "Amazon CloudFront"
},
"requestId": "8e110a76-5815-4de9-be4e-34967937cc07",
"routeKey": "$default",
"stage": "$default",
"time": "08/Jul/2024:19:02:43 +0000",
"timeEpoch": 1720465363505
},
"routeKey": "$default",
"version": "2.0"
}
20 changes: 20 additions & 0 deletions lambdas/client-sync/deploy.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Run this script from the root of the project

target=aarch64-unknown-linux-gnu
region=us-east-1
lambda=client-sync
crate=client-sync

cargo build --release --target $target --package $crate
cp ./target/$target/release/$crate ./bootstrap && zip proxy.zip bootstrap && rm bootstrap
aws lambda update-function-code --region $region --function-name $lambda --zip-file fileb://proxy.zip
rm proxy.zip

# Available targets:
# x86_64-unknown-linux-gnu
# x86_64-unknown-linux-musl
# aarch64-unknown-linux-gnu
# aarch64-unknown-linux-musl

# permissions script
# aws lambda add-permission \--statement-id "AllowCloudFrontServicePrincipal" \--action "lambda:InvokeFunctionUrl" \--principal "cloudfront.amazonaws.com" \--source-arn "arn:aws:cloudfront::512295225992:distribution/E3FGXRC3VXQ2IF" \--region "us-east-1" \--function-name index-html-server
89 changes: 89 additions & 0 deletions lambdas/client-sync/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
use aws_lambda_events::{
http::{HeaderMap, HeaderValue},
lambda_function_urls::{LambdaFunctionUrlRequest, LambdaFunctionUrlResponse},
};
/// This is a basic lambda for testing the emulator locally.
use lambda_runtime::{service_fn, Error, LambdaEvent, Runtime};
// use serde::{Deserialize, Serialize};
// use serde_json::from_str;
use tracing::info;
use tracing_subscriber::filter::LevelFilter;
// use wasm_mod::google;

#[tokio::main]
async fn main() -> Result<(), Error> {
// required to enable CloudWatch error logging by the runtime
tracing_subscriber::fmt()
.with_ansi(true)
.without_time()
.with_max_level(LevelFilter::INFO)
.init();

let func = service_fn(my_handler);
let runtime = Runtime::new(func);
#[cfg(not(debug_assertions))]
let runtime = runtime.layer(lambda_runtime::layers::TracingLayer::new());
runtime.run().await?;
Ok(())
}

pub(crate) async fn my_handler(
event: LambdaEvent<LambdaFunctionUrlRequest>,
) -> Result<LambdaFunctionUrlResponse, Error> {
// info!("Received event: {:?}", event);
let path = event.payload.raw_path.clone().unwrap_or("".to_string());
info!("Path: {}", path);

if let Some(method) = event.payload.request_context.http.method {
info!("Method: {}", method);
if method == "OPTIONS" {
let mut headers = HeaderMap::new();
headers.append("Access-Control-Allow-Origin", HeaderValue::from_static("*"));
headers.append("Access-Control-Allow-Methods", HeaderValue::from_static("GET, OPTIONS"));
headers.append(
"Access-Control-Allow-Headers",
HeaderValue::from_static("auth0,authorization"),
);

return Ok(LambdaFunctionUrlResponse {
status_code: 200,
headers,
cookies: Default::default(),
body: Some("Hello".to_string()),
is_base64_encoded: false,
});
}
}

// get bearer token from the event
let authorization = match event.payload.headers.get("authorization") {
Some(v) => v.to_str().unwrap_or("").to_string(),
None => String::new(),
};
let auth0 = match event.payload.headers.get("auth0") {
Some(v) => v.to_str().unwrap_or("").to_string(),
None => String::new(),
};

info!("Authorization: {authorization}");
info!("Auth0: {auth0}");

// get index.html from S3
let body = "Hello from client-sync".to_string();

// create headers
let mut headers = HeaderMap::new();
headers.append("Content-Type", HeaderValue::from_static("text/html; charset=utf-8"));

// prepare the response
let resp = LambdaFunctionUrlResponse {
status_code: 200,
headers,
cookies: Default::default(),
body: Some(body),
is_base64_encoded: false,
};

// return `Response` (it will be serialized to JSON automatically by the runtime)
Ok(resp)
}

0 comments on commit 11b7752

Please sign in to comment.