|
| 1 | +use crate::s3; |
| 2 | +use crate::{config::Config, Error}; |
| 3 | +use base64::decode; |
| 4 | +use lambda_runtime::Context; |
| 5 | +use ring::signature; |
| 6 | +use serde::{Deserialize, Serialize}; |
| 7 | +use serde_json::Value; |
| 8 | +use std::collections::HashMap; |
| 9 | +use tracing::{debug, error, info}; |
| 10 | + |
| 11 | +#[derive(Serialize, Debug)] |
| 12 | +#[serde(rename_all = "camelCase")] |
| 13 | +struct ApiGatewayResponse { |
| 14 | + is_base64_encoded: bool, |
| 15 | + status_code: u32, |
| 16 | + headers: HashMap<String, String>, |
| 17 | + #[serde(skip_serializing_if = "Option::is_none")] |
| 18 | + body: Option<String>, |
| 19 | +} |
| 20 | + |
| 21 | +#[derive(Deserialize, Debug)] |
| 22 | +struct ApiGatewayRequestHeaders { |
| 23 | + /// The user public key, which may or may not be known to us at the time of submission. |
| 24 | + /// A base58 encoded string, e.g. "EFY9NXEytYgBgGsyAeGfXzkBEBQzC9NXFyj47EPdmVLB" |
| 25 | + stackmuncher_key: Option<String>, |
| 26 | + /// The signature for the content sent in the body, base58 encoded, e.g. |
| 27 | + /// "3phLLQyiquyX4xge3CXYGCfb1KdrXQ8cTgBbvE8obwCkcm7vPdLsKT6JtNCdF9qeyjcgF2b4kTRXEsoMTHcQr43n" |
| 28 | + stackmuncher_sig: Option<String>, |
| 29 | + /// The IP address of the user. Apparently it is preferred over sourceIp field. |
| 30 | + /// See https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/x-forwarded-headers.html |
| 31 | + #[serde(rename = "x-forwarded-for")] |
| 32 | + x_forwarded_for: Option<String>, |
| 33 | +} |
| 34 | + |
| 35 | +#[derive(Deserialize, Debug)] |
| 36 | +#[serde(rename_all = "camelCase")] |
| 37 | +struct ApiGatewayRequest { |
| 38 | + headers: ApiGatewayRequestHeaders, |
| 39 | + is_base64_encoded: bool, |
| 40 | + body: Option<String>, |
| 41 | +} |
| 42 | + |
| 43 | +/// A generic error message sent to the user when the request cannot be processed for a reason the user can't do much about. |
| 44 | +const ERROR_500_MSG: &str = "stackmuncher.com failed to process the report. If the error persists, can you log an issue at https://github.com/stackmuncher/stm_inbox/issues?"; |
| 45 | + |
| 46 | +pub(crate) async fn my_handler(event: Value, ctx: Context) -> Result<Value, Error> { |
| 47 | + // these 2 lines are for debugging only to see the raw APIGW request |
| 48 | + debug!("Event: {}", event); |
| 49 | + debug!("Context: {:?}", ctx); |
| 50 | + |
| 51 | + // parse the request |
| 52 | + let api_request = match serde_json::from_value::<ApiGatewayRequest>(event.clone()) { |
| 53 | + Err(e) => { |
| 54 | + error!( |
| 55 | + "Failed to deser APIGW request due to {}. Request: {}", |
| 56 | + e, event |
| 57 | + ); |
| 58 | + return gw_response(Some(ERROR_500_MSG.to_owned()), 500); |
| 59 | + } |
| 60 | + Ok(v) => v, |
| 61 | + }; |
| 62 | + |
| 63 | + info!("Report from IP: {:?}", api_request.headers.x_forwarded_for); |
| 64 | + |
| 65 | + // these 2 headers are required no matter what |
| 66 | + if api_request.headers.stackmuncher_key.is_none() |
| 67 | + || api_request.headers.stackmuncher_sig.is_none() |
| 68 | + { |
| 69 | + error!( |
| 70 | + "Missing a header. Key: {:?}, Sig: {:?}", |
| 71 | + api_request.headers.stackmuncher_key, api_request.headers.stackmuncher_sig |
| 72 | + ); |
| 73 | + return gw_response( |
| 74 | + Some("stackmuncher.com failed to process the report: missing required HTTP headers. If you have not modified the source code it's a bug at stackmuncher.com end.".to_owned()), |
| 75 | + 500, |
| 76 | + ); |
| 77 | + } |
| 78 | + |
| 79 | + // get the body contents and decode it if needed |
| 80 | + let body = match api_request.body { |
| 81 | + Some(v) => v, |
| 82 | + None => { |
| 83 | + error!("Empty body"); |
| 84 | + return gw_response( |
| 85 | + Some("stackmuncher.com: no report found in the request. It's a bug in the app. Can you log an issue at https://github.com/stackmuncher/stm_inbox/issues?".to_owned()), |
| 86 | + 500, |
| 87 | + ); |
| 88 | + } |
| 89 | + }; |
| 90 | + let body = if api_request.is_base64_encoded { |
| 91 | + match decode(body) { |
| 92 | + Ok(v) => v, |
| 93 | + Err(e) => { |
| 94 | + error!("Failed to decode the body due to: {}", e); |
| 95 | + return gw_response(Some(ERROR_500_MSG.to_owned()), 500); |
| 96 | + } |
| 97 | + } |
| 98 | + } else { |
| 99 | + body.as_bytes().into() |
| 100 | + }; |
| 101 | + |
| 102 | + info!("Body len: {}", body.len()); |
| 103 | + debug!("Body: {}", String::from_utf8_lossy(&body)); |
| 104 | + |
| 105 | + // convert the public key from base58 into bytes |
| 106 | + let pub_key_bs58 = api_request |
| 107 | + .headers |
| 108 | + .stackmuncher_key |
| 109 | + .expect("Cannot unwrap stackmuncher_key. It's a bug."); |
| 110 | + |
| 111 | + info!("Report for pub key: {}", pub_key_bs58); |
| 112 | + |
| 113 | + let pub_key = match bs58::decode(pub_key_bs58.clone()).into_vec() { |
| 114 | + Ok(v) => v, |
| 115 | + Err(e) => { |
| 116 | + error!( |
| 117 | + "Failed to decode the stackmuncher_key from based58 due to: {}", |
| 118 | + e |
| 119 | + ); |
| 120 | + return gw_response(Some(ERROR_500_MSG.to_owned()), 500); |
| 121 | + } |
| 122 | + }; |
| 123 | + |
| 124 | + // convert the signature from base58 into bytes |
| 125 | + let signature = match bs58::decode( |
| 126 | + api_request |
| 127 | + .headers |
| 128 | + .stackmuncher_sig |
| 129 | + .expect("Cannot unwrap stackmuncher_sig. It's a bug."), |
| 130 | + ) |
| 131 | + .into_vec() |
| 132 | + { |
| 133 | + Ok(v) => v, |
| 134 | + Err(e) => { |
| 135 | + error!( |
| 136 | + "Failed to decode the stackmuncher_key from based58 due to: {}", |
| 137 | + e |
| 138 | + ); |
| 139 | + return gw_response(Some(ERROR_500_MSG.to_owned()), 500); |
| 140 | + } |
| 141 | + }; |
| 142 | + |
| 143 | + // validate the signature |
| 144 | + let pub_key = signature::UnparsedPublicKey::new(&signature::ED25519, pub_key); |
| 145 | + match pub_key.verify(&body, &signature) { |
| 146 | + Ok(_) => { |
| 147 | + info!("Signature OK"); |
| 148 | + } |
| 149 | + Err(e) => { |
| 150 | + error!("Invalid signature: {}", e); |
| 151 | + return gw_response(Some("Invalid StackMuncher signature. If the error persists, can you log an issue at https://github.com/stackmuncher/stm_inbox/issues?".to_owned()), 500); |
| 152 | + } |
| 153 | + }; |
| 154 | + |
| 155 | + let config = Config::new(); |
| 156 | + s3::upload_to_s3(&config, body, pub_key_bs58).await; |
| 157 | + |
| 158 | + // render the prepared data as HTML |
| 159 | + info!("Report stored"); |
| 160 | + |
| 161 | + // Submission accepted - return 200 with no body |
| 162 | + gw_response(None, 200) |
| 163 | +} |
| 164 | + |
| 165 | +/// Prepares the response with the status and text or json body. May fail and return an error. |
| 166 | +fn gw_response(body: Option<String>, status_code: u32) -> Result<Value, Error> { |
| 167 | + let mut headers: HashMap<String, String> = HashMap::new(); |
| 168 | + headers.insert("Content-Type".to_owned(), "text/text".to_owned()); |
| 169 | + headers.insert("Cache-Control".to_owned(), "no-store".to_owned()); |
| 170 | + |
| 171 | + let resp = ApiGatewayResponse { |
| 172 | + is_base64_encoded: false, |
| 173 | + status_code, |
| 174 | + headers, |
| 175 | + body, |
| 176 | + }; |
| 177 | + |
| 178 | + Ok(serde_json::to_value(resp).expect("Failed to serialize response")) |
| 179 | +} |
0 commit comments