Skip to content

Commit

Permalink
impl trait for rpc auth
Browse files Browse the repository at this point in the history
  • Loading branch information
hmzakhalid committed Nov 29, 2024
1 parent 89d410b commit f159b96
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 36 deletions.
48 changes: 45 additions & 3 deletions packages/ciphernode/config/src/app_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -342,7 +342,7 @@ mod tests {
let filedir = format!("{}/.config/enclave", home);
jail.create_dir(filedir)?;
jail.create_file(
filename,
filename.clone(),
r#"
chains:
- name: "hardhat"
Expand All @@ -361,8 +361,8 @@ chains:
"#,
)?;

let config: AppConfig = load_config(None).map_err(|err| err.to_string())?;
let chain = config.chains().first().unwrap();
let mut config: AppConfig = load_config(None).map_err(|err| err.to_string())?;
let mut chain = config.chains().first().unwrap();

assert_eq!(chain.name, "hardhat");
assert_eq!(chain.rpc_url, "ws://localhost:8545");
Expand All @@ -386,6 +386,48 @@ chains:
chain.contracts.ciphernode_registry.deploy_block(),
Some(1764352873645)
);

jail.create_file(
filename.clone(),
r#"
chains:
- name: "hardhat"
rpc_url: "ws://localhost:8545"
contracts:
enclave: "0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0"
ciphernode_registry:
address: "0xCf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"
deploy_block: 1764352873645
filter_registry: "0xDc64a140Aa3E981100a9becA4E685f962f0cF6C9"
"#,
)?;
config = load_config(None).map_err(|err| err.to_string())?;
chain = config.chains().first().unwrap();

assert_eq!(chain.rpc_auth, RpcAuth::None);

jail.create_file(
filename,
r#"
chains:
- name: "hardhat"
rpc_url: "ws://localhost:8545"
rpc_auth:
type: "Bearer"
credentials: "testToken"
contracts:
enclave: "0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0"
ciphernode_registry:
address: "0xCf7Ed3AccA5a467e9e704C703E8D87F634fB0Fc9"
deploy_block: 1764352873645
filter_registry: "0xDc64a140Aa3E981100a9becA4E685f962f0cF6C9"
"#,
)?;

config = load_config(None).map_err(|err| err.to_string())?;
chain = config.chains().first().unwrap();
assert_eq!(chain.rpc_auth, RpcAuth::Bearer("testToken".to_string()));

Ok(())
});
}
Expand Down
2 changes: 1 addition & 1 deletion packages/ciphernode/enclave_node/src/aggregator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ pub async fn setup_aggregator(
let rpc_url = RPC::from_url(&chain.rpc_url).map_err(|e| {
anyhow::anyhow!("Failed to parse RPC URL for chain {}: {}", chain.name, e)
})?;
let provider_config = ProviderConfig::new(rpc_url, chain.rpc_auth.clone().into());
let provider_config = ProviderConfig::new(rpc_url, chain.rpc_auth.clone());
let read_provider = provider_config.create_readonly_provider().await?;
let write_provider = provider_config.create_ws_signer_provider(&signer).await?;

Expand Down
2 changes: 1 addition & 1 deletion packages/ciphernode/enclave_node/src/ciphernode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ pub async fn setup_ciphernode(
let rpc_url = RPC::from_url(&chain.rpc_url).map_err(|e| {
anyhow::anyhow!("Failed to parse RPC URL for chain {}: {}", chain.name, e)
})?;
let provider_config = ProviderConfig::new(rpc_url, chain.rpc_auth.clone().into());
let provider_config = ProviderConfig::new(rpc_url, chain.rpc_auth.clone());
let read_provider = provider_config.create_readonly_provider().await?;
EnclaveSolReader::attach(
&bus,
Expand Down
43 changes: 12 additions & 31 deletions packages/ciphernode/evm/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use alloy::{
use anyhow::{bail, Context, Result};
use base64::{engine::general_purpose::STANDARD, Engine};
use cipher::Cipher;
use config::RpcAuth as ConfigRpcAuth;
use config::RpcAuth;
use data::Repository;
use std::{env, marker::PhantomData, sync::Arc};
use url::Url;
Expand Down Expand Up @@ -55,7 +55,7 @@ impl RPC {
match self {
RPC::Http(url) | RPC::Https(url) => url.clone(),
RPC::Ws(url) | RPC::Wss(url) => {
let mut parsed = Url::parse(url).expect("URL was validated in constructor");
let mut parsed = Url::parse(url).expect(&format!("Failed to parse URL: {}", url));
parsed
.set_scheme(if self.is_secure() { "https" } else { "http" })
.expect("http(s) are valid schemes");
Expand All @@ -68,7 +68,7 @@ impl RPC {
match self {
RPC::Ws(url) | RPC::Wss(url) => url.clone(),
RPC::Http(url) | RPC::Https(url) => {
let mut parsed = Url::parse(url).expect("URL was validated in constructor");
let mut parsed = Url::parse(url).expect(&format!("Failed to parse URL: {}", url));
parsed
.set_scheme(if self.is_secure() { "wss" } else { "ws" })
.expect("ws(s) are valid schemes");
Expand All @@ -86,21 +86,19 @@ impl RPC {
}
}

#[derive(Clone)]
pub enum RpcAuth {
None,
Basic { username: String, password: String },
Bearer(String),
pub trait AuthConversions {
fn to_header_value(&self) -> Option<HeaderValue>;
fn to_ws_auth(&self) -> Option<Authorization>;
}

impl RpcAuth {
impl AuthConversions for RpcAuth {
fn to_header_value(&self) -> Option<HeaderValue> {
match self {
RpcAuth::None => None,
RpcAuth::Basic { username, password } => {
let auth = format!(
"Basic {}",
STANDARD.encode(format!("{}:{}", username, password))
STANDARD.encode(Zeroizing::new(format!("{}:{}", username, password)))
);
HeaderValue::from_str(&auth).ok()
}
Expand All @@ -117,26 +115,6 @@ impl RpcAuth {
}
}

impl From<ConfigRpcAuth> for RpcAuth {
fn from(value: ConfigRpcAuth) -> Self {
match value {
ConfigRpcAuth::None => RpcAuth::None,
ConfigRpcAuth::Basic { username, password } => RpcAuth::Basic { username, password },
ConfigRpcAuth::Bearer(token) => RpcAuth::Bearer(token),
}
}
}

impl From<RpcAuth> for ConfigRpcAuth {
fn from(value: RpcAuth) -> Self {
match value {
RpcAuth::None => ConfigRpcAuth::None,
RpcAuth::Basic { username, password } => ConfigRpcAuth::Basic { username, password },
RpcAuth::Bearer(token) => ConfigRpcAuth::Bearer(token),
}
}
}

/// We need to cache the chainId so we can easily use it in a non-async situation
/// This wrapper just stores the chain_id with the Provider
#[derive(Clone)]
Expand Down Expand Up @@ -267,7 +245,10 @@ impl ProviderConfig {
if let Some(auth_header) = self.auth.to_header_value() {
headers.insert(AUTHORIZATION, auth_header);
}
let client = Client::builder().default_headers(headers).build()?;
let client = Client::builder()
.default_headers(headers)
.build()
.context("Failed to create HTTP client")?;
let http = Http::with_client(client, self.rpc.as_http_url().parse()?);
Ok(RpcClient::new(http, false))
}
Expand Down

0 comments on commit f159b96

Please sign in to comment.