Skip to content

Commit

Permalink
refactor: adjust let's encrypt renew
Browse files Browse the repository at this point in the history
  • Loading branch information
vicanso committed Dec 3, 2024
1 parent 227dd3a commit f596461
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 36 deletions.
24 changes: 6 additions & 18 deletions src/acme/lets_encrypt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use super::{get_certificate_info, Certificate, Error, Result};
use super::{Certificate, Error, Result};
use crate::config::get_current_config;
use crate::http_extra::HttpResponse;
use crate::proxy::init_certificates;
Expand Down Expand Up @@ -50,7 +50,7 @@ struct LetsEncryptService {
domains: Vec<String>,
}

static WELL_KNOWN_PAHT_PREFIX: &str = "/.well-known/acme-challenge/";
static WELL_KNOWN_PATH_PREFIX: &str = "/.well-known/acme-challenge/";

/// Create a Let's Encrypt service to generate the certificate,
/// and regenerate if the certificate is invalid or will be expired.
Expand All @@ -63,7 +63,7 @@ pub fn new_lets_encrypt_service(
domains.sort();

CommonServiceTask::new(
Duration::from_secs(30 * 60),
Duration::from_secs(10 * 60),
LetsEncryptService {
certificate_file,
domains,
Expand Down Expand Up @@ -101,7 +101,7 @@ impl ServiceTask for LetsEncryptService {
Err(e) => error!(
error = e.to_string(),
domains = domains.join(","),
"renew certificate fail"
"renew certificate fail, renew it again later"
),
};
None
Expand Down Expand Up @@ -137,7 +137,7 @@ pub async fn handle_lets_encrypt(
) -> pingora::Result<bool> {
let path = session.req_header().uri.path();
// lets encrypt acme challenge path
if path.starts_with(WELL_KNOWN_PAHT_PREFIX) {
if path.starts_with(WELL_KNOWN_PATH_PREFIX) {
let value = {
// token auth
let data = get_lets_encrypt_challenge().lock().await;
Expand Down Expand Up @@ -242,7 +242,7 @@ async fn new_lets_encrypt(

// http://your-domain/.well-known/acme-challenge/<TOKEN>
let well_known_path =
format!("{WELL_KNOWN_PAHT_PREFIX}{}", challenge.token);
format!("{WELL_KNOWN_PATH_PREFIX}{}", challenge.token);
info!(well_known_path, "let's encrypt well known path",);

// save token for verification later
Expand Down Expand Up @@ -343,16 +343,6 @@ async fn new_lets_encrypt(
}
};

// get certificate validity
let mut not_before = params.not_before.unix_timestamp();
let now = util::now().as_secs() as i64;
// default expired time set 90 days
let mut not_after = now + 90 * 24 * 3600;
if let Ok(info) = get_certificate_info(cert_chain_pem.as_bytes()) {
not_before = info.not_before;
not_after = info.not_after;
}

// save certificate as json file
let mut f = fs::OpenOptions::new()
.create(true)
Expand All @@ -366,8 +356,6 @@ async fn new_lets_encrypt(
})?;
let info = Certificate {
domains: domains.to_vec(),
not_after,
not_before,
pem: util::base64_encode(&cert_chain_pem),
key: util::base64_encode(private_key.serialize_pem()),
};
Expand Down
22 changes: 5 additions & 17 deletions src/acme/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,19 +92,18 @@ pub fn get_certificate_info(data: &[u8]) -> Result<CertificateInfo> {
#[derive(Debug, Deserialize, Serialize, Default)]
pub struct Certificate {
pub domains: Vec<String>,
pub not_after: i64,
pub not_before: i64,
pub pem: String,
pub key: String,
}
impl Certificate {
/// Validate the cert is within the expiration date.
pub fn valid(&self) -> bool {
let ts = util::now().as_secs() as i64;
if self.not_before > ts {
return false;
if let Ok(info) = get_certificate_info(&self.get_cert()) {
info.not_after - ts > 2 * 24 * 3600
} else {
false
}
self.not_after - ts > 2 * 24 * 3600
}
/// Get the cert pem data.
pub fn get_cert(&self) -> Vec<u8> {
Expand All @@ -128,25 +127,14 @@ pub use validity_checker::new_tls_validity_service;
mod tests {
use super::{get_certificate_info, Certificate};
use pretty_assertions::assert_eq;
use std::time::{SystemTime, UNIX_EPOCH};

#[test]
fn test_cert() {
let ts = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64;
let mut cert = Certificate {
not_before: ts - 10,
not_after: ts + 3 * 24 * 3600,
let cert = Certificate {
pem: "cGluZ2Fw".to_string(),
key: "cGluZ2FwLWtleQ==".to_string(),
..Default::default()
};
assert_eq!(true, cert.valid());

cert.not_after = ts;
assert_eq!(false, cert.valid());

assert_eq!(b"pingap".to_vec(), cert.get_cert());
assert_eq!(b"pingap-key".to_vec(), cert.get_key());
Expand Down
2 changes: 1 addition & 1 deletion src/discovery/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use std::collections::BTreeSet;
use std::net::ToSocketAddrs;

pub fn is_static_discovery(value: &str) -> bool {
value.is_empty() || value == "static"
value.is_empty() || value == "common"
}

/// Create a static discovery, execute it only once.
Expand Down

0 comments on commit f596461

Please sign in to comment.