13 Commits

Author SHA1 Message Date
CleverWild
694c569c08 feat(integrity): introduce sealed provenance markers for Verified
Some checks failed
ci/woodpecker/pr/server-audit Pipeline failed
ci/woodpecker/pr/server-vet Pipeline failed
ci/woodpecker/pr/server-lint Pipeline failed
ci/woodpecker/pr/server-test Pipeline failed
2026-04-15 19:45:59 +02:00
CleverWild
bec82e036e feat(integrity): derive-like macro VerifiedFields that allows to inherit Verified<T> type's provenance to all fields of T
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-11 03:53:25 +02:00
CleverWild
763058b014 feat(server): unify integrity API and propagate verified IDs through auth/EVM flows
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-04-07 21:12:36 +02:00
hdbg
1497884ce6 fix(server::bootsrapper): token compare is now constant-time
Some checks failed
ci/woodpecker/push/server-audit Pipeline was successful
ci/woodpecker/push/server-vet Pipeline failed
ci/woodpecker/push/server-lint Pipeline failed
ci/woodpecker/push/server-test Pipeline was successful
2026-04-06 18:33:47 +02:00
hdbg
b3464cf8a6 tests(server::client::auth): integrity envelope insertion for valid paths
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 was successful
ci/woodpecker/push/server-audit Pipeline was successful
ci/woodpecker/push/server-vet Pipeline failed
ci/woodpecker/push/server-lint Pipeline failed
ci/woodpecker/push/server-test Pipeline was successful
2026-04-06 18:24:13 +02:00
hdbg
46d1318b6f feat(server): add integrity verification for client keys 2026-04-06 18:13:11 +02:00
9c80d51d45 Merge pull request 'fix(server): replaced postcard-based integrity fingerprint with custom trait providing order-independent hashing' (#77) from push-opwuyuwxknyo 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 failed
ci/woodpecker/push/server-test Pipeline was successful
Reviewed-on: #77
2026-04-06 15:42:47 +00:00
hdbg
33456a644d tests(server): property-based testing for ordering independency for hash
Some checks failed
ci/woodpecker/pr/server-audit Pipeline was successful
ci/woodpecker/pr/server-lint Pipeline failed
ci/woodpecker/pr/server-vet Pipeline failed
ci/woodpecker/pr/server-test Pipeline was successful
2026-04-06 17:40:41 +02:00
hdbg
5bc0c42cc7 fix(server): replaced postcard-based integrity fingerprint with custom trait providing order-independent hashing 2026-04-06 16:25:32 +02:00
hdbg
f6b62ab884 fix(server): added chain_id check and covered check_shared_constraints with unit tests
Some checks failed
ci/woodpecker/pr/server-audit Pipeline was successful
ci/woodpecker/pr/server-lint Pipeline failed
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-04-06 12:57:18 +02:00
hdbg
2dd5a3f32f tests(server): initial cargo-mutants
Some checks failed
ci/woodpecker/push/server-audit Pipeline was successful
ci/woodpecker/push/server-vet Pipeline failed
ci/woodpecker/push/server-lint Pipeline failed
ci/woodpecker/push/server-test Pipeline was successful
2026-04-06 12:03:56 +02:00
hdbg
1aca9d4007 fix(server): simplify hash function for debug profile 2026-04-05 22:50:28 +02:00
5ee1b49c43 Merge pull request 'feat(server): integrity envelope engine for EVM grants with HMAC verification' (#51) from integrity-envelope into main
Some checks failed
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
Reviewed-on: #51
2026-04-05 16:26:51 +00:00
42 changed files with 2362 additions and 1013 deletions

View File

@@ -48,6 +48,10 @@ backend = "cargo:cargo-features-manager"
version = "1.46.3" version = "1.46.3"
backend = "cargo:cargo-insta" backend = "cargo:cargo-insta"
[[tools."cargo:cargo-mutants"]]
version = "27.0.0"
backend = "cargo:cargo-mutants"
[[tools."cargo:cargo-nextest"]] [[tools."cargo:cargo-nextest"]]
version = "0.9.126" version = "0.9.126"
backend = "cargo:cargo-nextest" backend = "cargo:cargo-nextest"
@@ -111,30 +115,37 @@ backend = "core:python"
[tools.python."platforms.linux-arm64"] [tools.python."platforms.linux-arm64"]
checksum = "sha256:53700338695e402a1a1fe22be4a41fbdacc70e22bb308a48eca8ed67cb7992be" checksum = "sha256:53700338695e402a1a1fe22be4a41fbdacc70e22bb308a48eca8ed67cb7992be"
url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260324/cpython-3.14.3+20260324-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz" url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260324/cpython-3.14.3+20260324-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz"
provenance = "github-attestations"
[tools.python."platforms.linux-arm64-musl"] [tools.python."platforms.linux-arm64-musl"]
checksum = "sha256:53700338695e402a1a1fe22be4a41fbdacc70e22bb308a48eca8ed67cb7992be" checksum = "sha256:53700338695e402a1a1fe22be4a41fbdacc70e22bb308a48eca8ed67cb7992be"
url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260324/cpython-3.14.3+20260324-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz" url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260324/cpython-3.14.3+20260324-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz"
provenance = "github-attestations"
[tools.python."platforms.linux-x64"] [tools.python."platforms.linux-x64"]
checksum = "sha256:d7a9f970914bb4c88756fe3bdcc186d4feb90e9500e54f1db47dae4dc9687e39" checksum = "sha256:d7a9f970914bb4c88756fe3bdcc186d4feb90e9500e54f1db47dae4dc9687e39"
url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260324/cpython-3.14.3+20260324-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz" url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260324/cpython-3.14.3+20260324-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz"
provenance = "github-attestations"
[tools.python."platforms.linux-x64-musl"] [tools.python."platforms.linux-x64-musl"]
checksum = "sha256:d7a9f970914bb4c88756fe3bdcc186d4feb90e9500e54f1db47dae4dc9687e39" checksum = "sha256:d7a9f970914bb4c88756fe3bdcc186d4feb90e9500e54f1db47dae4dc9687e39"
url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260324/cpython-3.14.3+20260324-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz" url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260324/cpython-3.14.3+20260324-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz"
provenance = "github-attestations"
[tools.python."platforms.macos-arm64"] [tools.python."platforms.macos-arm64"]
checksum = "sha256:c43aecde4a663aebff99b9b83da0efec506479f1c3f98331442f33d2c43501f9" checksum = "sha256:c43aecde4a663aebff99b9b83da0efec506479f1c3f98331442f33d2c43501f9"
url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260324/cpython-3.14.3+20260324-aarch64-apple-darwin-install_only_stripped.tar.gz" url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260324/cpython-3.14.3+20260324-aarch64-apple-darwin-install_only_stripped.tar.gz"
provenance = "github-attestations"
[tools.python."platforms.macos-x64"] [tools.python."platforms.macos-x64"]
checksum = "sha256:9ab41dbc2f100a2a45d1833b9c11165f51051c558b5213eda9a9731d5948a0c0" checksum = "sha256:9ab41dbc2f100a2a45d1833b9c11165f51051c558b5213eda9a9731d5948a0c0"
url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260324/cpython-3.14.3+20260324-x86_64-apple-darwin-install_only_stripped.tar.gz" url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260324/cpython-3.14.3+20260324-x86_64-apple-darwin-install_only_stripped.tar.gz"
provenance = "github-attestations"
[tools.python."platforms.windows-x64"] [tools.python."platforms.windows-x64"]
checksum = "sha256:bbe19034b35b0267176a7442575ae7dc6343480fd4d35598cb7700173d431e09" checksum = "sha256:bbe19034b35b0267176a7442575ae7dc6343480fd4d35598cb7700173d431e09"
url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260324/cpython-3.14.3+20260324-x86_64-pc-windows-msvc-install_only_stripped.tar.gz" url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260324/cpython-3.14.3+20260324-x86_64-pc-windows-msvc-install_only_stripped.tar.gz"
provenance = "github-attestations"
[[tools.rust]] [[tools.rust]]
version = "1.93.0" version = "1.93.0"

View File

@@ -12,6 +12,7 @@ protoc = "29.6"
python = "3.14.3" python = "3.14.3"
ast-grep = "0.42.0" ast-grep = "0.42.0"
"cargo:cargo-edit" = "0.13.9" "cargo:cargo-edit" = "0.13.9"
"cargo:cargo-mutants" = "27.0.0"
[tasks.codegen] [tasks.codegen]
sources = ['protobufs/*.proto', 'protobufs/**/*.proto'] sources = ['protobufs/*.proto', 'protobufs/**/*.proto']

View File

@@ -36,6 +36,10 @@ message GasLimitExceededViolation {
} }
message EvalViolation { message EvalViolation {
message ChainIdMismatch {
uint64 expected = 1;
uint64 actual = 2;
}
oneof kind { oneof kind {
bytes invalid_target = 1; // 20-byte Ethereum address bytes invalid_target = 1; // 20-byte Ethereum address
GasLimitExceededViolation gas_limit_exceeded = 2; GasLimitExceededViolation gas_limit_exceeded = 2;
@@ -43,6 +47,8 @@ message EvalViolation {
google.protobuf.Empty volumetric_limit_exceeded = 4; google.protobuf.Empty volumetric_limit_exceeded = 4;
google.protobuf.Empty invalid_time = 5; google.protobuf.Empty invalid_time = 5;
google.protobuf.Empty invalid_transaction_type = 6; google.protobuf.Empty invalid_transaction_type = 6;
ChainIdMismatch chain_id_mismatch = 7;
} }
} }

View File

@@ -0,0 +1 @@
test_tool = "nextest"

2
server/.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
mutants.out/
mutants.out.old/

109
server/Cargo.lock generated
View File

@@ -742,23 +742,27 @@ dependencies = [
"insta", "insta",
"k256", "k256",
"kameo", "kameo",
"macro_rules_attribute",
"memsafe", "memsafe",
"mutants",
"paste",
"pem", "pem",
"postcard", "proptest",
"prost", "prost",
"prost-types", "prost-types",
"rand 0.10.0", "rand 0.10.0",
"rcgen", "rcgen",
"restructed", "restructed",
"rsa", "rsa",
"rstest",
"rustls", "rustls",
"secrecy", "secrecy",
"serde",
"serde_with", "serde_with",
"sha2 0.10.9", "sha2 0.10.9",
"smlang", "smlang",
"spki", "spki",
"strum 0.28.0", "strum 0.28.0",
"subtle",
"test-log", "test-log",
"thiserror 2.0.18", "thiserror 2.0.18",
"tokio", "tokio",
@@ -1057,15 +1061,6 @@ dependencies = [
"syn 2.0.117", "syn 2.0.117",
] ]
[[package]]
name = "atomic-polyfill"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8cf2bce30dfe09ef0bfaef228b9d414faaf7e563035494d7fe092dba54b300f4"
dependencies = [
"critical-section",
]
[[package]] [[package]]
name = "atomic-waker" name = "atomic-waker"
version = "1.1.2" version = "1.1.2"
@@ -1456,15 +1451,6 @@ dependencies = [
"cc", "cc",
] ]
[[package]]
name = "cobs"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1"
dependencies = [
"thiserror 2.0.18",
]
[[package]] [[package]]
name = "console" name = "console"
version = "0.15.11" version = "0.15.11"
@@ -1572,12 +1558,6 @@ dependencies = [
"cfg-if", "cfg-if",
] ]
[[package]]
name = "critical-section"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b"
[[package]] [[package]]
name = "crossbeam-utils" name = "crossbeam-utils"
version = "0.8.21" version = "0.8.21"
@@ -2043,18 +2023,6 @@ dependencies = [
"zeroize", "zeroize",
] ]
[[package]]
name = "embedded-io"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced"
[[package]]
name = "embedded-io"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d"
[[package]] [[package]]
name = "encode_unicode" name = "encode_unicode"
version = "1.0.0" version = "1.0.0"
@@ -2472,15 +2440,6 @@ dependencies = [
"tracing", "tracing",
] ]
[[package]]
name = "hash32"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67"
dependencies = [
"byteorder",
]
[[package]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.12.3" version = "0.12.3"
@@ -2515,20 +2474,6 @@ dependencies = [
"serde_core", "serde_core",
] ]
[[package]]
name = "heapless"
version = "0.7.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdc6457c0eb62c71aac4bc17216026d8410337c4126773b9c5daba343f17964f"
dependencies = [
"atomic-polyfill",
"hash32",
"rustc_version 0.4.1",
"serde",
"spin",
"stable_deref_trait",
]
[[package]] [[package]]
name = "heck" name = "heck"
version = "0.5.0" version = "0.5.0"
@@ -3114,6 +3059,22 @@ dependencies = [
"syn 2.0.117", "syn 2.0.117",
] ]
[[package]]
name = "macro_rules_attribute"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65049d7923698040cd0b1ddcced9b0eb14dd22c5f86ae59c3740eab64a676520"
dependencies = [
"macro_rules_attribute-proc_macro",
"paste",
]
[[package]]
name = "macro_rules_attribute-proc_macro"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "670fdfda89751bc4a84ac13eaa63e205cf0fd22b4c9a5fbfa085b63c1f1d3a30"
[[package]] [[package]]
name = "matchers" name = "matchers"
version = "0.2.0" version = "0.2.0"
@@ -3236,6 +3197,12 @@ version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084"
[[package]]
name = "mutants"
version = "0.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "add0ac067452ff1aca8c5002111bd6b1c895baee6e45fcbc44e0193aea17be56"
[[package]] [[package]]
name = "nom" name = "nom"
version = "7.1.3" version = "7.1.3"
@@ -3589,19 +3556,6 @@ version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"
[[package]]
name = "postcard"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24"
dependencies = [
"cobs",
"embedded-io 0.4.0",
"embedded-io 0.6.1",
"heapless",
"serde",
]
[[package]] [[package]]
name = "potential_utf" name = "potential_utf"
version = "0.1.4" version = "0.1.4"
@@ -3713,9 +3667,9 @@ dependencies = [
[[package]] [[package]]
name = "proptest" name = "proptest"
version = "1.10.0" version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37566cb3fdacef14c0737f9546df7cfeadbfbc9fef10991038bf5015d0c80532" checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744"
dependencies = [ dependencies = [
"bit-set", "bit-set",
"bit-vec", "bit-vec",
@@ -4790,9 +4744,6 @@ name = "spin"
version = "0.9.8" version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
dependencies = [
"lock_api",
]
[[package]] [[package]]
name = "spki" name = "spki"

View File

@@ -44,3 +44,4 @@ sha2 = "0.10"
spki = "0.7" spki = "0.7"
prost = "0.14.3" prost = "0.14.3"
miette = { version = "7.6.0", features = ["fancy", "serde"] } miette = { version = "7.6.0", features = ["fancy", "serde"] }
mutants = "0.0.4"

View File

@@ -59,6 +59,10 @@ pub struct ArbiterEvmWallet {
} }
impl ArbiterEvmWallet { impl ArbiterEvmWallet {
#[expect(
dead_code,
reason = "constructor may be used in future extensions, e.g. to support wallet listing"
)]
pub(crate) fn new(transport: Arc<Mutex<ClientTransport>>, address: Address) -> Self { pub(crate) fn new(transport: Arc<Mutex<ClientTransport>>, address: Address) -> Self {
Self { Self {
transport, transport,

View File

@@ -58,10 +58,14 @@ prost-types.workspace = true
prost.workspace = true prost.workspace = true
arbiter-tokens-registry.path = "../arbiter-tokens-registry" arbiter-tokens-registry.path = "../arbiter-tokens-registry"
anyhow = "1.0.102" anyhow = "1.0.102"
postcard = { version = "1.1.3", features = ["use-std"] }
serde = { version = "1.0.228", features = ["derive"] }
serde_with = "3.18.0" serde_with = "3.18.0"
mutants.workspace = true
subtle = "2.6.1"
macro_rules_attribute = "0.2.2"
paste = "1.0.15"
[dev-dependencies] [dev-dependencies]
insta = "1.46.3" insta = "1.46.3"
proptest = "1.11.0"
rstest.workspace = true
test-log = { version = "0.2", default-features = false, features = ["trace"] } test-log = { version = "0.2", default-features = false, features = ["trace"] }

View File

@@ -4,6 +4,7 @@ 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 thiserror::Error; use thiserror::Error;
use crate::db::{self, DatabasePool, schema}; use crate::db::{self, DatabasePool, schema};
@@ -44,14 +45,14 @@ pub struct Bootstrapper {
impl Bootstrapper { impl Bootstrapper {
pub async fn new(db: &DatabasePool) -> Result<Self, Error> { pub async fn new(db: &DatabasePool) -> Result<Self, Error> {
let mut conn = db.get().await?; let row_count: i64 = {
let mut conn = db.get().await?;
let row_count: i64 = schema::useragent_client::table schema::useragent_client::table
.count() .count()
.get_result(&mut conn) .get_result(&mut conn)
.await?; .await?
};
drop(conn);
let token = if row_count == 0 { let token = if row_count == 0 {
let token = generate_token().await?; let token = generate_token().await?;
@@ -69,7 +70,13 @@ impl Bootstrapper {
#[message] #[message]
pub fn is_correct_token(&self, token: String) -> bool { pub fn is_correct_token(&self, token: String) -> bool {
match &self.token { match &self.token {
Some(expected) => *expected == token, Some(expected) => {
let expected_bytes = expected.as_bytes();
let token_bytes = token.as_bytes();
let choice = expected_bytes.ct_eq(token_bytes);
bool::from(choice)
}
None => false, None => false,
} }
} }

View File

@@ -9,14 +9,16 @@ use diesel::{
}; };
use diesel_async::RunQueryDsl as _; use diesel_async::RunQueryDsl as _;
use ed25519_dalek::{Signature, VerifyingKey}; use ed25519_dalek::{Signature, VerifyingKey};
use kameo::error::SendError; use kameo::{actor::ActorRef, error::SendError};
use tracing::error; use tracing::error;
use crate::{ use crate::{
actors::{ actors::{
client::{ClientConnection, ClientProfile}, client::{ClientConnection, ClientCredentials, ClientProfile},
flow_coordinator::{self, RequestClientApproval}, flow_coordinator::{self, RequestClientApproval},
keyholder::KeyHolder,
}, },
crypto::integrity::{self, Verified, verified::VerifiedFieldsAccessor},
db::{ db::{
self, self,
models::{ProgramClientMetadata, SqliteTimestamp}, models::{ProgramClientMetadata, SqliteTimestamp},
@@ -30,6 +32,8 @@ pub enum Error {
DatabasePoolUnavailable, DatabasePoolUnavailable,
#[error("Database operation failed")] #[error("Database operation failed")]
DatabaseOperationFailed, DatabaseOperationFailed,
#[error("Integrity check failed")]
IntegrityCheckFailed,
#[error("Invalid challenge solution")] #[error("Invalid challenge solution")]
InvalidChallengeSolution, InvalidChallengeSolution,
#[error("Client approval request failed")] #[error("Client approval request failed")]
@@ -38,6 +42,13 @@ pub enum Error {
Transport, Transport,
} }
impl From<diesel::result::Error> for Error {
fn from(e: diesel::result::Error) -> Self {
error!(?e, "Database error");
Self::DatabaseOperationFailed
}
}
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)] #[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
pub enum ApproveError { pub enum ApproveError {
#[error("Internal error")] #[error("Internal error")]
@@ -65,17 +76,36 @@ pub enum Outbound {
AuthSuccess, AuthSuccess,
} }
pub struct ClientInfo { /// Returns the current nonce and client ID for a registered client.
pub id: i32,
pub current_nonce: i32,
}
/// Atomically reads and increments the nonce for a known client.
/// Returns `None` if the pubkey is not registered. /// Returns `None` if the pubkey is not registered.
async fn get_client_and_nonce( async fn get_current_nonce_and_id(
db: &db::DatabasePool, db: &db::DatabasePool,
pubkey: &VerifyingKey, pubkey: &VerifyingKey,
) -> Result<Option<ClientInfo>, Error> { ) -> Result<Option<(i32, i32)>, Error> {
let pubkey_bytes = pubkey.as_bytes().to_vec();
let mut conn = db.get().await.map_err(|e| {
error!(error = ?e, "Database pool error");
Error::DatabasePoolUnavailable
})?;
program_client::table
.filter(program_client::public_key.eq(&pubkey_bytes))
.select((program_client::id, program_client::nonce))
.first::<(i32, i32)>(&mut conn)
.await
.optional()
.map_err(|e| {
error!(error = ?e, "Database error");
Error::DatabaseOperationFailed
})
}
/// Atomically increments the nonce and re-signs the integrity envelope.
/// Returns the new nonce, which is used as the challenge nonce.
async fn create_nonce(
db: &db::DatabasePool,
keyholder: &ActorRef<KeyHolder>,
pubkey: &VerifyingKey,
) -> Result<i32, Error> {
let pubkey_bytes = pubkey.as_bytes().to_vec(); let pubkey_bytes = pubkey.as_bytes().to_vec();
let mut conn = db.get().await.map_err(|e| { let mut conn = db.get().await.map_err(|e| {
@@ -84,34 +114,35 @@ async fn get_client_and_nonce(
})?; })?;
conn.exclusive_transaction(|conn| { conn.exclusive_transaction(|conn| {
let keyholder = keyholder.clone();
Box::pin(async move { Box::pin(async move {
let Some((client_id, current_nonce)) = program_client::table let (id, new_nonce): (i32, i32) = update(program_client::table)
.filter(program_client::public_key.eq(&pubkey_bytes)) .filter(program_client::public_key.eq(&pubkey_bytes))
.select((program_client::id, program_client::nonce)) .set(program_client::nonce.eq(program_client::nonce + 1))
.first::<(i32, i32)>(conn) .returning((program_client::id, program_client::nonce))
.await .get_result(conn)
.optional()?
else {
return Result::<_, diesel::result::Error>::Ok(None);
};
update(program_client::table)
.filter(program_client::public_key.eq(&pubkey_bytes))
.set(program_client::nonce.eq(current_nonce + 1))
.execute(conn)
.await?; .await?;
Ok(Some(ClientInfo { integrity::sign_entity(
id: client_id, conn,
current_nonce, &keyholder,
})) &ClientCredentials {
pubkey: *pubkey,
nonce: new_nonce,
},
id,
)
.await
.map_err(|e| {
error!(?e, "Integrity sign failed after nonce update");
Error::DatabaseOperationFailed
})?
.drop_verification_provenance();
Ok(new_nonce)
}) })
}) })
.await .await
.map_err(|e| {
error!(error = ?e, "Database error");
Error::DatabaseOperationFailed
})
} }
async fn approve_new_client( async fn approve_new_client(
@@ -139,45 +170,64 @@ async fn approve_new_client(
async fn insert_client( async fn insert_client(
db: &db::DatabasePool, db: &db::DatabasePool,
keyholder: &ActorRef<KeyHolder>,
pubkey: &VerifyingKey, pubkey: &VerifyingKey,
metadata: &ClientMetadata, metadata: &ClientMetadata,
) -> Result<i32, Error> { ) -> Result<Verified<i32>, Error> {
use crate::db::schema::{client_metadata, program_client}; use crate::db::schema::{client_metadata, program_client};
let metadata = metadata.clone();
let mut conn = db.get().await.map_err(|e| { let mut conn = db.get().await.map_err(|e| {
error!(error = ?e, "Database pool error"); error!(error = ?e, "Database pool error");
Error::DatabasePoolUnavailable Error::DatabasePoolUnavailable
})?; })?;
let metadata_id = insert_into(client_metadata::table) conn.exclusive_transaction(|conn| {
.values(( let keyholder = keyholder.clone();
client_metadata::name.eq(&metadata.name), Box::pin(async move {
client_metadata::description.eq(&metadata.description), const NONCE_START: i32 = 1;
client_metadata::version.eq(&metadata.version),
))
.returning(client_metadata::id)
.get_result::<i32>(&mut conn)
.await
.map_err(|e| {
error!(error = ?e, "Failed to insert client metadata");
Error::DatabaseOperationFailed
})?;
let client_id = insert_into(program_client::table) let metadata_id = insert_into(client_metadata::table)
.values(( .values((
program_client::public_key.eq(pubkey.as_bytes().to_vec()), client_metadata::name.eq(&metadata.name),
program_client::metadata_id.eq(metadata_id), client_metadata::description.eq(&metadata.description),
program_client::nonce.eq(1), // pre-incremented; challenge uses 0 client_metadata::version.eq(&metadata.version),
)) ))
.on_conflict_do_nothing() .returning(client_metadata::id)
.returning(program_client::id) .get_result::<i32>(conn)
.get_result::<i32>(&mut conn) .await?;
.await
.map_err(|e| {
error!(error = ?e, "Failed to insert client metadata");
Error::DatabaseOperationFailed
})?;
Ok(client_id) let client_id = insert_into(program_client::table)
.values((
program_client::public_key.eq(pubkey.as_bytes().to_vec()),
program_client::metadata_id.eq(metadata_id),
program_client::nonce.eq(NONCE_START),
))
.on_conflict_do_nothing()
.returning(program_client::id)
.get_result::<i32>(conn)
.await?;
let verified_id = integrity::sign_entity(
conn,
&keyholder,
&ClientCredentials {
pubkey: *pubkey,
nonce: NONCE_START,
},
client_id,
)
.await
.map_err(|e| {
error!(error = ?e, "Failed to sign integrity tag for new client key");
Error::DatabaseOperationFailed
})?
.unqualify_origin();
Ok(verified_id)
})
})
.await
} }
async fn sync_client_metadata( async fn sync_client_metadata(
@@ -287,7 +337,10 @@ where
Ok(()) Ok(())
} }
pub async fn authenticate<T>(props: &mut ClientConnection, transport: &mut T) -> Result<i32, Error> pub async fn authenticate<T>(
props: &mut ClientConnection,
transport: &mut T,
) -> Result<Verified<i32>, Error>
where where
T: Bi<Inbound, Result<Outbound, Error>> + Send + ?Sized, T: Bi<Inbound, Result<Outbound, Error>> + Send + ?Sized,
{ {
@@ -295,8 +348,29 @@ where
return Err(Error::Transport); return Err(Error::Transport);
}; };
let info = match get_client_and_nonce(&props.db, &pubkey).await? { // fixme! triage needed: probable regretion since in match->Some get_current_nonce_and_id called only once instead of twice
Some(nonce) => nonce, let client_id = match get_current_nonce_and_id(&props.db, &pubkey).await? {
Some((nonce, id)) => {
let mut db_conn = props.db.get().await.map_err(|e| {
error!(error = ?e, "Database pool error");
Error::DatabasePoolUnavailable
})?;
integrity::verify_entity(
&mut db_conn,
&props.actors.key_holder,
ClientCredentials { pubkey, nonce },
id,
)
.await
.map_err(|e| {
error!(?e, "Integrity verification failed");
Error::IntegrityCheckFailed
})?
.inherit()
.entity_id
.unqualify_origin()
}
None => { None => {
approve_new_client( approve_new_client(
&props.actors, &props.actors,
@@ -306,16 +380,13 @@ where
}, },
) )
.await?; .await?;
let client_id = insert_client(&props.db, &pubkey, &metadata).await?; insert_client(&props.db, &props.actors.key_holder, &pubkey, &metadata).await?
ClientInfo {
id: client_id,
current_nonce: 0,
}
} }
}; };
sync_client_metadata(&props.db, info.id, &metadata).await?; sync_client_metadata(&props.db, *client_id, &metadata).await?;
challenge_client(transport, pubkey, info.current_nonce).await?; let challenge_nonce = create_nonce(&props.db, &props.actors.key_holder, &pubkey).await?;
challenge_client(transport, pubkey, challenge_nonce).await?;
transport transport
.send(Ok(Outbound::AuthSuccess)) .send(Ok(Outbound::AuthSuccess))
@@ -325,5 +396,5 @@ where
Error::Transport Error::Transport
})?; })?;
Ok(info.id) Ok(client_id)
} }

View File

@@ -4,6 +4,7 @@ use tracing::{error, info};
use crate::{ use crate::{
actors::{GlobalActors, client::session::ClientSession}, actors::{GlobalActors, client::session::ClientSession},
crypto::integrity::{Integrable, hashing::Hashable},
db, db,
}; };
@@ -13,6 +14,22 @@ pub struct ClientProfile {
pub metadata: ClientMetadata, pub metadata: ClientMetadata,
} }
pub struct ClientCredentials {
pub pubkey: ed25519_dalek::VerifyingKey,
pub nonce: i32,
}
impl Integrable for ClientCredentials {
const KIND: &'static str = "client_credentials";
}
impl Hashable for ClientCredentials {
fn hash<H: sha2::Digest>(&self, hasher: &mut H) {
hasher.update(self.pubkey.as_bytes());
self.nonce.hash(hasher);
}
}
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

@@ -5,23 +5,25 @@ use alloy::{consensus::TxEip1559, primitives::Address, signers::Signature};
use crate::{ use crate::{
actors::{ actors::{
GlobalActors,
client::ClientConnection, client::ClientConnection,
evm::{ClientSignTransaction, SignTransactionError}, evm::{ClientSignTransaction, SignTransactionError},
flow_coordinator::RegisterClient, flow_coordinator::RegisterClient,
keyholder::KeyHolderState, keyholder::KeyHolderState,
}, },
db, crypto::integrity::Verified,
evm::VetError, evm::VetError,
}; };
#[cfg(test)]
use crate::{actors::GlobalActors, db};
pub struct ClientSession { pub struct ClientSession {
props: ClientConnection, props: ClientConnection,
client_id: i32, client_id: Verified<i32>,
} }
impl ClientSession { impl ClientSession {
pub(crate) fn new(props: ClientConnection, client_id: i32) -> Self { pub(crate) fn new(props: ClientConnection, client_id: Verified<i32>) -> Self {
Self { props, client_id } Self { props, client_id }
} }
} }
@@ -54,7 +56,7 @@ impl ClientSession {
.actors .actors
.evm .evm
.ask(ClientSignTransaction { .ask(ClientSignTransaction {
client_id: self.client_id, client_id: *self.client_id,
wallet_address, wallet_address,
transaction, transaction,
}) })
@@ -92,11 +94,12 @@ impl Actor for ClientSession {
} }
impl ClientSession { impl ClientSession {
#[cfg(test)]
pub fn new_test(db: db::DatabasePool, actors: GlobalActors) -> Self { pub fn new_test(db: db::DatabasePool, actors: GlobalActors) -> Self {
let props = ClientConnection::new(db, actors); let props = ClientConnection::new(db, actors);
Self { Self {
props, props,
client_id: 0, client_id: Verified::new_unchecked(0),
} }
} }
} }

View File

@@ -1,15 +1,14 @@
use alloy::{consensus::TxEip1559, primitives::Address, signers::Signature}; use alloy::{consensus::TxEip1559, primitives::Address, signers::Signature};
use diesel::{ use diesel::{
BoolExpressionMethods as _, ExpressionMethods, OptionalExtension as _, QueryDsl, ExpressionMethods, OptionalExtension as _, QueryDsl, SelectableHelper as _, dsl::insert_into,
SelectableHelper as _, dsl::insert_into,
}; };
use diesel_async::{AsyncConnection as _, RunQueryDsl}; use diesel_async::RunQueryDsl;
use kameo::{Actor, actor::ActorRef, messages}; use kameo::{Actor, actor::ActorRef, messages};
use rand::{SeedableRng, rng, rngs::StdRng}; use rand::{SeedableRng, rng, rngs::StdRng};
use crate::{ use crate::{
actors::keyholder::{CreateNew, Decrypt, KeyHolder}, actors::keyholder::{CreateNew, Decrypt, KeyHolder},
crypto::integrity, crypto::integrity::{self, Integrable, Verified, hashing::Hashable},
db::{ db::{
DatabaseError, DatabasePool, DatabaseError, DatabasePool,
models::{self}, models::{self},
@@ -27,11 +26,37 @@ use crate::{
pub use crate::evm::safe_signer; pub use crate::evm::safe_signer;
/// Hashable structure for wallet integrity protection.
/// Binds the encrypted private key to the wallet address using HMAC.
pub struct EvmWalletIntegrity {
pub address: Vec<u8>, // 20-byte Ethereum address
pub aead_encrypted_id: i32, // Reference to encrypted key material
}
impl Hashable for EvmWalletIntegrity {
fn hash<H: sha2::Digest>(&self, hasher: &mut H) {
hasher.update(&self.address);
hasher.update(self.aead_encrypted_id.to_be_bytes());
}
}
impl Integrable for EvmWalletIntegrity {
const KIND: &'static str = "evm_wallet";
}
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum SignTransactionError { pub enum SignTransactionError {
#[error("Wallet not found")] #[error("Wallet not found")]
WalletNotFound, WalletNotFound,
#[error("Wallet integrity check failed")]
WalletIntegrityCheckFailed,
#[error(
"Decrypted key does not correspond to wallet address (CRITICAL: possible key substitution attack)"
)]
KeyAddressMismatch,
#[error("Database error: {0}")] #[error("Database error: {0}")]
Database(#[from] DatabaseError), Database(#[from] DatabaseError),
@@ -46,6 +71,9 @@ pub enum SignTransactionError {
#[error("Policy error: {0}")] #[error("Policy error: {0}")]
Vet(#[from] evm::VetError), Vet(#[from] evm::VetError),
#[error("Integrity error: {0}")]
Integrity(#[from] integrity::Error),
} }
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
@@ -89,7 +117,7 @@ impl EvmActor {
#[messages] #[messages]
impl EvmActor { impl EvmActor {
#[message] #[message]
pub async fn generate(&mut self) -> Result<(i32, Address), Error> { pub async fn generate(&mut self) -> Result<(Verified<i32>, Address), Error> {
let (mut key_cell, address) = safe_signer::generate(&mut self.rng); let (mut key_cell, address) = safe_signer::generate(&mut self.rng);
let plaintext = key_cell.read_inline(|reader| SafeCell::new(reader.to_vec())); let plaintext = key_cell.read_inline(|reader| SafeCell::new(reader.to_vec()));
@@ -101,7 +129,7 @@ impl EvmActor {
.map_err(|_| Error::KeyholderSend)?; .map_err(|_| Error::KeyholderSend)?;
let mut conn = self.db.get().await.map_err(DatabaseError::from)?; let mut conn = self.db.get().await.map_err(DatabaseError::from)?;
let wallet_id = insert_into(schema::evm_wallet::table) let wallet_id: i32 = insert_into(schema::evm_wallet::table)
.values(&models::NewEvmWallet { .values(&models::NewEvmWallet {
address: address.as_slice().to_vec(), address: address.as_slice().to_vec(),
aead_encrypted_id: aead_id, aead_encrypted_id: aead_id,
@@ -111,7 +139,17 @@ impl EvmActor {
.await .await
.map_err(DatabaseError::from)?; .map_err(DatabaseError::from)?;
Ok((wallet_id, address)) // Sign integrity envelope to bind encrypted key to wallet address
let wallet_integrity = EvmWalletIntegrity {
address: address.as_slice().to_vec(),
aead_encrypted_id: aead_id,
};
let verified_wallet_id =
integrity::sign_entity(&mut conn, &self.keyholder, &wallet_integrity, wallet_id)
.await?
.unqualify_origin();
Ok((verified_wallet_id, address))
} }
#[message] #[message]
@@ -137,7 +175,7 @@ impl EvmActor {
&mut self, &mut self,
basic: SharedGrantSettings, basic: SharedGrantSettings,
grant: SpecificGrant, grant: SpecificGrant,
) -> Result<i32, Error> { ) -> Result<integrity::Verified<i32>, Error> {
match grant { match grant {
SpecificGrant::EtherTransfer(settings) => self SpecificGrant::EtherTransfer(settings) => self
.engine .engine
@@ -159,115 +197,28 @@ impl EvmActor {
} }
#[message] #[message]
pub async fn useragent_delete_grant(&mut self, grant_id: i32) -> Result<(), Error> { pub async fn useragent_delete_grant(&mut self, _grant_id: i32) -> Result<(), Error> {
let mut conn = self.db.get().await.map_err(DatabaseError::from)?; // let mut conn = self.db.get().await.map_err(DatabaseError::from)?;
// let keyholder = self.keyholder.clone();
// We intentionally perform a hard delete here to avoid leaving revoked grants and their // diesel_async::AsyncConnection::transaction(&mut conn, |conn| {
// related rows as long-lived DB garbage. We also don't rely on SQLite FK cascades because // Box::pin(async move {
// they can be disabled per-connection. // diesel::update(schema::evm_basic_grant::table)
conn.transaction(|conn| { // .filter(schema::evm_basic_grant::id.eq(grant_id))
Box::pin(async move { // .set(schema::evm_basic_grant::revoked_at.eq(SqliteTimestamp::now()))
// First, resolve policy-specific rows by basic grant id. // .execute(conn)
let token_grant_id: Option<i32> = schema::evm_token_transfer_grant::table // .await?;
.select(schema::evm_token_transfer_grant::id)
.filter(schema::evm_token_transfer_grant::basic_grant_id.eq(grant_id))
.first::<i32>(conn)
.await
.optional()?;
let ether_grant: Option<(i32, i32)> = schema::evm_ether_transfer_grant::table // let signed = integrity::evm::load_signed_grant_by_basic_id(conn, grant_id).await?;
.select((
schema::evm_ether_transfer_grant::id,
schema::evm_ether_transfer_grant::limit_id,
))
.filter(schema::evm_ether_transfer_grant::basic_grant_id.eq(grant_id))
.first::<(i32, i32)>(conn)
.await
.optional()?;
// Token-transfer: logs must be deleted before transaction logs (FK restrict). // diesel::result::QueryResult::Ok(())
if let Some(token_grant_id) = token_grant_id { // })
diesel::delete( // })
schema::evm_token_transfer_log::table // .await
.filter(schema::evm_token_transfer_log::grant_id.eq(token_grant_id)), // .map_err(DatabaseError::from)?;
)
.execute(conn)
.await?;
diesel::delete(schema::evm_token_transfer_volume_limit::table.filter( // Ok(())
schema::evm_token_transfer_volume_limit::grant_id.eq(token_grant_id), todo!()
))
.execute(conn)
.await?;
diesel::delete(
schema::evm_token_transfer_grant::table
.filter(schema::evm_token_transfer_grant::id.eq(token_grant_id)),
)
.execute(conn)
.await?;
}
// Shared transaction logs for any grant kind.
diesel::delete(
schema::evm_transaction_log::table
.filter(schema::evm_transaction_log::grant_id.eq(grant_id)),
)
.execute(conn)
.await?;
// Ether-transfer: delete targets, grant row, then its limit row.
if let Some((ether_grant_id, limit_id)) = ether_grant {
diesel::delete(schema::evm_ether_transfer_grant_target::table.filter(
schema::evm_ether_transfer_grant_target::grant_id.eq(ether_grant_id),
))
.execute(conn)
.await?;
diesel::delete(
schema::evm_ether_transfer_grant::table
.filter(schema::evm_ether_transfer_grant::id.eq(ether_grant_id)),
)
.execute(conn)
.await?;
diesel::delete(
schema::evm_ether_transfer_limit::table
.filter(schema::evm_ether_transfer_limit::id.eq(limit_id)),
)
.execute(conn)
.await?;
}
// Integrity envelopes are not FK-constrained; delete only grant-related kinds to
// avoid accidentally deleting other entities that share the same integer ID.
let entity_id = grant_id.to_be_bytes().to_vec();
diesel::delete(
schema::integrity_envelope::table
.filter(schema::integrity_envelope::entity_id.eq(entity_id))
.filter(
schema::integrity_envelope::entity_kind
.eq("EtherTransfer")
.or(schema::integrity_envelope::entity_kind.eq("TokenTransfer")),
),
)
.execute(conn)
.await?;
// Finally remove the basic grant row itself (idempotent if it doesn't exist).
diesel::delete(
schema::evm_basic_grant::table.filter(schema::evm_basic_grant::id.eq(grant_id)),
)
.execute(conn)
.await?;
diesel::result::QueryResult::Ok(())
})
})
.await
.map_err(DatabaseError::from)?;
Ok(())
} }
#[message] #[message]
@@ -295,9 +246,23 @@ impl EvmActor {
.optional() .optional()
.map_err(DatabaseError::from)? .map_err(DatabaseError::from)?
.ok_or(SignTransactionError::WalletNotFound)?; .ok_or(SignTransactionError::WalletNotFound)?;
// Verify wallet integrity envelope
let wallet = integrity::verify_entity(
&mut conn,
&self.keyholder,
EvmWalletIntegrity {
address: wallet.address.clone(),
aead_encrypted_id: wallet.aead_encrypted_id,
},
wallet.id,
)
.await
.map_err(|_| SignTransactionError::WalletIntegrityCheckFailed)?;
let wallet_access = schema::evm_wallet_access::table let wallet_access = schema::evm_wallet_access::table
.select(models::EvmWalletAccess::as_select()) .select(models::EvmWalletAccess::as_select())
.filter(schema::evm_wallet_access::wallet_id.eq(wallet.id)) .filter(schema::evm_wallet_access::wallet_id.eq(wallet.entity_id))
.filter(schema::evm_wallet_access::client_id.eq(client_id)) .filter(schema::evm_wallet_access::client_id.eq(client_id))
.first(&mut conn) .first(&mut conn)
.await .await
@@ -330,9 +295,23 @@ impl EvmActor {
.optional() .optional()
.map_err(DatabaseError::from)? .map_err(DatabaseError::from)?
.ok_or(SignTransactionError::WalletNotFound)?; .ok_or(SignTransactionError::WalletNotFound)?;
// Verify wallet integrity envelope to ensure encrypted key is bound to address
let wallet = integrity::verify_entity(
&mut conn,
&self.keyholder,
EvmWalletIntegrity {
address: wallet.address.clone(),
aead_encrypted_id: wallet.aead_encrypted_id,
},
wallet.id,
)
.await
.map_err(|_| SignTransactionError::WalletIntegrityCheckFailed)?;
let wallet_access = schema::evm_wallet_access::table let wallet_access = schema::evm_wallet_access::table
.select(models::EvmWalletAccess::as_select()) .select(models::EvmWalletAccess::as_select())
.filter(schema::evm_wallet_access::wallet_id.eq(wallet.id)) .filter(schema::evm_wallet_access::wallet_id.eq(wallet.entity_id))
.filter(schema::evm_wallet_access::client_id.eq(client_id)) .filter(schema::evm_wallet_access::client_id.eq(client_id))
.first(&mut conn) .first(&mut conn)
.await .await
@@ -351,6 +330,12 @@ impl EvmActor {
let signer = safe_signer::SafeSigner::from_cell(raw_key)?; let signer = safe_signer::SafeSigner::from_cell(raw_key)?;
// Verify that the decrypted key's derived address matches the wallet address
// This prevents an attacker from substituting one wallet's key with another's even if they compromised the DB
if signer.address() != wallet_address {
return Err(SignTransactionError::KeyAddressMismatch);
}
self.engine self.engine
.evaluate_transaction(wallet_access, transaction.clone(), RunKind::Execution) .evaluate_transaction(wallet_access, transaction.clone(), RunKind::Execution)
.await?; .await?;
@@ -359,6 +344,3 @@ impl EvmActor {
Ok(signer.sign_transaction_sync(&mut transaction)?) Ok(signer.sign_transaction_sync(&mut transaction)?)
} }
} }
#[cfg(test)]
mod tests;

View File

@@ -1,283 +0,0 @@
use diesel::{ExpressionMethods as _, QueryDsl as _, dsl::insert_into};
use diesel_async::RunQueryDsl;
use kameo::actor::Spawn as _;
use crate::{
actors::{evm::EvmActor, keyholder::KeyHolder},
db::{self, models, schema},
};
#[tokio::test]
async fn delete_ether_grant_cleans_related_tables() {
let db = db::create_test_pool().await;
let keyholder = KeyHolder::spawn(KeyHolder::new(db.clone()).await.unwrap());
let mut actor = EvmActor::new(keyholder, db.clone());
let mut conn = db.get().await.unwrap();
let basic_id: i32 = insert_into(schema::evm_basic_grant::table)
.values(&models::NewEvmBasicGrant {
wallet_access_id: 1,
chain_id: 1,
valid_from: None,
valid_until: None,
max_gas_fee_per_gas: None,
max_priority_fee_per_gas: None,
rate_limit_count: None,
rate_limit_window_secs: None,
revoked_at: None,
})
.returning(schema::evm_basic_grant::id)
.get_result(&mut conn)
.await
.unwrap();
let limit_id: i32 = insert_into(schema::evm_ether_transfer_limit::table)
.values(&models::NewEvmEtherTransferLimit {
window_secs: 60,
max_volume: vec![1],
})
.returning(schema::evm_ether_transfer_limit::id)
.get_result(&mut conn)
.await
.unwrap();
let ether_grant_id: i32 = insert_into(schema::evm_ether_transfer_grant::table)
.values(&models::NewEvmEtherTransferGrant {
basic_grant_id: basic_id,
limit_id,
})
.returning(schema::evm_ether_transfer_grant::id)
.get_result(&mut conn)
.await
.unwrap();
insert_into(schema::evm_ether_transfer_grant_target::table)
.values(&models::NewEvmEtherTransferGrantTarget {
grant_id: ether_grant_id,
address: vec![0u8; 20],
})
.execute(&mut conn)
.await
.unwrap();
insert_into(schema::evm_transaction_log::table)
.values(&models::NewEvmTransactionLog {
grant_id: basic_id,
wallet_access_id: 1,
chain_id: 1,
eth_value: vec![0],
signed_at: models::SqliteTimestamp::now(),
})
.execute(&mut conn)
.await
.unwrap();
insert_into(schema::integrity_envelope::table)
.values(&models::NewIntegrityEnvelope {
entity_kind: "EtherTransfer".to_owned(),
entity_id: basic_id.to_be_bytes().to_vec(),
payload_version: 1,
key_version: 1,
mac: vec![0u8; 32],
})
.execute(&mut conn)
.await
.unwrap();
drop(conn);
actor.useragent_delete_grant(basic_id).await.unwrap();
// Idempotency: second delete should be a no-op.
actor.useragent_delete_grant(basic_id).await.unwrap();
let mut conn = db.get().await.unwrap();
let basic_count: i64 = schema::evm_basic_grant::table
.count()
.get_result(&mut conn)
.await
.unwrap();
assert_eq!(basic_count, 0);
let ether_grant_count: i64 = schema::evm_ether_transfer_grant::table
.count()
.get_result(&mut conn)
.await
.unwrap();
assert_eq!(ether_grant_count, 0);
let target_count: i64 = schema::evm_ether_transfer_grant_target::table
.count()
.get_result(&mut conn)
.await
.unwrap();
assert_eq!(target_count, 0);
let limit_count: i64 = schema::evm_ether_transfer_limit::table
.count()
.get_result(&mut conn)
.await
.unwrap();
assert_eq!(limit_count, 0);
let log_count: i64 = schema::evm_transaction_log::table
.count()
.get_result(&mut conn)
.await
.unwrap();
assert_eq!(log_count, 0);
let envelope_count: i64 = schema::integrity_envelope::table
.filter(schema::integrity_envelope::entity_kind.eq("EtherTransfer"))
.count()
.get_result(&mut conn)
.await
.unwrap();
assert_eq!(envelope_count, 0);
}
#[tokio::test]
async fn delete_token_grant_cleans_related_tables() {
let db = db::create_test_pool().await;
let keyholder = KeyHolder::spawn(KeyHolder::new(db.clone()).await.unwrap());
let mut actor = EvmActor::new(keyholder, db.clone());
let mut conn = db.get().await.unwrap();
let basic_id: i32 = insert_into(schema::evm_basic_grant::table)
.values(&models::NewEvmBasicGrant {
wallet_access_id: 1,
chain_id: 1,
valid_from: None,
valid_until: None,
max_gas_fee_per_gas: None,
max_priority_fee_per_gas: None,
rate_limit_count: None,
rate_limit_window_secs: None,
revoked_at: None,
})
.returning(schema::evm_basic_grant::id)
.get_result(&mut conn)
.await
.unwrap();
let token_grant_id: i32 = insert_into(schema::evm_token_transfer_grant::table)
.values(&models::NewEvmTokenTransferGrant {
basic_grant_id: basic_id,
token_contract: vec![1u8; 20],
receiver: None,
})
.returning(schema::evm_token_transfer_grant::id)
.get_result(&mut conn)
.await
.unwrap();
insert_into(schema::evm_token_transfer_volume_limit::table)
.values(&models::NewEvmTokenTransferVolumeLimit {
grant_id: token_grant_id,
window_secs: 60,
max_volume: vec![1],
})
.execute(&mut conn)
.await
.unwrap();
insert_into(schema::evm_token_transfer_volume_limit::table)
.values(&models::NewEvmTokenTransferVolumeLimit {
grant_id: token_grant_id,
window_secs: 3600,
max_volume: vec![2],
})
.execute(&mut conn)
.await
.unwrap();
let tx_log_id: i32 = insert_into(schema::evm_transaction_log::table)
.values(&models::NewEvmTransactionLog {
grant_id: basic_id,
wallet_access_id: 1,
chain_id: 1,
eth_value: vec![0],
signed_at: models::SqliteTimestamp::now(),
})
.returning(schema::evm_transaction_log::id)
.get_result(&mut conn)
.await
.unwrap();
insert_into(schema::evm_token_transfer_log::table)
.values(&models::NewEvmTokenTransferLog {
grant_id: token_grant_id,
log_id: tx_log_id,
chain_id: 1,
token_contract: vec![1u8; 20],
recipient_address: vec![2u8; 20],
value: vec![3],
})
.execute(&mut conn)
.await
.unwrap();
insert_into(schema::integrity_envelope::table)
.values(&models::NewIntegrityEnvelope {
entity_kind: "TokenTransfer".to_owned(),
entity_id: basic_id.to_be_bytes().to_vec(),
payload_version: 1,
key_version: 1,
mac: vec![0u8; 32],
})
.execute(&mut conn)
.await
.unwrap();
drop(conn);
actor.useragent_delete_grant(basic_id).await.unwrap();
let mut conn = db.get().await.unwrap();
let basic_count: i64 = schema::evm_basic_grant::table
.count()
.get_result(&mut conn)
.await
.unwrap();
assert_eq!(basic_count, 0);
let token_grant_count: i64 = schema::evm_token_transfer_grant::table
.count()
.get_result(&mut conn)
.await
.unwrap();
assert_eq!(token_grant_count, 0);
let token_limits_count: i64 = schema::evm_token_transfer_volume_limit::table
.count()
.get_result(&mut conn)
.await
.unwrap();
assert_eq!(token_limits_count, 0);
let token_logs_count: i64 = schema::evm_token_transfer_log::table
.count()
.get_result(&mut conn)
.await
.unwrap();
assert_eq!(token_logs_count, 0);
let tx_logs_count: i64 = schema::evm_transaction_log::table
.count()
.get_result(&mut conn)
.await
.unwrap();
assert_eq!(tx_logs_count, 0);
let envelope_count: i64 = schema::integrity_envelope::table
.filter(schema::integrity_envelope::entity_kind.eq("TokenTransfer"))
.count()
.get_result(&mut conn)
.await
.unwrap();
assert_eq!(envelope_count, 0);
}

View File

@@ -30,17 +30,26 @@ pub enum Error {
} }
impl Error { impl Error {
fn internal(details: impl Into<String>) -> Self { #[track_caller]
Self::Internal { pub(super) fn internal(details: impl Into<String>, err: &impl std::fmt::Debug) -> Self {
details: details.into(), let details = details.into();
} let caller = std::panic::Location::caller();
error!(
caller_file = %caller.file(),
caller_line = caller.line(),
caller_column = caller.column(),
details = %details,
error = ?err,
"Internal error"
);
Self::Internal { details }
} }
} }
impl From<diesel::result::Error> for Error { impl From<diesel::result::Error> for Error {
fn from(e: diesel::result::Error) -> Self { fn from(e: diesel::result::Error) -> Self {
error!(?e, "Database error"); Self::internal("Database error", &e)
Self::internal("Database error")
} }
} }

View File

@@ -1,7 +1,7 @@
use arbiter_proto::transport::Bi; use arbiter_proto::transport::Bi;
use diesel::{ExpressionMethods as _, OptionalExtension as _, QueryDsl, update}; use diesel::{ExpressionMethods as _, OptionalExtension as _, QueryDsl, update};
use diesel_async::{AsyncConnection, RunQueryDsl}; use diesel_async::{AsyncConnection, RunQueryDsl};
use kameo::{actor::ActorRef, error::SendError}; use kameo::actor::ActorRef;
use tracing::error; use tracing::error;
use super::Error; use super::Error;
@@ -11,7 +11,7 @@ use crate::{
keyholder::KeyHolder, keyholder::KeyHolder,
user_agent::{AuthPublicKey, UserAgentConnection, UserAgentCredentials, auth::Outbound}, user_agent::{AuthPublicKey, UserAgentConnection, UserAgentCredentials, auth::Outbound},
}, },
crypto::integrity::{self, AttestationStatus}, crypto::integrity,
db::{DatabasePool, schema::useragent_client}, db::{DatabasePool, schema::useragent_client},
}; };
@@ -48,10 +48,10 @@ async fn get_current_nonce_and_id(
db: &DatabasePool, db: &DatabasePool,
key: &AuthPublicKey, key: &AuthPublicKey,
) -> Result<(i32, i32), Error> { ) -> Result<(i32, i32), Error> {
let mut db_conn = db.get().await.map_err(|e| { let mut db_conn = db
error!(error = ?e, "Database pool error"); .get()
Error::internal("Database unavailable") .await
})?; .map_err(|e| Error::internal("Database unavailable", &e))?;
db_conn db_conn
.exclusive_transaction(|conn| { .exclusive_transaction(|conn| {
Box::pin(async move { Box::pin(async move {
@@ -65,10 +65,7 @@ async fn get_current_nonce_and_id(
}) })
.await .await
.optional() .optional()
.map_err(|e| { .map_err(|e| Error::internal("Database operation failed", &e))?
error!(error = ?e, "Database error");
Error::internal("Database operation failed")
})?
.ok_or_else(|| { .ok_or_else(|| {
error!(?key, "Public key not found in database"); error!(?key, "Public key not found in database");
Error::UnregisteredPublicKey Error::UnregisteredPublicKey
@@ -80,14 +77,14 @@ async fn verify_integrity(
keyholder: &ActorRef<KeyHolder>, keyholder: &ActorRef<KeyHolder>,
pubkey: &AuthPublicKey, pubkey: &AuthPublicKey,
) -> Result<(), Error> { ) -> Result<(), Error> {
let mut db_conn = db.get().await.map_err(|e| { let mut db_conn = db
error!(error = ?e, "Database pool error"); .get()
Error::internal("Database unavailable") .await
})?; .map_err(|e| Error::internal("Database unavailable", &e))?;
let (id, nonce) = get_current_nonce_and_id(db, pubkey).await?; let (id, nonce) = get_current_nonce_and_id(db, pubkey).await?;
let result = integrity::verify_entity( let attestation_status = integrity::check_entity_attestation(
&mut db_conn, &mut db_conn,
keyholder, keyholder,
&UserAgentCredentials { &UserAgentCredentials {
@@ -97,13 +94,17 @@ async fn verify_integrity(
id, id,
) )
.await .await
.map_err(|e| { .map_err(|e| Error::internal("Integrity verification failed", &e))?;
error!(?e, "Integrity verification failed");
Error::internal("Integrity verification failed")
})?;
Ok(())
use integrity::AttestationStatus as AS;
// SAFETY (policy): challenge auth must work in both vault states.
// While sealed, integrity checks can only report `Unavailable` because key material is not
// accessible. While unsealed, the same check can report `Attested`.
// This path intentionally accepts both outcomes to keep challenge auth available across state
// transitions; stricter verification is enforced in sensitive post-auth flows.
match attestation_status {
AS::Attested | AS::Unavailable => Ok(()),
}
} }
async fn create_nonce( async fn create_nonce(
@@ -111,10 +112,10 @@ async fn create_nonce(
keyholder: &ActorRef<KeyHolder>, keyholder: &ActorRef<KeyHolder>,
pubkey: &AuthPublicKey, pubkey: &AuthPublicKey,
) -> Result<i32, Error> { ) -> Result<i32, Error> {
let mut db_conn = db.get().await.map_err(|e| { let mut db_conn = db
error!(error = ?e, "Database pool error"); .get()
Error::internal("Database unavailable") .await
})?; .map_err(|e| Error::internal("Database unavailable", &e))?;
let new_nonce = db_conn let new_nonce = db_conn
.exclusive_transaction(|conn| { .exclusive_transaction(|conn| {
Box::pin(async move { Box::pin(async move {
@@ -125,10 +126,7 @@ async fn create_nonce(
.returning((useragent_client::id, useragent_client::nonce)) .returning((useragent_client::id, useragent_client::nonce))
.get_result(conn) .get_result(conn)
.await .await
.map_err(|e| { .map_err(|e| Error::internal("Database operation failed", &e))?;
error!(error = ?e, "Database error");
Error::internal("Database operation failed")
})?;
integrity::sign_entity( integrity::sign_entity(
conn, conn,
@@ -140,10 +138,8 @@ async fn create_nonce(
id, id,
) )
.await .await
.map_err(|e| { .map_err(|e| Error::internal("Database error", &e))?
error!(?e, "Integrity signature update failed"); .drop_verification_provenance();
Error::internal("Database error")
})?;
Result::<_, Error>::Ok(new_nonce) Result::<_, Error>::Ok(new_nonce)
}) })
@@ -159,10 +155,10 @@ async fn register_key(
) -> Result<(), Error> { ) -> Result<(), Error> {
let pubkey_bytes = pubkey.to_stored_bytes(); let pubkey_bytes = pubkey.to_stored_bytes();
let key_type = pubkey.key_type(); let key_type = pubkey.key_type();
let mut conn = db.get().await.map_err(|e| { let mut conn = db
error!(error = ?e, "Database pool error"); .get()
Error::internal("Database unavailable") .await
})?; .map_err(|e| Error::internal("Database unavailable", &e))?;
conn.transaction(|conn| { conn.transaction(|conn| {
Box::pin(async move { Box::pin(async move {
@@ -177,22 +173,32 @@ async fn register_key(
.returning(useragent_client::id) .returning(useragent_client::id)
.get_result(conn) .get_result(conn)
.await .await
.map_err(|e| { .map_err(|e| Error::internal("Database operation failed", &e))?;
error!(error = ?e, "Database error");
Error::internal("Database operation failed")
})?;
let entity = UserAgentCredentials { if let Err(e) = integrity::sign_entity(
pubkey: pubkey.clone(), conn,
nonce: NONCE_START, keyholder,
}; &UserAgentCredentials {
pubkey: pubkey.clone(),
integrity::sign_entity(conn, &keyholder, &entity, id) nonce: NONCE_START,
.await },
.map_err(|e| { id,
error!(error = ?e, "Failed to sign integrity tag for new user-agent key"); )
Error::internal("Failed to register public key") .await
})?; {
match e {
integrity::Error::Keyholder(
crate::actors::keyholder::Error::NotBootstrapped,
) => {
// IMPORTANT: bootstrap-token auth must work before the vault has a root key.
// We intentionally allow creating the DB row first and backfill envelopes
// after bootstrap/unseal to keep the bootstrap flow possible.
}
other => {
return Err(Error::internal("Failed to register public key", &other));
}
}
}
Result::<_, Error>::Ok(()) Result::<_, Error>::Ok(())
}) })
@@ -255,10 +261,7 @@ where
token: token.clone(), token: token.clone(),
}) })
.await .await
.map_err(|e| { .map_err(|e| Error::internal("Failed to consume bootstrap token", &e))?;
error!(?e, "Failed to consume bootstrap token");
Error::internal("Failed to consume bootstrap token")
})?;
if !token_ok { if !token_ok {
error!("Invalid bootstrap token provided"); error!("Invalid bootstrap token provided");

View File

@@ -1,59 +1,23 @@
use crate::{ use crate::{
actors::{GlobalActors, client::ClientProfile}, crypto::integrity::Integrable, db::{self, models::KeyType} actors::{GlobalActors, client::ClientProfile},
crypto::integrity::Integrable,
db::{self, models::KeyType},
}; };
fn serialize_ecdsa<S>(key: &k256::ecdsa::VerifyingKey, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
// Serialize as hex string for easier debugging (33 bytes compressed SEC1 format)
let key = key.to_encoded_point(true);
let bytes = key.as_bytes();
serializer.serialize_bytes(bytes)
}
fn deserialize_ecdsa<'de, D>(deserializer: D) -> Result<k256::ecdsa::VerifyingKey, D::Error>
where
D: serde::Deserializer<'de>,
{
struct EcdsaVisitor;
impl<'de> serde::de::Visitor<'de> for EcdsaVisitor {
type Value = k256::ecdsa::VerifyingKey;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("a compressed SEC1-encoded ECDSA public key")
}
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
let point = k256::EncodedPoint::from_bytes(v)
.map_err(|_| E::custom("invalid compressed SEC1 format"))?;
k256::ecdsa::VerifyingKey::from_encoded_point(&point)
.map_err(|_| E::custom("invalid ECDSA public key"))
}
}
deserializer.deserialize_bytes(EcdsaVisitor)
}
/// Abstraction over Ed25519 / ECDSA-secp256k1 / RSA public keys used during the auth handshake. /// Abstraction over Ed25519 / ECDSA-secp256k1 / RSA public keys used during the auth handshake.
#[derive(Clone, Debug, Serialize)] #[derive(Clone, Debug)]
pub enum AuthPublicKey { pub enum AuthPublicKey {
Ed25519(ed25519_dalek::VerifyingKey), Ed25519(ed25519_dalek::VerifyingKey),
/// Compressed SEC1 public key; signature bytes are raw 64-byte (r||s). /// Compressed SEC1 public key; signature bytes are raw 64-byte (r||s).
#[serde(serialize_with = "serialize_ecdsa", deserialize_with = "deserialize_ecdsa")]
EcdsaSecp256k1(k256::ecdsa::VerifyingKey), EcdsaSecp256k1(k256::ecdsa::VerifyingKey),
/// RSA-2048+ public key (Windows Hello / KeyCredentialManager); signature bytes are PSS+SHA-256. /// RSA-2048+ public key (Windows Hello / KeyCredentialManager); signature bytes are PSS+SHA-256.
Rsa(rsa::RsaPublicKey), Rsa(rsa::RsaPublicKey),
} }
#[derive(Debug, Serialize)] #[derive(Debug)]
pub struct UserAgentCredentials { pub struct UserAgentCredentials {
pub pubkey: AuthPublicKey, pub pubkey: AuthPublicKey,
pub nonce: i32 pub nonce: i32,
} }
impl Integrable for UserAgentCredentials { impl Integrable for UserAgentCredentials {
@@ -138,5 +102,19 @@ pub mod auth;
pub mod session; pub mod session;
pub use auth::authenticate; pub use auth::authenticate;
use serde::Serialize;
pub use session::UserAgentSession; pub use session::UserAgentSession;
use crate::crypto::integrity::hashing::Hashable;
impl Hashable for AuthPublicKey {
fn hash<H: sha2::Digest>(&self, hasher: &mut H) {
hasher.update(self.to_stored_bytes());
}
}
impl Hashable for UserAgentCredentials {
fn hash<H: sha2::Digest>(&self, hasher: &mut H) {
self.pubkey.hash(hasher);
self.nonce.hash(hasher);
}
}

View File

@@ -10,7 +10,6 @@ use kameo::prelude::Context;
use tracing::{error, info}; use tracing::{error, info};
use x25519_dalek::{EphemeralSecret, PublicKey}; use x25519_dalek::{EphemeralSecret, PublicKey};
use crate::actors::flow_coordinator::client_connect_approval::ClientApprovalAnswer;
use crate::actors::keyholder::KeyHolderState; use crate::actors::keyholder::KeyHolderState;
use crate::actors::user_agent::session::Error; use crate::actors::user_agent::session::Error;
use crate::db::models::{ use crate::db::models::{
@@ -18,6 +17,10 @@ use crate::db::models::{
}; };
use crate::evm::policies::{Grant, SpecificGrant}; use crate::evm::policies::{Grant, SpecificGrant};
use crate::safe_cell::SafeCell; use crate::safe_cell::SafeCell;
use crate::{
actors::flow_coordinator::client_connect_approval::ClientApprovalAnswer,
crypto::integrity::{self, Verified},
};
use crate::{ use crate::{
actors::{ actors::{
evm::{ evm::{
@@ -29,11 +32,67 @@ use crate::{
UserAgentSession, UserAgentSession,
state::{UnsealContext, UserAgentEvents, UserAgentStates}, state::{UnsealContext, UserAgentEvents, UserAgentStates},
}, },
user_agent::{AuthPublicKey, UserAgentCredentials},
}, },
db::schema::useragent_client,
safe_cell::SafeCellHandle as _, safe_cell::SafeCellHandle as _,
}; };
fn is_vault_sealed_from_evm<M>(err: &SendError<M, crate::actors::evm::Error>) -> bool {
matches!(
err,
SendError::HandlerError(crate::actors::evm::Error::Keyholder(
keyholder::Error::NotBootstrapped
)) | SendError::HandlerError(crate::actors::evm::Error::Integrity(
crate::crypto::integrity::Error::Keyholder(keyholder::Error::NotBootstrapped)
))
)
}
impl UserAgentSession { impl UserAgentSession {
async fn backfill_useragent_integrity(&self) -> Result<(), Error> {
let mut conn = self.props.db.get().await?;
let keyholder = self.props.actors.key_holder.clone();
conn.transaction(|conn| {
Box::pin(async move {
let rows: Vec<(i32, i32, Vec<u8>, crate::db::models::KeyType)> =
useragent_client::table
.select((
useragent_client::id,
useragent_client::nonce,
useragent_client::public_key,
useragent_client::key_type,
))
.load(conn)
.await?;
for (id, nonce, public_key, key_type) in rows {
let pubkey = AuthPublicKey::try_from((key_type, public_key)).map_err(|e| {
Error::internal(format!("Invalid user-agent key in db: {e}"))
})?;
integrity::sign_entity(
conn,
&keyholder,
&UserAgentCredentials { pubkey, nonce },
id,
)
.await
.map_err(|e| {
Error::internal(format!("Failed to backfill user-agent integrity: {e}"))
})?
.drop_verification_provenance();
}
Result::<_, Error>::Ok(())
})
})
.await?;
Ok(())
}
fn take_unseal_secret(&mut self) -> Result<(EphemeralSecret, PublicKey), Error> { fn take_unseal_secret(&mut self) -> Result<(EphemeralSecret, PublicKey), Error> {
let UserAgentStates::WaitingForUnsealKey(unseal_context) = self.state.state() else { let UserAgentStates::WaitingForUnsealKey(unseal_context) = self.state.state() else {
error!("Received encrypted key in invalid state"); error!("Received encrypted key in invalid state");
@@ -191,6 +250,7 @@ impl UserAgentSession {
.await .await
{ {
Ok(_) => { Ok(_) => {
self.backfill_useragent_integrity().await?;
info!("Successfully unsealed key with client-provided key"); info!("Successfully unsealed key with client-provided key");
self.transition(UserAgentEvents::ReceivedValidKey)?; self.transition(UserAgentEvents::ReceivedValidKey)?;
Ok(()) Ok(())
@@ -252,6 +312,7 @@ impl UserAgentSession {
.await .await
{ {
Ok(_) => { Ok(_) => {
self.backfill_useragent_integrity().await?;
info!("Successfully bootstrapped vault with client-provided key"); info!("Successfully bootstrapped vault with client-provided key");
self.transition(UserAgentEvents::ReceivedValidKey)?; self.transition(UserAgentEvents::ReceivedValidKey)?;
Ok(()) Ok(())
@@ -297,7 +358,9 @@ impl UserAgentSession {
#[messages] #[messages]
impl UserAgentSession { impl UserAgentSession {
#[message] #[message]
pub(crate) async fn handle_evm_wallet_create(&mut self) -> Result<(i32, Address), Error> { pub(crate) async fn handle_evm_wallet_create(
&mut self,
) -> Result<(Verified<i32>, Address), Error> {
match self.props.actors.evm.ask(Generate {}).await { match self.props.actors.evm.ask(Generate {}).await {
Ok(address) => Ok(address), Ok(address) => Ok(address),
Err(SendError::HandlerError(err)) => Err(Error::internal(format!( Err(SendError::HandlerError(err)) => Err(Error::internal(format!(
@@ -325,12 +388,15 @@ impl UserAgentSession {
#[messages] #[messages]
impl UserAgentSession { impl UserAgentSession {
#[message] #[message]
pub(crate) async fn handle_grant_list(&mut self) -> Result<Vec<Grant<SpecificGrant>>, Error> { pub(crate) async fn handle_grant_list(
&mut self,
) -> Result<Vec<Grant<SpecificGrant>>, GrantMutationError> {
match self.props.actors.evm.ask(UseragentListGrants {}).await { match self.props.actors.evm.ask(UseragentListGrants {}).await {
Ok(grants) => Ok(grants), Ok(grants) => Ok(grants),
Err(err) if is_vault_sealed_from_evm(&err) => Err(GrantMutationError::VaultSealed),
Err(err) => { Err(err) => {
error!(?err, "EVM grant list failed"); error!(?err, "EVM grant list failed");
Err(Error::internal("Failed to list EVM grants")) Err(GrantMutationError::Internal)
} }
} }
} }
@@ -340,7 +406,7 @@ impl UserAgentSession {
&mut self, &mut self,
basic: crate::evm::policies::SharedGrantSettings, basic: crate::evm::policies::SharedGrantSettings,
grant: crate::evm::policies::SpecificGrant, grant: crate::evm::policies::SpecificGrant,
) -> Result<i32, GrantMutationError> { ) -> Result<Verified<i32>, GrantMutationError> {
match self match self
.props .props
.actors .actors
@@ -349,6 +415,7 @@ impl UserAgentSession {
.await .await
{ {
Ok(grant_id) => Ok(grant_id), Ok(grant_id) => Ok(grant_id),
Err(err) if is_vault_sealed_from_evm(&err) => Err(GrantMutationError::VaultSealed),
Err(err) => { Err(err) => {
error!(?err, "EVM grant create failed"); error!(?err, "EVM grant create failed");
Err(GrantMutationError::Internal) Err(GrantMutationError::Internal)
@@ -365,10 +432,13 @@ impl UserAgentSession {
.props .props
.actors .actors
.evm .evm
.ask(UseragentDeleteGrant { grant_id }) .ask(UseragentDeleteGrant {
_grant_id: grant_id,
})
.await .await
{ {
Ok(()) => Ok(()), Ok(()) => Ok(()),
Err(err) if is_vault_sealed_from_evm(&err) => Err(GrantMutationError::VaultSealed),
Err(err) => { Err(err) => {
error!(?err, "EVM grant delete failed"); error!(?err, "EVM grant delete failed");
Err(GrantMutationError::Internal) Err(GrantMutationError::Internal)

View File

@@ -1,3 +1,3 @@
pub mod v1; pub mod v1;
pub use v1::*; pub use v1::*;

View File

@@ -1,3 +1,3 @@
pub mod v1; pub mod v1;
pub use v1::*; pub use v1::*;

View File

@@ -1,23 +1,34 @@
use crate::{actors::keyholder, crypto::KeyCell,safe_cell::SafeCellHandle as _}; use crate::actors::keyholder;
use chacha20poly1305::Key; use hmac::Hmac;
use hmac::{Hmac, Mac as _};
use serde::Serialize;
use sha2::Sha256; use sha2::Sha256;
use std::future::Future;
use std::ops::Deref;
use std::pin::Pin;
use diesel::{ExpressionMethods as _, QueryDsl, dsl::insert_into, sqlite::Sqlite}; use diesel::{ExpressionMethods as _, QueryDsl, dsl::insert_into, sqlite::Sqlite};
use diesel_async::{AsyncConnection, RunQueryDsl}; use diesel_async::{AsyncConnection, RunQueryDsl};
use kameo::{actor::ActorRef, error::SendError}; use kameo::{actor::ActorRef, error::SendError};
use sha2::Digest as _; use sha2::Digest as _;
pub mod hashing;
pub mod verified;
use self::hashing::Hashable;
use crate::{ use crate::{
actors::keyholder::{KeyHolder, SignIntegrity, VerifyIntegrity}, actors::keyholder::{KeyHolder, SignIntegrity, VerifyIntegrity},
db::{ db::{
self, self,
models::{IntegrityEnvelope, NewIntegrityEnvelope}, models::{IntegrityEnvelope as IntegrityEnvelopeRow, NewIntegrityEnvelope},
schema::integrity_envelope, schema::integrity_envelope,
}, },
}; };
pub const CURRENT_PAYLOAD_VERSION: i32 = 1;
pub const INTEGRITY_SUBKEY_TAG: &[u8] = b"arbiter/db-integrity-key/v1";
pub type HmacSha256 = Hmac<Sha256>;
pub use self::verified::{Nested, Root, VerificationOrigin, Verified};
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
pub enum Error { pub enum Error {
#[error("Database error: {0}")] #[error("Database error: {0}")]
@@ -43,76 +54,93 @@ pub enum Error {
#[error("Integrity MAC mismatch for entity {entity_kind}")] #[error("Integrity MAC mismatch for entity {entity_kind}")]
MacMismatch { entity_kind: &'static str }, MacMismatch { entity_kind: &'static str },
#[error("Payload serialization error: {0}")]
PayloadSerialization(#[from] postcard::Error),
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[must_use]
pub enum AttestationStatus { pub enum AttestationStatus {
Attested, Attested,
Unavailable, Unavailable,
} }
pub const CURRENT_PAYLOAD_VERSION: i32 = 1; pub trait Integrable: Hashable {
pub const INTEGRITY_SUBKEY_TAG: &[u8] = b"arbiter/db-integrity-key/v1";
pub type HmacSha256 = Hmac<Sha256>;
pub trait Integrable: Serialize {
const KIND: &'static str; const KIND: &'static str;
const VERSION: i32 = 1; const VERSION: i32 = 1;
} }
fn payload_hash(payload: &[u8]) -> [u8; 32] { impl<T: Integrable> Integrable for &T {
Sha256::digest(payload).into() const KIND: &'static str = T::KIND;
const VERSION: i32 = T::VERSION;
} }
fn push_len_prefixed(out: &mut Vec<u8>, bytes: &[u8]) { #[derive(Debug, Clone)]
out.extend_from_slice(&(bytes.len() as u32).to_be_bytes()); pub struct EntityId(Vec<u8>);
out.extend_from_slice(bytes);
}
fn build_mac_input( impl Deref for EntityId {
entity_kind: &str, type Target = [u8];
entity_id: &[u8],
payload_version: i32,
payload_hash: &[u8; 32],
) -> Vec<u8> {
let mut out = Vec::with_capacity(8 + entity_kind.len() + entity_id.len() + 32);
push_len_prefixed(&mut out, entity_kind.as_bytes());
push_len_prefixed(&mut out, entity_id);
out.extend_from_slice(&payload_version.to_be_bytes());
out.extend_from_slice(payload_hash);
out
}
pub trait IntoId { fn deref(&self) -> &Self::Target {
fn into_id(self) -> Vec<u8>; &self.0
}
impl IntoId for i32 {
fn into_id(self) -> Vec<u8> {
self.to_be_bytes().to_vec()
} }
} }
impl IntoId for &'_ [u8] { impl From<i32> for EntityId {
fn into_id(self) -> Vec<u8> { fn from(value: i32) -> Self {
self.to_vec() Self(value.to_be_bytes().to_vec())
} }
} }
pub async fn sign_entity<E: Integrable>( impl From<&'_ [u8]> for EntityId {
fn from(bytes: &'_ [u8]) -> Self {
Self(bytes.to_vec())
}
}
pub async fn lookup_verified<E, Id, C, F, Fut>(
conn: &mut C,
keyholder: &ActorRef<KeyHolder>,
entity_id: Id,
load: F,
) -> Result<Verified<Entity<E, Id>, Nested<E>>, Error>
where
C: AsyncConnection<Backend = Sqlite>,
E: Integrable,
Id: Into<EntityId> + Clone,
F: FnOnce(&mut C) -> Fut,
Fut: Future<Output = Result<E, db::DatabaseError>>,
{
let entity = load(conn).await?;
verify_entity(conn, keyholder, entity, entity_id).await
}
pub async fn lookup_verified_from_query<E, Id, C, F>(
conn: &mut C,
keyholder: &ActorRef<KeyHolder>,
load: F,
) -> Result<Verified<Entity<E, Id>, Nested<E>>, Error>
where
C: AsyncConnection<Backend = Sqlite> + Send,
E: Integrable,
Id: Into<EntityId> + Clone,
F: for<'a> FnOnce(
&'a mut C,
) -> Pin<
Box<dyn Future<Output = Result<(Id, E), db::DatabaseError>> + Send + 'a>,
>,
{
let (entity_id, entity) = load(conn).await?;
verify_entity(conn, keyholder, entity, entity_id).await
}
pub async fn sign_entity<E: Integrable, Id: Into<EntityId> + Clone>(
conn: &mut impl AsyncConnection<Backend = Sqlite>, conn: &mut impl AsyncConnection<Backend = Sqlite>,
keyholder: &ActorRef<KeyHolder>, keyholder: &ActorRef<KeyHolder>,
entity: &E, entity: &E,
entity_id: impl IntoId, as_entity_id: Id,
) -> Result<(), Error> { ) -> Result<Verified<Id, Nested<E>>, Error> {
let payload = postcard::to_stdvec(entity)?; let payload_hash = payload_hash(entity);
let payload_hash = payload_hash(&payload);
let entity_id = entity_id.into_id(); let entity_id = as_entity_id.clone().into();
let mac_input = build_mac_input(E::KIND, &entity_id, E::VERSION, &payload_hash); let mac_input = build_mac_input(E::KIND, &entity_id, E::VERSION, &payload_hash);
@@ -127,8 +155,8 @@ pub async fn sign_entity<E: Integrable>(
insert_into(integrity_envelope::table) insert_into(integrity_envelope::table)
.values(NewIntegrityEnvelope { .values(NewIntegrityEnvelope {
entity_kind: E::KIND.to_owned(), entity_kind: E::KIND.to_owned(),
entity_id: entity_id, entity_id: entity_id.to_vec(),
payload_version: E::VERSION , payload_version: E::VERSION,
key_version, key_version,
mac: mac.to_vec(), mac: mac.to_vec(),
}) })
@@ -146,23 +174,25 @@ pub async fn sign_entity<E: Integrable>(
.await .await
.map_err(db::DatabaseError::from)?; .map_err(db::DatabaseError::from)?;
Ok(()) Ok(Verified::<Id, Nested<E>>::new(as_entity_id))
} }
pub async fn verify_entity<E: Integrable>( pub async fn check_entity_attestation<E: Integrable>(
conn: &mut impl AsyncConnection<Backend = Sqlite>, conn: &mut impl AsyncConnection<Backend = Sqlite>,
keyholder: &ActorRef<KeyHolder>, keyholder: &ActorRef<KeyHolder>,
entity: &E, entity: &E,
entity_id: impl IntoId, entity_id: impl Into<EntityId>,
) -> Result<AttestationStatus, Error> { ) -> Result<AttestationStatus, Error> {
let entity_id = entity_id.into_id(); let entity_id = entity_id.into();
let envelope: IntegrityEnvelope = integrity_envelope::table let envelope: IntegrityEnvelopeRow = integrity_envelope::table
.filter(integrity_envelope::entity_kind.eq(E::KIND)) .filter(integrity_envelope::entity_kind.eq(E::KIND))
.filter(integrity_envelope::entity_id.eq(&entity_id)) .filter(integrity_envelope::entity_id.eq(&*entity_id))
.first(conn) .first(conn)
.await .await
.map_err(|err| match err { .map_err(|err| match err {
diesel::result::Error::NotFound => Error::MissingEnvelope { entity_kind: E::KIND }, diesel::result::Error::NotFound => Error::MissingEnvelope {
entity_kind: E::KIND,
},
other => Error::Database(db::DatabaseError::from(other)), other => Error::Database(db::DatabaseError::from(other)),
})?; })?;
@@ -174,14 +204,8 @@ pub async fn verify_entity<E: Integrable>(
}); });
} }
let payload = postcard::to_stdvec(entity)?; let payload_hash = payload_hash(entity);
let payload_hash = payload_hash(&payload); let mac_input = build_mac_input(E::KIND, &entity_id, envelope.payload_version, &payload_hash);
let mac_input = build_mac_input(
E::KIND,
&entity_id,
envelope.payload_version,
&payload_hash,
);
let result = keyholder let result = keyholder
.ask(VerifyIntegrity { .ask(VerifyIntegrity {
@@ -189,131 +213,107 @@ pub async fn verify_entity<E: Integrable>(
expected_mac: envelope.mac, expected_mac: envelope.mac,
key_version: envelope.key_version, key_version: envelope.key_version,
}) })
.await .await;
;
match result { match result {
Ok(true) => Ok(AttestationStatus::Attested), Ok(true) => Ok(AttestationStatus::Attested),
Ok(false) => Err(Error::MacMismatch { entity_kind: E::KIND }), Ok(false) => Err(Error::MacMismatch {
Err(SendError::HandlerError(keyholder::Error::NotBootstrapped)) => Ok(AttestationStatus::Unavailable), entity_kind: E::KIND,
}),
Err(SendError::HandlerError(keyholder::Error::NotBootstrapped)) => {
Ok(AttestationStatus::Unavailable)
}
Err(_) => Err(Error::KeyholderSend), Err(_) => Err(Error::KeyholderSend),
} }
} }
#[cfg(test)] #[derive(Debug, Clone, crate::VerifiedFields!)]
mod tests { #[repr(C)]
use diesel::{ExpressionMethods as _, QueryDsl}; pub struct Entity<E, Id> {
use diesel_async::RunQueryDsl; pub entity: E,
use kameo::{actor::ActorRef, prelude::Spawn}; pub entity_id: Id,
}
use crate::{ impl<E, Id> Deref for Entity<E, Id> {
actors::keyholder::{Bootstrap, KeyHolder}, type Target = E;
db::{self, schema},
safe_cell::{SafeCell, SafeCellHandle as _},
};
use super::{Error, Integrable, sign_entity, verify_entity}; fn deref(&self) -> &Self::Target {
&self.entity
#[derive(Clone, serde::Serialize)]
struct DummyEntity {
payload_version: i32,
payload: Vec<u8>,
}
impl Integrable for DummyEntity {
const KIND: &'static str = "dummy_entity";
}
async fn bootstrapped_keyholder(db: &db::DatabasePool) -> ActorRef<KeyHolder> {
let actor = KeyHolder::spawn(KeyHolder::new(db.clone()).await.unwrap());
actor
.ask(Bootstrap {
seal_key_raw: SafeCell::new(b"integrity-test-seal-key".to_vec()),
})
.await
.unwrap();
actor
}
#[tokio::test]
async fn sign_writes_envelope_and_verify_passes() {
let db = db::create_test_pool().await;
let keyholder = bootstrapped_keyholder(&db).await;
let mut conn = db.get().await.unwrap();
const ENTITY_ID: &[u8] = b"entity-id-7";
let entity = DummyEntity {
payload_version: 1,
payload: b"payload-v1".to_vec(),
};
sign_entity(&mut conn, &keyholder, &entity, ENTITY_ID).await.unwrap();
let count: i64 = schema::integrity_envelope::table
.filter(schema::integrity_envelope::entity_kind.eq("dummy_entity"))
.filter(schema::integrity_envelope::entity_id.eq(ENTITY_ID))
.count()
.get_result(&mut conn)
.await
.unwrap();
assert_eq!(count, 1, "envelope row must be created exactly once");
verify_entity(&mut conn, &keyholder, &entity, ENTITY_ID).await.unwrap();
}
#[tokio::test]
async fn tampered_mac_fails_verification() {
let db = db::create_test_pool().await;
let keyholder = bootstrapped_keyholder(&db).await;
let mut conn = db.get().await.unwrap();
const ENTITY_ID: &[u8] = b"entity-id-11";
let entity = DummyEntity {
payload_version: 1,
payload: b"payload-v1".to_vec(),
};
sign_entity(&mut conn, &keyholder, &entity, ENTITY_ID).await.unwrap();
diesel::update(schema::integrity_envelope::table)
.filter(schema::integrity_envelope::entity_kind.eq("dummy_entity"))
.filter(schema::integrity_envelope::entity_id.eq(ENTITY_ID))
.set(schema::integrity_envelope::mac.eq(vec![0u8; 32]))
.execute(&mut conn)
.await
.unwrap();
let err = verify_entity(&mut conn, &keyholder, &entity, ENTITY_ID)
.await
.unwrap_err();
assert!(matches!(err, Error::MacMismatch { .. }));
}
#[tokio::test]
async fn changed_payload_fails_verification() {
let db = db::create_test_pool().await;
let keyholder = bootstrapped_keyholder(&db).await;
let mut conn = db.get().await.unwrap();
const ENTITY_ID: &[u8] = b"entity-id-21";
let entity = DummyEntity {
payload_version: 1,
payload: b"payload-v1".to_vec(),
};
sign_entity(&mut conn, &keyholder, &entity, ENTITY_ID).await.unwrap();
let tampered = DummyEntity {
payload: b"payload-v1-but-tampered".to_vec(),
..entity
};
let err = verify_entity(&mut conn, &keyholder, &tampered, ENTITY_ID)
.await
.unwrap_err();
assert!(matches!(err, Error::MacMismatch { .. }));
} }
} }
pub async fn verify_entity<E: Integrable, Id: Into<EntityId> + Clone>(
conn: &mut impl AsyncConnection<Backend = Sqlite>,
keyholder: &ActorRef<KeyHolder>,
entity: E,
entity_id: Id,
) -> Result<Verified<Entity<E, Id>, Nested<E>>, Error> {
match check_entity_attestation(conn, keyholder, &entity, entity_id.clone()).await? {
AttestationStatus::Attested => Ok(Verified::<Entity<E, Id>, Nested<E>>::new(Entity {
entity,
entity_id,
})),
AttestationStatus::Unavailable => Err(Error::Keyholder(keyholder::Error::NotBootstrapped)),
}
}
pub async fn verify_entity_ref<'e, E: Integrable, Id: Into<EntityId> + Clone>(
conn: &mut impl AsyncConnection<Backend = Sqlite>,
keyholder: &ActorRef<KeyHolder>,
entity: &'e E,
entity_id: Id,
) -> Result<Verified<Entity<&'e E, Id>, Nested<E>>, Error> {
match check_entity_attestation(conn, keyholder, entity, entity_id.clone()).await? {
AttestationStatus::Attested => Ok(Verified::<Entity<&'e E, Id>, Nested<E>>::new(Entity {
entity,
entity_id,
})),
AttestationStatus::Unavailable => Err(Error::Keyholder(keyholder::Error::NotBootstrapped)),
}
}
pub async fn delete_envelope<E: Integrable>(
conn: &mut impl AsyncConnection<Backend = Sqlite>,
entity_id: impl Into<EntityId>,
) -> Result<usize, Error> {
let entity_id = entity_id.into();
let affected = diesel::delete(
integrity_envelope::table
.filter(integrity_envelope::entity_kind.eq(E::KIND))
.filter(integrity_envelope::entity_id.eq(&*entity_id)),
)
.execute(conn)
.await
.map_err(db::DatabaseError::from)?;
Ok(affected)
}
fn payload_hash(payload: &impl Hashable) -> [u8; 32] {
let mut hasher = Sha256::new();
payload.hash(&mut hasher);
hasher.finalize().into()
}
fn build_mac_input(
entity_kind: &str,
entity_id: &[u8],
payload_version: i32,
payload_hash: &[u8; 32],
) -> Vec<u8> {
let mut out = Vec::with_capacity(8 + entity_kind.len() + entity_id.len() + 32);
push_len_prefixed(&mut out, entity_kind.as_bytes());
push_len_prefixed(&mut out, entity_id);
out.extend_from_slice(&payload_version.to_be_bytes());
out.extend_from_slice(payload_hash);
out
}
fn push_len_prefixed(out: &mut Vec<u8>, bytes: &[u8]) {
out.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
out.extend_from_slice(bytes);
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,107 @@
use hmac::digest::Digest;
use std::collections::HashSet;
/// Deterministically hash a value by feeding its fields into the hasher in a consistent order.
pub trait Hashable {
fn hash<H: Digest>(&self, hasher: &mut H);
}
macro_rules! impl_numeric {
($($t:ty),*) => {
$(
impl Hashable for $t {
fn hash<H: Digest>(&self, hasher: &mut H) {
hasher.update(&self.to_be_bytes());
}
}
)*
};
}
impl_numeric!(u8, u16, u32, u64, i8, i16, i32, i64);
impl Hashable for &[u8] {
fn hash<H: Digest>(&self, hasher: &mut H) {
hasher.update(self);
}
}
impl Hashable for String {
fn hash<H: Digest>(&self, hasher: &mut H) {
hasher.update(self.as_bytes());
}
}
impl<T: Hashable + PartialOrd> Hashable for Vec<T> {
fn hash<H: Digest>(&self, hasher: &mut H) {
let ref_sorted = {
let mut sorted = self.iter().collect::<Vec<_>>();
sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
sorted
};
for item in ref_sorted {
item.hash(hasher);
}
}
}
impl<T: Hashable + PartialOrd> Hashable for HashSet<T> {
fn hash<H: Digest>(&self, hasher: &mut H) {
let ref_sorted = {
let mut sorted = self.iter().collect::<Vec<_>>();
sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
sorted
};
for item in ref_sorted {
item.hash(hasher);
}
}
}
impl<T: Hashable> Hashable for Option<T> {
fn hash<H: Digest>(&self, hasher: &mut H) {
match self {
Some(value) => {
hasher.update([1]);
value.hash(hasher);
}
None => hasher.update([0]),
}
}
}
impl<T: Hashable> Hashable for Box<T> {
fn hash<H: Digest>(&self, hasher: &mut H) {
self.as_ref().hash(hasher);
}
}
impl<T: Hashable> Hashable for &T {
fn hash<H: Digest>(&self, hasher: &mut H) {
(*self).hash(hasher);
}
}
impl Hashable for alloy::primitives::Address {
fn hash<H: Digest>(&self, hasher: &mut H) {
hasher.update(self.as_slice());
}
}
impl Hashable for alloy::primitives::U256 {
fn hash<H: Digest>(&self, hasher: &mut H) {
hasher.update(self.to_be_bytes::<32>());
}
}
impl Hashable for chrono::Duration {
fn hash<H: Digest>(&self, hasher: &mut H) {
hasher.update(self.num_seconds().to_be_bytes());
}
}
impl Hashable for chrono::DateTime<chrono::Utc> {
fn hash<H: Digest>(&self, hasher: &mut H) {
hasher.update(self.timestamp_millis().to_be_bytes());
}
}

View File

@@ -0,0 +1,298 @@
use diesel::{ExpressionMethods as _, QueryDsl};
use diesel_async::RunQueryDsl;
use kameo::{actor::ActorRef, prelude::Spawn};
use sha2::Digest;
use crate::{
actors::keyholder::{Bootstrap, KeyHolder},
db::{self, schema},
safe_cell::{SafeCell, SafeCellHandle as _},
};
use super::hashing::Hashable;
use super::{
Error, Integrable, check_entity_attestation, lookup_verified, lookup_verified_from_query,
sign_entity, verify_entity,
};
#[derive(Clone, Debug)]
struct DummyEntity {
payload_version: i32,
payload: Vec<u8>,
}
impl Hashable for DummyEntity {
fn hash<H: Digest>(&self, hasher: &mut H) {
self.payload_version.hash(hasher);
self.payload.hash(hasher);
}
}
impl Integrable for DummyEntity {
const KIND: &'static str = "dummy_entity";
}
async fn bootstrapped_keyholder(db: &db::DatabasePool) -> ActorRef<KeyHolder> {
let actor = KeyHolder::spawn(KeyHolder::new(db.clone()).await.unwrap());
actor
.ask(Bootstrap {
seal_key_raw: SafeCell::new(b"integrity-test-seal-key".to_vec()),
})
.await
.unwrap();
actor
}
#[tokio::test]
async fn sign_writes_envelope_and_verify_passes() {
let db = db::create_test_pool().await;
let keyholder = bootstrapped_keyholder(&db).await;
let mut conn = db.get().await.unwrap();
const ENTITY_ID: &[u8] = b"entity-id-7";
let entity = DummyEntity {
payload_version: 1,
payload: b"payload-v1".to_vec(),
};
sign_entity(&mut conn, &keyholder, &entity, ENTITY_ID)
.await
.unwrap()
.drop_verification_provenance();
let count: i64 = schema::integrity_envelope::table
.filter(schema::integrity_envelope::entity_kind.eq("dummy_entity"))
.filter(schema::integrity_envelope::entity_id.eq(ENTITY_ID))
.count()
.get_result(&mut conn)
.await
.unwrap();
assert_eq!(count, 1, "envelope row must be created exactly once");
let _ = check_entity_attestation(&mut conn, &keyholder, &entity, ENTITY_ID)
.await
.unwrap();
}
#[tokio::test]
async fn tampered_mac_fails_verification() {
let db = db::create_test_pool().await;
let keyholder = bootstrapped_keyholder(&db).await;
let mut conn = db.get().await.unwrap();
const ENTITY_ID: &[u8] = b"entity-id-11";
let entity = DummyEntity {
payload_version: 1,
payload: b"payload-v1".to_vec(),
};
sign_entity(&mut conn, &keyholder, &entity, ENTITY_ID)
.await
.unwrap()
.drop_verification_provenance();
diesel::update(schema::integrity_envelope::table)
.filter(schema::integrity_envelope::entity_kind.eq("dummy_entity"))
.filter(schema::integrity_envelope::entity_id.eq(ENTITY_ID))
.set(schema::integrity_envelope::mac.eq(vec![0u8; 32]))
.execute(&mut conn)
.await
.unwrap();
let err = check_entity_attestation(&mut conn, &keyholder, &entity, ENTITY_ID)
.await
.unwrap_err();
assert!(matches!(err, Error::MacMismatch { .. }));
}
#[tokio::test]
async fn changed_payload_fails_verification() {
let db = db::create_test_pool().await;
let keyholder = bootstrapped_keyholder(&db).await;
let mut conn = db.get().await.unwrap();
const ENTITY_ID: &[u8] = b"entity-id-21";
let entity = DummyEntity {
payload_version: 1,
payload: b"payload-v1".to_vec(),
};
sign_entity(&mut conn, &keyholder, &entity, ENTITY_ID)
.await
.unwrap()
.drop_verification_provenance();
let tampered = DummyEntity {
payload: b"payload-v1-but-tampered".to_vec(),
..entity
};
let err = check_entity_attestation(&mut conn, &keyholder, &tampered, ENTITY_ID)
.await
.unwrap_err();
assert!(matches!(err, Error::MacMismatch { .. }));
}
#[tokio::test]
async fn strict_verify_fails_closed_while_sealed() {
let db = db::create_test_pool().await;
let keyholder = bootstrapped_keyholder(&db).await;
let mut conn = db.get().await.unwrap();
const ENTITY_ID: &[u8] = b"entity-id-41";
let entity = DummyEntity {
payload_version: 1,
payload: b"payload-v1".to_vec(),
};
sign_entity(&mut conn, &keyholder, &entity, ENTITY_ID)
.await
.unwrap()
.drop_verification_provenance();
drop(keyholder);
let sealed_keyholder = KeyHolder::spawn(KeyHolder::new(db.clone()).await.unwrap());
let err = verify_entity(&mut conn, &sealed_keyholder, &entity, ENTITY_ID)
.await
.unwrap_err();
assert!(matches!(
err,
Error::Keyholder(crate::actors::keyholder::Error::NotBootstrapped)
));
let err = lookup_verified(&mut conn, &sealed_keyholder, ENTITY_ID, |_| async {
Ok::<_, db::DatabaseError>(DummyEntity {
payload_version: 1,
payload: b"payload-v1".to_vec(),
})
})
.await
.unwrap_err();
assert!(matches!(
err,
Error::Keyholder(crate::actors::keyholder::Error::NotBootstrapped)
));
}
#[tokio::test]
async fn lookup_verified_supports_loaded_aggregate() {
let db = db::create_test_pool().await;
let keyholder = bootstrapped_keyholder(&db).await;
let mut conn = db.get().await.unwrap();
const ENTITY_ID: i32 = 77;
let entity = DummyEntity {
payload_version: 1,
payload: b"payload-v1".to_vec(),
};
sign_entity(&mut conn, &keyholder, &entity, ENTITY_ID)
.await
.unwrap()
.drop_verification_provenance();
let verified = lookup_verified(&mut conn, &keyholder, ENTITY_ID, |_| async {
Ok::<_, db::DatabaseError>(DummyEntity {
payload_version: 1,
payload: b"payload-v1".to_vec(),
})
})
.await
.unwrap();
assert_eq!(verified.entity.payload, b"payload-v1".to_vec());
}
#[tokio::test]
async fn extension_trait_lookup_verified_required_works() {
let db = db::create_test_pool().await;
let keyholder = bootstrapped_keyholder(&db).await;
let mut conn = db.get().await.unwrap();
const ENTITY_ID: i32 = 79;
let entity = DummyEntity {
payload_version: 1,
payload: b"payload-v1".to_vec(),
};
sign_entity(&mut conn, &keyholder, &entity, ENTITY_ID)
.await
.unwrap()
.drop_verification_provenance();
let verified = lookup_verified(&mut conn, &keyholder, ENTITY_ID, |_| {
Box::pin(async {
Ok::<_, db::DatabaseError>(DummyEntity {
payload_version: 1,
payload: b"payload-v1".to_vec(),
})
})
})
.await
.unwrap();
assert_eq!(verified.entity.payload, b"payload-v1".to_vec());
}
#[tokio::test]
async fn lookup_verified_from_query_helpers_work() {
let db = db::create_test_pool().await;
let keyholder = bootstrapped_keyholder(&db).await;
let mut conn = db.get().await.unwrap();
const ENTITY_ID: i32 = 80;
let entity = DummyEntity {
payload_version: 1,
payload: b"payload-v1".to_vec(),
};
sign_entity(&mut conn, &keyholder, &entity, ENTITY_ID)
.await
.unwrap()
.drop_verification_provenance();
let verified = lookup_verified_from_query(&mut conn, &keyholder, |_| {
Box::pin(async {
Ok::<_, db::DatabaseError>((
ENTITY_ID,
DummyEntity {
payload_version: 1,
payload: b"payload-v1".to_vec(),
},
))
})
})
.await
.unwrap();
assert_eq!(verified.entity.payload, b"payload-v1".to_vec());
drop(keyholder);
let sealed_keyholder = KeyHolder::spawn(KeyHolder::new(db.clone()).await.unwrap());
let err = lookup_verified_from_query(&mut conn, &sealed_keyholder, |_| {
Box::pin(async {
Ok::<_, db::DatabaseError>((
ENTITY_ID,
DummyEntity {
payload_version: 1,
payload: b"payload-v1".to_vec(),
},
))
})
})
.await
.unwrap_err();
assert!(matches!(
err,
Error::Keyholder(crate::actors::keyholder::Error::NotBootstrapped)
));
}

View File

@@ -0,0 +1,593 @@
use std::ops::Deref;
use super::Integrable;
mod private {
pub trait Sealed {}
}
/// Marker trait for type-level verification provenance.
///
/// This trait is intentionally sealed so external code cannot invent arbitrary
/// provenance tags and bypass the intended type-level guarantees.
pub trait VerificationOrigin: private::Sealed {
type Origin: VerificationOrigin;
}
/// Root provenance marker for values directly produced by integrity APIs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Root;
/// Nested provenance marker carrying the source integrable type and previous
/// provenance marker in the chain.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Nested<From, P: VerificationOrigin = Root>(core::marker::PhantomData<(From, P)>);
impl private::Sealed for Root {}
impl VerificationOrigin for Root {
type Origin = Self;
}
impl<T, P: VerificationOrigin> private::Sealed for Nested<T, P> {}
impl<T, P: VerificationOrigin> VerificationOrigin for Nested<T, P> {
type Origin = P;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(transparent)]
#[must_use = "Verified<T> is a proof-bearing wrapper; use self.drop_verification_provenance() to explicitly discard integrity provenance when needed"]
pub struct Verified<T, O: VerificationOrigin = Root> {
inner: T,
origin: core::marker::PhantomData<O>,
}
impl<T, O: VerificationOrigin> AsRef<Verified<T, O>> for Verified<&T, O> {
fn as_ref(&self) -> &Verified<T, O> {
// SAFETY: `Verified<T>` is `#[repr(transparent)]` over `T`, so `&T`
// and `&Verified<T>` have identical layout.
unsafe { reinterpret_layout_ref::<T, Verified<T, O>>(self.inner) }
}
}
impl<T, U: Integrable, O: VerificationOrigin> Deref for Verified<T, Nested<U, O>> {
type Target = Verified<T, O::Origin>;
fn deref(&self) -> &Self::Target {
// SAFETY: `Verified<T, Nested<U, O>>` is `#[repr(transparent)]` over `T`, so `&Verified<T, Nested<U, O>>`
// and `&Nested<U, O>` have identical layout.
unsafe { reinterpret_layout_ref::<Self, Verified<T, O::Origin>>(self) }
}
}
impl<T> Deref for Verified<T, Root> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T, O: VerificationOrigin> Verified<T, O> {
/// Unwraps the verified value, discarding the integrity provenance.
///
/// The name is intentionally verbose — call sites where provenance is
/// dropped should be easy to find and audit.
pub fn drop_verification_provenance(self) -> T {
self.inner
}
/// Downgrades the origin provenance to any lower nestedness level,
/// e.g. `Verified<T, Nested<Other>>` to `Verified<T, Root>`.
pub fn unqualify_origin<Target: VerificationOrigin>(self) -> Verified<T, Target>
where
O: VerificationOrigin<Origin = Target>,
{
Verified {
inner: self.inner,
origin: core::marker::PhantomData,
}
}
/// Constructs a `Verified<T>` by wrapping a `T`.
pub(super) fn new(value: T) -> Self {
Self {
inner: value,
origin: core::marker::PhantomData,
}
}
/// Constructs a `Verified<T>` from a raw value without performing any
/// integrity check. Only available in test builds; use the integrity
/// module's functions to obtain a `Verified<T>` in production code.
#[cfg(test)]
pub(crate) fn new_unchecked(value: T) -> Self {
Self {
inner: value,
origin: core::marker::PhantomData,
}
}
/// Reinterprets `&T` as `&Verified<T>`.
#[allow(dead_code)]
pub(super) fn from_ref(from: &T) -> &Self {
// SAFETY: `Self` is `#[repr(transparent)]` over `T`.
unsafe { reinterpret_layout_ref::<T, Self>(from) }
}
}
/// Bit-copies `value: From` into a `To`, suppressing the source destructor so
/// the destination owns the bytes.
///
/// # Safety
///
/// The caller must guarantee that `From` and `To` have identical in-memory
/// layout — the raw bytes that encode a valid `From` must also encode a valid
/// `To`.
///
/// A `union` is used instead of [`std::mem::transmute`] because `transmute`
/// rejects generic source/destination types at the call site even when their
/// sizes are provably equal at monomorphization time.
#[allow(dead_code)]
#[inline]
pub const unsafe fn reinterpret_layout<From, To>(value: From) -> To {
const {
assert!(
::std::mem::size_of::<From>() == ::std::mem::size_of::<To>(),
"reinterpret_layout: source and destination must have identical size"
);
assert!(
::std::mem::align_of::<From>() == ::std::mem::align_of::<To>(),
"reinterpret_layout: source and destination must have identical alignment"
);
}
union Reinterpret<A, B> {
from: ::std::mem::ManuallyDrop<A>,
to: ::std::mem::ManuallyDrop<B>,
}
// SAFETY: caller guarantees layout equivalence (see fn docs). The union
// write-read copies the raw bytes of `value` into a `To` slot, and
// `ManuallyDrop` on the source side suppresses its destructor so the
// destination owns the bytes unambiguously — no double-drop is possible.
unsafe {
::std::mem::ManuallyDrop::into_inner(
Reinterpret {
from: ::std::mem::ManuallyDrop::new(value),
}
.to,
)
}
}
/// Reinterprets `&From` as `&To` via a layout-preserving pointer cast.
///
/// # Safety
///
/// Same invariants as [`reinterpret_layout`].
#[inline]
pub const unsafe fn reinterpret_layout_ref<From, To>(value: &From) -> &To {
const {
assert!(
::std::mem::size_of::<From>() == ::std::mem::size_of::<To>(),
"reinterpret_layout_ref: source and destination must have identical size"
);
assert!(
::std::mem::align_of::<From>() == ::std::mem::align_of::<To>(),
"reinterpret_layout_ref: source and destination must have identical alignment"
);
}
// SAFETY: caller guarantees layout equivalence (see fn docs). A reference
// cast between identically-laid-out types produces a reference with the
// same address and lifetime, which is sound.
unsafe { &*(value as *const From as *const To) }
}
/// Implemented on `Verified<T>` by [`VerifiedFields!`], exposing the field-wise counterpart.
///
/// ## Disclaimer
/// Do not implement this trait manually. It is intended to be implemented only
/// by the `VerifiedFields!` macro, which generates the necessary layout
/// guarantees for sound pointer casts.
///
/// ## Soundness
/// When [`verify_entity`][crate::crypto::integrity::verify_entity] attests an
/// entity, it returns `Verified<T>` — an aggregate proof over the whole value.
/// This trait converts that wrapper into `Counterpart` (e.g.
/// `VerifiedMyStruct`), where every field is individually wrapped in
/// [`Verified`], allowing verified data to flow into functions that require
/// `Verified<FieldType>` without re-verifying.
///
/// ## Safety
/// The conversion is a zero-cost reinterpretation — no copying (beyond a
/// bitwise move in the owned variant) or HMAC work occurs. Soundness rests on
/// identical memory layout between `Verified<T>` and `Counterpart`:
///
/// - `T` carries `#[repr(C)]` (enforced by `@require_repr` in the macro).
/// - `T` does **not** carry `packed` (enforced by `@reject_packed`).
/// - `Counterpart` also carries `#[repr(C)]`, with the same fields in the same
/// order.
/// - Each `Verified<F>` field is `#[repr(transparent)]` over `F`, so its size
/// and alignment match `F` exactly.
/// - `Verified<T>` itself is `#[repr(transparent)]` over `T`.
///
/// As an additional machine-checked guard, [`reinterpret_layout`] and
/// [`reinterpret_layout_ref`] assert size/align equality of the two types at
/// monomorphization time.
///
/// The trait is implemented directly on `Verified<T>` (not on `T`), so no
/// `Deref`-coercion or auto-ref stripping is needed at call sites — the impl
/// is unambiguous.
pub trait VerifiedFieldsAccessor {
/// The field-wise verified counterpart, e.g. `VerifiedMyStruct`.
type Counterpart;
/// Reinterprets `&self` as `&Counterpart` via a layout-preserving pointer cast.
///
/// No data is copied and no re-verification occurs. The returned reference
/// borrows from `self` and has the same lifetime.
fn inherit_ref(&self) -> &Self::Counterpart;
/// Consumes `self` and returns `Counterpart` via a layout-preserving
/// bitwise move.
///
/// The original `Verified<T>` is moved without running its destructor
/// (there is none — `Verified` is a transparent wrapper with no heap
/// allocation), and the returned counterpart owns the original bytes. No
/// re-verification occurs.
fn inherit(self) -> Self::Counterpart;
}
// todo! rewrite macro_rules to derive crate
#[macro_export]
macro_rules! VerifiedFields {
// --- Entry point (no source generics) ---
(
$(#$attr:tt)*
$vis:vis struct $name:ident
{
$(
$field_vis:vis $field_name:ident : $field_ty:ty
),* $(,)?
}
) => {
// Attribute-list checks run in isolation — they only receive the attrs,
// not the struct body.
$crate::VerifiedFields!(@require_repr [$(#$attr)*]);
$crate::VerifiedFields!(@reject_packed [$(#$attr)*]);
paste::paste! {
#[doc = concat!(
"Field-wise verified counterpart of [`", stringify!($name), "`]."
)]
//
// `#[repr(C)]` is required for the pointer casts in `inherit_ref`
// and `inherit` to be sound. Both the source struct (enforced by
// `@require_repr`) and this counterpart carry `#[repr(C)]`, which
// guarantees matching field offsets. Combined with each
// `Verified<F>` being `#[repr(transparent)]` over `F`, the two
// structs have identical memory layout.
//
// `#[repr(transparent)]` is not usable here because it only permits
// a single non-ZST field; multi-field structs would fail to compile.
#[repr(C)]
$vis struct [<Verified $name>]<P: $crate::crypto::integrity::v1::verified::VerificationOrigin>
{
$(
$field_vis $field_name : $crate::crypto::integrity::Verified<$field_ty, P>
),*
}
impl<P: $crate::crypto::integrity::v1::verified::VerificationOrigin>
$crate::crypto::integrity::v1::verified::VerifiedFieldsAccessor
for $crate::crypto::integrity::Verified<$name, P>
{
type Counterpart = [<Verified $name>]<P>;
fn inherit_ref(&self) -> &Self::Counterpart {
// SAFETY: `Self` is `Verified<T>` (transparent over
// `T #[repr(C)]`) and `Self::Counterpart` is `#[repr(C)]`
// with the same fields in the same order, each wrapped in
// a `#[repr(transparent)]` `Verified<F>`. The two types
// therefore have identical memory layout, which
// `reinterpret_layout_ref` re-checks as size/align
// equality at monomorphization.
unsafe {
$crate::crypto::integrity::v1::verified::reinterpret_layout_ref::<
Self,
Self::Counterpart,
>(self)
}
}
fn inherit(self) -> Self::Counterpart {
// SAFETY: identical layout — see `inherit_ref`. The owned
// helper additionally suppresses the source destructor so
// the returned counterpart owns the original bytes (no
// double-drop is possible).
unsafe {
$crate::crypto::integrity::v1::verified::reinterpret_layout::<
Self,
Self::Counterpart,
>(self)
}
}
}
}
};
// --- Entry point (source has generics) ---
(
$(#$attr:tt)*
$vis:vis struct $name:ident <$($gen:tt),*>
{
$(
$field_vis:vis $field_name:ident : $field_ty:ty
),* $(,)?
}
) => {
// Attribute-list checks run in isolation — they only receive the attrs,
// not the struct body.
$crate::VerifiedFields!(@require_repr [$(#$attr)*]);
$crate::VerifiedFields!(@reject_packed [$(#$attr)*]);
paste::paste! {
#[doc = concat!(
"Field-wise verified counterpart of [`", stringify!($name), "`]."
)]
//
// `#[repr(C)]` is required for the pointer casts in `inherit_ref`
// and `inherit` to be sound. Both the source struct (enforced by
// `@require_repr`) and this counterpart carry `#[repr(C)]`, which
// guarantees matching field offsets. Combined with each
// `Verified<F>` being `#[repr(transparent)]` over `F`, the two
// structs have identical memory layout.
//
// `#[repr(transparent)]` is not usable here because it only permits
// a single non-ZST field; multi-field structs would fail to compile.
#[repr(C)]
$vis struct [<Verified $name>]<$($gen),*, P: $crate::crypto::integrity::v1::verified::VerificationOrigin>
{
$(
$field_vis $field_name : $crate::crypto::integrity::Verified<$field_ty, P>
),*
}
impl<$($gen),*, P: $crate::crypto::integrity::v1::verified::VerificationOrigin>
$crate::crypto::integrity::v1::verified::VerifiedFieldsAccessor
for $crate::crypto::integrity::Verified<$name<$($gen),*>, P>
{
type Counterpart = [<Verified $name>]<$($gen),*, P>;
fn inherit_ref(&self) -> &Self::Counterpart {
// SAFETY: `Self` is `Verified<T>` (transparent over
// `T #[repr(C)]`) and `Self::Counterpart` is `#[repr(C)]`
// with the same fields in the same order, each wrapped in
// a `#[repr(transparent)]` `Verified<F>`. The two types
// therefore have identical memory layout, which
// `reinterpret_layout_ref` re-checks as size/align
// equality at monomorphization.
unsafe {
$crate::crypto::integrity::v1::verified::reinterpret_layout_ref::<
Self,
Self::Counterpart,
>(self)
}
}
fn inherit(self) -> Self::Counterpart {
// SAFETY: identical layout — see `inherit_ref`. The owned
// helper additionally suppresses the source destructor so
// the returned counterpart owns the original bytes (no
// double-drop is possible).
unsafe {
$crate::crypto::integrity::v1::verified::reinterpret_layout::<
Self,
Self::Counterpart,
>(self)
}
}
}
}
};
// --- @require_repr: ensure `#[repr(C)]` appears in the attribute list ---
(@require_repr [#[repr(C)] $($rest:tt)*]) => {};
(@require_repr [#$other:tt $($rest:tt)*]) => {
$crate::VerifiedFields!(@require_repr [$($rest)*]);
};
(@require_repr []) => {
::std::compile_error!(
"VerifiedFields requires `#[repr(C)]` on the struct to guarantee field layout"
);
};
// --- @reject_packed: walk attrs and reject any `#[repr(..., packed, ...)]`.
//
// Without this, a packed struct would still fail at monomorphization via
// the const assertions inside the `reinterpret_layout*` helpers, but the
// diagnostic would be much harder to read. `align(N)` is *not* rejected
// here because const assertions catch alignment mismatches cleanly, and
// forbidding it would be unnecessarily restrictive.
(@reject_packed [#[repr($($inner:tt)*)] $($rest:tt)*]) => {
$crate::VerifiedFields!(@reject_packed_inner [$($inner)*]);
$crate::VerifiedFields!(@reject_packed [$($rest)*]);
};
(@reject_packed [#$other:tt $($rest:tt)*]) => {
$crate::VerifiedFields!(@reject_packed [$($rest)*]);
};
(@reject_packed []) => {};
(@reject_packed_inner [packed $($rest:tt)*]) => {
::std::compile_error!(
"VerifiedFields does not support packed layouts; the generated \
counterpart would not share layout with the source struct"
);
};
(@reject_packed_inner [$first:tt $($rest:tt)*]) => {
$crate::VerifiedFields!(@reject_packed_inner [$($rest)*]);
};
(@reject_packed_inner []) => {};
}
#[cfg(test)]
mod tests {
use super::*;
#[derive(VerifiedFields!)]
#[repr(C)]
#[derive(Default, Clone)]
pub struct MyStruct<T> {
pub field1: String,
pub field2: T,
}
fn verify<T>(t: T) -> Verified<T> {
Verified {
inner: t,
origin: core::marker::PhantomData,
}
}
// --- inherit_ref ---
// Verifies that `inherit_ref` returns a reference to the same memory
// address, confirming that no copy is made and the cast is purely a
// reinterpretation.
#[test]
fn inherit_ref_is_same_address() {
let v = verify(MyStruct {
field1: "hello".into(),
field2: 42u32,
});
let fields = v.inherit_ref();
assert_eq!(
&v as *const _ as *const u8, fields as *const _ as *const u8,
"inherit_ref must return a pointer to the same memory, not a copy"
);
}
// Verifies that field values are correctly accessible after `inherit_ref`.
#[test]
fn inherit_ref_field_values() {
let v = verify(MyStruct {
field1: "hello".into(),
field2: 99u32,
});
let fields = v.inherit_ref();
assert_eq!(*fields.field1, "hello");
assert_eq!(*fields.field2, 99u32);
}
// Verifies that casting the counterpart back to `Verified<T>` via a raw
// pointer lands on the original address — confirms the round-trip is a
// pure reinterpretation.
#[test]
fn inherit_ref_cast_roundtrip() {
let v = verify(MyStruct {
field1: "x".into(),
field2: 7u32,
});
let fields: &VerifiedMyStruct<u32, Root> = v.inherit_ref();
let back_ptr =
fields as *const VerifiedMyStruct<u32, Root> as *const Verified<MyStruct<u32>>;
assert_eq!(
back_ptr as *const u8, &v as *const _ as *const u8,
"cast of counterpart must point back to the same Verified<T>"
);
}
// ZST fields must still produce a counterpart with identical layout — the
// const asserts in `reinterpret_layout_ref` guard this at monomorphization.
#[test]
fn inherit_ref_with_zst_field() {
#[derive(VerifiedFields!)]
#[repr(C)]
struct WithZst {
pub unit: (),
pub val: u64,
}
let v = Verified::<WithZst>::new_unchecked(WithZst { unit: (), val: 777 });
let fields = v.inherit_ref();
assert_eq!(*fields.val, 777);
assert_eq!(*fields.unit, ());
}
// --- inherit ---
// Verifies that `inherit` preserves field values in the owned counterpart.
#[test]
fn inherit_field_values() {
let v = verify(MyStruct {
field1: "world".into(),
field2: 1234u64,
});
let VerifiedMyStruct { field1, field2 } = v.inherit();
assert_eq!(*field1, "world");
assert_eq!(*field2, 1234u64);
}
// Verifies that `inherit` does not double-drop the inner value.
// If `ManuallyDrop` handling is wrong, running under Miri or with a drop
// counter catches a double-free.
#[test]
fn inherit_no_double_drop() {
use std::sync::atomic::{AtomicUsize, Ordering};
static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);
struct DropCounter;
impl Drop for DropCounter {
fn drop(&mut self) {
DROP_COUNT.fetch_add(1, Ordering::Relaxed);
}
}
#[derive(VerifiedFields!)]
#[repr(C)]
struct WithDrop {
pub val: DropCounter,
}
DROP_COUNT.store(0, Ordering::Relaxed);
{
let v = Verified::<WithDrop>::new_unchecked(WithDrop { val: DropCounter });
let _ = v.inherit();
}
assert_eq!(
DROP_COUNT.load(Ordering::Relaxed),
1,
"DropCounter must be dropped exactly once"
);
}
// --- Verified::from_ref ---
#[test]
fn from_ref_is_same_address() {
let val = 42u32;
let verified: &Verified<u32> = Verified::from_ref(&val);
assert_eq!(
&val as *const u32 as *const u8, verified as *const _ as *const u8,
"from_ref must alias the original reference, not copy the value"
);
}
#[test]
fn from_ref_value_preserved() {
let val = String::from("test");
let verified: &Verified<String> = Verified::from_ref(&val);
assert_eq!(**verified, "test");
}
// --- AsRef<Verified<T>> for Verified<&T> ---
#[test]
fn verified_ref_as_ref_is_same_address() {
let val = 99u32;
let vref: Verified<&u32> = Verified::new_unchecked(&val);
let v: &Verified<u32> = vref.as_ref();
assert_eq!(
&val as *const u32 as *const u8, v as *const _ as *const u8,
"AsRef<Verified<T>> for Verified<&T> must alias the referent, not copy it"
);
}
}

View File

@@ -102,11 +102,21 @@ impl KeyCell {
} }
} }
/// User password might be of different length, have not enough entropy, etc...
/// Derive a fixed-length key from the password using Argon2id, which is designed for password hashing and key derivation. /// Derive a fixed-length key from the password using Argon2id, which is designed for password hashing and key derivation.
pub fn derive_key(mut password: SafeCell<Vec<u8>>, salt: &Salt) -> KeyCell { pub fn derive_key(mut password: SafeCell<Vec<u8>>, salt: &Salt) -> KeyCell {
let params = {
#[cfg(debug_assertions)]
{
argon2::Params::new(8, 1, 1, None).unwrap()
}
#[cfg(not(debug_assertions))]
{
argon2::Params::new(262_144, 3, 4, None).unwrap()
}
};
#[allow(clippy::unwrap_used)] #[allow(clippy::unwrap_used)]
let params = argon2::Params::new(262_144, 3, 4, None).unwrap();
let hasher = Argon2::new(Algorithm::Argon2id, argon2::Version::V0x13, params); let hasher = Argon2::new(Algorithm::Argon2id, argon2::Version::V0x13, params);
let mut key = SafeCell::new(Key::default()); let mut key = SafeCell::new(Key::default());
password.read_inline(|password_source| { password.read_inline(|password_source| {

View File

@@ -133,6 +133,7 @@ pub async fn create_pool(url: Option<&str>) -> Result<DatabasePool, DatabaseSetu
Ok(pool) Ok(pool)
} }
#[mutants::skip]
pub async fn create_test_pool() -> DatabasePool { pub async fn create_test_pool() -> DatabasePool {
use rand::distr::{Alphanumeric, SampleString as _}; use rand::distr::{Alphanumeric, SampleString as _};

View File

@@ -12,7 +12,7 @@ use kameo::actor::ActorRef;
use crate::{ use crate::{
actors::keyholder::KeyHolder, actors::keyholder::KeyHolder,
crypto::integrity, crypto::integrity::{self, Verified, VerifiedEntity, verified::VerifiedFieldsAccessor},
db::{ db::{
self, DatabaseError, self, DatabaseError,
models::{ models::{
@@ -21,8 +21,8 @@ use crate::{
schema::{self, evm_transaction_log}, schema::{self, evm_transaction_log},
}, },
evm::policies::{ evm::policies::{
DatabaseID, EvalContext, EvalViolation, Grant, Policy, CombinedSettings, SharedGrantSettings, CombinedSettings, DatabaseID, EvalContext, EvalViolation, Grant, Policy,
SpecificGrant, SpecificMeaning, ether_transfer::EtherTransfer, SharedGrantSettings, SpecificGrant, SpecificMeaning, ether_transfer::EtherTransfer,
token_transfers::TokenTransfer, token_transfers::TokenTransfer,
}, },
}; };
@@ -90,6 +90,14 @@ async fn check_shared_constraints(
let mut violations = Vec::new(); let mut violations = Vec::new();
let now = Utc::now(); let now = Utc::now();
if shared.chain != context.chain {
violations.push(EvalViolation::MismatchingChainId {
expected: shared.chain,
actual: context.chain,
});
return Ok(violations);
}
// Validity window // Validity window
if shared.valid_from.is_some_and(|t| now < t) || shared.valid_until.is_some_and(|t| now > t) { if shared.valid_from.is_some_and(|t| now < t) || shared.valid_until.is_some_and(|t| now > t) {
violations.push(EvalViolation::InvalidTime); violations.push(EvalViolation::InvalidTime);
@@ -145,12 +153,39 @@ impl Engine {
{ {
let mut conn = self.db.get().await.map_err(DatabaseError::from)?; let mut conn = self.db.get().await.map_err(DatabaseError::from)?;
let grant = P::try_find_grant(&context, &mut conn) let verified_settings =
match integrity::lookup_verified_from_query(&mut conn, &self.keyholder, |conn| {
let context = context.clone();
Box::pin(async move {
let grant = P::try_find_grant(&context, conn)
.await
.map_err(DatabaseError::from)?
.ok_or_else(|| DatabaseError::from(diesel::result::Error::NotFound))?;
Ok::<_, DatabaseError>((grant.common_settings_id, grant.settings))
})
})
.await
{
Ok(verified) => verified,
Err(integrity::Error::Database(DatabaseError::Connection(
diesel::result::Error::NotFound,
))) => return Err(PolicyError::NoMatchingGrant),
Err(err) => return Err(PolicyError::Integrity(err)),
};
let mut grant = P::try_find_grant(&context, &mut conn)
.await .await
.map_err(DatabaseError::from)? .map_err(DatabaseError::from)?
.ok_or(PolicyError::NoMatchingGrant)?; .ok_or(PolicyError::NoMatchingGrant)?;
integrity::verify_entity(&mut conn, &self.keyholder, &grant.settings, grant.id).await?; // IMPORTANT: policy evaluation uses extra non-integrity fields from Grant
// (e.g., per-policy ids), so we currently reload Grant after the query-native
// integrity check over canonicalized settings.
grant.settings = verified_settings
.inherit()
.entity
.drop_verification_provenance();
let mut violations = check_shared_constraints( let mut violations = check_shared_constraints(
&context, &context,
@@ -206,7 +241,7 @@ impl Engine {
pub async fn create_grant<P: Policy>( pub async fn create_grant<P: Policy>(
&self, &self,
full_grant: CombinedSettings<P::Settings>, full_grant: CombinedSettings<P::Settings>,
) -> Result<i32, DatabaseError> ) -> Result<Verified<i32>, DatabaseError>
where where
P::Settings: Clone, P::Settings: Clone,
{ {
@@ -250,27 +285,23 @@ impl Engine {
P::create_grant(&basic_grant, &full_grant.specific, conn).await?; P::create_grant(&basic_grant, &full_grant.specific, conn).await?;
integrity::sign_entity( let verified_entity_id =
conn, integrity::sign_entity(conn, &keyholder, &full_grant, basic_grant.id)
&keyholder, .await
&full_grant, .map_err(|_| diesel::result::Error::RollbackTransaction)?;
basic_grant.id,
)
.await
.map_err(|_| diesel::result::Error::RollbackTransaction)?;
QueryResult::Ok(basic_grant.id) QueryResult::Ok(verified_entity_id)
}) })
}) })
.await?; .await?;
Ok(id) Ok(id.unqualify_origin())
} }
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>,
) -> Result<impl Iterator<Item = Grant<Y>>, ListError> ) -> Result<Vec<Grant<Y>>, ListError>
where where
Y: From<Kind::Settings>, Y: From<Kind::Settings>,
{ {
@@ -278,16 +309,32 @@ impl Engine {
.await .await
.map_err(DatabaseError::from)?; .map_err(DatabaseError::from)?;
// Verify integrity of all grants before returning any results let mut verified_grants = Vec::with_capacity(all_grants.len());
for grant in &all_grants {
integrity::verify_entity(conn, &self.keyholder, &grant.settings, grant.id).await?; // Verify integrity of all grants before returning any results.
for grant in all_grants {
let VerifiedEntity {
entity: verified_settings,
entity_id: _,
} = integrity::verify_entity(
conn,
&self.keyholder,
grant.settings,
grant.common_settings_id,
)
.await?
.inherit();
verified_grants.push(Grant {
id: grant.id,
common_settings_id: grant.common_settings_id,
settings: verified_settings
.drop_verification_provenance()
.generalize(),
});
} }
Ok(all_grants.into_iter().map(|g| Grant { Ok(verified_grants)
id: g.id,
common_settings_id: g.common_settings_id,
settings: g.settings.generalize(),
}))
} }
pub async fn list_all_grants(&self) -> Result<Vec<Grant<SpecificGrant>>, ListError> { pub async fn list_all_grants(&self) -> Result<Vec<Grant<SpecificGrant>>, ListError> {
@@ -342,3 +389,255 @@ impl Engine {
Err(VetError::UnsupportedTransactionType) Err(VetError::UnsupportedTransactionType)
} }
} }
#[cfg(test)]
mod tests {
use alloy::primitives::{Address, Bytes, U256, address};
use chrono::{Duration, Utc};
use diesel::{SelectableHelper, insert_into};
use diesel_async::RunQueryDsl;
use rstest::rstest;
use crate::db::{
self, DatabaseConnection,
models::{
EvmBasicGrant, EvmWalletAccess, NewEvmBasicGrant, NewEvmTransactionLog, SqliteTimestamp,
},
schema::{evm_basic_grant, evm_transaction_log},
};
use crate::evm::policies::{
EvalContext, EvalViolation, SharedGrantSettings, TransactionRateLimit,
};
use super::check_shared_constraints;
const WALLET_ACCESS_ID: i32 = 1;
const CHAIN_ID: u64 = 1;
const RECIPIENT: Address = address!("1111111111111111111111111111111111111111");
fn context() -> EvalContext {
EvalContext {
target: EvmWalletAccess {
id: WALLET_ACCESS_ID,
wallet_id: 10,
client_id: 20,
created_at: SqliteTimestamp(Utc::now()),
},
chain: CHAIN_ID,
to: RECIPIENT,
value: U256::ZERO,
calldata: Bytes::new(),
max_fee_per_gas: 100,
max_priority_fee_per_gas: 10,
}
}
fn shared_settings() -> SharedGrantSettings {
SharedGrantSettings {
wallet_access_id: WALLET_ACCESS_ID,
chain: CHAIN_ID,
valid_from: None,
valid_until: None,
max_gas_fee_per_gas: None,
max_priority_fee_per_gas: None,
rate_limit: None,
}
}
async fn insert_basic_grant(
conn: &mut DatabaseConnection,
shared: &SharedGrantSettings,
) -> EvmBasicGrant {
insert_into(evm_basic_grant::table)
.values(NewEvmBasicGrant {
wallet_access_id: shared.wallet_access_id,
chain_id: shared.chain as i32,
valid_from: shared.valid_from.map(SqliteTimestamp),
valid_until: shared.valid_until.map(SqliteTimestamp),
max_gas_fee_per_gas: shared
.max_gas_fee_per_gas
.map(|fee| super::utils::u256_to_bytes(fee).to_vec()),
max_priority_fee_per_gas: shared
.max_priority_fee_per_gas
.map(|fee| super::utils::u256_to_bytes(fee).to_vec()),
rate_limit_count: shared.rate_limit.as_ref().map(|limit| limit.count as i32),
rate_limit_window_secs: shared
.rate_limit
.as_ref()
.map(|limit| limit.window.num_seconds() as i32),
revoked_at: None,
})
.returning(EvmBasicGrant::as_select())
.get_result(conn)
.await
.unwrap()
}
#[rstest]
#[case::matching_chain(CHAIN_ID, false)]
#[case::mismatching_chain(CHAIN_ID + 1, true)]
#[tokio::test]
async fn check_shared_constraints_enforces_chain_id(
#[case] context_chain: u64,
#[case] expect_mismatch: bool,
) {
let db = db::create_test_pool().await;
let mut conn = db.get().await.unwrap();
let context = EvalContext {
chain: context_chain,
..context()
};
let violations = check_shared_constraints(&context, &shared_settings(), 999, &mut *conn)
.await
.unwrap();
assert_eq!(
violations
.iter()
.any(|violation| matches!(violation, EvalViolation::MismatchingChainId { .. })),
expect_mismatch
);
if expect_mismatch {
assert_eq!(violations.len(), 1);
} else {
assert!(violations.is_empty());
}
}
#[rstest]
#[case::valid_from_in_bounds(Some(Utc::now() - Duration::hours(1)), None, false)]
#[case::valid_from_out_of_bounds(Some(Utc::now() + Duration::hours(1)), None, true)]
#[case::valid_until_in_bounds(None, Some(Utc::now() + Duration::hours(1)), false)]
#[case::valid_until_out_of_bounds(None, Some(Utc::now() - Duration::hours(1)), true)]
#[tokio::test]
async fn check_shared_constraints_enforces_validity_window(
#[case] valid_from: Option<chrono::DateTime<Utc>>,
#[case] valid_until: Option<chrono::DateTime<Utc>>,
#[case] expect_invalid_time: bool,
) {
let db = db::create_test_pool().await;
let mut conn = db.get().await.unwrap();
let shared = SharedGrantSettings {
valid_from,
valid_until,
..shared_settings()
};
let violations = check_shared_constraints(&context(), &shared, 999, &mut *conn)
.await
.unwrap();
assert_eq!(
violations
.iter()
.any(|violation| matches!(violation, EvalViolation::InvalidTime)),
expect_invalid_time
);
if expect_invalid_time {
assert_eq!(violations.len(), 1);
} else {
assert!(violations.is_empty());
}
}
#[rstest]
#[case::max_fee_within_limit(Some(U256::from(100u64)), None, 100, 10, false)]
#[case::max_fee_exceeded(Some(U256::from(99u64)), None, 100, 10, true)]
#[case::priority_fee_within_limit(None, Some(U256::from(10u64)), 100, 10, false)]
#[case::priority_fee_exceeded(None, Some(U256::from(9u64)), 100, 10, true)]
#[tokio::test]
async fn check_shared_constraints_enforces_gas_fee_caps(
#[case] max_gas_fee_per_gas: Option<U256>,
#[case] max_priority_fee_per_gas: Option<U256>,
#[case] actual_max_fee_per_gas: u128,
#[case] actual_max_priority_fee_per_gas: u128,
#[case] expect_gas_limit_violation: bool,
) {
let db = db::create_test_pool().await;
let mut conn = db.get().await.unwrap();
let context = EvalContext {
max_fee_per_gas: actual_max_fee_per_gas,
max_priority_fee_per_gas: actual_max_priority_fee_per_gas,
..context()
};
let shared = SharedGrantSettings {
max_gas_fee_per_gas,
max_priority_fee_per_gas,
..shared_settings()
};
let violations = check_shared_constraints(&context, &shared, 999, &mut *conn)
.await
.unwrap();
assert_eq!(
violations
.iter()
.any(|violation| matches!(violation, EvalViolation::GasLimitExceeded { .. })),
expect_gas_limit_violation
);
if expect_gas_limit_violation {
assert_eq!(violations.len(), 1);
} else {
assert!(violations.is_empty());
}
}
#[rstest]
#[case::under_rate_limit(2, false)]
#[case::at_rate_limit(1, true)]
#[tokio::test]
async fn check_shared_constraints_enforces_rate_limit(
#[case] rate_limit_count: u32,
#[case] expect_rate_limit_violation: bool,
) {
let db = db::create_test_pool().await;
let mut conn = db.get().await.unwrap();
let shared = SharedGrantSettings {
rate_limit: Some(TransactionRateLimit {
count: rate_limit_count,
window: Duration::hours(1),
}),
..shared_settings()
};
let basic_grant = insert_basic_grant(&mut conn, &shared).await;
insert_into(evm_transaction_log::table)
.values(NewEvmTransactionLog {
grant_id: basic_grant.id,
wallet_access_id: WALLET_ACCESS_ID,
chain_id: CHAIN_ID as i32,
eth_value: super::utils::u256_to_bytes(U256::ZERO).to_vec(),
signed_at: SqliteTimestamp(Utc::now()),
})
.execute(&mut *conn)
.await
.unwrap();
let violations = check_shared_constraints(&context(), &shared, basic_grant.id, &mut *conn)
.await
.unwrap();
assert_eq!(
violations
.iter()
.any(|violation| matches!(violation, EvalViolation::RateLimitExceeded)),
expect_rate_limit_violation
);
if expect_rate_limit_violation {
assert_eq!(violations.len(), 1);
} else {
assert!(violations.is_empty());
}
}
}

View File

@@ -7,11 +7,12 @@ use diesel::{
}; };
use diesel_async::{AsyncConnection, RunQueryDsl}; use diesel_async::{AsyncConnection, RunQueryDsl};
use serde::Serialize;
use thiserror::Error; use thiserror::Error;
use crate::{ use crate::{
crypto::integrity::v1::Integrable, db::models::{self, EvmBasicGrant, EvmWalletAccess}, evm::utils crypto::integrity::v1::Integrable,
db::models::{self, EvmBasicGrant, EvmWalletAccess},
evm::utils,
}; };
pub mod ether_transfer; pub mod ether_transfer;
@@ -55,11 +56,14 @@ pub enum EvalViolation {
#[error("Transaction type is not allowed by this grant")] #[error("Transaction type is not allowed by this grant")]
InvalidTransactionType, InvalidTransactionType,
#[error("Mismatching chain ID")]
MismatchingChainId { expected: ChainId, actual: ChainId },
} }
pub type DatabaseID = i32; pub type DatabaseID = i32;
#[derive(Debug, Serialize)] #[derive(Debug)]
pub struct Grant<PolicySettings> { pub struct Grant<PolicySettings> {
pub id: DatabaseID, pub id: DatabaseID,
pub common_settings_id: DatabaseID, // ID of the basic grant for shared-logic checks like rate limits and validity periods pub common_settings_id: DatabaseID, // ID of the basic grant for shared-logic checks like rate limits and validity periods
@@ -123,19 +127,19 @@ pub enum SpecificMeaning {
TokenTransfer(token_transfers::Meaning), TokenTransfer(token_transfers::Meaning),
} }
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TransactionRateLimit { pub struct TransactionRateLimit {
pub count: u32, pub count: u32,
pub window: Duration, pub window: Duration,
} }
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct VolumeRateLimit { pub struct VolumeRateLimit {
pub max_volume: U256, pub max_volume: U256,
pub window: Duration, pub window: Duration,
} }
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)] #[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct SharedGrantSettings { pub struct SharedGrantSettings {
pub wallet_access_id: i32, pub wallet_access_id: i32,
pub chain: ChainId, pub chain: ChainId,
@@ -196,7 +200,7 @@ pub enum SpecificGrant {
TokenTransfer(token_transfers::Settings), TokenTransfer(token_transfers::Settings),
} }
#[derive(Debug, Serialize)] #[derive(Debug, Clone)]
pub struct CombinedSettings<PolicyGrant> { pub struct CombinedSettings<PolicyGrant> {
pub shared: SharedGrantSettings, pub shared: SharedGrantSettings,
pub specific: PolicyGrant, pub specific: PolicyGrant,
@@ -216,3 +220,37 @@ impl<P: Integrable> Integrable for CombinedSettings<P> {
const VERSION: i32 = P::VERSION; const VERSION: i32 = P::VERSION;
} }
use crate::crypto::integrity::hashing::Hashable;
impl Hashable for TransactionRateLimit {
fn hash<H: sha2::Digest>(&self, hasher: &mut H) {
self.count.hash(hasher);
self.window.hash(hasher);
}
}
impl Hashable for VolumeRateLimit {
fn hash<H: sha2::Digest>(&self, hasher: &mut H) {
self.max_volume.hash(hasher);
self.window.hash(hasher);
}
}
impl Hashable for SharedGrantSettings {
fn hash<H: sha2::Digest>(&self, hasher: &mut H) {
self.wallet_access_id.hash(hasher);
self.chain.hash(hasher);
self.valid_from.hash(hasher);
self.valid_until.hash(hasher);
self.max_gas_fee_per_gas.hash(hasher);
self.max_priority_fee_per_gas.hash(hasher);
self.rate_limit.hash(hasher);
}
}
impl<P: Hashable> Hashable for CombinedSettings<P> {
fn hash<H: sha2::Digest>(&self, hasher: &mut H) {
self.shared.hash(hasher);
self.specific.hash(hasher);
}
}

View File

@@ -52,7 +52,7 @@ impl From<Meaning> for SpecificMeaning {
} }
// A grant for ether transfers, which can be scoped to specific target addresses and volume limits // A grant for ether transfers, which can be scoped to specific target addresses and volume limits
#[derive(Debug, Clone, serde::Serialize)] #[derive(Debug, Clone)]
pub struct Settings { pub struct Settings {
pub target: Vec<Address>, pub target: Vec<Address>,
pub limit: VolumeRateLimit, pub limit: VolumeRateLimit,
@@ -61,6 +61,15 @@ impl Integrable for Settings {
const KIND: &'static str = "EtherTransfer"; const KIND: &'static str = "EtherTransfer";
} }
use crate::crypto::integrity::hashing::Hashable;
impl Hashable for Settings {
fn hash<H: sha2::Digest>(&self, hasher: &mut H) {
self.target.hash(hasher);
self.limit.hash(hasher);
}
}
impl From<Settings> for SpecificGrant { impl From<Settings> for SpecificGrant {
fn from(val: Settings) -> SpecificGrant { fn from(val: Settings) -> SpecificGrant {
SpecificGrant::EtherTransfer(val) SpecificGrant::EtherTransfer(val)
@@ -101,7 +110,8 @@ async fn check_rate_limits(
let mut violations = Vec::new(); let mut violations = Vec::new();
let window = grant.settings.specific.limit.window; let window = grant.settings.specific.limit.window;
let past_transaction = query_relevant_past_transaction(grant.id, window, db).await?; let past_transaction =
query_relevant_past_transaction(grant.common_settings_id, window, db).await?;
let window_start = chrono::Utc::now() - grant.settings.specific.limit.window; let window_start = chrono::Utc::now() - grant.settings.specific.limit.window;
let prospective_cumulative_volume: U256 = past_transaction let prospective_cumulative_volume: U256 = past_transaction
@@ -240,21 +250,20 @@ impl Policy for EtherTransfer {
}) })
.collect(); .collect();
let settings = Settings {
target: targets,
limit: VolumeRateLimit {
max_volume: utils::try_bytes_to_u256(&limit.max_volume)
.map_err(|err| diesel::result::Error::DeserializationError(Box::new(err)))?,
window: chrono::Duration::seconds(limit.window_secs as i64),
},
};
Ok(Some(Grant { Ok(Some(Grant {
id: grant.id, id: grant.id,
common_settings_id: grant.basic_grant_id, common_settings_id: grant.basic_grant_id,
settings: CombinedSettings { settings: CombinedSettings {
shared: SharedGrantSettings::try_from_model(basic_grant)?, shared: SharedGrantSettings::try_from_model(basic_grant)?,
specific: settings, specific: Settings {
target: targets,
limit: VolumeRateLimit {
max_volume: utils::try_bytes_to_u256(&limit.max_volume).map_err(|err| {
diesel::result::Error::DeserializationError(Box::new(err))
})?,
window: chrono::Duration::seconds(limit.window_secs as i64),
},
},
}, },
})) }))
} }

View File

@@ -84,8 +84,6 @@ fn shared() -> SharedGrantSettings {
} }
} }
// ── analyze ─────────────────────────────────────────────────────────────
#[test] #[test]
fn analyze_matches_empty_calldata() { fn analyze_matches_empty_calldata() {
let m = EtherTransfer::analyze(&ctx(ALLOWED, U256::from(1_000u64))).unwrap(); let m = EtherTransfer::analyze(&ctx(ALLOWED, U256::from(1_000u64))).unwrap();
@@ -102,8 +100,6 @@ fn analyze_rejects_nonempty_calldata() {
assert!(EtherTransfer::analyze(&context).is_none()); assert!(EtherTransfer::analyze(&context).is_none());
} }
// ── evaluate ────────────────────────────────────────────────────────────
#[tokio::test] #[tokio::test]
async fn evaluate_passes_for_allowed_target() { async fn evaluate_passes_for_allowed_target() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
@@ -276,8 +272,6 @@ async fn evaluate_passes_at_exactly_volume_limit() {
); );
} }
// ── try_find_grant ───────────────────────────────────────────────────────
#[tokio::test] #[tokio::test]
async fn try_find_grant_roundtrip() { async fn try_find_grant_roundtrip() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
@@ -336,7 +330,36 @@ async fn try_find_grant_wrong_target_returns_none() {
assert!(found.is_none()); assert!(found.is_none());
} }
// ── find_all_grants ────────────────────────────────────────────────────── proptest::proptest! {
#[test]
fn target_order_does_not_affect_hash(
raw_addrs in proptest::collection::vec(proptest::prelude::any::<[u8; 20]>(), 0..8),
seed in proptest::prelude::any::<u64>(),
max_volume in proptest::prelude::any::<u64>(),
window_secs in 1i64..=86400,
) {
use rand::{SeedableRng, seq::SliceRandom};
use sha2::Digest;
use crate::crypto::integrity::hashing::Hashable;
let addrs: Vec<Address> = raw_addrs.iter().map(|b| Address::from(*b)).collect();
let mut shuffled = addrs.clone();
shuffled.shuffle(&mut rand::rngs::StdRng::seed_from_u64(seed));
let limit = VolumeRateLimit {
max_volume: U256::from(max_volume),
window: Duration::seconds(window_secs),
};
let mut h1 = sha2::Sha256::new();
Settings { target: addrs, limit: limit.clone() }.hash(&mut h1);
let mut h2 = sha2::Sha256::new();
Settings { target: shuffled, limit }.hash(&mut h2);
proptest::prop_assert_eq!(h1.finalize(), h2.finalize());
}
}
#[tokio::test] #[tokio::test]
async fn find_all_grants_empty_db() { async fn find_all_grants_empty_db() {

View File

@@ -1,17 +1,5 @@
use std::collections::HashMap; use std::collections::HashMap;
use alloy::{
primitives::{Address, U256},
sol_types::SolCall,
};
use arbiter_tokens_registry::evm::nonfungible::{self, TokenInfo};
use chrono::{DateTime, Duration, Utc};
use diesel::dsl::{auto_type, insert_into};
use diesel::sqlite::Sqlite;
use diesel::{ExpressionMethods, prelude::*};
use diesel_async::{AsyncConnection, RunQueryDsl};
use serde::Serialize;
use crate::db::schema::{ use crate::db::schema::{
evm_basic_grant, evm_token_transfer_grant, evm_token_transfer_log, evm_basic_grant, evm_token_transfer_grant, evm_token_transfer_log,
evm_token_transfer_volume_limit, evm_token_transfer_volume_limit,
@@ -32,6 +20,16 @@ use crate::{
}, },
evm::policies::CombinedSettings, evm::policies::CombinedSettings,
}; };
use alloy::{
primitives::{Address, U256},
sol_types::SolCall,
};
use arbiter_tokens_registry::evm::nonfungible::{self, TokenInfo};
use chrono::{DateTime, Duration, Utc};
use diesel::dsl::{auto_type, insert_into};
use diesel::sqlite::Sqlite;
use diesel::{ExpressionMethods, prelude::*};
use diesel_async::{AsyncConnection, RunQueryDsl};
use super::{DatabaseID, EvalContext, EvalViolation}; use super::{DatabaseID, EvalContext, EvalViolation};
@@ -64,7 +62,7 @@ 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, Serialize)] #[derive(Debug, Clone)]
pub struct Settings { pub struct Settings {
pub token_contract: Address, pub token_contract: Address,
pub target: Option<Address>, pub target: Option<Address>,
@@ -73,6 +71,17 @@ pub struct Settings {
impl Integrable for Settings { impl Integrable for Settings {
const KIND: &'static str = "TokenTransfer"; const KIND: &'static str = "TokenTransfer";
} }
use crate::crypto::integrity::hashing::Hashable;
impl Hashable for Settings {
fn hash<H: sha2::Digest>(&self, hasher: &mut H) {
self.token_contract.hash(hasher);
self.target.hash(hasher);
self.volume_limits.hash(hasher);
}
}
impl From<Settings> for SpecificGrant { impl From<Settings> for SpecificGrant {
fn from(val: Settings) -> SpecificGrant { fn from(val: Settings) -> SpecificGrant {
SpecificGrant::TokenTransfer(val) SpecificGrant::TokenTransfer(val)
@@ -277,18 +286,16 @@ impl Policy for TokenTransfer {
} }
}; };
let settings = Settings {
token_contract: Address::from(token_contract),
target,
volume_limits,
};
Ok(Some(Grant { Ok(Some(Grant {
id: token_grant.id, id: token_grant.id,
common_settings_id: token_grant.basic_grant_id, common_settings_id: token_grant.basic_grant_id,
settings: CombinedSettings { settings: CombinedSettings {
shared: SharedGrantSettings::try_from_model(basic_grant)?, shared: SharedGrantSettings::try_from_model(basic_grant)?,
specific: settings, specific: Settings {
token_contract: Address::from(token_contract),
target,
volume_limits,
},
}, },
})) }))
} }

View File

@@ -101,8 +101,6 @@ fn shared() -> SharedGrantSettings {
} }
} }
// ── analyze ─────────────────────────────────────────────────────────────
#[test] #[test]
fn analyze_known_token_valid_calldata() { fn analyze_known_token_valid_calldata() {
let calldata = transfer_calldata(RECIPIENT, U256::from(100u64)); let calldata = transfer_calldata(RECIPIENT, U256::from(100u64));
@@ -128,8 +126,6 @@ fn analyze_empty_calldata_returns_none() {
assert!(TokenTransfer::analyze(&ctx(DAI, Bytes::new())).is_none()); assert!(TokenTransfer::analyze(&ctx(DAI, Bytes::new())).is_none());
} }
// ── evaluate ────────────────────────────────────────────────────────────
#[tokio::test] #[tokio::test]
async fn evaluate_rejects_nonzero_eth_value() { async fn evaluate_rejects_nonzero_eth_value() {
let db = db::create_test_pool().await; let db = db::create_test_pool().await;
@@ -412,7 +408,39 @@ async fn try_find_grant_unknown_token_returns_none() {
assert!(found.is_none()); assert!(found.is_none());
} }
// ── find_all_grants ────────────────────────────────────────────────────── proptest::proptest! {
#[test]
fn volume_limits_order_does_not_affect_hash(
raw_limits in proptest::collection::vec(
(proptest::prelude::any::<u64>(), 1i64..=86400),
0..8,
),
seed in proptest::prelude::any::<u64>(),
) {
use rand::{SeedableRng, seq::SliceRandom};
use sha2::Digest;
use crate::crypto::integrity::hashing::Hashable;
let limits: Vec<VolumeRateLimit> = raw_limits
.iter()
.map(|(max_vol, window_secs)| VolumeRateLimit {
max_volume: U256::from(*max_vol),
window: Duration::seconds(*window_secs),
})
.collect();
let mut shuffled = limits.clone();
shuffled.shuffle(&mut rand::rngs::StdRng::seed_from_u64(seed));
let mut h1 = sha2::Sha256::new();
Settings { token_contract: DAI, target: None, volume_limits: limits }.hash(&mut h1);
let mut h2 = sha2::Sha256::new();
Settings { token_contract: DAI, target: None, volume_limits: shuffled }.hash(&mut h2);
proptest::prop_assert_eq!(h1.finalize(), h2.finalize());
}
}
#[tokio::test] #[tokio::test]
async fn find_all_grants_empty_db() { async fn find_all_grants_empty_db() {

View File

@@ -22,6 +22,7 @@ use tracing::warn;
use crate::{ use crate::{
actors::client::{self, ClientConnection, auth}, actors::client::{self, ClientConnection, auth},
crypto::integrity::Verified,
grpc::request_tracker::RequestTracker, grpc::request_tracker::RequestTracker,
}; };
@@ -68,6 +69,7 @@ impl<'a> AuthTransportAdapter<'a> {
auth::Error::ApproveError(auth::ApproveError::Internal) auth::Error::ApproveError(auth::ApproveError::Internal)
| auth::Error::DatabasePoolUnavailable | auth::Error::DatabasePoolUnavailable
| auth::Error::DatabaseOperationFailed | auth::Error::DatabaseOperationFailed
| auth::Error::IntegrityCheckFailed
| auth::Error::Transport => ProtoAuthResult::Internal, | auth::Error::Transport => ProtoAuthResult::Internal,
} }
.into(), .into(),
@@ -199,7 +201,7 @@ pub 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,
) -> Result<i32, auth::Error> { ) -> Result<Verified<i32>, auth::Error> {
let mut transport = AuthTransportAdapter::new(bi, request_tracker); let mut transport = AuthTransportAdapter::new(bi, request_tracker);
client::auth::authenticate(conn, &mut transport).await client::auth::authenticate(conn, &mut transport).await
} }

View File

@@ -8,7 +8,7 @@ use arbiter_proto::proto::{
EvalViolation as ProtoEvalViolation, GasLimitExceededViolation, NoMatchingGrantError, EvalViolation as ProtoEvalViolation, GasLimitExceededViolation, NoMatchingGrantError,
PolicyViolationsError, SpecificMeaning as ProtoSpecificMeaning, PolicyViolationsError, SpecificMeaning as ProtoSpecificMeaning,
TokenInfo as ProtoTokenInfo, TransactionEvalError as ProtoTransactionEvalError, TokenInfo as ProtoTokenInfo, TransactionEvalError as ProtoTransactionEvalError,
eval_violation::Kind as ProtoEvalViolationKind, eval_violation as proto_eval_violation, eval_violation::Kind as ProtoEvalViolationKind,
specific_meaning::Meaning as ProtoSpecificMeaningKind, specific_meaning::Meaning as ProtoSpecificMeaningKind,
transaction_eval_error::Kind as ProtoTransactionEvalErrorKind, transaction_eval_error::Kind as ProtoTransactionEvalErrorKind,
}, },
@@ -79,6 +79,12 @@ impl Convert for EvalViolation {
EvalViolation::InvalidTransactionType => { EvalViolation::InvalidTransactionType => {
ProtoEvalViolationKind::InvalidTransactionType(()) ProtoEvalViolationKind::InvalidTransactionType(())
} }
EvalViolation::MismatchingChainId { expected, actual } => {
ProtoEvalViolationKind::ChainIdMismatch(proto_eval_violation::ChainIdMismatch {
expected,
actual,
})
}
}; };
ProtoEvalViolation { kind: Some(kind) } ProtoEvalViolation { kind: Some(kind) }
@@ -108,7 +114,7 @@ impl Convert for VetError {
violations: violations.into_iter().map(Convert::convert).collect(), violations: violations.into_iter().map(Convert::convert).collect(),
}) })
} }
PolicyError::Database(_)| PolicyError::Integrity(_) => { PolicyError::Database(_) | PolicyError::Integrity(_) => {
return EvmSignTransactionResult::Error(ProtoEvmError::Internal.into()); return EvmSignTransactionResult::Error(ProtoEvmError::Internal.into());
} }
}, },

View File

@@ -66,7 +66,7 @@ async fn handle_wallet_create(
) -> Result<Option<UserAgentResponsePayload>, Status> { ) -> Result<Option<UserAgentResponsePayload>, Status> {
let result = match actor.ask(HandleEvmWalletCreate {}).await { let result = match actor.ask(HandleEvmWalletCreate {}).await {
Ok((wallet_id, address)) => WalletCreateResult::Wallet(WalletEntry { Ok((wallet_id, address)) => WalletCreateResult::Wallet(WalletEntry {
id: wallet_id, id: wallet_id.drop_verification_provenance(),
address: address.to_vec(), address: address.to_vec(),
}), }),
Err(err) => { Err(err) => {
@@ -121,6 +121,9 @@ async fn handle_grant_list(
}) })
.collect(), .collect(),
}), }),
Err(kameo::error::SendError::HandlerError(GrantMutationError::VaultSealed)) => {
EvmGrantListResult::Error(ProtoEvmError::VaultSealed.into())
}
Err(err) => { Err(err) => {
warn!(error = ?err, "Failed to list EVM grants"); warn!(error = ?err, "Failed to list EVM grants");
EvmGrantListResult::Error(ProtoEvmError::Internal.into()) EvmGrantListResult::Error(ProtoEvmError::Internal.into())
@@ -147,7 +150,7 @@ async fn handle_grant_create(
.try_convert()?; .try_convert()?;
let result = match actor.ask(HandleGrantCreate { basic, grant }).await { let result = match actor.ask(HandleGrantCreate { basic, grant }).await {
Ok(grant_id) => EvmGrantCreateResult::GrantId(grant_id), Ok(grant_id) => EvmGrantCreateResult::GrantId(grant_id.drop_verification_provenance()),
Err(kameo::error::SendError::HandlerError(GrantMutationError::VaultSealed)) => { Err(kameo::error::SendError::HandlerError(GrantMutationError::VaultSealed)) => {
EvmGrantCreateResult::Error(ProtoEvmError::VaultSealed.into()) EvmGrantCreateResult::Error(ProtoEvmError::VaultSealed.into())
} }

View File

@@ -1,6 +1,8 @@
#![forbid(unsafe_code)]
use crate::context::ServerContext; use crate::context::ServerContext;
#[macro_use]
extern crate macro_rules_attribute;
pub mod actors; pub mod actors;
pub mod context; pub mod context;
pub mod crypto; pub mod crypto;

View File

@@ -10,6 +10,7 @@ use tracing::info;
const PORT: u16 = 50051; const PORT: u16 = 50051;
#[tokio::main] #[tokio::main]
#[mutants::skip]
async fn main() -> anyhow::Result<()> { async fn main() -> anyhow::Result<()> {
aws_lc_rs::default_provider().install_default().unwrap(); aws_lc_rs::default_provider().install_default().unwrap();

View File

@@ -1,3 +1,5 @@
use std::ops::Deref;
struct DeferClosure<F: FnOnce()> { struct DeferClosure<F: FnOnce()> {
f: Option<F>, f: Option<F>,
} }
@@ -14,3 +16,19 @@ impl<F: FnOnce()> Drop for DeferClosure<F> {
pub fn defer<F: FnOnce()>(f: F) -> impl Drop + Sized { pub fn defer<F: FnOnce()>(f: F) -> impl Drop + Sized {
DeferClosure { f: Some(f) } DeferClosure { f: Some(f) }
} }
/// A trait for casting between two transparently wrapped types with identical memory layouts.
///
/// [`ReinterpretWrapper`] enables zero-cost conversions between two types (`Self` and `Counterpart`)
/// that wrap the same underlying data but differ in how that data is presented. Both types must
/// transparently wrap the same "deref target" and provide bidirectional `AsRef` conversions.
pub trait ReinterpretWrapper<Counterpart>
where
Self: Deref<Target = Self::Inner> + AsRef<Counterpart>,
Counterpart: Deref<Target = Self::Inner> + AsRef<Self>,
{
/// The shared target type that both `Self` and `Counterpart` transparently wrap.
type Inner;
/// Reinterprets `Self` as `Counterpart`.
fn reinterpret(self) -> Counterpart;
}

View File

@@ -1,9 +1,14 @@
use arbiter_proto::ClientMetadata; use arbiter_proto::ClientMetadata;
use arbiter_proto::transport::{Receiver, Sender}; use arbiter_proto::transport::{Receiver, Sender};
use arbiter_server::actors::GlobalActors;
use arbiter_server::{ use arbiter_server::{
actors::client::{ClientConnection, auth, connect_client}, actors::{
db, GlobalActors,
client::{ClientConnection, ClientCredentials, auth, connect_client},
keyholder::Bootstrap,
},
crypto::integrity,
db::{self, schema},
safe_cell::{SafeCell, SafeCellHandle as _},
}; };
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;
@@ -21,7 +26,8 @@ fn metadata(name: &str, description: Option<&str>, version: Option<&str>) -> Cli
async fn insert_registered_client( async fn insert_registered_client(
db: &db::DatabasePool, db: &db::DatabasePool,
pubkey: Vec<u8>, actors: &GlobalActors,
pubkey: ed25519_dalek::VerifyingKey,
metadata: &ClientMetadata, metadata: &ClientMetadata,
) { ) {
use arbiter_server::db::schema::{client_metadata, program_client}; use arbiter_server::db::schema::{client_metadata, program_client};
@@ -37,23 +43,64 @@ async fn insert_registered_client(
.get_result(&mut conn) .get_result(&mut conn)
.await .await
.unwrap(); .unwrap();
insert_into(program_client::table) let client_id: i32 = insert_into(program_client::table)
.values(( .values((
program_client::public_key.eq(pubkey), program_client::public_key.eq(pubkey.to_bytes().to_vec()),
program_client::metadata_id.eq(metadata_id), program_client::metadata_id.eq(metadata_id),
)) ))
.returning(program_client::id)
.get_result(&mut conn)
.await
.unwrap();
let _ = integrity::sign_entity(
&mut conn,
&actors.key_holder,
&ClientCredentials { pubkey, nonce: 1 },
client_id,
)
.await
.unwrap();
}
async fn insert_bootstrap_sentinel_useragent(db: &db::DatabasePool) {
let mut conn = db.get().await.unwrap();
let sentinel_key = ed25519_dalek::SigningKey::generate(&mut rand::rng())
.verifying_key()
.to_bytes()
.to_vec();
insert_into(schema::useragent_client::table)
.values((
schema::useragent_client::public_key.eq(sentinel_key),
schema::useragent_client::key_type.eq(1i32),
))
.execute(&mut conn) .execute(&mut conn)
.await .await
.unwrap(); .unwrap();
} }
async fn spawn_test_actors(db: &db::DatabasePool) -> GlobalActors {
insert_bootstrap_sentinel_useragent(db).await;
let actors = GlobalActors::spawn(db.clone()).await.unwrap();
actors
.key_holder
.ask(Bootstrap {
seal_key_raw: SafeCell::new(b"test-seal-key".to_vec()),
})
.await
.unwrap();
actors
}
#[tokio::test] #[tokio::test]
#[test_log::test] #[test_log::test]
pub async fn test_unregistered_pubkey_rejected() { pub 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();
let actors = GlobalActors::spawn(db.clone()).await.unwrap(); let actors = spawn_test_actors(&db).await;
let props = ClientConnection::new(db.clone(), actors); let props = ClientConnection::new(db.clone(), actors);
let task = tokio::spawn(async move { let task = tokio::spawn(async move {
let mut server_transport = server_transport; let mut server_transport = server_transport;
@@ -78,20 +125,19 @@ pub async fn test_unregistered_pubkey_rejected() {
#[test_log::test] #[test_log::test]
pub async fn test_challenge_auth() { pub 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 new_key = ed25519_dalek::SigningKey::generate(&mut rand::rng()); let new_key = ed25519_dalek::SigningKey::generate(&mut rand::rng());
let pubkey_bytes = new_key.verifying_key().to_bytes().to_vec();
insert_registered_client( insert_registered_client(
&db, &db,
pubkey_bytes.clone(), &actors,
new_key.verifying_key(),
&metadata("client", Some("desc"), Some("1.0.0")), &metadata("client", Some("desc"), Some("1.0.0")),
) )
.await; .await;
let (server_transport, mut test_transport) = ChannelTransport::new(); let (server_transport, mut test_transport) = ChannelTransport::new();
let actors = GlobalActors::spawn(db.clone()).await.unwrap();
let props = ClientConnection::new(db.clone(), actors); let props = ClientConnection::new(db.clone(), actors);
let task = tokio::spawn(async move { let task = tokio::spawn(async move {
let mut server_transport = server_transport; let mut server_transport = server_transport;
@@ -147,34 +193,13 @@ pub async fn test_challenge_auth() {
#[test_log::test] #[test_log::test]
pub async fn test_metadata_unchanged_does_not_append_history() { pub 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 = GlobalActors::spawn(db.clone()).await.unwrap(); let actors = spawn_test_actors(&db).await;
let props = ClientConnection::new(db.clone(), actors);
let new_key = ed25519_dalek::SigningKey::generate(&mut rand::rng()); let new_key = ed25519_dalek::SigningKey::generate(&mut rand::rng());
let requested = metadata("client", Some("desc"), Some("1.0.0")); let requested = metadata("client", Some("desc"), Some("1.0.0"));
{ insert_registered_client(&db, &actors, new_key.verifying_key(), &requested).await;
use arbiter_server::db::schema::{client_metadata, program_client};
let mut conn = db.get().await.unwrap(); let props = ClientConnection::new(db.clone(), actors);
let metadata_id: i32 = insert_into(client_metadata::table)
.values((
client_metadata::name.eq(&requested.name),
client_metadata::description.eq(&requested.description),
client_metadata::version.eq(&requested.version),
))
.returning(client_metadata::id)
.get_result(&mut conn)
.await
.unwrap();
insert_into(program_client::table)
.values((
program_client::public_key.eq(new_key.verifying_key().to_bytes().to_vec()),
program_client::metadata_id.eq(metadata_id),
))
.execute(&mut conn)
.await
.unwrap();
}
let (server_transport, mut test_transport) = ChannelTransport::new(); let (server_transport, mut test_transport) = ChannelTransport::new();
let task = tokio::spawn(async move { let task = tokio::spawn(async move {
@@ -225,33 +250,18 @@ pub async fn test_metadata_unchanged_does_not_append_history() {
#[test_log::test] #[test_log::test]
pub async fn test_metadata_change_appends_history_and_repoints_binding() { pub 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 = GlobalActors::spawn(db.clone()).await.unwrap(); let actors = spawn_test_actors(&db).await;
let props = ClientConnection::new(db.clone(), actors);
let new_key = ed25519_dalek::SigningKey::generate(&mut rand::rng()); let new_key = ed25519_dalek::SigningKey::generate(&mut rand::rng());
{ insert_registered_client(
use arbiter_server::db::schema::{client_metadata, program_client}; &db,
let mut conn = db.get().await.unwrap(); &actors,
let metadata_id: i32 = insert_into(client_metadata::table) new_key.verifying_key(),
.values(( &metadata("client", Some("old"), Some("1.0.0")),
client_metadata::name.eq("client"), )
client_metadata::description.eq(Some("old")), .await;
client_metadata::version.eq(Some("1.0.0")),
)) let props = ClientConnection::new(db.clone(), actors);
.returning(client_metadata::id)
.get_result(&mut conn)
.await
.unwrap();
insert_into(program_client::table)
.values((
program_client::public_key.eq(new_key.verifying_key().to_bytes().to_vec()),
program_client::metadata_id.eq(metadata_id),
))
.execute(&mut conn)
.await
.unwrap();
}
let (server_transport, mut test_transport) = ChannelTransport::new(); let (server_transport, mut test_transport) = ChannelTransport::new();
let task = tokio::spawn(async move { let task = tokio::spawn(async move {
@@ -322,3 +332,59 @@ pub async fn test_metadata_change_appends_history_and_repoints_binding() {
); );
} }
} }
#[tokio::test]
#[test_log::test]
pub async fn test_challenge_auth_rejects_integrity_tag_mismatch() {
let db = db::create_test_pool().await;
let actors = spawn_test_actors(&db).await;
let new_key = ed25519_dalek::SigningKey::generate(&mut rand::rng());
let requested = metadata("client", Some("desc"), Some("1.0.0"));
{
use arbiter_server::db::schema::{client_metadata, program_client};
let mut conn = db.get().await.unwrap();
let metadata_id: i32 = insert_into(client_metadata::table)
.values((
client_metadata::name.eq(&requested.name),
client_metadata::description.eq(&requested.description),
client_metadata::version.eq(&requested.version),
))
.returning(client_metadata::id)
.get_result(&mut conn)
.await
.unwrap();
insert_into(program_client::table)
.values((
program_client::public_key.eq(new_key.verifying_key().to_bytes().to_vec()),
program_client::metadata_id.eq(metadata_id),
))
.execute(&mut conn)
.await
.unwrap();
}
let (server_transport, mut test_transport) = ChannelTransport::new();
let props = ClientConnection::new(db.clone(), actors);
let task = tokio::spawn(async move {
let mut server_transport = server_transport;
connect_client(props, &mut server_transport).await;
});
test_transport
.send(auth::Inbound::AuthChallengeRequest {
pubkey: new_key.verifying_key(),
metadata: requested,
})
.await
.unwrap();
let response = test_transport
.recv()
.await
.expect("should receive auth rejection");
assert!(matches!(response, Err(auth::Error::IntegrityCheckFailed)));
task.await.unwrap();
}

View File

@@ -139,7 +139,8 @@ pub async fn test_challenge_auth() {
id, id,
) )
.await .await
.unwrap(); .unwrap()
.drop_verification_provenance();
} }
let (server_transport, mut test_transport) = ChannelTransport::new(); let (server_transport, mut test_transport) = ChannelTransport::new();
@@ -278,7 +279,8 @@ pub async fn test_challenge_auth_rejects_invalid_signature() {
id, id,
) )
.await .await
.unwrap(); .unwrap()
.drop_verification_provenance();
} }
let (server_transport, mut test_transport) = ChannelTransport::new(); let (server_transport, mut test_transport) = ChannelTransport::new();

View File

@@ -11,8 +11,6 @@ use arbiter_server::{
safe_cell::{SafeCell, SafeCellHandle as _}, safe_cell::{SafeCell, SafeCellHandle as _},
}; };
use chacha20poly1305::{AeadInPlace, XChaCha20Poly1305, XNonce, aead::KeyInit}; use chacha20poly1305::{AeadInPlace, XChaCha20Poly1305, XNonce, aead::KeyInit};
use diesel::{ExpressionMethods as _, QueryDsl as _, insert_into};
use diesel_async::RunQueryDsl;
use kameo::actor::Spawn as _; use kameo::actor::Spawn as _;
use x25519_dalek::{EphemeralSecret, PublicKey}; use x25519_dalek::{EphemeralSecret, PublicKey};
@@ -151,4 +149,4 @@ pub async fn test_unseal_retry_after_invalid_key() {
let response = user_agent.ask(encrypted_key).await; let response = user_agent.ask(encrypted_key).await;
assert!(matches!(response, Ok(()))); assert!(matches!(response, Ok(())));
} }
} }