Skip to content

Commit

Permalink
refactor: adjust certificate
Browse files Browse the repository at this point in the history
  • Loading branch information
vicanso committed Jan 21, 2025
1 parent df4f6d1 commit 2092c0c
Show file tree
Hide file tree
Showing 7 changed files with 23 additions and 24 deletions.
8 changes: 4 additions & 4 deletions src/acme/lets_encrypt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ async fn update_certificate_lets_encrypt(
/// The check runs every UPDATE_INTERVAL iterations to avoid excessive checks.
async fn do_update_certificates(
count: u32,
params: Vec<(String, Vec<String>)>,
params: &[(String, Vec<String>)],
) -> Result<bool, ServiceError> {
const UPDATE_INTERVAL: u32 = 10;
if count % UPDATE_INTERVAL != 0 {
Expand Down Expand Up @@ -177,7 +177,7 @@ pub fn new_lets_encrypt_service(
let value = params.clone();
async move {
let value = value.clone();
do_update_certificates(count, value).await
do_update_certificates(count, &value).await
}
})
});
Expand All @@ -193,8 +193,8 @@ pub fn get_lets_encrypt_certificate(name: &str) -> Result<Certificate> {
});
};
Certificate::new(
cert.tls_cert.clone().unwrap_or_default(),
cert.tls_key.clone().unwrap_or_default(),
cert.tls_cert.clone().unwrap_or_default().as_str(),
cert.tls_key.clone().unwrap_or_default().as_str(),
)
.map_err(|e| Error::Fail {
category: "new_certificate".to_string(),
Expand Down
2 changes: 1 addition & 1 deletion src/acme/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ Ztdj1N0eTfn02pibVcXXfwESPUzcjERaMAGg1hoH1F4Gxg0mqmbySAuVRqNLnXp5
CRVQZGgOQL6WDg3tUUDXYOs=
-----END CERTIFICATE-----"###;
// spellchecker:on
let cert = Certificate::new(pem.to_string(), "".to_string()).unwrap();
let cert = Certificate::new(pem, "").unwrap();

assert_eq!(
"O=mkcert development CA, OU=vicanso@tree, CN=mkcert vicanso@tree",
Expand Down
2 changes: 1 addition & 1 deletion src/certificate/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ fn parse_chain_certificate(data: &[u8]) -> Option<X509> {

String::from_utf8(data.to_vec())
.ok()
.and_then(|pem_str| Certificate::new(pem_str, String::new()).ok())
.and_then(|pem_str| Certificate::new(&pem_str, "").ok())
.filter(|cert| cert.not_after > expiration_threshold as i64)
.and_then(|_| X509::from_pem(data).ok())
}
Expand Down
7 changes: 3 additions & 4 deletions src/certificate/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,9 @@ impl Certificate {
///
/// # Returns
/// * `Result<Certificate>` - The parsed certificate or an error if invalid
pub fn new(pem: String, key: String) -> Result<Certificate> {
pub fn new(pem: &str, key: &str) -> Result<Certificate> {
let pem_data =
util::convert_certificate_bytes(&Some(pem)).ok_or_else(|| {
util::convert_certificate_bytes(Some(pem)).ok_or_else(|| {
Error::Invalid {
category: "certificate".to_string(),
message: "invalid pem data".to_string(),
Expand Down Expand Up @@ -126,8 +126,7 @@ impl Certificate {
Ok(Self {
domains: dns_names,
pem: pem_data,
key: util::convert_certificate_bytes(&Some(key))
.unwrap_or_default(),
key: util::convert_certificate_bytes(Some(key)).unwrap_or_default(),
not_after: validity.not_after.timestamp(),
not_before: validity.not_before.timestamp(),
issuer: x509.issuer.to_string(),
Expand Down
5 changes: 3 additions & 2 deletions src/certificate/self_signed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ async fn do_self_signed_certificate_validity(
let stale = v.stale.load(Ordering::Relaxed);

if count == 0 {
// certificate is not used and stale, remove it
if stale {
return None;
}
Expand Down Expand Up @@ -151,7 +152,7 @@ pub fn get_self_signed_certificate(
/// This function creates a new certificate entry with initial usage counters
/// and adds it to the global certificate map.
pub fn add_self_signed_certificate(
name: &str,
name: String,
x509: X509,
key: PKey<Private>,
not_after: i64,
Expand All @@ -164,7 +165,7 @@ pub fn add_self_signed_certificate(
stale: AtomicBool::new(false),
count: AtomicU32::new(0),
});
m.insert(name.to_string(), v.clone());
m.insert(name, v.clone());
SELF_SIGNED_CERTIFICATE_MAP.store(Arc::new(m));
v
}
11 changes: 5 additions & 6 deletions src/certificate/tls_certificate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ impl TryFrom<&CertificateConf> for TlsCertificate {
fn try_from(value: &CertificateConf) -> Result<Self, Self::Error> {
// parse certificate
let info = Certificate::new(
value.tls_cert.clone().unwrap_or_default(),
value.tls_key.clone().unwrap_or_default(),
value.tls_cert.clone().unwrap_or_default().as_str(),
value.tls_key.clone().unwrap_or_default().as_str(),
)
.map_err(|e| Error::Invalid {
message: e.to_string(),
Expand All @@ -70,7 +70,8 @@ impl TryFrom<&CertificateConf> for TlsCertificate {
};
let hash_key = value.hash_key();

let tls_chain = util::convert_certificate_bytes(&value.tls_chain);
let tls_chain =
util::convert_certificate_bytes(value.tls_chain.as_deref());
let chain_certificate = if let Some(value) = &tls_chain {
// ignore chain error
X509::from_pem(value)
Expand Down Expand Up @@ -239,9 +240,7 @@ impl TlsCertificate {
// Generate new certificate if not found in cache
let (cert, key, not_after) = new_certificate_with_ca(self, &cn)?;
info!(common_name = cn, "Created new self-signed certificate");
Ok(add_self_signed_certificate(
&cache_key, cert, key, not_after,
))
Ok(add_self_signed_certificate(cache_key, cert, key, not_after))
}

/// Formats a server name into a common name by converting subdomain patterns
Expand Down
12 changes: 6 additions & 6 deletions src/util/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ pub fn convert_pem(value: &str) -> Result<Vec<u8>> {
Ok(buf)
}

pub fn convert_certificate_bytes(value: &Option<String>) -> Option<Vec<u8>> {
pub fn convert_certificate_bytes(value: Option<&str>) -> Option<Vec<u8>> {
if let Some(value) = value {
return convert_pem(value).ok();
}
Expand Down Expand Up @@ -722,21 +722,21 @@ Ztdj1N0eTfn02pibVcXXfwESPUzcjERaMAGg1hoH1F4Gxg0mqmbySAuVRqNLnXp5
CRVQZGgOQL6WDg3tUUDXYOs=
-----END CERTIFICATE-----"###;
// spellchecker:on
let result = convert_certificate_bytes(&Some(pem.to_string()));
let result = convert_certificate_bytes(Some(pem));
assert_eq!(true, result.is_some());

let mut tmp = NamedTempFile::new().unwrap();

tmp.write_all(pem.as_bytes()).unwrap();

let result = convert_certificate_bytes(&Some(
tmp.path().to_string_lossy().to_string(),
));
let result = convert_certificate_bytes(
Some(tmp.path().to_string_lossy()).as_deref(),
);
assert_eq!(true, result.is_some());

let data = base64_encode(pem.as_bytes());
assert_eq!(1924, data.len());
let result = convert_certificate_bytes(&Some(data));
let result = convert_certificate_bytes(Some(data).as_deref());
assert_eq!(true, result.is_some());
}
}

0 comments on commit 2092c0c

Please sign in to comment.