aboutsummaryrefslogtreecommitdiff
path: root/src/cert.rs
blob: 12b92183cb5338231b726b6bd9e721cc02fa3de9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use std::sync::Arc;

use anyhow::Result;

use chrono::{Date, NaiveDate, Utc};
use rustls::sign::CertifiedKey;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CertSer {
	pub hostname: String,
	pub date: NaiveDate,
	pub valid_days: i64,

	pub key_pem: String,
	pub cert_pem: String,
}

pub struct Cert {
	pub ser: CertSer,

	pub certkey: Arc<CertifiedKey>,
}

impl Cert {
	pub fn new(ser: CertSer) -> Result<Self> {
		let pem_certs = rustls_pemfile::read_all(&mut ser.cert_pem.as_bytes())?;
		let certs = pem_certs
			.into_iter()
			.filter_map(|cert| match cert {
				rustls_pemfile::Item::X509Certificate(cert) => Some(rustls::Certificate(cert)),
				_ => None,
			})
			.collect::<Vec<_>>();

		let pem_keys = rustls_pemfile::read_all(&mut ser.key_pem.as_bytes())?;
		let keys = pem_keys
			.into_iter()
			.filter_map(|key| match key {
				rustls_pemfile::Item::RSAKey(bytes) | rustls_pemfile::Item::PKCS8Key(bytes) => {
					Some(rustls::sign::any_supported_type(&rustls::PrivateKey(bytes)).ok()?)
				}
				_ => None,
			})
			.collect::<Vec<_>>();

		if keys.len() != 1 {
			bail!("{} keys present in pem file", keys.len());
		}

		let certkey = Arc::new(CertifiedKey::new(certs, keys.into_iter().next().unwrap()));

		Ok(Cert { ser, certkey })
	}

	pub fn is_old(&self) -> bool {
		let date = Date::<Utc>::from_utc(self.ser.date, Utc);
		let today = Utc::today();
		today - date > chrono::Duration::days(self.ser.valid_days / 2)
	}
}