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

Add AWS Lambda gateway function to support IPv6 #24

Merged
merged 2 commits into from
May 7, 2024
Merged
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
43 changes: 43 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ members = [
"rs/canister/impl",
"rs/canister_upgrader",
"rs/email_sender/aws",
"rs/email_sender/aws/gateway",
"rs/email_sender/aws/lambda",
"rs/email_sender/aws/template_updater",
"rs/email_sender/core",
Expand All @@ -22,6 +23,7 @@ async-trait = "0.1.79"
aws-config = "1.3.0"
aws_lambda_events = { version = "0.15.0", default-features = false }
aws-sdk-sesv2 = "1.23.0"
aws-sdk-sns = "1.23.0"
aws-sign-v4 = "0.3.0"
base64 = "0.22.0"
candid = "0.10.6"
Expand Down
1 change: 1 addition & 0 deletions rs/canister/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
### Added

- Add `canister_upgrader` to simplify upgrading the canister ([#23](https://github.com/open-chat-labs/ic-sign-in-with-email/pull/23))
- Add AWS Lambda gateway function to support IPv6 ([#24](https://github.com/open-chat-labs/ic-sign-in-with-email/pull/24))

### Changed

Expand Down
8 changes: 4 additions & 4 deletions rs/canister/api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ pub enum EmailSenderConfig {
#[derive(CandidType, Serialize, Deserialize, Clone, Debug)]
pub struct AwsEmailSenderConfig {
pub region: String,
pub target_arn: String,
pub function_url: String,
pub access_key: String,
pub secret_key: String,
}
Expand All @@ -60,7 +60,7 @@ pub enum EncryptedEmailSenderConfig {
#[derive(CandidType, Serialize, Deserialize, Clone, Debug)]
pub struct EncryptedAwsEmailSenderConfig {
pub region: String,
pub target_arn: String,
pub function_url: String,
pub access_key_encrypted: String,
pub secret_key_encrypted: String,
}
Expand Down Expand Up @@ -97,7 +97,7 @@ impl AwsEmailSenderConfig {
) -> EncryptedAwsEmailSenderConfig {
EncryptedAwsEmailSenderConfig {
region: self.region,
target_arn: self.target_arn,
function_url: self.function_url,
access_key_encrypted: encrypt(&self.access_key, rsa_public_key, rng),
secret_key_encrypted: encrypt(&self.secret_key, rsa_public_key, rng),
}
Expand All @@ -108,7 +108,7 @@ impl EncryptedAwsEmailSenderConfig {
pub fn decrypt(self, rsa_private_key: &RsaPrivateKey) -> AwsEmailSenderConfig {
AwsEmailSenderConfig {
region: self.region,
target_arn: self.target_arn,
function_url: self.function_url,
access_key: decrypt(&self.access_key_encrypted, rsa_private_key),
secret_key: decrypt(&self.secret_key_encrypted, rsa_private_key),
}
Expand Down
9 changes: 3 additions & 6 deletions rs/canister/impl/src/email_sender.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{env, rng};
use crate::env;
use candid::Principal;
use email_sender_core::EmailSender;
use magic_links::EncryptedMagicLink;
Expand All @@ -17,7 +17,7 @@ pub fn init_from_config(config: EmailSenderConfig, identity_canister_id: Princip
init(email_sender_aws::AwsEmailSender::new(
identity_canister_id,
aws.region,
aws.target_arn,
aws.function_url,
aws.access_key,
aws.secret_key,
));
Expand All @@ -40,9 +40,6 @@ pub async fn send_magic_link(
magic_link: EncryptedMagicLink,
) -> Result<(), String> {
let sender = EMAIL_SENDER.get().expect("Email sender has not been set");
let idempotency_id = rng::gen();

sender
.send(email.into(), magic_link, idempotency_id, env::now())
.await
sender.send(email.into(), magic_link, env::now()).await
}
10 changes: 1 addition & 9 deletions rs/canister/impl/src/rng.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use rand::distributions::{Distribution, Standard};
use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use rand::SeedableRng;
use rsa::RsaPrivateKey;
use std::cell::RefCell;

Expand All @@ -21,13 +20,6 @@ pub fn generate_rsa_private_key() -> RsaPrivateKey {
with_rng(|rng| RsaPrivateKey::new(rng, 2048).unwrap())
}

pub fn gen<T>() -> T
where
Standard: Distribution<T>,
{
with_rng(|rng| rng.gen())
}

pub fn with_rng<F: FnOnce(&mut StdRng) -> T, T>(f: F) -> T {
RNG.with_borrow_mut(|rng| f(rng.as_mut().unwrap()))
}
4 changes: 2 additions & 2 deletions rs/canister_upgrader/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ async fn main() {
None,
EmailSenderConfig::Aws(AwsEmailSenderConfig {
region: opts.aws_region,
target_arn: opts.aws_target_arn,
function_url: opts.aws_function_url,
access_key: opts.aws_access_key,
secret_key: opts.aws_secret_key,
}),
Expand All @@ -39,7 +39,7 @@ struct Opts {
aws_region: String,

#[arg(long)]
aws_target_arn: String,
aws_function_url: String,

#[arg(long)]
aws_access_key: String,
Expand Down
15 changes: 15 additions & 0 deletions rs/email_sender/aws/gateway/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[package]
name = "email_sender_aws_gateway"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
aws-config.workspace = true
aws_lambda_events = { workspace = true, features = ["lambda_function_urls"] }
aws-sdk-sns.workspace = true
lambda_runtime.workspace = true
tokio.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
31 changes: 31 additions & 0 deletions rs/email_sender/aws/gateway/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
use aws_config::BehaviorVersion;
use aws_lambda_events::lambda_function_urls::LambdaFunctionUrlRequest;
use aws_sdk_sns::Client as SnsClient;
use lambda_runtime::{run, service_fn, Error, LambdaEvent};

#[tokio::main]
async fn main() -> Result<(), Error> {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::INFO)
.with_target(false)
.without_time()
.init();

run(service_fn(function_handler)).await
}

async fn function_handler(event: LambdaEvent<LambdaFunctionUrlRequest>) -> Result<(), Error> {
let aws_config = aws_config::load_defaults(BehaviorVersion::latest()).await;
let sns_client = SnsClient::new(&aws_config);
let target_arn = std::env::var("SNS_TARGET_ARN").unwrap();

sns_client
.publish()
.target_arn(target_arn)
.message(&event.payload.body.unwrap())
.message_group_id("0")
.send()
.await?;

Ok(())
}
13 changes: 8 additions & 5 deletions rs/email_sender/aws/lambda/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,13 @@ async fn main() -> Result<(), Error> {
async fn function_handler(event: LambdaEvent<SqsEvent>) -> Result<(), Error> {
let aws_config = aws_config::load_defaults(BehaviorVersion::latest()).await;
let ses_client = SesClient::new(&aws_config);
let rsa_private_key_pem = std::env::var("RSA_PRIVATE_KEY_PEM")
.expect("RSA_PRIVATE_KEY_PEM not set")
.replace("\\n", "\n");
let rsa_private_key_pem = std::env::var("RSA_PRIVATE_KEY_PEM")?.replace("\\n", "\n");
let rsa_private_key = RsaPrivateKey::from_pkcs1_pem(&rsa_private_key_pem)?;

for event in event.payload.records {
process_record(event, rsa_private_key.clone(), &ses_client).await?;
if let Err(error) = process_record(event, rsa_private_key.clone(), &ses_client).await {
error!(?error, "Error processing record");
}
}

Ok(())
Expand Down Expand Up @@ -75,7 +75,10 @@ async fn process_record(
.send()
.await
{
Ok(_) => Ok(()),
Ok(_) => {
info!("Successfully sent email");
Ok(())
}
Err(error) => {
error!(?error, "Failed to send email");
Err(error.into())
Expand Down
45 changes: 18 additions & 27 deletions rs/email_sender/aws/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use time::OffsetDateTime;
pub struct AwsEmailSender {
identity_canister_id: Principal,
region: String,
target_arn: String,
function_url: String,
access_key: String,
secret_key: String,
}
Expand All @@ -25,14 +25,14 @@ impl AwsEmailSender {
pub fn new(
identity_canister_id: Principal,
region: String,
target_arn: String,
function_url: String,
access_key: String,
secret_key: String,
) -> AwsEmailSender {
AwsEmailSender {
identity_canister_id,
region,
target_arn,
function_url,
access_key,
secret_key,
}
Expand All @@ -42,16 +42,21 @@ impl AwsEmailSender {
&self,
email: String,
magic_link: EncryptedMagicLink,
idempotency_id: u64,
now_millis: u64,
) -> CanisterHttpRequestArgument {
let datetime =
OffsetDateTime::from_unix_timestamp_nanos(now_millis as i128 * 1_000_000).unwrap();

let region = &self.region;
let host = format!("sns.{region}.amazonaws.com");
let host = self.function_url.trim_start_matches("https://");
let url = format!("https://{host}");

let body = serde_json::to_string(&MagicLinkMessage {
email,
identity_canister_id: self.identity_canister_id,
magic_link,
})
.unwrap();

let mut header_map = HeaderMap::new();
header_map.insert(
"X-Amz-Date",
Expand All @@ -60,25 +65,12 @@ impl AwsEmailSender {
header_map.insert("host", host.parse().unwrap());
header_map.insert(
http::header::CONTENT_TYPE,
"application/x-www-form-urlencoded".parse().unwrap(),
"application/json".parse().unwrap(),
);
header_map.insert(
http::header::CONTENT_LENGTH,
body.len().to_string().parse().unwrap(),
);

let message_deduplication_id = idempotency_id.to_string();
let message = serde_json::to_string(&MagicLinkMessage {
email,
identity_canister_id: self.identity_canister_id,
magic_link,
})
.unwrap();

let body = [
("Action", "Publish"),
("TargetArn", &self.target_arn),
("Message", &message),
("MessageDeduplicationId", &message_deduplication_id),
("MessageGroupId", "0"),
];
let body = serde_urlencoded::to_string(body).unwrap();

let signature = aws_sign_v4::AwsSign::new(
"POST",
Expand All @@ -88,7 +80,7 @@ impl AwsEmailSender {
&self.region,
&self.access_key,
&self.secret_key,
"sns",
"lambda",
&body,
)
.sign();
Expand Down Expand Up @@ -120,10 +112,9 @@ impl EmailSender for AwsEmailSender {
&self,
email: String,
magic_link: EncryptedMagicLink,
idempotency_id: u64,
now_millis: u64,
) -> Result<(), String> {
let args = self.build_args(email, magic_link, idempotency_id, now_millis);
let args = self.build_args(email, magic_link, now_millis);

let resp =
ic_cdk::api::management_canister::http_request::http_request(args, 1_000_000_000)
Expand Down
2 changes: 0 additions & 2 deletions rs/email_sender/core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ pub trait EmailSender: Send + Sync {
&self,
email: String,
magic_link: EncryptedMagicLink,
idempotency_id: u64,
now_millis: u64,
) -> Result<(), String>;
}
Expand All @@ -21,7 +20,6 @@ impl EmailSender for NullEmailSender {
&self,
_email: String,
_magic_link: EncryptedMagicLink,
_idempotency_id: u64,
_now_millis: u64,
) -> Result<(), String> {
Ok(())
Expand Down
1 change: 1 addition & 0 deletions scripts/build-aws-gateway-function.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
cargo lambda build -p email_sender_aws_gateway --release --arm64 --output-format zip
Loading
Loading