housekeeping(server): clean too-broad visibility markers and organize imports
Some checks failed
ci/woodpecker/pr/server-audit Pipeline was successful
ci/woodpecker/pr/server-vet Pipeline failed
ci/woodpecker/pr/server-lint Pipeline failed
ci/woodpecker/pr/server-test Pipeline failed
ci/woodpecker/pr/useragent-analyze Pipeline failed

This commit is contained in:
Skipper
2026-04-18 13:29:45 +02:00
parent 70acfc99b5
commit 929d50b589
72 changed files with 507 additions and 549 deletions

View File

@@ -1,3 +1,7 @@
use crate::{
storage::StorageError,
transport::{ClientTransport, next_request_id},
};
use arbiter_crypto::authn::{self, CLIENT_CONTEXT, SigningKey}; use arbiter_crypto::authn::{self, CLIENT_CONTEXT, SigningKey};
use arbiter_proto::{ use arbiter_proto::{
ClientMetadata, ClientMetadata,
@@ -15,12 +19,8 @@ use arbiter_proto::{
shared::ClientInfo as ProtoClientInfo, shared::ClientInfo as ProtoClientInfo,
}, },
}; };
use chrono::DateTime;
use crate::{ use chrono::DateTime;
storage::StorageError,
transport::{ClientTransport, next_request_id},
};
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum AuthError { pub enum AuthError {

View File

@@ -1,8 +1,8 @@
use std::io::{self, Write};
use arbiter_client::ArbiterClient; use arbiter_client::ArbiterClient;
use arbiter_proto::{ClientMetadata, url::ArbiterUrl}; use arbiter_proto::{ClientMetadata, url::ArbiterUrl};
use std::io::{self, Write};
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
println!("Testing connection to Arbiter server..."); println!("Testing connection to Arbiter server...");

View File

@@ -1,21 +1,20 @@
use arbiter_crypto::authn::SigningKey; #[cfg(feature = "evm")]
use arbiter_proto::{ use crate::wallets::evm::ArbiterEvmWallet;
ClientMetadata, proto::arbiter_service_client::ArbiterServiceClient, url::ArbiterUrl,
};
use std::sync::Arc;
use tokio::sync::{Mutex, mpsc};
use tokio_stream::wrappers::ReceiverStream;
use tonic::transport::ClientTlsConfig;
use crate::{ use crate::{
StorageError, StorageError,
auth::{AuthError, authenticate}, auth::{AuthError, authenticate},
storage::{FileSigningKeyStorage, SigningKeyStorage}, storage::{FileSigningKeyStorage, SigningKeyStorage},
transport::{BUFFER_LENGTH, ClientTransport}, transport::{BUFFER_LENGTH, ClientTransport},
}; };
use arbiter_crypto::authn::SigningKey;
use arbiter_proto::{
ClientMetadata, proto::arbiter_service_client::ArbiterServiceClient, url::ArbiterUrl,
};
#[cfg(feature = "evm")] use std::sync::Arc;
use crate::wallets::evm::ArbiterEvmWallet; use tokio::sync::{Mutex, mpsc};
use tokio_stream::wrappers::ReceiverStream;
use tonic::transport::ClientTlsConfig;
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum Error { pub enum Error {

View File

@@ -1,5 +1,6 @@
use arbiter_crypto::authn::SigningKey; use arbiter_crypto::authn::SigningKey;
use arbiter_proto::home_path; use arbiter_proto::home_path;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]

View File

@@ -1,4 +1,5 @@
use arbiter_proto::proto::client::{ClientRequest, ClientResponse}; use arbiter_proto::proto::client::{ClientRequest, ClientResponse};
use std::sync::atomic::{AtomicI32, Ordering}; use std::sync::atomic::{AtomicI32, Ordering};
use tokio::sync::mpsc; use tokio::sync::mpsc;

View File

@@ -1,13 +1,4 @@
use alloy::{ use crate::transport::{ClientTransport, next_request_id};
consensus::SignableTransaction,
network::TxSigner,
primitives::{Address, B256, ChainId, Signature},
signers::{Error, Result, Signer},
};
use async_trait::async_trait;
use std::sync::Arc;
use tokio::sync::Mutex;
use arbiter_proto::proto::{ use arbiter_proto::proto::{
client::{ client::{
ClientRequest, ClientRequest,
@@ -25,7 +16,15 @@ use arbiter_proto::proto::{
shared::evm::TransactionEvalError, shared::evm::TransactionEvalError,
}; };
use crate::transport::{ClientTransport, next_request_id}; use alloy::{
consensus::SignableTransaction,
network::TxSigner,
primitives::{Address, B256, ChainId, Signature},
signers::{Error, Result, Signer},
};
use async_trait::async_trait;
use std::sync::Arc;
use tokio::sync::Mutex;
/// A typed error payload returned by [`ArbiterEvmWallet`] transaction signing. /// A typed error payload returned by [`ArbiterEvmWallet`] transaction signing.
/// ///

View File

@@ -1,6 +1,7 @@
pub use hmac::digest::Digest;
use std::collections::HashSet; use std::collections::HashSet;
pub use hmac::digest::Digest;
/// Deterministically hash a value by feeding its fields into the hasher in a consistent order. /// Deterministically hash a value by feeding its fields into the hasher in a consistent order.
#[diagnostic::on_unimplemented( #[diagnostic::on_unimplemented(
note = "for local types consider adding `#[derive(arbiter_macros::Hashable)]` to your `{Self}` type", note = "for local types consider adding `#[derive(arbiter_macros::Hashable)]` to your `{Self}` type",

View File

@@ -1,7 +1,9 @@
use std::ops::{Deref, DerefMut};
use std::{any::type_name, fmt};
use memsafe::MemSafe; use memsafe::MemSafe;
use std::{
any::type_name,
fmt,
ops::{Deref, DerefMut},
};
pub trait SafeCellHandle<T> { pub trait SafeCellHandle<T> {
type CellRead<'a>: Deref<Target = T> type CellRead<'a>: Deref<Target = T>

View File

@@ -1,10 +1,8 @@
use crate::utils::{HASHABLE_TRAIT_PATH, HMAC_DIGEST_PATH};
use proc_macro2::{Span, TokenStream, TokenTree}; use proc_macro2::{Span, TokenStream, TokenTree};
use quote::quote; use quote::quote;
use syn::parse_quote; use syn::{DataStruct, DeriveInput, Fields, Generics, Index, parse_quote, spanned::Spanned};
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 { pub(crate) fn derive(input: &DeriveInput) -> TokenStream {
match &input.data { match &input.data {

View File

@@ -1,7 +1,7 @@
pub struct ToPath(pub &'static str); pub(crate) struct ToPath(pub(crate) &'static str);
impl ToPath { impl ToPath {
pub fn to_path(&self) -> syn::Path { pub(crate) fn to_path(&self) -> syn::Path {
syn::parse_str(self.0).expect("Invalid path") syn::parse_str(self.0).expect("Invalid path")
} }
} }
@@ -15,5 +15,5 @@ macro_rules! ensure_path {
}}; }};
} }
pub const HASHABLE_TRAIT_PATH: ToPath = ensure_path!(::arbiter_crypto::hashing::Hashable); pub(crate) const HASHABLE_TRAIT_PATH: ToPath = ensure_path!(::arbiter_crypto::hashing::Hashable);
pub const HMAC_DIGEST_PATH: ToPath = ensure_path!(::arbiter_crypto::hashing::Digest); pub(crate) const HMAC_DIGEST_PATH: ToPath = ensure_path!(::arbiter_crypto::hashing::Digest);

View File

@@ -54,11 +54,9 @@
//! as a closed outbound channel. //! as a closed outbound channel.
//! - [`Bi::recv`] returns `None` when the underlying transport closes. //! - [`Bi::recv`] returns `None` when the underlying transport closes.
//! - Message translation is intentionally out of scope for this module. //! - Message translation is intentionally out of scope for this module.
use std::marker::PhantomData;
use async_trait::async_trait; use async_trait::async_trait;
use kameo::{error::Infallible, prelude::*}; use kameo::{error::Infallible, prelude::*};
use std::marker::PhantomData;
/// Errors returned by transport adapters implementing [`Bi`]. /// Errors returned by transport adapters implementing [`Bi`].
#[derive(thiserror::Error, Debug)] #[derive(thiserror::Error, Debug)]

View File

@@ -1,10 +1,10 @@
use super::{Bi, Receiver, Sender};
use async_trait::async_trait; use async_trait::async_trait;
use futures::StreamExt; use futures::StreamExt;
use tokio::sync::mpsc; use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream; use tokio_stream::wrappers::ReceiverStream;
use super::{Bi, Receiver, Sender};
pub struct GrpcSender<Outbound> { pub struct GrpcSender<Outbound> {
tx: mpsc::Sender<Result<Outbound, tonic::Status>>, tx: mpsc::Sender<Result<Outbound, tonic::Status>>,
} }

View File

@@ -1,7 +1,6 @@
use std::fmt::Display;
use base64::{Engine as _, prelude::BASE64_URL_SAFE}; use base64::{Engine as _, prelude::BASE64_URL_SAFE};
use rustls_pki_types::CertificateDer; use rustls_pki_types::CertificateDer;
use std::fmt::Display;
const ARBITER_URL_SCHEME: &str = "arbiter"; const ARBITER_URL_SCHEME: &str = "arbiter";
const CERT_QUERY_KEY: &str = "cert"; const CERT_QUERY_KEY: &str = "cert";

View File

@@ -1,13 +1,13 @@
use crate::db::{self, DatabasePool, schema};
use arbiter_proto::{BOOTSTRAP_PATH, home_path}; use arbiter_proto::{BOOTSTRAP_PATH, home_path};
use diesel::QueryDsl; use diesel::QueryDsl;
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
use kameo::{Actor, messages}; use kameo::{Actor, messages};
use rand::{RngExt, distr::Alphanumeric, make_rng, rngs::StdRng}; use rand::{RngExt, distr::Alphanumeric, make_rng, rngs::StdRng};
use subtle::ConstantTimeEq as _; use subtle::ConstantTimeEq as _;
use thiserror::Error; use thiserror::Error;
use crate::db::{self, DatabasePool, schema};
const TOKEN_LENGTH: usize = 64; const TOKEN_LENGTH: usize = 64;
pub async fn generate_token() -> Result<String, std::io::Error> { pub async fn generate_token() -> Result<String, std::io::Error> {

View File

@@ -1,11 +1,3 @@
use alloy::{consensus::TxEip1559, primitives::Address, signers::Signature};
use diesel::{
ExpressionMethods, OptionalExtension as _, QueryDsl, SelectableHelper as _, dsl::insert_into,
};
use diesel_async::RunQueryDsl;
use kameo::{Actor, actor::ActorRef, messages};
use rand::{SeedableRng, rng, rngs::StdRng};
use crate::{ use crate::{
actors::vault::{CreateNew, Decrypt, Vault}, actors::vault::{CreateNew, Decrypt, Vault},
crypto::integrity, crypto::integrity,
@@ -24,6 +16,14 @@ use crate::{
}; };
use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _}; use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _};
use alloy::{consensus::TxEip1559, primitives::Address, signers::Signature};
use diesel::{
ExpressionMethods, OptionalExtension as _, QueryDsl, SelectableHelper as _, dsl::insert_into,
};
use diesel_async::RunQueryDsl;
use kameo::{Actor, actor::ActorRef, messages};
use rand::{SeedableRng, rng, rngs::StdRng};
pub use crate::evm::safe_signer; pub use crate::evm::safe_signer;
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]

View File

@@ -1,11 +1,3 @@
use std::ops::ControlFlow;
use kameo::{
Actor, messages,
prelude::{ActorId, ActorRef, ActorStopReason, Context, WeakActorRef},
reply::ReplySender,
};
use crate::{ use crate::{
actors::flow_coordinator::ApprovalError, actors::flow_coordinator::ApprovalError,
peers::{ peers::{
@@ -14,6 +6,13 @@ use crate::{
}, },
}; };
use kameo::{
Actor, messages,
prelude::{ActorId, ActorRef, ActorStopReason, Context, WeakActorRef},
reply::ReplySender,
};
use std::ops::ControlFlow;
pub struct Args { pub struct Args {
pub client: ClientProfile, pub client: ClientProfile,
pub user_agents: Vec<ActorRef<UserAgentSession>>, pub user_agents: Vec<ActorRef<UserAgentSession>>,

View File

@@ -1,4 +1,10 @@
use std::{collections::HashMap, ops::ControlFlow}; use crate::{
actors::{
flow_coordinator::client_connect_approval::ClientApprovalController,
useragent_registry::{GetConnected, UserAgentRegistry},
},
peers::client::{ClientProfile, session::ClientSession},
};
use kameo::{ use kameo::{
Actor, Actor,
@@ -7,16 +13,9 @@ use kameo::{
prelude::{ActorStopReason, Context, WeakActorRef}, prelude::{ActorStopReason, Context, WeakActorRef},
reply::DelegatedReply, reply::DelegatedReply,
}; };
use std::{collections::HashMap, ops::ControlFlow};
use tracing::info; use tracing::info;
use crate::{
actors::{
flow_coordinator::client_connect_approval::ClientApprovalController,
useragent_registry::{GetConnected, UserAgentRegistry},
},
peers::client::{ClientProfile, session::ClientSession},
};
pub mod client_connect_approval; pub mod client_connect_approval;
pub struct FlowCoordinator { pub struct FlowCoordinator {

View File

@@ -1,23 +1,20 @@
use kameo::actor::{ActorRef, Spawn};
use kameo_actors::{DeliveryStrategy, message_bus::MessageBus};
use thiserror::Error;
use crate::{ use crate::{
actors::{ actors::{
bootstrap::Bootstrapper, bootstrap::Bootstrapper, evm::EvmActor, flow_coordinator::FlowCoordinator,
evm::EvmActor, useragent_registry::UserAgentRegistry, vault::Vault,
flow_coordinator::FlowCoordinator,
useragent_registry::UserAgentRegistry,
vault::Vault,
}, },
db, db,
}; };
use kameo::actor::{ActorRef, Spawn};
use kameo_actors::{DeliveryStrategy, message_bus::MessageBus};
use thiserror::Error;
pub mod bootstrap; pub mod bootstrap;
pub mod evm; pub mod evm;
pub mod flow_coordinator; pub mod flow_coordinator;
pub mod vault;
pub mod useragent_registry; pub mod useragent_registry;
pub mod vault;
#[derive(Error, Debug)] #[derive(Error, Debug)]
pub enum SpawnError { pub enum SpawnError {

View File

@@ -1,4 +1,4 @@
use std::{collections::HashMap, ops::ControlFlow}; use crate::peers::user_agent::UserAgentSession;
use kameo::{ use kameo::{
Actor, Actor,
@@ -7,10 +7,9 @@ use kameo::{
messages, messages,
prelude::{ActorStopReason, Context, WeakActorRef}, prelude::{ActorStopReason, Context, WeakActorRef},
}; };
use std::{collections::HashMap, ops::ControlFlow};
use tracing::info; use tracing::info;
use crate::peers::user_agent::UserAgentSession;
#[derive(Default)] #[derive(Default)]
pub struct UserAgentRegistry { pub struct UserAgentRegistry {
connected: HashMap<ActorId, ActorRef<UserAgentSession>>, connected: HashMap<ActorId, ActorRef<UserAgentSession>>,
@@ -32,7 +31,11 @@ impl Actor for UserAgentRegistry {
_: ActorStopReason, _: ActorStopReason,
) -> Result<ControlFlow<ActorStopReason>, Self::Error> { ) -> Result<ControlFlow<ActorStopReason>, Self::Error> {
if self.connected.remove(&id).is_some() { if self.connected.remove(&id).is_some() {
info!(?id, actor = "UserAgentRegistry", event = "useragent.disconnected"); info!(
?id,
actor = "UserAgentRegistry",
event = "useragent.disconnected"
);
} }
Ok(ControlFlow::Continue(())) Ok(ControlFlow::Continue(()))
} }

View File

@@ -1,3 +1,17 @@
use crate::{
crypto::{
KeyCell, derive_key,
encryption::v1::{self, Nonce},
integrity::v1::HmacSha256,
},
db::{
self,
models::{self, RootKeyHistory},
schema::{self},
},
};
use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _};
use chrono::Utc; use chrono::Utc;
use diesel::{ use diesel::{
ExpressionMethods as _, OptionalExtension, QueryDsl, SelectableHelper, ExpressionMethods as _, OptionalExtension, QueryDsl, SelectableHelper,
@@ -10,18 +24,6 @@ use kameo_actors::message_bus::{MessageBus, Publish};
use strum::{EnumDiscriminants, IntoDiscriminant}; use strum::{EnumDiscriminants, IntoDiscriminant};
use tracing::{error, info}; use tracing::{error, info};
use crate::crypto::{
KeyCell, derive_key,
encryption::v1::{self, Nonce},
integrity::v1::HmacSha256,
};
use crate::db::{
self,
models::{self, RootKeyHistory},
schema::{self},
};
use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _};
pub mod events { pub mod events {
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
@@ -213,7 +215,7 @@ impl Vault {
}); });
info!("Vault bootstrapped successfully"); info!("Vault bootstrapped successfully");
self.events.tell(Publish(events::Bootstrapped)).await; let _ = self.events.tell(Publish(events::Bootstrapped)).await;
Ok(()) Ok(())
} }
@@ -269,7 +271,7 @@ impl Vault {
}); });
info!("Vault unsealed successfully"); info!("Vault unsealed successfully");
self.events.tell(Publish(events::Unsealed)).await; let _ = self.events.tell(Publish(events::Unsealed)).await;
Ok(()) Ok(())
} }
@@ -399,7 +401,7 @@ impl Vault {
self.state = State::Sealed { self.state = State::Sealed {
root_key_history_id: *root_key_history_id, root_key_history_id: *root_key_history_id,
}; };
self.events.tell(Publish(events::VaultResealed)).await; let _ = self.events.tell(Publish(events::VaultResealed)).await;
Ok(()) Ok(())
} }
} }

View File

@@ -1,13 +1,12 @@
use std::sync::Arc;
use thiserror::Error;
use crate::{ use crate::{
actors::GlobalActors, actors::GlobalActors,
context::tls::TlsManager, context::tls::TlsManager,
db::{self}, db::{self},
}; };
use std::sync::Arc;
use thiserror::Error;
pub mod tls; pub mod tls;
#[derive(Error, Debug)] #[derive(Error, Debug)]

View File

@@ -1,17 +1,3 @@
use std::{net::Ipv4Addr, string::FromUtf8Error};
use diesel::{ExpressionMethods as _, QueryDsl, SelectableHelper as _};
use diesel_async::{AsyncConnection, RunQueryDsl};
use pem::Pem;
use rcgen::{
BasicConstraints, Certificate, CertificateParams, CertifiedIssuer, DistinguishedName, DnType,
IsCa, Issuer, KeyPair, KeyUsagePurpose, SanType,
};
use rustls::pki_types::pem::PemObject;
use thiserror::Error;
use tonic::transport::CertificateDer;
use crate::db::{ use crate::db::{
self, self,
models::{NewTlsHistory, TlsHistory}, models::{NewTlsHistory, TlsHistory},
@@ -21,6 +7,18 @@ use crate::db::{
}, },
}; };
use diesel::{ExpressionMethods as _, QueryDsl, SelectableHelper as _};
use diesel_async::{AsyncConnection, RunQueryDsl};
use pem::Pem;
use rcgen::{
BasicConstraints, Certificate, CertificateParams, CertifiedIssuer, DistinguishedName, DnType,
IsCa, Issuer, KeyPair, KeyUsagePurpose, SanType,
};
use rustls::pki_types::pem::PemObject;
use std::{net::Ipv4Addr, string::FromUtf8Error};
use thiserror::Error;
use tonic::transport::CertificateDer;
const ENCODE_CONFIG: pem::EncodeConfig = { const ENCODE_CONFIG: pem::EncodeConfig = {
let line_ending = match cfg!(target_family = "windows") { let line_ending = match cfg!(target_family = "windows") {
true => pem::LineEnding::CRLF, true => pem::LineEnding::CRLF,

View File

@@ -1,5 +1,4 @@
use argon2::password_hash::Salt as ArgonSalt; use argon2::password_hash::Salt as ArgonSalt;
use rand::{ use rand::{
Rng as _, SeedableRng, Rng as _, SeedableRng,
rngs::{StdRng, SysRng}, rngs::{StdRng, SysRng},
@@ -63,7 +62,7 @@ mod tests {
use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _}; use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _};
#[test] #[test]
pub fn derive_seal_key_deterministic() { fn derive_seal_key_deterministic() {
static PASSWORD: &[u8] = b"password"; static PASSWORD: &[u8] = b"password";
let password = SafeCell::new(PASSWORD.to_vec()); let password = SafeCell::new(PASSWORD.to_vec());
let password2 = SafeCell::new(PASSWORD.to_vec()); let password2 = SafeCell::new(PASSWORD.to_vec());
@@ -79,7 +78,7 @@ mod tests {
} }
#[test] #[test]
pub fn successful_derive() { fn successful_derive() {
static PASSWORD: &[u8] = b"password"; static PASSWORD: &[u8] = b"password";
let password = SafeCell::new(PASSWORD.to_vec()); let password = SafeCell::new(PASSWORD.to_vec());
let salt = generate_salt(); let salt = generate_salt();
@@ -93,7 +92,7 @@ mod tests {
#[test] #[test]
// We should fuzz this // We should fuzz this
pub fn test_nonce_increment() { fn test_nonce_increment() {
let mut nonce = Nonce([0u8; NONCE_LENGTH]); let mut nonce = Nonce([0u8; NONCE_LENGTH]);
nonce.increment(); nonce.increment();

View File

@@ -1,12 +1,3 @@
use arbiter_crypto::hashing::Hashable;
use hmac::Hmac;
use sha2::Sha256;
use diesel::{ExpressionMethods as _, QueryDsl, dsl::insert_into, sqlite::Sqlite};
use diesel_async::{AsyncConnection, RunQueryDsl};
use kameo::{actor::ActorRef, error::SendError};
use sha2::Digest as _;
use crate::{ use crate::{
actors::vault::{self, GetState, SignIntegrity, Vault, VerifyIntegrity}, actors::vault::{self, GetState, SignIntegrity, Vault, VerifyIntegrity},
db::{ db::{
@@ -15,6 +6,13 @@ use crate::{
schema::integrity_envelope, schema::integrity_envelope,
}, },
}; };
use arbiter_crypto::hashing::Hashable;
use diesel::{ExpressionMethods as _, QueryDsl, dsl::insert_into, sqlite::Sqlite};
use diesel_async::{AsyncConnection, RunQueryDsl};
use hmac::Hmac;
use kameo::{actor::ActorRef, error::SendError};
use sha2::{Digest as _, Sha256};
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum Error { pub enum Error {

View File

@@ -1,4 +1,5 @@
use std::ops::Deref as _; use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _};
use encryption::v1::{Nonce, Salt};
use argon2::{Algorithm, Argon2}; use argon2::{Algorithm, Argon2};
use chacha20poly1305::{ use chacha20poly1305::{
@@ -9,14 +10,11 @@ use rand::{
Rng as _, SeedableRng as _, Rng as _, SeedableRng as _,
rngs::{StdRng, SysRng}, rngs::{StdRng, SysRng},
}; };
use std::ops::Deref as _;
use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _};
pub mod encryption; pub mod encryption;
pub mod integrity; pub mod integrity;
use encryption::v1::{Nonce, Salt};
pub struct KeyCell(pub SafeCell<Key>); pub struct KeyCell(pub SafeCell<Key>);
impl From<SafeCell<Key>> for KeyCell { impl From<SafeCell<Key>> for KeyCell {
fn from(value: SafeCell<Key>) -> Self { fn from(value: SafeCell<Key>) -> Self {
@@ -144,7 +142,7 @@ mod tests {
use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _}; use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _};
#[test] #[test]
pub fn encrypt_decrypt() { fn encrypt_decrypt() {
static PASSWORD: &[u8] = b"password"; static PASSWORD: &[u8] = b"password";
let password = SafeCell::new(PASSWORD.to_vec()); let password = SafeCell::new(PASSWORD.to_vec());
let salt = generate_salt(); let salt = generate_salt();

View File

@@ -5,7 +5,6 @@ use diesel_async::{
sync_connection_wrapper::SyncConnectionWrapper, sync_connection_wrapper::SyncConnectionWrapper,
}; };
use diesel_migrations::{EmbeddedMigrations, MigrationHarness, embed_migrations}; use diesel_migrations::{EmbeddedMigrations, MigrationHarness, embed_migrations};
use thiserror::Error; use thiserror::Error;
use tracing::info; use tracing::info;

View File

@@ -1,12 +1,12 @@
#![allow(unused)] #![allow(unused)]
#![allow(clippy::all)] #![allow(clippy::all)]
use crate::db::schema::{ use crate::db::schema::{
self, aead_encrypted, arbiter_settings, evm_basic_grant, evm_ether_transfer_grant, self, aead_encrypted, arbiter_settings, evm_basic_grant, evm_ether_transfer_grant,
evm_ether_transfer_grant_target, evm_ether_transfer_limit, evm_token_transfer_grant, evm_ether_transfer_grant_target, evm_ether_transfer_limit, evm_token_transfer_grant,
evm_token_transfer_log, evm_token_transfer_volume_limit, evm_transaction_log, evm_wallet, evm_token_transfer_log, evm_token_transfer_volume_limit, evm_transaction_log, evm_wallet,
integrity_envelope, root_key_history, tls_history, integrity_envelope, root_key_history, tls_history,
}; };
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use diesel::{prelude::*, sqlite::Sqlite}; use diesel::{prelude::*, sqlite::Sqlite};
use restructed::Models; use restructed::Models;

View File

@@ -1,15 +1,3 @@
pub mod abi;
pub mod safe_signer;
use alloy::{
consensus::TxEip1559,
primitives::{TxKind, U256},
};
use chrono::Utc;
use diesel::{ExpressionMethods as _, QueryDsl as _, QueryResult, insert_into, sqlite::Sqlite};
use diesel_async::{AsyncConnection, RunQueryDsl};
use kameo::actor::ActorRef;
use crate::{ use crate::{
actors::vault::Vault, actors::vault::Vault,
crypto::integrity, crypto::integrity,
@@ -27,6 +15,18 @@ use crate::{
}, },
}; };
use alloy::{
consensus::TxEip1559,
primitives::{TxKind, U256},
};
use chrono::Utc;
use diesel::{ExpressionMethods as _, QueryDsl as _, QueryResult, insert_into, sqlite::Sqlite};
use diesel_async::{AsyncConnection, RunQueryDsl};
use kameo::actor::ActorRef;
pub mod abi;
pub mod safe_signer;
pub mod policies; pub mod policies;
mod utils; mod utils;

View File

@@ -1,4 +1,8 @@
use std::fmt::Display; use crate::{
crypto::integrity::v1::Integrable,
db::models::{self, EvmBasicGrant, EvmWalletAccess},
evm::utils,
};
use alloy::primitives::{Address, Bytes, ChainId, U256}; use alloy::primitives::{Address, Bytes, ChainId, U256};
use chrono::{DateTime, Duration, Utc}; use chrono::{DateTime, Duration, Utc};
@@ -6,15 +10,9 @@ use diesel::{
ExpressionMethods as _, QueryDsl, SelectableHelper, result::QueryResult, sqlite::Sqlite, ExpressionMethods as _, QueryDsl, SelectableHelper, result::QueryResult, sqlite::Sqlite,
}; };
use diesel_async::{AsyncConnection, RunQueryDsl}; use diesel_async::{AsyncConnection, RunQueryDsl};
use std::fmt::Display;
use thiserror::Error; use thiserror::Error;
use crate::{
crypto::integrity::v1::Integrable,
db::models::{self, EvmBasicGrant, EvmWalletAccess},
evm::utils,
};
pub mod ether_transfer; pub mod ether_transfer;
pub mod token_transfers; pub mod token_transfers;

View File

@@ -1,30 +1,33 @@
use std::collections::HashMap; use super::{DatabaseID, EvalContext, EvalViolation};
use std::fmt::Display;
use alloy::primitives::{Address, U256};
use chrono::{DateTime, Duration, Utc};
use diesel::dsl::{auto_type, insert_into};
use diesel::sqlite::Sqlite;
use diesel::{ExpressionMethods, JoinOnDsl, prelude::*};
use diesel_async::{AsyncConnection, RunQueryDsl};
use crate::crypto::integrity::v1::Integrable;
use crate::db::models::{
EvmBasicGrant, EvmEtherTransferGrant, EvmEtherTransferGrantTarget, EvmEtherTransferLimit,
NewEvmEtherTransferLimit, SqliteTimestamp,
};
use crate::db::schema::{evm_basic_grant, evm_ether_transfer_limit, evm_transaction_log};
use crate::evm::policies::{
CombinedSettings, Grant, SharedGrantSettings, SpecificGrant, SpecificMeaning, VolumeRateLimit,
};
use crate::{ use crate::{
crypto::integrity::v1::Integrable,
db::models::{
EvmBasicGrant, EvmEtherTransferGrant, EvmEtherTransferGrantTarget, EvmEtherTransferLimit,
NewEvmEtherTransferLimit, SqliteTimestamp,
},
db::schema::{evm_basic_grant, evm_ether_transfer_limit, evm_transaction_log},
db::{ db::{
models::{self, NewEvmEtherTransferGrant, NewEvmEtherTransferGrantTarget}, models::{self, NewEvmEtherTransferGrant, NewEvmEtherTransferGrantTarget},
schema::{evm_ether_transfer_grant, evm_ether_transfer_grant_target}, schema::{evm_ether_transfer_grant, evm_ether_transfer_grant_target},
}, },
evm::policies::{
CombinedSettings, Grant, SharedGrantSettings, SpecificGrant, SpecificMeaning,
VolumeRateLimit,
},
evm::{policies::Policy, utils}, evm::{policies::Policy, utils},
}; };
use alloy::primitives::{Address, U256};
use chrono::{DateTime, Duration, Utc};
use diesel::{
ExpressionMethods, JoinOnDsl,
dsl::{auto_type, insert_into},
prelude::*,
sqlite::Sqlite,
};
use diesel_async::{AsyncConnection, RunQueryDsl};
use std::{collections::HashMap, fmt::Display};
#[auto_type] #[auto_type]
fn grant_join() -> _ { fn grant_join() -> _ {
evm_ether_transfer_grant::table.inner_join( evm_ether_transfer_grant::table.inner_join(
@@ -32,8 +35,6 @@ fn grant_join() -> _ {
) )
} }
use super::{DatabaseID, EvalContext, EvalViolation};
// Plain ether transfer // Plain ether transfer
#[derive(Clone, Debug, PartialEq, Eq, Hash)] #[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Meaning { pub struct Meaning {

View File

@@ -1,25 +1,26 @@
use super::{EtherTransfer, Settings};
use crate::{
db::{
self, DatabaseConnection,
models::{
EvmBasicGrant, EvmWalletAccess, NewEvmBasicGrant, NewEvmTransactionLog, SqliteTimestamp,
},
schema::{evm_basic_grant, evm_transaction_log},
},
evm::{
policies::{
CombinedSettings, EvalContext, EvalViolation, Grant, Policy, SharedGrantSettings,
VolumeRateLimit,
},
utils,
},
};
use alloy::primitives::{Address, Bytes, U256, address}; use alloy::primitives::{Address, Bytes, U256, address};
use chrono::{Duration, Utc}; use chrono::{Duration, Utc};
use diesel::{SelectableHelper, insert_into}; use diesel::{SelectableHelper, insert_into};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
use crate::db::{
self, DatabaseConnection,
models::{
EvmBasicGrant, EvmWalletAccess, NewEvmBasicGrant, NewEvmTransactionLog, SqliteTimestamp,
},
schema::{evm_basic_grant, evm_transaction_log},
};
use crate::evm::{
policies::{
CombinedSettings, EvalContext, EvalViolation, Grant, Policy, SharedGrantSettings,
VolumeRateLimit,
},
utils,
};
use super::{EtherTransfer, Settings};
const WALLET_ACCESS_ID: i32 = 1; const WALLET_ACCESS_ID: i32 = 1;
const CHAIN_ID: u64 = 1; const CHAIN_ID: u64 = 1;

View File

@@ -1,16 +1,4 @@
use std::collections::HashMap; use super::{DatabaseID, EvalContext, EvalViolation};
use crate::db::schema::{
evm_basic_grant, evm_token_transfer_grant, evm_token_transfer_log,
evm_token_transfer_volume_limit,
};
use crate::evm::{
abi::IERC20::transferCall,
policies::{
Grant, Policy, SharedGrantSettings, SpecificGrant, SpecificMeaning, VolumeRateLimit,
},
utils,
};
use crate::{ use crate::{
crypto::integrity::Integrable, crypto::integrity::Integrable,
db::models::{ db::models::{
@@ -18,20 +6,34 @@ use crate::{
NewEvmTokenTransferGrant, NewEvmTokenTransferLog, NewEvmTokenTransferVolumeLimit, NewEvmTokenTransferGrant, NewEvmTokenTransferLog, NewEvmTokenTransferVolumeLimit,
SqliteTimestamp, SqliteTimestamp,
}, },
db::schema::{
evm_basic_grant, evm_token_transfer_grant, evm_token_transfer_log,
evm_token_transfer_volume_limit,
},
evm::policies::CombinedSettings, evm::policies::CombinedSettings,
evm::{
abi::IERC20::transferCall,
policies::{
Grant, Policy, SharedGrantSettings, SpecificGrant, SpecificMeaning, VolumeRateLimit,
},
utils,
},
}; };
use arbiter_tokens_registry::evm::nonfungible::{self, TokenInfo};
use alloy::{ use alloy::{
primitives::{Address, U256}, primitives::{Address, U256},
sol_types::SolCall, sol_types::SolCall,
}; };
use arbiter_tokens_registry::evm::nonfungible::{self, TokenInfo};
use chrono::{DateTime, Duration, Utc}; use chrono::{DateTime, Duration, Utc};
use diesel::dsl::{auto_type, insert_into}; use diesel::{
use diesel::sqlite::Sqlite; ExpressionMethods,
use diesel::{ExpressionMethods, prelude::*}; dsl::{auto_type, insert_into},
prelude::*,
sqlite::Sqlite,
};
use diesel_async::{AsyncConnection, RunQueryDsl}; use diesel_async::{AsyncConnection, RunQueryDsl};
use std::collections::HashMap;
use super::{DatabaseID, EvalContext, EvalViolation};
#[auto_type] #[auto_type]
fn grant_join() -> _ { fn grant_join() -> _ {

View File

@@ -1,25 +1,28 @@
use alloy::primitives::{Address, Bytes, U256, address}; use super::{Settings, TokenTransfer};
use alloy::sol_types::SolCall; use crate::{
db::{
self, DatabaseConnection,
models::{EvmBasicGrant, EvmWalletAccess, NewEvmBasicGrant, SqliteTimestamp},
schema::evm_basic_grant,
},
evm::{
abi::IERC20::transferCall,
policies::{
CombinedSettings, EvalContext, EvalViolation, Grant, Policy, SharedGrantSettings,
VolumeRateLimit,
},
utils,
},
};
use alloy::{
primitives::{Address, Bytes, U256, address},
sol_types::SolCall,
};
use chrono::{Duration, Utc}; use chrono::{Duration, Utc};
use diesel::{SelectableHelper, insert_into}; use diesel::{SelectableHelper, insert_into};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
use crate::db::{
self, DatabaseConnection,
models::{EvmBasicGrant, EvmWalletAccess, NewEvmBasicGrant, SqliteTimestamp},
schema::evm_basic_grant,
};
use crate::evm::{
abi::IERC20::transferCall,
policies::{
CombinedSettings, EvalContext, EvalViolation, Grant, Policy, SharedGrantSettings,
VolumeRateLimit,
},
utils,
};
use super::{Settings, TokenTransfer};
// DAI on Ethereum mainnet — present in the static token registry // DAI on Ethereum mainnet — present in the static token registry
const CHAIN_ID: u64 = 1; const CHAIN_ID: u64 = 1;
const DAI: Address = address!("6B175474E89094C44Da98b954EedeAC495271d0F"); const DAI: Address = address!("6B175474E89094C44Da98b954EedeAC495271d0F");

View File

@@ -1,4 +1,4 @@
use std::sync::Mutex; use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _};
use alloy::{ use alloy::{
consensus::SignableTransaction, consensus::SignableTransaction,
@@ -6,9 +6,9 @@ use alloy::{
primitives::{Address, B256, ChainId, Signature}, primitives::{Address, B256, ChainId, Signature},
signers::{Error, Result, Signer, SignerSync, utils::secret_key_to_address}, signers::{Error, Result, Signer, SignerSync, utils::secret_key_to_address},
}; };
use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _};
use async_trait::async_trait; use async_trait::async_trait;
use k256::ecdsa::{self, RecoveryId, SigningKey, signature::hazmat::PrehashSigner}; use k256::ecdsa::{self, RecoveryId, SigningKey, signature::hazmat::PrehashSigner};
use std::sync::Mutex;
/// An Ethereum signer that stores its secp256k1 secret key inside a /// An Ethereum signer that stores its secp256k1 secret key inside a
/// hardware-protected [`MemSafe`] cell. /// hardware-protected [`MemSafe`] cell.

View File

@@ -2,20 +2,20 @@ use alloy::primitives::U256;
#[derive(thiserror::Error, Debug)] #[derive(thiserror::Error, Debug)]
#[error("Expected {expected} bytes but got {actual} bytes")] #[error("Expected {expected} bytes but got {actual} bytes")]
pub struct LengthError { pub(super) struct LengthError {
pub expected: usize, pub(super) expected: usize,
pub actual: usize, pub(super) actual: usize,
} }
pub fn u256_to_bytes(value: U256) -> [u8; 32] { pub(super) fn u256_to_bytes(value: U256) -> [u8; 32] {
value.to_le_bytes() value.to_le_bytes()
} }
pub fn bytes_to_u256(bytes: &[u8]) -> Option<U256> { pub(super) fn bytes_to_u256(bytes: &[u8]) -> Option<U256> {
let bytes: [u8; 32] = bytes.try_into().ok()?; let bytes: [u8; 32] = bytes.try_into().ok()?;
Some(U256::from_le_bytes(bytes)) Some(U256::from_le_bytes(bytes))
} }
pub fn try_bytes_to_u256(bytes: &[u8]) -> diesel::result::QueryResult<U256> { pub(super) fn try_bytes_to_u256(bytes: &[u8]) -> diesel::result::QueryResult<U256> {
let bytes: [u8; 32] = bytes.try_into().map_err(|_| { let bytes: [u8; 32] = bytes.try_into().map_err(|_| {
diesel::result::Error::DeserializationError(Box::new(LengthError { diesel::result::Error::DeserializationError(Box::new(LengthError {
expected: 32, expected: 32,

View File

@@ -1,3 +1,7 @@
use crate::{
grpc::request_tracker::RequestTracker,
peers::client::{ClientConnection, session::ClientSession},
};
use arbiter_proto::{ use arbiter_proto::{
proto::client::{ proto::client::{
ClientRequest, ClientResponse, client_request::Payload as ClientRequestPayload, ClientRequest, ClientResponse, client_request::Payload as ClientRequestPayload,
@@ -5,15 +9,11 @@ use arbiter_proto::{
}, },
transport::{Receiver, Sender, grpc::GrpcBi}, transport::{Receiver, Sender, grpc::GrpcBi},
}; };
use kameo::actor::{ActorRef, Spawn as _}; use kameo::actor::{ActorRef, Spawn as _};
use tonic::Status; use tonic::Status;
use tracing::{info, warn}; use tracing::{info, warn};
use crate::{
grpc::request_tracker::RequestTracker,
peers::client::{ClientConnection, session::ClientSession},
};
mod auth; mod auth;
mod evm; mod evm;
mod inbound; mod inbound;

View File

@@ -1,3 +1,7 @@
use crate::{
grpc::request_tracker::RequestTracker,
peers::client::{self, ClientConnection, auth},
};
use arbiter_crypto::authn; use arbiter_crypto::authn;
use arbiter_proto::{ use arbiter_proto::{
ClientMetadata, ClientMetadata,
@@ -17,22 +21,18 @@ use arbiter_proto::{
}, },
transport::{Bi, Error as TransportError, Receiver, Sender, grpc::GrpcBi}, transport::{Bi, Error as TransportError, Receiver, Sender, grpc::GrpcBi},
}; };
use async_trait::async_trait; use async_trait::async_trait;
use tonic::Status; use tonic::Status;
use tracing::warn; use tracing::warn;
use crate::{ pub(super) struct AuthTransportAdapter<'a> {
grpc::request_tracker::RequestTracker,
peers::client::{self, ClientConnection, auth},
};
pub struct AuthTransportAdapter<'a> {
bi: &'a mut GrpcBi<ClientRequest, ClientResponse>, bi: &'a mut GrpcBi<ClientRequest, ClientResponse>,
request_tracker: &'a mut RequestTracker, request_tracker: &'a mut RequestTracker,
} }
impl<'a> AuthTransportAdapter<'a> { impl<'a> AuthTransportAdapter<'a> {
pub fn new( pub(super) fn new(
bi: &'a mut GrpcBi<ClientRequest, ClientResponse>, bi: &'a mut GrpcBi<ClientRequest, ClientResponse>,
request_tracker: &'a mut RequestTracker, request_tracker: &'a mut RequestTracker,
) -> Self { ) -> Self {
@@ -44,7 +44,7 @@ impl<'a> AuthTransportAdapter<'a> {
fn response_to_proto(response: auth::Outbound) -> AuthResponsePayload { fn response_to_proto(response: auth::Outbound) -> AuthResponsePayload {
match response { match response {
auth::Outbound::AuthChallenge { challenge } => { auth::Outbound::AuthChallenge { challenge } => {
AuthResponsePayload::Challenge(ProtoAuthChallenge { AuthResponsePayload::Challenge(ProtoAuthChallenge {
timestamp_nanos: challenge timestamp_nanos: challenge
.timestamp .timestamp
@@ -197,7 +197,7 @@ fn client_metadata_from_proto(metadata: ProtoClientInfo) -> ClientMetadata {
} }
} }
pub async fn start( pub(super) async fn start(
conn: &mut ClientConnection, conn: &mut ClientConnection,
bi: &mut GrpcBi<ClientRequest, ClientResponse>, bi: &mut GrpcBi<ClientRequest, ClientResponse>,
request_tracker: &mut RequestTracker, request_tracker: &mut RequestTracker,

View File

@@ -1,3 +1,10 @@
use crate::{
grpc::{
Convert, TryConvert,
common::inbound::{RawEvmAddress, RawEvmTransaction},
},
peers::client::session::{ClientSession, HandleSignTransaction, SignTransactionRpcError},
};
use arbiter_proto::proto::{ use arbiter_proto::proto::{
client::{ client::{
client_response::Payload as ClientResponsePayload, client_response::Payload as ClientResponsePayload,
@@ -11,18 +18,11 @@ use arbiter_proto::proto::{
evm_sign_transaction_response::Result as EvmSignTransactionResult, evm_sign_transaction_response::Result as EvmSignTransactionResult,
}, },
}; };
use kameo::actor::ActorRef; use kameo::actor::ActorRef;
use tonic::Status; use tonic::Status;
use tracing::warn; use tracing::warn;
use crate::{
grpc::{
Convert, TryConvert,
common::inbound::{RawEvmAddress, RawEvmTransaction},
},
peers::client::session::{ClientSession, HandleSignTransaction, SignTransactionRpcError},
};
fn wrap_response(payload: EvmResponsePayload) -> ClientResponsePayload { fn wrap_response(payload: EvmResponsePayload) -> ClientResponsePayload {
ClientResponsePayload::Evm(proto_evm::Response { ClientResponsePayload::Evm(proto_evm::Response {
payload: Some(payload), payload: Some(payload),

View File

@@ -1,3 +1,7 @@
use crate::{
actors::vault::VaultState,
peers::client::session::{ClientSession, Error, HandleQueryVaultState},
};
use arbiter_proto::proto::{ use arbiter_proto::proto::{
client::{ client::{
client_response::Payload as ClientResponsePayload, client_response::Payload as ClientResponsePayload,
@@ -8,15 +12,11 @@ use arbiter_proto::proto::{
}, },
shared::VaultState as ProtoVaultState, shared::VaultState as ProtoVaultState,
}; };
use kameo::{actor::ActorRef, error::SendError}; use kameo::{actor::ActorRef, error::SendError};
use tonic::Status; use tonic::Status;
use tracing::warn; use tracing::warn;
use crate::{
actors::vault::VaultState,
peers::client::session::{ClientSession, Error, HandleQueryVaultState},
};
pub(super) async fn dispatch( pub(super) async fn dispatch(
actor: &ActorRef<ClientSession>, actor: &ActorRef<ClientSession>,
req: proto_vault::Request, req: proto_vault::Request,

View File

@@ -1,2 +1,2 @@
pub mod inbound; pub(super) mod inbound;
pub mod outbound; pub(super) mod outbound;

View File

@@ -1,8 +1,8 @@
use alloy::{consensus::TxEip1559, primitives::Address, rlp::Decodable as _};
use crate::grpc::TryConvert; use crate::grpc::TryConvert;
pub struct RawEvmAddress(pub Vec<u8>); use alloy::{consensus::TxEip1559, primitives::Address, rlp::Decodable as _};
pub(in crate::grpc) struct RawEvmAddress(pub(in crate::grpc) Vec<u8>);
impl TryConvert for RawEvmAddress { impl TryConvert for RawEvmAddress {
type Output = Address; type Output = Address;
@@ -21,7 +21,7 @@ impl TryConvert for RawEvmAddress {
} }
} }
pub struct RawEvmTransaction(pub Vec<u8>); pub(in crate::grpc) struct RawEvmTransaction(pub(in crate::grpc) Vec<u8>);
impl TryConvert for RawEvmTransaction { impl TryConvert for RawEvmTransaction {
type Output = TxEip1559; type Output = TxEip1559;

View File

@@ -1,4 +1,10 @@
use alloy::primitives::U256; use crate::{
evm::{
PolicyError, VetError,
policies::{EvalViolation, SpecificMeaning},
},
grpc::Convert,
};
use arbiter_proto::proto::{ use arbiter_proto::proto::{
evm::{ evm::{
EvmError as ProtoEvmError, EvmError as ProtoEvmError,
@@ -14,13 +20,7 @@ use arbiter_proto::proto::{
}, },
}; };
use crate::{ use alloy::primitives::U256;
evm::{
PolicyError, VetError,
policies::{EvalViolation, SpecificMeaning},
},
grpc::Convert,
};
fn u256_to_proto_bytes(value: U256) -> Vec<u8> { fn u256_to_proto_bytes(value: U256) -> Vec<u8> {
value.to_be_bytes::<32>().to_vec() value.to_be_bytes::<32>().to_vec()

View File

@@ -1,3 +1,4 @@
use crate::peers::{client::ClientConnection, user_agent::UserAgentConnection};
use arbiter_proto::{ use arbiter_proto::{
proto::{ proto::{
client::{ClientRequest, ClientResponse}, client::{ClientRequest, ClientResponse},
@@ -5,14 +6,11 @@ use arbiter_proto::{
}, },
transport::grpc::GrpcBi, transport::grpc::GrpcBi,
}; };
use tokio_stream::wrappers::ReceiverStream; use tokio_stream::wrappers::ReceiverStream;
use tonic::{Request, Response, Status, async_trait}; use tonic::{Request, Response, Status, async_trait};
use tracing::info; use tracing::info;
use crate::{
peers::{client::ClientConnection, user_agent::UserAgentConnection},
};
mod request_tracker; mod request_tracker;
pub mod client; pub mod client;

View File

@@ -1,12 +1,12 @@
use tonic::Status; use tonic::Status;
#[derive(Default)] #[derive(Default)]
pub struct RequestTracker { pub(super) struct RequestTracker {
next_request_id: i32, next_request_id: i32,
} }
impl RequestTracker { impl RequestTracker {
pub fn request(&mut self, id: i32) -> Result<i32, Status> { pub(super) fn request(&mut self, id: i32) -> Result<i32, Status> {
if id < self.next_request_id { if id < self.next_request_id {
return Err(Status::invalid_argument("Duplicate request id")); return Err(Status::invalid_argument("Duplicate request id"));
} }
@@ -20,7 +20,7 @@ impl RequestTracker {
// This is used to set the response id for auth responses, which need to match the request id of the auth challenge request. // This is used to set the response id for auth responses, which need to match the request id of the auth challenge request.
// -1 offset is needed because request() increments the next_request_id after returning the current request id. // -1 offset is needed because request() increments the next_request_id after returning the current request id.
pub fn current_request_id(&self) -> i32 { pub(super) fn current_request_id(&self) -> i32 {
self.next_request_id - 1 self.next_request_id - 1
} }
} }

View File

@@ -1,5 +1,7 @@
use tokio::sync::mpsc; use crate::{
grpc::request_tracker::RequestTracker,
peers::user_agent::{OutOfBand, UserAgentConnection, UserAgentSession},
};
use arbiter_proto::{ use arbiter_proto::{
proto::user_agent::{ proto::user_agent::{
UserAgentRequest, UserAgentResponse, UserAgentRequest, UserAgentResponse,
@@ -8,16 +10,13 @@ use arbiter_proto::{
}, },
transport::{Error as TransportError, Receiver, Sender, grpc::GrpcBi}, transport::{Error as TransportError, Receiver, Sender, grpc::GrpcBi},
}; };
use async_trait::async_trait; use async_trait::async_trait;
use kameo::actor::ActorRef; use kameo::actor::ActorRef;
use tokio::sync::mpsc;
use tonic::Status; use tonic::Status;
use tracing::{error, info, warn}; use tracing::{error, info, warn};
use crate::{
grpc::request_tracker::RequestTracker,
peers::user_agent::{OutOfBand, UserAgentConnection, UserAgentSession},
};
mod auth; mod auth;
mod evm; mod evm;
mod inbound; mod inbound;
@@ -144,4 +143,3 @@ pub async fn start(
dispatch_loop(bi, actor.clone(), oob_receiver, request_tracker).await; dispatch_loop(bi, actor.clone(), oob_receiver, request_tracker).await;
actor.kill(); actor.kill();
} }

View File

@@ -1,3 +1,4 @@
use crate::{grpc::request_tracker::RequestTracker, peers::user_agent::auth};
use arbiter_crypto::authn; use arbiter_crypto::authn;
use arbiter_proto::{ use arbiter_proto::{
proto::user_agent::{ proto::user_agent::{
@@ -13,22 +14,18 @@ use arbiter_proto::{
}, },
transport::{Bi, Error as TransportError, Receiver, Sender, grpc::GrpcBi}, transport::{Bi, Error as TransportError, Receiver, Sender, grpc::GrpcBi},
}; };
use async_trait::async_trait; use async_trait::async_trait;
use tonic::Status; use tonic::Status;
use tracing::warn; use tracing::warn;
use crate::{ pub(super) struct AuthTransportAdapter<'a> {
grpc::request_tracker::RequestTracker,
peers::user_agent::{Credentials, UserAgentConnection, auth},
};
pub struct AuthTransportAdapter<'a> {
pub(super) bi: &'a mut GrpcBi<UserAgentRequest, UserAgentResponse>, pub(super) bi: &'a mut GrpcBi<UserAgentRequest, UserAgentResponse>,
pub(super) request_tracker: &'a mut RequestTracker, pub(super) request_tracker: &'a mut RequestTracker,
} }
impl<'a> AuthTransportAdapter<'a> { impl<'a> AuthTransportAdapter<'a> {
pub fn new( pub(super) fn new(
bi: &'a mut GrpcBi<UserAgentRequest, UserAgentResponse>, bi: &'a mut GrpcBi<UserAgentRequest, UserAgentResponse>,
request_tracker: &'a mut RequestTracker, request_tracker: &'a mut RequestTracker,
) -> Self { ) -> Self {
@@ -185,12 +182,3 @@ impl Receiver<auth::Inbound> for AuthTransportAdapter<'_> {
} }
impl Bi<auth::Inbound, Result<auth::Outbound, auth::Error>> for AuthTransportAdapter<'_> {} impl Bi<auth::Inbound, Result<auth::Outbound, auth::Error>> for AuthTransportAdapter<'_> {}
pub async fn start(
conn: &mut UserAgentConnection,
bi: &mut GrpcBi<UserAgentRequest, UserAgentResponse>,
request_tracker: &mut RequestTracker,
) -> Result<Credentials, auth::Error> {
let mut transport = AuthTransportAdapter::new(bi, request_tracker);
auth::authenticate(conn, &mut transport).await
}

View File

@@ -1,3 +1,17 @@
use crate::{
grpc::{
Convert, TryConvert,
common::inbound::{RawEvmAddress, RawEvmTransaction},
},
peers::user_agent::{
UserAgentSession,
session::handlers::{
GrantMutationError, HandleEvmWalletCreate, HandleEvmWalletList, HandleGrantCreate,
HandleGrantDelete, HandleGrantList, HandleSignTransaction,
SignTransactionError as SessionSignTransactionError,
},
},
};
use arbiter_proto::proto::{ use arbiter_proto::proto::{
evm::{ evm::{
EvmError as ProtoEvmError, EvmGrantCreateRequest, EvmGrantCreateResponse, EvmError as ProtoEvmError, EvmGrantCreateRequest, EvmGrantCreateResponse,
@@ -18,25 +32,11 @@ use arbiter_proto::proto::{
user_agent_response::Payload as UserAgentResponsePayload, user_agent_response::Payload as UserAgentResponsePayload,
}, },
}; };
use kameo::actor::ActorRef; use kameo::actor::ActorRef;
use tonic::Status; use tonic::Status;
use tracing::warn; use tracing::warn;
use crate::{
grpc::{
Convert, TryConvert,
common::inbound::{RawEvmAddress, RawEvmTransaction},
},
peers::user_agent::{
UserAgentSession,
session::handlers::{
GrantMutationError, HandleEvmWalletCreate, HandleEvmWalletList, HandleGrantCreate,
HandleGrantDelete, HandleGrantList, HandleSignTransaction,
SignTransactionError as SessionSignTransactionError,
},
},
};
fn wrap_evm_response(payload: EvmResponsePayload) -> UserAgentResponsePayload { fn wrap_evm_response(payload: EvmResponsePayload) -> UserAgentResponsePayload {
UserAgentResponsePayload::Evm(proto_evm::Response { UserAgentResponsePayload::Evm(proto_evm::Response {
payload: Some(payload), payload: Some(payload),

View File

@@ -1,26 +1,26 @@
use alloy::primitives::{Address, U256};
use arbiter_proto::proto::evm::{
EtherTransferSettings as ProtoEtherTransferSettings, SharedSettings as ProtoSharedSettings,
SpecificGrant as ProtoSpecificGrant, TokenTransferSettings as ProtoTokenTransferSettings,
TransactionRateLimit as ProtoTransactionRateLimit, VolumeRateLimit as ProtoVolumeRateLimit,
specific_grant::Grant as ProtoSpecificGrantType,
};
use arbiter_proto::proto::user_agent::sdk_client::{
WalletAccess, WalletAccessEntry as SdkClientWalletAccess,
};
use chrono::{DateTime, TimeZone, Utc};
use prost_types::Timestamp as ProtoTimestamp;
use tonic::Status;
use crate::db::models::{CoreEvmWalletAccess, NewEvmWalletAccess};
use crate::grpc::Convert;
use crate::{ use crate::{
db::models::{CoreEvmWalletAccess, NewEvmWalletAccess},
evm::policies::{ evm::policies::{
SharedGrantSettings, SpecificGrant, TransactionRateLimit, VolumeRateLimit, ether_transfer, SharedGrantSettings, SpecificGrant, TransactionRateLimit, VolumeRateLimit, ether_transfer,
token_transfers, token_transfers,
}, },
grpc::Convert,
grpc::TryConvert, grpc::TryConvert,
}; };
use arbiter_proto::{
proto::evm::{
EtherTransferSettings as ProtoEtherTransferSettings, SharedSettings as ProtoSharedSettings,
SpecificGrant as ProtoSpecificGrant, TokenTransferSettings as ProtoTokenTransferSettings,
TransactionRateLimit as ProtoTransactionRateLimit, VolumeRateLimit as ProtoVolumeRateLimit,
specific_grant::Grant as ProtoSpecificGrantType,
},
proto::user_agent::sdk_client::{WalletAccess, WalletAccessEntry as SdkClientWalletAccess},
};
use alloy::primitives::{Address, U256};
use chrono::{DateTime, TimeZone, Utc};
use prost_types::Timestamp as ProtoTimestamp;
use tonic::Status;
fn address_from_bytes(bytes: Vec<u8>) -> Result<Address, Status> { fn address_from_bytes(bytes: Vec<u8>) -> Result<Address, Status> {
if bytes.len() != 20 { if bytes.len() != 20 {

View File

@@ -1,3 +1,8 @@
use crate::{
db::models::EvmWalletAccess,
evm::policies::{SharedGrantSettings, SpecificGrant, TransactionRateLimit, VolumeRateLimit},
grpc::Convert,
};
use arbiter_proto::proto::{ use arbiter_proto::proto::{
evm::{ evm::{
EtherTransferSettings as ProtoEtherTransferSettings, SharedSettings as ProtoSharedSettings, EtherTransferSettings as ProtoEtherTransferSettings, SharedSettings as ProtoSharedSettings,
@@ -7,15 +12,10 @@ use arbiter_proto::proto::{
}, },
user_agent::sdk_client::{WalletAccess, WalletAccessEntry as ProtoSdkClientWalletAccess}, user_agent::sdk_client::{WalletAccess, WalletAccessEntry as ProtoSdkClientWalletAccess},
}; };
use chrono::{DateTime, Utc}; use chrono::{DateTime, Utc};
use prost_types::Timestamp as ProtoTimestamp; use prost_types::Timestamp as ProtoTimestamp;
use crate::{
db::models::EvmWalletAccess,
evm::policies::{SharedGrantSettings, SpecificGrant, TransactionRateLimit, VolumeRateLimit},
grpc::Convert,
};
impl Convert for DateTime<Utc> { impl Convert for DateTime<Utc> {
type Output = ProtoTimestamp; type Output = ProtoTimestamp;

View File

@@ -1,3 +1,14 @@
use crate::{
db::models::NewEvmWalletAccess,
grpc::Convert,
peers::user_agent::{
OutOfBand, UserAgentSession,
session::handlers::{
HandleGrantEvmWalletAccess, HandleListWalletAccess, HandleNewClientApprove,
HandleRevokeEvmWalletAccess, HandleSdkClientList,
},
},
};
use arbiter_crypto::authn; use arbiter_crypto::authn;
use arbiter_proto::proto::{ use arbiter_proto::proto::{
shared::ClientInfo as ProtoClientMetadata, shared::ClientInfo as ProtoClientMetadata,
@@ -16,22 +27,11 @@ use arbiter_proto::proto::{
user_agent_response::Payload as UserAgentResponsePayload, user_agent_response::Payload as UserAgentResponsePayload,
}, },
}; };
use kameo::actor::ActorRef; use kameo::actor::ActorRef;
use tonic::Status; use tonic::Status;
use tracing::{info, warn}; use tracing::{info, warn};
use crate::{
db::models::NewEvmWalletAccess,
grpc::Convert,
peers::user_agent::{
OutOfBand, UserAgentSession,
session::handlers::{
HandleGrantEvmWalletAccess, HandleListWalletAccess, HandleNewClientApprove,
HandleRevokeEvmWalletAccess, HandleSdkClientList,
},
},
};
fn wrap_sdk_client_response(payload: SdkClientResponsePayload) -> UserAgentResponsePayload { fn wrap_sdk_client_response(payload: SdkClientResponsePayload) -> UserAgentResponsePayload {
UserAgentResponsePayload::SdkClient(proto_sdk_client::Response { UserAgentResponsePayload::SdkClient(proto_sdk_client::Response {
payload: Some(payload), payload: Some(payload),

View File

@@ -1,16 +1,21 @@
use arbiter_proto::proto::shared::VaultState as ProtoVaultState;
use arbiter_proto::proto::user_agent::{
user_agent_response::Payload as UserAgentResponsePayload,
vault::{self as proto_vault, request::Payload as VaultRequestPayload, response::Payload as VaultResponsePayload},
};
use kameo::actor::ActorRef;
use tonic::Status;
use tracing::warn;
use crate::{ use crate::{
actors::vault::VaultState, actors::vault::VaultState,
peers::user_agent::{UserAgentSession, session::handlers::HandleQueryVaultState}, peers::user_agent::{UserAgentSession, session::handlers::HandleQueryVaultState},
}; };
use arbiter_proto::{
proto::shared::VaultState as ProtoVaultState,
proto::user_agent::{
user_agent_response::Payload as UserAgentResponsePayload,
vault::{
self as proto_vault, request::Payload as VaultRequestPayload,
response::Payload as VaultResponsePayload,
},
},
};
use kameo::actor::ActorRef;
use tonic::Status;
use tracing::warn;
fn wrap_vault_response(payload: VaultResponsePayload) -> UserAgentResponsePayload { fn wrap_vault_response(payload: VaultResponsePayload) -> UserAgentResponsePayload {
UserAgentResponsePayload::Vault(proto_vault::Response { UserAgentResponsePayload::Vault(proto_vault::Response {

View File

@@ -1,13 +1,13 @@
use arbiter_proto::transport::{Bi, Error as TransportError, Receiver, Sender};
use async_trait::async_trait;
use tonic::Status;
use tracing::warn;
use super::auth::AuthTransportAdapter; use super::auth::AuthTransportAdapter;
use crate::{ use crate::{
grpc::TryConvert, grpc::TryConvert,
peers::user_agent::vault_gate::{self as vault_gate}, peers::user_agent::vault_gate::{self as vault_gate},
}; };
use arbiter_proto::transport::{Bi, Error as TransportError, Receiver, Sender};
use async_trait::async_trait;
use tonic::Status;
use tracing::warn;
mod inbound; mod inbound;
mod outbound; mod outbound;

View File

@@ -1,3 +1,9 @@
use crate::{
grpc::{Convert, TryConvert},
peers::user_agent::vault_gate::{
self as vault_gate, HandleBootstrapEncryptedKey, HandleHandshake, HandleUnsealEncryptedKey,
},
};
use arbiter_proto::proto::user_agent::{ use arbiter_proto::proto::user_agent::{
user_agent_request::Payload as UserAgentRequestPayload, user_agent_request::Payload as UserAgentRequestPayload,
vault::{ vault::{
@@ -7,14 +13,8 @@ use arbiter_proto::proto::user_agent::{
unseal::{self as proto_unseal, request::Payload as UnsealRequestPayload}, unseal::{self as proto_unseal, request::Payload as UnsealRequestPayload},
}, },
}; };
use tonic::Status;
use crate::{ use tonic::Status;
grpc::{Convert, TryConvert},
peers::user_agent::vault_gate::{
self as vault_gate, HandleBootstrapEncryptedKey, HandleHandshake, HandleUnsealEncryptedKey,
},
};
impl TryConvert for UserAgentRequestPayload { impl TryConvert for UserAgentRequestPayload {
type Output = vault_gate::Inbound; type Output = vault_gate::Inbound;

View File

@@ -1,3 +1,8 @@
use crate::{
actors::vault::VaultState,
grpc::{Convert, TryConvert},
peers::user_agent::vault_gate::{self as vault_gate},
};
use arbiter_proto::proto::{ use arbiter_proto::proto::{
shared::VaultState as ProtoVaultState, shared::VaultState as ProtoVaultState,
user_agent::{ user_agent::{
@@ -13,15 +18,10 @@ use arbiter_proto::proto::{
}, },
}, },
}; };
use tonic::Status; use tonic::Status;
use tracing::warn; use tracing::warn;
use crate::{
actors::vault::VaultState,
grpc::{Convert, TryConvert},
peers::user_agent::vault_gate::{self as vault_gate},
};
fn wrap_vault_response(payload: VaultResponsePayload) -> UserAgentResponsePayload { fn wrap_vault_response(payload: VaultResponsePayload) -> UserAgentResponsePayload {
UserAgentResponsePayload::Vault(proto_vault::Response { UserAgentResponsePayload::Vault(proto_vault::Response {
payload: Some(payload), payload: Some(payload),

View File

@@ -1,9 +1,9 @@
use std::net::SocketAddr;
use anyhow::anyhow;
use arbiter_proto::{proto::arbiter_service_server::ArbiterServiceServer, url::ArbiterUrl}; use arbiter_proto::{proto::arbiter_service_server::ArbiterServiceServer, url::ArbiterUrl};
use arbiter_server::{Server, actors::bootstrap::GetToken, context::ServerContext, db}; use arbiter_server::{Server, actors::bootstrap::GetToken, context::ServerContext, db};
use anyhow::anyhow;
use rustls::crypto::aws_lc_rs; use rustls::crypto::aws_lc_rs;
use std::net::SocketAddr;
use tonic::transport::{Identity, ServerTlsConfig}; use tonic::transport::{Identity, ServerTlsConfig};
use tracing::info; use tracing::info;

View File

@@ -1,17 +1,4 @@
use arbiter_crypto::authn::{self, AuthChallenge, CLIENT_CONTEXT}; use super::{ClientConnection, ClientCredentials, ClientProfile};
use arbiter_proto::{
ClientMetadata,
transport::{Bi, expect_message},
};
use chrono::Utc;
use diesel::{
ExpressionMethods as _, OptionalExtension as _, QueryDsl as _, SelectableHelper as _,
dsl::insert_into, update,
};
use diesel_async::RunQueryDsl as _;
use kameo::{actor::ActorRef, error::SendError};
use tracing::error;
use crate::{ use crate::{
actors::{ actors::{
GlobalActors, GlobalActors,
@@ -25,8 +12,20 @@ use crate::{
schema::program_client, schema::program_client,
}, },
}; };
use arbiter_crypto::authn::{self, AuthChallenge, CLIENT_CONTEXT};
use arbiter_proto::{
ClientMetadata,
transport::{Bi, expect_message},
};
use super::{ClientConnection, ClientCredentials, ClientProfile}; use chrono::Utc;
use diesel::{
ExpressionMethods as _, OptionalExtension as _, QueryDsl as _, SelectableHelper as _,
dsl::insert_into, update,
};
use diesel_async::RunQueryDsl as _;
use kameo::{actor::ActorRef, error::SendError};
use tracing::error;
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)] #[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
pub enum Error { pub enum Error {

View File

@@ -1,12 +1,12 @@
use arbiter_crypto::authn;
use arbiter_macros::Hashable;
use arbiter_proto::{ClientMetadata, transport::Bi};
use kameo::actor::Spawn;
use tracing::{error, info};
use crate::{ use crate::{
actors::GlobalActors, crypto::integrity::Integrable, db, peers::client::session::ClientSession, actors::GlobalActors, crypto::integrity::Integrable, db, peers::client::session::ClientSession,
}; };
use arbiter_crypto::authn;
use arbiter_macros::Hashable;
use arbiter_proto::{ClientMetadata, transport::Bi};
use kameo::actor::Spawn;
use tracing::{error, info};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ClientProfile { pub struct ClientProfile {

View File

@@ -1,8 +1,4 @@
use kameo::{Actor, messages}; use super::ClientConnection;
use tracing::error;
use alloy::{consensus::TxEip1559, primitives::Address, signers::Signature};
use crate::{ use crate::{
actors::{ actors::{
GlobalActors, GlobalActors,
@@ -14,7 +10,9 @@ use crate::{
evm::VetError, evm::VetError,
}; };
use super::ClientConnection; use alloy::{consensus::TxEip1559, primitives::Address, signers::Signature};
use kameo::{Actor, messages};
use tracing::error;
pub struct ClientSession { pub struct ClientSession {
props: ClientConnection, props: ClientConnection,

View File

@@ -1,12 +1,11 @@
use super::{Credentials, UserAgentConnection};
use arbiter_crypto::authn::{self, AuthChallenge}; use arbiter_crypto::authn::{self, AuthChallenge};
use arbiter_proto::transport::Bi; use arbiter_proto::transport::Bi;
use state::*;
use tracing::error; use tracing::error;
mod state; mod state;
use state::*;
use super::Credentials;
use super::UserAgentConnection;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum Inbound { pub enum Inbound {

View File

@@ -1,30 +1,32 @@
use super::super::{Credentials, UserAgentConnection}; use super::{
use arbiter_crypto::authn::{self, AuthChallenge, USERAGENT_CONTEXT}; super::{Credentials, UserAgentConnection},
use arbiter_proto::transport::Bi; Error,
use diesel::{ExpressionMethods as _, OptionalExtension as _, QueryDsl}; };
use diesel_async::RunQueryDsl;
use tracing::error;
use super::Error;
use crate::{ use crate::{
actors::bootstrap::ConsumeToken, actors::bootstrap::ConsumeToken,
db::{DatabasePool, schema::useragent_client}, db::{DatabasePool, schema::useragent_client},
peers::user_agent::auth::Outbound, peers::user_agent::auth::Outbound,
}; };
use arbiter_crypto::authn::{self, AuthChallenge, USERAGENT_CONTEXT};
use arbiter_proto::transport::Bi;
pub struct ChallengeRequest { use diesel::{ExpressionMethods as _, OptionalExtension as _, QueryDsl};
pub pubkey: authn::PublicKey, use diesel_async::RunQueryDsl;
pub bootstrap_token: Option<String>, use tracing::error;
pub(super) struct ChallengeRequest {
pub(super) pubkey: authn::PublicKey,
pub(super) bootstrap_token: Option<String>,
} }
pub struct ChallengeContext { pub(super) struct ChallengeContext {
pub challenge: AuthChallenge, pub(super) challenge: AuthChallenge,
pub pubkey: authn::PublicKey, pub(super) pubkey: authn::PublicKey,
pub bootstrap_token: Option<String>, pub(super) bootstrap_token: Option<String>,
} }
pub struct ChallengeSolution { pub(super) struct ChallengeSolution {
pub solution: Vec<u8>, pub(super) solution: Vec<u8>,
} }
smlang::statemachine!( smlang::statemachine!(
@@ -74,13 +76,13 @@ async fn register_key(db: &DatabasePool, pubkey: &authn::PublicKey) -> Result<i3
Ok(id) Ok(id)
} }
pub struct AuthContext<'a, T: ?Sized> { pub(super) struct AuthContext<'a, T: ?Sized> {
pub(super) conn: &'a mut UserAgentConnection, pub(super) conn: &'a mut UserAgentConnection,
pub(super) transport: &'a mut T, pub(super) transport: &'a mut T,
} }
impl<'a, T: ?Sized> AuthContext<'a, T> { impl<'a, T: ?Sized> AuthContext<'a, T> {
pub fn new(conn: &'a mut UserAgentConnection, transport: &'a mut T) -> Self { pub(super) fn new(conn: &'a mut UserAgentConnection, transport: &'a mut T) -> Self {
Self { conn, transport } Self { conn, transport }
} }
} }

View File

@@ -8,15 +8,16 @@ use crate::{
peers::client::ClientProfile, peers::client::ClientProfile,
}; };
use arbiter_crypto::authn; use arbiter_crypto::authn;
use arbiter_macros::Hashable; use arbiter_macros::Hashable;
use arbiter_proto::transport::{Bi, Sender}; use arbiter_proto::transport::{Bi, Sender};
pub use auth::authenticate; use vault_gate::VaultGate;
use kameo::actor::{ActorRef, Spawn as _}; use kameo::actor::{ActorRef, Spawn as _};
pub use session::UserAgentSession;
use tokio::sync::oneshot; use tokio::sync::oneshot;
use tracing::{error, warn}; use tracing::{error, warn};
use vault_gate::VaultGate;
pub use auth::authenticate;
pub use session::UserAgentSession;
pub mod auth; pub mod auth;
pub mod session; pub mod session;
@@ -179,7 +180,6 @@ where
Ok(UserAgentSession::spawn(UserAgentSession::new( Ok(UserAgentSession::spawn(UserAgentSession::new(
props.clone(), props.clone(),
creds,
oob_sender, oob_sender,
))) )))
} }

View File

@@ -1,32 +1,21 @@
use super::{Error, UserAgentSession};
use alloy::{consensus::TxEip1559, primitives::Address, signers::Signature}; use crate::{
use arbiter_crypto::{ actors::evm::{
authn,
safecell::SafeCellHandle as _,
};
use chacha20poly1305::aead::KeyInit;
use diesel::{ExpressionMethods as _, QueryDsl as _, SelectableHelper};
use diesel_async::{AsyncConnection, RunQueryDsl};
use kameo::error::SendError;
use kameo::messages;
use kameo::prelude::Context;
use tracing::error;
use crate::actors::flow_coordinator::client_connect_approval::ClientApprovalAnswer;
use crate::actors::evm::{
ClientSignTransaction, Generate, ListWallets, SignTransactionError as EvmSignError, ClientSignTransaction, Generate, ListWallets, SignTransactionError as EvmSignError,
UseragentCreateGrant, UseragentListGrants, UseragentCreateGrant, UseragentListGrants,
}; },
use crate::db::models::{ actors::flow_coordinator::client_connect_approval::ClientApprovalAnswer,
EvmWalletAccess, NewEvmWalletAccess, ProgramClient, ProgramClientMetadata,
};
use crate::evm::policies::{Grant, SpecificGrant};
use crate::{
actors::vault::VaultState, actors::vault::VaultState,
db::models::{EvmWalletAccess, NewEvmWalletAccess, ProgramClient, ProgramClientMetadata},
evm::policies::{Grant, SpecificGrant},
}; };
use arbiter_crypto::authn;
use super::{Error, UserAgentSession}; use alloy::{consensus::TxEip1559, primitives::Address, signers::Signature};
use diesel::{ExpressionMethods as _, QueryDsl as _, SelectableHelper};
use diesel_async::{AsyncConnection, RunQueryDsl};
use kameo::{error::SendError, messages, prelude::Context};
use tracing::error;
#[derive(Debug, Error)] #[derive(Debug, Error)]
pub enum SignTransactionError { pub enum SignTransactionError {

View File

@@ -1,21 +1,18 @@
use arbiter_crypto::authn; use super::{OutOfBand, UserAgentConnection};
use std::{borrow::Cow, collections::HashMap};
use arbiter_proto::transport::Sender;
use kameo::{Actor, actor::ActorRef, messages};
use thiserror::Error;
use tracing::error;
use crate::{ use crate::{
actors::{ actors::{
flow_coordinator::client_connect_approval::ClientApprovalController, flow_coordinator::client_connect_approval::ClientApprovalController,
useragent_registry::ConnectUseragent, useragent_registry::ConnectUseragent,
}, },
peers::{client::ClientProfile, user_agent::Credentials}, peers::client::ClientProfile,
}; };
use arbiter_crypto::authn;
use arbiter_proto::transport::Sender;
use super::{OutOfBand, UserAgentConnection}; use kameo::{Actor, actor::ActorRef, messages};
use std::{borrow::Cow, collections::HashMap};
use thiserror::Error;
use tracing::error;
#[derive(Debug, Error)] #[derive(Debug, Error)]
pub enum Error { pub enum Error {
@@ -53,7 +50,6 @@ pub struct PendingClientApproval {
} }
pub struct UserAgentSession { pub struct UserAgentSession {
creds: Credentials,
props: UserAgentConnection, props: UserAgentConnection,
sender: Box<dyn Sender<OutOfBand>>, sender: Box<dyn Sender<OutOfBand>>,
@@ -63,13 +59,8 @@ pub struct UserAgentSession {
pub mod handlers; pub mod handlers;
impl UserAgentSession { impl UserAgentSession {
pub(crate) fn new( pub(crate) fn new(props: UserAgentConnection, sender: Box<dyn Sender<OutOfBand>>) -> Self {
props: UserAgentConnection,
creds: Credentials,
sender: Box<dyn Sender<OutOfBand>>,
) -> Self {
Self { Self {
creds,
props, props,
sender, sender,
pending_client_approvals: Default::default(), pending_client_approvals: Default::default(),

View File

@@ -1,14 +1,3 @@
use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _};
use chacha20poly1305::{AeadInPlace, KeyInit as _, XChaCha20Poly1305, XNonce};
use kameo::{Actor, error::SendError, messages, prelude::Message};
use kameo_actors::message_bus::Register;
use tokio::sync::oneshot;
use tracing::{error, info};
use x25519_dalek::{EphemeralSecret, PublicKey, SharedSecret};
pub mod state;
use state::*;
use super::Credentials; use super::Credentials;
use crate::{ use crate::{
actors::{ actors::{
@@ -18,6 +7,17 @@ use crate::{
crypto::integrity::{self}, crypto::integrity::{self},
db::DatabasePool, db::DatabasePool,
}; };
use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _};
use state::*;
use chacha20poly1305::{AeadInPlace, KeyInit as _, XChaCha20Poly1305, XNonce};
use kameo::{Actor, error::SendError, messages, prelude::Message};
use kameo_actors::message_bus::Register;
use tokio::sync::oneshot;
use tracing::{error, info};
use x25519_dalek::{EphemeralSecret, PublicKey, SharedSecret};
pub mod state;
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum Error { pub enum Error {

View File

@@ -1,10 +1,5 @@
use x25519_dalek::{PublicKey, SharedSecret}; use x25519_dalek::{PublicKey, SharedSecret};
pub struct Handshake {
client_pubkey: PublicKey,
}
#[derive(Default)] #[derive(Default)]
pub enum State { pub enum State {
#[default] #[default]

View File

@@ -1,21 +1,23 @@
use super::common::ChannelTransport;
use arbiter_crypto::{ use arbiter_crypto::{
authn::{self, AuthChallenge, CLIENT_CONTEXT}, authn::{self, AuthChallenge, CLIENT_CONTEXT},
safecell::{SafeCell, SafeCellHandle as _}, safecell::{SafeCell, SafeCellHandle as _},
}; };
use arbiter_proto::ClientMetadata; use arbiter_proto::{
use arbiter_proto::transport::{Receiver, Sender}; ClientMetadata,
transport::{Receiver, Sender},
};
use arbiter_server::{ use arbiter_server::{
actors::{GlobalActors, vault::Bootstrap}, actors::{GlobalActors, vault::Bootstrap},
crypto::integrity, crypto::integrity,
db::{self, schema}, db::{self, schema},
peers::client::{ClientConnection, ClientCredentials, auth, connect_client}, peers::client::{ClientConnection, ClientCredentials, auth, connect_client},
}; };
use diesel::{ExpressionMethods as _, NullableExpressionMethods as _, QueryDsl as _, insert_into}; use diesel::{ExpressionMethods as _, NullableExpressionMethods as _, QueryDsl as _, insert_into};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
use ml_dsa::{KeyGen, MlDsa87, SigningKey, VerifyingKey, signature::Keypair as _}; use ml_dsa::{KeyGen, MlDsa87, SigningKey, VerifyingKey, signature::Keypair as _};
use super::common::ChannelTransport;
fn metadata(name: &str, description: Option<&str>, version: Option<&str>) -> ClientMetadata { fn metadata(name: &str, description: Option<&str>, version: Option<&str>) -> ClientMetadata {
ClientMetadata { ClientMetadata {
name: name.to_owned(), name: name.to_owned(),
@@ -103,7 +105,7 @@ async fn spawn_test_actors(db: &db::DatabasePool) -> GlobalActors {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
pub async fn test_unregistered_pubkey_rejected() { async fn test_unregistered_pubkey_rejected() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let (server_transport, mut test_transport) = ChannelTransport::new(); let (server_transport, mut test_transport) = ChannelTransport::new();
@@ -130,7 +132,7 @@ pub async fn test_unregistered_pubkey_rejected() {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
pub async fn test_challenge_auth() { async fn test_challenge_auth() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let actors = spawn_test_actors(&db).await; let actors = spawn_test_actors(&db).await;
@@ -197,7 +199,7 @@ pub async fn test_challenge_auth() {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
pub async fn test_metadata_unchanged_does_not_append_history() { async fn test_metadata_unchanged_does_not_append_history() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let actors = spawn_test_actors(&db).await; let actors = spawn_test_actors(&db).await;
let new_key = MlDsa87::key_gen(&mut rand::rng()); let new_key = MlDsa87::key_gen(&mut rand::rng());
@@ -254,7 +256,7 @@ pub async fn test_metadata_unchanged_does_not_append_history() {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
pub async fn test_metadata_change_appends_history_and_repoints_binding() { async fn test_metadata_change_appends_history_and_repoints_binding() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let actors = spawn_test_actors(&db).await; let actors = spawn_test_actors(&db).await;
let new_key = MlDsa87::key_gen(&mut rand::rng()); let new_key = MlDsa87::key_gen(&mut rand::rng());
@@ -341,7 +343,7 @@ pub async fn test_metadata_change_appends_history_and_repoints_binding() {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
pub async fn test_challenge_auth_rejects_integrity_tag_mismatch() { async fn test_challenge_auth_rejects_integrity_tag_mismatch() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let actors = spawn_test_actors(&db).await; let actors = spawn_test_actors(&db).await;

View File

@@ -11,7 +11,7 @@ use diesel_async::RunQueryDsl;
use tokio::sync::mpsc; use tokio::sync::mpsc;
#[allow(dead_code)] #[allow(dead_code)]
pub async fn bootstrapped_vault(db: &db::DatabasePool) -> Vault { pub(crate) async fn bootstrapped_vault(db: &db::DatabasePool) -> Vault {
let mut actor = Vault::new(db.clone(), GlobalActors::spawn_message_bus()) let mut actor = Vault::new(db.clone(), GlobalActors::spawn_message_bus())
.await .await
.unwrap(); .unwrap();
@@ -23,7 +23,7 @@ pub async fn bootstrapped_vault(db: &db::DatabasePool) -> Vault {
} }
#[allow(dead_code)] #[allow(dead_code)]
pub async fn root_key_history_id(db: &db::DatabasePool) -> i32 { pub(crate) async fn root_key_history_id(db: &db::DatabasePool) -> i32 {
let mut conn = db.get().await.unwrap(); let mut conn = db.get().await.unwrap();
let id = schema::arbiter_settings::table let id = schema::arbiter_settings::table
.select(schema::arbiter_settings::root_key_id) .select(schema::arbiter_settings::root_key_id)
@@ -34,14 +34,14 @@ pub async fn root_key_history_id(db: &db::DatabasePool) -> i32 {
} }
#[allow(dead_code)] #[allow(dead_code)]
pub struct ChannelTransport<T, Y> { pub(crate) struct ChannelTransport<T, Y> {
receiver: mpsc::Receiver<T>, receiver: mpsc::Receiver<T>,
sender: mpsc::Sender<Y>, sender: mpsc::Sender<Y>,
} }
impl<T, Y> ChannelTransport<T, Y> { impl<T, Y> ChannelTransport<T, Y> {
#[allow(dead_code)] #[allow(dead_code)]
pub fn new() -> (Self, ChannelTransport<Y, T>) { pub(crate) fn new() -> (Self, ChannelTransport<Y, T>) {
let (tx1, rx1) = mpsc::channel(10); let (tx1, rx1) = mpsc::channel(10);
let (tx2, rx2) = mpsc::channel(10); let (tx2, rx2) = mpsc::channel(10);
( (

View File

@@ -1,8 +1,8 @@
use super::common::ChannelTransport;
use arbiter_crypto::{ use arbiter_crypto::{
authn::{self, AuthChallenge, USERAGENT_CONTEXT}, authn::{self, AuthChallenge, USERAGENT_CONTEXT},
safecell::{SafeCell, SafeCellHandle as _}, safecell::{SafeCell, SafeCellHandle as _},
}; };
use arbiter_proto::transport::{Error as TransportError, Receiver, Sender}; use arbiter_proto::transport::{Error as TransportError, Receiver, Sender};
use arbiter_server::{ use arbiter_server::{
actors::{GlobalActors, bootstrap::GetToken, vault::Bootstrap}, actors::{GlobalActors, bootstrap::GetToken, vault::Bootstrap},
@@ -10,14 +10,13 @@ use arbiter_server::{
db::{self, schema}, db::{self, schema},
peers::user_agent::{self, Credentials, UserAgentConnection, auth, vault_gate}, peers::user_agent::{self, Credentials, UserAgentConnection, auth, vault_gate},
}; };
use async_trait::async_trait; use async_trait::async_trait;
use diesel::{ExpressionMethods as _, QueryDsl, insert_into}; use diesel::{ExpressionMethods as _, QueryDsl, insert_into};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
use ml_dsa::{KeyGen, MlDsa87, SigningKey, signature::Keypair as _}; use ml_dsa::{KeyGen, MlDsa87, SigningKey, signature::Keypair as _};
use tokio::sync::mpsc; use tokio::sync::mpsc;
use super::common::ChannelTransport;
fn sign_useragent_challenge( fn sign_useragent_challenge(
key: &SigningKey<MlDsa87>, key: &SigningKey<MlDsa87>,
challenge: &AuthChallenge, challenge: &AuthChallenge,
@@ -85,7 +84,10 @@ impl Receiver<auth::Inbound> for StartServerTransport {
#[async_trait] #[async_trait]
impl Sender<Result<auth::Outbound, auth::Error>> for StartServerTransport { impl Sender<Result<auth::Outbound, auth::Error>> for StartServerTransport {
async fn send(&mut self, item: Result<auth::Outbound, auth::Error>) -> Result<(), TransportError> { async fn send(
&mut self,
item: Result<auth::Outbound, auth::Error>,
) -> Result<(), TransportError> {
self.auth_tx self.auth_tx
.send(item) .send(item)
.await .await
@@ -118,8 +120,11 @@ impl Sender<Result<vault_gate::Outbound, vault_gate::Error>> for StartServerTran
} }
} }
impl arbiter_proto::transport::Bi<vault_gate::Inbound, Result<vault_gate::Outbound, vault_gate::Error>> impl
for StartServerTransport arbiter_proto::transport::Bi<
vault_gate::Inbound,
Result<vault_gate::Outbound, vault_gate::Error>,
> for StartServerTransport
{ {
} }
@@ -142,7 +147,7 @@ impl Sender<auth::Inbound> for StartTestTransport {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
pub async fn test_bootstrap_token_auth() { async fn test_bootstrap_token_auth() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let actors = GlobalActors::spawn(db.clone()).await.unwrap(); let actors = GlobalActors::spawn(db.clone()).await.unwrap();
actors actors
@@ -207,7 +212,7 @@ pub async fn test_bootstrap_token_auth() {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
pub async fn test_bootstrap_invalid_token_auth() { async fn test_bootstrap_invalid_token_auth() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let actors = GlobalActors::spawn(db.clone()).await.unwrap(); let actors = GlobalActors::spawn(db.clone()).await.unwrap();
@@ -260,7 +265,7 @@ pub async fn test_bootstrap_invalid_token_auth() {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
pub async fn test_challenge_auth() { async fn test_challenge_auth() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let actors = GlobalActors::spawn(db.clone()).await.unwrap(); let actors = GlobalActors::spawn(db.clone()).await.unwrap();
actors actors
@@ -345,7 +350,7 @@ pub async fn test_challenge_auth() {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
pub async fn test_challenge_auth_rejects_integrity_tag_mismatch_when_unsealed() { async fn test_challenge_auth_rejects_integrity_tag_mismatch_when_unsealed() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let actors = GlobalActors::spawn(db.clone()).await.unwrap(); let actors = GlobalActors::spawn(db.clone()).await.unwrap();
@@ -419,7 +424,7 @@ pub async fn test_challenge_auth_rejects_integrity_tag_mismatch_when_unsealed()
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
pub async fn test_challenge_auth_rejects_invalid_signature() { async fn test_challenge_auth_rejects_invalid_signature() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let actors = GlobalActors::spawn(db.clone()).await.unwrap(); let actors = GlobalActors::spawn(db.clone()).await.unwrap();
actors actors

View File

@@ -82,7 +82,7 @@ async fn client_dh_encrypt(
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
pub async fn test_unseal_success() { async fn test_unseal_success() {
let seal_key = b"test-seal-key"; let seal_key = b"test-seal-key";
let (_db, gate, _promotion_rx) = setup_sealed_gate(seal_key).await; let (_db, gate, _promotion_rx) = setup_sealed_gate(seal_key).await;
@@ -94,7 +94,7 @@ pub async fn test_unseal_success() {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
pub async fn test_unseal_wrong_seal_key() { async fn test_unseal_wrong_seal_key() {
let (_db, gate, _promotion_rx) = setup_sealed_gate(b"correct-key").await; let (_db, gate, _promotion_rx) = setup_sealed_gate(b"correct-key").await;
let encrypted_key = client_dh_encrypt(&gate, b"wrong-key").await; let encrypted_key = client_dh_encrypt(&gate, b"wrong-key").await;
@@ -110,7 +110,7 @@ pub async fn test_unseal_wrong_seal_key() {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
pub async fn test_unseal_corrupted_ciphertext() { async fn test_unseal_corrupted_ciphertext() {
let (_db, gate, _promotion_rx) = setup_sealed_gate(b"test-key").await; let (_db, gate, _promotion_rx) = setup_sealed_gate(b"test-key").await;
let client_secret = EphemeralSecret::random(); let client_secret = EphemeralSecret::random();
@@ -140,7 +140,7 @@ pub async fn test_unseal_corrupted_ciphertext() {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
pub async fn test_unseal_retry_after_invalid_key() { async fn test_unseal_retry_after_invalid_key() {
let seal_key = b"real-seal-key"; let seal_key = b"real-seal-key";
let (_db, gate, _promotion_rx) = setup_sealed_gate(seal_key).await; let (_db, gate, _promotion_rx) = setup_sealed_gate(seal_key).await;

View File

@@ -1,5 +1,4 @@
use std::collections::{HashMap, HashSet}; use crate::common;
use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _}; use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _};
use arbiter_server::{ use arbiter_server::{
actors::{ actors::{
@@ -12,10 +11,9 @@ use arbiter_server::{
use diesel::{ExpressionMethods as _, QueryDsl, SelectableHelper, dsl::sql_query}; use diesel::{ExpressionMethods as _, QueryDsl, SelectableHelper, dsl::sql_query};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
use kameo::actor::{ActorRef, Spawn as _}; use kameo::actor::{ActorRef, Spawn as _};
use std::collections::{HashMap, HashSet};
use tokio::task::JoinSet; use tokio::task::JoinSet;
use crate::common;
async fn write_concurrently( async fn write_concurrently(
actor: ActorRef<Vault>, actor: ActorRef<Vault>,
prefix: &'static str, prefix: &'static str,

View File

@@ -1,3 +1,4 @@
use crate::common;
use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _}; use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _};
use arbiter_server::{ use arbiter_server::{
actors::{ actors::{
@@ -11,8 +12,6 @@ use arbiter_server::{
use diesel::{QueryDsl, SelectableHelper}; use diesel::{QueryDsl, SelectableHelper};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
use crate::common;
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
async fn test_bootstrap() { async fn test_bootstrap() {

View File

@@ -1,5 +1,4 @@
use std::collections::HashSet; use crate::common;
use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _}; use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _};
use arbiter_server::{ use arbiter_server::{
actors::vault::Error, actors::vault::Error,
@@ -9,8 +8,7 @@ use arbiter_server::{
use diesel::{ExpressionMethods as _, QueryDsl, SelectableHelper, dsl::update}; use diesel::{ExpressionMethods as _, QueryDsl, SelectableHelper, dsl::update};
use diesel_async::RunQueryDsl; use diesel_async::RunQueryDsl;
use std::collections::HashSet;
use crate::common;
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]