Skip to content

Commit

Permalink
scraping key requesting logic to use the key from config
Browse files Browse the repository at this point in the history
  • Loading branch information
geekbrother committed Oct 9, 2023
1 parent 6bfe997 commit 212a9fd
Show file tree
Hide file tree
Showing 7 changed files with 16 additions and 83 deletions.
8 changes: 0 additions & 8 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ pub struct Config {
pub log_level_otel: String,
#[serde(default = "default_disable_header")]
pub disable_header: bool,
#[serde(default = "default_relay_url")]
pub relay_url: String,
pub relay_public_key: String,
#[serde(default = "default_validate_signatures")]
pub validate_signatures: bool,
Expand Down Expand Up @@ -199,12 +197,6 @@ fn default_validate_signatures() -> bool {
true
}

pub const RELAY_URL: &str = "https://relay.walletconnect.com";

fn default_relay_url() -> String {
RELAY_URL.to_string()
}

fn default_is_test() -> bool {
false
}
Expand Down
8 changes: 1 addition & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ use {
request_id::{PropagateRequestIdLayer, SetRequestIdLayer},
trace::{DefaultMakeSpan, DefaultOnRequest, DefaultOnResponse, TraceLayer},
},
tracing::{info, log::LevelFilter, warn, Level},
tracing::{info, log::LevelFilter, Level},
};

#[cfg(not(feature = "multitenant"))]
Expand Down Expand Up @@ -155,12 +155,6 @@ pub async fn bootstap(mut shutdown: broadcast::Receiver<()>, config: Config) ->
.collect::<Vec<&str>>()
.join(", ");

// Fetch public key so it's cached for the first 6hrs
let public_key = state.relay_client.public_key().await;
if public_key.is_err() {
warn!("Failed initial fetch of Relay's Public Key, this may prevent webhook validation.")
}

if state.config.telemetry_prometheus_port.is_some() {
state.set_metrics(metrics::Metrics::new(Resource::new(vec![
KeyValue::new("service_name", "echo-server"),
Expand Down
2 changes: 1 addition & 1 deletion src/middleware/validate_signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ where
let s = span!(tracing::Level::DEBUG, "validate_signature");
let _ = s.enter();

let public_key = state.relay_client().public_key().await?;
let public_key = state.relay_client().get_verifying_key().clone();

Check failure on line 47 in src/middleware/validate_signature.rs

View workflow job for this annotation

GitHub Actions / [ubuntu-latest/rust-stable] Clippy

using `clone` on type `VerifyingKey` which implements the `Copy` trait

let (parts, body_raw) = req.into_parts();
let bytes = hyper::body::to_bytes(body_raw)
Expand Down
60 changes: 12 additions & 48 deletions src/relay/mod.rs
Original file line number Diff line number Diff line change
@@ -1,62 +1,26 @@
use {
chrono::{DateTime, Duration, Utc},
ed25519_dalek::VerifyingKey,
std::ops::Add,
ed25519_dalek::VerifyingKey
};

const PUBLIC_KEY_TTL_HOURS: i64 = 6;

#[derive(Clone)]
pub struct RelayClient {
http_client: reqwest::Client,
base_url: String,
public_key: Option<VerifyingKey>,
public_key_last_fetched: DateTime<Utc>,
public_key: VerifyingKey,
}

impl RelayClient {
pub fn new(base_url: String) -> RelayClient {
RelayClient {
http_client: reqwest::Client::new(),
base_url,
public_key: None,
public_key_last_fetched: DateTime::<Utc>::MIN_UTC,
}
}

/// Fetches the public key with a TTL
pub async fn public_key(&mut self) -> crate::error::Result<VerifyingKey> {
if let Some(public_key) = self.public_key {
// TTL Not exceeded
if self
.public_key_last_fetched
.add(Duration::hours(PUBLIC_KEY_TTL_HOURS))
< Utc::now()
{
return Ok(public_key);
}
}

let public_key = self.fetch_public_key().await?;
self.public_key = Some(public_key);
self.public_key_last_fetched = Utc::now();
Ok(public_key)
pub fn new(string_public_key: String) -> crate::error::Result<RelayClient> {
let verifying_key = Self::string_to_verifying_key(&string_public_key)?;
Ok(RelayClient {
public_key: verifying_key
})
}

async fn fetch_public_key(&self) -> crate::error::Result<VerifyingKey> {
let response = self
.http_client
.get(self.get_url("public-key"))
.send()
.await?;
let body = response.text().await?;
let key_bytes = hex::decode(body)?;
let public_key =
VerifyingKey::from_bytes(<&[u8; 32]>::try_from(key_bytes.as_slice()).unwrap())?;
Ok(public_key)
pub fn get_verifying_key(&self) -> &VerifyingKey {
&self.public_key
}

fn get_url(&self, path: &str) -> String {
format!("{}/{}", self.base_url, path)
fn string_to_verifying_key(string_key: &str) -> crate::error::Result<VerifyingKey> {
let key_bytes = hex::decode(string_key)?;
Ok(VerifyingKey::from_bytes(<&[u8; 32]>::try_from(key_bytes.as_slice()).unwrap())?)
}
}
6 changes: 2 additions & 4 deletions src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,6 @@ pub fn new_state(
#[cfg(not(feature = "multitenant"))]
let is_multitenant = false;

let relay_url = config.relay_url.to_string();

#[cfg(feature = "cloud")]
let (cloud_url, cloud_api_key) = (config.cloud_api_url.clone(), config.cloud_api_key.clone());

Expand All @@ -86,15 +84,15 @@ pub fn new_state(
};

Ok(AppState {
config,
config: config.clone(),
build_info: build_info.clone(),
metrics: None,
#[cfg(feature = "analytics")]
analytics: None,
client_store,
notification_store,
tenant_store,
relay_client: RelayClient::new(relay_url),
relay_client: RelayClient::new(config.relay_public_key)?,
#[cfg(feature = "cloud")]
registry_client: RegistryHttpClient::new(cloud_url, cloud_api_key.as_str())?,
#[cfg(feature = "multitenant")]
Expand Down
1 change: 0 additions & 1 deletion tests/context/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ impl EchoServer {
log_level: "info,echo-server=info".into(),
log_level_otel: "info,echo-server=trace".into(),
disable_header: true,
relay_url: "https://relay.walletconnect.com".into(),
validate_signatures: false,
database_url: DATABASE_URL.into(),
#[cfg(feature = "multitenant")]
Expand Down
14 changes: 0 additions & 14 deletions tests/unit/relay.rs

This file was deleted.

0 comments on commit 212a9fd

Please sign in to comment.