From 2210e6f84e71114d4b10084a27ba0dd6ac8dd038 Mon Sep 17 00:00:00 2001 From: Martin Hoffmann Date: Mon, 30 Jun 2025 14:24:45 +0200 Subject: [PATCH] Code improvements suggested by Clippy 1.88. (#1303) --- build.rs | 10 +- src/api/admin.rs | 4 +- src/api/aspa.rs | 17 +-- src/api/bgp.rs | 49 +++--- src/api/ca.rs | 33 ++-- src/api/history.rs | 4 +- src/api/import.rs | 11 +- src/api/roa.rs | 16 +- src/api/rta.rs | 2 +- src/api/ta.rs | 34 ++--- src/bin/krill.rs | 4 +- src/bin/krillup.rs | 12 +- src/cli/client.rs | 2 +- src/cli/options/args.rs | 6 +- src/cli/options/bgpsec.rs | 7 +- src/cli/options/children.rs | 6 +- src/cli/options/config.rs | 12 +- src/cli/options/parents.rs | 6 +- src/cli/options/pubserver.rs | 6 +- src/cli/options/repo.rs | 6 +- src/cli/options/roas.rs | 4 +- src/cli/report.rs | 2 +- src/cli/ta/options/proxy.rs | 9 +- src/cli/ta/options/signer.rs | 3 +- src/cli/ta/signer.rs | 10 +- src/commons/crypto/signing/dispatch/error.rs | 2 +- .../crypto/signing/dispatch/signerinfo.rs | 27 ++-- .../crypto/signing/dispatch/signerrouter.rs | 55 +++---- src/commons/crypto/signing/misc.rs | 2 +- src/commons/crypto/signing/signers/error.rs | 12 +- .../crypto/signing/signers/kmip/connpool.rs | 4 +- .../crypto/signing/signers/kmip/signer.rs | 46 +++--- .../crypto/signing/signers/pkcs11/context.rs | 10 +- .../crypto/signing/signers/pkcs11/signer.rs | 77 ++++------ src/commons/crypto/signing/signers/probe.rs | 15 +- .../crypto/signing/signers/softsigner.rs | 13 +- src/commons/error.rs | 144 +++++++++--------- src/commons/eventsourcing/store.rs | 30 ++-- src/commons/eventsourcing/test.rs | 6 +- src/commons/eventsourcing/wal.rs | 14 +- src/commons/ext_serde.rs | 3 +- src/commons/file.rs | 14 +- src/commons/httpclient.rs | 50 +++--- src/commons/queue.rs | 3 +- src/commons/storage/backends/disk.rs | 17 +-- src/commons/storage/backends/memory.rs | 6 +- src/commons/storage/store.rs | 16 +- src/commons/version.rs | 4 +- src/config.rs | 45 +++--- src/daemon/http/auth/authorizer.rs | 2 +- src/daemon/http/auth/crypt.rs | 3 +- src/daemon/http/auth/providers/admin_token.rs | 2 +- src/daemon/http/auth/providers/config_file.rs | 11 +- .../auth/providers/openid_connect/claims.rs | 5 +- .../providers/openid_connect/httpclient.rs | 6 +- .../auth/providers/openid_connect/provider.rs | 90 +++++------ .../auth/providers/openid_connect/util.rs | 10 +- src/daemon/http/auth/session.rs | 16 +- src/daemon/http/dispatch/auth.rs | 3 +- src/daemon/http/dispatch/metrics.rs | 4 +- src/daemon/http/response.rs | 2 +- src/daemon/http/tls_keys.rs | 7 +- src/daemon/start.rs | 18 +-- src/server/ca/aspa.rs | 2 +- src/server/ca/certauth.rs | 8 +- src/server/ca/commands.rs | 56 +++---- src/server/ca/events.rs | 81 ++++------ src/server/ca/keys.rs | 11 +- src/server/ca/manager.rs | 94 +++++------- src/server/ca/publishing.rs | 4 +- src/server/ca/roa.rs | 6 +- src/server/ca/status.rs | 11 +- src/server/ca/upgrades/data_migration.rs | 4 +- .../ca/upgrades/pre_0_10_0/migration.rs | 5 +- .../ca/upgrades/pre_0_10_0/old_events.rs | 8 +- .../ca/upgrades/pre_0_14_0/old_events.rs | 2 +- src/server/manager.rs | 15 +- src/server/mq.rs | 57 +++---- src/server/pubd/access.rs | 16 +- src/server/pubd/content.rs | 24 ++- src/server/pubd/manager.rs | 11 +- src/server/pubd/rrdp.rs | 13 +- src/server/pubd/rsync.rs | 2 +- src/server/pubd/upgrades/pre_0_13_0.rs | 2 +- src/server/scheduler.rs | 51 +++---- src/server/taproxy.rs | 28 ++-- src/tasigner/config.rs | 13 +- src/tasigner/signer.rs | 11 +- src/upgrades/data_migration.rs | 10 +- src/upgrades/mod.rs | 63 ++++---- tests/benchmark.rs | 3 +- tests/common.rs | 12 +- tests/functional_keyroll.rs | 2 +- tests/functional_old_data.rs | 8 +- tests/functional_ta.rs | 4 +- 95 files changed, 722 insertions(+), 984 deletions(-) diff --git a/build.rs b/build.rs index 0c9ca3c4..6ebaf804 100644 --- a/build.rs +++ b/build.rs @@ -43,7 +43,7 @@ impl Asset { Some(media) => media, None => { return Err(format!( - "Asset with unknown extension '{}'", path_ext + "Asset with unknown extension '{path_ext}'" )) } }; @@ -130,7 +130,7 @@ fn write_mod( "# )?; for item in assets.0 { - write!(dest, "{},", item)?; + write!(dest, "{item},")?; } writeln!(dest, "];") } @@ -152,14 +152,14 @@ fn main() { let index = match Asset::load(INDEX_PATH.into(), false) { Ok(index) => index, Err(err) => { - eprintln!("{}", err); + eprintln!("{err}"); process::exit(1); } }; let mut assets = Assets::default(); if let Err(err) = assets.load_dir(ASSETS_DIR.into()) { - eprintln!("{}", err); + eprintln!("{err}"); process::exit(1); } @@ -170,6 +170,6 @@ fn main() { process::exit(1) } - println!("cargo:rerun-if-changed={}", UI_DIR); + println!("cargo:rerun-if-changed={UI_DIR}"); } diff --git a/src/api/admin.rs b/src/api/admin.rs index 941cba02..5cee4af6 100644 --- a/src/api/admin.rs +++ b/src/api/admin.rs @@ -523,10 +523,10 @@ impl fmt::Display for UpdateChildRequest { write!(f, "new id cert ")?; } if let Some(resources) = &self.resources { - write!(f, "new resources: {} ", resources)?; + write!(f, "new resources: {resources} ")?; } if let Some(suspend) = self.suspend { - write!(f, "change suspend status to: {}", suspend)?; + write!(f, "change suspend status to: {suspend}")?; } Ok(()) } diff --git a/src/api/aspa.rs b/src/api/aspa.rs index 325d87d1..9646bb0f 100644 --- a/src/api/aspa.rs +++ b/src/api/aspa.rs @@ -49,13 +49,13 @@ impl fmt::Display for AspaDefinitionUpdates { if !self.add_or_replace.is_empty() { write!(f, " add or replace:")?; for definition in &self.add_or_replace { - write!(f, " {}", definition)?; + write!(f, " {definition}")?; } } if !self.remove.is_empty() { write!(f, " remove where customer ASN is:")?; for as_id in &self.remove { - write!(f, " {}", as_id)?; + write!(f, " {as_id}")?; } } @@ -83,7 +83,7 @@ impl AspaDefinitionList { impl fmt::Display for AspaDefinitionList { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for def in self.0.iter() { - writeln!(f, "{}", def)?; + writeln!(f, "{def}")?; } Ok(()) } @@ -256,14 +256,14 @@ impl fmt::Display for AspaProvidersUpdate { if !self.added.is_empty() { write!(f, "adding providers:")?; for added in &self.added { - write!(f, " {}", added)?; + write!(f, " {added}")?; } write!(f, " ")?; } if !self.removed.is_empty() { write!(f, "removing providers:")?; for removed in &self.removed { - write!(f, " {}", removed)?; + write!(f, " {removed}")?; } } Ok(()) @@ -302,16 +302,15 @@ impl fmt::Display for AspaDefinitionFormatError { write!(f, "customer AS missing") } AspaDefinitionFormatError::CustomerAsInvalid(s) => { - write!(f, "cannot parse customer AS: {}", s) + write!(f, "cannot parse customer AS: {s}") } AspaDefinitionFormatError::ProviderAsInvalid(s) => { - write!(f, "cannot parse provider AS: {}", s) + write!(f, "cannot parse provider AS: {s}") } AspaDefinitionFormatError::ProviderAsDuplicate(l, r) => { write!( f, - "duplicate AS in provider list. Found {} and {}", - l, r + "duplicate AS in provider list. Found {l} and {r}" ) } AspaDefinitionFormatError::ExtraParts => { diff --git a/src/api/bgp.rs b/src/api/bgp.rs index 1386d888..24accec6 100644 --- a/src/api/bgp.rs +++ b/src/api/bgp.rs @@ -36,7 +36,7 @@ impl fmt::Display for BgpAnalysisAdvice { writeln!(f)?; writeln!(f, " Announcements from invalid ASNs:")?; for invalid in invalid_asns { - writeln!(f, " {}\n", invalid)?; + writeln!(f, " {invalid}\n")?; } } @@ -47,7 +47,7 @@ impl fmt::Display for BgpAnalysisAdvice { writeln!(f)?; writeln!(f, " Announcements too specific for their ASNs:\n")?; for invalid in invalid_length { - writeln!(f, " {}", invalid)?; + writeln!(f, " {invalid}")?; } } @@ -116,7 +116,7 @@ impl fmt::Display for BgpAnalysisSuggestion { if !self.stale.is_empty() { writeln!(f, "Remove the following stale entries:")?; for auth in &self.stale { - writeln!(f, " {}", auth)?; + writeln!(f, " {auth}")?; } writeln!(f)?; } @@ -126,7 +126,7 @@ impl fmt::Display for BgpAnalysisSuggestion { for entry in &self.too_permissive { writeln!(f, " Remove: {}", entry.current)?; for replace in &entry.new { - writeln!(f, " Add: {}", replace)?; + writeln!(f, " Add: {replace}")?; } writeln!(f)?; } @@ -139,7 +139,7 @@ impl fmt::Display for BgpAnalysisSuggestion { ROAs for the same prefix and a real ASN:" )?; for auth in &self.as0_redundant { - writeln!(f, " {}", auth)?; + writeln!(f, " {auth}")?; } writeln!(f)?; } @@ -151,7 +151,7 @@ impl fmt::Display for BgpAnalysisSuggestion { using max length:" )?; for auth in &self.redundant { - writeln!(f, " {}", auth)?; + writeln!(f, " {auth}")?; } writeln!(f)?; } @@ -164,7 +164,7 @@ impl fmt::Display for BgpAnalysisSuggestion { intended you may want to use AS0 instead:" )?; for auth in &self.disallowing { - writeln!(f, " {}", auth)?; + writeln!(f, " {auth}")?; } writeln!(f)?; } @@ -172,7 +172,7 @@ impl fmt::Display for BgpAnalysisSuggestion { if !self.keep.is_empty() { writeln!(f, "Keep the following authorizations:")?; for auth in &self.keep { - writeln!(f, " {}", auth)?; + writeln!(f, " {auth}")?; } writeln!(f)?; } @@ -183,7 +183,7 @@ impl fmt::Display for BgpAnalysisSuggestion { not covered:" )?; for auth in &self.not_found { - writeln!(f, " {}", auth)?; + writeln!(f, " {auth}")?; } writeln!(f)?; } @@ -195,7 +195,7 @@ impl fmt::Display for BgpAnalysisSuggestion { invalid because they are too specific:" )?; for auth in &self.invalid_length { - writeln!(f, " {}", auth)?; + writeln!(f, " {auth}")?; } writeln!(f)?; } @@ -207,7 +207,7 @@ impl fmt::Display for BgpAnalysisSuggestion { invalid because they are not allowed for these ASNs:" )?; for auth in &self.invalid_asn { - writeln!(f, " {}", auth)?; + writeln!(f, " {auth}")?; } writeln!(f)?; } @@ -356,14 +356,14 @@ impl fmt::Display for BgpAnalysisReport { writeln!(f)?; writeln!(f, "\t\tAuthorizes announcement(s):")?; for ann in roa.authorizes.iter() { - writeln!(f, "\t\t{}", ann)?; + writeln!(f, "\t\t{ann}")?; } if !roa.disallows.is_empty() { writeln!(f)?; writeln!(f, "\t\tDisallows announcement(s):")?; for ann in roa.disallows.iter() { - writeln!(f, "\t\t{}", ann)?; + writeln!(f, "\t\t{ann}")?; } } } @@ -384,21 +384,21 @@ impl fmt::Display for BgpAnalysisReport { writeln!(f)?; writeln!(f, "\t\tAuthorizes announcement(s):")?; for ann in roa.authorizes.iter() { - writeln!(f, "\t\t{}", ann)?; + writeln!(f, "\t\t{ann}")?; } if !roa.disallows.is_empty() { writeln!(f)?; writeln!(f, "\t\tDisallows announcement(s):")?; for ann in roa.disallows.iter() { - writeln!(f, "\t\t{}", ann)?; + writeln!(f, "\t\t{ann}")?; } } writeln!(f)?; writeln!(f, "\t\tMade redundant by:")?; for redundant_by in roa.made_redundant_by.iter() { - writeln!(f, "\t\t{}", redundant_by)?; + writeln!(f, "\t\t{redundant_by}")?; } } writeln!(f)?; @@ -453,7 +453,7 @@ impl fmt::Display for BgpAnalysisReport { writeln!(f)?; writeln!(f, "\t\tDisallows:")?; for ann in roa.disallows.iter() { - writeln!(f, "\t\t{}", ann)?; + writeln!(f, "\t\t{ann}")?; } } writeln!(f)?; @@ -473,14 +473,14 @@ impl fmt::Display for BgpAnalysisReport { writeln!(f)?; writeln!(f, "\t\tAuthorizes announcement(s):")?; for ann in roa.authorizes.iter() { - writeln!(f, "\t\t{}", ann)?; + writeln!(f, "\t\t{ann}")?; } if !roa.disallows.is_empty() { writeln!(f)?; writeln!(f, "\t\tDisallows announcement(s):")?; for ann in roa.disallows.iter() { - writeln!(f, "\t\t{}", ann)?; + writeln!(f, "\t\t{ann}")?; } } } @@ -517,7 +517,7 @@ impl fmt::Display for BgpAnalysisReport { "\t\tMade redundant by ROA configuration(s):" )?; for redundant_by in &roa.made_redundant_by { - writeln!(f, "\t\t{}", redundant_by)?; + writeln!(f, "\t\t{redundant_by}")?; } writeln!(f)?; } @@ -548,7 +548,7 @@ impl fmt::Display for BgpAnalysisReport { writeln!(f)?; writeln!(f, "\t\tDisallowed by ROA configuration(s):")?; for roa in ann.disallowed_by.iter() { - writeln!(f, "\t\t{}", roa)?; + writeln!(f, "\t\t{roa}")?; } } writeln!(f)?; @@ -564,7 +564,7 @@ impl fmt::Display for BgpAnalysisReport { writeln!(f)?; writeln!(f, "\t\tDisallowed by ROA configuration(s):")?; for roa in ann.disallowed_by.iter() { - writeln!(f, "\t\t{}", roa)?; + writeln!(f, "\t\t{roa}")?; } } writeln!(f)?; @@ -1056,12 +1056,11 @@ impl FromStr for Announcement { fn from_str(s: &str) -> Result { let as_roa = RoaPayload::from_str(s).map_err(|e| { - format!("Can't parse: {}, Error: {}", s, e) + format!("Can't parse: {s}, Error: {e}") })?; if as_roa.max_length.is_some() { Err(format!( - "Cannot parse announcement (max length not allowed): {}", - s + "Cannot parse announcement (max length not allowed): {s}" )) } else { diff --git a/src/api/ca.rs b/src/api/ca.rs index 6a6c2fc7..c3145e3a 100644 --- a/src/api/ca.rs +++ b/src/api/ca.rs @@ -87,8 +87,7 @@ impl TryFrom<&IdCertInfo> for IdCert { fn try_from(info: &IdCertInfo) -> Result { IdCert::decode(info.base64.to_bytes().as_ref()).map_err(|e| { error::Error::Custom(format!( - "Could not decode IdCertInfo into IdCert: {}", - e + "Could not decode IdCertInfo into IdCert: {e}" )) }) } @@ -528,7 +527,7 @@ impl ObjectName { /// Creates a new object name from a key identifer and a file extension. pub fn from_key(ki: &KeyIdentifier, extension: &str) -> Self { - ObjectName(format!("{}.{}", ki, extension).into()) + ObjectName(format!("{ki}.{extension}").into()) } /// Creates the name for a CA certificate from its key. @@ -548,7 +547,7 @@ impl ObjectName { /// Creates the name of an ASPA object from the customer ASN. pub fn aspa_from_customer(customer: Asn) -> Self { - ObjectName(format!("{}.asa", customer).into()) + ObjectName(format!("{customer}.asa").into()) } /// Creates the name of a router key from ASN and key identifer. @@ -1026,7 +1025,7 @@ impl<'a> IntoIterator for &'a ParentStatuses { impl fmt::Display for ParentStatuses { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (parent, status) in self.0.iter() { - writeln!(f, "Parent: {}", parent)?; + writeln!(f, "Parent: {parent}")?; match &status.last_exchange { None => writeln!(f, "Status: connection still pending")?, Some(exchange) => { @@ -1729,8 +1728,8 @@ impl fmt::Display for CertAuthInfo { .map(|uri| uri.as_str()) .unwrap_or(""); - writeln!(f, "Base uri: {}", base_uri)?; - writeln!(f, "RRDP uri: {}", rrdp_uri)?; + writeln!(f, "Base uri: {base_uri}")?; + writeln!(f, "RRDP uri: {rrdp_uri}")?; } else { writeln!(f, "No repository configured.")?; } @@ -1754,7 +1753,7 @@ impl fmt::Display for CertAuthInfo { writeln!(f, "Parents:")?; if !self.parents.is_empty() { for parent in &self.parents { - writeln!(f, "{}", parent)?; + writeln!(f, "{parent}")?; } writeln!(f)?; } else { @@ -1762,7 +1761,7 @@ impl fmt::Display for CertAuthInfo { } for (name, rc) in &self.resource_classes { - writeln!(f, "Resource Class: {}", name,)?; + writeln!(f, "Resource Class: {name}",)?; writeln!(f, "Parent: {}", rc.parent_handle)?; writeln!(f, "{}", rc.keys)?; } @@ -1770,7 +1769,7 @@ impl fmt::Display for CertAuthInfo { writeln!(f, "Children:")?; if !self.children.is_empty() { for child_handle in &self.children { - writeln!(f, "{}", child_handle)?; + writeln!(f, "{child_handle}")?; } } else { writeln!(f, "")?; @@ -1955,7 +1954,7 @@ impl fmt::Display for CaRepoDetails { writeln!( f, " base_uri: {}", self.contact.repo_info.base_uri() )?; - writeln!(f, " rpki_notify: {}", rrdp_uri)?; + writeln!(f, " rpki_notify: {rrdp_uri}")?; writeln!(f)?; Ok(()) @@ -1979,10 +1978,10 @@ impl fmt::Display for AllCertAuthIssues { } else { for (ca, issues) in &self.cas { - writeln!(f, "Found issue for CA '{}':", ca)?; + writeln!(f, "Found issue for CA '{ca}':")?; if let Some(repo_issue) = issues.repo_issue() { - writeln!(f, " Repository Issue: {}", repo_issue)?; + writeln!(f, " Repository Issue: {repo_issue}")?; } let parent_issues = issues.parent_issues(); if !parent_issues.is_empty() { @@ -2043,7 +2042,7 @@ impl fmt::Display for CertAuthIssues { } else { if let Some(repo_issue) = self.repo_issue.as_ref() { - writeln!(f, "Repository Issue: {}", repo_issue)?; + writeln!(f, "Repository Issue: {repo_issue}")?; } if !self.parent_issues.is_empty() { for parent_issue in &self.parent_issues { @@ -2131,7 +2130,7 @@ impl RtaList { impl fmt::Display for RtaList { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for name in &self.0 { - writeln!(f, "{}", name)?; + writeln!(f, "{name}")?; } Ok(()) } @@ -2160,7 +2159,7 @@ impl fmt::Display for RtaPrepResponse { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "Created the following keys")?; for key in &self.0 { - writeln!(f, " {}", key)?; + writeln!(f, " {key}")?; } Ok(()) } @@ -2200,7 +2199,7 @@ impl fmt::Display for InvalidCert { ) } Self::Uri(s) => { - write!(f, "Cannot derive filename from URI: {}", s) + write!(f, "Cannot derive filename from URI: {s}") } } } diff --git a/src/api/history.rs b/src/api/history.rs index 1307d9e2..16f92146 100644 --- a/src/api/history.rs +++ b/src/api/history.rs @@ -42,7 +42,7 @@ impl fmt::Display for CommandHistory { CommandHistoryResult::Init() => "INIT".to_string(), CommandHistoryResult::Ok() => "OK".to_string(), CommandHistoryResult::Error(msg) => { - format!("ERROR -> {}", msg) + format!("ERROR -> {msg}") } }; writeln!( @@ -358,7 +358,7 @@ impl fmt::Display for CommandDetails { match &self.effect { CommandEffect::Error { msg, .. } => { - writeln!(f, "Error: {}", msg)? + writeln!(f, "Error: {msg}")? } CommandEffect::Success { events } => { writeln!(f, "Changes:")?; diff --git a/src/api/import.rs b/src/api/import.rs index 47fbeb91..cc33a9bd 100644 --- a/src/api/import.rs +++ b/src/api/import.rs @@ -81,8 +81,7 @@ impl Structure { for ca in &self.cas { if ca.handle == ta_handle { return Err(Error::Custom(format!( - "CA name {} is reserved.", - ta_handle + "CA name {ta_handle} is reserved." ))); } @@ -233,17 +232,17 @@ impl fmt::Display for ImportChild { )?; writeln!(f, "Resources: {}", self.resources)?; if let Some(class_name) = &self.issued_cert.class_name { - writeln!(f, "Classname: {}", class_name)?; + writeln!(f, "Classname: {class_name}")?; } let (ca_repository, rpki_manifest, rpki_notify, key) = self.issued_cert.csr.clone().unpack(); writeln!(f, "Issued Certificate:")?; writeln!(f, " Key Id: {}", key.key_identifier())?; - writeln!(f, " CA repo: {}", ca_repository)?; - writeln!(f, " CA mft: {}", rpki_manifest)?; + writeln!(f, " CA repo: {ca_repository}")?; + writeln!(f, " CA mft: {rpki_manifest}")?; if let Some(rrdp) = rpki_notify { - writeln!(f, " RRDP: {}", rrdp)?; + writeln!(f, " RRDP: {rrdp}")?; } Ok(()) diff --git a/src/api/roa.rs b/src/api/roa.rs index f0f469b6..a7df4755 100644 --- a/src/api/roa.rs +++ b/src/api/roa.rs @@ -386,7 +386,7 @@ impl fmt::Display for RoaConfiguration { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.payload)?; if let Some(comment) = &self.comment { - write!(f, " # {}", comment)?; + write!(f, " # {comment}")?; } Ok(()) } @@ -502,7 +502,7 @@ impl ConfiguredRoas { impl fmt::Display for ConfiguredRoas { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for def in self.0.iter() { - writeln!(f, "{}", def)?; + writeln!(f, "{def}")?; } Ok(()) } @@ -625,10 +625,10 @@ impl FromStr for RoaConfigurationUpdates { impl fmt::Display for RoaConfigurationUpdates { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for a in &self.added { - writeln!(f, "A: {}", a)?; + writeln!(f, "A: {a}")?; } for r in &self.removed { - writeln!(f, "R: {}", r)?; + writeln!(f, "R: {r}")?; } Ok(()) } @@ -991,16 +991,16 @@ impl fmt::Display for AuthorizationFmtError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { AuthorizationFmtError::Pfx(s) => { - write!(f, "Invalid prefix string: {}", s) + write!(f, "Invalid prefix string: {s}") } AuthorizationFmtError::Asn(s) => { - write!(f, "Invalid asn in string: {}", s) + write!(f, "Invalid asn in string: {s}") } AuthorizationFmtError::Auth(s) => { - write!(f, "Invalid authorization string: {}", s) + write!(f, "Invalid authorization string: {s}") } AuthorizationFmtError::Delta(s) => { - write!(f, "Invalid authorization delta string: {}", s) + write!(f, "Invalid authorization delta string: {s}") } } } diff --git a/src/api/rta.rs b/src/api/rta.rs index 32d2d776..88b5c39b 100644 --- a/src/api/rta.rs +++ b/src/api/rta.rs @@ -48,7 +48,7 @@ impl fmt::Display for RtaContentRequest { write!(f, "keys: ")?; for key in self.subject_keys.iter() { - write!(f, "{} ", key)?; + write!(f, "{key} ")?; } writeln!(f)?; writeln!( diff --git a/src/api/ta.rs b/src/api/ta.rs index 6c3dbd47..90cd8d91 100644 --- a/src/api/ta.rs +++ b/src/api/ta.rs @@ -166,19 +166,19 @@ impl TrustAnchorObjects { let mft_uri = self .base_uri .join(ObjectName::mft_from_ca_key(&self.key_identifier).as_ref()) - .map_err(|e| Error::Custom(format!("Cannot make uri: {}", e)))?; + .map_err(|e| Error::Custom(format!("Cannot make uri: {e}")))?; res.push(self.manifest.published_file(mft_uri)); let crl_uri = self .base_uri .join(ObjectName::crl_from_ca_key(&self.key_identifier).as_ref()) - .map_err(|e| Error::Custom(format!("Cannot make uri: {}", e)))?; + .map_err(|e| Error::Custom(format!("Cannot make uri: {e}")))?; res.push(self.crl.published_file(crl_uri)); for (name, object) in self.issued_certs_objects() { let cert_uri = self.base_uri.join(name.as_ref()).map_err(|e| { - Error::Custom(format!("Cannot make uri: {}", e)) + Error::Custom(format!("Cannot make uri: {e}")) })?; res.push(object.published_file(cert_uri)); } @@ -322,7 +322,7 @@ impl std::fmt::Display for TrustAnchorLocator { let base64_string = self.encoded_ski.to_string(); for uri in self.uris.iter() { - writeln!(f, "{}", uri)?; + writeln!(f, "{uri}")?; } writeln!(f, "{}", self.rsync_uri)?; @@ -456,11 +456,11 @@ impl TrustAnchorSignedMessage { let bytes = self.message.to_bytes(); let signed_message = SignedMessage::decode(bytes, true).map_err(|e| { - Error::Custom(format!("Cannot decode signed message: {}", e)) + Error::Custom(format!("Cannot decode signed message: {e}")) })?; signed_message.validate_at(issuer_key, time).map_err(|e| { - Error::Custom(format!("Invalid signed message: {}", e)) + Error::Custom(format!("Invalid signed message: {e}")) })?; Ok(signed_message) @@ -510,10 +510,10 @@ impl fmt::Display for ApiTrustAnchorSignedRequest { for (key, child_req) in &request.requests { match child_req { ProvisioningRequest::Issuance(_) => { - writeln!(f, "key: {} (re-)issue", key)? + writeln!(f, "key: {key} (re-)issue")? } ProvisioningRequest::Revocation(_) => { - writeln!(f, "key: {} revoke", key)? + writeln!(f, "key: {key} revoke")? } } } @@ -577,8 +577,7 @@ impl TrustAnchorSignedRequest { let signed_bytes = signed_message.content().to_bytes(); let signed_request: TrustAnchorSignerRequest = serde_json::from_slice(&signed_bytes).map_err(|e| { Error::Custom(format!( - "Cannot deserialize content of signed Trust Anchor request: {}", - e + "Cannot deserialize content of signed Trust Anchor request: {e}" )) })?; @@ -656,10 +655,10 @@ impl fmt::Display for TrustAnchorSignerRequest { for (key, child_req) in &request.requests { match child_req { ProvisioningRequest::Issuance(_) => { - writeln!(f, "key: {} (re-)issue", key)? + writeln!(f, "key: {key} (re-)issue")? } ProvisioningRequest::Revocation(_) => { - writeln!(f, "key: {} revoke", key)? + writeln!(f, "key: {key} revoke")? } } } @@ -704,8 +703,7 @@ impl TrustAnchorSignedResponse { let signed_bytes = signed_message.content().to_bytes(); let signed_response: TrustAnchorSignerResponse = serde_json::from_slice(&signed_bytes).map_err(|e| { Error::Custom(format!( - "Cannot deserialize content of signed Trust Anchor response: {}", - e + "Cannot deserialize content of signed Trust Anchor response: {e}" )) })?; @@ -777,17 +775,17 @@ impl fmt::Display for TrustAnchorSignerResponse { writeln!(f, "-------------------------------")?; writeln!(f, " child response")?; writeln!(f, "-------------------------------")?; - writeln!(f, "child: {}", child)?; + writeln!(f, "child: {child}")?; for (key, response) in responses.iter() { match response { ProvisioningResponse::Error => { - writeln!(f, "key: {} ERROR", key)? + writeln!(f, "key: {key} ERROR")? } ProvisioningResponse::Issuance(_) => { - writeln!(f, "key: {} issued", key)? + writeln!(f, "key: {key} issued")? } ProvisioningResponse::Revocation(_) => { - writeln!(f, "key: {} revoked", key)? + writeln!(f, "key: {key} revoked")? } } } diff --git a/src/bin/krill.rs b/src/bin/krill.rs index e0795a66..7d067afd 100644 --- a/src/bin/krill.rs +++ b/src/bin/krill.rs @@ -21,12 +21,12 @@ async fn main() { if let Err(e) = start_krill_daemon( Arc::new(config), None ).await { - error!("Krill failed to start: {}", e); + error!("Krill failed to start: {e}"); ::std::process::exit(1); } } Err(e) => { - eprintln!("Could not parse config: {}", e); + eprintln!("Could not parse config: {e}"); ::std::process::exit(1); } } diff --git a/src/bin/krillup.rs b/src/bin/krillup.rs index 9d7642e7..965cf0ec 100644 --- a/src/bin/krillup.rs +++ b/src/bin/krillup.rs @@ -40,7 +40,7 @@ fn main() { Ok(mgr) => mgr, Err(e) => { eprintln!("*** Error Preparing Data Migration ***"); - eprintln!("{}", e); + eprintln!("{e}"); eprintln!(); eprintln!( "Note that your server data has NOT been modified. \ @@ -62,7 +62,7 @@ fn main() { ) { Err(e) => { eprintln!("*** Error Preparing Data Migration ***"); - eprintln!("{}", e); + eprintln!("{e}"); eprintln!(); eprintln!( "Note that your server data has NOT been modified. \ @@ -81,14 +81,12 @@ fn main() { let to = report.versions().to(); if report.data_migration() { info!( - "Prepared and verified upgrade from {} to {}.", - from, to + "Prepared and verified upgrade from {from} to {to}." ); } else { info!( "No preparation is needed for the upgrade from \ - {} to {}.", - from, to + {from} to {to}." ) } }, @@ -97,7 +95,7 @@ fn main() { Command::Migrate(cmd) => { if let Err(e) = migrate(config, cmd.target) { eprintln!("*** Error Migrating DATA ***"); - eprintln!("{}", e); + eprintln!("{e}"); eprintln!(); eprintln!( "Note that your server data has NOT been modified." diff --git a/src/cli/client.rs b/src/cli/client.rs index ed99e2ad..a3cc6e1b 100644 --- a/src/cli/client.rs +++ b/src/cli/client.rs @@ -258,7 +258,7 @@ impl KrillClient { format!("{}/{}", rows.unwrap_or(100), offset) } else if let Some(rows) = rows { - format!("{}", rows) + format!("{rows}") } else { String::new() diff --git a/src/cli/options/args.rs b/src/cli/options/args.rs index 43a143fa..0bb6f320 100644 --- a/src/cli/options/args.rs +++ b/src/cli/options/args.rs @@ -53,14 +53,12 @@ impl fmt::Display for JsonFileError { match self { Self::Io(path, msg, err) => { write!( - f, "Failed to read {} file '{}': {}'", - msg, path, err + f, "Failed to read {msg} file '{path}': {err}'" ) } Self::Parse(path, msg, err) => { write!( - f, "Failed to parse {} file '{}': {}'", - msg, path, err + f, "Failed to parse {msg} file '{path}': {err}'" ) } } diff --git a/src/cli/options/bgpsec.rs b/src/cli/options/bgpsec.rs index 6f299675..77395961 100644 --- a/src/cli/options/bgpsec.rs +++ b/src/cli/options/bgpsec.rs @@ -167,15 +167,14 @@ impl fmt::Display for BgpsecCsrFileError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::Io(path, err) => { - write!(f, "Failed to read CSR file '{}': {}", path, err) + write!(f, "Failed to read CSR file '{path}': {err}") } Self::Decode(path, err) => { - write!(f, "Failed to parse CSR file '{}': {}", path, err) + write!(f, "Failed to parse CSR file '{path}': {err}") } Self::Verify(path, err) => { write!( - f, "Failed to verify signature in CSR file '{}': {}", - path, err + f, "Failed to verify signature in CSR file '{path}': {err}" ) } } diff --git a/src/cli/options/children.rs b/src/cli/options/children.rs index 1d9a97da..c6640665 100644 --- a/src/cli/options/children.rs +++ b/src/cli/options/children.rs @@ -321,13 +321,11 @@ impl fmt::Display for ChildIdCertError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::Io(path, err) => { - write!(f, "Failed to open request file '{}': {}", - path, err + write!(f, "Failed to open request file '{path}': {err}" ) } Self::Parse(path, err) => { - write!(f, "Failed to parse request file '{}': {}", - path, err + write!(f, "Failed to parse request file '{path}': {err}" ) } } diff --git a/src/cli/options/config.rs b/src/cli/options/config.rs index 5d7056ab..0e3bc966 100644 --- a/src/cli/options/config.rs +++ b/src/cli/options/config.rs @@ -65,18 +65,18 @@ impl Simple { Cow::Borrowed(data_dir) } else { - Cow::Owned(format!("{}/", data_dir)) + Cow::Owned(format!("{data_dir}/")) }; config = config.replace( "### storage_uri = \"./data\"", - &format!("storage_uri = \"{}\"", data_dir) + &format!("storage_uri = \"{data_dir}\"") ); } if let Some(log_file) = self.logfile { config = config.replace( "### log_file = \"./krill.log\"", - &format!("log_file = \"{}\"", log_file), + &format!("log_file = \"{log_file}\""), ) } @@ -143,7 +143,7 @@ impl User { // the client browser knows how to construct based on the // users id and a site specific string. Then hash again using // a strong random salt only known to the server. - let weak_salt = format!("krill-lagosta-{}", user_id); + let weak_salt = format!("krill-lagosta-{user_id}"); let weak_salt = weak_salt.nfkc().collect::(); let mut interim_hash = [0u8; 32]; @@ -178,11 +178,11 @@ impl User { .into_iter() // quote the key if needed .map(|KeyValuePair(k, v)| match k.contains(' ') { - true => (format!(r#""{}""#, k), v), + true => (format!(r#""{k}""#), v), false => (k, v), }) // quote the value - .map(|(k, v)| format!(r#"{}="{}""#, k, v)) + .map(|(k, v)| format!(r#"{k}="{v}""#)) .collect::>() .join(", ") ) diff --git a/src/cli/options/parents.rs b/src/cli/options/parents.rs index af6d8e2c..e72593fb 100644 --- a/src/cli/options/parents.rs +++ b/src/cli/options/parents.rs @@ -193,13 +193,11 @@ impl fmt::Display for ParentResponseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::Io(path, err) => { - write!(f, "Failed to open request file '{}': {}", - path, err + write!(f, "Failed to open request file '{path}': {err}" ) } Self::Parse(path, err) => { - write!(f, "Failed to parse request file '{}': {}", - path, err + write!(f, "Failed to parse request file '{path}': {err}" ) } } diff --git a/src/cli/options/pubserver.rs b/src/cli/options/pubserver.rs index c247fd4d..e3cf2c0d 100644 --- a/src/cli/options/pubserver.rs +++ b/src/cli/options/pubserver.rs @@ -353,14 +353,12 @@ impl fmt::Display for PublisherRequestFileError { match self { Self::Io(path, err) => { write!( - f, "Failed to read publisher request file '{}': {}'", - path, err + f, "Failed to read publisher request file '{path}': {err}'" ) } Self::Parse(path, err) => { write!( - f, "Failed to parse publisher request file '{}': {}'", - path, err + f, "Failed to parse publisher request file '{path}': {err}'" ) } } diff --git a/src/cli/options/repo.rs b/src/cli/options/repo.rs index c4aa81f2..28995a3a 100644 --- a/src/cli/options/repo.rs +++ b/src/cli/options/repo.rs @@ -158,14 +158,12 @@ impl fmt::Display for RepositoryResponseFileError { match self { Self::Io(path, err) => { write!( - f, "Failed to read repository response file '{}': {}'", - path, err + f, "Failed to read repository response file '{path}': {err}'" ) } Self::Parse(path, err) => { write!( - f, "Failed to parse repository response file '{}': {}'", - path, err + f, "Failed to parse repository response file '{path}': {err}'" ) } } diff --git a/src/cli/options/roas.rs b/src/cli/options/roas.rs index fe881821..2b7b74af 100644 --- a/src/cli/options/roas.rs +++ b/src/cli/options/roas.rs @@ -225,10 +225,10 @@ impl fmt::Display for RoaUpdatesFileError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::Io(path, err) => { - write!(f, "Failed to read delta file '{}': {}", path, err) + write!(f, "Failed to read delta file '{path}': {err}") } Self::Parse(path, err) => { - write!(f, "Failed to parse delta file '{}': {}", path, err) + write!(f, "Failed to parse delta file '{path}': {err}") } } } diff --git a/src/cli/report.rs b/src/cli/report.rs index d1e9548c..b64bce5b 100644 --- a/src/cli/report.rs +++ b/src/cli/report.rs @@ -95,7 +95,7 @@ impl ReportContent for T { Ok(()) } ReportFormat::Text => { - writeln!(target, "{}", self) + writeln!(target, "{self}") } } } diff --git a/src/cli/ta/options/proxy.rs b/src/cli/ta/options/proxy.rs index feccce5e..532b2d46 100644 --- a/src/cli/ta/options/proxy.rs +++ b/src/cli/ta/options/proxy.rs @@ -455,20 +455,17 @@ impl fmt::Display for CertAuthInfoFileError { match self { Self::Io(path, err) => { write!( - f, "Failed to read child info file '{}': {}'", - path, err + f, "Failed to read child info file '{path}': {err}'" ) } Self::Parse(path, err) => { write!( - f, "Failed to parse child info file '{}': {}'", - path, err + f, "Failed to parse child info file '{path}': {err}'" ) } Self::Cert(path, err) => { write!( - f, "Failed to parse child info file '{}': {}'", - path, err + f, "Failed to parse child info file '{path}': {err}'" ) } } diff --git a/src/cli/ta/options/signer.rs b/src/cli/ta/options/signer.rs index d5fe88f1..445f7642 100644 --- a/src/cli/ta/options/signer.rs +++ b/src/cli/ta/options/signer.rs @@ -318,8 +318,7 @@ impl fmt::Display for ConfigFileError { match self { Self::Parse(path, err) => { write!( - f, "Failed to read config file '{}': {}", - path, err + f, "Failed to read config file '{path}': {err}" ) } Self::Create(err) => err.fmt(f) diff --git a/src/cli/ta/signer.rs b/src/cli/ta/signer.rs index 45054571..78b1be6c 100644 --- a/src/cli/ta/signer.rs +++ b/src/cli/ta/signer.rs @@ -54,16 +54,16 @@ impl std::fmt::Display for SignerClientError { write!(f, "Unrecognised argument. Use 'help'") } SignerClientError::HttpClientError(e) => { - write!(f, "HTTP client error: {}", e) + write!(f, "HTTP client error: {e}") } - SignerClientError::KrillError(e) => write!(f, "{}", e), + SignerClientError::KrillError(e) => write!(f, "{e}"), SignerClientError::StorageError(e) => { - write!(f, "Issue with persistence layer: {}", e) + write!(f, "Issue with persistence layer: {e}") } SignerClientError::ConfigError(e) => { - write!(f, "Issue with configuration file: {}", e) + write!(f, "Issue with configuration file: {e}") } - SignerClientError::Other(msg) => write!(f, "{}", msg), + SignerClientError::Other(msg) => write!(f, "{msg}"), } } } diff --git a/src/commons/crypto/signing/dispatch/error.rs b/src/commons/crypto/signing/dispatch/error.rs index 8c7fee00..bc475014 100644 --- a/src/commons/crypto/signing/dispatch/error.rs +++ b/src/commons/crypto/signing/dispatch/error.rs @@ -10,7 +10,7 @@ impl std::ops::Deref for ErrorString { impl ErrorString { pub fn new(displayable: T) -> Self { - ErrorString(format!("{}", displayable)) + ErrorString(format!("{displayable}")) } } diff --git a/src/commons/crypto/signing/dispatch/signerinfo.rs b/src/commons/crypto/signing/dispatch/signerinfo.rs index 206ac34a..fe109b3a 100644 --- a/src/commons/crypto/signing/dispatch/signerinfo.rs +++ b/src/commons/crypto/signing/dispatch/signerinfo.rs @@ -134,17 +134,16 @@ impl fmt::Display for SignerInfoEvent { match self { SignerInfoEvent::KeyAdded(key_id, internal_key_id) => write!( f, - "added key with key id '{}' and internal key id '{}'", - key_id, internal_key_id + "added key with key id '{key_id}' and internal key id '{internal_key_id}'" ), SignerInfoEvent::KeyRemoved(key_id) => { - write!(f, "removed key with key id '{}'", key_id) + write!(f, "removed key with key id '{key_id}'") } SignerInfoEvent::SignerNameChanged(signer_name) => { - write!(f, "signer name changed to '{}'", signer_name) + write!(f, "signer name changed to '{signer_name}'") } SignerInfoEvent::SignerInfoChanged(signer_info) => { - write!(f, "signer info changed to '{}'", signer_info) + write!(f, "signer info changed to '{signer_info}'") } } } @@ -175,18 +174,17 @@ impl fmt::Display for SignerInfoCommandDetails { SignerInfoCommandDetails::AddKey(key_id, internal_key_id) => { write!( f, - "Add key with key id '{}' and internal key id '{}'", - key_id, internal_key_id + "Add key with key id '{key_id}' and internal key id '{internal_key_id}'" ) } SignerInfoCommandDetails::RemoveKey(key_id) => { - write!(f, "Remove key with key id '{}'", key_id) + write!(f, "Remove key with key id '{key_id}'") } SignerInfoCommandDetails::ChangeSignerName(signer_name) => { - write!(f, "Change signer name to '{}'", signer_name) + write!(f, "Change signer name to '{signer_name}'") } SignerInfoCommandDetails::ChangeSignerInfo(signer_info) => { - write!(f, "Change signer info to '{}'", signer_info) + write!(f, "Change signer info to '{signer_info}'") } } } @@ -500,8 +498,7 @@ impl SignerMapper { SignerHandle::from_str(&uuid::Uuid::new_v4().to_string()) .map_err(|err| { Error::SignerError(format!( - "Generated UUID is not a valid signer handle: {}", - err + "Generated UUID is not a valid signer handle: {err}" )) })?; @@ -630,8 +627,7 @@ impl SignerMapper { .cloned() .ok_or_else(|| { Error::SignerError(format!( - "Key with key id '{}' not found", - key_id + "Key with key id '{key_id}' not found" )) }) } @@ -658,8 +654,7 @@ impl SignerMapper { } } Err(Error::SignerError(format!( - "No signer owns key id '{}'", - key_id + "No signer owns key id '{key_id}'" ))) } } diff --git a/src/commons/crypto/signing/dispatch/signerrouter.rs b/src/commons/crypto/signing/dispatch/signerrouter.rs index c11cfc2a..036b75ef 100644 --- a/src/commons/crypto/signing/dispatch/signerrouter.rs +++ b/src/commons/crypto/signing/dispatch/signerrouter.rs @@ -363,7 +363,7 @@ impl SignerRouter { /// attempts. fn bind_ready_signers(&self) { if let Err(err) = self.do_ready_signer_binding() { - error!("Internal error: Unable to bind ready signers: {}", err); + error!("Internal error: Unable to bind ready signers: {err}"); } } @@ -372,8 +372,7 @@ impl SignerRouter { let num_pending_signers = self.pending_signers.read().unwrap().len(); if num_pending_signers > 0 { trace!( - "Attempting to bind {} pending signers", - num_pending_signers + "Attempting to bind {num_pending_signers} pending signers" ); // Fetch the handle of every signer previously created in the @@ -409,7 +408,7 @@ impl SignerRouter { .and_then(|verify_result| match verify_result { IdentifyResult::Unavailable => { // Signer isn't ready yet, leave it in the pending set and try again next time. - trace!("Signer '{}' is unavailable", signer_name); + trace!("Signer '{signer_name}' is unavailable"); Ok(true) } IdentifyResult::Identified(signer_handle) => { @@ -418,7 +417,7 @@ impl SignerRouter { .write() .unwrap() .insert(signer_handle, signer_provider.clone()); - info!("Signer '{}' is ready for use", signer_name); + info!("Signer '{signer_name}' is ready for use"); // And remove it from the pending set Ok(false) } @@ -429,7 +428,7 @@ impl SignerRouter { RegisterResult::NotReady => { // Strange, it was ready just now when we verified it ... leave it in the // pending set and try again next time. - trace!("Signer '{}' is not ready", signer_name); + trace!("Signer '{signer_name}' is not ready"); true } RegisterResult::ReadyVerified(signer_handle) => { @@ -438,15 +437,14 @@ impl SignerRouter { .write() .unwrap() .insert(signer_handle, signer_provider.clone()); - info!("Signer '{}' is ready for use", signer_name); + info!("Signer '{signer_name}' is ready for use"); // And remove it from the pending set false } RegisterResult::ReadyUnusable(err) => { // Signer registration failed, remove it from the pending set error!( - "Signer '{}' could not be registered: signer is not usable: {}", - signer_name, err + "Signer '{signer_name}' could not be registered: signer is not usable: {err}" ); false } @@ -454,7 +452,7 @@ impl SignerRouter { } IdentifyResult::Unusable => { // Signer is ready and unusable, remove it from the pending set - error!("Signer '{}' could not be identified: signer is not usable", signer_name); + error!("Signer '{signer_name}' could not be identified: signer is not usable"); Ok(false) } IdentifyResult::Corrupt => { @@ -482,7 +480,7 @@ impl SignerRouter { .as_ref() .unwrap() .get_signer_handles() - .map_err(|err| format!("Failed to get signer handles: {}", err)) + .map_err(|err| format!("Failed to get signer handles: {err}")) } /// Checks if the signer identity can be shown to match one of the known @@ -568,9 +566,7 @@ impl SignerRouter { .get_signer_name(candidate_handle)?; let signer_name = signer_provider.get_name().to_string(); trace!( - "Attempting to identify signer '{}' using identity key stored for signer '{}'", - signer_name, - handle_name + "Attempting to identify signer '{signer_name}' using identity key stored for signer '{handle_name}'" ); let public_key = match self @@ -583,8 +579,7 @@ impl SignerRouter { Err(err) => match err { crate::commons::error::Error::SignerError(err) => { error!( - "Internal error: Identity public key for signer '{}' is invalid: {}", - handle_name, err + "Internal error: Identity public key for signer '{handle_name}' is invalid: {err}" ); return Ok(IdentifyResult::Corrupt); } @@ -603,25 +598,24 @@ impl SignerRouter { .sign_registration_challenge(&signer_private_key_id, challenge) { Err(SignerError::TemporarilyUnavailable) => { - debug!("Signer '{}' could not be contacted", signer_name); + debug!("Signer '{signer_name}' could not be contacted"); return Ok(IdentifyResult::Unavailable); } Err(SignerError::KeyNotFound) => { debug!( - "Signer '{}' not matched: private key id '{}' not found", - signer_name, signer_private_key_id + "Signer '{signer_name}' not matched: private key id '{signer_private_key_id}' not found" ); return Ok(IdentifyResult::Unidentified); } Err(err) => { - error!("Signer '{}' is unusable: {}", signer_name, err); + error!("Signer '{signer_name}' is unusable: {err}"); return Ok(IdentifyResult::Unusable); } Ok(res) => res, }; if public_key.verify(challenge, &signature).is_ok() { - debug!("Signer '{}' is ready and known, binding", signer_name); + debug!("Signer '{signer_name}' is ready and known, binding"); let signer_info = signer_provider .get_info() .unwrap_or_else(|| "No signer info".to_string()); @@ -637,8 +631,7 @@ impl SignerRouter { // This is unexpected and perhaps indicative of a deeper // problem but log and keep going. error!( - "Internal error: Failed to change name of signer to '{}': {}", - signer_name, err + "Internal error: Failed to change name of signer to '{signer_name}': {err}" ); } if let Err(err) = self @@ -650,19 +643,16 @@ impl SignerRouter { // This is unexpected and perhaps indicative of a deeper // problem but log and keep going. error!( - "Internal error: Failed to change info for signer '{}' to '{}': {}", - signer_name, signer_info, err + "Internal error: Failed to change info for signer '{signer_name}' to '{signer_info}': {err}" ); } debug!( - "Signer '{}' bound to signer mapper handle '{}'", - signer_name, candidate_handle + "Signer '{signer_name}' bound to signer mapper handle '{candidate_handle}'" ); } else { debug!( - "Signer '{}' not matched: incorrect signature created with private key '{}'", - signer_name, signer_private_key_id + "Signer '{signer_name}' not matched: incorrect signature created with private key '{signer_private_key_id}'" ); } @@ -682,7 +672,7 @@ impl SignerRouter { ) -> Result { let signer_name = signer_provider.get_name().to_string(); - trace!("Attempting to register signer '{}'", signer_name); + trace!("Attempting to register signer '{signer_name}'"); let (public_key, signer_private_key_id) = match signer_provider.create_registration_key() { @@ -714,7 +704,7 @@ impl SignerRouter { )); } - debug!("Signer '{}' is ready and new, binding", signer_name); + debug!("Signer '{signer_name}' is ready and new, binding"); let signer_info = signer_provider .get_info() @@ -730,8 +720,7 @@ impl SignerRouter { signer_provider.set_handle(signer_handle.clone()); debug!( - "Signer '{}' bound to signer handle '{}'", - signer_name, signer_handle + "Signer '{signer_name}' bound to signer handle '{signer_handle}'" ); Ok(RegisterResult::ReadyVerified(signer_handle)) } diff --git a/src/commons/crypto/signing/misc.rs b/src/commons/crypto/signing/misc.rs index 64a20250..adc77d51 100644 --- a/src/commons/crypto/signing/misc.rs +++ b/src/commons/crypto/signing/misc.rs @@ -148,7 +148,7 @@ impl SignSupport { // Still, to to be absolutely sure and future proof it's better to // fail with an error than it would be to unwrap and panic. IssuedCertificate::create(cert, uri, resources, limit).map_err(|e| { - Error::Custom(format!("Signed certificate has issue: {}", e)) + Error::Custom(format!("Signed certificate has issue: {e}")) }) } diff --git a/src/commons/crypto/signing/signers/error.rs b/src/commons/crypto/signing/signers/error.rs index 245d47f0..08eb70fe 100644 --- a/src/commons/crypto/signing/signers/error.rs +++ b/src/commons/crypto/signing/signers/error.rs @@ -33,20 +33,20 @@ impl fmt::Display for SignerError { match self { SignerError::DecodeError => write!(f, "Could not decode key"), SignerError::InvalidStorage(url) => { - write!(f, "Invalid storage url: {}", url) + write!(f, "Invalid storage url: {url}") } SignerError::IoError(e) => e.fmt(f), SignerError::JsonError(e) => { - write!(f, "Could not decode public key info: {}", e) + write!(f, "Could not decode public key info: {e}") } SignerError::KeyNotFound => write!(f, "Could not find key"), - SignerError::KmipError(e) => write!(f, "KMIP Error: {}", e), - SignerError::OpenSslError(e) => write!(f, "OpenSSL Error: {}", e), - SignerError::Other(e) => write!(f, "Signer error: {}", e), + SignerError::KmipError(e) => write!(f, "KMIP Error: {e}"), + SignerError::OpenSslError(e) => write!(f, "OpenSSL Error: {e}"), + SignerError::Other(e) => write!(f, "Signer error: {e}"), SignerError::PermanentlyUnusable => { write!(f, "Signer is unusable") } - SignerError::Pkcs11Error(e) => write!(f, "{}", e), /* Cryptoki prefixes e with "PKCS11 error" */ + SignerError::Pkcs11Error(e) => write!(f, "{e}"), /* Cryptoki prefixes e with "PKCS11 error" */ SignerError::TemporarilyUnavailable => { write!(f, "Signer is unavailable") } diff --git a/src/commons/crypto/signing/signers/kmip/connpool.rs b/src/commons/crypto/signing/signers/kmip/connpool.rs index 20393b8d..c75ae94b 100644 --- a/src/commons/crypto/signing/signers/kmip/connpool.rs +++ b/src/commons/crypto/signing/signers/kmip/connpool.rs @@ -134,12 +134,12 @@ where E: std::fmt::Display, { fn handle_error(&self, err: E) { - warn!("Pool error: {}", err) + warn!("Pool error: {err}") } } impl From for SignerError { fn from(err: r2d2::Error) -> Self { - SignerError::KmipError(format!("{}", err)) + SignerError::KmipError(format!("{err}")) } } diff --git a/src/commons/crypto/signing/signers/kmip/signer.rs b/src/commons/crypto/signing/signers/kmip/signer.rs index 70487ee3..6f9469dc 100644 --- a/src/commons/crypto/signing/signers/kmip/signer.rs +++ b/src/commons/crypto/signing/signers/kmip/signer.rs @@ -261,7 +261,7 @@ impl TryFrom<&KmipSignerConfig> for ConnectionSettings { fn read_binary_file(file_path: &PathBuf) -> Result, SignerError> { std::fs::read(file_path).map_err(|err| { SignerError::IoError(KrillIoError::new( - format!("Failed to read file '{:?}'", file_path), + format!("Failed to read file '{file_path:?}'"), err, )) }) @@ -422,15 +422,15 @@ impl KmipSigner { match err { // Fatal error kmip::client::Error::ConfigurationError(err) => { - error!("Failed to connect KMIP server: Configuration error: {}", err); + error!("Failed to connect KMIP server: Configuration error: {err}"); ProbeError::CompletedUnusable } // I/O error attempting to contact the server or a problem on an internal problem at the server, not // necessarily fatal or a reason to abort creating the pool. kmip::client::Error::ServerError(err) => { - error!("Failed to connect KMIP server: Server error: {}", err); - ProbeError::CallbackFailed(SignerError::KmipError(format!("Failed to connect to server: {}", err))) + error!("Failed to connect KMIP server: Server error: {err}"); + ProbeError::CallbackFailed(SignerError::KmipError(format!("Failed to connect to server: {err}"))) } // Impossible errors: we didn't yet try to send a request or receive a response @@ -441,12 +441,12 @@ impl KmipSigner { | kmip::client::Error::InternalError(err) | kmip::client::Error::Unknown(err) | kmip::client::Error::ItemNotFound(err) => { - error!("Failed to connect KMIP server: Unexpected error: {}", err); + error!("Failed to connect KMIP server: Unexpected error: {err}"); ProbeError::CompletedUnusable } other => { - error!("Failed to connect KMIP server: Unexpected error: {}", other); + error!("Failed to connect KMIP server: Unexpected error: {other}"); ProbeError::CompletedUnusable } } @@ -667,8 +667,7 @@ impl KmipSigner { .add_key(signer_handle, key_id, &internal_key_id) .map_err(|err| { SignerError::KmipError(format!( - "Failed to record signer key: {}", - err + "Failed to record signer key: {err}" )) })?; @@ -735,8 +734,8 @@ impl KmipSigner { // should be none as they key should either be renamed after // creation or should have been deleted at some point). let prefix = format!("krill_new_key_{}", Timestamp::now()); - let private_key_name = format!("{}_priv", prefix); - let public_key_name = format!("{}_pub", prefix); + let private_key_name = format!("{prefix}_priv"); + let public_key_name = format!("{prefix}_pub"); // Create the RSA key pair let kmip_key_pair_ids = @@ -809,9 +808,9 @@ impl KmipSigner { // more helpful names to the keys such as the name of the CA they were // created for? let hex_key_id = hex::encode(public_key.key_identifier()); - let new_public_key_name = format!("krill-public-key-{}", hex_key_id); + let new_public_key_name = format!("krill-public-key-{hex_key_id}"); let new_private_key_name = - format!("krill-private-key-{}", hex_key_id); + format!("krill-private-key-{hex_key_id}"); // Rename the keys to their new names self.with_conn("rename key", |conn| { @@ -852,8 +851,7 @@ impl KmipSigner { } _ => { return Err(SignerError::KmipError(format!( - "Failed to get key material: unsupported cryptographic object type returned by KMIP Get operation for public key with ID '{}'", - public_key_id))); + "Failed to get key material: unsupported cryptographic object type returned by KMIP Get operation for public key with ID '{public_key_id}'"))); } }; @@ -861,16 +859,14 @@ impl KmipSigner { KeyMaterial::Bytes(bytes) => { PublicKey::rsa_from_bits_bytes(bytes::Bytes::from(bytes)).map_err(|e| { SignerError::KmipError(format!( - "Failed to construct RSA Public for key with ID '{}'. Error: {}", - public_key_id, e + "Failed to construct RSA Public for key with ID '{public_key_id}'. Error: {e}" )) }) } KeyMaterial::TransparentRSAPublicKey(pub_key) => { PublicKey::rsa_from_components(&pub_key.modulus, &pub_key.public_exponent).map_err(|e| { SignerError::KmipError(format!( - "Failed to construct RSA Public for key with ID '{}'. Error: {}", - public_key_id, e + "Failed to construct RSA Public for key with ID '{public_key_id}'. Error: {e}" )) }) } @@ -878,20 +874,17 @@ impl KmipSigner { if let Some(public_exponent) = priv_key.public_exponent { PublicKey::rsa_from_components(&priv_key.modulus, &public_exponent).map_err(|e| { SignerError::KmipError(format!( - "Failed to construct RSA Public for key with ID '{}'. Error: {}", - public_key_id, e + "Failed to construct RSA Public for key with ID '{public_key_id}'. Error: {e}" )) }) } else { Err(SignerError::KmipError(format!( - "Failed to get key material: missing exponent in transparent RSA private key returned by KMIP Get operation for public key with ID '{}'", - public_key_id))) + "Failed to get key material: missing exponent in transparent RSA private key returned by KMIP Get operation for public key with ID '{public_key_id}'"))) } } _ => { Err(SignerError::KmipError(format!( - "Failed to get key material: unsupported key material type {:?} returned by KMIP Get operation for public key with ID '{}'", - key_material, public_key_id))) + "Failed to get key material: unsupported key material type {key_material:?} returned by KMIP Get operation for public key with ID '{public_key_id}'"))) } } } @@ -1088,8 +1081,7 @@ impl KmipSigner { ) .map_err(|err| { SignerError::KmipError(format!( - "One-off signing of data failed: {}", - err + "One-off signing of data failed: {err}" )) }); @@ -1109,7 +1101,7 @@ impl From for SignerError { fn from(err: kmip::client::Error) -> Self { match err { kmip::client::Error::ItemNotFound(_) => SignerError::KeyNotFound, - _ => SignerError::KmipError(format!("Client error: {}", err)), + _ => SignerError::KmipError(format!("Client error: {err}")), } } } diff --git a/src/commons/crypto/signing/signers/pkcs11/context.rs b/src/commons/crypto/signing/signers/pkcs11/context.rs index 05fad009..6ee459d1 100644 --- a/src/commons/crypto/signing/signers/pkcs11/context.rs +++ b/src/commons/crypto/signing/signers/pkcs11/context.rs @@ -115,8 +115,7 @@ impl Pkcs11Context { // path represents a file. let lib_file_name = lib_path.file_name().ok_or_else(|| { SignerError::Pkcs11Error(format!( - "Failed to load PKCS#11 library '{:?}': path does not refer to a file", - lib_path + "Failed to load PKCS#11 library '{lib_path:?}': path does not refer to a file" )) })?; @@ -129,16 +128,15 @@ impl Pkcs11Context { // Note, we cannot use entry and or_insert_with because our fn may // fail. if !locked_contexts.contains_key(&lib_file_name) { - trace!("Loading PKCS#11 library '{:?}'", lib_path); + trace!("Loading PKCS#11 library '{lib_path:?}'"); let ctx = Pkcs11::new(lib_path).map_err(|err| { SignerError::Pkcs11Error(format!( - "Failed to load PKCS#11 library '{:?}': {}", - lib_path, err + "Failed to load PKCS#11 library '{lib_path:?}': {err}" )) })?; - trace!("Loaded PKCS#11 library '{:?}'", lib_path); + trace!("Loaded PKCS#11 library '{lib_path:?}'"); locked_contexts.insert( lib_file_name.clone(), ThreadSafePkcs11Context::new(&lib_file_name, ctx), diff --git a/src/commons/crypto/signing/signers/pkcs11/signer.rs b/src/commons/crypto/signing/signers/pkcs11/signer.rs index 9421dc80..5a128844 100644 --- a/src/commons/crypto/signing/signers/pkcs11/signer.rs +++ b/src/commons/crypto/signing/signers/pkcs11/signer.rs @@ -420,9 +420,8 @@ impl Pkcs11Signer { ) => { // https://github.com/NLnetLabs/krill/issues/1019 let err_msg = format!( - "{} [Note: This error can occur if the signer does not support authenticated \ - access to public keys. Setting `CKA_PRIVATE` in krill.conf to \"false\"` may help]", - err + "{err} [Note: This error can occur if the signer does not support authenticated \ + access to public keys. Setting `CKA_PRIVATE` in krill.conf to \"false\"` may help]" ); Err(SignerError::Pkcs11Error(err_msg)) } @@ -571,12 +570,11 @@ impl Pkcs11Signer { let cryptoki_info = readable_ctx.get_info().map_err(|err| { error!( - "[{}] Unable to read PKCS#11 info for library '{}': {}", - name, lib_name, err + "[{name}] Unable to read PKCS#11 info for library '{lib_name}': {err}" ); ProbeError::CompletedUnusable })?; - trace!("[{}] C_GetInfo(): {:?}", name, cryptoki_info); + trace!("[{name}] C_GetInfo(): {cryptoki_info:?}"); let slot = match &conn_settings.slot { SlotIdOrLabel::Id(id) => { @@ -584,8 +582,7 @@ impl Pkcs11Signer { .get_slot_list(false) .map_err(|err| { error!( - "[{}] Unable to get PKCS#11 slot list for library '{}': {}", - name, lib_name, err + "[{name}] Unable to get PKCS#11 slot list for library '{lib_name}': {err}" ); ProbeError::CompletedUnusable })? @@ -593,8 +590,7 @@ impl Pkcs11Signer { .find(|&slot| slot.id() == *id) .ok_or_else(|| { error!( - "[{}] No PKCS#11 slot found for library '{}' with id {}", - name, lib_name, id + "[{name}] No PKCS#11 slot found for library '{lib_name}' with id {id}" ); ProbeError::CallbackFailed( SignerError::TemporarilyUnavailable @@ -607,17 +603,15 @@ impl Pkcs11Signer { Ok(Some(slot)) => slot, Ok(None) => { let err_msg = format!( - "[{}] No PKCS#11 slot found for library '{}' with label '{}'", - name, lib_name, label + "[{name}] No PKCS#11 slot found for library '{lib_name}' with label '{label}'" ); - error!("{}", err_msg); + error!("{err_msg}"); return Err(ProbeError::CallbackFailed(SignerError::TemporarilyUnavailable)); } Err(err) => { error!( - "[{}] Failed to enumerate PKCS#11 slots for library '{}': {}", - name, lib_name, err + "[{name}] Failed to enumerate PKCS#11 slots for library '{lib_name}': {err}" ); return Err(ProbeError::CompletedUnusable); } @@ -627,11 +621,10 @@ impl Pkcs11Signer { let slot_info = readable_ctx.get_slot_info(slot).map_err(|err| { let err_msg = format!( - "[{}] Unable to read PKCS#11 slot info for library '{}' slot {}: {}", - name, lib_name, slot, err + "[{name}] Unable to read PKCS#11 slot info for library '{lib_name}' slot {slot}: {err}" ); - error!("{}", err_msg); + error!("{err_msg}"); if is_transient_error(&err) { ProbeError::CallbackFailed(SignerError::TemporarilyUnavailable) @@ -639,15 +632,14 @@ impl Pkcs11Signer { ProbeError::CallbackFailed(SignerError::Pkcs11Error(err_msg)) } })?; - trace!("[{}] C_GetSlotInfo(): {:?}", name, slot_info); + trace!("[{name}] C_GetSlotInfo(): {slot_info:?}"); let token_info = readable_ctx.get_token_info(slot).map_err(|err| { let err_msg = format!( - "[{}] Unable to read PKCS#11 token info for library '{}' slot {}: {}", - name, lib_name, slot, err + "[{name}] Unable to read PKCS#11 token info for library '{lib_name}' slot {slot}: {err}" ); - error!("{}", err_msg); + error!("{err_msg}"); if is_transient_error(&err) { ProbeError::CallbackFailed(SignerError::TemporarilyUnavailable) @@ -655,7 +647,7 @@ impl Pkcs11Signer { ProbeError::CallbackFailed(SignerError::Pkcs11Error(err_msg)) } })?; - trace!("[{}] C_GetTokenInfo(): {:?}", name, token_info); + trace!("[{name}] C_GetTokenInfo(): {token_info:?}"); let user_pin = conn_settings.user_pin.clone(); Ok((cryptoki_info, slot, slot_info, token_info, user_pin)) @@ -677,17 +669,13 @@ impl Pkcs11Signer { LoginMode::LoginRequired => { session.login(UserType::User, user_pin.as_ref()).map_err(|err| { error!( - "[{}] Unable to login to PKCS#11 session for library '{}' slot {}: {}", - name, lib_name, slot, err + "[{name}] Unable to login to PKCS#11 session for library '{lib_name}' slot {slot}: {err}" ); ProbeError::CallbackFailed(SignerError::TemporarilyUnavailable) })?; trace!( - "[{}] Logged in to PKCS#11 session for library '{}' slot {}", - name, - lib_name, - slot, + "[{name}] Logged in to PKCS#11 session for library '{lib_name}' slot {slot}", ); Ok(Some(session)) @@ -698,13 +686,12 @@ impl Pkcs11Signer { let conn_settings = status.config()?; let lib_name = &conn_settings.lib_path; - debug!("[{}] Probing server using library '{}'", name, lib_name); + debug!("[{name}] Probing server using library '{lib_name}'"); let context = initialize_if_needed(&conn_settings).map_err(|err| { error!( - "[{}] Unable to initialize PKCS#11 info for library '{}': {}", - name, lib_name, err + "[{name}] Unable to initialize PKCS#11 info for library '{lib_name}': {err}" ); ProbeError::CompletedUnusable })?; @@ -718,8 +705,7 @@ impl Pkcs11Signer { Ok((cryptoki_info, slot, _slot_info, token_info, user_pin)) => { let session = Pkcs11Session::new(context.clone(), slot).map_err(|err| { error!( - "[{}] Unable to open PKCS#11 session for library '{}' slot {}: {}", - name, lib_name, slot, err + "[{name}] Unable to open PKCS#11 session for library '{lib_name}' slot {slot}: {err}" ); ProbeError::CompletedUnusable })?; @@ -763,13 +749,11 @@ impl Pkcs11Signer { ); info!( - "Using PKCS#11 token '{}' in slot {} of server '{}' via library '{}'", - token_identification, slot, server_identification, lib_name + "Using PKCS#11 token '{token_identification}' in slot {slot} of server '{server_identification}' via library '{lib_name}'" ); let server_info = format!( - "PKCS#11 Signer [token: {}, slot: {}, server: {}, library: {}]", - token_identification, slot, server_identification, lib_name + "PKCS#11 Signer [token: {token_identification}, slot: {slot}, server: {server_identification}, library: {lib_name}]" ); let state = UsableServerState::new( @@ -881,8 +865,7 @@ impl Pkcs11Signer { // Try (and retry if needed) the requested operation. backoff::retry_notify(backoff_policy, op, notify).map_err(|e| { error!( - "[{}] {} failed, retries exhausted: {}", - signer_name, desc, e + "[{signer_name}] {desc} failed, retries exhausted: {e}" ); e.into() }) @@ -909,8 +892,7 @@ impl Pkcs11Signer { .add_key(signer_handle, key_id, &internal_key_id) .map_err(|err| { SignerError::Pkcs11Error(format!( - "Failed to record signer key: {}", - err + "Failed to record signer key: {err}" )) })?; @@ -1053,8 +1035,7 @@ impl Pkcs11Signer { { PublicKey::rsa_from_components(m, e).map_err(|e| { SignerError::Pkcs11Error(format!( - "Failed to construct RSA Public for key '{:?}'. Error: {}", - pub_handle, e + "Failed to construct RSA Public for key '{pub_handle:?}'. Error: {e}" )) }) } else { @@ -1067,8 +1048,7 @@ impl Pkcs11Signer { } } else { Err(SignerError::Pkcs11Error(format!( - "Unable to obtain modulus and public exponent attributes for key {:?}", - pub_handle + "Unable to obtain modulus and public exponent attributes for key {pub_handle:?}" ))) } } @@ -1301,8 +1281,7 @@ impl Pkcs11Signer { .sign_with_key(priv_handle, algorithm, data.as_ref()) .map_err(|err| { SignerError::Pkcs11Error(format!( - "One-off signing of data failed: {}", - err + "One-off signing of data failed: {err}" )) }); @@ -1560,7 +1539,7 @@ fn is_transient_error(err: &Pkcs11Error) -> bool { impl From for SignerError { fn from(err: Pkcs11Error) -> Self { if is_transient_error(&err) { - error!("PKCS#11 signer unavailable: {}", err); + error!("PKCS#11 signer unavailable: {err}"); SignerError::TemporarilyUnavailable } else { SignerError::Pkcs11Error(err.to_string()) diff --git a/src/commons/crypto/signing/signers/probe.rs b/src/commons/crypto/signing/signers/probe.rs index 927f5a2e..69ec14a5 100644 --- a/src/commons/crypto/signing/signers/probe.rs +++ b/src/commons/crypto/signing/signers/probe.rs @@ -346,8 +346,7 @@ pub mod tests { match res { Err(ProbeError::CompletedUnusable) => {} other => panic!( - "Expected Err(ProbeError::PermanentlyUnusable) but got {:?}", - other + "Expected Err(ProbeError::PermanentlyUnusable) but got {other:?}" ), } } @@ -364,8 +363,7 @@ pub mod tests { match res { Err(ProbeError::CompletedUnusable) => {} other => panic!( - "Expected Err(ProbeError::PermanentlyUnusable) but got {:?}", - other + "Expected Err(ProbeError::PermanentlyUnusable) but got {other:?}" ), } } @@ -382,8 +380,7 @@ pub mod tests { match res { Err(ProbeError::CompletedUnusable) => {} other => panic!( - "Expected Err(ProbeError::PermanentlyUnusable) but got {:?}", - other + "Expected Err(ProbeError::PermanentlyUnusable) but got {other:?}" ), } } @@ -400,8 +397,7 @@ pub mod tests { match res { Err(ProbeError::AwaitingNextProbe) => {} other => panic!( - "Expected Err(ProbeError::AwaitingNextProbe) but got {:?}", - other + "Expected Err(ProbeError::AwaitingNextProbe) but got {other:?}" ), } } @@ -420,8 +416,7 @@ pub mod tests { match res { Err(ProbeError::AwaitingNextProbe) => {} other => panic!( - "Expected Err(ProbeError::AwaitingNextProbe) but got {:?}", - other + "Expected Err(ProbeError::AwaitingNextProbe) but got {other:?}" ), } } diff --git a/src/commons/crypto/signing/signers/softsigner.rs b/src/commons/crypto/signing/signers/softsigner.rs index 873acc49..d0097432 100644 --- a/src/commons/crypto/signing/signers/softsigner.rs +++ b/src/commons/crypto/signing/signers/softsigner.rs @@ -163,7 +163,7 @@ impl OpenSslSigner { .store(&Key::new_global(Segment::parse_lossy(&key_id.to_string())), &json) // key_id should always be a valid Segment { Ok(_) => Ok(key_id), - Err(err) => Err(SignerError::Other(format!("Failed to store key: {}:", err))), + Err(err) => Err(SignerError::Other(format!("Failed to store key: {err}:"))), } } @@ -200,7 +200,7 @@ impl OpenSslSigner { { Ok(Some(kp)) => Ok(kp), Ok(None) => Err(SignerError::KeyNotFound), - Err(err) => Err(SignerError::Other(format!("Failed to get key: {}", err))), + Err(err) => Err(SignerError::Other(format!("Failed to get key: {err}"))), } } @@ -220,11 +220,10 @@ impl OpenSslSigner { SignerError::Other("OpenSSL: Failed to record signer key: Signer handle not set".to_string()) })?; mapper - .add_key(signer_handle, key_id, &format!("{}", key_id)) + .add_key(signer_handle, key_id, &format!("{key_id}")) .map_err(|err| { SignerError::Other(format!( - "Failed to record signer key: {}", - err + "Failed to record signer key: {err}" )) }) } else { @@ -362,7 +361,7 @@ impl OpenSslKeyPair { PKey::private_key_from_pem(pem.as_bytes()) .map(|pkey| OpenSslKeyPair { pkey }) .map_err(|e| { - SignerError::Other(format!("Invalid private key: {}", e)) + SignerError::Other(format!("Invalid private key: {e}")) }) } @@ -374,7 +373,7 @@ impl OpenSslKeyPair { PKey::private_key_from_der(&bytes) .map(|pkey| OpenSslKeyPair { pkey }) .map_err(|e| { - SignerError::Other(format!("Invalid private key: {}", e)) + SignerError::Other(format!("Invalid private key: {e}")) }) } } diff --git a/src/commons/error.rs b/src/commons/error.rs index 449e5b4b..ac5fc2c8 100644 --- a/src/commons/error.rs +++ b/src/commons/error.rs @@ -83,7 +83,7 @@ impl fmt::Display for RoaDeltaError { if !self.duplicates.is_empty() { writeln!(f, "Cannot add the following duplicate ROAs:")?; for dup in self.duplicates.iter() { - writeln!(f, " {}", dup)?; + writeln!(f, " {dup}")?; } } if !self.notheld.is_empty() { @@ -92,13 +92,13 @@ impl fmt::Display for RoaDeltaError { "Cannot add the following ROAs with prefixes not on any of your certificates:" )?; for not in self.notheld.iter() { - writeln!(f, " {}", not)?; + writeln!(f, " {not}")?; } } if !self.unknowns.is_empty() { writeln!(f, "Cannot remove the following unknown ROAs:")?; for unk in self.unknowns.iter() { - writeln!(f, " {}", unk)?; + writeln!(f, " {unk}")?; } } if !self.invalid_length.is_empty() { @@ -107,7 +107,7 @@ impl fmt::Display for RoaDeltaError { "The following ROAs have a max length which is invalid for the prefix:" )?; for unk in self.invalid_length.iter() { - writeln!(f, " {}", unk)?; + writeln!(f, " {unk}")?; } } Ok(()) @@ -140,15 +140,13 @@ impl ApiAuthError { match resource { Some(res) => { format!( - "User '{}' does not have permission '{}' \ - on resource '{}'", - actor, perm, res, + "User '{actor}' does not have permission '{perm}' \ + on resource '{res}'", ) }, None => { format!( - "User '{}' does not have permission '{}'", - actor, perm, + "User '{actor}' does not have permission '{perm}'", ) } } @@ -408,23 +406,23 @@ impl fmt::Display for Error { //----------------------------------------------------------------- // System Issues //----------------------------------------------------------------- - Error::IoError(e) => write!(f, "I/O error: {}", e), - Error::KeyValueError(e) => write!(f, "Key/Value error: {}", e), - Error::QueueError(e) => write!(f, "Queue error: {}", e), - Error::AggregateStoreError(e) => write!(f, "Persistence (aggregate store) error: {}", e), - Error::WalStoreError(e) => write!(f, "Persistence (wal store) error: {}", e), - Error::SignerError(e) => write!(f, "Signing issue: {}", e), - Error::HttpsSetup(e) => write!(f, "Cannot set up HTTPS: {}", e), - Error::HttpClientError(e) => write!(f, "HTTP client error: {}", e), - Error::ConfigError(e) => write!(f, "Configuration error: {}", e), - Error::UpgradeError(e) => write!(f, "Could not upgrade Krill: {}", e), + Error::IoError(e) => write!(f, "I/O error: {e}"), + Error::KeyValueError(e) => write!(f, "Key/Value error: {e}"), + Error::QueueError(e) => write!(f, "Queue error: {e}"), + Error::AggregateStoreError(e) => write!(f, "Persistence (aggregate store) error: {e}"), + Error::WalStoreError(e) => write!(f, "Persistence (wal store) error: {e}"), + Error::SignerError(e) => write!(f, "Signing issue: {e}"), + Error::HttpsSetup(e) => write!(f, "Cannot set up HTTPS: {e}"), + Error::HttpClientError(e) => write!(f, "HTTP client error: {e}"), + Error::ConfigError(e) => write!(f, "Configuration error: {e}"), + Error::UpgradeError(e) => write!(f, "Could not upgrade Krill: {e}"), Error::NotImplemented => write!(f, "Not yet implemented"), //----------------------------------------------------------------- // General API Client Issues //----------------------------------------------------------------- Error::UnexpectedBody => write!(f, "Unexpected body in request"), - Error::JsonError(e) => write!(f,"Invalid JSON: {}", e), + Error::JsonError(e) => write!(f,"Invalid JSON: {e}"), Error::InvalidUtf8Input => write!(f, "Submitted bytes are invalid UTF8"), Error::ApiUnknownMethod => write!(f,"Unknown API method"), Error::ApiUnknownResource => write!(f, "Unknown resource"), @@ -432,12 +430,12 @@ impl fmt::Display for Error { Error::ApiInvalidSeconds => write!(f, "Invalid path argument for seconds"), Error::PostTooBig => write!(f, "POST body exceeds configured limit"), Error::PostCannotRead => write!(f, "POST body cannot be read"), - Error::ApiInvalidCredentials(e) => write!(f, "Invalid credentials: {}", e), - Error::ApiLoginError(e) => write!(f, "Login error: {}", e), - Error::ApiAuthPermanentError(e) => write!(f, "Authentication error: {}", e), - Error::ApiAuthTransientError(e) => write!(f, "Transient authentication error: {}", e), - Error::ApiAuthSessionExpired(e) => write!(f, "Session expired: {}", e), - Error::ApiInsufficientRights(e) => write!(f, "Insufficient rights: {}", e), + Error::ApiInvalidCredentials(e) => write!(f, "Invalid credentials: {e}"), + Error::ApiLoginError(e) => write!(f, "Login error: {e}"), + Error::ApiAuthPermanentError(e) => write!(f, "Authentication error: {e}"), + Error::ApiAuthTransientError(e) => write!(f, "Transient authentication error: {e}"), + Error::ApiAuthSessionExpired(e) => write!(f, "Session expired: {e}"), + Error::ApiInsufficientRights(e) => write!(f, "Insufficient rights: {e}"), //----------------------------------------------------------------- // Repository Issues @@ -448,10 +446,10 @@ impl fmt::Display for Error { //----------------------------------------------------------------- // Publisher Issues //----------------------------------------------------------------- - Error::PublisherUnknown(pbl) => write!(f, "Unknown publisher '{}'", pbl), - Error::PublisherUriOutsideBase(uri, jail) => write!(f, "Publishing uri '{}' outside repository uri '{}'", uri, jail), - Error::PublisherBaseUriNoSlash(uri) => write!(f, "Publisher uri '{}' must have a trailing slash", uri), - Error::PublisherDuplicate(pbl) => write!(f, "Duplicate publisher '{}'", pbl), + Error::PublisherUnknown(pbl) => write!(f, "Unknown publisher '{pbl}'"), + Error::PublisherUriOutsideBase(uri, jail) => write!(f, "Publishing uri '{uri}' outside repository uri '{jail}'"), + Error::PublisherBaseUriNoSlash(uri) => write!(f, "Publisher uri '{uri}' must have a trailing slash"), + Error::PublisherDuplicate(pbl) => write!(f, "Duplicate publisher '{pbl}'"), //----------------------------------------------------------------- // Repository Server Issues @@ -463,56 +461,52 @@ impl fmt::Display for Error { //----------------------------------------------------------------- // RFC 8181 (publishing) //----------------------------------------------------------------- - Error::Rfc8181Validation(req) => write!(f, "Issue with RFC8181 request: {}", req), - Error::Rfc8181Decode(req) => write!(f, "Issue with decoding RFC8181 request: {}", req), + Error::Rfc8181Validation(req) => write!(f, "Issue with RFC8181 request: {req}"), + Error::Rfc8181Decode(req) => write!(f, "Issue with decoding RFC8181 request: {req}"), Error::Rfc8181(e) => e.fmt(f), Error::Rfc8181Delta(e) => e.fmt(f), - Error::PublishingObjects(msg) => write!(f, "Issue generating repository objects: '{}'", msg), + Error::PublishingObjects(msg) => write!(f, "Issue generating repository objects: '{msg}'"), //----------------------------------------------------------------- // CA Issues //----------------------------------------------------------------- - Error::CaDuplicate(ca) => write!(f, "CA '{}' was already initialized", ca), - Error::CaUnknown(ca) => write!(f, "CA '{}' is unknown", ca), + Error::CaDuplicate(ca) => write!(f, "CA '{ca}' was already initialized"), + Error::CaUnknown(ca) => write!(f, "CA '{ca}' is unknown"), // CA Repo Issues - Error::CaRepoInUse(ca) => write!(f, "CA '{}' already uses this repository", ca), - Error::CaRepoIssue(ca, e) => write!(f, "CA '{}' cannot get response from repository '{}'. Is the 'service_uri' in the XML reachable? Note that when upgrading Krill you should re-use existing configuration and data. For a fresh \ - re-install of Krill you will need to send XML to all other parties again: parent(s), children, and repository", ca, e), - Error::CaRepoResponseInvalid(ca, e) => write!(f, "CA '{}' got invalid repository response: {}", ca, e), - Error::CaRepoResponseWrongXml(ca) => write!(f, "CA '{}' got parent instead of repository response", ca), + Error::CaRepoInUse(ca) => write!(f, "CA '{ca}' already uses this repository"), + Error::CaRepoIssue(ca, e) => write!(f, "CA '{ca}' cannot get response from repository '{e}'. Is the 'service_uri' in the XML reachable? Note that when upgrading Krill you should re-use existing configuration and data. For a fresh \ + re-install of Krill you will need to send XML to all other parties again: parent(s), children, and repository"), + Error::CaRepoResponseInvalid(ca, e) => write!(f, "CA '{ca}' got invalid repository response: {e}"), + Error::CaRepoResponseWrongXml(ca) => write!(f, "CA '{ca}' got parent instead of repository response"), // CA Parent Issues - Error::CaParentDuplicateName(ca, parent) => write!(f, "CA '{}' already has a parent named '{}'", ca, parent), - Error::CaParentDuplicateInfo(ca, parent) => write!(f, "CA '{}' already has a parent named '{}' for this XML", ca, parent), - Error::CaParentUnknown(ca, parent) => write!(f, "CA '{}' does not have a parent named '{}'", ca, parent), - Error::CaParentIssue(ca, parent, e) => write!(f, "CA '{}' got error from parent '{}': {}", ca, parent, e), - Error::CaParentResponseInvalid(ca, e) => write!(f, "CA '{}' got invalid parent response: {}", ca, e), - Error::CaParentResponseWrongXml(ca) => write!(f, "CA '{}' got repository response when adding parent", ca), - Error::CaParentAddNotResponsive(ca, parent) => write!(f, "CA '{}' cannot get response from parent '{}'. Is the 'service_uri' in the XML reachable? Note that when upgrading Krill you should re-use existing configuration and data. For a fresh re-install of Krill you will need to send XML to all other parties again: parent(s), children, and repository", ca, parent), + Error::CaParentDuplicateName(ca, parent) => write!(f, "CA '{ca}' already has a parent named '{parent}'"), + Error::CaParentDuplicateInfo(ca, parent) => write!(f, "CA '{ca}' already has a parent named '{parent}' for this XML"), + Error::CaParentUnknown(ca, parent) => write!(f, "CA '{ca}' does not have a parent named '{parent}'"), + Error::CaParentIssue(ca, parent, e) => write!(f, "CA '{ca}' got error from parent '{parent}': {e}"), + Error::CaParentResponseInvalid(ca, e) => write!(f, "CA '{ca}' got invalid parent response: {e}"), + Error::CaParentResponseWrongXml(ca) => write!(f, "CA '{ca}' got repository response when adding parent"), + Error::CaParentAddNotResponsive(ca, parent) => write!(f, "CA '{ca}' cannot get response from parent '{parent}'. Is the 'service_uri' in the XML reachable? Note that when upgrading Krill you should re-use existing configuration and data. For a fresh re-install of Krill you will need to send XML to all other parties again: parent(s), children, and repository"), Error::CaParentSyncError(ca, parent, rcn, error_msg) => { write!( f, - "CA '{}' could not sync with parent '{}', for resource class '{}', error: {}", - ca, - parent, - rcn, - error_msg + "CA '{ca}' could not sync with parent '{parent}', for resource class '{rcn}', error: {error_msg}" ) } //----------------------------------------------------------------- // RFC8183 (exchanging id XML) //----------------------------------------------------------------- - Error::Rfc8183(e) => write!(f, "RFC 8183 XML issue: {}", e), + Error::Rfc8183(e) => write!(f, "RFC 8183 XML issue: {e}"), //----------------------------------------------------------------- // RFC6492 (requesting resources) //----------------------------------------------------------------- - Error::Rfc6492(e) => write!(f, "RFC 6492 Issue: {}", e), - Error::Rfc6492NotPerformed(not) => write!(f, "RFC 6492 Not Performed: {}", not), - Error::Rfc6492InvalidCsrSent(e) => write!(f, "Invalid CSR received: {}", e), + Error::Rfc6492(e) => write!(f, "RFC 6492 Issue: {e}"), + Error::Rfc6492NotPerformed(not) => write!(f, "RFC 6492 Not Performed: {not}"), + Error::Rfc6492InvalidCsrSent(e) => write!(f, "Invalid CSR received: {e}"), //----------------------------------------------------------------- // CA Child Issues @@ -523,30 +517,30 @@ impl fmt::Display for Error { '{path}' in path, '{body}' in body" ) }, - Error::CaChildDuplicate(ca, child) => write!(f, "CA '{}' already has a child named '{}'", ca, child), - Error::CaChildUnknown(ca, child) => write!(f, "CA '{}' does not have a child named '{}'", ca, child), - Error::CaChildMustHaveResources(ca, child) => write!(f, "Child '{}' for CA '{}' MUST have resources specified", child, ca), - Error::CaChildExtraResources(ca, child) => write!(f, "Child '{}' cannot have resources not held by CA '{}'", child, ca), - Error::CaChildUnauthorized(ca, child) => write!(f, "CA '{}' does not know id certificate for child '{}'", ca, child), + Error::CaChildDuplicate(ca, child) => write!(f, "CA '{ca}' already has a child named '{child}'"), + Error::CaChildUnknown(ca, child) => write!(f, "CA '{ca}' does not have a child named '{child}'"), + Error::CaChildMustHaveResources(ca, child) => write!(f, "Child '{child}' for CA '{ca}' MUST have resources specified"), + Error::CaChildExtraResources(ca, child) => write!(f, "Child '{child}' cannot have resources not held by CA '{ca}'"), + Error::CaChildUnauthorized(ca, child) => write!(f, "CA '{ca}' does not know id certificate for child '{child}'"), //----------------------------------------------------------------- // RouteAuthorizations - ROAs //----------------------------------------------------------------- - Error::CaAuthorizationUnknown(_ca, roa) => write!(f, "Cannot remove unknown ROA '{}'", roa), - Error::CaAuthorizationDuplicate(_ca, roa) => write!(f, "ROA '{}' already present", roa), - Error::CaAuthorizationInvalidMaxLength(_ca, roa) => write!(f, "Invalid max length in ROA: '{}'", roa), - Error::CaAuthorizationNotEntitled(_ca, roa) => write!(f, "Prefix in ROA '{}' not held by you", roa), - Error::RoaDeltaError(_ca, e) => write!(f, "ROA delta rejected:\n\n'{}' ", e), + Error::CaAuthorizationUnknown(_ca, roa) => write!(f, "Cannot remove unknown ROA '{roa}'"), + Error::CaAuthorizationDuplicate(_ca, roa) => write!(f, "ROA '{roa}' already present"), + Error::CaAuthorizationInvalidMaxLength(_ca, roa) => write!(f, "Invalid max length in ROA: '{roa}'"), + Error::CaAuthorizationNotEntitled(_ca, roa) => write!(f, "Prefix in ROA '{roa}' not held by you"), + Error::RoaDeltaError(_ca, e) => write!(f, "ROA delta rejected:\n\n'{e}' "), //----------------------------------------------------------------- // Autonomous System Provider Authorization - ASPAs //----------------------------------------------------------------- - Error::AspaCustomerAsNotEntitled(_ca, asn) => write!(f, "Customer AS '{}' is not held by you", asn), - Error::AspaCustomerAlreadyPresent(_ca, asn) => write!(f, "ASPA already exists for customer AS '{}'", asn), - Error::AspaProvidersEmpty(_ca, asn) => write!(f, "ASPA for customer AS '{}' requires at least one provider", asn), - Error::AspaCustomerAsProvider(_ca, asn) => write!(f, "ASPA for customer AS '{}' cannot have that AS as provider", asn), - Error::AspaProvidersDuplicates(_ca, asn) => write!(f, "ASPA for customer AS '{}' cannot have duplicate providers", asn), - Error::AspaCustomerUnknown(_ca, asn) => write!(f, "No current ASPA exists for customer AS '{}'", asn), + Error::AspaCustomerAsNotEntitled(_ca, asn) => write!(f, "Customer AS '{asn}' is not held by you"), + Error::AspaCustomerAlreadyPresent(_ca, asn) => write!(f, "ASPA already exists for customer AS '{asn}'"), + Error::AspaProvidersEmpty(_ca, asn) => write!(f, "ASPA for customer AS '{asn}' requires at least one provider"), + Error::AspaCustomerAsProvider(_ca, asn) => write!(f, "ASPA for customer AS '{asn}' cannot have that AS as provider"), + Error::AspaProvidersDuplicates(_ca, asn) => write!(f, "ASPA for customer AS '{asn}' cannot have duplicate providers"), + Error::AspaCustomerUnknown(_ca, asn) => write!(f, "No current ASPA exists for customer AS '{asn}'"), //----------------------------------------------------------------- // BGPSec @@ -578,14 +572,14 @@ impl fmt::Display for Error { Error::KeyUseNoCurrentKey => write!(f, "No current key in resource class"), Error::KeyUseNoOldKey => write!(f, "No old key in resource class"), Error::KeyUseNoIssuedCert => write!(f, "No issued cert matching pub key"), - Error::KeyUseNoMatch(ki) => write!(f, "No key found matching key identifier: '{}'", ki), + Error::KeyUseNoMatch(ki) => write!(f, "No key found matching key identifier: '{ki}'"), Error::KeyRollInProgress => write!(f, "Key roll in progress"), Error::KeyRollActivatePendingRequests => write!(f, "Cannot activate key while there are still pending requests."), //----------------------------------------------------------------- // Resource Issues //----------------------------------------------------------------- - Error::ResourceClassUnknown(rcn) => write!(f, "Unknown resource class: '{}'", rcn), + Error::ResourceClassUnknown(rcn) => write!(f, "Unknown resource class: '{rcn}'"), Error::ResourceSetError(e) => e.fmt(f), Error::MissingResources => write!(f, "Requester is not entitled to all requested resources"), @@ -604,7 +598,7 @@ impl fmt::Display for Error { Error::TaProxyHasDifferentSigner => write!(f, "Trust Anchor Proxy already has a different associated signer"), Error::TaProxyHasNoRequest => write!(f, "Trust Anchor Proxy has no signer request"), Error::TaProxyHasRequest => write!(f, "Trust Anchor Proxy already has signer request"), - Error::TaProxyRequestNonceMismatch(rcvd, expected) => write!(f, "Trust Anchor Response nonce '{}' does not match open Request nonce '{}'", rcvd, expected), + Error::TaProxyRequestNonceMismatch(rcvd, expected) => write!(f, "Trust Anchor Response nonce '{rcvd}' does not match open Request nonce '{expected}'"), //----------------------------------------------------------------- // Resource Tagged Attestation issues diff --git a/src/commons/eventsourcing/store.rs b/src/commons/eventsourcing/store.rs index 333651cb..22676158 100644 --- a/src/commons/eventsourcing/store.rs +++ b/src/commons/eventsourcing/store.rs @@ -663,7 +663,7 @@ impl AggregateStore { Self::scope_for_agg(agg), // Cannot panic as a u64 cannot contain a Scope::SEPARATOR. Segment::parse( - &format!("command-{}.json", version) + &format!("command-{version}.json") ).unwrap(), ) } @@ -701,19 +701,19 @@ impl fmt::Display for AggregateStoreError { match self { AggregateStoreError::IoError(e) => e.fmt(f), AggregateStoreError::KeyStoreError(e) => { - write!(f, "KeyStore Error: {}", e) + write!(f, "KeyStore Error: {e}") } AggregateStoreError::NotInitialized => { write!(f, "This aggregate store is not initialized") } AggregateStoreError::UnknownAggregate(handle) => { - write!(f, "unknown entity: {}", handle) + write!(f, "unknown entity: {handle}") } AggregateStoreError::DuplicateAggregate(handle) => { - write!(f, "duplicate entity: {}", handle) + write!(f, "duplicate entity: {handle}") } AggregateStoreError::InitError(handle) => { - write!(f, "Command 0 for '{}' has no init", handle) + write!(f, "Command 0 for '{handle}' has no init") } AggregateStoreError::ReplayError( handle, @@ -721,41 +721,35 @@ impl fmt::Display for AggregateStoreError { fail_version, ) => write!( f, - "Event for '{}' version '{}' had version '{}'", - handle, version, fail_version + "Event for '{handle}' version '{version}' had version '{fail_version}'" ), AggregateStoreError::ConcurrentModification(handle) => { write!( f, - "concurrent modification attempt for entity: '{}'", - handle + "concurrent modification attempt for entity: '{handle}'" ) } AggregateStoreError::UnknownCommand(handle, version) => write!( f, - "Aggregate '{}' does not have command with version '{}'", - handle, version + "Aggregate '{handle}' does not have command with version '{version}'" ), AggregateStoreError::WarmupFailed(handle, e) => { - write!(f, "Could not rebuild state for '{}': {}", handle, e) + write!(f, "Could not rebuild state for '{handle}': {e}") } AggregateStoreError::CouldNotArchive(handle, e) => write!( f, - "Could not archive commands and events for '{}'. Error: {}", - handle, e + "Could not archive commands and events for '{handle}'. Error: {e}" ), AggregateStoreError::CommandCorrupt(handle, key) => { write!( f, - "StoredCommand '{}' for '{}' was corrupt", - handle, key + "StoredCommand '{handle}' for '{key}' was corrupt" ) } AggregateStoreError::CommandNotFound(handle, key) => { write!( f, - "StoredCommand '{}' for '{}' cannot be found", - handle, key + "StoredCommand '{handle}' for '{key}' cannot be found" ) } } diff --git a/src/commons/eventsourcing/test.rs b/src/commons/eventsourcing/test.rs index d7156fee..bac7c24d 100644 --- a/src/commons/eventsourcing/test.rs +++ b/src/commons/eventsourcing/test.rs @@ -99,7 +99,7 @@ impl fmt::Display for PersonEvent { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { PersonEvent::NameChanged(new_name) => { - write!(f, "changed name to '{}'", new_name) + write!(f, "changed name to '{new_name}'") } PersonEvent::HadBirthday => write!(f, "went around the sun."), } @@ -137,7 +137,7 @@ impl fmt::Display for PersonCommandDetails { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { PersonCommandDetails::ChangeName(name) => { - write!(f, "Change name to {}", name) + write!(f, "Change name to {name}") } PersonCommandDetails::GoAroundTheSun => { write!(f, "Go around the sun") @@ -198,7 +198,7 @@ impl fmt::Display for PersonStorableCommand { match self { PersonStorableCommand::Init => write!(f, "Initialise person"), PersonStorableCommand::ChangeName(name) => { - write!(f, "Change name to {}", name) + write!(f, "Change name to {name}") } PersonStorableCommand::GoAroundTheSun => { write!(f, "Go around the sun") diff --git a/src/commons/eventsourcing/wal.rs b/src/commons/eventsourcing/wal.rs index a1c1890f..cac711ab 100644 --- a/src/commons/eventsourcing/wal.rs +++ b/src/commons/eventsourcing/wal.rs @@ -344,9 +344,8 @@ impl WalStore { Ok(changes) => { if changes.is_empty() { trace!( - "No changes needed for '{}' when \ - processing command: {}", - handle, summary, + "No changes needed for '{handle}' when \ + processing command: {summary}", ); } else { @@ -463,7 +462,7 @@ impl WalStore { Self::scope_for_handle(handle), // Cannot panic as a u64 cannot contain a Scope::SEPARATOR. Segment::parse( - &format!("wal-{}.json", revision) + &format!("wal-{revision}.json") ).unwrap(), ) } @@ -490,15 +489,14 @@ impl fmt::Display for WalStoreError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { WalStoreError::KeyStoreError(e) => { - write!(f, "KeyStore Error: {}", e) + write!(f, "KeyStore Error: {e}") } WalStoreError::Unknown(handle) => { - write!(f, "Unknown entity: {}", handle) + write!(f, "Unknown entity: {handle}") } WalStoreError::WarmupFailed(handle, e) => write!( f, - "Warmup failed with entity '{}' error: {}", - handle, e + "Warmup failed with entity '{handle}' error: {e}" ), } } diff --git a/src/commons/ext_serde.rs b/src/commons/ext_serde.rs index 1cf7f639..fafa4cc9 100644 --- a/src/commons/ext_serde.rs +++ b/src/commons/ext_serde.rs @@ -189,8 +189,7 @@ where let string = String::deserialize(d)?; Facility::from_str(&string).map_err(|_| { de::Error::custom(format!( - "Unsupported syslog_facility: \"{}\"", - string + "Unsupported syslog_facility: \"{string}\"" )) }) } diff --git a/src/commons/file.rs b/src/commons/file.rs index f399115c..3181257c 100644 --- a/src/commons/file.rs +++ b/src/commons/file.rs @@ -120,7 +120,7 @@ pub fn load_json( full_path.to_string_lossy() ), io::Error::other( - format!("could not deserialize json: {}", e), + format!("could not deserialize json: {e}"), ), ) }) @@ -313,8 +313,8 @@ fn derive_uri( let rel_string = rel.to_string_lossy().to_string(); let uri_string = match rsync_base { - Some(rsync_base) => format!("{}{}", rsync_base, rel_string), - None => format!("rsync://{}", rel_string), + Some(rsync_base) => format!("{rsync_base}{rel_string}"), + None => format!("rsync://{rel_string}"), }; let uri = uri::Rsync::from_str(&uri_string) @@ -509,9 +509,9 @@ pub enum Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - Error::CannotRead(s) => write!(f, "Cannot read: {}", s), + Error::CannotRead(s) => write!(f, "Cannot read: {s}"), Error::UnsupportedFileName(name) => { - write!(f, "Unsupported characters: {}", name) + write!(f, "Unsupported characters: {name}") } Error::PathOutsideBasePath => { write!(f, "Cannot use path outside of rsync jail") @@ -521,10 +521,10 @@ impl fmt::Display for Error { "Do not ever use '/' as the source or target for backups" ), Error::BackupCannotReadSource(e) => { - write!(f, "Source for backup cannot be read: {}", e) + write!(f, "Source for backup cannot be read: {e}") } Error::BackupTargetExists(e) => { - write!(f, "Target for backup already exists: {}", e) + write!(f, "Target for backup already exists: {e}") } Error::Io(e) => e.fmt(f), } diff --git a/src/commons/httpclient.rs b/src/commons/httpclient.rs index 48c4dd01..6073d080 100644 --- a/src/commons/httpclient.rs +++ b/src/commons/httpclient.rs @@ -23,9 +23,9 @@ use crate::api::status::ErrorResponse; const JSON_CONTENT: &str = "application/json"; fn report_get_and_exit(uri: &str, token: Option<&Token>) { - println!("GET:\n {}", uri); + println!("GET:\n {uri}"); if let Some(token) = token { - println!("Headers:\n Authorization: Bearer {}", token); + println!("Headers:\n Authorization: Bearer {token}"); } std::process::exit(0); } @@ -36,19 +36,19 @@ fn report_post_and_exit( token: Option<&Token>, body: &str, ) { - println!("POST:\n {}", uri); + println!("POST:\n {uri}"); if content_type.is_some() || token.is_some() { println!("Headers:"); } if let Some(content_type) = content_type { - println!(" content-type: {}", content_type); + println!(" content-type: {content_type}"); } if let Some(token) = token { - println!(" Authorization: Bearer {}", token); + println!(" Authorization: Bearer {token}"); } - println!("Body:\n{}", body); + println!("Body:\n{body}"); std::process::exit(0); } @@ -58,16 +58,16 @@ fn report_delete( token: Option<&Token>, ) { if env::var(KRILL_CLI_API_ENV).is_ok() { - println!("DELETE:\n {}", uri); + println!("DELETE:\n {uri}"); if content_type.is_some() || token.is_some() { println!("Headers:"); } if let Some(content_type) = content_type { - println!(" content-type: {}", content_type); + println!(" content-type: {content_type}"); } if let Some(token) = token { - println!(" Authorization: Bearer {}", token); + println!(" Authorization: Bearer {token}"); } std::process::exit(0); } @@ -296,7 +296,7 @@ pub async fn post_binary_with_full_ua( match res.status() { StatusCode::OK => { let bytes = res.bytes().await.map_err(|e| { - Error::response(uri, format!("cannot get body: {}", e)) + Error::response(uri, format!("cannot get body: {e}")) })?; Ok(bytes) } @@ -391,7 +391,7 @@ fn headers( if let Some(token) = token { headers.insert( hyper::header::AUTHORIZATION, - HeaderValue::from_str(&format!("Bearer {}", token)) + HeaderValue::from_str(&format!("Bearer {token}")) .map_err(|e| Error::request_build(uri, e))?, ); } @@ -418,7 +418,7 @@ async fn process_opt_json_response( let res: T = serde_json::from_str(&s).map_err(|e| { Error::response( uri, - format!("could not parse JSON response: {}", e), + format!("could not parse JSON response: {e}"), ) })?; Ok(Some(res)) @@ -486,48 +486,42 @@ impl fmt::Display for Error { match self { Error::RequestBuild(uri, msg) => write!( f, - "Issue creating request for URI: {}, error: {}", - uri, msg + "Issue creating request for URI: {uri}, error: {msg}" ), Error::RequestBuildHttpsCert(path, msg) => { write!( f, - "Cannot use configured HTTPS root cert '{}'. Error: {}", - path, msg + "Cannot use configured HTTPS root cert '{path}'. Error: {msg}" ) } Error::RequestExecute(uri, msg) => { - write!(f, "Issue accessing URI: {}, error: {}", uri, msg) + write!(f, "Issue accessing URI: {uri}, error: {msg}") } Error::Response(uri, msg) => write!( f, - "Issue processing response from URI: {}, error: {}", - uri, msg + "Issue processing response from URI: {uri}, error: {msg}" ), Error::Forbidden(uri) => { - write!(f, "Got 'Forbidden' response for URI: {}", uri) + write!(f, "Got 'Forbidden' response for URI: {uri}") } Error::ErrorResponse(uri, code) => { write!( f, - "Issue processing response from URI: {}, \ - error: unexpected status code {}", - uri, code + "Issue processing response from URI: {uri}, \ + error: unexpected status code {code}" ) } Error::ErrorResponseWithBody(uri, code, e) => { write!( f, - "Error response from URI: {}, Status: {}, Error: {}", - uri, code, e + "Error response from URI: {uri}, Status: {code}, Error: {e}" ) } Error::ErrorResponseWithJson(uri, code, res) => write!( f, - "Error response from URI: {}, Status: {}, ErrorResponse: {}", - uri, code, res + "Error response from URI: {uri}, Status: {code}, ErrorResponse: {res}" ), } } @@ -541,7 +535,7 @@ impl Error { pub fn request_build_json(uri: &str, e: impl fmt::Display) -> Self { Error::RequestBuild( uri.to_string(), - format!("could not serialize type to JSON: {}", e), + format!("could not serialize type to JSON: {e}"), ) } diff --git a/src/commons/queue.rs b/src/commons/queue.rs index cd5a99c3..f57f0516 100644 --- a/src/commons/queue.rs +++ b/src/commons/queue.rs @@ -210,8 +210,7 @@ impl Queue { Ok(Ok(())) } else { Ok(Err(Error::other(format!( - "Cannot finish task {}. It is not running.", - running_key + "Cannot finish task {running_key}. It is not running." )))) } })? diff --git a/src/commons/storage/backends/disk.rs b/src/commons/storage/backends/disk.rs index 2006e286..44f3476b 100644 --- a/src/commons/storage/backends/disk.rs +++ b/src/commons/storage/backends/disk.rs @@ -179,7 +179,7 @@ impl Store { pub fn has(&self, key: &Key) -> Result { self.key_path(key).try_exists().map_err(|err| { Error::io( - format!("failed to check existance of key '{}'", key), + format!("failed to check existance of key '{key}'"), err ) }) @@ -189,7 +189,7 @@ impl Store { pub fn has_scope(&self, scope: &Scope) -> Result { self.scope_path(scope).try_exists().map_err(|err| { Error::io( - format!("failed to check existance of scope '{}'", scope), + format!("failed to check existance of scope '{scope}'"), err ) }) @@ -400,8 +400,7 @@ impl Store { let mut tmp_file = NamedTempFile::new_in(&self.tmp).map_err(|err| { Error::io( format!( - "writing temp file failed for key: '{}'", - key + "writing temp file failed for key: '{key}'" ), err, ) @@ -649,7 +648,7 @@ impl FileLock { fn write(&mut self) -> Result, Error> { self.lock .write() - .map_err(|e| Error::other(format!("Cannot get file lock: {}", e))) + .map_err(|e| Error::other(format!("Cannot get file lock: {e}"))) } } @@ -695,18 +694,16 @@ impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::Io { context, err } => { - write!(f, "{}: {}", context, err) + write!(f, "{context}: {err}") } Error::Deserialize { key, err } => { write!(f, - "failed to deserialize value for key '{}': {}", - key, err + "failed to deserialize value for key '{key}': {err}" ) } Error::Serialize { key, err } => { write!(f, - "failed to serialize value for key '{}': {}", - key, err + "failed to serialize value for key '{key}': {err}" ) } Error::Other(s) => f.write_str(s) diff --git a/src/commons/storage/backends/memory.rs b/src/commons/storage/backends/memory.rs index 571227b9..aca23b96 100644 --- a/src/commons/storage/backends/memory.rs +++ b/src/commons/storage/backends/memory.rs @@ -359,14 +359,12 @@ impl fmt::Display for Error { } Error::Deserialize { key, err } => { write!(f, - "failed to deserialize value for key '{}': {}", - key, err + "failed to deserialize value for key '{key}': {err}" ) } Error::Serialize { key, err } => { write!(f, - "failed to serialize value for key '{}': {}", - key, err + "failed to serialize value for key '{key}': {err}" ) } Error::NotFound(key) => write!(f, "no such key '{key}'"), diff --git a/src/commons/storage/store.rs b/src/commons/storage/store.rs index 88c51859..3389a8b5 100644 --- a/src/commons/storage/store.rs +++ b/src/commons/storage/store.rs @@ -184,11 +184,10 @@ impl KeyValueStore { namespace: &Namespace, prefix: &str, ) -> Result { - let namespace_string = format!("{}_{}", prefix, namespace); + let namespace_string = format!("{prefix}_{namespace}"); NamespaceBuf::from_str(&namespace_string).map_err(|e| { KeyValueError::Other(format!( - "Cannot parse namespace: {}. Error: {}", - namespace_string, e + "Cannot parse namespace: {namespace_string}. Error: {e}" )) }) } @@ -219,8 +218,7 @@ impl KeyValueStore { let current_store = KeyValueStore::create(storage_uri, namespace)?; if !current_store.is_empty()? { Err(KeyValueError::Other(format!( - "Abort migrate upgraded store for {} to current. The current store was not archived.", - namespace + "Abort migrate upgraded store for {namespace} to current. The current store was not archived." ))) } else { self.inner @@ -275,13 +273,13 @@ impl fmt::Display for KeyValueError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { KeyValueError::UnknownScheme(e) => { - write!(f, "Unknown Scheme: {}", e) + write!(f, "Unknown Scheme: {e}") } KeyValueError::DuplicateKey(key) => { - write!(f, "Duplicate key: {}", key) + write!(f, "Duplicate key: {key}") } - KeyValueError::Inner(e) => write!(f, "Store error: {}", e), - KeyValueError::Other(msg) => write!(f, "{}", msg), + KeyValueError::Inner(e) => write!(f, "Store error: {e}"), + KeyValueError::Other(msg) => write!(f, "{msg}"), } } } diff --git a/src/commons/version.rs b/src/commons/version.rs index 4a133f3a..9b76d2be 100644 --- a/src/commons/version.rs +++ b/src/commons/version.rs @@ -248,8 +248,8 @@ impl fmt::Display for KrillVersionReleaseType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { KrillVersionReleaseType::Release => write!(f, ""), - KrillVersionReleaseType::Candidate(nr) => write!(f, "-rc{}", nr), - KrillVersionReleaseType::Dev(text) => write!(f, "-{}", text), + KrillVersionReleaseType::Candidate(nr) => write!(f, "-rc{nr}"), + KrillVersionReleaseType::Dev(text) => write!(f, "-{text}"), } } } diff --git a/src/config.rs b/src/config.rs index b2c31073..cdfbd71b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -83,8 +83,7 @@ impl ConfigDefaults { Ok(level) => level, Err(_) => { eprintln!( - "Unrecognized value for log level in env var {}", - KRILL_ENV_LOG_LEVEL + "Unrecognized value for log level in env var {KRILL_ENV_LOG_LEVEL}" ); ::std::process::exit(1); } @@ -99,8 +98,7 @@ impl ConfigDefaults { Ok(log_type) => log_type, Err(e) => { eprintln!( - "Unrecognized value for log type in env var {}, {}", - KRILL_ENV_LOG_TYPE, e + "Unrecognized value for log type in env var {KRILL_ENV_LOG_TYPE}, {e}" ); ::std::process::exit(1); } @@ -1204,8 +1202,8 @@ impl Config { let testbed = if enable_testbed { Some(TestBed::new( test::rsync("rsync://localhost/ta/ta.cer"), - test::https(&format!("https://localhost:{}/ta/ta.cer", port)), - test::https(&format!("https://localhost:{}/rrdp/", port)), + test::https(&format!("https://localhost:{port}/ta/ta.cer")), + test::https(&format!("https://localhost:{port}/rrdp/")), test::rsync("rsync://localhost/repo/"), )) } else { @@ -1349,16 +1347,14 @@ impl Config { fn fix(&mut self) -> Result<(), ConfigError> { if self.ca_refresh_seconds < CA_REFRESH_SECONDS_MIN { warn!( - "The value for 'ca_refresh_seconds' was below the minimum value, changing it to {} seconds", - CA_REFRESH_SECONDS_MIN + "The value for 'ca_refresh_seconds' was below the minimum value, changing it to {CA_REFRESH_SECONDS_MIN} seconds" ); self.ca_refresh_seconds = CA_REFRESH_SECONDS_MIN; } if self.ca_refresh_seconds > CA_REFRESH_SECONDS_MAX { warn!( - "The value for 'ca_refresh_seconds' was above the maximum value, changing it to {} seconds", - CA_REFRESH_SECONDS_MAX + "The value for 'ca_refresh_seconds' was above the maximum value, changing it to {CA_REFRESH_SECONDS_MAX} seconds" ); self.ca_refresh_seconds = CA_REFRESH_SECONDS_MAX; } @@ -1393,7 +1389,7 @@ impl Config { let half_refresh = self.ca_refresh_seconds / 2; if self.ca_refresh_jitter_seconds > half_refresh { - warn!("The value for 'ca_refresh_jitter_seconds' exceeded 50% of 'ca_refresh_seconds'. Changing it to {} seconds", half_refresh); + warn!("The value for 'ca_refresh_jitter_seconds' exceeded 50% of 'ca_refresh_seconds'. Changing it to {half_refresh} seconds"); self.ca_refresh_jitter_seconds = half_refresh; } @@ -1458,7 +1454,7 @@ impl Config { fn verify(&self) -> Result<(), ConfigError> { if env::var(KRILL_ENV_ADMIN_TOKEN_DEPRECATED).is_ok() { - warn!("The environment variable for setting the admin token has been updated from '{}' to '{}', please update as the old value may not be supported in future releases", KRILL_ENV_ADMIN_TOKEN_DEPRECATED, KRILL_ENV_ADMIN_TOKEN) + warn!("The environment variable for setting the admin token has been updated from '{KRILL_ENV_ADMIN_TOKEN_DEPRECATED}' to '{KRILL_ENV_ADMIN_TOKEN}', please update as the old value may not be supported in future releases") } if self.port < 1024 { @@ -1552,8 +1548,7 @@ impl Config { if let Some(threshold) = self.suspend_child_after_inactive_hours { if threshold < CA_SUSPEND_MIN_HOURS { return Err(ConfigError::Other(format!( - "suspend_child_after_inactive_hours must be {} or higher (or not set at all)", - CA_SUSPEND_MIN_HOURS + "suspend_child_after_inactive_hours must be {CA_SUSPEND_MIN_HOURS} or higher (or not set at all)" ))); } } @@ -1688,8 +1683,7 @@ impl Config { fn stderr_logger(&self) -> Result<(), ConfigError> { self.fern_logger().chain(io::stderr()).apply().map_err(|e| { ConfigError::Other(format!( - "Failed to init stderr logging: {}", - e + "Failed to init stderr logging: {e}" )) }) } @@ -1713,7 +1707,7 @@ impl Config { } }; self.fern_logger().chain(file).apply().map_err(|e| { - ConfigError::Other(format!("Failed to init file logging: {}", e)) + ConfigError::Other(format!("Failed to init file logging: {e}")) }) } @@ -1746,13 +1740,12 @@ impl Config { Ok(logger) => { self.fern_logger().chain(logger).apply().map_err(|e| { ConfigError::Other(format!( - "Failed to init syslog: {}", - e + "Failed to init syslog: {e}" )) }) } Err(err) => { - let msg = format!("Cannot connect to syslog: {}", err); + let msg = format!("Cannot connect to syslog: {err}"); Err(ConfigError::Other(msg)) } } @@ -1871,8 +1864,7 @@ impl FromStr for LogType { "file" => Ok(LogType::File), "syslog" => Ok(LogType::Syslog), _ => Err(format!( - "expected \"stderr\", \"file\" or \"syslog\", found : \"{}\"", - log_type + "expected \"stderr\", \"file\" or \"syslog\", found : \"{log_type}\"" )), } } @@ -1918,8 +1910,7 @@ impl<'de> Deserialize<'de> for HttpsMode { "generate" => Ok(HttpsMode::Generate), "disable" => Ok(HttpsMode::Disable), _ => Err(de::Error::custom(format!( - "expected \"existing\", \"generate\", or \"disable\" found: \"{}\"", - string + "expected \"existing\", \"generate\", or \"disable\" found: \"{string}\"" ))), } } @@ -1957,8 +1948,7 @@ impl<'de> Deserialize<'de> for AuthType { ); #[cfg(feature = "multi-user")] let msg = format!( - "expected \"config-file\", \"admin-token\", or \"openid-connect\", found: \"{}\"", - string + "expected \"config-file\", \"admin-token\", or \"openid-connect\", found: \"{string}\"" ); Err(de::Error::custom(msg)) } @@ -2058,8 +2048,7 @@ mod tests { assert_eq!(msg, expected_err_msg); } else { panic!( - "Expected error '{}' but got: {:?}", - expected_err_msg, res + "Expected error '{expected_err_msg}' but got: {res:?}" ); } } diff --git a/src/daemon/http/auth/authorizer.rs b/src/daemon/http/auth/authorizer.rs index 710218e6..c86ad139 100644 --- a/src/daemon/http/auth/authorizer.rs +++ b/src/daemon/http/auth/authorizer.rs @@ -268,7 +268,7 @@ impl Authorizer { Err(err) => (AuthInfo::error(err), None), }; - trace!("AuthInfo determination result: {:?}", res); + trace!("AuthInfo determination result: {res:?}"); res } diff --git a/src/daemon/http/auth/crypt.rs b/src/daemon/http/auth/crypt.rs index b31cd41a..645fc73e 100644 --- a/src/daemon/http/auth/crypt.rs +++ b/src/daemon/http/auth/crypt.rs @@ -174,8 +174,7 @@ pub(crate) fn crypt_init(config: &Config) -> KrillResult { let mut key_bytes = [0; CHACHA20_KEY_BYTE_LEN]; openssl::rand::rand_bytes(&mut key_bytes).map_err(|err| { Error::Custom(format!( - "Unable to generate symmetric key: {}", - err + "Unable to generate symmetric key: {err}" )) })?; diff --git a/src/daemon/http/auth/providers/admin_token.rs b/src/daemon/http/auth/providers/admin_token.rs index 1ffe2512..54632355 100644 --- a/src/daemon/http/auth/providers/admin_token.rs +++ b/src/daemon/http/auth/providers/admin_token.rs @@ -75,7 +75,7 @@ impl AuthProvider { }; if log_enabled!(log::Level::Trace) { - trace!("Authentication result: {:?}", res); + trace!("Authentication result: {res:?}"); } res diff --git a/src/daemon/http/auth/providers/config_file.rs b/src/daemon/http/auth/providers/config_file.rs index 8a04b44e..371c320c 100644 --- a/src/daemon/http/auth/providers/config_file.rs +++ b/src/daemon/http/auth/providers/config_file.rs @@ -142,7 +142,7 @@ impl AuthProvider { }; if log_enabled!(log::Level::Trace) { - trace!("Authentication result: {:?}", res); + trace!("Authentication result: {res:?}"); } res @@ -222,7 +222,7 @@ impl AuthProvider { // the two scenarios which could potentially // be used to discover user names. if encoded_hash != user_password_hash { - trace!("Unknown user {}", username); + trace!("Unknown user {username}"); return Err(Error::ApiInvalidCredentials( "Incorrect credentials".to_string(), )) @@ -231,7 +231,7 @@ impl AuthProvider { let user = match self.users.get(username.as_str()) { Some(user) => user, None => { - trace!("Incorrect password for user {}", username); + trace!("Incorrect password for user {username}"); return Err(Error::ApiInvalidCredentials( "Incorrect credentials".to_string(), )); @@ -251,11 +251,10 @@ impl AuthProvider { if !role.is_allowed(Permission::Login, None) { let reason = format!( - "Login denied for user '{}': \ + "Login denied for user '{username}': \ User is not permitted to 'login'", - username, ); - warn!("{}", reason); + warn!("{reason}"); return Err(Error::ApiInsufficientRights(reason)); } diff --git a/src/daemon/http/auth/providers/openid_connect/claims.rs b/src/daemon/http/auth/providers/openid_connect/claims.rs index 9d54d45d..3736c56a 100644 --- a/src/daemon/http/auth/providers/openid_connect/claims.rs +++ b/src/daemon/http/auth/providers/openid_connect/claims.rs @@ -289,7 +289,7 @@ impl<'a> Claims<'a> { Some(additional_info) => { warn!("{} [additional info: {}]", msg, additional_info.into()) } - None => warn!("{}", msg), + None => warn!("{msg}"), }; Error::ApiLoginError(msg) } @@ -455,8 +455,7 @@ impl<'de> Deserialize<'de> for ClaimSource { "expected \"id-token-additional-claim\", \ \"id-token-standard-claim\", \ \"user-info-standard-claim\", or \ - \"user-info-additional-claim\", found : \"{}\"", - s + \"user-info-additional-claim\", found : \"{s}\"" ))) } } diff --git a/src/daemon/http/auth/providers/openid_connect/httpclient.rs b/src/daemon/http/auth/providers/openid_connect/httpclient.rs index 5793a893..11c3bc5f 100644 --- a/src/daemon/http/auth/providers/openid_connect/httpclient.rs +++ b/src/daemon/http/auth/providers/openid_connect/httpclient.rs @@ -47,7 +47,7 @@ pub async fn logging_http_client( ); } Err(err) => { - debug!("OpenID Connect response: {:?}", err) + debug!("OpenID Connect response: {err:?}") } } } @@ -119,7 +119,7 @@ async fn convert_to_openid_response( .map_err(|_| { httpclient::Error::response( uri, - format!("invalid status code: {}", response_code), + format!("invalid status code: {response_code}"), ) })?; @@ -155,7 +155,7 @@ async fn convert_to_openid_response( let response_body = response.bytes().await.map_err(|e| { httpclient::Error::response( uri, - format!("could not get response body: {}", e), + format!("could not get response body: {e}"), ) })?; diff --git a/src/daemon/http/auth/providers/openid_connect/provider.rs b/src/daemon/http/auth/providers/openid_connect/provider.rs index b13db1a8..05656443 100644 --- a/src/daemon/http/auth/providers/openid_connect/provider.rs +++ b/src/daemon/http/auth/providers/openid_connect/provider.rs @@ -405,7 +405,7 @@ impl AuthProvider { // to the rules given in [RFC6749], Section 3.1. Clients // MUST verify that the URL is an HTTPS URL. if urlparse(rev_url).scheme != "https" { - warn!("OpenID Connect: Ignoring insecure revocation_endpoint '{}'", rev_url); + warn!("OpenID Connect: Ignoring insecure revocation_endpoint '{rev_url}'"); revocation_url = None; } } @@ -422,8 +422,7 @@ impl AuthProvider { // components. if urlparse(rpinit_url).scheme != "https" { warn!( - "OpenID Connect: Ignoring insecure end_session_endpoint '{}'", - rpinit_url + "OpenID Connect: Ignoring insecure end_session_endpoint '{rpinit_url}'" ); rp_initiated_logout_url = None; } @@ -593,8 +592,7 @@ impl AuthProvider { .revoke_token(token_to_revoke) .map_err(|err| { RevocationErrorResponseType::Basic(CoreErrorResponseType::Extension(format!( - "Unexpected error while preparing to revoke token: {}", - err + "Unexpected error while preparing to revoke token: {err}" ))) })? .request_async(logging_http_client) @@ -615,11 +613,11 @@ impl AuthProvider { openidconnect::RequestTokenError::Request(r) => { self.on_connection_issue(lock_guard); Err(RevocationErrorResponseType::Basic(CoreErrorResponseType::Extension( - format!("Network failure while revoking token: {}", r), + format!("Network failure while revoking token: {r}"), ))) } openidconnect::RequestTokenError::Parse(r, _) => Err(RevocationErrorResponseType::Basic( - CoreErrorResponseType::Extension(format!("Error while parsing token revocation response: {}", r)), + CoreErrorResponseType::Extension(format!("Error while parsing token revocation response: {r}")), )), openidconnect::RequestTokenError::Other(err_string) => match err_string.as_str() { "temporarily_unavailable" | "server_error" => { @@ -629,7 +627,7 @@ impl AuthProvider { ))) } _ => Err(RevocationErrorResponseType::Basic(CoreErrorResponseType::Extension( - format!("Unknown error while revoking token: {}", err_string), + format!("Unknown error while revoking token: {err_string}"), ))), }, }, @@ -691,8 +689,7 @@ impl AuthProvider { Ok(new_token) } Err(err) => Err(CoreErrorResponseType::Extension(format!( - "Internal error: Error while encoding the refreshed token {}", - err + "Internal error: Error while encoding the refreshed token {err}" ))), } } @@ -716,14 +713,12 @@ impl AuthProvider { openidconnect::RequestTokenError::Request(r) => { self.on_connection_issue(lock_guard); Err(CoreErrorResponseType::Extension(format!( - "Network failure while refreshing token: {}", - r + "Network failure while refreshing token: {r}" ))) } openidconnect::RequestTokenError::Parse(r, _) => { Err(CoreErrorResponseType::Extension(format!( - "Error while parsing refreshed token: {}", - r + "Error while parsing refreshed token: {r}" ))) } openidconnect::RequestTokenError::Other(err_string) => { @@ -736,8 +731,7 @@ impl AuthProvider { } _ => Err(CoreErrorResponseType::Extension( format!( - "Unknown error while refreshing token: {}", - err_string + "Unknown error while refreshing token: {err_string}" ), )), } @@ -803,8 +797,7 @@ impl AuthProvider { } Err(err) => { error!( - "Unable to parse HTTP cookie header value '{}': {}", - cookie_hdr_val_str, err + "Unable to parse HTTP cookie header value '{cookie_hdr_val_str}': {err}" ); } } @@ -825,7 +818,7 @@ impl AuthProvider { Some(additional_info) => { warn!("{} [additional info: {}]", msg, additional_info.into()) } - None => warn!("{}", msg), + None => warn!("{msg}"), }; Error::ApiLoginError(msg) } @@ -950,19 +943,18 @@ impl AuthProvider { let (msg, additional_info) = match e { RequestTokenError::ServerResponse(ref provider_err) => ( format!( - "Server returned error response: {:?}", - provider_err + "Server returned error response: {provider_err:?}" ), None, ), RequestTokenError::Request(ref req) => { self.on_connection_issue(lock_guard); - (format!("Request failed: {:?}", req), None) + (format!("Request failed: {req:?}"), None) } RequestTokenError::Parse(_, ref res) => { let body = match std::str::from_utf8(res) { Ok(text) => text.to_string(), - Err(_) => format!("{:?}", res), + Err(_) => format!("{res:?}"), }; ( "Failed to parse server response".to_string(), @@ -983,13 +975,13 @@ impl AuthProvider { let cause_chain_str = stringify_cause_chain(e); let additional_info = match additional_info { Some(ai_str) => { - format!("{}, {}", ai_str, cause_chain_str) + format!("{ai_str}, {cause_chain_str}") } None => cause_chain_str, }; Self::internal_error( - format!("OpenID Connect: Code exchange failed: {}", msg), + format!("OpenID Connect: Code exchange failed: {msg}"), Some(additional_info), ) })?; @@ -1030,14 +1022,13 @@ impl AuthProvider { .claims(&id_token_verifier, &nonce_hash) .map_err(|e| { Self::internal_error( - format!("OpenID Connect: ID token verification failed: {}", e), + format!("OpenID Connect: ID token verification failed: {e}"), Some(stringify_cause_chain(e)), ) })?; trace!( - "OpenID Connect: Identity provider returned ID token: {:?}", - id_token_claims + "OpenID Connect: Identity provider returned ID token: {id_token_claims:?}" ); Ok(id_token_claims) @@ -1074,17 +1065,17 @@ impl AuthProvider { .map_err(|e| { let msg = match e { UserInfoError::ClaimsVerification(ref provider_err) => { - format!("Failed to verify claims: {:?}", provider_err) + format!("Failed to verify claims: {provider_err:?}") } UserInfoError::Response(_, _, ref provider_err) => { - format!("Server returned error response: {:?}", provider_err) + format!("Server returned error response: {provider_err:?}") } UserInfoError::Request(ref req) => { self.on_connection_issue(lock_guard); - format!("Request failed: {:?}", req) + format!("Request failed: {req:?}") } UserInfoError::Parse(ref parse_err) => { - format!("Failed to parse server response: {}", parse_err) + format!("Failed to parse server response: {parse_err}") } UserInfoError::Other(ref err_string) => match err_string.as_str() { "temporarily_unavailable" | "server_error" => { @@ -1097,7 +1088,7 @@ impl AuthProvider { }; Self::internal_error( - format!("OpenID Connect: UserInfo request failed: {}", msg), + format!("OpenID Connect: UserInfo request failed: {msg}"), Some(stringify_cause_chain(e)), ) })?, @@ -1217,8 +1208,7 @@ impl AuthProvider { // new session by logging in again. CoreErrorResponseType::InvalidGrant => { warn!( - "OpenID Connect: invalid_grant {:?}", - err + "OpenID Connect: invalid_grant {err:?}" ); return Err(ApiAuthError::ApiInvalidCredentials( "Unable to extend login session: your session has been terminated.".to_string(), @@ -1227,8 +1217,7 @@ impl AuthProvider { CoreErrorResponseType::InvalidRequest | CoreErrorResponseType::InvalidClient => { warn!( - "OpenID Connect: RFC 6749 5.2 {:?}", - err + "OpenID Connect: RFC 6749 5.2 {err:?}" ); return Err(ApiAuthError::ApiAuthPermanentError( "Unable to extend login session: the provider rejected the request.".to_string(), @@ -1243,8 +1232,7 @@ impl AuthProvider { | CoreErrorResponseType::UnsupportedGrantType | CoreErrorResponseType::InvalidScope => { warn!( - "OpenID Connect: RFC 6749 5.2 {:?}", - err + "OpenID Connect: RFC 6749 5.2 {err:?}" ); return Err(ApiAuthError::ApiInsufficientRights( "Unable to extend login session: the authorization was revoked for this user, client or action.".to_string(), @@ -1264,13 +1252,13 @@ impl AuthProvider { match err.as_str() { "temporarily_unavailable" | "server_error" => { - warn!("OpenID Connect: RFC 6749 5.2 {:?}", err); + warn!("OpenID Connect: RFC 6749 5.2 {err:?}"); return Err(ApiAuthError::ApiAuthTransientError( "Unable to extend login session: could not contact the provider".to_string(), )); } _ => { - warn!("OpenID Connect: RFC 6749 5.2 unknown error {:?}", err); + warn!("OpenID Connect: RFC 6749 5.2 unknown error {err:?}"); return Err(ApiAuthError::ApiAuthTransientError( "Unable to extend login session: unknown error".to_string(), )); @@ -1290,7 +1278,7 @@ impl AuthProvider { }; if log_enabled!(log::Level::Trace) { - trace!("Authentication result: {:?}", res); + trace!("Authentication result: {res:?}"); } res @@ -1504,14 +1492,12 @@ impl AuthProvider { cookie_value: &str, ) -> KrillResult { let cookie_str = format!( - "{}={}; Secure; HttpOnly; SameSite=Lax; Max-Age=300; Path=/", - cookie_name, cookie_value + "{cookie_name}={cookie_value}; Secure; HttpOnly; SameSite=Lax; Max-Age=300; Path=/" ); HeaderValue::from_str(&cookie_str).map_err(|err| { AuthProvider::internal_error( format!( - "Unable to construct HTTP cookie '{}' with value '{}'", - cookie_name, cookie_value + "Unable to construct HTTP cookie '{cookie_name}' with value '{cookie_value}'" ), Some(stringify_cause_chain(err)), ) @@ -1694,22 +1680,20 @@ impl AuthProvider { &role_name ).ok_or_else(|| { let reason = format!( - "Login denied for user '{}': \ - user is assigned undefined role '{}'.", - id, role_name + "Login denied for user '{id}': \ + user is assigned undefined role '{role_name}'." ); - warn!("{}", reason); + warn!("{reason}"); Error::ApiInsufficientRights(reason) })?; // Step 4 1/2: Check that the user is allowed to log in. if !role.is_allowed(Permission::Login, None) { let reason = format!( - "Login denied for user '{}': \ + "Login denied for user '{id}': \ User is not permitted to 'login'", - id, ); - warn!("{}", reason); + warn!("{reason}"); return Err(Error::ApiInsufficientRights(reason)); } diff --git a/src/daemon/http/auth/providers/openid_connect/util.rs b/src/daemon/http/auth/providers/openid_connect/util.rs index 2fa99679..74e3930a 100644 --- a/src/daemon/http/auth/providers/openid_connect/util.rs +++ b/src/daemon/http/auth/providers/openid_connect/util.rs @@ -167,24 +167,22 @@ pub trait LogOrFail { impl LogOrFail for Option { fn log_or_fail(self, prop: &str, val: Option<&str>) -> KrillResult<()> { let prop_val_text = match val { - Some(val) => format!("{}={}", prop, val), + Some(val) => format!("{prop}={val}"), None => prop.to_string(), }; match self { Some(_) => { debug!( - "OpenID Connect provider has capability {}", - prop_val_text + "OpenID Connect provider has capability {prop_val_text}" ); Ok(()) } None => { let err = format!( - "OpenID Connect provider lacks capability {}", - prop_val_text + "OpenID Connect provider lacks capability {prop_val_text}" ); - error!("{}", err); + error!("{err}"); Err(Error::Custom(err)) } } diff --git a/src/daemon/http/auth/session.rs b/src/daemon/http/auth/session.rs index 8b52eb75..1e3fb79d 100644 --- a/src/daemon/http/auth/session.rs +++ b/src/daemon/http/auth/session.rs @@ -73,8 +73,7 @@ impl ClientSession { Err(err) => { warn!( "Login session status check: unable to determine \ - the current time: {}", - err + the current time: {err}" ); } } @@ -172,8 +171,7 @@ impl LoginSessionCache { let session_json_str = serde_json::to_string(&session).map_err(|err| { Error::Custom(format!( - "Error while serializing session data: {}", - err + "Error while serializing session data: {err}" )) })?; let unencrypted_bytes = session_json_str.as_bytes(); @@ -195,8 +193,7 @@ impl LoginSessionCache { .duration_since(UNIX_EPOCH) .map_err(|err| { Error::Custom(format!( - "Unable to determine the current time: {}", - err + "Unable to determine the current time: {err}" )) })? .as_secs()) @@ -243,7 +240,7 @@ impl LoginSessionCache { let bytes = BASE64_ENGINE.decode(token.as_ref().as_bytes()).map_err( |err| { - debug!("Invalid bearer token: cannot decode: {}", err); + debug!("Invalid bearer token: cannot decode: {err}"); ApiAuthError::ApiInvalidCredentials( "Invalid bearer token".to_string(), ) @@ -256,7 +253,7 @@ impl LoginSessionCache { &unencrypted_bytes ).map_err(|err| { debug!( - "Invalid bearer token: cannot deserialize: {}", err + "Invalid bearer token: cannot deserialize: {err}" ); ApiAuthError::ApiInvalidCredentials( "Invalid bearer token".to_string(), @@ -343,8 +340,7 @@ impl LoginSessionCache { if size_after != size_before { debug!( "Login session cache purge: \ - size before={}, size after={}", - size_before, size_after + size before={size_before}, size after={size_after}" ); } } diff --git a/src/daemon/http/dispatch/auth.rs b/src/daemon/http/dispatch/auth.rs index 2853c514..e73c8b1e 100644 --- a/src/daemon/http/dispatch/auth.rs +++ b/src/daemon/http/dispatch/auth.rs @@ -82,8 +82,7 @@ mod multi_user { build_auth_redirect_location(user).map_err(|err| { Error::custom(format!( "Unable to build redirect with logged in user details: \ - {:?}", - err + {err:?}" )) }) }).map(|location| { diff --git a/src/daemon/http/dispatch/metrics.rs b/src/daemon/http/dispatch/metrics.rs index bed8d2c2..1e30040b 100644 --- a/src/daemon/http/dispatch/metrics.rs +++ b/src/daemon/http/dispatch/metrics.rs @@ -563,14 +563,14 @@ impl<'a> LabelValue<'a> { self.target.buf.push_str(", "); } write!( - &mut self.target.buf, "{}=\"{}\"", name, value + &mut self.target.buf, "{name}=\"{value}\"" ).expect("writing to string"); self } pub fn value(self, value: impl fmt::Display) { writeln!( - &mut self.target.buf, "}} {}", value + &mut self.target.buf, "}} {value}" ).expect("writing to string"); } } diff --git a/src/daemon/http/response.rs b/src/daemon/http/response.rs index 9f6c8775..5e6535e9 100644 --- a/src/daemon/http/response.rs +++ b/src/daemon/http/response.rs @@ -85,7 +85,7 @@ impl Response { if let Some(max_age) = self.max_age { builder = builder - .header("Cache-Control", &format!("max-age={}", max_age)); + .header("Cache-Control", &format!("max-age={max_age}")); } if self.status == StatusCode::UNAUTHORIZED { diff --git a/src/daemon/http/tls_keys.rs b/src/daemon/http/tls_keys.rs index 9d448f7d..1e59525b 100644 --- a/src/daemon/http/tls_keys.rs +++ b/src/daemon/http/tls_keys.rs @@ -224,13 +224,12 @@ impl fmt::Display for Error { write!(f, "Certificate PEM file contains no certificates") } Error::Pkcs12(e) => { - write!(f, "Cannot create PKCS12 Identity: {}", e) + write!(f, "Cannot create PKCS12 Identity: {e}") } - Error::Connection(e) => write!(f, "Connection error: {}", e), + Error::Connection(e) => write!(f, "Connection error: {e}"), Error::SignerError(e) => write!( f, - "Error signing self-signed HTTPS certificate: {}", - e + "Error signing self-signed HTTPS certificate: {e}" ), } } diff --git a/src/daemon/start.rs b/src/daemon/start.rs index 12a5ce16..698061f9 100644 --- a/src/daemon/start.rs +++ b/src/daemon/start.rs @@ -47,10 +47,9 @@ pub async fn start_krill_daemon( }, _ => { Error::Custom(format!( - "Upgrade data migration failed with error: {}\n\n\ + "Upgrade data migration failed with error: {e}\n\n\ NOTE: your data was not changed. Please downgrade \ - your krill instance to your previous version.", - e + your krill instance to your previous version." )) } } @@ -104,7 +103,7 @@ pub async fn start_krill_daemon( // Create self-signed HTTPS cert if configured and not generated earlier. if config.https_mode().is_generate_https_cert() { tls_keys::create_key_cert_if_needed(config.tls_keys_dir()) - .map_err(|e| Error::HttpsSetup(format!("{}", e)))?; + .map_err(|e| Error::HttpsSetup(format!("{e}")))?; } // Start a hyper server for the configured socket. @@ -137,7 +136,7 @@ async fn single_http_listener( let listener = match TcpListener::bind(addr).await { Ok(listener) => listener, Err(err) => { - error!("Could not bind to {}: {}", addr, err); + error!("Could not bind to {addr}: {err}"); return; } }; @@ -151,7 +150,7 @@ async fn single_http_listener( ) { Ok(config) => Some(TlsAcceptor::from(Arc::new(config))), Err(err) => { - error!("{}", err); + error!("{err}"); return; } } @@ -167,7 +166,7 @@ async fn single_http_listener( tls::MaybeTlsTcpStream::new(stream, tls.as_ref()) } Err(err) => { - error!("Fatal error in HTTP server {}: {}", addr, err); + error!("Fatal error in HTTP server {addr}: {err}"); return; } }; @@ -193,8 +192,7 @@ fn write_pid_file_or_die(config: &Config) { process::id().to_string().as_bytes(), config.pid_file() ) { print_write_error_hint_and_die(format!( - "Could not write PID file: {}", - e + "Could not write PID file: {e}" )); } } @@ -235,7 +233,7 @@ fn test_data_dir_or_die(config_item: &str, dir: &Path) { fn print_write_error_hint_and_die(error_msg: String) { - eprintln!("{}", error_msg); + eprintln!("{error_msg}"); eprintln!(); eprintln!("Hint: if you use systemd you may need to override the allowed"); eprintln!("ReadWritePaths, the easiest way may be by doing "); diff --git a/src/server/ca/aspa.rs b/src/server/ca/aspa.rs index dcb41b61..b342b3c5 100644 --- a/src/server/ca/aspa.rs +++ b/src/server/ca/aspa.rs @@ -320,7 +320,7 @@ impl AspaObjects { aspa_def.customer, aspa_def.providers.clone(), ).map_err(|e| { - Error::Custom(format!("Cannot use aspa config: {}", e)) + Error::Custom(format!("Cannot use aspa config: {e}")) })?; let object_builder = { diff --git a/src/server/ca/certauth.rs b/src/server/ca/certauth.rs index 93b8f358..b2305c1b 100644 --- a/src/server/ca/certauth.rs +++ b/src/server/ca/certauth.rs @@ -1999,8 +1999,7 @@ impl CertAuth { signer: Arc, ) -> KrillResult> { warn!( - "Dropping resource class '{}' because of reason: {}", - rcn, reason + "Dropping resource class '{rcn}' because of reason: {reason}" ); let rc = self.resources.get(&rcn).ok_or_else(|| { Error::ResourceClassUnknown(rcn.clone()) @@ -2498,8 +2497,7 @@ impl CertAuth { if self.rtas.has(&name) { return Err(Error::Custom(format!( - "RTA with name '{}' already exists", - name + "RTA with name '{name}' already exists" ))); } @@ -2562,7 +2560,7 @@ impl CertAuth { ) -> KrillResult> { if self.rtas.has(&name) { return Err(Error::Custom( - format!("RTA with name '{}' already exists", name) + format!("RTA with name '{name}' already exists") )); } diff --git a/src/server/ca/commands.rs b/src/server/ca/commands.rs index ea778a9f..f635cfc7 100644 --- a/src/server/ca/commands.rs +++ b/src/server/ca/commands.rs @@ -810,8 +810,7 @@ impl fmt::Display for CertAuthStorableCommand { } CertAuthStorableCommand::ChildCertify { child, ki, .. } => { write!(f, - "Issue certificate to child '{}' for key '{}'", - child, ki + "Issue certificate to child '{child}' for key '{ki}'" ) } CertAuthStorableCommand::ChildRevokeKey { child, revoke_req } => { @@ -825,45 +824,40 @@ impl fmt::Display for CertAuthStorableCommand { } CertAuthStorableCommand::ChildRemove { child } => { write!(f, - "Remove child '{}' and revoke & remove its certs", - child + "Remove child '{child}' and revoke & remove its certs" ) } CertAuthStorableCommand::ChildSuspendInactive { child } => { write!(f, - "Suspend inactive child '{}': stop publishing its certs", - child + "Suspend inactive child '{child}': stop publishing its certs" ) } CertAuthStorableCommand::ChildUnsuspend { child } => { write!(f, - "Unsuspend child '{}': publish its unexpired certs", - child + "Unsuspend child '{child}': publish its unexpired certs" ) } CertAuthStorableCommand::GenerateNewIdKey => { write!(f, "Generate a new RFC8183 ID.") } CertAuthStorableCommand::AddParent { parent, contact } => { - write!(f, "Add parent '{}' as '{}'", parent, contact) + write!(f, "Add parent '{parent}' as '{contact}'") } CertAuthStorableCommand::UpdateParentContact { parent, contact } => { write!(f, - "Update contact for parent '{}' to '{}'", - parent, contact + "Update contact for parent '{parent}' to '{contact}'" ) } CertAuthStorableCommand::RemoveParent { parent } => { - write!(f, "Remove parent '{}'", parent) + write!(f, "Remove parent '{parent}'") } CertAuthStorableCommand::UpdateResourceEntitlements { parent, entitlements } => { write!(f, - "Update entitlements under parent '{}': ", - parent + "Update entitlements under parent '{parent}': " )?; for entitlement in entitlements.iter() { write!(f, @@ -880,8 +874,7 @@ impl fmt::Display for CertAuthStorableCommand { } => { let summary = ResourceSetSummary::from(resources); write!(f, - "Update received cert in RC '{}', with resources '{}'", - resource_class_name, summary + "Update received cert in RC '{resource_class_name}', with resources '{summary}'" ) } CertAuthStorableCommand::DropResourceClass { @@ -889,32 +882,28 @@ impl fmt::Display for CertAuthStorableCommand { reason, } => { write!(f, - "Removing resource class '{}' because of reason: {}", - resource_class_name, reason + "Removing resource class '{resource_class_name}' because of reason: {reason}" ) } CertAuthStorableCommand::KeyRollInitiate { older_than_seconds } => { write!(f, - "Initiate key roll for keys older than '{}' seconds", - older_than_seconds + "Initiate key roll for keys older than '{older_than_seconds}' seconds" ) } CertAuthStorableCommand::KeyRollActivate { staged_for_seconds } => { write!(f, - "Activate new keys staging longer than '{}' seconds", - staged_for_seconds + "Activate new keys staging longer than '{staged_for_seconds}' seconds" ) } CertAuthStorableCommand::KeyRollFinish { resource_class_name } => { write!(f, - "Retire old revoked key in RC '{}'", - resource_class_name + "Retire old revoked key in RC '{resource_class_name}'" ) } CertAuthStorableCommand::RoaDefinitionUpdates { updates } => { @@ -922,13 +911,13 @@ impl fmt::Display for CertAuthStorableCommand { if !updates.added.is_empty() { write!(f, " ADD:",)?; for addition in &updates.added { - write!(f, " {}", addition)?; + write!(f, " {addition}")?; } } if !updates.removed.is_empty() { write!(f, " REMOVE:",)?; for rem in &updates.removed { - write!(f, " {}", rem)?; + write!(f, " {rem}")?; } } Ok(()) @@ -942,33 +931,32 @@ impl fmt::Display for CertAuthStorableCommand { write!(f, "Force re-issuance of objects") } CertAuthStorableCommand::AspasUpdate { updates } => { - write!(f, "{}", updates) + write!(f, "{updates}") } CertAuthStorableCommand::AspasUpdateExisting { customer, update } => { write!(f, - "update ASPA for customer AS: {} {}", - customer, update + "update ASPA for customer AS: {customer} {update}" ) } CertAuthStorableCommand::AspaRemove { customer } => { - write!(f, "Remove ASPA for customer AS: {}", customer) + write!(f, "Remove ASPA for customer AS: {customer}") } CertAuthStorableCommand::BgpSecDefinitionUpdates => { write!(f, "Update BGPSec definitions") } CertAuthStorableCommand::RepoUpdate { service_uri } => { - write!(f, "Update repo to server at: {}", service_uri) + write!(f, "Update repo to server at: {service_uri}") } CertAuthStorableCommand::RtaPrepare { name } => { - write!(f, "RTA Prepare {}", name) + write!(f, "RTA Prepare {name}") } CertAuthStorableCommand::RtaSign { name } => { - write!(f, "RTA Sign {}", name) + write!(f, "RTA Sign {name}") } CertAuthStorableCommand::RtaCoSign { name } => { - write!(f, "RTA Co-Sign {}", name) + write!(f, "RTA Co-Sign {name}") } CertAuthStorableCommand::Deactivate => { write!(f, "Deactivate CA") diff --git a/src/server/ca/events.rs b/src/server/ca/events.rs index d9618c8b..31515fa1 100644 --- a/src/server/ca/events.rs +++ b/src/server/ca/events.rs @@ -522,9 +522,8 @@ impl fmt::Display for CertAuthEvent { ki, } => write!( f, - "issued certificate to child '{}' for class '{}' and \ - pub key '{}'", - child, resource_class_name, ki + "issued certificate to child '{child}' for class '{resource_class_name}' and \ + pub key '{ki}'" ), CertAuthEvent::ChildCertificatesUpdated { resource_class_name, @@ -532,8 +531,7 @@ impl fmt::Display for CertAuthEvent { } => { write!( f, - "updated child certificates in resource class {}", - resource_class_name + "updated child certificates in resource class {resource_class_name}" )?; if !updates.issued.is_empty() { write!(f, " issued keys: ")?; @@ -544,7 +542,7 @@ impl fmt::Display for CertAuthEvent { if !updates.removed.is_empty() { write!(f, " revoked keys: ")?; for rev in &updates.removed { - write!(f, " {}", rev)?; + write!(f, " {rev}")?; } } if !updates.suspended.is_empty() { @@ -568,9 +566,8 @@ impl fmt::Display for CertAuthEvent { ki, } => write!( f, - "revoked certificate for child '{}' in resource class \ - '{}' with key(hash) '{}'", - child, resource_class_name, ki + "revoked certificate for child '{child}' in resource class \ + '{resource_class_name}' with key(hash) '{ki}'" ), CertAuthEvent::ChildUpdatedIdCert { child, id_cert } => { write!( @@ -582,7 +579,7 @@ impl fmt::Display for CertAuthEvent { } CertAuthEvent::ChildUpdatedResources { child, resources } => { write!(f, - "updated child '{}' resources to '{}'", child, resources + "updated child '{child}' resources to '{resources}'" ) } CertAuthEvent::ChildUpdatedResourceClassNameMapping { @@ -592,20 +589,19 @@ impl fmt::Display for CertAuthEvent { } => { write!( f, - "updated child '{}' map parent RC name '{}' to '{}' \ - for child", - child, name_in_parent, name_for_child + "updated child '{child}' map parent RC name '{name_in_parent}' to '{name_for_child}' \ + for child" ) } CertAuthEvent::ChildRemoved { child } => { - write!(f, "removed child '{}'", child) + write!(f, "removed child '{child}'") } CertAuthEvent::ChildSuspended { child } => { - write!(f, "suspended child '{}'", child) + write!(f, "suspended child '{child}'") } CertAuthEvent::ChildUnsuspended { child } => { - write!(f, "unsuspended child '{}'", child) + write!(f, "unsuspended child '{child}'") } CertAuthEvent::IdUpdated { id } => write!( f, @@ -613,20 +609,19 @@ impl fmt::Display for CertAuthEvent { id.cert().public_key.key_identifier() ), CertAuthEvent::ParentAdded { parent, .. } => { - write!(f, "added parent '{}' ", parent) + write!(f, "added parent '{parent}' ") } CertAuthEvent::ParentUpdated { parent, .. } => { - write!(f, "updated parent '{}'", parent) + write!(f, "updated parent '{parent}'") } CertAuthEvent::ParentRemoved { parent } => { - write!(f, "removed parent '{}'", parent) + write!(f, "removed parent '{parent}'") } CertAuthEvent::ResourceClassAdded { resource_class_name, .. } => { write!(f, - "added resource class with name '{}'", - resource_class_name + "added resource class with name '{resource_class_name}'" ) } CertAuthEvent::ResourceClassRemoved { @@ -635,8 +630,7 @@ impl fmt::Display for CertAuthEvent { .. } => { write!(f, - "removed resource class with name '{}' under parent '{}'", - resource_class_name, parent + "removed resource class with name '{resource_class_name}' under parent '{parent}'" ) } CertAuthEvent::CertificateRequested { @@ -645,9 +639,8 @@ impl fmt::Display for CertAuthEvent { .. } => { write!(f, - "requested certificate for key (hash) '{}' under \ - resource class '{}'", - ki, resource_class_name + "requested certificate for key (hash) '{ki}' under \ + resource class '{resource_class_name}'" ) } CertAuthEvent::CertificateReceived { @@ -656,9 +649,8 @@ impl fmt::Display for CertAuthEvent { .. } => { write!(f, - "received certificate for key (hash) '{}' under \ - resource class '{}'", - ki, resource_class_name + "received certificate for key (hash) '{ki}' under \ + resource class '{resource_class_name}'" ) } CertAuthEvent::KeyRollPendingKeyAdded { @@ -667,9 +659,8 @@ impl fmt::Display for CertAuthEvent { } => { write!( f, - "key roll: added pending key '{}' under resource class \ - '{}'", - pending_key_id, resource_class_name + "key roll: added pending key '{pending_key_id}' under resource class \ + '{resource_class_name}'" ) } CertAuthEvent::KeyPendingToNew { @@ -704,8 +695,7 @@ impl fmt::Display for CertAuthEvent { } CertAuthEvent::KeyRollFinished { resource_class_name } => { write!(f, - "key roll: finished for resource class '{}'", - resource_class_name + "key roll: finished for resource class '{resource_class_name}'" ) } CertAuthEvent::UnexpectedKeyFound { @@ -719,45 +709,41 @@ impl fmt::Display for CertAuthEvent { ) } CertAuthEvent::RouteAuthorizationAdded { auth } => { - write!(f, "added ROA: '{}'", auth) + write!(f, "added ROA: '{auth}'") } CertAuthEvent::RouteAuthorizationComment { auth, comment } => { if let Some(comment) = comment { write!(f, - "added comment to ROA: '{}' => {}", - auth, comment + "added comment to ROA: '{auth}' => {comment}" ) } else { - write!(f, "removed comment from ROA: '{}'", auth) + write!(f, "removed comment from ROA: '{auth}'") } } CertAuthEvent::RouteAuthorizationRemoved { auth } => { - write!(f, "removed ROA: '{}'", auth) + write!(f, "removed ROA: '{auth}'") } CertAuthEvent::RoasUpdated { resource_class_name, updates, } => { write!(f, - "updated ROA objects under resource class '{}'", - resource_class_name + "updated ROA objects under resource class '{resource_class_name}'" )?; updates.fmt_event(f) } CertAuthEvent::AspaConfigAdded { aspa_config: addition } => { - write!(f, "{}", addition) + write!(f, "{addition}") } CertAuthEvent::AspaConfigUpdated { customer, update } => { write!(f, - "updated ASPA config for customer ASN: {} {}", - customer, update + "updated ASPA config for customer ASN: {customer} {update}" ) } CertAuthEvent::AspaConfigRemoved { customer } => { write!(f, - "removed ASPA config for customer ASN: {}", - customer + "removed ASPA config for customer ASN: {customer}" ) } CertAuthEvent::AspaObjectsUpdated { @@ -765,8 +751,7 @@ impl fmt::Display for CertAuthEvent { updates, } => { write!(f, - "updated ASPA objects under resource class '{}'{}", - resource_class_name, updates, + "updated ASPA objects under resource class '{resource_class_name}'{updates}", ) } CertAuthEvent::BgpSecDefinitionAdded { key, .. } => { diff --git a/src/server/ca/keys.rs b/src/server/ca/keys.rs index 3f6be3c9..317aecca 100644 --- a/src/server/ca/keys.rs +++ b/src/server/ca/keys.rs @@ -157,10 +157,8 @@ impl CertifiedKey { } else if remaining_seconds_on_current == remaining_seconds_on_eligible { debug!( - "Will not request new certificate for CA '{}' \ - under RC '{}'. Resources and not after time are unchanged.", - handle, - rcn, + "Will not request new certificate for CA '{handle}' \ + under RC '{rcn}'. Resources and not after time are unchanged.", ); false } @@ -170,9 +168,8 @@ impl CertifiedKey { < 0.9_f64 { warn!( - "Parent of CA '{}' *reduced* not after time for certificate \ - under RC '{}'. This is odd, but requesting new certificate.", - handle, rcn, + "Parent of CA '{handle}' *reduced* not after time for certificate \ + under RC '{rcn}'. This is odd, but requesting new certificate.", ); true } diff --git a/src/server/ca/manager.rs b/src/server/ca/manager.rs index f65da098..61e6243d 100644 --- a/src/server/ca/manager.rs +++ b/src/server/ca/manager.rs @@ -751,31 +751,28 @@ impl CaManager { ca_handle: &CaHandle, actor: &Actor, ) -> KrillResult<()> { - warn!("Deleting CA '{}' as requested by: {}", ca_handle, actor); + warn!("Deleting CA '{ca_handle}' as requested by: {actor}"); let ca = self.get_ca(ca_handle)?; // Request revocations from all parents - best effort info!( - "Will try to request revocations from all parents CA '{}' \ - before removing it.", - ca_handle + "Will try to request revocations from all parents CA '{ca_handle}' \ + before removing it." ); for parent in ca.parents() { if let Err(e) = self.ca_parent_revoke(ca_handle, parent).await { warn!( - "Removing CA '{}', but could not send revoke request \ - to parent '{}': {}", - ca_handle, parent, e + "Removing CA '{ca_handle}', but could not send revoke request \ + to parent '{parent}': {e}" ); } } // Clean all repos - again best effort info!( - "Will try to clean up all repositories for CA '{}' before \ - removing it.", - ca_handle + "Will try to clean up all repositories for CA '{ca_handle}' before \ + removing it." ); // XXX This is quite wasteful. Maybe have a dedicated method to @@ -875,7 +872,7 @@ impl CaManager { ca: &CaHandle, child: &ChildHandle, ) -> KrillResult { - trace!("Finding details for CA: {} under parent: {}", child, ca); + trace!("Finding details for CA: {child} under parent: {ca}"); self.get_ca(ca)?.get_child(child).map(|details| details.to_info()) } @@ -895,7 +892,7 @@ impl CaManager { ca: &CaHandle, child_handle: &ChildHandle, ) -> KrillResult { - trace!("Exporting CA: {} under parent: {}", child_handle, ca); + trace!("Exporting CA: {child_handle} under parent: {ca}"); self.get_ca(ca)?.child_export(child_handle) } @@ -974,7 +971,7 @@ impl CaManager { base_uri: &uri::Https, ca_handle: &CaHandle, ) -> ServiceUri { - let service_uri = format!("{}rfc6492/{}", base_uri, ca_handle); + let service_uri = format!("{base_uri}rfc6492/{ca_handle}"); let service_uri = uri::Https::from_string(service_uri).unwrap(); ServiceUri::Https(service_uri) } @@ -1425,9 +1422,8 @@ impl CaManager { // parent. if let Err(e) = self.ca_parent_revoke(&handle, &parent).await { warn!( - "Removing parent '{}' from CA '{}', but could not send \ - revoke requests: {}", - parent, handle, e + "Removing parent '{parent}' from CA '{handle}', but could not send \ + revoke requests: {e}" ); } @@ -1528,13 +1524,12 @@ impl CaManager { let threshold_string = if threshold_seconds >= 3600 { format!("{} hours", threshold_seconds / 3600) } else { - format!("{} seconds", threshold_seconds) + format!("{threshold_seconds} seconds") }; info!( - "Child '{}' under CA '{}' was inactive for more \ - than {}. Will suspend it.", - child, ca_handle, threshold_string + "Child '{child}' under CA '{ca_handle}' was inactive for more \ + than {threshold_string}. Will suspend it." ); } if let Err(e) = @@ -1553,8 +1548,7 @@ impl CaManager { ca_handle, child, req, actor ) { error!( - "Could not suspend inactive child, error: {}", - e + "Could not suspend inactive child, error: {e}" ); } } @@ -1928,8 +1922,7 @@ impl CaManager { } _ => { return Err(Error::custom(format!( - "Got unexpected response '{}' to revoke query", - payload_type + "Got unexpected response '{payload_type}' to revoke query" ))) } } @@ -2366,12 +2359,11 @@ impl CaManager { match payload { provisioning::Payload::ListResponse(response) => Ok(response), provisioning::Payload::ErrorResponse(np) => { - Err(Error::Custom(format!("Not performed: {}", np))) + Err(Error::Custom(format!("Not performed: {np}"))) } _ => { Err(Error::custom(format!( - "Got unexpected response type '{}' to list query", - payload_type + "Got unexpected response type '{payload_type}' to list query" ))) } } @@ -2427,10 +2419,9 @@ impl CaManager { Err(e) => { error!( "Could not decode response from parent (handle): \ - {}, for ca (handle): {}, at URI: {}. Error: {}", - recipient, sender, service_uri, e + {recipient}, for ca (handle): {sender}, at URI: {service_uri}. Error: {e}" ); - cms_logger.err(format!("Could not decode CMS: {}", e))?; + cms_logger.err(format!("Could not decode CMS: {e}"))?; Err(Error::Rfc6492(e)) } Ok(cms) => { @@ -2440,12 +2431,11 @@ impl CaManager { Err(e) => { error!( "Could not validate response from parent \ - (handle): {}, for ca (handle): {}, \ - at URI: {}. Error: {}", - recipient, sender, service_uri, e + (handle): {recipient}, for ca (handle): {sender}, \ + at URI: {service_uri}. Error: {e}" ); cms_logger.err( - format!("Response invalid: {}", e) + format!("Response invalid: {e}") )?; Err(Error::Rfc6492(e)) } @@ -2475,7 +2465,7 @@ impl CaManager { ).await { Err(e) => { cms_logger.err(format!( - "Error posting CMS to {}: {}", service_uri, e + "Error posting CMS to {service_uri}: {e}" ))?; Err(Error::HttpClientError(e)) } @@ -2628,8 +2618,7 @@ impl CaManager { vec![], ).await { warn!( - "Could not clean up deprecated repository: {}", - e + "Could not clean up deprecated repository: {e}" ); if deprecated.clean_attempts() < 5 { @@ -2661,7 +2650,7 @@ impl CaManager { repo_contact: &RepositoryContact, publish_elements: Vec, ) -> KrillResult<()> { - debug!("CA '{}' sends list query to repo", ca_handle); + debug!("CA '{ca_handle}' sends list query to repo"); let list_reply = self.send_rfc8181_list( repo_manager, ca_handle, @@ -2699,7 +2688,7 @@ impl CaManager { } if !delta.is_empty() { - debug!("CA '{}' sends delta", ca_handle); + debug!("CA '{ca_handle}' sends delta"); self.send_rfc8181_delta( repo_manager, ca_handle, @@ -2707,10 +2696,10 @@ impl CaManager { &repo_contact.server_info, delta, ).await?; - debug!("CA '{}' sent delta", ca_handle); + debug!("CA '{ca_handle}' sent delta"); } else { - debug!("CA '{}' has nothing to publish", ca_handle); + debug!("CA '{ca_handle}' has nothing to publish"); } Ok(()) @@ -2850,7 +2839,7 @@ impl CaManager { Err(err) } publication::Reply::ErrorReply(e) => { - let err = Error::Custom(format!("Got error reply: {}", e)); + let err = Error::Custom(format!("Got error reply: {e}")); self.status_store.set_status_repo_failure( ca_handle, server_info.service_uri.clone(), @@ -2902,7 +2891,7 @@ impl CaManager { Ok(()) } publication::Reply::ErrorReply(e) => { - let err = Error::Custom(format!("Got error reply: {}", e)); + let err = Error::Custom(format!("Got error reply: {e}")); self.status_store.set_status_repo_failure( ca_handle, server_info.service_uri.clone(), @@ -2966,20 +2955,18 @@ impl CaManager { Err(e) => { error!( "Could not decode response from publication server \ - at: {}, for ca: {}. Error: {}", - repo_service_uri, ca_handle, e + at: {repo_service_uri}, for ca: {ca_handle}. Error: {e}" ); - cms_logger.err(format!("Could not decode CMS: {}", e))?; + cms_logger.err(format!("Could not decode CMS: {e}"))?; Err(Error::Rfc8181(e)) } Ok(cms) => match cms.validate(&server_info.public_key) { Err(e) => { error!( "Could not validate response from publication \ - server at: {}, for ca: {}. Error: {}", - repo_service_uri, ca_handle, e + server at: {repo_service_uri}, for ca: {ca_handle}. Error: {e}" ); - cms_logger.err(format!("Response invalid: {}", e))?; + cms_logger.err(format!("Response invalid: {e}"))?; Err(Error::Rfc8181(e)) } Ok(()) => { @@ -3122,8 +3109,7 @@ impl CaManager { ) ) { error!( - "Renewing ROAs for CA '{}' failed with error: {}", - ca, e + "Renewing ROAs for CA '{ca}' failed with error: {e}" ); } @@ -3135,8 +3121,7 @@ impl CaManager { ), ) { error!( - "Renewing ASPAs for CA '{}' failed with error: {}", - ca, e + "Renewing ASPAs for CA '{ca}' failed with error: {e}" ); } @@ -3176,8 +3161,7 @@ impl CaManager { ), ) { error!( - "Renewing ROAs for CA '{}' failed with error: {}", - ca, e + "Renewing ROAs for CA '{ca}' failed with error: {e}" ); } } diff --git a/src/server/ca/publishing.rs b/src/server/ca/publishing.rs index fd25e5f9..40678dc2 100644 --- a/src/server/ca/publishing.rs +++ b/src/server/ca/publishing.rs @@ -211,7 +211,7 @@ impl CaObjectsStore { fn key(ca: &CaHandle) -> Key { // CA handles should always be a valid segment Key::new_global( - Segment::parse_lossy(&format!("{}.json", ca)) + Segment::parse_lossy(&format!("{ca}.json")) ) } @@ -296,7 +296,7 @@ impl CaObjectsStore { force: bool, ca_handle: &CaHandle, ) -> KrillResult { - debug!("Re-issue for CA {} using force: {}", ca_handle, force); + debug!("Re-issue for CA {ca_handle} using force: {force}"); self.with_ca_objects(ca_handle, |objects| { objects.re_issue( force, diff --git a/src/server/ca/roa.rs b/src/server/ca/roa.rs index 362d4afe..0ebaa840 100644 --- a/src/server/ca/roa.rs +++ b/src/server/ca/roa.rs @@ -597,7 +597,7 @@ impl Roas { } }; - debug!("Selecting ROA publication mode: {:?}", mode); + debug!("Selecting ROA publication mode: {mode:?}"); mode } @@ -683,7 +683,7 @@ impl Roas { // Then remove all simple ROAs for roa_key in self.simple.keys() { - debug!("Will remove simple authorization for: {}", roa_key); + debug!("Will remove simple authorization for: {roa_key}"); roa_updates.removed.push(*roa_key); } @@ -1055,7 +1055,7 @@ mod tests { fn parse_encode_authorization(s: &str) { let auth = authorization(s); let json = serde_json::to_string(&auth).unwrap(); - assert_eq!(format!("\"{}\"", s), json); + assert_eq!(format!("\"{s}\""), json); let des: RoaPayloadJsonMapKey = serde_json::from_str(&json).unwrap(); diff --git a/src/server/ca/status.rs b/src/server/ca/status.rs index 8f428ab8..61d3c700 100644 --- a/src/server/ca/status.rs +++ b/src/server/ca/status.rs @@ -202,9 +202,8 @@ impl CaStatusStore { let status = self.store.get::(&key).ok().flatten(); if let Some(full_status) = status { info!( - "Migrating pre 0.9.5 connection status file for CA '{}' \ - to new format", - ca + "Migrating pre 0.9.5 connection status file for CA '{ca}' \ + to new format" ); // repo status self.store.store( @@ -249,8 +248,7 @@ impl CaStatusStore { Key::new_scoped( Scope::from_segment(Segment::parse_lossy(ca.as_str())), Segment::parse_lossy(&format!( - "{}{}{}", - PARENTS_PREFIX, parent, JSON_SUFFIX + "{PARENTS_PREFIX}{parent}{JSON_SUFFIX}" )), ) } @@ -260,8 +258,7 @@ impl CaStatusStore { Key::new_scoped( Scope::from_segment(Segment::parse_lossy(ca.as_str())), Segment::parse_lossy(&format!( - "{}{}{}", - CHILDREN_PREFIX, child, JSON_SUFFIX + "{CHILDREN_PREFIX}{child}{JSON_SUFFIX}" )), ) } diff --git a/src/server/ca/upgrades/data_migration.rs b/src/server/ca/upgrades/data_migration.rs index 7f4d0a81..6063f2f6 100644 --- a/src/server/ca/upgrades/data_migration.rs +++ b/src/server/ca/upgrades/data_migration.rs @@ -38,13 +38,13 @@ pub fn check_ca_objects(config: &Config) -> UpgradeResult<()> { for ca in &cas_with_objects { ca_objects_store.ca_objects(ca)?; if !ca_store.has(ca)? { - warn!(" Objects found for CA '{}' which no longer exists.", ca); + warn!(" Objects found for CA '{ca}' which no longer exists."); } } for ca in ca_store.list()? { if !cas_with_objects.contains(&ca) { - debug!(" CA '{}' did not have any CA objects yet.", ca); + debug!(" CA '{ca}' did not have any CA objects yet."); } } diff --git a/src/server/ca/upgrades/pre_0_10_0/migration.rs b/src/server/ca/upgrades/pre_0_10_0/migration.rs index 5fb3cfdf..0b763884 100644 --- a/src/server/ca/upgrades/pre_0_10_0/migration.rs +++ b/src/server/ca/upgrades/pre_0_10_0/migration.rs @@ -232,8 +232,7 @@ impl UpgradeAggregateStorePre0_14 for CasMigration { /// Override post migration, we need to do extra stuff. fn post_command_migration(&self, handle: &MyHandle) -> UpgradeResult<()> { info!( - "Will migrate the current repository objects for CA '{}'", - handle + "Will migrate the current repository objects for CA '{handle}'" ); self.ca_objects_migration.prepare_new_data_for(handle) } @@ -270,7 +269,7 @@ impl CaObjectsMigration { ca: &CaHandle, ) -> Result<(), UpgradeError> { let key = - Key::new_global(Segment::parse_lossy(&format!("{}.json", ca))); // ca should always be a valid Segment + Key::new_global(Segment::parse_lossy(&format!("{ca}.json"))); // ca should always be a valid Segment if let Some(old_objects) = self.current_store.get::(&key)? diff --git a/src/server/ca/upgrades/pre_0_10_0/old_events.rs b/src/server/ca/upgrades/pre_0_10_0/old_events.rs index e11e9d5e..c6d55d5b 100644 --- a/src/server/ca/upgrades/pre_0_10_0/old_events.rs +++ b/src/server/ca/upgrades/pre_0_10_0/old_events.rs @@ -129,8 +129,7 @@ impl TryFrom for TaCertDetails { ReceivedCert::create(cert, rsync_uri.clone(), resources, limit) .map_err(|e| { UpgradeError::Custom(format!( - "Could not convert old TA details: {}", - e + "Could not convert old TA details: {e}" )) })?; @@ -234,8 +233,7 @@ impl TryFrom for CertInfo { CertInfo::create(old.cert, old.uri, old.resource_set, old.limit) .map_err(|e| { UpgradeError::Custom(format!( - "cannot convert certificate: {}", - e + "cannot convert certificate: {e}" )) }) } @@ -275,7 +273,7 @@ impl TryFrom for ReceivedCert { RequestResourceLimit::default(), ) .map_err(|e| { - UpgradeError::Custom(format!("cannot convert certificate: {}", e)) + UpgradeError::Custom(format!("cannot convert certificate: {e}")) }) } } diff --git a/src/server/ca/upgrades/pre_0_14_0/old_events.rs b/src/server/ca/upgrades/pre_0_14_0/old_events.rs index 2c43f900..8b333401 100644 --- a/src/server/ca/upgrades/pre_0_14_0/old_events.rs +++ b/src/server/ca/upgrades/pre_0_14_0/old_events.rs @@ -274,7 +274,7 @@ pub enum Pre0_14_0CertAuthEvent { impl fmt::Display for Pre0_14_0CertAuthEvent { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{:?}", self) + write!(f, "{self:?}") } } diff --git a/src/server/manager.rs b/src/server/manager.rs index bdf9492b..0000fecd 100644 --- a/src/server/manager.rs +++ b/src/server/manager.rs @@ -108,7 +108,7 @@ impl KrillManager { let service_uri = config.service_uri(); info!("Starting {} v{}", KRILL_SERVER_APP, crate_version!()); - info!("{} uses service uri: {}", KRILL_SERVER_APP, service_uri); + info!("{KRILL_SERVER_APP} uses service uri: {service_uri}"); // Assumes that Config::verify() has already ensured that the signer // configuration is valid and that Config::resolve() has been @@ -216,7 +216,7 @@ impl KrillManager { testbed_ca_handle().into_converted(); for nr in 0..benchmark.cas { let handle = CaHandle::new( - format!("benchmark-{}", nr).into(), + format!("benchmark-{nr}").into(), ); // derive resources for benchmark ca @@ -224,15 +224,13 @@ impl KrillManager { let byte_3_ipv4 = nr % 256; let prefix_str = format!( - "10.{}.{}.0/24", - byte_2_ipv4, byte_3_ipv4 + "10.{byte_2_ipv4}.{byte_3_ipv4}.0/24" ); let resources = ResourceSet::from_strs("", &prefix_str, "") .map_err(|e| { Error::ResourceSetError(format!( - "cannot parse resources: {}", - e + "cannot parse resources: {e}" )) })?; @@ -243,8 +241,7 @@ impl KrillManager { ..asn_range_start + benchmark.ca_roas { let payload = RoaPayload::from_str(&format!( - "{} => {}", - prefix_str, asn + "{prefix_str} => {asn}" )) .unwrap(); roas.push(payload.into()); @@ -721,7 +718,7 @@ impl KrillManager { ))); } try_join_all(import_fns).await.map_err(|e| { - Error::Custom(format!("Could not import CAs: {}", e)) + Error::Custom(format!("Could not import CAs: {e}")) })?; Ok(()) diff --git a/src/server/mq.rs b/src/server/mq.rs index f107d692..ec956bf2 100644 --- a/src/server/mq.rs +++ b/src/server/mq.rs @@ -97,20 +97,18 @@ impl Task { fn name(&self) -> KrillResult { match self { Task::SyncRepo { ca_handle: ca, .. } => { - SegmentBuf::from_str(&format!("sync_repo_{}", ca)) + SegmentBuf::from_str(&format!("sync_repo_{ca}")) } Task::SyncParent { ca_handle: ca, parent, .. } => SegmentBuf::from_str(&format!( - "sync_{}_with_parent_{}", - ca, parent + "sync_{ca}_with_parent_{parent}" )), Task::SuspendChildrenIfNeeded { ca_handle: ca } => { SegmentBuf::from_str(&format!( - "suspend_children_if_needed_{}", - ca + "suspend_children_if_needed_{ca}" )) } Task::RepublishIfNeeded => { @@ -125,8 +123,7 @@ impl Task { rcn, .. } => SegmentBuf::from_str(&format!( - "resource_class_removed_ca_{}_parent_{}_rcn_{}", - ca, parent, rcn + "resource_class_removed_ca_{ca}_parent_{parent}_rcn_{rcn}" )), Task::UnexpectedKey { ca_handle: ca, @@ -161,7 +158,7 @@ impl Task { Ok(Segment::make("refresh_bgp_announcements_info").to_owned()) } } - .map_err(|e| Error::Custom(format!("could not create name: {}", e))) + .map_err(|e| Error::Custom(format!("could not create name: {e}"))) } } @@ -170,21 +167,21 @@ impl fmt::Display for Task { match self { Task::QueueStartTasks => write!(f, "Server just started"), Task::SyncRepo { ca_handle: ca, .. } => { - write!(f, "synchronize repo for '{}'", ca) + write!(f, "synchronize repo for '{ca}'") } Task::SyncParent { ca_handle: ca, parent, .. } => { - write!(f, "synchronize CA '{}' with parent '{}'", ca, parent) + write!(f, "synchronize CA '{ca}' with parent '{parent}'") } Task::RenewTestbedTa => write!(f, "renew testbed TA"), Task::SyncTrustAnchorProxySignerIfPossible => { write!(f, "sync TA Proxy and Signer if both in this server.") } Task::SuspendChildrenIfNeeded { ca_handle: ca } => { - write!(f, "verify if CA '{}' has children to suspend", ca) + write!(f, "verify if CA '{ca}' has children to suspend") } Task::RepublishIfNeeded => { write!(f, "let CAs republish their mft/crls if needed") @@ -199,15 +196,14 @@ impl fmt::Display for Task { write!(f, "create new RRDP delta, if needed") } Task::ResourceClassRemoved { ca_handle: ca, .. } => { - write!(f, "resource class removed for '{}' ", ca) + write!(f, "resource class removed for '{ca}' ") } Task::UnexpectedKey { ca_handle: ca, rcn, .. } => { write!( f, - "unexpected key found for '{}' resource class: '{}'", - ca, rcn + "unexpected key found for '{ca}' resource class: '{rcn}'" ) } Task::SweepLoginCache => write!(f, "sweep up expired logins"), @@ -248,7 +244,7 @@ impl TaskQueue { // a database is used - might be temporarily unavailable. // In that case we don't want Krill to crash on this, but // just keep trying to poll. - error!("Could not get pending task from queue: {}", e); + error!("Could not get pending task from queue: {e}"); None } Ok(None) => { @@ -315,14 +311,11 @@ impl TaskQueue { ) -> KrillResult<()> { let task_name = task.name()?; debug!( - "add task: {} with priority: {}", - task_name, - priority, + "add task: {task_name} with priority: {priority}", ); let json = serde_json::to_value(&task).map_err(|e| { Error::Custom(format!( - "could not serialize task {}. error: {}", - task_name, e + "could not serialize task {task_name}. error: {e}" )) })?; @@ -333,7 +326,7 @@ impl TaskQueue { /// Finish a running task, without rescheduling it. pub fn finish(&self, task: &Key) -> KrillResult<()> { - debug!("Finish task: {}", task); + debug!("Finish task: {task}"); self.q.finish_running_task(task).map_err(Error::from) } @@ -343,7 +336,7 @@ impl TaskQueue { task: &Key, priority: Priority, ) -> KrillResult<()> { - debug!("Reschedule task: {} to: {}", task, priority); + debug!("Reschedule task: {task} to: {priority}"); self.q .reschedule_running_task(task, Some(priority.to_millis())) .map_err(Error::from) @@ -381,8 +374,7 @@ impl TaskQueue { let ca_handle = ca.handle().clone(); debug!( - "Seen event for CA {} version {}: '{}'", - ca_handle, ca_version, event + "Seen event for CA {ca_handle} version {ca_version}: '{event}'" ); match event { @@ -477,8 +469,7 @@ impl TaskQueue { | CertAuthEvent::ParentUpdated { parent, .. } => { if ca.repository_contact().is_ok() { debug!( - "Parent {} added to CA {}, scheduling sync", - parent, ca_handle + "Parent {parent} added to CA {ca_handle}, scheduling sync" ); self.schedule( Task::SyncParent { @@ -493,8 +484,7 @@ impl TaskQueue { // when the event for updating the // repository is seen. warn!( - "Synchronisation of CA '{}' with parent '{}' postponed until repository is configured.", - ca_handle, parent + "Synchronisation of CA '{ca_handle}' with parent '{parent}' postponed until repository is configured." ); Ok(()) } @@ -517,13 +507,11 @@ impl TaskQueue { .. } => { debug!( - "CA {} requested certificate for RC {}", - ca_handle, resource_class_name + "CA {ca_handle} requested certificate for RC {resource_class_name}" ); if let Ok(parent) = ca.parent_for_rc(resource_class_name) { debug!( - "CA {} will schedule sync for parent {} when CA is version {}", - ca_handle, parent, ca_version + "CA {ca_handle} will schedule sync for parent {parent} when CA is version {ca_version}" ); self.schedule( Task::SyncParent { @@ -601,7 +589,7 @@ impl eventsourcing::PreSaveEventListener for TaskQueue { events: &[TrustAnchorProxyEvent], ) -> KrillResult<()> { for event in events { - trace!("Seen TrustAnchorProxy event '{}'", event); + trace!("Seen TrustAnchorProxy event '{event}'"); match event { TrustAnchorProxyEvent::ChildRequestAdded( _child, @@ -651,8 +639,7 @@ impl eventsourcing::PostSaveEventListener for TaskQueue { // response. for ca in response.content().child_responses.keys() { trace!( - "Received signed response for TA child {}", - ca + "Received signed response for TA child {ca}" ); if let Err(e) = self.schedule( Task::SyncParent { diff --git a/src/server/pubd/access.rs b/src/server/pubd/access.rs index 68ecbff3..7921801e 100644 --- a/src/server/pubd/access.rs +++ b/src/server/pubd/access.rs @@ -77,8 +77,7 @@ impl RepositoryAccessProxy { // - user started error!( "Could not warm up cache, data seems corrupt. \ - You may need to restore a backup. Error was: {}", - e + You may need to restore a backup. Error was: {e}" ); } } @@ -144,7 +143,7 @@ impl RepositoryAccessProxy { } else { self.store.get_latest(&self.key).map_err(|e| { - Error::custom(format!("Publication Server data issue: {}", e)) + Error::custom(format!("Publication Server data issue: {e}")) }) } } @@ -422,8 +421,7 @@ impl RepositoryAccess { uri::Rsync::from_str( &format!("{}{}/", self.rsync_base, name)).map_err(|_| { Error::Custom(format!( - "Cannot derive base uri for {}", - name + "Cannot derive base uri for {name}" )) } ) @@ -628,10 +626,10 @@ impl fmt::Display for StorableRepositoryCommand { write!(f, "Initialise server") } StorableRepositoryCommand::AddPublisher { name } => { - write!(f, "Added publisher '{}'", name) + write!(f, "Added publisher '{name}'") } StorableRepositoryCommand::RemovePublisher { name } => { - write!(f, "Removed publisher '{}'", name) + write!(f, "Removed publisher '{name}'") } } } @@ -718,10 +716,10 @@ impl fmt::Display for RepositoryAccessEvent { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { RepositoryAccessEvent::PublisherAdded { name, .. } => { - write!(f, "Publisher '{}' added", name) + write!(f, "Publisher '{name}' added") } RepositoryAccessEvent::PublisherRemoved { name } => { - write!(f, "Publisher '{}' removed", name) + write!(f, "Publisher '{name}' removed") } } } diff --git a/src/server/pubd/content.rs b/src/server/pubd/content.rs index 29c3e240..fb016d76 100644 --- a/src/server/pubd/content.rs +++ b/src/server/pubd/content.rs @@ -164,7 +164,7 @@ impl RepositoryContentProxy { delta: PublishDelta, jail: &uri::Rsync, ) -> KrillResult<()> { - debug!("Publish delta for {}", publisher); + debug!("Publish delta for {publisher}"); self.store.send_command( RepositoryContentCommand::publish( self.default_handle.clone(), @@ -480,7 +480,7 @@ impl RepositoryContent { ) -> KrillResult> { let mut res = vec![]; - info!("Deleting files matching '{}'", del_uri); + info!("Deleting files matching '{del_uri}'"); for publisher in self.rrdp.publishers() { let current_objects = self.objects_for_publisher(&publisher); @@ -665,16 +665,15 @@ impl fmt::Display for RepositoryContentCommand { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { RepositoryContentCommand::ResetSession { handle } => { - write!(f, "reset session for repository {}", handle) + write!(f, "reset session for repository {handle}") } RepositoryContentCommand::CreateRrdpDelta { handle, .. } => { - write!(f, "create next RRDP delta for repository {}", handle) + write!(f, "create next RRDP delta for repository {handle}") } RepositoryContentCommand::AddPublisher { handle, publisher } => { write!( f, - "add publisher '{}' to repository {}", - publisher, handle + "add publisher '{publisher}' to repository {handle}" ) } RepositoryContentCommand::RemovePublisher { @@ -684,8 +683,7 @@ impl fmt::Display for RepositoryContentCommand { } => { write!( f, - "remove publisher '{}' from repository {}", - publisher, handle + "remove publisher '{publisher}' from repository {handle}" ) } RepositoryContentCommand::DeleteMatchingFiles { @@ -695,8 +693,7 @@ impl fmt::Display for RepositoryContentCommand { } => { write!( f, - "remove content matching '{}' from repository {}", - uri, handle + "remove content matching '{uri}' from repository {handle}" ) } RepositoryContentCommand::Publish { @@ -704,8 +701,7 @@ impl fmt::Display for RepositoryContentCommand { } => { write!( f, - "publish for publisher '{}' under repository {}", - publisher, handle + "publish for publisher '{publisher}' under repository {handle}" ) } } @@ -749,10 +745,10 @@ impl fmt::Display for RepositoryContentChange { write!(f, "RRDP updated") } RepositoryContentChange::PublisherAdded { publisher } => { - write!(f, "added publisher: {}", publisher) + write!(f, "added publisher: {publisher}") } RepositoryContentChange::PublisherRemoved { publisher } => { - write!(f, "removed publisher: {}", publisher) + write!(f, "removed publisher: {publisher}") } } } diff --git a/src/server/pubd/manager.rs b/src/server/pubd/manager.rs index ca40c841..1d1d876f 100644 --- a/src/server/pubd/manager.rs +++ b/src/server/pubd/manager.rs @@ -137,8 +137,7 @@ impl RepositoryManager { &publisher_handle, &msg_bytes ).map_err(|e| { Error::Custom(format!( - "Issue with publication request by publisher '{}': {}", - publisher_handle, e + "Issue with publication request by publisher '{publisher_handle}': {e}" )) })?; let message = cms.into_message(); @@ -184,16 +183,14 @@ impl RepositoryManager { match query { publication::Query::List => { debug!( - "Received RFC 8181 list query for {}", - publisher_handle + "Received RFC 8181 list query for {publisher_handle}" ); let list_reply = self.list(publisher_handle)?; Ok(publication::Message::list_reply(list_reply)) } publication::Query::Delta(delta) => { debug!( - "Received RFC 8181 delta query for {}", - publisher_handle + "Received RFC 8181 delta query for {publisher_handle}" ); self.publish(publisher_handle, delta)?; Ok(publication::Message::success()) @@ -911,7 +908,7 @@ mod tests { serial: u64, filename: &str, ) -> Option { - let session_path = base_dir.join(format!("repo/rrdp/{}", session)); + let session_path = base_dir.join(format!("repo/rrdp/{session}")); RrdpServer::find_in_serial_dir(&session_path, serial, filename) .unwrap() } diff --git a/src/server/pubd/rrdp.rs b/src/server/pubd/rrdp.rs index ca7eddfe..48e560fb 100644 --- a/src/server/pubd/rrdp.rs +++ b/src/server/pubd/rrdp.rs @@ -758,7 +758,7 @@ impl RrdpServer { let mut dest = self.rrdp_archive_dir.clone(); dest.push(self.session.to_string()); - dest.push(format!("{}", serial)); + dest.push(format!("{serial}")); info!( "Archiving RRDP serial '{}' to '{}", @@ -2131,18 +2131,16 @@ impl fmt::Display for PublicationDeltaError { match self { PublicationDeltaError::UriOutsideJail(uri, jail) => { write!(f, - "Publishing '{}' outside of jail URI '{}'", - uri, jail + "Publishing '{uri}' outside of jail URI '{jail}'" ) } PublicationDeltaError::ObjectAlreadyPresent(uri) => { write!(f, - "File already exists for uri (use update!): {}", - uri + "File already exists for uri (use update!): {uri}" ) } PublicationDeltaError::NoObjectForHashAndOrUri(uri) => { - write!(f, "File does not match hash at uri: {}", uri) + write!(f, "File does not match hash at uri: {uri}") } } } @@ -2264,8 +2262,7 @@ mod test { fn file_uri(name: &str) -> CurrentObjectUri { CurrentObjectUri( format!( - "rsync://example.krill.cloud/repo/publisher/{}", - name + "rsync://example.krill.cloud/repo/publisher/{name}" ) .into(), ) diff --git a/src/server/pubd/rsync.rs b/src/server/pubd/rsync.rs index 2a5d30f3..0a0ef24c 100644 --- a/src/server/pubd/rsync.rs +++ b/src/server/pubd/rsync.rs @@ -79,7 +79,7 @@ impl RsyncdStore { })?; let mut new_dir = self.rsync_dir.clone(); - new_dir.push(format!("tmp-{}", serial)); + new_dir.push(format!("tmp-{serial}")); fs::create_dir_all(&new_dir).map_err(|e| { KrillIoError::new( format!( diff --git a/src/server/pubd/upgrades/pre_0_13_0.rs b/src/server/pubd/upgrades/pre_0_13_0.rs index 497ddfaf..0101306b 100644 --- a/src/server/pubd/upgrades/pre_0_13_0.rs +++ b/src/server/pubd/upgrades/pre_0_13_0.rs @@ -322,7 +322,7 @@ pub enum OldRepositoryContentChange { impl fmt::Display for OldRepositoryContentChange { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{:?}", self) + write!(f, "{self:?}") } } diff --git a/src/server/scheduler.rs b/src/server/scheduler.rs index f76e5b72..cfb8a0ab 100644 --- a/src/server/scheduler.rs +++ b/src/server/scheduler.rs @@ -107,12 +107,12 @@ impl Scheduler { self.tasks.reschedule(&task_key, priority) } } { - error!("Error finishing / scheduling task {}. Krill will stop as there is no good way to recover from this. When Krill starts it will try to reschedule any missing tasks. Error was: {}", task_key, e); + error!("Error finishing / scheduling task {task_key}. Krill will stop as there is no good way to recover from this. When Krill starts it will try to reschedule any missing tasks. Error was: {e}"); std::process::exit(1); } } Err(e) => { - error!("Error processing task: {}. Tasks are only allowed to return fatal errors. Krill will stop as there is no good way to recover from this. When Krill starts it will try to reschedule any missing tasks. Error was: {}", task_key, e); + error!("Error processing task: {task_key}. Tasks are only allowed to return fatal errors. Krill will stop as there is no good way to recover from this. When Krill starts it will try to reschedule any missing tasks. Error was: {e}"); std::process::exit(1); } }, @@ -322,7 +322,7 @@ impl Scheduler { ca: CaHandle, version: u64, ) -> Result { - info!("Synchronize CA {} with repository", ca); + info!("Synchronize CA {ca} with repository"); match self .ca_manager @@ -333,8 +333,7 @@ impl Scheduler { let next = self.config.requeue_remote_failed(); error!( - "Failed to publish for '{}'. Will reschedule to: '{}'. Error: {}", - ca, next, e + "Failed to publish for '{ca}'. Will reschedule to: '{next}'. Error: {e}" ); Ok(TaskResult::Reschedule(next)) @@ -357,7 +356,7 @@ impl Scheduler { parent: ParentHandle, ) -> Result { if self.ca_manager.has_ca(&ca).map_err(FatalError)? { - info!("Synchronize CA '{}' with its parent '{}'", ca, parent); + info!("Synchronize CA '{ca}' with its parent '{parent}'"); match self .ca_manager .ca_sync_parent(&ca, ca_version, &parent, &self.system_actor) @@ -367,8 +366,7 @@ impl Scheduler { let next = self.config.requeue_remote_failed(); error!( - "Failed to synchronize CA '{}' with its parent '{}'. Will reschedule to: '{}'. Error: {}", - ca, parent, next, e + "Failed to synchronize CA '{ca}' with its parent '{parent}'. Will reschedule to: '{next}'. Error: {e}" ); Ok(TaskResult::Reschedule(next)) } @@ -394,8 +392,7 @@ impl Scheduler { // 6492 then we will also be able to alert // remote children. debug!( - "Skipping parent sync fo CA '{}'. It is either a remote child, or a local CA that has been removed", - ca + "Skipping parent sync fo CA '{ca}'. It is either a remote child, or a local CA that has been removed" ); Ok(TaskResult::Done) } @@ -404,7 +401,7 @@ impl Scheduler { /// Resync the testbed TA signer and proxy async fn renew_testbed_ta(&self) -> Result { if let Err(e) = self.ca_manager.ta_renew_testbed_ta() { - error!("There was an issue renewing the testbed TA: {}", e); + error!("There was an issue renewing the testbed TA: {e}"); } let weeks_to_resync = self.config.ta_timing.mft_next_update_weeks / 2; Ok(TaskResult::FollowUp( @@ -422,7 +419,7 @@ impl Scheduler { if let Err(e) = self.ca_manager.sync_ta_proxy_signer_if_possible() { - error!("There was an issue synchronising the TA Proxy and Signer: {}", e); + error!("There was an issue synchronising the TA Proxy and Signer: {e}"); } Ok(TaskResult::Done) } @@ -434,8 +431,7 @@ impl Scheduler { ) -> Result { if self.ca_manager.has_ca(&ca_handle).map_err(FatalError)? { debug!( - "Verify if CA '{}' has children that need to be suspended", - ca_handle + "Verify if CA '{ca_handle}' has children that need to be suspended" ); self.ca_manager.ca_suspend_inactive_children( &ca_handle, self.started, &self.system_actor, @@ -469,7 +465,7 @@ impl Scheduler { .map_err(FatalError)?; for ca_handle in cas { - info!("Re-issued MFT and CRL for CA: {}", ca_handle); + info!("Re-issued MFT and CRL for CA: {ca_handle}"); let ca_version = 0; // we use 0 because we don't need to wait for an updated CertAuth self.tasks @@ -520,8 +516,7 @@ impl Scheduler { // is broken and Krill would // have panicked as a result already. error!( - "Could not update snapshots for {} will try again in 24 hours. Error: {}", - namespace, e + "Could not update snapshots for {namespace} will try again in 24 hours. Error: {e}" ); } Ok(store) => { @@ -530,11 +525,10 @@ impl Scheduler { // else is broken and Krill // would have panicked as a result already. error!( - "Could not update snapshots for {} will try again in 24 hours. Error: {}", - namespace, e + "Could not update snapshots for {namespace} will try again in 24 hours. Error: {e}" ); } else { - info!("Updated snapshots for {}", namespace); + info!("Updated snapshots for {namespace}"); } } } @@ -550,8 +544,7 @@ impl Scheduler { // is broken and Krill would // have panicked as a result already. error!( - "Could not update snapshots for {} will try again in 24 hours. Error: {}", - namespace, e + "Could not update snapshots for {namespace} will try again in 24 hours. Error: {e}" ); } Ok(store) => { @@ -560,8 +553,7 @@ impl Scheduler { // else is broken and Krill // would have panicked as a result already. error!( - "Could not update snapshots for {} will try again in 24 hours. Error: {}", - namespace, e + "Could not update snapshots for {namespace} will try again in 24 hours. Error: {e}" ); } } @@ -596,7 +588,7 @@ impl Scheduler { fn update_rrdp_if_needed(&self) -> Result { match self.repo_manager.update_rrdp_if_needed() { Err(e) => { - error!("Could not update RRDP deltas! Error: {}", e); + error!("Could not update RRDP deltas! Error: {e}"); // Should we panic in this case? For now, just keep trying, // this may be an issue that gets resolved // (permission? disk space?) @@ -624,8 +616,7 @@ impl Scheduler { revocation_requests: Vec, ) -> Result { info!( - "Trigger send revoke requests for removed RC for '{}' under '{}'", - ca_handle, parent + "Trigger send revoke requests for removed RC for '{ca_handle}' under '{parent}'" ); let requests = HashMap::from([(rcn, revocation_requests)]); @@ -648,8 +639,7 @@ impl Scheduler { Ok(TaskResult::Done) } else { debug!( - "Revoked keys for CA '{}' under parent '{}'", - ca_handle, parent + "Revoked keys for CA '{ca_handle}' under parent '{parent}'" ); Ok(TaskResult::Done) } @@ -692,8 +682,7 @@ impl Scheduler { .await { warn!( - "Could not revoke surplus key, most likely already revoked by parent. Error was: {}", - e + "Could not revoke surplus key, most likely already revoked by parent. Error was: {e}" ); } diff --git a/src/server/taproxy.rs b/src/server/taproxy.rs index a39341d7..36003b51 100644 --- a/src/server/taproxy.rs +++ b/src/server/taproxy.rs @@ -486,8 +486,7 @@ impl TrustAnchorProxy { // This should not never happen. The command would not be sent, // but let's return some useful error anyway. Err(Error::Custom(format!( - "No response found for child {} and key {}", - child_handle, key + "No response found for child {child_handle} and key {key}" ))) } } @@ -621,8 +620,7 @@ impl TrustAnchorProxy { let received_cert = &signer.ta_cert_details.cert; let my_cert = received_cert.to_cert().map_err(|e| { Error::Custom(format!( - "Issue with certificate held by TA: {} ", - e + "Issue with certificate held by TA: {e} " )) })?; SigningCert::new(received_cert.uri.clone(), my_cert) @@ -643,8 +641,7 @@ impl TrustAnchorProxy { // This should never happen, unless our current issued // certificate can no longer be parsed Error::Custom(format!( - "Issue with issued certificate held by TA: {} ", - e + "Issue with issued certificate held by TA: {e} " )) }, )?); @@ -690,8 +687,7 @@ impl TrustAnchorProxy { Ok(Some(response)) } else { Err(Error::Custom(format!( - "Response for {} does not match request type.", - child_handle + "Response for {child_handle} does not match request type." ))) } } else { @@ -864,7 +860,7 @@ impl fmt::Display for TrustAnchorProxyEvent { ) } TrustAnchorProxyEvent::SignerRequestMade(nonce) => { - write!(f, "Created signer request with nonce '{}'", nonce) + write!(f, "Created signer request with nonce '{nonce}'") } TrustAnchorProxyEvent::SignerResponseReceived(response) => { write!( @@ -888,15 +884,13 @@ impl fmt::Display for TrustAnchorProxyEvent { ) => { write!( f, - "Added request for child {}: {}", - child_handle, request + "Added request for child {child_handle}: {request}" ) } TrustAnchorProxyEvent::ChildResponseGiven(child_handle, key) => { write!( f, - "Given response to child {} for key: {}", - child_handle, key + "Given response to child {child_handle} for key: {key}" ) } } @@ -1088,7 +1082,7 @@ impl fmt::Display for TrustAnchorProxyCommandDetails { // Children TrustAnchorProxyCommandDetails::AddChild(child) => { - write!(f, "Add child: {}", child) + write!(f, "Add child: {child}") } TrustAnchorProxyCommandDetails::AddChildRequest( child_handle, @@ -1096,8 +1090,7 @@ impl fmt::Display for TrustAnchorProxyCommandDetails { ) => { write!( f, - "Add request for child {}: {}", - child_handle, request + "Add request for child {child_handle}: {request}" ) } TrustAnchorProxyCommandDetails::GiveChildResponse( @@ -1106,8 +1099,7 @@ impl fmt::Display for TrustAnchorProxyCommandDetails { ) => { write!( f, - "Give (and remove) response to child {} for key {}", - child_handle, key + "Give (and remove) response to child {child_handle} for key {key}" ) } } diff --git a/src/tasigner/config.rs b/src/tasigner/config.rs index a83fbb83..ff9ba44c 100644 --- a/src/tasigner/config.rs +++ b/src/tasigner/config.rs @@ -144,15 +144,13 @@ impl Config { let mut file = File::open(file_path).map_err(|e| { ConfigError::Other(format!( - "Could not read config file '{}': {}", - file_path, e + "Could not read config file '{file_path}': {e}" )) })?; file.read_to_string(&mut v).map_err(|e| { ConfigError::Other(format!( - "Could not read config file '{}': {}", - file_path, e + "Could not read config file '{file_path}': {e}" )) })?; @@ -245,7 +243,7 @@ impl Config { .with_one_off_signer(self.one_off_signer()) .build() .map_err(|e| { - ConfigError::Other(format!("Could not create KrillSigner: {}", e)) + ConfigError::Other(format!("Could not create KrillSigner: {e}")) })?; Ok(Arc::new(signer)) @@ -288,7 +286,7 @@ impl Config { })?; self.fern_logger().chain(log_file).apply().map_err(|e| { - ConfigError::Other(format!("Failed to init file logging: {}", e)) + ConfigError::Other(format!("Failed to init file logging: {e}")) }) } @@ -296,8 +294,7 @@ impl Config { fn stderr_logger(&self) -> Result<(), ConfigError> { self.fern_logger().chain(io::stderr()).apply().map_err(|e| { ConfigError::Other(format!( - "Failed to init stderr logging: {}", - e + "Failed to init stderr logging: {e}" )) }) } diff --git a/src/tasigner/signer.rs b/src/tasigner/signer.rs index 150a3602..418dfb6a 100644 --- a/src/tasigner/signer.rs +++ b/src/tasigner/signer.rs @@ -399,8 +399,7 @@ impl TrustAnchorSigner { if rcn != ta_rcn { return Err(Error::Custom(format!( - "TA child request uses unknown resource class name '{}'", - rcn + "TA child request uses unknown resource class name '{rcn}'" ))); } @@ -454,8 +453,7 @@ impl TrustAnchorSigner { if rcn != ta_rcn { return Err(Error::Custom(format!( - "TA child request uses unknown resource class name '{}'", - rcn + "TA child request uses unknown resource class name '{rcn}'" ))); } @@ -472,8 +470,7 @@ impl TrustAnchorSigner { // investigated. if !objects.revoke_issued(&key) { return Err(Error::Custom(format!( - "TA child requests revocation for unknown key '{}'", - key + "TA child requests revocation for unknown key '{key}'" ))); } @@ -884,7 +881,7 @@ impl fmt::Display for TrustAnchorProxySignerExchanges { ProvisioningResponse::Revocation(_) => "revoked ", ProvisioningResponse::Error => "error ", }; - writeln!(f, " {} | {} | {}", res_type, key, child)?; + writeln!(f, " {res_type} | {key} | {child}")?; } } writeln!(f)?; diff --git a/src/upgrades/data_migration.rs b/src/upgrades/data_migration.rs index af23c1fb..eee0d99d 100644 --- a/src/upgrades/data_migration.rs +++ b/src/upgrades/data_migration.rs @@ -136,7 +136,7 @@ fn check_openssl_keys(config: &Config) -> UpgradeResult<()> { None, ) .map_err(|e| { - UpgradeError::Custom(format!("Cannot create openssl signer: {}", e)) + UpgradeError::Custom(format!("Cannot create openssl signer: {e}")) })?; let keys_key_store = KeyValueStore::create(&config.storage_uri, KEYS_NS)?; @@ -151,8 +151,7 @@ fn check_openssl_keys(config: &Config) -> UpgradeResult<()> { })?; open_ssl_signer.get_key_info(&key_id).map_err(|e| { UpgradeError::Custom(format!( - "Cannot get key with key_id {} from openssl keystore. Error: {}", - key_id, e + "Cannot get key with key_id {key_id} from openssl keystore. Error: {e}" )) })?; } @@ -213,8 +212,7 @@ fn copy_data_for_migration( ] { let namespace = Namespace::parse(ns).map_err(|_| { UpgradeError::Custom(format!( - "Cannot parse namespace '{}'. This is a bug.", - ns + "Cannot parse namespace '{ns}'. This is a bug." )) })?; let source_kv_store = @@ -241,7 +239,7 @@ pub mod tests { // Create a config file that uses test data for its storage_uri let test_sources_base = "test-resources/migrations/v0_9_5/"; let test_sources_url = - Url::parse(&format!("local://{}", test_sources_base)).unwrap(); + Url::parse(&format!("local://{test_sources_base}")).unwrap(); let bogus_path = PathBuf::from("/dev/null"); // needed for tls_dir etc, but will be ignored here let mut config = Config::test( diff --git a/src/upgrades/mod.rs b/src/upgrades/mod.rs index 3fe99b80..738fd94c 100644 --- a/src/upgrades/mod.rs +++ b/src/upgrades/mod.rs @@ -191,19 +191,19 @@ pub enum UpgradeError { impl fmt::Display for UpgradeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let cause = match &self { - UpgradeError::AggregateStoreError(e) => format!("Aggregate Error: {}", e), - UpgradeError::WalStoreError(e) => format!("Write-Ahead-Log Store Error: {}", e), - UpgradeError::KeyStoreError(e) => format!("Keystore Error: {}", e), - UpgradeError::IoError(e) => format!("I/O Error: {}", e), - UpgradeError::Unrecognised(s) => format!("Unrecognised: {}", s), - UpgradeError::CannotLoadAggregate(h) => format!("Cannot load: {}", h), - UpgradeError::IdExchange(s) => format!("Could not use exchanged id info: {}", s), + UpgradeError::AggregateStoreError(e) => format!("Aggregate Error: {e}"), + UpgradeError::WalStoreError(e) => format!("Write-Ahead-Log Store Error: {e}"), + UpgradeError::KeyStoreError(e) => format!("Keystore Error: {e}"), + UpgradeError::IoError(e) => format!("I/O Error: {e}"), + UpgradeError::Unrecognised(s) => format!("Unrecognised: {s}"), + UpgradeError::CannotLoadAggregate(h) => format!("Cannot load: {h}"), + UpgradeError::IdExchange(s) => format!("Could not use exchanged id info: {s}"), UpgradeError::OldTaMigration => "Your installation cannot be upgraded to Krill 0.13.0 or later because it includes a CA called \"ta\". These CAs were used for the preliminary Trust Anchor support needed by testbed and benchmark setups. They cannot be migrated to the production grade Trust Anchor support that was introduced in Krill 0.13.0. If you want to continue to use your existing installation we recommend that you downgrade to Krill 0.12.1 or earlier. If you want to operate a testbed using Krill 0.13.0 or later, then you can create a fresh testbed instead of migrating your existing testbed. If you believe that you should not have a CA called \"ta\" - i.e. it may have been left over from an abandoned testbed set up - then you can delete the \"ta\" directory under your krill data \"cas\" directory and restart Krill.".to_string(), UpgradeError::CodeOlderThanData(code, data) => format!("Krill version {code} is older than data version {data}. You either need to upgrade krill, or restore the data from version {code}."), UpgradeError::Custom(s) => s.clone(), }; - write!(f, "Upgrade preparation failed because of: {}", cause) + write!(f, "Upgrade preparation failed because of: {cause}") } } impl UpgradeError { @@ -392,7 +392,7 @@ pub trait UpgradeAggregateStorePre0_14 { // We only need top-level scopes, not sub-scopes such as 'surplus' // archive dirs if scope.len() != 1 { - trace!("Skipping migration for sub-scope: {}", scope); + trace!("Skipping migration for sub-scope: {scope}"); continue; } @@ -401,8 +401,7 @@ pub trait UpgradeAggregateStorePre0_14 { let handle = MyHandle::from_str(&scope.to_string()).map_err(|_| { UpgradeError::Custom(format!( - "Found invalid handle '{}'", - scope + "Found invalid handle '{scope}'" )) })?; @@ -476,7 +475,7 @@ pub trait UpgradeAggregateStorePre0_14 { // Process remaining commands for old_cmd_key in old_cmd_keys { // Read and parse the command. - trace!(" +- command: {}", old_cmd_key); + trace!(" +- command: {old_cmd_key}"); let old_command: OldStoredCommand = self.get(&old_cmd_key)?; @@ -488,14 +487,13 @@ pub trait UpgradeAggregateStorePre0_14 { for v in events { let event_key = Self::event_key(scope.clone(), *v); - trace!(" +- event: {}", event_key); + trace!(" +- event: {event_key}"); let evt: OldStoredEvent = self .deployed_store() .get(&event_key)? .ok_or_else(|| { UpgradeError::Custom(format!( - "Cannot parse old event: {}", - event_key + "Cannot parse old event: {event_key}" )) })?; full_events.push(evt.into_details()); @@ -575,7 +573,7 @@ pub trait UpgradeAggregateStorePre0_14 { } } - info!("Finished migrating commands for '{}'", scope); + info!("Finished migrating commands for '{scope}'"); // Verify migration info!( @@ -584,8 +582,7 @@ pub trait UpgradeAggregateStorePre0_14 { ); let _latest = self.preparation_aggregate_store().save_snapshot(&handle).map_err(|e| { UpgradeError::Custom(format!( - "Could not rebuild state after migrating CA '{}'! Error was: {}.", - handle, e + "Could not rebuild state after migrating CA '{handle}'! Error was: {e}." )) })?; @@ -598,7 +595,7 @@ pub trait UpgradeAggregateStorePre0_14 { // changes were applied. self.update_data_upgrade_info(&scope, &data_upgrade_info)?; - info!("Verified migration of '{}'", handle); + info!("Verified migration of '{handle}'"); } match mode { @@ -621,8 +618,7 @@ pub trait UpgradeAggregateStorePre0_14 { let ca = MyHandle::from_str(&scope.to_string()).map_err( |_| { UpgradeError::Custom(format!( - "Found invalid handle '{}'", - scope + "Found invalid handle '{scope}'" )) }, )?; @@ -694,13 +690,11 @@ pub trait UpgradeAggregateStorePre0_14 { if last_command == 0 { info!( - "Will migrate {} commands for '{}'", - total_remaining, handle + "Will migrate {total_remaining} commands for '{handle}'" ); } else { info!( - "Will resume migration of {} remaining commands for '{}'", - total_remaining, handle + "Will resume migration of {total_remaining} remaining commands for '{handle}'" ); } @@ -792,7 +786,7 @@ pub trait UpgradeAggregateStorePre0_14 { .map(|ck| { Key::new_scoped( scope.clone(), - Segment::parse_lossy(&format!("{}.json", ck)), + Segment::parse_lossy(&format!("{ck}.json")), ) }) // ck should always be a valid Segment .collect(); @@ -802,7 +796,7 @@ pub trait UpgradeAggregateStorePre0_14 { fn get(&self, key: &Key) -> Result { self.deployed_store().get(key)?.ok_or_else(|| { - UpgradeError::Custom(format!("Cannot read key: {}", key)) + UpgradeError::Custom(format!("Cannot read key: {key}")) }) } @@ -880,11 +874,11 @@ pub fn prepare_upgrade_data_migrations( if versions.from < KrillVersion::release(0, 6, 0) { let msg = "Cannot upgrade Krill installations from before version 0.6.0. Please upgrade to 0.8.1 first, then upgrade to 0.12.3, and then upgrade to this version."; - error!("{}", msg); + error!("{msg}"); Err(UpgradeError::custom(msg)) } else if versions.from < KrillVersion::release(0, 9, 0) { let msg = "Cannot upgrade Krill installations from before version 0.9.0. Please upgrade to 0.12.3 first, and then upgrade to this version."; - error!("{}", msg); + error!("{msg}"); Err(UpgradeError::custom(msg)) } else if versions.from < KrillVersion::candidate(0, 10, 0, 1) { // Complex migrations involving command / event conversions @@ -1027,7 +1021,7 @@ pub fn finalise_data_migration( let mut upgrade_store = KeyValueStore::create_upgrade_store(&config.storage_uri, ns)?; if !upgrade_store.is_empty()? { - info!("Migrate new data for {} and archive old", ns); + info!("Migrate new data for {ns} and archive old"); let mut current_store = KeyValueStore::create(&config.storage_uri, ns)?; if !current_store.is_empty()? { @@ -1045,7 +1039,7 @@ pub fn finalise_data_migration( const { Segment::make("version") }); if current_store.has(&version_key)? { - debug!("Removing excess version key in ns: {}", ns); + debug!("Removing excess version key in ns: {ns}"); current_store.drop_key(&version_key)?; } } @@ -1110,7 +1104,7 @@ fn record_preexisting_openssl_keys_in_signer_mapper( let mut openssl_signer_handle: Option = None; for key in keys_key_store.keys(&Scope::global(), "")? { - debug!("Found key: {}", key); + debug!("Found key: {key}"); // Is it a key identifier? if let Ok(key_id) = KeyIdentifier::from_str(key.name().as_str()) { // Is the key already recorded in the mapper? It shouldn't be, @@ -1158,13 +1152,12 @@ fn record_preexisting_openssl_keys_in_signer_mapper( } } } else { - debug!("Could not parse key as key identifier: {}", key); + debug!("Could not parse key as key identifier: {key}"); } } info!( - "Recorded {} key identifiers in the signer store", - num_recorded_keys + "Recorded {num_recorded_keys} key identifiers in the signer store" ); Ok(()) } else { diff --git a/tests/benchmark.rs b/tests/benchmark.rs index 4ef8e6ca..6019934d 100644 --- a/tests/benchmark.rs +++ b/tests/benchmark.rs @@ -57,8 +57,7 @@ async fn wait_for_nr_cas_under_publication_server( } panic!( - "Expected {} publishers, but found {}", - publishers_expected, publishers_found + "Expected {publishers_expected} publishers, but found {publishers_found}" ); } diff --git a/tests/common.rs b/tests/common.rs index c301721b..dda1af5c 100644 --- a/tests/common.rs +++ b/tests/common.rs @@ -229,10 +229,10 @@ impl TestConfig { Some(TestBed::new( uri::Rsync::from_str("rsync://localhost/ta/ta.cer").unwrap(), uri::Https::from_string( - format!("https://localhost:{}/ta/ta.cer", port) + format!("https://localhost:{port}/ta/ta.cer") ).unwrap(), uri::Https::from_string( - format!("https://localhost:{}/rrdp/", port) + format!("https://localhost:{port}/rrdp/") ).unwrap(), uri::Rsync::from_str("rsync://localhost/repo/").unwrap(), )) @@ -397,7 +397,7 @@ impl KrillServer { if let Err(err) = start_krill_daemon( config.into(), Some(tx) ).await { - error!("Krill failed to start: {}", err); + error!("Krill failed to start: {err}"); } }), running: Some(running), @@ -418,14 +418,14 @@ impl KrillServer { self.client.authorized(), ).await { Ok(Ok(_)) => { debug!("health check succeded") }, - err => panic!("health check failed: {:?}", err), + err => panic!("health check failed: {err:?}"), } } pub async fn pubserver_init(&self, port: u16) { self.client().pubserver_init( uri::Https::from_str( - &format!("https://localhost:{}/test-rrdp/", port) + &format!("https://localhost:{port}/test-rrdp/") ).unwrap(), uri::Rsync::from_str( "rsync://localhost/dedicated-repo/" @@ -733,7 +733,7 @@ impl<'a> ExpectedObjects<'a> { } eprintln!("Expected:"); for file in &self.files { - eprintln!(" {}", file); + eprintln!(" {file}"); } false diff --git a/tests/functional_keyroll.rs b/tests/functional_keyroll.rs index 0290c882..53a5a18e 100644 --- a/tests/functional_keyroll.rs +++ b/tests/functional_keyroll.rs @@ -194,7 +194,7 @@ impl common::KrillServer { common::sleep_millis(500).await; } - eprintln!("Expected serial: {}, found: {}", nr, number_found); + eprintln!("Expected serial: {nr}, found: {number_found}"); false } } diff --git a/tests/functional_old_data.rs b/tests/functional_old_data.rs index 8fd6256d..d38f444d 100644 --- a/tests/functional_old_data.rs +++ b/tests/functional_old_data.rs @@ -25,14 +25,14 @@ async fn functional_old_data() { let (mut config, tempdir) = common::TestConfig::file_storage() .enable_second_signer().finalize(); - fs::create_dir(&tempdir.path().join("ta")).unwrap(); + fs::create_dir(tempdir.path().join("ta")).unwrap(); untar_file( "test-resources/migrations/v0_14_5.tar", - &tempdir.path().join("data") + tempdir.path().join("data") ); untar_file( "test-resources/migrations/v0_14_5_signer.tar", - &tempdir.path().join("ta") + tempdir.path().join("ta") ); config.ta_support_enabled = true; @@ -42,7 +42,7 @@ async fn functional_old_data() { let signer_config = include_str!("../test-resources/migrations/v0_14_5_signer/ta.conf"); let signer_config = signer_config.replace("%TEMPDIR%", - &tempdir.path().join("ta").to_str().unwrap()); + tempdir.path().join("ta").to_str().unwrap()); eprintln!(">>>> Configure the TA signer."); let signer = TrustAnchorSignerManager::create( diff --git a/tests/functional_ta.rs b/tests/functional_ta.rs index b1f39023..04e22368 100644 --- a/tests/functional_ta.rs +++ b/tests/functional_ta.rs @@ -60,7 +60,7 @@ async fn functional_ta() { }, tal_https: vec![ uri::Https::from_string( - format!("https://localhost:{}/ta/ta.cer", port) + format!("https://localhost:{port}/ta/ta.cer") ).unwrap() ], tal_rsync: uri::Rsync::from_str( @@ -124,7 +124,7 @@ async fn functional_ta() { }, tal_https: vec![ uri::Https::from_string( - format!("https://localhost:{}/ta/ta.cer", port) + format!("https://localhost:{port}/ta/ta.cer") ).unwrap() ], tal_rsync: uri::Rsync::from_str(