Compare commits

..

No commits in common. "28104f36e1582812436971367d54219d67e0069e" and "af1dc183ece7d69d0642a0320731858c67de4c6e" have entirely different histories.

6 changed files with 121 additions and 91 deletions

View File

@ -2,19 +2,11 @@ use std::{sync, time};
use crate::domain::acme::{self, Certificate, PrivateKey}; use crate::domain::acme::{self, Certificate, PrivateKey};
use crate::error::unexpected::{self, Intoable, Mappable}; use crate::error::unexpected::{self, Intoable, Mappable};
use crate::{domain, token, util}; use crate::{domain, util};
const LETS_ENCRYPT_URL: &str = "https://acme-v02.api.letsencrypt.org/directory"; const LETS_ENCRYPT_URL: &str = "https://acme-v02.api.letsencrypt.org/directory";
#[derive(thiserror::Error, Debug)] pub type GetHttp01ChallengeKeyError = acme::store::GetHttp01ChallengeKeyError;
pub enum GetHttp01ChallengeKeyError {
#[error("not found")]
NotFound,
#[error(transparent)]
Unexpected(#[from] unexpected::Error),
}
pub type GetCertificateError = acme::store::GetCertificateError; pub type GetCertificateError = acme::store::GetCertificateError;
#[mockall::automock] #[mockall::automock]
@ -35,20 +27,14 @@ pub trait Manager {
pub struct ManagerImpl { pub struct ManagerImpl {
store: Box<dyn acme::store::Store + Send + Sync>, store: Box<dyn acme::store::Store + Send + Sync>,
token_store: Box<dyn token::Store + Send + Sync>,
account: sync::Arc<acme2::Account>, account: sync::Arc<acme2::Account>,
} }
impl ManagerImpl { impl ManagerImpl {
pub async fn new<AcmeStore, TokenStore>( pub async fn new<Store: acme::store::Store + Send + Sync + 'static>(
store: AcmeStore, store: Store,
token_store: TokenStore,
config: &domain::ConfigACME, config: &domain::ConfigACME,
) -> Result<Self, unexpected::Error> ) -> Result<Self, unexpected::Error> {
where
AcmeStore: acme::store::Store + Send + Sync + 'static,
TokenStore: token::Store + Send + Sync + 'static,
{
let dir = acme2::DirectoryBuilder::new(LETS_ENCRYPT_URL.to_string()) let dir = acme2::DirectoryBuilder::new(LETS_ENCRYPT_URL.to_string())
.build() .build()
.await .await
@ -92,7 +78,6 @@ impl ManagerImpl {
Ok(Self { Ok(Self {
store: Box::from(store), store: Box::from(store),
token_store: Box::from(token_store),
account, account,
}) })
} }
@ -155,8 +140,8 @@ impl Manager for ManagerImpl {
.or_unexpected_while("getting challenge key from authorization")? .or_unexpected_while("getting challenge key from authorization")?
.ok_or(unexpected::Error::from("expected challenge to have key"))?; .ok_or(unexpected::Error::from("expected challenge to have key"))?;
self.token_store self.store
.set(challenge_token.clone(), challenge_key) .set_http01_challenge_key(challenge_token, &challenge_key)
.or_unexpected_while("storing challenge token")?; .or_unexpected_while("storing challenge token")?;
// At this point the manager is prepared to serve the challenge key via the // At this point the manager is prepared to serve the challenge key via the
@ -180,8 +165,8 @@ impl Manager for ManagerImpl {
let challenge_res = challenge.wait_done(time::Duration::from_secs(5), 3).await; let challenge_res = challenge.wait_done(time::Duration::from_secs(5), 3).await;
// no matter what the result is, clean up the challenge key // no matter what the result is, clean up the challenge key
self.token_store self.store
.del(challenge_token) .del_http01_challenge_key(challenge_token)
.or_unexpected_while("deleting challenge token")?; .or_unexpected_while("deleting challenge token")?;
let challenge = challenge_res.or_unexpected_while("getting challenge status")?; let challenge = challenge_res.or_unexpected_while("getting challenge status")?;
@ -311,11 +296,7 @@ impl Manager for ManagerImpl {
} }
fn get_http01_challenge_key(&self, token: &str) -> Result<String, GetHttp01ChallengeKeyError> { fn get_http01_challenge_key(&self, token: &str) -> Result<String, GetHttp01ChallengeKeyError> {
match self.token_store.get(token) { self.store.get_http01_challenge_key(token)
Ok(Some(v)) => Ok(v),
Ok(None) => Err(GetHttp01ChallengeKeyError::NotFound),
Err(e) => Err(e.into()),
}
} }
/// Returned vec is guaranteed to have len > 0 /// Returned vec is guaranteed to have len > 0

View File

@ -6,7 +6,9 @@ use crate::domain::acme::{Certificate, PrivateKey};
use crate::error::unexpected::{self, Mappable}; use crate::error::unexpected::{self, Mappable};
use crate::util; use crate::util;
use hex::ToHex;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
#[derive(thiserror::Error, Debug)] #[derive(thiserror::Error, Debug)]
pub enum GetAccountKeyError { pub enum GetAccountKeyError {
@ -17,6 +19,15 @@ pub enum GetAccountKeyError {
Unexpected(#[from] unexpected::Error), Unexpected(#[from] unexpected::Error),
} }
#[derive(thiserror::Error, Debug)]
pub enum GetHttp01ChallengeKeyError {
#[error("not found")]
NotFound,
#[error(transparent)]
Unexpected(#[from] unexpected::Error),
}
#[derive(thiserror::Error, Debug)] #[derive(thiserror::Error, Debug)]
pub enum GetCertificateError { pub enum GetCertificateError {
#[error("not found")] #[error("not found")]
@ -31,6 +42,10 @@ pub trait Store {
fn set_account_key(&self, k: &PrivateKey) -> Result<(), unexpected::Error>; fn set_account_key(&self, k: &PrivateKey) -> Result<(), unexpected::Error>;
fn get_account_key(&self) -> Result<PrivateKey, GetAccountKeyError>; fn get_account_key(&self) -> Result<PrivateKey, GetAccountKeyError>;
fn set_http01_challenge_key(&self, token: &str, key: &str) -> Result<(), unexpected::Error>;
fn get_http01_challenge_key(&self, token: &str) -> Result<String, GetHttp01ChallengeKeyError>;
fn del_http01_challenge_key(&self, token: &str) -> Result<(), unexpected::Error>;
fn set_certificate( fn set_certificate(
&self, &self,
domain: &str, domain: &str,
@ -78,6 +93,16 @@ impl FSStore {
self.dir_path.join("account.key") self.dir_path.join("account.key")
} }
fn http01_challenge_key_path(&self, token: &str) -> path::PathBuf {
// hash it for safety
let mut h = Sha256::new();
h.write_all(token.as_bytes())
.expect("token successfully hashed");
let n = h.finalize().encode_hex::<String>();
self.dir_path.join("http01_challenge_keys").join(n)
}
fn certificate_path(&self, domain: &str) -> path::PathBuf { fn certificate_path(&self, domain: &str) -> path::PathBuf {
let mut domain = domain.to_string(); let mut domain = domain.to_string();
domain.push_str(".json"); domain.push_str(".json");
@ -119,6 +144,42 @@ impl Store for FSStore {
.map_err(|err| err.into()) .map_err(|err| err.into())
} }
fn set_http01_challenge_key(&self, token: &str, key: &str) -> Result<(), unexpected::Error> {
let path = self.http01_challenge_key_path(token);
{
let mut file = fs::File::create(path.as_path()).or_unexpected_while("creating file")?;
file.write_all(key.as_bytes())
.or_unexpected_while("writing file")
}
.map_unexpected_while(|| format!("path is {}", path.display()))?;
Ok(())
}
fn get_http01_challenge_key(&self, token: &str) -> Result<String, GetHttp01ChallengeKeyError> {
let path = self.http01_challenge_key_path(token);
{
let mut file =
match util::open_file(path.as_path()).or_unexpected_while("opening_file")? {
Some(file) => file,
None => return Err(GetHttp01ChallengeKeyError::NotFound),
};
let mut key = String::new();
file.read_to_string(&mut key)
.or_unexpected_while("reading file")?;
Ok::<String, unexpected::Error>(key)
}
.map_unexpected_while(|| format!("path is {}", path.display()))
.map_err(|err| err.into())
}
fn del_http01_challenge_key(&self, token: &str) -> Result<(), unexpected::Error> {
let path = self.http01_challenge_key_path(token);
fs::remove_file(path.as_path())
.map_unexpected_while(|| format!("path is {}", path.display()))
}
fn set_certificate( fn set_certificate(
&self, &self,
domain: &str, domain: &str,
@ -190,4 +251,38 @@ mod tests {
.expect("account private key retrieved") .expect("account private key retrieved")
); );
} }
#[test]
fn http01_challenge_key() {
let tmp_dir = TempDir::new("domain_acme_store_http01_challenge_key").unwrap();
let store = FSStore::new(tmp_dir.path()).expect("store created");
let token = "foo".to_string();
let key = "bar".to_string();
assert!(matches!(
store.get_http01_challenge_key(&token),
Err::<String, GetHttp01ChallengeKeyError>(GetHttp01ChallengeKeyError::NotFound)
));
store
.set_http01_challenge_key(&token, &key)
.expect("http01 challenge set");
assert_eq!(
key,
store
.get_http01_challenge_key(&token)
.expect("retrieved http01 challenge"),
);
store
.del_http01_challenge_key(&token)
.expect("deleted http01 challenge");
assert!(matches!(
store.get_http01_challenge_key(&token),
Err::<String, GetHttp01ChallengeKeyError>(GetHttp01ChallengeKeyError::NotFound)
));
}
} }

View File

@ -1,5 +1,5 @@
use std::fmt::Write; use std::fmt::Write;
use std::{error, fmt, result}; use std::{error, fmt};
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
/// Error is a String which implements the Error trait. It is intended to be used in /// Error is a String which implements the Error trait. It is intended to be used in
@ -10,8 +10,6 @@ use std::{error, fmt, result};
/// async situations. /// async situations.
pub struct Error(String); pub struct Error(String);
pub type Result<T> = result::Result<T, Error>;
impl Error { impl Error {
fn from_displays<D1, D2, D3>(prefix: Option<D1>, body: &D2, source: Option<D3>) -> Error fn from_displays<D1, D2, D3>(prefix: Option<D1>, body: &D2, source: Option<D3>) -> Error
where where
@ -57,24 +55,24 @@ impl error::Error for Error {}
pub trait Mappable<T> { pub trait Mappable<T> {
/// or_unexpected returns an Err(Error) wrapping self's Err, or the Ok value of self. /// or_unexpected returns an Err(Error) wrapping self's Err, or the Ok value of self.
fn or_unexpected(self) -> Result<T>; fn or_unexpected(self) -> Result<T, Error>;
/// or_unexpected_while is like or_unexpected, but will prefix the error message. The prefix /// or_unexpected_while is like or_unexpected, but will prefix the error message. The prefix
/// should be worded as if it started with the word "while", e.g.: `opening file {path}`. /// should be worded as if it started with the word "while", e.g.: `opening file {path}`.
fn or_unexpected_while<D: fmt::Display>(self, prefix: D) -> Result<T>; fn or_unexpected_while<D: fmt::Display>(self, prefix: D) -> Result<T, Error>;
/// map_unexpected_while is like or_unexpected_while, but uses a closure to produce the error /// map_unexpected_while is like or_unexpected_while, but uses a closure to produce the error
/// prefix. /// prefix.
fn map_unexpected_while<F, D>(self, f: F) -> Result<T> fn map_unexpected_while<F, D>(self, f: F) -> Result<T, Error>
where where
F: FnOnce() -> D, F: FnOnce() -> D,
D: fmt::Display; D: fmt::Display;
} }
fn map_unexpected_maybe_while<T, E, F, D>( fn map_unexpected_maybe_while<T, E, F, D>(
res: result::Result<T, E>, res: Result<T, E>,
prefix_fn: Option<F>, prefix_fn: Option<F>,
) -> Result<T> ) -> Result<T, Error>
where where
E: error::Error, E: error::Error,
F: FnOnce() -> D, F: FnOnce() -> D,
@ -86,17 +84,17 @@ where
} }
} }
impl<T, E: error::Error> Mappable<T> for result::Result<T, E> { impl<T, E: error::Error> Mappable<T> for Result<T, E> {
fn or_unexpected(self) -> Result<T> { fn or_unexpected(self) -> Result<T, Error> {
let no_fn = None::<Box<dyn FnOnce() -> Box<dyn fmt::Display>>>; // lol, good job rust let no_fn = None::<Box<dyn FnOnce() -> Box<dyn fmt::Display>>>; // lol, good job rust
map_unexpected_maybe_while(self, no_fn) map_unexpected_maybe_while(self, no_fn)
} }
fn or_unexpected_while<D: fmt::Display>(self, prefix: D) -> Result<T> { fn or_unexpected_while<D: fmt::Display>(self, prefix: D) -> Result<T, Error> {
map_unexpected_maybe_while(self, Some(|| prefix)) map_unexpected_maybe_while(self, Some(|| prefix))
} }
fn map_unexpected_while<F, D>(self, f: F) -> Result<T> fn map_unexpected_while<F, D>(self, f: F) -> Result<T, Error>
where where
F: FnOnce() -> D, F: FnOnce() -> D,
D: fmt::Display, D: fmt::Display,
@ -108,16 +106,16 @@ impl<T, E: error::Error> Mappable<T> for result::Result<T, E> {
static OPTION_NONE_ERROR: &str = "expected Some but got None"; static OPTION_NONE_ERROR: &str = "expected Some but got None";
impl<T> Mappable<T> for Option<T> { impl<T> Mappable<T> for Option<T> {
fn or_unexpected(self) -> Result<T> { fn or_unexpected(self) -> Result<T, Error> {
self.ok_or(Error::from(OPTION_NONE_ERROR)).or_unexpected() self.ok_or(Error::from(OPTION_NONE_ERROR)).or_unexpected()
} }
fn or_unexpected_while<D: fmt::Display>(self, prefix: D) -> Result<T> { fn or_unexpected_while<D: fmt::Display>(self, prefix: D) -> Result<T, Error> {
self.ok_or(Error::from(OPTION_NONE_ERROR)) self.ok_or(Error::from(OPTION_NONE_ERROR))
.or_unexpected_while(prefix) .or_unexpected_while(prefix)
} }
fn map_unexpected_while<F, D>(self, f: F) -> Result<T> fn map_unexpected_while<F, D>(self, f: F) -> Result<T, Error>
where where
F: FnOnce() -> D, F: FnOnce() -> D,
D: fmt::Display, D: fmt::Display,

View File

@ -7,5 +7,4 @@ pub mod domain;
pub mod error; pub mod error;
pub mod origin; pub mod origin;
pub mod service; pub mod service;
pub mod token;
pub mod util; pub mod util;

View File

@ -78,8 +78,6 @@ async fn main() {
config config
}; };
let token_store = domani::token::MemStore::new();
let origin_store = domani::origin::git::FSStore::new(&config.origin) let origin_store = domani::origin::git::FSStore::new(&config.origin)
.expect("git origin store initialization failed"); .expect("git origin store initialization failed");
@ -109,11 +107,7 @@ async fn main() {
.expect("domain acme store initialization failed"); .expect("domain acme store initialization failed");
Some( Some(
domani::domain::acme::manager::ManagerImpl::new( domani::domain::acme::manager::ManagerImpl::new(domain_acme_store, &acme_config)
domain_acme_store,
token_store,
&acme_config,
)
.await .await
.expect("domain acme manager initialization failed"), .expect("domain acme manager initialization failed"),
) )

View File

@ -1,37 +0,0 @@
/// Provides utilites for storing and retrieving various named string tokens which are needed.
use crate::error::unexpected;
use std::{collections, sync};
pub trait Store {
fn get(&self, key: &str) -> unexpected::Result<Option<String>>;
fn set(&self, key: String, val: String) -> unexpected::Result<()>;
fn del(&self, key: &str) -> unexpected::Result<()>;
}
pub struct MemStore {
m: sync::Mutex<collections::HashMap<String, String>>,
}
impl MemStore {
pub fn new() -> MemStore {
MemStore {
m: sync::Mutex::default(),
}
}
}
impl Store for MemStore {
fn get(&self, key: &str) -> unexpected::Result<Option<String>> {
Ok(self.m.lock().unwrap().get(key).map(|s| s.to_string()))
}
fn set(&self, key: String, val: String) -> unexpected::Result<()> {
self.m.lock().unwrap().insert(key, val);
Ok(())
}
fn del(&self, key: &str) -> unexpected::Result<()> {
self.m.lock().unwrap().remove(key);
Ok(())
}
}