Compare commits
7 Commits
push-wxnls
...
4bb2c062dc
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4bb2c062dc | ||
|
|
b0a3f37cea | ||
|
|
58a72da46c | ||
|
|
e287459b10 | ||
|
|
5a34463228 | ||
| 62dff3f810 | |||
|
|
6e22f368c9 |
@@ -90,6 +90,7 @@ message EvmGrantCreateResponse {
|
||||
|
||||
message EvmGrantDeleteRequest {
|
||||
int32 grant_id = 1;
|
||||
int32 wallet_access_id = 2;
|
||||
}
|
||||
|
||||
message EvmGrantDeleteResponse {
|
||||
|
||||
14
server/Cargo.lock
generated
14
server/Cargo.lock
generated
@@ -696,12 +696,25 @@ dependencies = [
|
||||
name = "arbiter-crypto"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"alloy",
|
||||
"base64",
|
||||
"chrono",
|
||||
"hmac",
|
||||
"memsafe",
|
||||
"ml-dsa",
|
||||
"rand 0.10.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arbiter-macros"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"arbiter-crypto",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arbiter-proto"
|
||||
version = "0.1.0"
|
||||
@@ -736,6 +749,7 @@ dependencies = [
|
||||
"alloy",
|
||||
"anyhow",
|
||||
"arbiter-crypto",
|
||||
"arbiter-macros",
|
||||
"arbiter-proto",
|
||||
"arbiter-tokens-registry",
|
||||
"argon2",
|
||||
|
||||
@@ -47,3 +47,4 @@ miette = { version = "7.6.0", features = ["fancy", "serde"] }
|
||||
mutants = "0.0.4"
|
||||
ml-dsa = { version = "0.1.0-rc.8", features = ["zeroize"] }
|
||||
base64 = "0.22.1"
|
||||
hmac = "0.12.1"
|
||||
|
||||
@@ -8,6 +8,9 @@ ml-dsa = {workspace = true, optional = true }
|
||||
rand = {workspace = true, optional = true}
|
||||
base64 = {workspace = true, optional = true }
|
||||
memsafe = {version = "0.4.0", optional = true}
|
||||
hmac.workspace = true
|
||||
alloy.workspace = true
|
||||
chrono.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use base64::{Engine as _, prelude::BASE64_STANDARD};
|
||||
use hmac::digest::Digest;
|
||||
use ml_dsa::{
|
||||
EncodedVerifyingKey, Error, KeyGen, MlDsa87, Seed, Signature as MlDsaSignature,
|
||||
SigningKey as MlDsaSigningKey, VerifyingKey as MlDsaVerifyingKey, signature::Keypair as _,
|
||||
@@ -17,6 +18,12 @@ pub type KeyParams = MlDsa87;
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PublicKey(Box<MlDsaVerifyingKey<KeyParams>>);
|
||||
|
||||
impl crate::hashing::Hashable for PublicKey {
|
||||
fn hash<H: Digest>(&self, hasher: &mut H) {
|
||||
hasher.update(self.to_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Signature(Box<MlDsaSignature<KeyParams>>);
|
||||
|
||||
@@ -25,7 +32,7 @@ pub struct SigningKey(Box<MlDsaSigningKey<KeyParams>>);
|
||||
|
||||
impl PublicKey {
|
||||
pub fn to_bytes(&self) -> Vec<u8> {
|
||||
self.0.encode().to_vec()
|
||||
self.0.encode().0.to_vec()
|
||||
}
|
||||
|
||||
pub fn verify(&self, nonce: i32, context: &[u8], signature: &Signature) -> bool {
|
||||
@@ -39,7 +46,7 @@ impl PublicKey {
|
||||
|
||||
impl Signature {
|
||||
pub fn to_bytes(&self) -> Vec<u8> {
|
||||
self.0.encode().to_vec()
|
||||
self.0.encode().0.to_vec()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
use hmac::digest::Digest;
|
||||
pub use hmac::digest::Digest;
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// Deterministically hash a value by feeding its fields into the hasher in a consistent order.
|
||||
#[diagnostic::on_unimplemented(
|
||||
note = "for local types consider adding `#[derive(arbiter_macros::Hashable)]` to your `{Self}` type",
|
||||
note = "for types from other crates check whether the crate offers a `Hashable` implementation"
|
||||
)]
|
||||
pub trait Hashable {
|
||||
fn hash<H: Digest>(&self, hasher: &mut H);
|
||||
}
|
||||
|
||||
macro_rules! impl_numeric {
|
||||
($($t:ty),*) => {
|
||||
$(
|
||||
impl Hashable for $t {
|
||||
fn hash<H: Digest>(&self, hasher: &mut H) {
|
||||
hasher.update(&self.to_be_bytes());
|
||||
($($t:ty),*) => {
|
||||
$(
|
||||
impl Hashable for $t {
|
||||
fn hash<H: Digest>(&self, hasher: &mut H) {
|
||||
hasher.update(&self.to_be_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
impl_numeric!(u8, u16, u32, u64, i8, i16, i32, i64);
|
||||
@@ -1,5 +1,5 @@
|
||||
#[cfg(feature = "authn")]
|
||||
pub mod authn;
|
||||
|
||||
pub mod hashing;
|
||||
#[cfg(feature = "safecell")]
|
||||
pub mod safecell;
|
||||
|
||||
18
server/crates/arbiter-macros/Cargo.toml
Normal file
18
server/crates/arbiter-macros/Cargo.toml
Normal file
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "arbiter-macros"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[lib]
|
||||
proc-macro = true
|
||||
|
||||
[dependencies]
|
||||
proc-macro2 = "1.0"
|
||||
quote = "1.0"
|
||||
syn = { version = "2.0", features = ["derive", "fold", "full", "visit-mut"] }
|
||||
|
||||
[dev-dependencies]
|
||||
arbiter-crypto = { path = "../arbiter-crypto" }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
133
server/crates/arbiter-macros/src/hashable.rs
Normal file
133
server/crates/arbiter-macros/src/hashable.rs
Normal file
@@ -0,0 +1,133 @@
|
||||
use proc_macro2::{Span, TokenStream, TokenTree};
|
||||
use quote::quote;
|
||||
use syn::parse_quote;
|
||||
use syn::spanned::Spanned;
|
||||
use syn::{DataStruct, DeriveInput, Fields, Generics, Index};
|
||||
|
||||
use crate::utils::{HASHABLE_TRAIT_PATH, HMAC_DIGEST_PATH};
|
||||
|
||||
pub(crate) fn derive(input: &DeriveInput) -> TokenStream {
|
||||
match &input.data {
|
||||
syn::Data::Struct(struct_data) => hashable_struct(input, struct_data),
|
||||
syn::Data::Enum(_) => {
|
||||
syn::Error::new_spanned(input, "Hashable can currently be derived only for structs")
|
||||
.to_compile_error()
|
||||
}
|
||||
syn::Data::Union(_) => {
|
||||
syn::Error::new_spanned(input, "Hashable cannot be derived for unions")
|
||||
.to_compile_error()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn hashable_struct(input: &DeriveInput, struct_data: &syn::DataStruct) -> TokenStream {
|
||||
let ident = &input.ident;
|
||||
let hashable_trait = HASHABLE_TRAIT_PATH.to_path();
|
||||
let hmac_digest = HMAC_DIGEST_PATH.to_path();
|
||||
let generics = add_hashable_bounds(input.generics.clone(), &hashable_trait);
|
||||
let field_accesses = collect_field_accesses(struct_data);
|
||||
let hash_calls = build_hash_calls(&field_accesses, &hashable_trait);
|
||||
|
||||
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
|
||||
|
||||
quote! {
|
||||
#[automatically_derived]
|
||||
impl #impl_generics #hashable_trait for #ident #ty_generics #where_clause {
|
||||
fn hash<H: #hmac_digest>(&self, hasher: &mut H) {
|
||||
#(#hash_calls)*
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn add_hashable_bounds(mut generics: Generics, hashable_trait: &syn::Path) -> Generics {
|
||||
for type_param in generics.type_params_mut() {
|
||||
type_param.bounds.push(parse_quote!(#hashable_trait));
|
||||
}
|
||||
|
||||
generics
|
||||
}
|
||||
|
||||
struct FieldAccess {
|
||||
access: TokenStream,
|
||||
span: Span,
|
||||
}
|
||||
|
||||
fn collect_field_accesses(struct_data: &DataStruct) -> Vec<FieldAccess> {
|
||||
match &struct_data.fields {
|
||||
Fields::Named(fields) => {
|
||||
// Keep deterministic alphabetical order for named fields.
|
||||
// Do not remove this sort, because it keeps hash output stable regardless of source order.
|
||||
let mut named_fields = fields
|
||||
.named
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let name = field
|
||||
.ident
|
||||
.as_ref()
|
||||
.expect("Fields::Named(fields) must have names")
|
||||
.clone();
|
||||
(name.to_string(), name)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
named_fields.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
|
||||
named_fields
|
||||
.into_iter()
|
||||
.map(|(_, name)| FieldAccess {
|
||||
access: quote! { #name },
|
||||
span: name.span(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
Fields::Unnamed(fields) => fields
|
||||
.unnamed
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, field)| FieldAccess {
|
||||
access: {
|
||||
let index = Index::from(i);
|
||||
quote! { #index }
|
||||
},
|
||||
span: field.ty.span(),
|
||||
})
|
||||
.collect(),
|
||||
Fields::Unit => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn build_hash_calls(
|
||||
field_accesses: &[FieldAccess],
|
||||
hashable_trait: &syn::Path,
|
||||
) -> Vec<TokenStream> {
|
||||
field_accesses
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let access = &field.access;
|
||||
let call = quote! {
|
||||
#hashable_trait::hash(&self.#access, hasher);
|
||||
};
|
||||
|
||||
respan(call, field.span)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Recursively set span on all tokens, including interpolated ones.
|
||||
fn respan(tokens: TokenStream, span: Span) -> TokenStream {
|
||||
tokens
|
||||
.into_iter()
|
||||
.map(|tt| match tt {
|
||||
TokenTree::Group(g) => {
|
||||
let mut new = proc_macro2::Group::new(g.delimiter(), respan(g.stream(), span));
|
||||
new.set_span(span);
|
||||
TokenTree::Group(new)
|
||||
}
|
||||
mut other => {
|
||||
other.set_span(span);
|
||||
other
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
10
server/crates/arbiter-macros/src/lib.rs
Normal file
10
server/crates/arbiter-macros/src/lib.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
use syn::{DeriveInput, parse_macro_input};
|
||||
|
||||
mod hashable;
|
||||
mod utils;
|
||||
|
||||
#[proc_macro_derive(Hashable)]
|
||||
pub fn derive_hashable(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
|
||||
let input = parse_macro_input!(input as DeriveInput);
|
||||
hashable::derive(&input).into()
|
||||
}
|
||||
19
server/crates/arbiter-macros/src/utils.rs
Normal file
19
server/crates/arbiter-macros/src/utils.rs
Normal file
@@ -0,0 +1,19 @@
|
||||
pub struct ToPath(pub &'static str);
|
||||
|
||||
impl ToPath {
|
||||
pub fn to_path(&self) -> syn::Path {
|
||||
syn::parse_str(self.0).expect("Invalid path")
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! ensure_path {
|
||||
($path:path) => {{
|
||||
#[cfg(test)]
|
||||
#[expect(unused_imports)]
|
||||
use $path as _;
|
||||
ToPath(stringify!($path))
|
||||
}};
|
||||
}
|
||||
|
||||
pub const HASHABLE_TRAIT_PATH: ToPath = ensure_path!(::arbiter_crypto::hashing::Hashable);
|
||||
pub const HMAC_DIGEST_PATH: ToPath = ensure_path!(::arbiter_crypto::hashing::Digest);
|
||||
@@ -18,6 +18,7 @@ diesel-async = { version = "0.8.0", features = [
|
||||
] }
|
||||
arbiter-proto.path = "../arbiter-proto"
|
||||
arbiter-crypto.path = "../arbiter-crypto"
|
||||
arbiter-macros.path = "../arbiter-macros"
|
||||
tracing.workspace = true
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
tonic.workspace = true
|
||||
@@ -44,7 +45,7 @@ restructed = "0.2.2"
|
||||
strum = { version = "0.28.0", features = ["derive"] }
|
||||
pem = "3.0.6"
|
||||
sha2.workspace = true
|
||||
hmac = "0.12"
|
||||
hmac.workspace = true
|
||||
spki.workspace = true
|
||||
alloy.workspace = true
|
||||
prost-types.workspace = true
|
||||
|
||||
@@ -5,7 +5,7 @@ use tracing::{error, info};
|
||||
|
||||
use crate::{
|
||||
actors::{GlobalActors, client::session::ClientSession},
|
||||
crypto::integrity::{Integrable, hashing::Hashable},
|
||||
crypto::integrity::Integrable,
|
||||
db,
|
||||
};
|
||||
|
||||
@@ -15,6 +15,7 @@ pub struct ClientProfile {
|
||||
pub metadata: ClientMetadata,
|
||||
}
|
||||
|
||||
#[derive(arbiter_macros::Hashable)]
|
||||
pub struct ClientCredentials {
|
||||
pub pubkey: authn::PublicKey,
|
||||
pub nonce: i32,
|
||||
@@ -24,13 +25,6 @@ impl Integrable for ClientCredentials {
|
||||
const KIND: &'static str = "client_credentials";
|
||||
}
|
||||
|
||||
impl Hashable for ClientCredentials {
|
||||
fn hash<H: sha2::Digest>(&self, hasher: &mut H) {
|
||||
hasher.update(self.pubkey.to_bytes());
|
||||
self.nonce.hash(hasher);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ClientConnection {
|
||||
pub(crate) db: db::DatabasePool,
|
||||
pub(crate) actors: GlobalActors,
|
||||
|
||||
@@ -158,28 +158,15 @@ impl EvmActor {
|
||||
}
|
||||
|
||||
#[message]
|
||||
pub async fn useragent_delete_grant(&mut self, _grant_id: i32) -> Result<(), Error> {
|
||||
// let mut conn = self.db.get().await.map_err(DatabaseError::from)?;
|
||||
// let keyholder = self.keyholder.clone();
|
||||
|
||||
// diesel_async::AsyncConnection::transaction(&mut conn, |conn| {
|
||||
// Box::pin(async move {
|
||||
// diesel::update(schema::evm_basic_grant::table)
|
||||
// .filter(schema::evm_basic_grant::id.eq(grant_id))
|
||||
// .set(schema::evm_basic_grant::revoked_at.eq(SqliteTimestamp::now()))
|
||||
// .execute(conn)
|
||||
// .await?;
|
||||
|
||||
// let signed = integrity::evm::load_signed_grant_by_basic_id(conn, grant_id).await?;
|
||||
|
||||
// diesel::result::QueryResult::Ok(())
|
||||
// })
|
||||
// })
|
||||
// .await
|
||||
// .map_err(DatabaseError::from)?;
|
||||
|
||||
// Ok(())
|
||||
todo!()
|
||||
pub async fn useragent_delete_grant(
|
||||
&mut self,
|
||||
grant_id: i32,
|
||||
wallet_access_id: i32,
|
||||
) -> Result<(), Error> {
|
||||
self.engine
|
||||
.revoke_grant(grant_id, wallet_access_id)
|
||||
.await
|
||||
.map_err(Error::from)
|
||||
}
|
||||
|
||||
#[message]
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::{
|
||||
};
|
||||
use arbiter_crypto::authn;
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, arbiter_macros::Hashable)]
|
||||
pub struct UserAgentCredentials {
|
||||
pub pubkey: authn::PublicKey,
|
||||
pub nonce: i32,
|
||||
@@ -38,18 +38,3 @@ pub mod session;
|
||||
|
||||
pub use auth::authenticate;
|
||||
pub use session::UserAgentSession;
|
||||
|
||||
use crate::crypto::integrity::hashing::Hashable;
|
||||
|
||||
impl Hashable for authn::PublicKey {
|
||||
fn hash<H: sha2::Digest>(&self, hasher: &mut H) {
|
||||
hasher.update(self.to_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
impl Hashable for UserAgentCredentials {
|
||||
fn hash<H: sha2::Digest>(&self, hasher: &mut H) {
|
||||
self.pubkey.hash(hasher);
|
||||
self.nonce.hash(hasher);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -360,12 +360,13 @@ impl UserAgentSession {
|
||||
pub(crate) async fn handle_grant_delete(
|
||||
&mut self,
|
||||
grant_id: i32,
|
||||
wallet_access_id: i32,
|
||||
) -> Result<(), GrantMutationError> {
|
||||
// match self
|
||||
// .props
|
||||
// .actors
|
||||
// .evm
|
||||
// .ask(UseragentDeleteGrant { grant_id })
|
||||
// .ask(UseragentDeleteGrant { grant_id, wallet_access_id })
|
||||
// .await
|
||||
// {
|
||||
// Ok(()) => Ok(()),
|
||||
@@ -374,7 +375,7 @@ impl UserAgentSession {
|
||||
// Err(GrantMutationError::Internal)
|
||||
// }
|
||||
// }
|
||||
let _ = grant_id;
|
||||
let _ = (grant_id, wallet_access_id);
|
||||
todo!()
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::{actors::keyholder, crypto::integrity::hashing::Hashable};
|
||||
use arbiter_crypto::safecell::SafeCellHandle as _;
|
||||
use hmac::{Hmac, Mac as _};
|
||||
use crate::actors::keyholder;
|
||||
use arbiter_crypto::hashing::Hashable;
|
||||
use hmac::Hmac;
|
||||
use sha2::Sha256;
|
||||
|
||||
use diesel::{ExpressionMethods as _, QueryDsl, dsl::insert_into, sqlite::Sqlite};
|
||||
@@ -8,8 +8,6 @@ use diesel_async::{AsyncConnection, RunQueryDsl};
|
||||
use kameo::{actor::ActorRef, error::SendError};
|
||||
use sha2::Digest as _;
|
||||
|
||||
pub mod hashing;
|
||||
|
||||
use crate::{
|
||||
actors::keyholder::{KeyHolder, SignIntegrity, VerifyIntegrity},
|
||||
db::{
|
||||
@@ -204,10 +202,6 @@ mod tests {
|
||||
use diesel_async::RunQueryDsl;
|
||||
use kameo::{actor::ActorRef, prelude::Spawn};
|
||||
|
||||
use sha2::Digest;
|
||||
|
||||
|
||||
|
||||
use crate::{
|
||||
actors::keyholder::{Bootstrap, KeyHolder},
|
||||
db::{self, schema},
|
||||
@@ -215,20 +209,11 @@ mod tests {
|
||||
use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _};
|
||||
|
||||
use super::{Error, Integrable, sign_entity, verify_entity};
|
||||
use super::hashing::Hashable;
|
||||
|
||||
#[derive(Clone)]
|
||||
#[derive(Clone, arbiter_macros::Hashable)]
|
||||
struct DummyEntity {
|
||||
payload_version: i32,
|
||||
payload: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Hashable for DummyEntity {
|
||||
fn hash<H: Digest>(&self, hasher: &mut H) {
|
||||
self.payload_version.hash(hasher);
|
||||
self.payload.hash(hasher);
|
||||
}
|
||||
}
|
||||
impl Integrable for DummyEntity {
|
||||
const KIND: &'static str = "dummy_entity";
|
||||
}
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
pub mod abi;
|
||||
pub mod safe_signer;
|
||||
|
||||
use alloy::primitives::Address;
|
||||
use alloy::{
|
||||
consensus::TxEip1559,
|
||||
primitives::{TxKind, U256},
|
||||
};
|
||||
use chrono::Utc;
|
||||
use diesel::{ExpressionMethods as _, QueryDsl as _, QueryResult, insert_into, sqlite::Sqlite};
|
||||
use diesel::{
|
||||
ExpressionMethods as _, OptionalExtension, QueryDsl as _, QueryResult, SelectableHelper,
|
||||
insert_into, sqlite::Sqlite, update,
|
||||
};
|
||||
use diesel_async::{AsyncConnection, RunQueryDsl};
|
||||
use kameo::actor::ActorRef;
|
||||
|
||||
@@ -16,14 +20,16 @@ use crate::{
|
||||
db::{
|
||||
self, DatabaseError,
|
||||
models::{
|
||||
EvmBasicGrant, EvmWalletAccess, NewEvmBasicGrant, NewEvmTransactionLog, SqliteTimestamp,
|
||||
EvmBasicGrant, EvmEtherTransferGrant, EvmEtherTransferGrantTarget,
|
||||
EvmEtherTransferLimit, EvmTokenTransferGrant, EvmTokenTransferVolumeLimit,
|
||||
EvmWalletAccess, NewEvmBasicGrant, NewEvmTransactionLog, SqliteTimestamp,
|
||||
},
|
||||
schema::{self, evm_transaction_log},
|
||||
},
|
||||
evm::policies::{
|
||||
CombinedSettings, DatabaseID, EvalContext, EvalViolation, Grant, Policy,
|
||||
SharedGrantSettings, SpecificGrant, SpecificMeaning, ether_transfer::EtherTransfer,
|
||||
token_transfers::TokenTransfer,
|
||||
SharedGrantSettings, SpecificGrant, SpecificMeaning, VolumeRateLimit,
|
||||
ether_transfer::EtherTransfer, token_transfers::TokenTransfer,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -270,6 +276,156 @@ impl Engine {
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
pub async fn revoke_grant(
|
||||
&self,
|
||||
basic_grant_id: i32,
|
||||
wallet_access_id: i32,
|
||||
) -> Result<(), DatabaseError> {
|
||||
let mut conn = self.db.get().await.map_err(DatabaseError::from)?;
|
||||
let keyholder = self.keyholder.clone();
|
||||
|
||||
conn.transaction(|conn| {
|
||||
Box::pin(async move {
|
||||
use crate::db::schema::{
|
||||
evm_basic_grant, evm_ether_transfer_grant, evm_ether_transfer_grant_target,
|
||||
evm_ether_transfer_limit, evm_token_transfer_grant,
|
||||
evm_token_transfer_volume_limit,
|
||||
};
|
||||
|
||||
update(evm_basic_grant::table)
|
||||
.filter(evm_basic_grant::id.eq(basic_grant_id))
|
||||
.filter(evm_basic_grant::wallet_access_id.eq(wallet_access_id))
|
||||
.set(evm_basic_grant::revoked_at.eq(SqliteTimestamp(Utc::now())))
|
||||
.execute(conn)
|
||||
.await?;
|
||||
|
||||
let basic_grant: EvmBasicGrant = evm_basic_grant::table
|
||||
.filter(evm_basic_grant::id.eq(basic_grant_id))
|
||||
.filter(evm_basic_grant::wallet_access_id.eq(wallet_access_id))
|
||||
.select(EvmBasicGrant::as_select())
|
||||
.first(conn)
|
||||
.await?;
|
||||
|
||||
let shared = SharedGrantSettings::try_from_model(basic_grant)?;
|
||||
|
||||
if let Some(ether_grant) = evm_ether_transfer_grant::table
|
||||
.filter(evm_ether_transfer_grant::basic_grant_id.eq(basic_grant_id))
|
||||
.select(EvmEtherTransferGrant::as_select())
|
||||
.first(conn)
|
||||
.await
|
||||
.optional()?
|
||||
{
|
||||
let target_rows: Vec<EvmEtherTransferGrantTarget> =
|
||||
evm_ether_transfer_grant_target::table
|
||||
.filter(evm_ether_transfer_grant_target::grant_id.eq(ether_grant.id))
|
||||
.select(EvmEtherTransferGrantTarget::as_select())
|
||||
.load(conn)
|
||||
.await?;
|
||||
let targets: Vec<Address> = target_rows
|
||||
.into_iter()
|
||||
.filter_map(|target| {
|
||||
let arr: [u8; 20] = target.address.try_into().ok()?;
|
||||
Some(Address::from(arr))
|
||||
})
|
||||
.collect();
|
||||
|
||||
let limit: EvmEtherTransferLimit = evm_ether_transfer_limit::table
|
||||
.filter(evm_ether_transfer_limit::id.eq(ether_grant.limit_id))
|
||||
.select(EvmEtherTransferLimit::as_select())
|
||||
.first(conn)
|
||||
.await?;
|
||||
|
||||
let settings = CombinedSettings {
|
||||
shared: shared.clone(),
|
||||
specific: crate::evm::policies::ether_transfer::Settings {
|
||||
target: targets,
|
||||
limit: VolumeRateLimit {
|
||||
max_volume: utils::try_bytes_to_u256(&limit.max_volume).map_err(
|
||||
|err| {
|
||||
diesel::result::Error::DeserializationError(Box::new(err))
|
||||
},
|
||||
)?,
|
||||
window: chrono::Duration::seconds(limit.window_secs as i64),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
integrity::sign_entity(conn, &keyholder, &settings, basic_grant_id)
|
||||
.await
|
||||
.map_err(|_| diesel::result::Error::RollbackTransaction)?;
|
||||
|
||||
return QueryResult::Ok(());
|
||||
}
|
||||
|
||||
if let Some(token_grant) = evm_token_transfer_grant::table
|
||||
.filter(evm_token_transfer_grant::basic_grant_id.eq(basic_grant_id))
|
||||
.select(EvmTokenTransferGrant::as_select())
|
||||
.first(conn)
|
||||
.await
|
||||
.optional()?
|
||||
{
|
||||
let volume_limit_rows: Vec<EvmTokenTransferVolumeLimit> =
|
||||
evm_token_transfer_volume_limit::table
|
||||
.filter(evm_token_transfer_volume_limit::grant_id.eq(token_grant.id))
|
||||
.select(EvmTokenTransferVolumeLimit::as_select())
|
||||
.load(conn)
|
||||
.await?;
|
||||
let volume_limits: Vec<VolumeRateLimit> = volume_limit_rows
|
||||
.into_iter()
|
||||
.map(|row| {
|
||||
Ok(VolumeRateLimit {
|
||||
max_volume: utils::try_bytes_to_u256(&row.max_volume).map_err(
|
||||
|err| {
|
||||
diesel::result::Error::DeserializationError(Box::new(err))
|
||||
},
|
||||
)?,
|
||||
window: chrono::Duration::seconds(row.window_secs as i64),
|
||||
})
|
||||
})
|
||||
.collect::<QueryResult<Vec<_>>>()?;
|
||||
|
||||
let target: Option<Address> = match token_grant.receiver {
|
||||
None => None,
|
||||
Some(bytes) => {
|
||||
let arr: [u8; 20] = bytes.try_into().map_err(|_| {
|
||||
diesel::result::Error::DeserializationError(
|
||||
"Invalid receiver address length".into(),
|
||||
)
|
||||
})?;
|
||||
Some(Address::from(arr))
|
||||
}
|
||||
};
|
||||
|
||||
let token_contract: [u8; 20] =
|
||||
token_grant.token_contract.clone().try_into().map_err(|_| {
|
||||
diesel::result::Error::DeserializationError(
|
||||
"Invalid token contract address length".into(),
|
||||
)
|
||||
})?;
|
||||
|
||||
let settings = CombinedSettings {
|
||||
shared,
|
||||
specific: crate::evm::policies::token_transfers::Settings {
|
||||
token_contract: Address::from(token_contract),
|
||||
target,
|
||||
volume_limits,
|
||||
},
|
||||
};
|
||||
|
||||
integrity::sign_entity(conn, &keyholder, &settings, basic_grant_id)
|
||||
.await
|
||||
.map_err(|_| diesel::result::Error::RollbackTransaction)?;
|
||||
|
||||
return QueryResult::Ok(());
|
||||
}
|
||||
|
||||
Err(diesel::result::Error::NotFound)
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(DatabaseError::from)
|
||||
}
|
||||
|
||||
async fn list_one_kind<Kind: Policy, Y>(
|
||||
&self,
|
||||
conn: &mut impl AsyncConnection<Backend = Sqlite>,
|
||||
@@ -349,11 +505,15 @@ impl Engine {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use alloy::primitives::{Address, Bytes, U256, address};
|
||||
use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _};
|
||||
use chrono::{Duration, Utc};
|
||||
use diesel::{SelectableHelper, insert_into};
|
||||
use diesel_async::RunQueryDsl;
|
||||
use kameo::{actor::ActorRef, prelude::Spawn};
|
||||
use rstest::rstest;
|
||||
|
||||
use crate::actors::keyholder::{Bootstrap, KeyHolder};
|
||||
use crate::crypto::integrity;
|
||||
use crate::db::{
|
||||
self, DatabaseConnection,
|
||||
models::{
|
||||
@@ -361,8 +521,10 @@ mod tests {
|
||||
},
|
||||
schema::{evm_basic_grant, evm_transaction_log},
|
||||
};
|
||||
use crate::evm::policies::ether_transfer::EtherTransfer;
|
||||
use crate::evm::policies::{
|
||||
EvalContext, EvalViolation, SharedGrantSettings, TransactionRateLimit,
|
||||
CombinedSettings, EvalContext, EvalViolation, Policy, SharedGrantSettings,
|
||||
TransactionRateLimit, VolumeRateLimit,
|
||||
};
|
||||
|
||||
use super::check_shared_constraints;
|
||||
@@ -394,6 +556,7 @@ mod tests {
|
||||
chain: CHAIN_ID,
|
||||
valid_from: None,
|
||||
valid_until: None,
|
||||
revoked_at: None,
|
||||
max_gas_fee_per_gas: None,
|
||||
max_priority_fee_per_gas: None,
|
||||
rate_limit: None,
|
||||
@@ -596,4 +759,111 @@ mod tests {
|
||||
assert!(violations.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
async fn bootstrapped_keyholder(db: &db::DatabasePool) -> ActorRef<KeyHolder> {
|
||||
let actor = KeyHolder::spawn(KeyHolder::new(db.clone()).await.unwrap());
|
||||
actor
|
||||
.ask(Bootstrap {
|
||||
seal_key_raw: SafeCell::new(b"integrity-test-seal-key".to_vec()),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
actor
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn revoke_grant_preserves_revoked_integrity() {
|
||||
use crate::db::schema::evm_basic_grant;
|
||||
use diesel::ExpressionMethods as _;
|
||||
|
||||
let db = db::create_test_pool().await;
|
||||
let keyholder = bootstrapped_keyholder(&db).await;
|
||||
let engine = super::Engine::new(db.clone(), keyholder.clone());
|
||||
|
||||
let full_grant = CombinedSettings {
|
||||
shared: SharedGrantSettings {
|
||||
wallet_access_id: WALLET_ACCESS_ID,
|
||||
chain: CHAIN_ID,
|
||||
valid_from: None,
|
||||
valid_until: None,
|
||||
revoked_at: None,
|
||||
max_gas_fee_per_gas: None,
|
||||
max_priority_fee_per_gas: None,
|
||||
rate_limit: None,
|
||||
},
|
||||
specific: crate::evm::policies::ether_transfer::Settings {
|
||||
target: vec![RECIPIENT],
|
||||
limit: VolumeRateLimit {
|
||||
max_volume: U256::from(100u64),
|
||||
window: Duration::hours(1),
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
let grant_id = engine
|
||||
.create_grant::<EtherTransfer>(full_grant)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
engine.revoke_grant(grant_id, WALLET_ACCESS_ID).await.unwrap();
|
||||
|
||||
let mut conn = db.get().await.unwrap();
|
||||
diesel::update(evm_basic_grant::table)
|
||||
.filter(evm_basic_grant::id.eq(grant_id))
|
||||
.set(evm_basic_grant::revoked_at.eq::<Option<SqliteTimestamp>>(None))
|
||||
.execute(&mut conn)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let wallet_access = EvmWalletAccess {
|
||||
id: WALLET_ACCESS_ID,
|
||||
wallet_id: 10,
|
||||
client_id: 20,
|
||||
created_at: SqliteTimestamp(Utc::now()),
|
||||
};
|
||||
let context = EvalContext {
|
||||
target: wallet_access,
|
||||
chain: CHAIN_ID,
|
||||
to: RECIPIENT,
|
||||
value: U256::ONE,
|
||||
calldata: Bytes::new(),
|
||||
max_fee_per_gas: 1,
|
||||
max_priority_fee_per_gas: 1,
|
||||
};
|
||||
|
||||
let grant = crate::evm::policies::ether_transfer::EtherTransfer::try_find_grant(
|
||||
&context, &mut conn,
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
let result =
|
||||
integrity::verify_entity(&mut conn, &keyholder, &grant.settings, grant.id).await;
|
||||
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(crate::crypto::integrity::Error::MacMismatch { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_settings_hash_changes_when_revoked_at_changes() {
|
||||
use arbiter_crypto::hashing::Hashable;
|
||||
use sha2::Digest;
|
||||
|
||||
let active = shared_settings();
|
||||
let revoked = SharedGrantSettings {
|
||||
revoked_at: Some(Utc::now()),
|
||||
..shared_settings()
|
||||
};
|
||||
|
||||
let mut active_hash = sha2::Sha256::new();
|
||||
active.hash(&mut active_hash);
|
||||
|
||||
let mut revoked_hash = sha2::Sha256::new();
|
||||
revoked.hash(&mut revoked_hash);
|
||||
|
||||
assert_ne!(active_hash.finalize(), revoked_hash.finalize());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,25 +127,26 @@ pub enum SpecificMeaning {
|
||||
TokenTransfer(token_transfers::Meaning),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, arbiter_macros::Hashable)]
|
||||
pub struct TransactionRateLimit {
|
||||
pub count: u32,
|
||||
pub window: Duration,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, arbiter_macros::Hashable)]
|
||||
pub struct VolumeRateLimit {
|
||||
pub max_volume: U256,
|
||||
pub window: Duration,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, arbiter_macros::Hashable)]
|
||||
pub struct SharedGrantSettings {
|
||||
pub wallet_access_id: i32,
|
||||
pub chain: ChainId,
|
||||
|
||||
pub valid_from: Option<DateTime<Utc>>,
|
||||
pub valid_until: Option<DateTime<Utc>>,
|
||||
pub revoked_at: Option<DateTime<Utc>>,
|
||||
|
||||
pub max_gas_fee_per_gas: Option<U256>,
|
||||
pub max_priority_fee_per_gas: Option<U256>,
|
||||
@@ -160,6 +161,7 @@ impl SharedGrantSettings {
|
||||
chain: model.chain_id as u64, // safe because chain_id is stored as i32 but is guaranteed to be a valid ChainId by the API when creating grants
|
||||
valid_from: model.valid_from.map(Into::into),
|
||||
valid_until: model.valid_until.map(Into::into),
|
||||
revoked_at: model.revoked_at.map(Into::into),
|
||||
max_gas_fee_per_gas: model
|
||||
.max_gas_fee_per_gas
|
||||
.map(|b| utils::try_bytes_to_u256(&b))
|
||||
@@ -200,7 +202,7 @@ pub enum SpecificGrant {
|
||||
TokenTransfer(token_transfers::Settings),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, arbiter_macros::Hashable)]
|
||||
pub struct CombinedSettings<PolicyGrant> {
|
||||
pub shared: SharedGrantSettings,
|
||||
pub specific: PolicyGrant,
|
||||
@@ -219,38 +221,3 @@ impl<P: Integrable> Integrable for CombinedSettings<P> {
|
||||
const KIND: &'static str = P::KIND;
|
||||
const VERSION: i32 = P::VERSION;
|
||||
}
|
||||
|
||||
use crate::crypto::integrity::hashing::Hashable;
|
||||
|
||||
impl Hashable for TransactionRateLimit {
|
||||
fn hash<H: sha2::Digest>(&self, hasher: &mut H) {
|
||||
self.count.hash(hasher);
|
||||
self.window.hash(hasher);
|
||||
}
|
||||
}
|
||||
|
||||
impl Hashable for VolumeRateLimit {
|
||||
fn hash<H: sha2::Digest>(&self, hasher: &mut H) {
|
||||
self.max_volume.hash(hasher);
|
||||
self.window.hash(hasher);
|
||||
}
|
||||
}
|
||||
|
||||
impl Hashable for SharedGrantSettings {
|
||||
fn hash<H: sha2::Digest>(&self, hasher: &mut H) {
|
||||
self.wallet_access_id.hash(hasher);
|
||||
self.chain.hash(hasher);
|
||||
self.valid_from.hash(hasher);
|
||||
self.valid_until.hash(hasher);
|
||||
self.max_gas_fee_per_gas.hash(hasher);
|
||||
self.max_priority_fee_per_gas.hash(hasher);
|
||||
self.rate_limit.hash(hasher);
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Hashable> Hashable for CombinedSettings<P> {
|
||||
fn hash<H: sha2::Digest>(&self, hasher: &mut H) {
|
||||
self.shared.hash(hasher);
|
||||
self.specific.hash(hasher);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ impl From<Meaning> for SpecificMeaning {
|
||||
}
|
||||
|
||||
// A grant for ether transfers, which can be scoped to specific target addresses and volume limits
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, arbiter_macros::Hashable)]
|
||||
pub struct Settings {
|
||||
pub target: Vec<Address>,
|
||||
pub limit: VolumeRateLimit,
|
||||
@@ -61,15 +61,6 @@ impl Integrable for Settings {
|
||||
const KIND: &'static str = "EtherTransfer";
|
||||
}
|
||||
|
||||
use crate::crypto::integrity::hashing::Hashable;
|
||||
|
||||
impl Hashable for Settings {
|
||||
fn hash<H: sha2::Digest>(&self, hasher: &mut H) {
|
||||
self.target.hash(hasher);
|
||||
self.limit.hash(hasher);
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Settings> for SpecificGrant {
|
||||
fn from(val: Settings) -> SpecificGrant {
|
||||
SpecificGrant::EtherTransfer(val)
|
||||
|
||||
@@ -78,6 +78,7 @@ fn shared() -> SharedGrantSettings {
|
||||
chain: CHAIN_ID,
|
||||
valid_from: None,
|
||||
valid_until: None,
|
||||
revoked_at: None,
|
||||
max_gas_fee_per_gas: None,
|
||||
max_priority_fee_per_gas: None,
|
||||
rate_limit: None,
|
||||
@@ -340,7 +341,7 @@ proptest::proptest! {
|
||||
) {
|
||||
use rand::{SeedableRng, seq::SliceRandom};
|
||||
use sha2::Digest;
|
||||
use crate::crypto::integrity::hashing::Hashable;
|
||||
use arbiter_crypto::hashing::Hashable;
|
||||
|
||||
let addrs: Vec<Address> = raw_addrs.iter().map(|b| Address::from(*b)).collect();
|
||||
let mut shuffled = addrs.clone();
|
||||
|
||||
@@ -62,7 +62,7 @@ impl From<Meaning> for SpecificMeaning {
|
||||
}
|
||||
|
||||
// A grant for token transfers, which can be scoped to specific target addresses and volume limits
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Debug, Clone, arbiter_macros::Hashable)]
|
||||
pub struct Settings {
|
||||
pub token_contract: Address,
|
||||
pub target: Option<Address>,
|
||||
@@ -72,16 +72,6 @@ impl Integrable for Settings {
|
||||
const KIND: &'static str = "TokenTransfer";
|
||||
}
|
||||
|
||||
use crate::crypto::integrity::hashing::Hashable;
|
||||
|
||||
impl Hashable for Settings {
|
||||
fn hash<H: sha2::Digest>(&self, hasher: &mut H) {
|
||||
self.token_contract.hash(hasher);
|
||||
self.target.hash(hasher);
|
||||
self.volume_limits.hash(hasher);
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Settings> for SpecificGrant {
|
||||
fn from(val: Settings) -> SpecificGrant {
|
||||
SpecificGrant::TokenTransfer(val)
|
||||
|
||||
@@ -95,6 +95,7 @@ fn shared() -> SharedGrantSettings {
|
||||
chain: CHAIN_ID,
|
||||
valid_from: None,
|
||||
valid_until: None,
|
||||
revoked_at: None,
|
||||
max_gas_fee_per_gas: None,
|
||||
max_priority_fee_per_gas: None,
|
||||
rate_limit: None,
|
||||
@@ -419,7 +420,7 @@ proptest::proptest! {
|
||||
) {
|
||||
use rand::{SeedableRng, seq::SliceRandom};
|
||||
use sha2::Digest;
|
||||
use crate::crypto::integrity::hashing::Hashable;
|
||||
use arbiter_crypto::hashing::Hashable;
|
||||
|
||||
let limits: Vec<VolumeRateLimit> = raw_limits
|
||||
.iter()
|
||||
|
||||
@@ -170,6 +170,7 @@ async fn handle_grant_delete(
|
||||
let result = match actor
|
||||
.ask(HandleGrantDelete {
|
||||
grant_id: req.grant_id,
|
||||
wallet_access_id: req.wallet_access_id,
|
||||
})
|
||||
.await
|
||||
{
|
||||
|
||||
@@ -87,6 +87,7 @@ impl TryConvert for ProtoSharedSettings {
|
||||
.valid_until
|
||||
.map(ProtoTimestamp::try_convert)
|
||||
.transpose()?,
|
||||
revoked_at: None,
|
||||
max_gas_fee_per_gas: self
|
||||
.max_gas_fee_per_gas
|
||||
.as_deref()
|
||||
|
||||
Reference in New Issue
Block a user