Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: dynamic chain support #403

Merged
merged 4 commits into from
Mar 11, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,9 @@ futures = "0.3.26"
futures-util = "0.3"
dashmap = "5.4.0"

relay_rpc = { git = "https://github.com/WalletConnect/WalletConnectRust.git", tag = "v0.28.0", features = ["cacao"] }
relay_client = { git = "https://github.com/WalletConnect/WalletConnectRust.git", tag = "v0.28.0" }
relay_rpc = { git = "https://github.com/WalletConnect/WalletConnectRust.git", branch = "fix/dynamic-chain-support", features = ["cacao"] }
relay_client = { git = "https://github.com/WalletConnect/WalletConnectRust.git", branch = "fix/dynamic-chain-support" }
blockchain_api = { git = "https://github.com/WalletConnect/WalletConnectRust.git", branch = "fix/dynamic-chain-support" }
x25519-dalek = { version = "2.0.0", features = ["static_secrets"] }
hkdf = "0.12.3"
sha2 = "0.10.6"
Expand Down Expand Up @@ -104,3 +105,4 @@ build-info-build = "0.0"
# [patch.'https://github.com/WalletConnect/WalletConnectRust.git']
# relay_rpc = { path = "../WalletConnectRust/relay_rpc" }
# relay_client = { path = "../WalletConnectRust/relay_client" }
# blockchain_api = { path = "../WalletConnectRust/blockchain_api" }

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm curious, do we need to maintain these lines commented out?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So it's easy to un-comment and be able to test local changes easily

141 changes: 116 additions & 25 deletions src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use {
},
registry::storage::{error::StorageError, redis::Redis, KeyValueStorage},
siwx::{
erc5573::{build_statement, parse_recap, RecapParseError},
erc5573::{build_statement, parse_recap, RecapParseError, RECAP_URI_PREFIX},
notify_recap::{
ABILITY_ABILITY_ALL_APPS_MAGIC, ABILITY_ABILITY_SUFFIX, ABILITY_NAMESPACE_MANAGE,
NOTIFY_URI,
Expand Down Expand Up @@ -589,8 +589,11 @@ pub enum IdentityVerificationClientError {
#[error("CACAO exp parse error: {0}")]
CacaoExpParse(chrono::ParseError),

#[error("CACAO recap error: {0}")]
CacaoRecap(RecapParseError),
#[error("CACAO recap more than one urn:recap URI in resources")]
CacaoMoreThanOneRecapUri,

#[error("CACAO recap parse error: {0}")]
CacaoRecapParse(RecapParseError),

#[error("CACAO statement does not match recap")]
CacaoStatementDoesNotMatchRecap,
Expand Down Expand Up @@ -752,7 +755,7 @@ pub async fn verify_identity(
ksu: &str,
sub: &str,
redis: Option<&Arc<Redis>>,
provider: &impl GetRpcUrl,
provider: Option<&impl GetRpcUrl>,
metrics: Option<&Metrics>,
) -> Result<Authorization, IdentityVerificationError> {
let mut url = Url::parse(ksu)
Expand Down Expand Up @@ -796,16 +799,22 @@ pub async fn verify_identity(
.ok_or(IdentityVerificationClientError::CacaoStatementMissing)?;
info!("CACAO statement: {statement}");

let resources = cacao.p.resources.unwrap_or(vec![]);

// As per the spec, there may be at most one recap URI in the spec
if resources
.iter()
.filter(|uri| uri.starts_with(RECAP_URI_PREFIX))
.count()
> 1
{
Err(IdentityVerificationClientError::CacaoMoreThanOneRecapUri)?;
}

// As per the spec, the last resource must be the recap, if recaps are in-use
let recap = parse_recap(
cacao
.p
.resources
.unwrap_or(vec![])
.last()
.map(String::as_str),
)
.map_err(IdentityVerificationClientError::CacaoRecap)?;
let recap_uri = resources.last().map(String::as_str);
let recap =
parse_recap(recap_uri).map_err(IdentityVerificationClientError::CacaoRecapParse)?;

if let Some(recap) = recap {
let expected_statement_suffix = build_statement(&recap);
Expand Down Expand Up @@ -1121,13 +1130,13 @@ pub mod test_utils {
let cacao_signature = [&signature.to_bytes()[..], &[recovery.to_byte()]].concat();
cacao.s.t = EIP191.to_owned();
cacao.s.s = hex::encode(cacao_signature);
cacao.verify(&MockGetRpcUrl).await.unwrap();
cacao.verify(Some(&MockGetRpcUrl)).await.unwrap();
cacao
}

pub struct MockGetRpcUrl;
impl GetRpcUrl for MockGetRpcUrl {
fn get_rpc_url(&self, _: String) -> Option<Url> {
async fn get_rpc_url(&self, _: String) -> Option<Url> {
None
}
}
Expand Down Expand Up @@ -1398,7 +1407,7 @@ pub mod test {
keys_server_url.as_ref(),
&account.to_did_pkh(),
None,
&MockGetRpcUrl,
Some(&MockGetRpcUrl),
None,
)
.await
Expand Down Expand Up @@ -1447,7 +1456,7 @@ pub mod test {
keys_server_url.as_ref(),
&account.to_did_pkh(),
None,
&MockGetRpcUrl,
Some(&MockGetRpcUrl),
None,
)
.await
Expand Down Expand Up @@ -1496,7 +1505,7 @@ pub mod test {
keys_server_url.as_ref(),
&account.to_did_pkh(),
None,
&MockGetRpcUrl,
Some(&MockGetRpcUrl),
None,
)
.await
Expand Down Expand Up @@ -1545,7 +1554,7 @@ pub mod test {
keys_server_url.as_ref(),
&account.to_did_pkh(),
None,
&MockGetRpcUrl,
Some(&MockGetRpcUrl),
None,
)
.await
Expand All @@ -1555,6 +1564,88 @@ pub mod test {
assert_eq!(app, AuthorizedApp::Unlimited);
}

#[tokio::test]
async fn recaps_fail_more_than_one_recap_uri() {
let (account_signing_key, account) = generate_account();

let keys_server = MockServer::start().await;
let keys_server_url = keys_server.uri().parse::<Url>().unwrap();

let (_identity_signing_key, identity_public_key) = generate_identity_key();

let project_id = ProjectId::generate();
let app_domain = DidWeb::from_domain(format!("{project_id}.walletconnect.com"));

let cacao = {
let did_key = identity_public_key.to_did_key();
let mut resources = vec![keys_server_url.to_string()];
let domain = app_domain.domain();
let recap = build_recap_details_object(Some(app_domain.domain()));
resources.push(encode_recaip_uri(&recap));
resources.push(encode_recaip_uri(&recap));
let statement = build_statement(&recap);
let aud = {
let mut url = format!("https://{domain}").parse::<Url>().unwrap();
url.query_pairs_mut().append_pair(
cacao::payload::Payload::WALLETCONNECT_IDENTITY_KEY,
&did_key,
);
url.to_string()
};
let mut cacao = cacao::Cacao {
h: cacao::header::Header {
t: EIP4361.to_owned().into(),
},
p: cacao::payload::Payload {
domain: app_domain.domain().to_owned(),
iss: account.to_did_pkh(),
statement: Some(statement),
aud,
version: cacao::Version::V1,
nonce: hex::encode(rand::Rng::gen::<[u8; 10]>(&mut rand::thread_rng())),
iat: Utc::now().to_rfc3339(),
exp: None,
nbf: None,
request_id: None,
resources: Some(resources),
},
s: cacao::signature::Signature {
t: "".to_owned(),
s: "".to_owned(),
},
};
let (signature, recovery): (k256::ecdsa::Signature, _) = account_signing_key
.sign_digest_recoverable(Keccak256::new_with_prefix(eip191_bytes(
&cacao.siwe_message().unwrap(),
)))
.unwrap();
let cacao_signature = [&signature.to_bytes()[..], &[recovery.to_byte()]].concat();
cacao.s.t = EIP191.to_owned();
cacao.s.s = hex::encode(cacao_signature);
cacao.verify(Some(&MockGetRpcUrl)).await.unwrap();
cacao
};

register_mocked_identity_key(&keys_server, identity_public_key.clone(), cacao.clone())
.await;

let result = verify_identity(
&identity_public_key,
keys_server_url.as_ref(),
&account.to_did_pkh(),
None,
Some(&MockGetRpcUrl),
None,
)
.await;
assert!(matches!(
result,
Err(IdentityVerificationError::Client(
IdentityVerificationClientError::CacaoMoreThanOneRecapUri
))
));
}

#[tokio::test]
async fn recaps_fail_empty_array() {
let (account_signing_key, account) = generate_account();
Expand Down Expand Up @@ -1625,7 +1716,7 @@ pub mod test {
let cacao_signature = [&signature.to_bytes()[..], &[recovery.to_byte()]].concat();
cacao.s.t = EIP191.to_owned();
cacao.s.s = hex::encode(cacao_signature);
cacao.verify(&MockGetRpcUrl).await.unwrap();
cacao.verify(Some(&MockGetRpcUrl)).await.unwrap();
cacao
};

Expand All @@ -1637,7 +1728,7 @@ pub mod test {
keys_server_url.as_ref(),
&account.to_did_pkh(),
None,
&MockGetRpcUrl,
Some(&MockGetRpcUrl),
None,
)
.await;
Expand Down Expand Up @@ -1711,7 +1802,7 @@ pub mod test {
let cacao_signature = [&signature.to_bytes()[..], &[recovery.to_byte()]].concat();
cacao.s.t = EIP191.to_owned();
cacao.s.s = hex::encode(cacao_signature);
cacao.verify(&MockGetRpcUrl).await.unwrap();
cacao.verify(Some(&MockGetRpcUrl)).await.unwrap();
cacao
};

Expand All @@ -1723,7 +1814,7 @@ pub mod test {
keys_server_url.as_ref(),
&account.to_did_pkh(),
None,
&MockGetRpcUrl,
Some(&MockGetRpcUrl),
None,
)
.await;
Expand Down Expand Up @@ -1787,7 +1878,7 @@ pub mod test {
let cacao_signature = [&signature.to_bytes()[..], &[recovery.to_byte()]].concat();
cacao.s.t = EIP191.to_owned();
cacao.s.s = hex::encode(cacao_signature);
cacao.verify(&MockGetRpcUrl).await.unwrap();
cacao.verify(Some(&MockGetRpcUrl)).await.unwrap();
cacao
};

Expand All @@ -1799,7 +1890,7 @@ pub mod test {
keys_server_url.as_ref(),
&account.to_did_pkh(),
None,
&MockGetRpcUrl,
Some(&MockGetRpcUrl),
None,
)
.await;
Expand Down
7 changes: 7 additions & 0 deletions src/config/deployed/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ pub struct DeployedConfiguration {
pub relay_url: Url,
pub relay_public_key: String,
pub notify_url: Url,
#[serde(default = "default_blockchain_api_endpoint")]
pub blockchain_api_endpoint: Option<String>,

pub registry_url: Url,
pub registry_auth_token: String,
Expand Down Expand Up @@ -76,6 +78,10 @@ fn default_redis_pool_size() -> u32 {
64
}

fn default_blockchain_api_endpoint() -> Option<String> {
Some("https://rpc.walletconnect.com".to_string())
}

pub fn get_configuration() -> Result<Configuration, NotifyServerError> {
let config = envy::from_env::<DeployedConfiguration>()?;

Expand All @@ -91,6 +97,7 @@ pub fn get_configuration() -> Result<Configuration, NotifyServerError> {
relay_url: config.relay_url,
relay_public_key: config.relay_public_key,
notify_url: config.notify_url,
blockchain_api_endpoint: config.blockchain_api_endpoint,
registry_url: config.registry_url,
registry_auth_token: config.registry_auth_token,
auth_redis_addr_read: config.auth_redis_addr_read,
Expand Down
7 changes: 7 additions & 0 deletions src/config/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ pub struct LocalConfiguration {
pub relay_url: Url,
#[serde(default = "default_registry_url")]
pub registry_url: Url,
#[serde(default = "default_blockchain_api_endpoint")]
pub blockchain_api_endpoint: Option<String>,
}

fn default_bind_ip() -> IpAddr {
Expand Down Expand Up @@ -76,6 +78,10 @@ fn default_registry_url() -> Url {
"https://registry.walletconnect.com".parse().unwrap()
}

fn default_blockchain_api_endpoint() -> Option<String> {
Some("https://rpc.walletconnect.com".to_string())
}

pub async fn get_configuration() -> Result<Configuration, NotifyServerError> {
load_dot_env()?;
let config = envy::from_env::<LocalConfiguration>()?;
Expand All @@ -101,6 +107,7 @@ pub async fn get_configuration() -> Result<Configuration, NotifyServerError> {
project_id: config.project_id,
relay_url: config.relay_url,
relay_public_key,
blockchain_api_endpoint: config.blockchain_api_endpoint,
registry_url: config.registry_url,
registry_auth_token: config.registry_auth_token,
auth_redis_addr_read: None,
Expand Down
1 change: 1 addition & 0 deletions src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub struct Configuration {
pub postgres_max_connections: u32,
pub keypair_seed: String,
pub project_id: ProjectId,
pub blockchain_api_endpoint: Option<String>,
/// Relay URL e.g. https://relay.walletconnect.com
pub relay_url: Url,
pub relay_public_key: String,
Expand Down
Loading
Loading