feat: add cloaker trait

This commit is contained in:
əlemi 2024-07-15 02:57:32 +02:00
parent a7004d1603
commit 1eb5cda033
Signed by: alemi
GPG key ID: A4895B84D311642C
3 changed files with 42 additions and 1 deletions

View file

@ -14,7 +14,9 @@ readme = "README.md"
thiserror = "1"
async-recursion = "1.1"
async-trait = "0.1"
sha256 = "1.5"
sha256 = "1.5" # TODO get rid of this and use directly sha2!!
sha2 = "0.10"
hmac = "0.12"
openssl = "0.10" # TODO handle pubkeys with a smaller crate
base64 = "0.22"
chrono = { version = "0.4", features = ["serde"] }

View file

@ -0,0 +1,37 @@
use base64::{Engine, prelude::BASE64_URL_SAFE};
use hmac::Mac;
pub type Signature = hmac::Hmac<sha2::Sha256>;
pub trait Cloaker {
fn secret(&self) -> &str;
fn cloak(&self, url: &str) -> (String, String) {
let mut hmac = Signature::new_from_slice(self.secret().as_bytes())
.expect("invalid length for hmac key, cannot cloak");
hmac.update(url.as_bytes());
let sig = BASE64_URL_SAFE.encode(hmac.finalize().into_bytes());
let url = BASE64_URL_SAFE.encode(url);
(sig, url)
}
fn uncloak(&self, signature: &str, url: &str) -> Option<String> {
let mut hmac = Signature::new_from_slice(self.secret().as_bytes())
.expect("invalid length for hmac key, cannot cloak");
let sig = BASE64_URL_SAFE.decode(signature).ok()?;
let url = std::str::from_utf8(&BASE64_URL_SAFE.decode(url).ok()?).ok()?.to_string();
hmac.update(url.as_bytes());
hmac.verify_slice(&sig).ok()?;
Some(url)
}
}
impl Cloaker for crate::Context {
fn secret(&self) -> &str {
&self.cfg().security.proxy_secret
}
}

View file

@ -3,9 +3,11 @@ pub mod fetch;
pub mod normalize;
pub mod process;
pub mod admin;
pub mod cloak;
pub use admin::Administrable;
pub use address::Addresser;
pub use normalize::Normalizer;
pub use process::Processor;
pub use fetch::Fetcher;
pub use cloak::Cloaker;