From 2dea589c0e6e567b75696eb3ee05c2632c8c3db5 Mon Sep 17 00:00:00 2001 From: "Lucille L. Blumire" Date: Thu, 17 Apr 2025 15:48:56 +0100 Subject: [PATCH] refactor: prefer inline format args --- bin/sha384-extend/src/main.rs | 6 ++--- bin/tee-self-attestation-test/src/main.rs | 2 +- bin/verify-attestation/src/main.rs | 2 +- .../src/client/json_rpc.rs | 12 ++++----- .../src/core/config.rs | 7 ++---- .../src/core/types.rs | 9 +++---- bin/verify-era-proof-attestation/src/main.rs | 2 +- .../src/proof/parsing.rs | 2 +- .../src/verification/attestation.rs | 2 +- .../src/verification/policy.rs | 6 ++--- .../src/verification/signature.rs | 7 +++--- crates/intel-dcap-api/src/client/helpers.rs | 25 ++++++++----------- crates/teepot/src/log/mod.rs | 5 +--- crates/teepot/src/prover/reportdata.rs | 3 +-- crates/teepot/src/quote/error.rs | 2 +- crates/teepot/src/quote/mod.rs | 2 +- crates/teepot/src/quote/phala.rs | 4 +-- crates/teepot/src/quote/tcblevel.rs | 6 ++--- 18 files changed, 42 insertions(+), 62 deletions(-) diff --git a/bin/sha384-extend/src/main.rs b/bin/sha384-extend/src/main.rs index f2ace5e..be496f0 100644 --- a/bin/sha384-extend/src/main.rs +++ b/bin/sha384-extend/src/main.rs @@ -61,13 +61,11 @@ pub fn extend_sha384(base: &str, extend: &str) -> Result { let mut hasher = sha2::Sha384::new(); hasher.update(pad::<48>(&hex::decode(base).context(format!( - "Failed to decode base digest '{}' - expected hex string", - base + "Failed to decode base digest '{base}' - expected hex string", ))?)?); hasher.update(pad::<48>(&hex::decode(extend).context(format!( - "Failed to decode extend digest '{}' - expected hex string", - extend + "Failed to decode extend digest '{extend}' - expected hex string", ))?)?); Ok(hex::encode(hasher.finalize())) diff --git a/bin/tee-self-attestation-test/src/main.rs b/bin/tee-self-attestation-test/src/main.rs index ee90314..4c9437f 100644 --- a/bin/tee-self-attestation-test/src/main.rs +++ b/bin/tee-self-attestation-test/src/main.rs @@ -26,7 +26,7 @@ async fn main() -> Result<()> { .context("failed to get quote and collateral")?; let base64_string = general_purpose::STANDARD.encode(report.quote.as_ref()); - print!("{}", base64_string); + print!("{base64_string}"); Ok(()) } diff --git a/bin/verify-attestation/src/main.rs b/bin/verify-attestation/src/main.rs index 4eb84f1..b33b7ad 100644 --- a/bin/verify-attestation/src/main.rs +++ b/bin/verify-attestation/src/main.rs @@ -81,7 +81,7 @@ fn print_quote_verification_summary(quote_verification_result: &QuoteVerificatio for advisory in advisories { println!("\tInfo: Advisory ID: {advisory}"); } - println!("Quote verification result: {}", tcblevel); + println!("Quote verification result: {tcblevel}"); println!("{:#}", "e.report); } diff --git a/bin/verify-era-proof-attestation/src/client/json_rpc.rs b/bin/verify-era-proof-attestation/src/client/json_rpc.rs index a9417ff..407b819 100644 --- a/bin/verify-era-proof-attestation/src/client/json_rpc.rs +++ b/bin/verify-era-proof-attestation/src/client/json_rpc.rs @@ -26,12 +26,10 @@ impl MainNodeClient { /// Create a new client for the main node pub fn new(rpc_url: Url, chain_id: u64) -> error::Result { let chain_id = L2ChainId::try_from(chain_id) - .map_err(|e| error::Error::Internal(format!("Invalid chain ID: {}", e)))?; + .map_err(|e| error::Error::Internal(format!("Invalid chain ID: {e}")))?; let node_client = NodeClient::http(rpc_url.into()) - .map_err(|e| { - error::Error::Internal(format!("Failed to create JSON-RPC client: {}", e)) - })? + .map_err(|e| error::Error::Internal(format!("Failed to create JSON-RPC client: {e}")))? .for_network(chain_id.into()) .build(); @@ -46,13 +44,13 @@ impl JsonRpcClient for MainNodeClient { .get_l1_batch_details(batch_number) .rpc_context("get_l1_batch_details") .await - .map_err(|e| error::Error::JsonRpc(format!("Failed to get batch details: {}", e)))? + .map_err(|e| error::Error::JsonRpc(format!("Failed to get batch details: {e}")))? .ok_or_else(|| { - error::Error::JsonRpc(format!("No details found for batch #{}", batch_number)) + error::Error::JsonRpc(format!("No details found for batch #{batch_number}")) })?; batch_details.base.root_hash.ok_or_else(|| { - error::Error::JsonRpc(format!("No root hash found for batch #{}", batch_number)) + error::Error::JsonRpc(format!("No root hash found for batch #{batch_number}")) }) } } diff --git a/bin/verify-era-proof-attestation/src/core/config.rs b/bin/verify-era-proof-attestation/src/core/config.rs index 8132ddc..d77566b 100644 --- a/bin/verify-era-proof-attestation/src/core/config.rs +++ b/bin/verify-era-proof-attestation/src/core/config.rs @@ -190,15 +190,12 @@ impl VerifierConfig { pub fn new(args: VerifierConfigArgs) -> error::Result { let policy = if let Some(path) = &args.attestation_policy_file { let policy_content = fs::read_to_string(path).map_err(|e| { - error::Error::internal(format!("Failed to read attestation policy file: {}", e)) + error::Error::internal(format!("Failed to read attestation policy file: {e}")) })?; let policy_config: AttestationPolicyConfig = serde_yaml::from_str(&policy_content) .map_err(|e| { - error::Error::internal(format!( - "Failed to parse attestation policy file: {}", - e - )) + error::Error::internal(format!("Failed to parse attestation policy file: {e}")) })?; tracing::info!("Loaded attestation policy from file: {:?}", path); diff --git a/bin/verify-era-proof-attestation/src/core/types.rs b/bin/verify-era-proof-attestation/src/core/types.rs index 11636c2..0f8b7d7 100644 --- a/bin/verify-era-proof-attestation/src/core/types.rs +++ b/bin/verify-era-proof-attestation/src/core/types.rs @@ -31,13 +31,13 @@ impl fmt::Display for VerifierMode { end_batch, } => { if start_batch == end_batch { - write!(f, "one-shot mode (batch {})", start_batch) + write!(f, "one-shot mode (batch {start_batch})") } else { - write!(f, "one-shot mode (batches {}-{})", start_batch, end_batch) + write!(f, "one-shot mode (batches {start_batch}-{end_batch})") } } VerifierMode::Continuous { start_batch } => { - write!(f, "continuous mode (starting from batch {})", start_batch) + write!(f, "continuous mode (starting from batch {start_batch})") } } } @@ -89,8 +89,7 @@ impl fmt::Display for VerificationResult { } => { write!( f, - "Partial Success ({} verified, {} failed)", - verified_count, unverified_count + "Partial Success ({verified_count} verified, {unverified_count} failed)" ) } VerificationResult::Failure => write!(f, "Failure"), diff --git a/bin/verify-era-proof-attestation/src/main.rs b/bin/verify-era-proof-attestation/src/main.rs index 2f66b43..9b45203 100644 --- a/bin/verify-era-proof-attestation/src/main.rs +++ b/bin/verify-era-proof-attestation/src/main.rs @@ -74,7 +74,7 @@ async fn main() -> Result<()> { }, Err(e) => { tracing::error!("Task panicked: {}", e); - Err(Error::internal(format!("Task panicked: {}", e))) + Err(Error::internal(format!("Task panicked: {e}"))) } } }, diff --git a/bin/verify-era-proof-attestation/src/proof/parsing.rs b/bin/verify-era-proof-attestation/src/proof/parsing.rs index 6519e17..8611741 100644 --- a/bin/verify-era-proof-attestation/src/proof/parsing.rs +++ b/bin/verify-era-proof-attestation/src/proof/parsing.rs @@ -21,7 +21,7 @@ impl ProofResponseParser { } } - return Err(error::Error::JsonRpc(format!("JSONRPC error: {:?}", error))); + return Err(error::Error::JsonRpc(format!("JSONRPC error: {error:?}"))); } // Extract proofs from the result diff --git a/bin/verify-era-proof-attestation/src/verification/attestation.rs b/bin/verify-era-proof-attestation/src/verification/attestation.rs index 656ab57..e37527f 100644 --- a/bin/verify-era-proof-attestation/src/verification/attestation.rs +++ b/bin/verify-era-proof-attestation/src/verification/attestation.rs @@ -17,7 +17,7 @@ impl AttestationVerifier { // Get current time for verification let unix_time: i64 = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) - .map_err(|e| error::Error::internal(format!("Failed to get system time: {}", e)))? + .map_err(|e| error::Error::internal(format!("Failed to get system time: {e}")))? .as_secs() as _; // Verify the quote with the collateral diff --git a/bin/verify-era-proof-attestation/src/verification/policy.rs b/bin/verify-era-proof-attestation/src/verification/policy.rs index 8130075..b925aab 100644 --- a/bin/verify-era-proof-attestation/src/verification/policy.rs +++ b/bin/verify-era-proof-attestation/src/verification/policy.rs @@ -107,8 +107,7 @@ impl PolicyEnforcer { ) -> Result<()> { if !allowed_levels.contains(actual_level) { let error_msg = format!( - "Quote verification failed: TCB level mismatch (expected one of: {:?}, actual: {})", - allowed_levels, actual_level + "Quote verification failed: TCB level mismatch (expected one of: {allowed_levels:?}, actual: {actual_level})", ); return Err(Error::policy_violation(error_msg)); } @@ -152,8 +151,7 @@ impl PolicyEnforcer { .collect::>() .join(", "); let error_msg = format!( - "Quote verification failed: {} mismatch (expected one of: [ {} ], actual: {:x})", - field_name, valid_values, actual_value + "Quote verification failed: {field_name} mismatch (expected one of: [ {valid_values} ], actual: {actual_value:x})" ); return Err(Error::policy_violation(error_msg)); } diff --git a/bin/verify-era-proof-attestation/src/verification/signature.rs b/bin/verify-era-proof-attestation/src/verification/signature.rs index 314218a..f940ba4 100644 --- a/bin/verify-era-proof-attestation/src/verification/signature.rs +++ b/bin/verify-era-proof-attestation/src/verification/signature.rs @@ -30,9 +30,8 @@ impl SignatureVerifier { let report_data_bytes = quote_verification_result.quote.get_report_data(); tracing::trace!(?report_data_bytes); - let report_data = ReportData::try_from(report_data_bytes).map_err(|e| { - error::Error::internal(format!("Could not convert to ReportData: {}", e)) - })?; + let report_data = ReportData::try_from(report_data_bytes) + .map_err(|e| error::Error::internal(format!("Could not convert to ReportData: {e}")))?; Self::verify(&report_data, &root_hash, signature) } @@ -100,7 +99,7 @@ impl SignatureVerifier { })?; recover_signer(&signature_bytes, &root_hash_msg).map_err(|e| { - error::Error::signature_verification(format!("Failed to recover signer: {}", e)) + error::Error::signature_verification(format!("Failed to recover signer: {e}")) })? } // Any other length is invalid diff --git a/crates/intel-dcap-api/src/client/helpers.rs b/crates/intel-dcap-api/src/client/helpers.rs index 8ebc887..1f37070 100644 --- a/crates/intel-dcap-api/src/client/helpers.rs +++ b/crates/intel-dcap-api/src/client/helpers.rs @@ -25,20 +25,18 @@ impl ApiClient { if technology == "tdx" && self.api_version == ApiVersion::V3 { return Err(IntelApiError::UnsupportedApiVersion(format!( - "TDX endpoint /{}/{}/{} requires API v4", - service, endpoint, technology + "TDX endpoint /{service}/{endpoint}/{technology} requires API v4", ))); } if technology == "sgx" && service == "registration" { // Registration paths are fixed at v1 regardless of client's api_version - return Ok(format!("/sgx/registration/v1/{}", endpoint).replace("//", "/")); + return Ok(format!("/sgx/registration/v1/{endpoint}").replace("//", "/")); } - Ok(format!( - "/{}/certification/{}/{}/{}", - technology, api_segment, service, endpoint + Ok( + format!("/{technology}/certification/{api_segment}/{service}/{endpoint}") + .replace("//", "/"), ) - .replace("//", "/")) } /// Helper to add an optional header if the string is non-empty. @@ -187,13 +185,11 @@ impl ApiClient { /// Ensures the client is configured for API v4, otherwise returns an error. pub(super) fn ensure_v4_api(&self, function_name: &str) -> Result<(), IntelApiError> { if self.api_version != ApiVersion::V4 { - Err(IntelApiError::UnsupportedApiVersion(format!( - "{} requires API v4", - function_name - ))) - } else { - Ok(()) + return Err(IntelApiError::UnsupportedApiVersion(format!( + "{function_name} requires API v4", + ))); } + Ok(()) } /// Checks if a V4-only parameter is provided with a V3 API version. @@ -204,8 +200,7 @@ impl ApiClient { ) -> Result<(), IntelApiError> { if self.api_version == ApiVersion::V3 && param_value.is_some() { Err(IntelApiError::UnsupportedApiVersion(format!( - "'{}' parameter requires API v4", - param_name + "'{param_name}' parameter requires API v4", ))) } else { Ok(()) diff --git a/crates/teepot/src/log/mod.rs b/crates/teepot/src/log/mod.rs index d0fd107..795cc10 100644 --- a/crates/teepot/src/log/mod.rs +++ b/crates/teepot/src/log/mod.rs @@ -53,10 +53,7 @@ pub fn setup_logging( .try_from_env() .unwrap_or(match *log_level { LevelFilter::OFF => EnvFilter::new("off"), - _ => EnvFilter::new(format!( - "warn,{crate_name}={log_level},teepot={log_level}", - log_level = log_level - )), + _ => EnvFilter::new(format!("warn,{crate_name}={log_level},teepot={log_level}")), }); let fmt_layer = tracing_subscriber::fmt::layer() diff --git a/crates/teepot/src/prover/reportdata.rs b/crates/teepot/src/prover/reportdata.rs index bcff688..fd849bf 100644 --- a/crates/teepot/src/prover/reportdata.rs +++ b/crates/teepot/src/prover/reportdata.rs @@ -37,8 +37,7 @@ pub enum ReportData { fn report_data_to_bytes(data: &[u8], version: u8) -> [u8; REPORT_DATA_LENGTH] { debug_assert!( data.len() < REPORT_DATA_LENGTH, // Ensure there is space for the version byte - "Data length exceeds maximum of {} bytes", - REPORT_DATA_LENGTH + "Data length exceeds maximum of {REPORT_DATA_LENGTH} bytes", ); let mut bytes = [0u8; REPORT_DATA_LENGTH]; bytes[..data.len()].copy_from_slice(data); diff --git a/crates/teepot/src/quote/error.rs b/crates/teepot/src/quote/error.rs index b469161..cf121d4 100644 --- a/crates/teepot/src/quote/error.rs +++ b/crates/teepot/src/quote/error.rs @@ -104,7 +104,7 @@ pub trait QuoteContextErr { impl QuoteContextErr for Result { type Ok = T; fn str_context(self, msg: I) -> Result { - self.map_err(|e| QuoteError::Unexpected(format!("{}: {}", msg, e))) + self.map_err(|e| QuoteError::Unexpected(format!("{msg}: {e}"))) } } diff --git a/crates/teepot/src/quote/mod.rs b/crates/teepot/src/quote/mod.rs index 8a373cf..c9bead8 100644 --- a/crates/teepot/src/quote/mod.rs +++ b/crates/teepot/src/quote/mod.rs @@ -583,7 +583,7 @@ impl Display for TEEType { TEEType::TDX => "tdx", TEEType::SNP => "snp", }; - write!(f, "{}", str) + write!(f, "{str}") } } diff --git a/crates/teepot/src/quote/phala.rs b/crates/teepot/src/quote/phala.rs index e416110..0fdafbc 100644 --- a/crates/teepot/src/quote/phala.rs +++ b/crates/teepot/src/quote/phala.rs @@ -134,14 +134,14 @@ fn convert_to_collateral( /// Split the last zero byte fn get_str_from_bytes(bytes: &[u8], context: &str) -> Result { let c_str = CStr::from_bytes_until_nul(bytes) - .str_context(format!("Failed to extract CString: {}", context))?; + .str_context(format!("Failed to extract CString: {context}"))?; Ok(c_str.to_string_lossy().into_owned()) } /// Parse JSON field from collateral data fn parse_json_field(data: &[u8], context: &str) -> Result { serde_json::from_str(&get_str_from_bytes(data, context)?) - .str_context(format!("Failed to parse JSON: {}", context)) + .str_context(format!("Failed to parse JSON: {context}")) } /// Convert Collateral to QuoteCollateralV3 diff --git a/crates/teepot/src/quote/tcblevel.rs b/crates/teepot/src/quote/tcblevel.rs index f2baee5..19561a2 100644 --- a/crates/teepot/src/quote/tcblevel.rs +++ b/crates/teepot/src/quote/tcblevel.rs @@ -46,7 +46,7 @@ impl FromStr for TcbLevel { "outofdate" => Ok(TcbLevel::OutOfDate), "outofdateconfigneeded" => Ok(TcbLevel::OutOfDateConfigNeeded), "invalid" => Ok(TcbLevel::Invalid), - _ => Err(format!("Invalid TCB level: {}", s)), + _ => Err(format!("Invalid TCB level: {s}")), } } } @@ -72,8 +72,8 @@ pub fn parse_tcb_levels( let mut set = EnumSet::new(); for level_str in s.split(',') { let level_str = level_str.trim(); - let level = TcbLevel::from_str(level_str) - .map_err(|_| format!("Invalid TCB level: {}", level_str))?; + let level = + TcbLevel::from_str(level_str).map_err(|_| format!("Invalid TCB level: {level_str}"))?; set.insert(level); } Ok(set)