From 1eb5cda03367c66b7a52faae485129cd56deb87c Mon Sep 17 00:00:00 2001 From: alemi Date: Mon, 15 Jul 2024 02:57:32 +0200 Subject: [PATCH] feat: add cloaker trait --- upub/core/Cargo.toml | 4 +++- upub/core/src/traits/cloak.rs | 37 +++++++++++++++++++++++++++++++++++ upub/core/src/traits/mod.rs | 2 ++ 3 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 upub/core/src/traits/cloak.rs diff --git a/upub/core/Cargo.toml b/upub/core/Cargo.toml index ec61028..6b6eff4 100644 --- a/upub/core/Cargo.toml +++ b/upub/core/Cargo.toml @@ -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"] } diff --git a/upub/core/src/traits/cloak.rs b/upub/core/src/traits/cloak.rs new file mode 100644 index 0000000..1856c52 --- /dev/null +++ b/upub/core/src/traits/cloak.rs @@ -0,0 +1,37 @@ +use base64::{Engine, prelude::BASE64_URL_SAFE}; +use hmac::Mac; + + +pub type Signature = hmac::Hmac; + +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 { + 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 + } +} diff --git a/upub/core/src/traits/mod.rs b/upub/core/src/traits/mod.rs index e2229a6..d4b711b 100644 --- a/upub/core/src/traits/mod.rs +++ b/upub/core/src/traits/mod.rs @@ -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;