Compare commits

...

15 Commits

Author SHA1 Message Date
CleverWild
0779d0db13 feat(macros): enhance Integrable derive with validation and versioning improvements
Some checks failed
ci/woodpecker/pr/server-audit Pipeline failed
ci/woodpecker/pr/server-vet Pipeline failed
ci/woodpecker/pr/server-lint Pipeline was successful
ci/woodpecker/pr/server-test Pipeline was successful
2026-06-30 19:55:28 +02:00
CleverWild
11a2d8c8f3 refactor(integrity): migrate impl Integrable to #[derive(Integrable)] 2026-06-29 16:58:36 +02:00
CleverWild
d861ff80be feat(macros): add #[derive(Integrable)] proc-macro 2026-06-29 16:58:35 +02:00
CleverWild
647f0c8519 refactor(crypto): move Integrable trait to arbiter-crypto 2026-06-29 16:58:35 +02:00
CleverWild
b843105533 fix(user-agent): zombie sessions #74
Some checks failed
ci/woodpecker/pr/server-audit Pipeline was successful
ci/woodpecker/pr/server-vet Pipeline failed
ci/woodpecker/pr/server-lint Pipeline was successful
ci/woodpecker/pr/server-test Pipeline was successful
ci/woodpecker/push/server-audit Pipeline was successful
ci/woodpecker/push/server-vet Pipeline failed
ci/woodpecker/push/server-lint Pipeline was successful
ci/woodpecker/push/server-test Pipeline was successful
2026-06-18 16:29:43 +02:00
a8e4a710f1 Merge pull request 'security(server): bind grant revocation state (revoked_at) to integrity hash' (#83) from security-hash-revoke_at into main
Some checks failed
ci/woodpecker/push/server-audit Pipeline was successful
ci/woodpecker/push/server-vet Pipeline failed
ci/woodpecker/push/server-lint Pipeline was successful
ci/woodpecker/push/server-test Pipeline was successful
ci/woodpecker/push/useragent-analyze Pipeline failed
Reviewed-on: #83
2026-06-11 09:44:28 +00:00
CleverWild
d99c87c473 fix: lints
Some checks failed
ci/woodpecker/pr/server-audit Pipeline was successful
ci/woodpecker/pr/server-vet Pipeline failed
ci/woodpecker/pr/server-lint Pipeline was successful
ci/woodpecker/pr/server-test Pipeline was successful
2026-06-09 21:07:01 +02:00
CleverWild
303120c9ac Merge branch 'main' into security-hash-revoke_at
Some checks failed
ci/woodpecker/pr/server-lint Pipeline failed
ci/woodpecker/pr/server-audit Pipeline was successful
ci/woodpecker/pr/server-vet Pipeline failed
ci/woodpecker/pr/server-test Pipeline was successful
2026-06-09 20:58:20 +02:00
CleverWild
32f317384d security(evm): remove client-controlled wallet_access_id from grant revocation
Some checks failed
ci/woodpecker/pr/server-audit Pipeline failed
ci/woodpecker/pr/server-lint Pipeline was successful
ci/woodpecker/pr/server-vet Pipeline failed
ci/woodpecker/pr/server-test Pipeline was successful
2026-06-09 19:36:44 +02:00
CleverWild
4bb2c062dc feat(evm): add wallet_access_id to grant deletion requests and revocation logic
Some checks failed
ci/woodpecker/pr/server-audit Pipeline failed
ci/woodpecker/pr/server-vet Pipeline failed
ci/woodpecker/pr/server-lint Pipeline was successful
ci/woodpecker/pr/server-test Pipeline was successful
2026-06-09 19:16:21 +02:00
CleverWild
b0a3f37cea refactor(evm): implement revoke_grant method for grant revocation 2026-06-09 19:11:39 +02:00
CleverWild
58a72da46c Merge branch 'security-hash-revoke_at' of ssh://git.markettakers.org:22222/MarketTakers/arbiter into security-hash-revoke_at
Some checks failed
ci/woodpecker/pr/server-audit Pipeline failed
ci/woodpecker/pr/server-vet Pipeline failed
ci/woodpecker/pr/server-lint Pipeline was successful
ci/woodpecker/pr/server-test Pipeline was successful
2026-06-09 19:10:57 +02:00
CleverWild
e287459b10 revert(server): bind grant revocation state (revoked_at) to integrity hash 2026-06-09 18:45:30 +02:00
CleverWild
3c482da917 fix(smlang::statemachine): macro invocation requires inner types to be public
Some checks failed
ci/woodpecker/pr/server-lint Pipeline failed
ci/woodpecker/pr/server-audit Pipeline was successful
ci/woodpecker/pr/server-vet Pipeline failed
ci/woodpecker/pr/server-test Pipeline was successful
ci/woodpecker/push/server-audit Pipeline was successful
ci/woodpecker/push/server-lint Pipeline failed
ci/woodpecker/push/server-vet Pipeline failed
ci/woodpecker/push/server-test Pipeline was successful
2026-06-08 18:00:52 +02:00
CleverWild
5a34463228 security(server): bind grant revocation state (revoked_at) to integrity hash
Some checks failed
ci/woodpecker/pr/server-audit Pipeline was successful
ci/woodpecker/pr/server-lint Pipeline was successful
ci/woodpecker/pr/server-vet Pipeline failed
ci/woodpecker/pr/server-test Pipeline was successful
2026-04-08 12:09:54 +02:00
44 changed files with 754 additions and 132 deletions

61
server/Cargo.lock generated
View File

@@ -719,6 +719,7 @@ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.117", "syn 2.0.117",
"trybuild",
] ]
[[package]] [[package]]
@@ -1965,6 +1966,12 @@ dependencies = [
"syn 2.0.117", "syn 2.0.117",
] ]
[[package]]
name = "dissimilar"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aeda16ab4059c5fd2a83f2b9c9e9c981327b18aa8e3b313f7e6563799d4f093e"
[[package]] [[package]]
name = "downcast-rs" name = "downcast-rs"
version = "2.0.2" version = "2.0.2"
@@ -3200,7 +3207,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "36c791ecdf977c99f45f23280405d7723727470f6689a5e6dbf513ac547ae10d" checksum = "36c791ecdf977c99f45f23280405d7723727470f6689a5e6dbf513ac547ae10d"
dependencies = [ dependencies = [
"serde", "serde",
"toml", "toml 0.9.12+spec-1.1.0",
] ]
[[package]] [[package]]
@@ -4972,6 +4979,12 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369" checksum = "55937e1799185b12863d447f42597ed69d9928686b8d88a1df17376a097d8369"
[[package]]
name = "target-triple"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "591ef38edfb78ca4771ee32cf494cb8771944bee237a9b91fc9c1424ac4b777b"
[[package]] [[package]]
name = "tempfile" name = "tempfile"
version = "3.27.0" version = "3.27.0"
@@ -4985,6 +4998,15 @@ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
[[package]]
name = "termcolor"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
dependencies = [
"winapi-util",
]
[[package]] [[package]]
name = "terminal_size" name = "terminal_size"
version = "0.4.4" version = "0.4.4"
@@ -5207,6 +5229,21 @@ dependencies = [
"winnow 0.7.15", "winnow 0.7.15",
] ]
[[package]]
name = "toml"
version = "1.1.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "81f3d15e84cbcd896376e6730314d59fb5a87f31e4b038454184435cd57defee"
dependencies = [
"indexmap 2.14.0",
"serde_core",
"serde_spanned",
"toml_datetime 1.1.1+spec-1.1.0",
"toml_parser",
"toml_writer",
"winnow 1.0.2",
]
[[package]] [[package]]
name = "toml_datetime" name = "toml_datetime"
version = "0.7.5+spec-1.1.0" version = "0.7.5+spec-1.1.0"
@@ -5246,6 +5283,12 @@ dependencies = [
"winnow 1.0.2", "winnow 1.0.2",
] ]
[[package]]
name = "toml_writer"
version = "1.1.1+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db"
[[package]] [[package]]
name = "tonic" name = "tonic"
version = "0.14.5" version = "0.14.5"
@@ -5433,6 +5476,22 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "trybuild"
version = "1.0.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0710d4dfbeae4f9c390baa784c49858a7468fa433f3fe5d0ec5ebef651cf59f9"
dependencies = [
"dissimilar",
"glob",
"serde",
"serde_derive",
"serde_json",
"target-triple",
"termcolor",
"toml 1.1.2+spec-1.1.0",
]
[[package]] [[package]]
name = "typenum" name = "typenum"
version = "1.20.0" version = "1.20.0"

View File

@@ -76,6 +76,7 @@ needless_pass_by_ref_mut = "allow"
pub_underscore_fields = "allow" pub_underscore_fields = "allow"
redundant_pub_crate = "allow" redundant_pub_crate = "allow"
uninhabited_references = "allow" # safe with unsafe_code = "forbid" and standard uninhabited pattern (match *self {}) uninhabited_references = "allow" # safe with unsafe_code = "forbid" and standard uninhabited pattern (match *self {})
too-many-lines = "allow" # this is a very common pattern in server code, and it's not always possible to break it down into smaller modules without hurting readability
# restriction lints # restriction lints
alloc_instead_of_core = "warn" alloc_instead_of_core = "warn"
@@ -128,7 +129,6 @@ rc_buffer = "warn"
rc_mutex = "warn" rc_mutex = "warn"
redundant_test_prefix = "warn" redundant_test_prefix = "warn"
redundant_type_annotations = "warn" redundant_type_annotations = "warn"
ref_patterns = "warn"
renamed_function_params = "warn" renamed_function_params = "warn"
rest_pat_in_fully_bound_structs = "warn" rest_pat_in_fully_bound_structs = "warn"
return_and_then = "warn" return_and_then = "warn"

View File

@@ -100,7 +100,7 @@ async fn send_auth_challenge_solution(
key: &SigningKey, key: &SigningKey,
challenge: AuthChallenge, challenge: AuthChallenge,
) -> Result<(), AuthError> { ) -> Result<(), AuthError> {
let timestamp = DateTime::from_timestamp_nanos(challenge.timestamp_nanos as i64); let timestamp = DateTime::from_timestamp_nanos(challenge.timestamp_nanos.cast_signed());
let challenge = authn::AuthChallenge { let challenge = authn::AuthChallenge {
nonce: *challenge nonce: *challenge
.random .random

View File

@@ -0,0 +1,49 @@
use crate::hashing::Hashable;
/// Marks a struct as a participant in the database integrity system.
///
/// Implementors are protected by an HMAC-SHA256 MAC stored in the
/// `integrity_envelope` table. The MAC is computed over:
///
/// ```text
/// HMAC-SHA256(key, len(KIND) || KIND || len(entity_id) || entity_id || VERSION || SHA256(Hashable))
/// ```
///
/// Both `KIND` and `VERSION` act as domain separators — they prevent a valid
/// MAC for one entity type or schema version from being accepted for another.
///
/// # Deriving
///
/// Use `#[derive(Integrable)]` with the `#[integrable(kind = "...")]` attribute.
/// `VERSION` is computed automatically as an FNV-1a hash of the struct's field
/// names and types, so it changes whenever the schema changes without any manual
/// bookkeeping.
///
/// ```rust,ignore
/// #[derive(Hashable, Integrable)]
/// #[integrable(kind = "operator_credentials")]
/// pub struct OperatorCredentials {
/// pub pubkey: PublicKey,
/// }
/// ```
///
/// # Upgrading schema
///
/// When fields are added, removed, or reordered, `VERSION` changes automatically.
/// Existing MAC records in the database will return [`PayloadVersionMismatch`] on
/// verification — this is the signal to re-sign all rows for this `KIND` as part
/// of a migration.
///
/// [`PayloadVersionMismatch`]: crate::integrity::Integrable
pub trait Integrable: Hashable {
/// Stable name of this entity type as stored in `integrity_envelope.entity_kind`.
///
/// Must be a valid schema name: starts with a letter, contains only `[a-zA-Z0-9_]`,
/// and must be globally unique across all `Integrable` types in the system.
const KIND: &'static str;
/// FNV-1a hash of the struct's field names and types at the time the derive
/// macro ran. Changes automatically when the schema changes, invalidating
/// existing MACs and signalling that a migration is required.
const VERSION: i32;
}

View File

@@ -1,6 +1,7 @@
#[cfg(feature = "authn")] #[cfg(feature = "authn")]
pub mod authn; pub mod authn;
pub mod hashing; pub mod hashing;
pub mod integrity;
#[cfg(feature = "safecell")] #[cfg(feature = "safecell")]
pub mod safecell; pub mod safecell;

View File

@@ -14,6 +14,7 @@ syn = { version = "2.0", features = ["derive", "fold", "full", "visit-mut"] }
[dev-dependencies] [dev-dependencies]
arbiter-crypto = { path = "../arbiter-crypto" } arbiter-crypto = { path = "../arbiter-crypto" }
trybuild = { version = "1.0", features = ["diff"] }
[lints] [lints]
workspace = true workspace = true

View File

@@ -53,32 +53,16 @@ struct FieldAccess {
fn collect_field_accesses(struct_data: &DataStruct) -> Vec<FieldAccess> { fn collect_field_accesses(struct_data: &DataStruct) -> Vec<FieldAccess> {
match &struct_data.fields { match &struct_data.fields {
Fields::Named(fields) => { Fields::Named(fields) => crate::utils::sorted_named_fields(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() .into_iter()
.map(|(_, name)| FieldAccess { .map(|field| {
let name = field.ident.as_ref().unwrap();
FieldAccess {
access: quote! { #name }, access: quote! { #name },
span: name.span(), span: name.span(),
})
.collect()
} }
})
.collect(),
Fields::Unnamed(fields) => fields Fields::Unnamed(fields) => fields
.unnamed .unnamed
.iter() .iter()

View File

@@ -0,0 +1,134 @@
use crate::utils::INTEGRABLE_TRAIT_PATH;
use proc_macro2::TokenStream;
use quote::quote;
use syn::{DeriveInput, LitStr, spanned::Spanned as _};
struct IntegrableAttr {
kind: String,
}
impl IntegrableAttr {
fn from_attrs(
attrs: &[syn::Attribute],
ident_span: proc_macro2::Span,
) -> Result<Self, syn::Error> {
let mut kind: Option<String> = None;
let mut found = false;
for attr in attrs {
if !attr.path().is_ident("integrable") {
continue;
}
if found {
return Err(syn::Error::new(attr.span(), "duplicate #[integrable] attribute"));
}
found = true;
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("kind") {
let lit: LitStr = meta.value()?.parse()?;
let v = lit.value();
if v.is_empty() {
return Err(syn::Error::new(lit.span(), "kind must not be empty"));
}
if !is_valid_kind(&v) {
return Err(syn::Error::new(
lit.span(),
"kind must be a valid schema name: start with a letter, contain only [a-zA-Z0-9_]",
));
}
kind = Some(v);
} else {
return Err(meta.error("unknown key; expected `kind`"));
}
Ok(())
})?;
}
let kind = kind.ok_or_else(|| {
syn::Error::new(ident_span, "#[integrable(kind = \"...\")] is required")
})?;
Ok(Self { kind })
}
}
fn is_valid_kind(s: &str) -> bool {
let mut chars = s.chars();
matches!(chars.next(), Some(c) if c.is_ascii_alphabetic())
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}
fn fnv1a(data: &[u8], mut hash: u32) -> u32 {
const FNV_PRIME: u32 = 16_777_619;
for &b in data {
hash ^= u32::from(b);
hash = hash.wrapping_mul(FNV_PRIME);
}
hash
}
// Hashes field names and types using the same alphabetical sort order as Hashable,
// so that source-level field reordering never changes VERSION.
fn compute_version(fields: &syn::Fields) -> i32 {
const FNV_OFFSET: u32 = 2_166_136_261;
let mut hash = FNV_OFFSET;
match fields {
syn::Fields::Named(named) => {
for field in crate::utils::sorted_named_fields(named) {
let name = field.ident.as_ref().unwrap().to_string();
let ty = &field.ty;
hash = fnv1a(name.as_bytes(), hash);
hash = fnv1a(quote!(#ty).to_string().as_bytes(), hash);
}
}
syn::Fields::Unnamed(unnamed) => {
for (i, field) in unnamed.unnamed.iter().enumerate() {
let ty = &field.ty;
hash = fnv1a(i.to_string().as_bytes(), hash);
hash = fnv1a(quote!(#ty).to_string().as_bytes(), hash);
}
}
syn::Fields::Unit => {}
}
// Clear sign bit to guarantee a positive i32; substitute 0 → 1.
let v = (hash >> 1).cast_signed();
if v == 0 { 1 } else { v }
}
pub(crate) fn derive(input: &DeriveInput) -> TokenStream {
let syn::Data::Struct(ref data) = input.data else {
return syn::Error::new(
input.ident.span(),
"#[derive(Integrable)] is only supported on structs",
)
.to_compile_error();
};
let integrable_trait = INTEGRABLE_TRAIT_PATH.to_path();
let hashable_trait = crate::utils::HASHABLE_TRAIT_PATH.to_path();
let ident = &input.ident;
let mut generics = input.generics.clone();
for type_param in generics.type_params_mut() {
type_param.bounds.push(syn::parse_quote!(#hashable_trait));
}
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let attr = match IntegrableAttr::from_attrs(&input.attrs, input.ident.span()) {
Ok(a) => a,
Err(e) => return e.to_compile_error(),
};
let kind = attr.kind;
let version = compute_version(&data.fields);
quote! {
#[automatically_derived]
impl #impl_generics #integrable_trait for #ident #ty_generics #where_clause {
const KIND: &'static str = #kind;
const VERSION: i32 = #version;
}
}
}

View File

@@ -1,6 +1,7 @@
use syn::{DeriveInput, parse_macro_input}; use syn::{DeriveInput, parse_macro_input};
mod hashable; mod hashable;
mod integrable;
mod utils; mod utils;
#[proc_macro_derive(Hashable)] #[proc_macro_derive(Hashable)]
@@ -8,3 +9,9 @@ pub fn derive_hashable(input: proc_macro::TokenStream) -> proc_macro::TokenStrea
let input = parse_macro_input!(input as DeriveInput); let input = parse_macro_input!(input as DeriveInput);
hashable::derive(&input).into() hashable::derive(&input).into()
} }
#[proc_macro_derive(Integrable, attributes(integrable))]
pub fn derive_integrable(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = parse_macro_input!(input as DeriveInput);
integrable::derive(&input).into()
}

View File

@@ -22,3 +22,14 @@ macro_rules! ensure_path {
ensure_path!(::arbiter_crypto::hashing::Hashable as HASHABLE_TRAIT_PATH); ensure_path!(::arbiter_crypto::hashing::Hashable as HASHABLE_TRAIT_PATH);
ensure_path!(::arbiter_crypto::hashing::Digest as HMAC_DIGEST_PATH); ensure_path!(::arbiter_crypto::hashing::Digest as HMAC_DIGEST_PATH);
ensure_path!(::arbiter_crypto::integrity::Integrable as INTEGRABLE_TRAIT_PATH);
/// Returns named struct fields sorted alphabetically by name.
/// Both `Hashable` and `Integrable` derive macros must iterate fields in the
/// same deterministic order so that source-level reordering never changes
/// either the runtime hash or the compile-time VERSION.
pub(crate) fn sorted_named_fields(fields: &syn::FieldsNamed) -> Vec<&syn::Field> {
let mut v: Vec<&syn::Field> = fields.named.iter().collect();
v.sort_by_key(|f| f.ident.as_ref().unwrap().to_string());
v
}

View File

@@ -0,0 +1,53 @@
use arbiter_crypto::integrity::Integrable;
#[derive(arbiter_macros::Hashable, arbiter_macros::Integrable)]
#[integrable(kind = "test_entity")]
struct TestEntity {
value: i32,
}
#[derive(arbiter_macros::Hashable, arbiter_macros::Integrable)]
#[integrable(kind = "other_entity")]
struct OtherEntity {
label: String,
count: u64,
}
#[test]
fn kind_is_set_correctly() {
assert_eq!(<TestEntity as Integrable>::KIND, "test_entity");
assert_eq!(<OtherEntity as Integrable>::KIND, "other_entity");
}
#[test]
fn version_is_positive() {
const {
assert!(<TestEntity as Integrable>::VERSION > 0);
assert!(<OtherEntity as Integrable>::VERSION > 0);
}
}
#[test]
fn different_field_layouts_produce_different_versions() {
assert_ne!(
<TestEntity as Integrable>::VERSION,
<OtherEntity as Integrable>::VERSION,
);
}
#[derive(arbiter_macros::Hashable, arbiter_macros::Integrable)]
#[integrable(kind = "generic_entity")]
struct GenericEntity<T> {
inner: T,
}
#[test]
fn generic_struct_derives_integrable() {
assert_eq!(
<GenericEntity<TestEntity> as Integrable>::KIND,
"generic_entity"
);
const {
assert!(<GenericEntity<TestEntity> as Integrable>::VERSION > 0);
}
}

View File

@@ -0,0 +1,5 @@
#[test]
fn integrable_compile_fail() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/ui/integrable/*.rs");
}

View File

@@ -0,0 +1,8 @@
#[derive(arbiter_macros::Hashable, arbiter_macros::Integrable)]
#[integrable(kind = "entity_a")]
#[integrable(kind = "entity_b")]
struct DuplicateAttr {
value: i32,
}
fn main() {}

View File

@@ -0,0 +1,5 @@
error: duplicate #[integrable] attribute
--> tests/ui/integrable/duplicate_attr.rs:3:1
|
3 | #[integrable(kind = "entity_b")]
| ^

View File

@@ -0,0 +1,7 @@
#[derive(arbiter_macros::Hashable, arbiter_macros::Integrable)]
#[integrable(kind = "")]
struct EmptyKind {
value: i32,
}
fn main() {}

View File

@@ -0,0 +1,5 @@
error: kind must not be empty
--> tests/ui/integrable/empty_kind.rs:2:21
|
2 | #[integrable(kind = "")]
| ^^

View File

@@ -0,0 +1,8 @@
#[derive(arbiter_macros::Integrable)]
#[integrable(kind = "my_enum")]
enum MyEnum {
A,
B,
}
fn main() {}

View File

@@ -0,0 +1,5 @@
error: #[derive(Integrable)] is only supported on structs
--> tests/ui/integrable/enum_not_supported.rs:3:6
|
3 | enum MyEnum {
| ^^^^^^

View File

@@ -0,0 +1,7 @@
#[derive(arbiter_macros::Hashable, arbiter_macros::Integrable)]
#[integrable(kind = "bad kind!")]
struct InvalidKind {
value: i32,
}
fn main() {}

View File

@@ -0,0 +1,5 @@
error: kind must be a valid schema name: start with a letter, contain only [a-zA-Z0-9_]
--> tests/ui/integrable/invalid_kind.rs:2:21
|
2 | #[integrable(kind = "bad kind!")]
| ^^^^^^^^^^^

View File

@@ -0,0 +1,6 @@
#[derive(arbiter_macros::Hashable, arbiter_macros::Integrable)]
struct MissingAttr {
value: i32,
}
fn main() {}

View File

@@ -0,0 +1,5 @@
error: #[integrable(kind = "...")] is required
--> tests/ui/integrable/missing_attr.rs:2:8
|
2 | struct MissingAttr {
| ^^^^^^^^^^^

View File

@@ -160,29 +160,14 @@ impl EvmActor {
} }
#[message] #[message]
#[expect(clippy::unused_async, reason = "reserved for impl")] pub async fn useragent_delete_grant(
pub async fn operator_delete_grant(&mut self, _grant_id: i32) -> Result<(), Error> { &mut self,
// let mut conn = self.db.get().await.map_err(DatabaseError::from)?; grant_id: i32,
// let vault = self.vault.clone(); ) -> Result<(), Error> {
self.engine
// diesel_async::AsyncConnection::transaction(&mut conn, |conn| { .revoke_grant(grant_id)
// Box::pin(async move { .await
// diesel::update(schema::evm_basic_grant::table) .map_err(Error::from)
// .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!()
} }
#[message] #[message]

View File

@@ -11,7 +11,9 @@ use kameo::{
prelude::{ActorId, ActorRef, ActorStopReason, Context, WeakActorRef}, prelude::{ActorId, ActorRef, ActorStopReason, Context, WeakActorRef},
reply::ReplySender, reply::ReplySender,
}; };
use std::ops::ControlFlow; use std::{ops::ControlFlow, time::Duration};
const APPROVAL_TIMEOUT: Duration = Duration::from_secs(30);
pub struct Args { pub struct Args {
pub client: ClientProfile, pub client: ClientProfile,
@@ -64,6 +66,14 @@ impl Actor for ClientApprovalController {
.await; .await;
} }
let weak = actor_ref.downgrade();
tokio::spawn(async move {
tokio::time::sleep(APPROVAL_TIMEOUT).await;
if let Some(r) = weak.upgrade() {
let _ = r.tell(OnApprovalTimeout {}).await;
}
});
Ok(this) Ok(this)
} }
@@ -104,4 +114,14 @@ impl ClientApprovalController {
ctx.stop(); ctx.stop();
} }
} }
/// Fired after `APPROVAL_TIMEOUT` elapses. Any operator that hasn't responded
/// by then is treated as a denial to prevent zombie sessions from blocking the flow.
#[message(ctx)]
pub fn on_approval_timeout(&mut self, ctx: &mut Context<Self, ()>) {
if self.pending > 0 {
self.send_reply(Ok(false));
ctx.stop();
}
}
} }

View File

@@ -346,11 +346,9 @@ impl Vault {
root_key_history_id, root_key_history_id,
} = Self::expect_unsealed(&mut self.state)?; } = Self::expect_unsealed(&mut self.state)?;
let mut hmac = root_key let mut hmac = root_key.0.read_inline(|k| {
.0 HmacSha256::new_from_slice(k)
.read_inline(|k| match HmacSha256::new_from_slice(k) { .unwrap_or_else(|_| unreachable!("HMAC accepts keys of any size"))
Ok(v) => v,
Err(_) => unreachable!("HMAC accepts keys of any size"),
}); });
hmac.update(&root_key_history_id.to_be_bytes()); hmac.update(&root_key_history_id.to_be_bytes());
hmac.update(&mac_input); hmac.update(&mac_input);
@@ -375,11 +373,9 @@ impl Vault {
return Ok(false); return Ok(false);
} }
let mut hmac = root_key let mut hmac = root_key.0.read_inline(|k| {
.0 HmacSha256::new_from_slice(k)
.read_inline(|k| match HmacSha256::new_from_slice(k) { .unwrap_or_else(|_| unreachable!("HMAC accepts keys of any size"))
Ok(v) => v,
Err(_) => unreachable!("HMAC accepts keys of any size"),
}); });
hmac.update(&key_version.to_be_bytes()); hmac.update(&key_version.to_be_bytes());
hmac.update(&mac_input); hmac.update(&mac_input);
@@ -423,12 +419,13 @@ mod tests {
async fn nonce_monotonic_even_when_nonce_allocation_interleaves() { async fn nonce_monotonic_even_when_nonce_allocation_interleaves() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let mut actor = bootstrapped_actor(&db).await; let mut actor = bootstrapped_actor(&db).await;
let root_key_history_id = match actor.state {
State::Unsealed(Unsealed { let State::Unsealed(Unsealed {
root_key_history_id, root_key_history_id,
.. ..
}) => root_key_history_id, }) = actor.state
_ => panic!("expected unsealed state"), else {
panic!("expected unsealed state")
}; };
let n1 = Vault::get_new_nonce(&db, root_key_history_id) let n1 = Vault::get_new_nonce(&db, root_key_history_id)
@@ -440,8 +437,8 @@ mod tests {
assert!(n2.to_vec() > n1.to_vec(), "nonce must increase"); assert!(n2.to_vec() > n1.to_vec(), "nonce must increase");
let mut conn = db.get().await.unwrap(); let mut conn = db.get().await.unwrap();
let root_row: models::RootKeyHistory = schema::root_key_history::table let root_row: RootKeyHistory = schema::root_key_history::table
.select(models::RootKeyHistory::as_select()) .select(RootKeyHistory::as_select())
.first(&mut conn) .first(&mut conn)
.await .await
.unwrap(); .unwrap();

View File

@@ -52,10 +52,7 @@ pub const INTEGRITY_SUBKEY_TAG: &[u8] = b"arbiter/db-integrity-key/v1";
pub type HmacSha256 = Hmac<Sha256>; pub type HmacSha256 = Hmac<Sha256>;
pub trait Integrable: Hashable { pub use arbiter_crypto::integrity::Integrable;
const KIND: &'static str;
const VERSION: i32 = 1;
}
fn payload_hash(payload: &impl Hashable) -> [u8; 32] { fn payload_hash(payload: &impl Hashable) -> [u8; 32] {
let mut hasher = Sha256::new(); let mut hasher = Sha256::new();
@@ -217,15 +214,13 @@ mod tests {
}; };
use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _}; use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _};
use super::{Error, Integrable, sign_entity, verify_entity}; use super::{Error, sign_entity, verify_entity};
#[derive(Clone, arbiter_macros::Hashable)] #[derive(Clone, arbiter_macros::Hashable, arbiter_macros::Integrable)]
#[integrable(kind = "dummy_entity")]
struct DummyEntity { struct DummyEntity {
payload_version: i32, payload_version: i32,
payload: Vec<u8>, payload: Vec<u8>,
} }
impl Integrable for DummyEntity {
const KIND: &'static str = "dummy_entity";
}
async fn bootstrapped_vault(db: &db::DatabasePool) -> ActorRef<Vault> { async fn bootstrapped_vault(db: &db::DatabasePool) -> ActorRef<Vault> {
let actor = Vault::spawn( let actor = Vault::spawn(

View File

@@ -1,28 +1,34 @@
use diesel_async::{AsyncConnection, RunQueryDsl};
use kameo::actor::ActorRef;
use crate::{ use crate::{
actors::vault::Vault, actors::vault::Vault,
crypto::integrity, crypto::integrity,
db::{ db::{
self, DatabaseError, self, DatabaseError,
models::{ models::{
EvmBasicGrant, EvmWalletAccess, NewEvmBasicGrant, NewEvmTransactionLog, SqliteTimestamp, EvmBasicGrant, EvmEtherTransferGrant, EvmEtherTransferGrantTarget,
EvmEtherTransferLimit, EvmTokenTransferGrant, EvmTokenTransferVolumeLimit,
EvmWalletAccess, NewEvmBasicGrant, NewEvmTransactionLog, SqliteTimestamp,
}, },
schema::{self, evm_transaction_log}, schema::{self, evm_transaction_log},
}, },
evm::policies::{ evm::policies::{
CombinedSettings, DatabaseID, EvalContext, EvalViolation, Grant, Policy, CombinedSettings, DatabaseID, EvalContext, EvalViolation, Grant, Policy,
SharedGrantSettings, SpecificGrant, SpecificMeaning, ether_transfer::EtherTransfer, SharedGrantSettings, SpecificGrant, SpecificMeaning, VolumeRateLimit,
token_transfers::TokenTransfer, ether_transfer::EtherTransfer, token_transfers::TokenTransfer,
}, },
}; };
use alloy::{ use alloy::{
consensus::TxEip1559, consensus::TxEip1559,
primitives::{TxKind, U256}, primitives::{Address, TxKind, U256},
}; };
use chrono::Utc; use chrono::Utc;
use diesel::{ExpressionMethods as _, QueryDsl as _, QueryResult, insert_into, sqlite::Sqlite}; use diesel::{
use diesel_async::{AsyncConnection, RunQueryDsl}; ExpressionMethods as _, OptionalExtension, QueryDsl as _, QueryResult, SelectableHelper,
use kameo::actor::ActorRef; insert_into, sqlite::Sqlite, update,
};
pub mod abi; pub mod abi;
pub mod safe_signer; pub mod safe_signer;
@@ -272,6 +278,151 @@ impl Engine {
Ok(id) Ok(id)
} }
pub async fn revoke_grant(
&self,
basic_grant_id: i32,
) -> Result<(), DatabaseError> {
let mut conn = self.db.get().await.map_err(DatabaseError::from)?;
let vault = self.vault.clone();
conn.transaction(async move |conn| {
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))
.set(evm_basic_grant::revoked_at.eq(SqliteTimestamp(Utc::now())))
.execute(&mut *conn)
.await?;
let basic_grant: EvmBasicGrant = evm_basic_grant::table
.filter(evm_basic_grant::id.eq(basic_grant_id))
.select(EvmBasicGrant::as_select())
.first(&mut *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(&mut *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(&mut *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(&mut *conn)
.await?;
let settings = CombinedSettings {
shared: shared.clone(),
specific: 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.into()),
},
},
};
integrity::sign_entity(&mut *conn, &vault, &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(&mut *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(&mut *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.into()),
})
})
.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: policies::token_transfers::Settings {
token_contract: Address::from(token_contract),
target,
volume_limits,
},
};
integrity::sign_entity(&mut *conn, &vault, &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>( async fn list_one_kind<Kind: Policy, Y>(
&self, &self,
conn: &mut impl AsyncConnection<Backend = Sqlite>, conn: &mut impl AsyncConnection<Backend = Sqlite>,
@@ -351,11 +502,15 @@ impl Engine {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use alloy::primitives::{Address, Bytes, U256, address}; use alloy::primitives::{Address, Bytes, U256, address};
use arbiter_crypto::safecell::{SafeCell, SafeCellHandle as _};
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 kameo::{actor::ActorRef, prelude::Spawn};
use rstest::rstest; use rstest::rstest;
use crate::actors::{GlobalActors, vault::{Bootstrap, Vault}};
use crate::crypto::integrity;
use crate::db::{ use crate::db::{
self, DatabaseConnection, self, DatabaseConnection,
models::{ models::{
@@ -363,8 +518,10 @@ mod tests {
}, },
schema::{evm_basic_grant, evm_transaction_log}, schema::{evm_basic_grant, evm_transaction_log},
}; };
use crate::evm::policies::ether_transfer::EtherTransfer;
use crate::evm::policies::{ use crate::evm::policies::{
EvalContext, EvalViolation, SharedGrantSettings, TransactionRateLimit, CombinedSettings, EvalContext, EvalViolation, Policy, SharedGrantSettings,
TransactionRateLimit, VolumeRateLimit,
}; };
use super::check_shared_constraints; use super::check_shared_constraints;
@@ -396,6 +553,7 @@ mod tests {
chain: CHAIN_ID, chain: CHAIN_ID,
valid_from: None, valid_from: None,
valid_until: None, valid_until: None,
revoked_at: None,
max_gas_fee_per_gas: None, max_gas_fee_per_gas: None,
max_priority_fee_per_gas: None, max_priority_fee_per_gas: None,
rate_limit: None, rate_limit: None,
@@ -604,4 +762,115 @@ mod tests {
assert!(violations.is_empty()); assert!(violations.is_empty());
} }
} }
async fn bootstrapped_vault(db: &db::DatabasePool) -> ActorRef<Vault> {
let actor = Vault::spawn(
Vault::new(db.clone(), GlobalActors::spawn_message_bus())
.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 vault = bootstrapped_vault(&db).await;
let engine = super::Engine::new(db.clone(), vault.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: super::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).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 = EtherTransfer::try_find_grant(
&context, &mut conn,
)
.await
.unwrap()
.unwrap();
let result =
integrity::verify_entity(&mut conn, &vault, &grant.settings, grant.id).await;
assert!(matches!(
result,
Err(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());
}
} }

View File

@@ -144,6 +144,7 @@ pub struct SharedGrantSettings {
pub valid_from: Option<DateTime<Utc>>, pub valid_from: Option<DateTime<Utc>>,
pub valid_until: 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_gas_fee_per_gas: Option<U256>,
pub max_priority_fee_per_gas: Option<U256>, pub max_priority_fee_per_gas: Option<U256>,
@@ -158,6 +159,7 @@ impl SharedGrantSettings {
chain: model.chain_id.into(), chain: model.chain_id.into(),
valid_from: model.valid_from.map(Into::into), valid_from: model.valid_from.map(Into::into),
valid_until: model.valid_until.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: model
.max_gas_fee_per_gas .max_gas_fee_per_gas
.map(|b| utils::try_bytes_to_u256(&b)) .map(|b| utils::try_bytes_to_u256(&b))

View File

@@ -1,6 +1,5 @@
use super::{DatabaseID, EvalContext, EvalViolation}; use super::{DatabaseID, EvalContext, EvalViolation};
use crate::{ use crate::{
crypto::integrity::v1::Integrable,
db::models::{ db::models::{
EvmBasicGrant, EvmEtherTransferGrant, EvmEtherTransferGrantTarget, EvmEtherTransferLimit, EvmBasicGrant, EvmEtherTransferGrant, EvmEtherTransferGrantTarget, EvmEtherTransferLimit,
NewEvmEtherTransferLimit, SqliteTimestamp, NewEvmEtherTransferLimit, SqliteTimestamp,
@@ -52,14 +51,12 @@ impl From<Meaning> for SpecificMeaning {
} }
// A grant for ether transfers, which can be scoped to specific target addresses and volume limits // A grant for ether transfers, which can be scoped to specific target addresses and volume limits
#[derive(Debug, Clone, arbiter_macros::Hashable)] #[derive(Debug, Clone, arbiter_macros::Hashable, arbiter_macros::Integrable)]
#[integrable(kind = "EtherTransfer")]
pub struct Settings { pub struct Settings {
pub target: Vec<Address>, pub target: Vec<Address>,
pub limit: VolumeRateLimit, pub limit: VolumeRateLimit,
} }
impl Integrable for Settings {
const KIND: &'static str = "EtherTransfer";
}
impl From<Settings> for SpecificGrant { impl From<Settings> for SpecificGrant {
fn from(val: Settings) -> Self { fn from(val: Settings) -> Self {

View File

@@ -79,6 +79,7 @@ fn shared() -> SharedGrantSettings {
chain: CHAIN_ID, chain: CHAIN_ID,
valid_from: None, valid_from: None,
valid_until: None, valid_until: None,
revoked_at: None,
max_gas_fee_per_gas: None, max_gas_fee_per_gas: None,
max_priority_fee_per_gas: None, max_priority_fee_per_gas: None,
rate_limit: None, rate_limit: None,

View File

@@ -1,6 +1,5 @@
use super::{DatabaseID, EvalContext, EvalViolation}; use super::{DatabaseID, EvalContext, EvalViolation};
use crate::{ use crate::{
crypto::integrity::Integrable,
db::models::{ db::models::{
EvmBasicGrant, EvmTokenTransferGrant, EvmTokenTransferVolumeLimit, EvmBasicGrant, EvmTokenTransferGrant, EvmTokenTransferVolumeLimit,
NewEvmTokenTransferGrant, NewEvmTokenTransferLog, NewEvmTokenTransferVolumeLimit, NewEvmTokenTransferGrant, NewEvmTokenTransferLog, NewEvmTokenTransferVolumeLimit,
@@ -63,15 +62,13 @@ impl From<Meaning> for SpecificMeaning {
} }
// A grant for token transfers, which can be scoped to specific target addresses and volume limits // A grant for token transfers, which can be scoped to specific target addresses and volume limits
#[derive(Debug, Clone, arbiter_macros::Hashable)] #[derive(Debug, Clone, arbiter_macros::Hashable, arbiter_macros::Integrable)]
#[integrable(kind = "TokenTransfer")]
pub struct Settings { pub struct Settings {
pub token_contract: Address, pub token_contract: Address,
pub target: Option<Address>, pub target: Option<Address>,
pub volume_limits: Vec<VolumeRateLimit>, pub volume_limits: Vec<VolumeRateLimit>,
} }
impl Integrable for Settings {
const KIND: &'static str = "TokenTransfer";
}
impl From<Settings> for SpecificGrant { impl From<Settings> for SpecificGrant {
fn from(val: Settings) -> Self { fn from(val: Settings) -> Self {

View File

@@ -98,6 +98,7 @@ fn shared() -> SharedGrantSettings {
chain: CHAIN_ID, chain: CHAIN_ID,
valid_from: None, valid_from: None,
valid_until: None, valid_until: None,
revoked_at: None,
max_gas_fee_per_gas: None, max_gas_fee_per_gas: None,
max_priority_fee_per_gas: None, max_priority_fee_per_gas: None,
rate_limit: None, rate_limit: None,

View File

@@ -200,7 +200,7 @@ impl Convert for auth::Outbound {
.timestamp .timestamp
.timestamp_nanos_opt() .timestamp_nanos_opt()
.expect("timestamp within range") .expect("timestamp within range")
as u64, .cast_unsigned(),
random: challenge.nonce.to_vec(), random: challenge.nonce.to_vec(),
}) })
} }

View File

@@ -80,7 +80,7 @@ impl Sender<Result<auth::Outbound, auth::Error>> for AuthTransportAdapter<'_> {
.timestamp .timestamp
.timestamp_nanos_opt() .timestamp_nanos_opt()
.expect("timestamp within range") .expect("timestamp within range")
as u64, .cast_unsigned(),
random: challenge.nonce.to_vec(), random: challenge.nonce.to_vec(),
}) })
} }

View File

@@ -87,6 +87,7 @@ impl TryConvert for ProtoSharedSettings {
.valid_until .valid_until
.map(ProtoTimestamp::try_convert) .map(ProtoTimestamp::try_convert)
.transpose()?, .transpose()?,
revoked_at: None,
max_gas_fee_per_gas: self max_gas_fee_per_gas: self
.max_gas_fee_per_gas .max_gas_fee_per_gas
.as_deref() .as_deref()

View File

@@ -298,7 +298,7 @@ where
let signature = expect_message(transport, |req: Inbound| match req { let signature = expect_message(transport, |req: Inbound| match req {
Inbound::AuthChallengeSolution { signature } => Some(signature), Inbound::AuthChallengeSolution { signature } => Some(signature),
_ => None, Inbound::AuthChallengeRequest { .. } => None,
}) })
.await .await
.map_err(|e| { .map_err(|e| {

View File

@@ -1,5 +1,5 @@
use crate::{ use crate::{
actors::GlobalActors, crypto::integrity::Integrable, db, peers::client::session::ClientSession, actors::GlobalActors, db, peers::client::session::ClientSession,
}; };
use arbiter_crypto::authn; use arbiter_crypto::authn;
use arbiter_macros::Hashable; use arbiter_macros::Hashable;
@@ -14,15 +14,12 @@ pub struct ClientProfile {
pub metadata: ClientMetadata, pub metadata: ClientMetadata,
} }
#[derive(Hashable)] #[derive(Hashable, arbiter_macros::Integrable)]
#[integrable(kind = "client_credentials")]
pub struct ClientCredentials { pub struct ClientCredentials {
pub pubkey: authn::PublicKey, pub pubkey: authn::PublicKey,
} }
impl Integrable for ClientCredentials {
const KIND: &'static str = "client_credentials";
}
pub struct ClientConnection { pub struct ClientConnection {
pub(crate) db: db::DatabasePool, pub(crate) db: db::DatabasePool,
pub(crate) actors: GlobalActors, pub(crate) actors: GlobalActors,

View File

@@ -19,7 +19,7 @@ pub(super) struct ChallengeRequest {
pub(super) bootstrap_token: Option<String>, pub(super) bootstrap_token: Option<String>,
} }
pub(super) struct ChallengeContext { pub struct ChallengeContext {
pub(super) challenge: AuthChallenge, pub(super) challenge: AuthChallenge,
pub(super) pubkey: authn::PublicKey, pub(super) pubkey: authn::PublicKey,
pub(super) bootstrap_token: Option<String>, pub(super) bootstrap_token: Option<String>,
@@ -127,8 +127,6 @@ where
}) })
} }
#[allow(missing_docs)]
#[allow(clippy::unused_unit)]
async fn verify_solution( async fn verify_solution(
&mut self, &mut self,
ChallengeContext { ChallengeContext {

View File

@@ -3,7 +3,7 @@ use crate::{
GlobalActors, GlobalActors,
vault::{GetState, Vault}, vault::{GetState, Vault},
}, },
crypto::integrity::{self, AttestationStatus, Integrable}, crypto::integrity::{self, AttestationStatus},
db::{DatabaseError, DatabasePool}, db::{DatabaseError, DatabasePool},
peers::client::ClientProfile, peers::client::ClientProfile,
}; };
@@ -23,16 +23,13 @@ pub mod auth;
pub mod session; pub mod session;
pub mod vault_gate; pub mod vault_gate;
#[derive(Debug, Clone, Hashable)] #[derive(Debug, Clone, Hashable, arbiter_macros::Integrable)]
#[integrable(kind = "operator_credentials")]
pub struct Credentials { pub struct Credentials {
pub id: i32, pub id: i32,
pub pubkey: authn::PublicKey, pub pubkey: authn::PublicKey,
} }
impl Integrable for Credentials {
const KIND: &'static str = "operator_credentials";
}
// Messages, sent by operator to connection client without having a request // Messages, sent by operator to connection client without having a request
#[derive(Debug)] #[derive(Debug)]
pub enum OutOfBand { pub enum OutOfBand {

View File

@@ -212,8 +212,7 @@ impl OperatorSession {
&mut self, &mut self,
) -> Result<Vec<EvmWalletAccess>, Error> { ) -> Result<Vec<EvmWalletAccess>, Error> {
let mut conn = self.props.db.get().await?; let mut conn = self.props.db.get().await?;
use crate::db::schema::evm_wallet_access; let access_entries = crate::db::schema::evm_wallet_access::table
let access_entries = evm_wallet_access::table
.select(EvmWalletAccess::as_select()) .select(EvmWalletAccess::as_select())
.load::<_>(&mut conn) .load::<_>(&mut conn)
.await?; .await?;

View File

@@ -1,7 +1,7 @@
use super::{OutOfBand, OperatorConnection}; use super::{OutOfBand, OperatorConnection};
use crate::{ use crate::{
actors::{ actors::{
flow_coordinator::client_connect_approval::ClientApprovalController, flow_coordinator::client_connect_approval::{ClientApprovalAnswer, ClientApprovalController},
operator_registry::ConnectOperator, operator_registry::ConnectOperator,
}, },
peers::client::ClientProfile, peers::client::ClientProfile,
@@ -63,7 +63,7 @@ impl OperatorSession {
Self { Self {
props, props,
sender, sender,
pending_client_approvals: Default::default(), pending_client_approvals: HashMap::default(),
} }
} }
} }
@@ -88,6 +88,7 @@ impl OperatorSession {
actor = "operator", actor = "operator",
event = "failed to announce new client connection" event = "failed to announce new client connection"
); );
let _ = controller.tell(ClientApprovalAnswer { approved: false }).await;
return; return;
} }

View File

@@ -400,7 +400,7 @@ pub async fn challenge_auth_rejects_integrity_tag_mismatch_when_unsealed() {
let challenge = match response { let challenge = match response {
Ok(resp) => match resp { Ok(resp) => match resp {
auth::Outbound::AuthChallenge { challenge } => challenge, auth::Outbound::AuthChallenge { challenge } => challenge,
other => panic!("Expected AuthChallenge, got {other:?}"), other @ auth::Outbound::AuthSuccess => panic!("Expected AuthChallenge, got {other:?}"),
}, },
Err(err) => panic!("Expected Ok response, got Err({err:?})"), Err(err) => panic!("Expected Ok response, got Err({err:?})"),
}; };

View File

@@ -14,7 +14,7 @@ use diesel_async::RunQueryDsl;
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
async fn test_bootstrap() { async fn bootstrap() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let mut actor = Vault::new(db.clone(), GlobalActors::spawn_message_bus()) let mut actor = Vault::new(db.clone(), GlobalActors::spawn_message_bus())
.await .await
@@ -39,7 +39,7 @@ async fn test_bootstrap() {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
async fn test_bootstrap_rejects_double() { async fn bootstrap_rejects_double() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let mut actor = common::bootstrapped_vault(&db).await; let mut actor = common::bootstrapped_vault(&db).await;
@@ -50,7 +50,7 @@ async fn test_bootstrap_rejects_double() {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
async fn test_create_new_before_bootstrap_fails() { async fn create_new_before_bootstrap_fails() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let mut actor = Vault::new(db, GlobalActors::spawn_message_bus()) let mut actor = Vault::new(db, GlobalActors::spawn_message_bus())
.await .await
@@ -65,7 +65,7 @@ async fn test_create_new_before_bootstrap_fails() {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
async fn test_decrypt_before_bootstrap_fails() { async fn decrypt_before_bootstrap_fails() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let mut actor = Vault::new(db, GlobalActors::spawn_message_bus()) let mut actor = Vault::new(db, GlobalActors::spawn_message_bus())
.await .await
@@ -77,7 +77,7 @@ async fn test_decrypt_before_bootstrap_fails() {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
async fn test_new_restores_sealed_state() { async fn new_restores_sealed_state() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let actor = common::bootstrapped_vault(&db).await; let actor = common::bootstrapped_vault(&db).await;
drop(actor); drop(actor);
@@ -91,7 +91,7 @@ async fn test_new_restores_sealed_state() {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
async fn test_unseal_correct_password() { async fn unseal_correct_password() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let mut actor = common::bootstrapped_vault(&db).await; let mut actor = common::bootstrapped_vault(&db).await;
@@ -114,7 +114,7 @@ async fn test_unseal_correct_password() {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
async fn test_unseal_wrong_then_correct_password() { async fn unseal_wrong_then_correct_password() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let mut actor = common::bootstrapped_vault(&db).await; let mut actor = common::bootstrapped_vault(&db).await;

View File

@@ -12,7 +12,7 @@ use std::collections::HashSet;
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
async fn test_create_decrypt_roundtrip() { async fn create_decrypt_roundtrip() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let mut actor = common::bootstrapped_vault(&db).await; let mut actor = common::bootstrapped_vault(&db).await;
@@ -28,7 +28,7 @@ async fn test_create_decrypt_roundtrip() {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
async fn test_decrypt_nonexistent_returns_not_found() { async fn decrypt_nonexistent_returns_not_found() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let mut actor = common::bootstrapped_vault(&db).await; let mut actor = common::bootstrapped_vault(&db).await;
@@ -38,7 +38,7 @@ async fn test_decrypt_nonexistent_returns_not_found() {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
async fn test_ciphertext_differs_across_entries() { async fn ciphertext_differs_across_entries() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let mut actor = common::bootstrapped_vault(&db).await; let mut actor = common::bootstrapped_vault(&db).await;
@@ -76,7 +76,7 @@ async fn test_ciphertext_differs_across_entries() {
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
async fn test_nonce_never_reused() { async fn nonce_never_reused() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
let mut actor = common::bootstrapped_vault(&db).await; let mut actor = common::bootstrapped_vault(&db).await;