From ceaf11c15f18b5fed105456638ffab5152010030 Mon Sep 17 00:00:00 2001 From: "Sebastian H. Gabrielli" Date: Sat, 30 Dec 2023 22:42:56 +0100 Subject: [PATCH] Handle all errors in fetch_jwt_certificates --- src/main.rs | 37 +++++++++++++++++++++++++++---------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/src/main.rs b/src/main.rs index be3027f..1bbc4ce 100644 --- a/src/main.rs +++ b/src/main.rs @@ -116,12 +116,32 @@ fn validate_jwt(token: &str, jwt_info: &mut JwtInfo) -> Result { fn fetch_jwt_certificates(jwt_info: &JwtInfo) -> Option> { // Fetch the JWKS endpoint - let jwks_body = reqwest::blocking::get(&jwt_info.jwks_uri) - .unwrap() - .text() - .unwrap(); + let jwks_body: String; + match reqwest::blocking::get(&jwt_info.jwks_uri) { + Ok(response) => { + match response.text() { + Ok(text) => jwks_body = text, + Err(e) => { + eprintln!("Failed to extract text from response body with error:\n{}", e); + return None; + } + } + }, + Err(e) => { + eprintln!("Failed to get the jwks_uri with error:\n{}", e); + return None; + } + } + // Parse the data into the struct - let jwks_data: Jwks = serde_json::from_str(&jwks_body).unwrap(); + let jwks_data: Jwks; + match serde_json::from_str(&jwks_body) { + Ok(jwks) => jwks_data = jwks, + Err(e) => { + eprintln!("Failed to parse fetched jwks body to Jwks struct with error:\n{}", e); + return None; + } + } // Create the output hashmap let mut output_map: HashMap = HashMap::new(); @@ -129,13 +149,10 @@ fn fetch_jwt_certificates(jwt_info: &JwtInfo) -> Option> // Go through each pair of keys and add them to the output jwt info for key in jwks_data.keys { // Extract the x5c key data - let x5c = key.x5c.get(0).unwrap(); + let x5c = key.x5c.get(0)?; // Add the PEM info in to the x5c - let pem_data = format!( - "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----", - x5c - ); + let pem_data = format!("-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----", x5c); // Add the resulting key to the hashmap output_map.insert(key.kid, pem_data);