Compare commits
45 Commits
PoC-terror
...
terrors-re
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
efb11d2271 | ||
| 2148faa376 | |||
|
|
eb37ee0a0c | ||
|
|
1f07fd6a98 | ||
|
|
e135519c06 | ||
|
|
f015d345f4 | ||
|
|
784261f4d8 | ||
|
|
971db0e919 | ||
|
|
e1a8553142 | ||
|
|
ec70561c93 | ||
|
|
3993d3a8cc | ||
|
|
c87456ae2f | ||
|
|
e89983de3a | ||
|
|
f56668d9f6 | ||
|
|
434738bae5 | ||
|
|
915540de32 | ||
|
|
5a5008080a | ||
|
|
3bc423f9b2 | ||
|
|
f2c33a5bf4 | ||
|
|
3e8b26418a | ||
|
|
60ce1cc110 | ||
|
|
2ff4d0961c | ||
|
|
d61dab3285 | ||
|
|
c439c9645d | ||
|
|
c2883704e6 | ||
| 47caec38a6 | |||
|
|
77c3babec7 | ||
|
|
6f03ce4d1d | ||
|
|
712f114763 | ||
|
|
c56184d30b | ||
|
|
9017ea4017 | ||
|
|
088fa6fe72 | ||
|
|
c90af9c196 | ||
|
|
a5a9bc73b0 | ||
|
|
6ed8150e48 | ||
|
|
fac312d860 | ||
|
|
549a0f5f52 | ||
|
|
4db102b3d1 | ||
|
|
c61a9e30ac | ||
|
|
27836beb75 | ||
|
|
ec0e8a980c | ||
|
|
16d5b9a233 | ||
|
|
62c4bc5ade | ||
|
|
ccd657c9ec | ||
|
|
013af7e65f |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -2,3 +2,4 @@ target/
|
||||
scripts/__pycache__/
|
||||
.DS_Store
|
||||
.cargo/config.toml
|
||||
.vscode/
|
||||
|
||||
2
.vscode/settings.json
vendored
2
.vscode/settings.json
vendored
@@ -1,2 +0,0 @@
|
||||
{
|
||||
}
|
||||
@@ -22,4 +22,4 @@ steps:
|
||||
- apt-get update && apt-get install -y pkg-config
|
||||
- mise install rust
|
||||
- mise install protoc
|
||||
- mise exec rust -- cargo clippy --all-targets --all-features -- -D warnings
|
||||
- mise exec rust -- cargo clippy --all -- -D warnings
|
||||
18
.woodpecker/useragent-analyze.yaml
Normal file
18
.woodpecker/useragent-analyze.yaml
Normal file
@@ -0,0 +1,18 @@
|
||||
when:
|
||||
- event: pull_request
|
||||
path:
|
||||
include: ['.woodpecker/useragent-*.yaml', 'useragent/**']
|
||||
- event: push
|
||||
branch: main
|
||||
path:
|
||||
include: ['.woodpecker/useragent-*.yaml', 'useragent/**']
|
||||
|
||||
steps:
|
||||
- name: analyze
|
||||
image: jdxcode/mise:latest
|
||||
commands:
|
||||
- mise install flutter
|
||||
- mise install protoc
|
||||
# Reruns codegen to catch protocol drift
|
||||
- mise codegen
|
||||
- cd useragent/ && flutter analyze
|
||||
128
AGENTS.md
Normal file
128
AGENTS.md
Normal file
@@ -0,0 +1,128 @@
|
||||
# AGENTS.md
|
||||
|
||||
This file provides guidance to Codex (Codex.ai/code) when working with code in this repository.
|
||||
|
||||
## Project Overview
|
||||
|
||||
Arbiter is a **permissioned signing service** for cryptocurrency wallets. It consists of:
|
||||
- **`server/`** — Rust gRPC daemon that holds encrypted keys and enforces policies
|
||||
- **`useragent/`** — Flutter desktop app (macOS/Windows) with a Rust backend via Rinf
|
||||
- **`protobufs/`** — Protocol Buffer definitions shared between server and client
|
||||
|
||||
The vault never exposes key material; it only produces signatures when requests satisfy configured policies.
|
||||
|
||||
## Toolchain Setup
|
||||
|
||||
Tools are managed via [mise](https://mise.jdx.dev/). Install all required tools:
|
||||
```sh
|
||||
mise install
|
||||
```
|
||||
|
||||
Key versions: Rust 1.93.0 (with clippy), Flutter 3.38.9-stable, protoc 29.6, diesel_cli 2.3.6 (sqlite).
|
||||
|
||||
## Server (Rust workspace at `server/`)
|
||||
|
||||
### Crates
|
||||
|
||||
| Crate | Purpose |
|
||||
|---|---|
|
||||
| `arbiter-proto` | Generated gRPC stubs + protobuf types; compiled from `protobufs/*.proto` via `tonic-prost-build` |
|
||||
| `arbiter-server` | Main daemon — actors, DB, EVM policy engine, gRPC service implementation |
|
||||
| `arbiter-useragent` | Rust client library for the user agent side of the gRPC protocol |
|
||||
| `arbiter-client` | Rust client library for SDK clients |
|
||||
|
||||
### Common Commands
|
||||
|
||||
```sh
|
||||
cd server
|
||||
|
||||
# Build
|
||||
cargo build
|
||||
|
||||
# Run the server daemon
|
||||
cargo run -p arbiter-server
|
||||
|
||||
# Run all tests (preferred over cargo test)
|
||||
cargo nextest run
|
||||
|
||||
# Run a single test
|
||||
cargo nextest run <test_name>
|
||||
|
||||
# Lint
|
||||
cargo clippy
|
||||
|
||||
# Security audit
|
||||
cargo audit
|
||||
|
||||
# Check unused dependencies
|
||||
cargo shear
|
||||
|
||||
# Run snapshot tests and update snapshots
|
||||
cargo insta review
|
||||
```
|
||||
|
||||
### Architecture
|
||||
|
||||
The server is actor-based using the **kameo** crate. All long-lived state lives in `GlobalActors`:
|
||||
|
||||
- **`Bootstrapper`** — Manages the one-time bootstrap token written to `~/.arbiter/bootstrap_token` on first run.
|
||||
- **`KeyHolder`** — Holds the encrypted root key and manages the Sealed/Unsealed vault state machine. On unseal, decrypts the root key into a `memsafe` hardened memory cell.
|
||||
- **`MessageRouter`** — Coordinates streaming messages between user agents and SDK clients.
|
||||
- **`EvmActor`** — Handles EVM transaction policy enforcement and signing.
|
||||
|
||||
Per-connection actors live under `actors/user_agent/` and `actors/client/`, each with `auth` (challenge-response authentication) and `session` (post-auth operations) sub-modules.
|
||||
|
||||
**Database:** SQLite via `diesel-async` + `bb8` connection pool. Schema managed by embedded Diesel migrations in `crates/arbiter-server/migrations/`. DB file lives at `~/.arbiter/arbiter.sqlite`. Tests use a temp-file DB via `db::create_test_pool()`.
|
||||
|
||||
**Cryptography:**
|
||||
- Authentication: ed25519 (challenge-response, nonce-tracked per peer)
|
||||
- Encryption at rest: XChaCha20-Poly1305 (versioned via `scheme` field for transparent migration on unseal)
|
||||
- Password KDF: Argon2
|
||||
- Unseal transport: X25519 ephemeral key exchange
|
||||
- TLS: self-signed certificate (aws-lc-rs backend), fingerprint distributed via `ArbiterUrl`
|
||||
|
||||
**Protocol:** gRPC with Protocol Buffers. The `ArbiterUrl` type encodes host, port, CA cert, and bootstrap token into a single shareable string (printed to console on first run).
|
||||
|
||||
### Proto Regeneration
|
||||
|
||||
When `.proto` files in `protobufs/` change, rebuild to regenerate:
|
||||
```sh
|
||||
cd server && cargo build -p arbiter-proto
|
||||
```
|
||||
|
||||
### Database Migrations
|
||||
|
||||
```sh
|
||||
# Create a new migration
|
||||
diesel migration generate <name> --migration-dir crates/arbiter-server/migrations
|
||||
|
||||
# Run migrations manually (server also runs them on startup)
|
||||
diesel migration run --migration-dir crates/arbiter-server/migrations
|
||||
```
|
||||
|
||||
## User Agent (Flutter + Rinf at `useragent/`)
|
||||
|
||||
The Flutter app uses [Rinf](https://rinf.cunarist.org) to call Rust code. The Rust logic lives in `useragent/native/hub/` as a separate crate that uses `arbiter-useragent` for the gRPC client.
|
||||
|
||||
Communication between Dart and Rust uses typed **signals** defined in `useragent/native/hub/src/signals/`. After modifying signal structs, regenerate Dart bindings:
|
||||
|
||||
```sh
|
||||
cd useragent && rinf gen
|
||||
```
|
||||
|
||||
### Common Commands
|
||||
|
||||
```sh
|
||||
cd useragent
|
||||
|
||||
# Run the app (macOS or Windows)
|
||||
flutter run
|
||||
|
||||
# Regenerate Rust↔Dart signal bindings
|
||||
rinf gen
|
||||
|
||||
# Analyze Dart code
|
||||
flutter analyze
|
||||
```
|
||||
|
||||
The Rinf Rust entry point is `useragent/native/hub/src/lib.rs`. It spawns actors defined in `useragent/native/hub/src/actors/` which handle Dart↔server communication via signals.
|
||||
128
CLAUDE.md
Normal file
128
CLAUDE.md
Normal file
@@ -0,0 +1,128 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Project Overview
|
||||
|
||||
Arbiter is a **permissioned signing service** for cryptocurrency wallets. It consists of:
|
||||
- **`server/`** — Rust gRPC daemon that holds encrypted keys and enforces policies
|
||||
- **`useragent/`** — Flutter desktop app (macOS/Windows) with a Rust backend via Rinf
|
||||
- **`protobufs/`** — Protocol Buffer definitions shared between server and client
|
||||
|
||||
The vault never exposes key material; it only produces signatures when requests satisfy configured policies.
|
||||
|
||||
## Toolchain Setup
|
||||
|
||||
Tools are managed via [mise](https://mise.jdx.dev/). Install all required tools:
|
||||
```sh
|
||||
mise install
|
||||
```
|
||||
|
||||
Key versions: Rust 1.93.0 (with clippy), Flutter 3.38.9-stable, protoc 29.6, diesel_cli 2.3.6 (sqlite).
|
||||
|
||||
## Server (Rust workspace at `server/`)
|
||||
|
||||
### Crates
|
||||
|
||||
| Crate | Purpose |
|
||||
|---|---|
|
||||
| `arbiter-proto` | Generated gRPC stubs + protobuf types; compiled from `protobufs/*.proto` via `tonic-prost-build` |
|
||||
| `arbiter-server` | Main daemon — actors, DB, EVM policy engine, gRPC service implementation |
|
||||
| `arbiter-useragent` | Rust client library for the user agent side of the gRPC protocol |
|
||||
| `arbiter-client` | Rust client library for SDK clients |
|
||||
|
||||
### Common Commands
|
||||
|
||||
```sh
|
||||
cd server
|
||||
|
||||
# Build
|
||||
cargo build
|
||||
|
||||
# Run the server daemon
|
||||
cargo run -p arbiter-server
|
||||
|
||||
# Run all tests (preferred over cargo test)
|
||||
cargo nextest run
|
||||
|
||||
# Run a single test
|
||||
cargo nextest run <test_name>
|
||||
|
||||
# Lint
|
||||
cargo clippy
|
||||
|
||||
# Security audit
|
||||
cargo audit
|
||||
|
||||
# Check unused dependencies
|
||||
cargo shear
|
||||
|
||||
# Run snapshot tests and update snapshots
|
||||
cargo insta review
|
||||
```
|
||||
|
||||
### Architecture
|
||||
|
||||
The server is actor-based using the **kameo** crate. All long-lived state lives in `GlobalActors`:
|
||||
|
||||
- **`Bootstrapper`** — Manages the one-time bootstrap token written to `~/.arbiter/bootstrap_token` on first run.
|
||||
- **`KeyHolder`** — Holds the encrypted root key and manages the Sealed/Unsealed vault state machine. On unseal, decrypts the root key into a `memsafe` hardened memory cell.
|
||||
- **`MessageRouter`** — Coordinates streaming messages between user agents and SDK clients.
|
||||
- **`EvmActor`** — Handles EVM transaction policy enforcement and signing.
|
||||
|
||||
Per-connection actors live under `actors/user_agent/` and `actors/client/`, each with `auth` (challenge-response authentication) and `session` (post-auth operations) sub-modules.
|
||||
|
||||
**Database:** SQLite via `diesel-async` + `bb8` connection pool. Schema managed by embedded Diesel migrations in `crates/arbiter-server/migrations/`. DB file lives at `~/.arbiter/arbiter.sqlite`. Tests use a temp-file DB via `db::create_test_pool()`.
|
||||
|
||||
**Cryptography:**
|
||||
- Authentication: ed25519 (challenge-response, nonce-tracked per peer)
|
||||
- Encryption at rest: XChaCha20-Poly1305 (versioned via `scheme` field for transparent migration on unseal)
|
||||
- Password KDF: Argon2
|
||||
- Unseal transport: X25519 ephemeral key exchange
|
||||
- TLS: self-signed certificate (aws-lc-rs backend), fingerprint distributed via `ArbiterUrl`
|
||||
|
||||
**Protocol:** gRPC with Protocol Buffers. The `ArbiterUrl` type encodes host, port, CA cert, and bootstrap token into a single shareable string (printed to console on first run).
|
||||
|
||||
### Proto Regeneration
|
||||
|
||||
When `.proto` files in `protobufs/` change, rebuild to regenerate:
|
||||
```sh
|
||||
cd server && cargo build -p arbiter-proto
|
||||
```
|
||||
|
||||
### Database Migrations
|
||||
|
||||
```sh
|
||||
# Create a new migration
|
||||
diesel migration generate <name> --migration-dir crates/arbiter-server/migrations
|
||||
|
||||
# Run migrations manually (server also runs them on startup)
|
||||
diesel migration run --migration-dir crates/arbiter-server/migrations
|
||||
```
|
||||
|
||||
## User Agent (Flutter + Rinf at `useragent/`)
|
||||
|
||||
The Flutter app uses [Rinf](https://rinf.cunarist.org) to call Rust code. The Rust logic lives in `useragent/native/hub/` as a separate crate that uses `arbiter-useragent` for the gRPC client.
|
||||
|
||||
Communication between Dart and Rust uses typed **signals** defined in `useragent/native/hub/src/signals/`. After modifying signal structs, regenerate Dart bindings:
|
||||
|
||||
```sh
|
||||
cd useragent && rinf gen
|
||||
```
|
||||
|
||||
### Common Commands
|
||||
|
||||
```sh
|
||||
cd useragent
|
||||
|
||||
# Run the app (macOS or Windows)
|
||||
flutter run
|
||||
|
||||
# Regenerate Rust↔Dart signal bindings
|
||||
rinf gen
|
||||
|
||||
# Analyze Dart code
|
||||
flutter analyze
|
||||
```
|
||||
|
||||
The Rinf Rust entry point is `useragent/native/hub/src/lib.rs`. It spawns actors defined in `useragent/native/hub/src/actors/` which handle Dart↔server communication via signals.
|
||||
@@ -6,6 +6,20 @@ This document covers concrete technology choices and dependencies. For the archi
|
||||
|
||||
## Client Connection Flow
|
||||
|
||||
### Authentication Result Semantics
|
||||
|
||||
Authentication no longer uses an implicit success-only response shape. Both `client` and `user-agent` return explicit auth status enums over the wire.
|
||||
|
||||
- **Client:** `AuthResult` may return `SUCCESS`, `INVALID_KEY`, `INVALID_SIGNATURE`, `APPROVAL_DENIED`, `NO_USER_AGENTS_ONLINE`, or `INTERNAL`
|
||||
- **User-agent:** `AuthResult` may return `SUCCESS`, `INVALID_KEY`, `INVALID_SIGNATURE`, `BOOTSTRAP_REQUIRED`, `TOKEN_INVALID`, or `INTERNAL`
|
||||
|
||||
This makes transport-level failures and actor/domain-level auth failures distinct:
|
||||
|
||||
- **Transport/protocol failures** are surfaced as stream/status errors
|
||||
- **Authentication failures** are surfaced as successful protocol responses carrying an explicit auth status
|
||||
|
||||
Clients are expected to handle these status codes directly and present the concrete failure reason to the user.
|
||||
|
||||
### New Client Approval
|
||||
|
||||
When a client whose public key is not yet in the database connects, all connected user agents are asked to approve the connection. The first agent to respond determines the outcome; remaining requests are cancelled via a watch channel.
|
||||
@@ -68,9 +82,21 @@ The `program_client.nonce` column stores the **next usable nonce** — i.e. it i
|
||||
## Communication
|
||||
|
||||
- **Protocol:** gRPC with Protocol Buffers
|
||||
- **Request/response matching:** multiplexed over a single bidirectional stream using per-connection request IDs
|
||||
- **Server identity distribution:** `ServerInfo` protobuf struct containing the TLS public key fingerprint
|
||||
- **Future consideration:** grpc-web lacks bidirectional stream support, so a browser-based wallet may require protojson over WebSocket
|
||||
|
||||
### Request Multiplexing
|
||||
|
||||
Both `client` and `user-agent` connections support multiple in-flight requests over one gRPC bidi stream.
|
||||
|
||||
- Every request carries a monotonically increasing request ID
|
||||
- Every normal response echoes the request ID it corresponds to
|
||||
- Out-of-band server messages omit the response ID entirely
|
||||
- The server rejects already-seen request IDs at the transport adapter boundary before business logic sees the message
|
||||
|
||||
This keeps request correlation entirely in transport/client connection code while leaving actor and domain handlers unaware of request IDs.
|
||||
|
||||
---
|
||||
|
||||
## EVM Policy Engine
|
||||
|
||||
84
mise.lock
84
mise.lock
@@ -1,7 +1,37 @@
|
||||
# @generated - this file is auto-generated by `mise lock` https://mise.jdx.dev/dev-tools/mise-lock.html
|
||||
|
||||
[[tools.ast-grep]]
|
||||
version = "0.42.0"
|
||||
backend = "aqua:ast-grep/ast-grep"
|
||||
|
||||
[tools.ast-grep."platforms.linux-arm64"]
|
||||
checksum = "sha256:5c830eae8456569e2f7212434ed9c238f58dca412d76045418ed6d394a755836"
|
||||
url = "https://github.com/ast-grep/ast-grep/releases/download/0.42.0/app-aarch64-unknown-linux-gnu.zip"
|
||||
|
||||
[tools.ast-grep."platforms.linux-x64"]
|
||||
checksum = "sha256:e825a05603f0bcc4cd9076c4cc8c9abd6d008b7cd07d9aa3cc323ba4b8606651"
|
||||
url = "https://github.com/ast-grep/ast-grep/releases/download/0.42.0/app-x86_64-unknown-linux-gnu.zip"
|
||||
|
||||
[tools.ast-grep."platforms.macos-arm64"]
|
||||
checksum = "sha256:fc300d5293b1c770a5aece03a8a193b92e71e87cec726c28096990691a582620"
|
||||
url = "https://github.com/ast-grep/ast-grep/releases/download/0.42.0/app-aarch64-apple-darwin.zip"
|
||||
|
||||
[tools.ast-grep."platforms.macos-x64"]
|
||||
checksum = "sha256:979ffe611327056f4730a1ae71b0209b3b830f58b22c6ed194cda34f55400db2"
|
||||
url = "https://github.com/ast-grep/ast-grep/releases/download/0.42.0/app-x86_64-apple-darwin.zip"
|
||||
|
||||
[tools.ast-grep."platforms.windows-x64"]
|
||||
checksum = "sha256:55836fa1b2c65dc7d61615a4d9368622a0d2371a76d28b9a165e5a3ab6ae32a4"
|
||||
url = "https://github.com/ast-grep/ast-grep/releases/download/0.42.0/app-x86_64-pc-windows-msvc.zip"
|
||||
|
||||
[[tools."cargo:cargo-audit"]]
|
||||
version = "0.22.1"
|
||||
backend = "cargo:cargo-audit"
|
||||
|
||||
[[tools."cargo:cargo-edit"]]
|
||||
version = "0.13.9"
|
||||
backend = "cargo:cargo-edit"
|
||||
|
||||
[[tools."cargo:cargo-features"]]
|
||||
version = "1.0.0"
|
||||
backend = "cargo:cargo-features"
|
||||
@@ -42,6 +72,10 @@ backend = "cargo:diesel_cli"
|
||||
default-features = "false"
|
||||
features = "sqlite,sqlite-bundled"
|
||||
|
||||
[[tools."cargo:rinf_cli"]]
|
||||
version = "8.9.1"
|
||||
backend = "cargo:rinf_cli"
|
||||
|
||||
[[tools.flutter]]
|
||||
version = "3.38.9-stable"
|
||||
backend = "asdf:flutter"
|
||||
@@ -49,20 +83,50 @@ backend = "asdf:flutter"
|
||||
[[tools.protoc]]
|
||||
version = "29.6"
|
||||
backend = "aqua:protocolbuffers/protobuf/protoc"
|
||||
"platforms.linux-arm64" = { checksum = "sha256:2594ff4fcae8cb57310d394d0961b236190ad9c5efbfdf1f597ea471d424fe79", url = "https://github.com/protocolbuffers/protobuf/releases/download/v29.6/protoc-29.6-linux-aarch_64.zip"}
|
||||
"platforms.linux-x64" = { checksum = "sha256:48785a926e73ffa3f68e2f22b14e7b849620c7a1d36809ac9249a5495e280323", url = "https://github.com/protocolbuffers/protobuf/releases/download/v29.6/protoc-29.6-linux-x86_64.zip"}
|
||||
"platforms.macos-arm64" = { checksum = "sha256:b9576b5fa1a1ef3fe13a8c91d9d8204b46545759bea5ae155cd6ba2ea4cdaeed", url = "https://github.com/protocolbuffers/protobuf/releases/download/v29.6/protoc-29.6-osx-aarch_64.zip"}
|
||||
"platforms.macos-x64" = { checksum = "sha256:312f04713946921cc0187ef34df80241ddca1bab6f564c636885fd2cc90d3f88", url = "https://github.com/protocolbuffers/protobuf/releases/download/v29.6/protoc-29.6-osx-x86_64.zip"}
|
||||
"platforms.windows-x64" = { checksum = "sha256:1ebd7c87baffb9f1c47169b640872bf5fb1e4408079c691af527be9561d8f6f7", url = "https://github.com/protocolbuffers/protobuf/releases/download/v29.6/protoc-29.6-win64.zip"}
|
||||
|
||||
[tools.protoc."platforms.linux-arm64"]
|
||||
checksum = "sha256:2594ff4fcae8cb57310d394d0961b236190ad9c5efbfdf1f597ea471d424fe79"
|
||||
url = "https://github.com/protocolbuffers/protobuf/releases/download/v29.6/protoc-29.6-linux-aarch_64.zip"
|
||||
|
||||
[tools.protoc."platforms.linux-x64"]
|
||||
checksum = "sha256:48785a926e73ffa3f68e2f22b14e7b849620c7a1d36809ac9249a5495e280323"
|
||||
url = "https://github.com/protocolbuffers/protobuf/releases/download/v29.6/protoc-29.6-linux-x86_64.zip"
|
||||
|
||||
[tools.protoc."platforms.macos-arm64"]
|
||||
checksum = "sha256:b9576b5fa1a1ef3fe13a8c91d9d8204b46545759bea5ae155cd6ba2ea4cdaeed"
|
||||
url = "https://github.com/protocolbuffers/protobuf/releases/download/v29.6/protoc-29.6-osx-aarch_64.zip"
|
||||
|
||||
[tools.protoc."platforms.macos-x64"]
|
||||
checksum = "sha256:312f04713946921cc0187ef34df80241ddca1bab6f564c636885fd2cc90d3f88"
|
||||
url = "https://github.com/protocolbuffers/protobuf/releases/download/v29.6/protoc-29.6-osx-x86_64.zip"
|
||||
|
||||
[tools.protoc."platforms.windows-x64"]
|
||||
checksum = "sha256:1ebd7c87baffb9f1c47169b640872bf5fb1e4408079c691af527be9561d8f6f7"
|
||||
url = "https://github.com/protocolbuffers/protobuf/releases/download/v29.6/protoc-29.6-win64.zip"
|
||||
|
||||
[[tools.python]]
|
||||
version = "3.14.3"
|
||||
backend = "core:python"
|
||||
"platforms.linux-arm64" = { checksum = "sha256:be0f4dc2932f762292b27d46ea7d3e8e66ddf3969a5eb0254a229015ed402625", url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260303/cpython-3.14.3+20260303-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz"}
|
||||
"platforms.linux-x64" = { checksum = "sha256:0a73413f89efd417871876c9accaab28a9d1e3cd6358fbfff171a38ec99302f0", url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260303/cpython-3.14.3+20260303-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz"}
|
||||
"platforms.macos-arm64" = { checksum = "sha256:4703cdf18b26798fde7b49b6b66149674c25f97127be6a10dbcf29309bdcdcdb", url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260303/cpython-3.14.3+20260303-aarch64-apple-darwin-install_only_stripped.tar.gz"}
|
||||
"platforms.macos-x64" = { checksum = "sha256:76f1cc26e3d262eae8ca546a93e8bded10cf0323613f7e246fea2e10a8115eb7", url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260303/cpython-3.14.3+20260303-x86_64-apple-darwin-install_only_stripped.tar.gz"}
|
||||
"platforms.windows-x64" = { checksum = "sha256:950c5f21a015c1bdd1337f233456df2470fab71e4d794407d27a84cb8b9909a0", url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260303/cpython-3.14.3+20260303-x86_64-pc-windows-msvc-install_only_stripped.tar.gz"}
|
||||
|
||||
[tools.python."platforms.linux-arm64"]
|
||||
checksum = "sha256:be0f4dc2932f762292b27d46ea7d3e8e66ddf3969a5eb0254a229015ed402625"
|
||||
url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260303/cpython-3.14.3+20260303-aarch64-unknown-linux-gnu-install_only_stripped.tar.gz"
|
||||
|
||||
[tools.python."platforms.linux-x64"]
|
||||
checksum = "sha256:0a73413f89efd417871876c9accaab28a9d1e3cd6358fbfff171a38ec99302f0"
|
||||
url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260303/cpython-3.14.3+20260303-x86_64-unknown-linux-gnu-install_only_stripped.tar.gz"
|
||||
|
||||
[tools.python."platforms.macos-arm64"]
|
||||
checksum = "sha256:4703cdf18b26798fde7b49b6b66149674c25f97127be6a10dbcf29309bdcdcdb"
|
||||
url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260303/cpython-3.14.3+20260303-aarch64-apple-darwin-install_only_stripped.tar.gz"
|
||||
|
||||
[tools.python."platforms.macos-x64"]
|
||||
checksum = "sha256:76f1cc26e3d262eae8ca546a93e8bded10cf0323613f7e246fea2e10a8115eb7"
|
||||
url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260303/cpython-3.14.3+20260303-x86_64-apple-darwin-install_only_stripped.tar.gz"
|
||||
|
||||
[tools.python."platforms.windows-x64"]
|
||||
checksum = "sha256:950c5f21a015c1bdd1337f233456df2470fab71e4d794407d27a84cb8b9909a0"
|
||||
url = "https://github.com/astral-sh/python-build-standalone/releases/download/20260303/cpython-3.14.3+20260303-x86_64-pc-windows-msvc-install_only_stripped.tar.gz"
|
||||
|
||||
[[tools.rust]]
|
||||
version = "1.93.0"
|
||||
|
||||
10
mise.toml
10
mise.toml
@@ -10,3 +10,13 @@ protoc = "29.6"
|
||||
"cargo:cargo-shear" = "latest"
|
||||
"cargo:cargo-insta" = "1.46.3"
|
||||
python = "3.14.3"
|
||||
ast-grep = "0.42.0"
|
||||
"cargo:cargo-edit" = "0.13.9"
|
||||
|
||||
[tasks.codegen]
|
||||
sources = ['protobufs/*.proto']
|
||||
outputs = ['useragent/lib/proto/*']
|
||||
run = '''
|
||||
dart pub global activate protoc_plugin && \
|
||||
protoc --dart_out=grpc:useragent/lib/proto --proto_path=protobufs/ protobufs/*.proto
|
||||
'''
|
||||
|
||||
@@ -3,6 +3,7 @@ syntax = "proto3";
|
||||
package arbiter.client;
|
||||
|
||||
import "evm.proto";
|
||||
import "google/protobuf/empty.proto";
|
||||
|
||||
message AuthChallengeRequest {
|
||||
bytes pubkey = 1;
|
||||
@@ -17,31 +18,40 @@ message AuthChallengeSolution {
|
||||
bytes signature = 1;
|
||||
}
|
||||
|
||||
message AuthOk {}
|
||||
enum AuthResult {
|
||||
AUTH_RESULT_UNSPECIFIED = 0;
|
||||
AUTH_RESULT_SUCCESS = 1;
|
||||
AUTH_RESULT_INVALID_KEY = 2;
|
||||
AUTH_RESULT_INVALID_SIGNATURE = 3;
|
||||
AUTH_RESULT_APPROVAL_DENIED = 4;
|
||||
AUTH_RESULT_NO_USER_AGENTS_ONLINE = 5;
|
||||
AUTH_RESULT_INTERNAL = 6;
|
||||
}
|
||||
|
||||
enum VaultState {
|
||||
VAULT_STATE_UNSPECIFIED = 0;
|
||||
VAULT_STATE_UNBOOTSTRAPPED = 1;
|
||||
VAULT_STATE_SEALED = 2;
|
||||
VAULT_STATE_UNSEALED = 3;
|
||||
VAULT_STATE_ERROR = 4;
|
||||
}
|
||||
|
||||
message ClientRequest {
|
||||
int32 request_id = 4;
|
||||
oneof payload {
|
||||
AuthChallengeRequest auth_challenge_request = 1;
|
||||
AuthChallengeSolution auth_challenge_solution = 2;
|
||||
arbiter.evm.EvmSignTransactionRequest evm_sign_transaction = 3;
|
||||
google.protobuf.Empty query_vault_state = 3;
|
||||
}
|
||||
}
|
||||
|
||||
message ClientConnectError {
|
||||
enum Code {
|
||||
UNKNOWN = 0;
|
||||
APPROVAL_DENIED = 1;
|
||||
NO_USER_AGENTS_ONLINE = 2;
|
||||
}
|
||||
Code code = 1;
|
||||
}
|
||||
|
||||
message ClientResponse {
|
||||
optional int32 request_id = 7;
|
||||
oneof payload {
|
||||
AuthChallenge auth_challenge = 1;
|
||||
AuthOk auth_ok = 2;
|
||||
ClientConnectError client_connect_error = 5;
|
||||
AuthResult auth_result = 2;
|
||||
arbiter.evm.EvmSignTransactionResponse evm_sign_transaction = 3;
|
||||
arbiter.evm.EvmAnalyzeTransactionResponse evm_analyze_transaction = 4;
|
||||
VaultState vault_state = 6;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,8 @@ syntax = "proto3";
|
||||
|
||||
package arbiter.user_agent;
|
||||
|
||||
import "google/protobuf/empty.proto";
|
||||
import "evm.proto";
|
||||
import "google/protobuf/empty.proto";
|
||||
|
||||
enum KeyType {
|
||||
KEY_TYPE_UNSPECIFIED = 0;
|
||||
@@ -68,15 +68,23 @@ message AuthChallengeRequest {
|
||||
}
|
||||
|
||||
message AuthChallenge {
|
||||
bytes pubkey = 1;
|
||||
int32 nonce = 2;
|
||||
reserved 1;
|
||||
}
|
||||
|
||||
message AuthChallengeSolution {
|
||||
bytes signature = 1;
|
||||
}
|
||||
|
||||
message AuthOk {}
|
||||
enum AuthResult {
|
||||
AUTH_RESULT_UNSPECIFIED = 0;
|
||||
AUTH_RESULT_SUCCESS = 1;
|
||||
AUTH_RESULT_INVALID_KEY = 2;
|
||||
AUTH_RESULT_INVALID_SIGNATURE = 3;
|
||||
AUTH_RESULT_BOOTSTRAP_REQUIRED = 4;
|
||||
AUTH_RESULT_TOKEN_INVALID = 5;
|
||||
AUTH_RESULT_INTERNAL = 6;
|
||||
}
|
||||
|
||||
message UnsealStart {
|
||||
bytes client_pubkey = 1;
|
||||
@@ -91,6 +99,12 @@ message UnsealEncryptedKey {
|
||||
bytes associated_data = 3;
|
||||
}
|
||||
|
||||
message BootstrapEncryptedKey {
|
||||
bytes nonce = 1;
|
||||
bytes ciphertext = 2;
|
||||
bytes associated_data = 3;
|
||||
}
|
||||
|
||||
enum UnsealResult {
|
||||
UNSEAL_RESULT_UNSPECIFIED = 0;
|
||||
UNSEAL_RESULT_SUCCESS = 1;
|
||||
@@ -98,6 +112,13 @@ enum UnsealResult {
|
||||
UNSEAL_RESULT_UNBOOTSTRAPPED = 3;
|
||||
}
|
||||
|
||||
enum BootstrapResult {
|
||||
BOOTSTRAP_RESULT_UNSPECIFIED = 0;
|
||||
BOOTSTRAP_RESULT_SUCCESS = 1;
|
||||
BOOTSTRAP_RESULT_ALREADY_BOOTSTRAPPED = 2;
|
||||
BOOTSTRAP_RESULT_INVALID_KEY = 3;
|
||||
}
|
||||
|
||||
enum VaultState {
|
||||
VAULT_STATE_UNSPECIFIED = 0;
|
||||
VAULT_STATE_UNBOOTSTRAPPED = 1;
|
||||
@@ -106,7 +127,18 @@ enum VaultState {
|
||||
VAULT_STATE_ERROR = 4;
|
||||
}
|
||||
|
||||
message SdkClientConnectionRequest {
|
||||
bytes pubkey = 1;
|
||||
}
|
||||
|
||||
message SdkClientConnectionResponse {
|
||||
bool approved = 1;
|
||||
}
|
||||
|
||||
message SdkClientConnectionCancel {}
|
||||
|
||||
message UserAgentRequest {
|
||||
int32 id = 16;
|
||||
oneof payload {
|
||||
AuthChallengeRequest auth_challenge_request = 1;
|
||||
AuthChallengeSolution auth_challenge_solution = 2;
|
||||
@@ -118,16 +150,18 @@ message UserAgentRequest {
|
||||
arbiter.evm.EvmGrantCreateRequest evm_grant_create = 8;
|
||||
arbiter.evm.EvmGrantDeleteRequest evm_grant_delete = 9;
|
||||
arbiter.evm.EvmGrantListRequest evm_grant_list = 10;
|
||||
// field 11 reserved: was client_connection_response (online approval removed)
|
||||
SdkClientConnectionResponse sdk_client_connection_response = 11;
|
||||
SdkClientApproveRequest sdk_client_approve = 12;
|
||||
SdkClientRevokeRequest sdk_client_revoke = 13;
|
||||
google.protobuf.Empty sdk_client_list = 14;
|
||||
BootstrapEncryptedKey bootstrap_encrypted_key = 15;
|
||||
}
|
||||
}
|
||||
message UserAgentResponse {
|
||||
optional int32 id = 16;
|
||||
oneof payload {
|
||||
AuthChallenge auth_challenge = 1;
|
||||
AuthOk auth_ok = 2;
|
||||
AuthResult auth_result = 2;
|
||||
UnsealStartResponse unseal_start_response = 3;
|
||||
UnsealResult unseal_result = 4;
|
||||
VaultState vault_state = 5;
|
||||
@@ -136,9 +170,10 @@ message UserAgentResponse {
|
||||
arbiter.evm.EvmGrantCreateResponse evm_grant_create = 8;
|
||||
arbiter.evm.EvmGrantDeleteResponse evm_grant_delete = 9;
|
||||
arbiter.evm.EvmGrantListResponse evm_grant_list = 10;
|
||||
// fields 11, 12 reserved: were client_connection_request, client_connection_cancel (online approval removed)
|
||||
SdkClientApproveResponse sdk_client_approve = 13;
|
||||
SdkClientRevokeResponse sdk_client_revoke = 14;
|
||||
SdkClientListResponse sdk_client_list = 15;
|
||||
SdkClientConnectionResponse sdk_client_connection_response = 11;
|
||||
SdkClientApproveResponse sdk_client_approve_response = 12;
|
||||
SdkClientRevokeResponse sdk_client_revoke_response = 13;
|
||||
SdkClientListResponse sdk_client_list_response = 14;
|
||||
BootstrapResult bootstrap_result = 15;
|
||||
}
|
||||
}
|
||||
|
||||
308
server/Cargo.lock
generated
308
server/Cargo.lock
generated
@@ -67,13 +67,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "alloy-chains"
|
||||
version = "0.2.31"
|
||||
version = "0.2.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6d9d22005bf31b018f31ef9ecadb5d2c39cf4f6acc8db0456f72c815f3d7f757"
|
||||
checksum = "9247f0a399ef71aeb68f497b2b8fb348014f742b50d3b83b1e00dfe1b7d64b3d"
|
||||
dependencies = [
|
||||
"alloy-primitives",
|
||||
"num_enum",
|
||||
"strum",
|
||||
"strum 0.27.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -100,7 +100,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_with",
|
||||
"thiserror",
|
||||
"thiserror 2.0.18",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -136,7 +136,7 @@ dependencies = [
|
||||
"futures",
|
||||
"futures-util",
|
||||
"serde_json",
|
||||
"thiserror",
|
||||
"thiserror 2.0.18",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -165,7 +165,7 @@ dependencies = [
|
||||
"itoa",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"winnow",
|
||||
"winnow 0.7.15",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -178,7 +178,7 @@ dependencies = [
|
||||
"alloy-rlp",
|
||||
"crc",
|
||||
"serde",
|
||||
"thiserror",
|
||||
"thiserror 2.0.18",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -203,7 +203,7 @@ dependencies = [
|
||||
"alloy-rlp",
|
||||
"borsh",
|
||||
"serde",
|
||||
"thiserror",
|
||||
"thiserror 2.0.18",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -239,7 +239,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_with",
|
||||
"sha2 0.10.9",
|
||||
"thiserror",
|
||||
"thiserror 2.0.18",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -280,7 +280,7 @@ dependencies = [
|
||||
"http",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror",
|
||||
"thiserror 2.0.18",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
@@ -307,7 +307,7 @@ dependencies = [
|
||||
"futures-utils-wasm",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror",
|
||||
"thiserror 2.0.18",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -382,7 +382,7 @@ dependencies = [
|
||||
"reqwest",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"url",
|
||||
@@ -471,11 +471,11 @@ dependencies = [
|
||||
"alloy-rlp",
|
||||
"alloy-serde",
|
||||
"alloy-sol-types",
|
||||
"itertools 0.14.0",
|
||||
"itertools 0.13.0",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_with",
|
||||
"thiserror",
|
||||
"thiserror 2.0.18",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -501,7 +501,7 @@ dependencies = [
|
||||
"either",
|
||||
"elliptic-curve",
|
||||
"k256",
|
||||
"thiserror",
|
||||
"thiserror 2.0.18",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -517,7 +517,7 @@ dependencies = [
|
||||
"async-trait",
|
||||
"k256",
|
||||
"rand 0.8.5",
|
||||
"thiserror",
|
||||
"thiserror 2.0.18",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -578,7 +578,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6df77fea9d6a2a75c0ef8d2acbdfd92286cc599983d3175ccdc170d3433d249"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"winnow",
|
||||
"winnow 0.7.15",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -608,7 +608,7 @@ dependencies = [
|
||||
"parking_lot",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tower",
|
||||
"tracing",
|
||||
@@ -624,7 +624,7 @@ checksum = "aa501ad58dd20acddbfebc65b52e60f05ebf97c52fa40d1b35e91f5e2da0ad0e"
|
||||
dependencies = [
|
||||
"alloy-json-rpc",
|
||||
"alloy-transport",
|
||||
"itertools 0.14.0",
|
||||
"itertools 0.13.0",
|
||||
"reqwest",
|
||||
"serde_json",
|
||||
"tower",
|
||||
@@ -644,7 +644,7 @@ dependencies = [
|
||||
"nybbles",
|
||||
"serde",
|
||||
"smallvec",
|
||||
"thiserror",
|
||||
"thiserror 2.0.18",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
@@ -684,8 +684,10 @@ dependencies = [
|
||||
"async-trait",
|
||||
"ed25519-dalek",
|
||||
"http",
|
||||
"rand 0.10.0",
|
||||
"rustls-webpki",
|
||||
"thiserror",
|
||||
"terrors",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
"tonic",
|
||||
@@ -708,8 +710,9 @@ dependencies = [
|
||||
"rcgen",
|
||||
"rstest",
|
||||
"rustls-pki-types",
|
||||
"thiserror",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
"tonic",
|
||||
"tonic-prost",
|
||||
"tonic-prost-build",
|
||||
@@ -733,6 +736,7 @@ dependencies = [
|
||||
"diesel-async",
|
||||
"diesel_migrations",
|
||||
"ed25519-dalek",
|
||||
"fatality",
|
||||
"futures",
|
||||
"insta",
|
||||
"k256",
|
||||
@@ -740,6 +744,7 @@ dependencies = [
|
||||
"memsafe",
|
||||
"miette",
|
||||
"pem",
|
||||
"prost-types",
|
||||
"rand 0.10.0",
|
||||
"rcgen",
|
||||
"restructed",
|
||||
@@ -749,9 +754,9 @@ dependencies = [
|
||||
"sha2 0.10.9",
|
||||
"smlang",
|
||||
"spki",
|
||||
"strum",
|
||||
"strum 0.28.0",
|
||||
"test-log",
|
||||
"thiserror",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
"tonic",
|
||||
@@ -761,13 +766,6 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arbiter-terrors-poc"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"terrors",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arbiter-tokens-registry"
|
||||
version = "0.1.0"
|
||||
@@ -775,30 +773,6 @@ dependencies = [
|
||||
"alloy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arbiter-useragent"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"arbiter-proto",
|
||||
"async-trait",
|
||||
"ed25519-dalek",
|
||||
"http",
|
||||
"k256",
|
||||
"kameo",
|
||||
"rand 0.10.0",
|
||||
"rsa",
|
||||
"rustls-webpki",
|
||||
"sha2 0.10.9",
|
||||
"smlang",
|
||||
"spki",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
"tonic",
|
||||
"tracing",
|
||||
"x25519-dalek",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "argon2"
|
||||
version = "0.5.3"
|
||||
@@ -1019,7 +993,7 @@ dependencies = [
|
||||
"nom",
|
||||
"num-traits",
|
||||
"rusticata-macros",
|
||||
"thiserror",
|
||||
"thiserror 2.0.18",
|
||||
"time",
|
||||
]
|
||||
|
||||
@@ -1104,9 +1078,9 @@ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
|
||||
|
||||
[[package]]
|
||||
name = "aws-lc-rs"
|
||||
version = "1.16.1"
|
||||
version = "1.16.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94bffc006df10ac2a68c83692d734a465f8ee6c5b384d8545a636f81d858f4bf"
|
||||
checksum = "a054912289d18629dc78375ba2c3726a3afe3ff71b4edba9dedfca0e3446d1fc"
|
||||
dependencies = [
|
||||
"aws-lc-sys",
|
||||
"untrusted 0.7.1",
|
||||
@@ -1115,9 +1089,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "aws-lc-sys"
|
||||
version = "0.38.0"
|
||||
version = "0.39.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4321e568ed89bb5a7d291a7f37997c2c0df89809d7b6d12062c81ddb54aa782e"
|
||||
checksum = "1fa7e52a4c5c547c741610a2c6f123f3881e409b714cd27e6798ef020c514f0a"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cmake",
|
||||
@@ -1312,19 +1286,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "borsh"
|
||||
version = "1.6.0"
|
||||
version = "1.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d1da5ab77c1437701eeff7c88d968729e7766172279eab0676857b3d63af7a6f"
|
||||
checksum = "cfd1e3f8955a5d7de9fab72fc8373fade9fb8a703968cb200ae3dc6cf08e185a"
|
||||
dependencies = [
|
||||
"borsh-derive",
|
||||
"bytes",
|
||||
"cfg_aliases",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "borsh-derive"
|
||||
version = "1.6.0"
|
||||
version = "1.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0686c856aa6aac0c4498f936d7d6a02df690f614c03e4d906d1018062b5c5e2c"
|
||||
checksum = "bfcfdc083699101d5a7965e49925975f2f55060f94f9a05e7187be95d530ca59"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"proc-macro-crate",
|
||||
@@ -1838,15 +1813,16 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "diesel-async"
|
||||
version = "0.7.4"
|
||||
version = "0.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13096fb8dae53f2d411c4b523bec85f45552ed3044a2ab4d85fb2092d9cb4f34"
|
||||
checksum = "b95864e58597509106f1fddfe0600de7e589e1fddddd87f54eee0a49fd111bbc"
|
||||
dependencies = [
|
||||
"bb8",
|
||||
"diesel",
|
||||
"diesel_migrations",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"pin-project-lite",
|
||||
"scoped-futures",
|
||||
"tokio",
|
||||
]
|
||||
@@ -2076,7 +2052,22 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "expander"
|
||||
version = "2.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e2c470c71d91ecbd179935b24170459e926382eaaa86b590b78814e180d8a8e2"
|
||||
dependencies = [
|
||||
"blake2",
|
||||
"file-guard",
|
||||
"fs-err",
|
||||
"prettyplease",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2107,6 +2098,30 @@ dependencies = [
|
||||
"bytes",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fatality"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec6f82451ff7f0568c6181287189126d492b5654e30a788add08027b6363d019"
|
||||
dependencies = [
|
||||
"fatality-proc-macro",
|
||||
"thiserror 1.0.69",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fatality-proc-macro"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eb42427514b063d97ce21d5199f36c0c307d981434a6be32582bc79fe5bd2303"
|
||||
dependencies = [
|
||||
"expander",
|
||||
"indexmap 2.13.0",
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ff"
|
||||
version = "0.13.1"
|
||||
@@ -2129,6 +2144,16 @@ version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"
|
||||
|
||||
[[package]]
|
||||
name = "file-guard"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "21ef72acf95ec3d7dbf61275be556299490a245f017cf084bd23b4f68cf9407c"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.9"
|
||||
@@ -2190,6 +2215,15 @@ dependencies = [
|
||||
"percent-encoding",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fs-err"
|
||||
version = "2.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "88a41f105fe1d5b6b34b2055e3dc59bb79b46b48b2040b9e6c7b4b5de097aa41"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fs_extra"
|
||||
version = "1.3.0"
|
||||
@@ -2838,20 +2872,11 @@ dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.14.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
|
||||
dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.17"
|
||||
version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "jobserver"
|
||||
@@ -3162,7 +3187,7 @@ version = "0.50.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3239,9 +3264,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "num_enum"
|
||||
version = "0.7.5"
|
||||
version = "0.7.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b1207a7e20ad57b847bbddc6776b968420d38292bbfe2089accff5e19e82454c"
|
||||
checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26"
|
||||
dependencies = [
|
||||
"num_enum_derive",
|
||||
"rustversion",
|
||||
@@ -3249,9 +3274,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "num_enum_derive"
|
||||
version = "0.7.5"
|
||||
version = "0.7.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff32365de1b6743cb203b710788263c44a03de03802daf96092f2da4fe6ba4d7"
|
||||
checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@@ -3643,7 +3668,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "343d3bd7056eda839b03204e68deff7d1b13aba7af2b2fd16890697274262ee7"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"itertools 0.14.0",
|
||||
"itertools 0.13.0",
|
||||
"log",
|
||||
"multimap",
|
||||
"petgraph",
|
||||
@@ -3664,7 +3689,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "27c6023962132f4b30eb4c172c91ce92d933da334c59c23cddee82358ddafb0b"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"itertools 0.14.0",
|
||||
"itertools 0.13.0",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
@@ -3746,9 +3771,9 @@ checksum = "95067976aca6421a523e491fce939a3e65249bac4b977adee0ee9771568e8aa3"
|
||||
|
||||
[[package]]
|
||||
name = "pulldown-cmark"
|
||||
version = "0.13.1"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "83c41efbf8f90ac44de7f3a868f0867851d261b56291732d0cbf7cceaaeb55a6"
|
||||
checksum = "14104c5a24d9bcf7eb2c24753e0f49fe14555d8bd565ea3d38e4b4303267259d"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"memchr",
|
||||
@@ -3784,7 +3809,7 @@ dependencies = [
|
||||
"rustc-hash",
|
||||
"rustls",
|
||||
"socket2",
|
||||
"thiserror",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"web-time",
|
||||
@@ -3805,7 +3830,7 @@ dependencies = [
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"slab",
|
||||
"thiserror",
|
||||
"thiserror 2.0.18",
|
||||
"tinyvec",
|
||||
"tracing",
|
||||
"web-time",
|
||||
@@ -4140,7 +4165,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a8a1f2315036ef6b1fbacd1972e8ee7688030b0a2121edfc2a6550febd41574d"
|
||||
dependencies = [
|
||||
"hashbrown 0.16.1",
|
||||
"thiserror",
|
||||
"thiserror 2.0.18",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4261,7 +4286,7 @@ dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
"linux-raw-sys",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4292,9 +4317,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.103.9"
|
||||
version = "0.103.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53"
|
||||
checksum = "df33b2b81ac578cabaf06b89b0631153a3f416b0a886e8a7a1707fb51abbd1ef"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"ring",
|
||||
@@ -4677,7 +4702,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4738,7 +4763,16 @@ version = "0.27.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf"
|
||||
dependencies = [
|
||||
"strum_macros",
|
||||
"strum_macros 0.27.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strum"
|
||||
version = "0.28.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd"
|
||||
dependencies = [
|
||||
"strum_macros 0.28.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4753,6 +4787,18 @@ dependencies = [
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strum_macros"
|
||||
version = "0.28.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
@@ -4850,7 +4896,7 @@ dependencies = [
|
||||
"getrandom 0.4.2",
|
||||
"once_cell",
|
||||
"rustix",
|
||||
"windows-sys 0.61.2",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4865,9 +4911,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "terrors"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "987fd8c678ca950df2a18b2c6e9da6ca511d449278fab3565efe0d49c0c07a5d"
|
||||
version = "0.5.1"
|
||||
source = "git+https://github.com/CleverWild/terrors#a0867fd9ca3fbb44c32e92113a917f1577b5716a"
|
||||
|
||||
[[package]]
|
||||
name = "test-log"
|
||||
@@ -4900,13 +4945,33 @@ dependencies = [
|
||||
"unicode-width 0.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "1.0.69"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
|
||||
dependencies = [
|
||||
"thiserror-impl 1.0.69",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "2.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
"thiserror-impl 2.0.18",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "1.0.69"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.117",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -4981,9 +5046,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tinyvec"
|
||||
version = "1.10.0"
|
||||
version = "1.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa"
|
||||
checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"
|
||||
dependencies = [
|
||||
"tinyvec_macros",
|
||||
]
|
||||
@@ -5068,7 +5133,7 @@ dependencies = [
|
||||
"serde_spanned",
|
||||
"toml_datetime 0.7.5+spec-1.1.0",
|
||||
"toml_parser",
|
||||
"winnow",
|
||||
"winnow 0.7.15",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5082,32 +5147,32 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "1.0.0+spec-1.1.0"
|
||||
version = "1.0.1+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32c2555c699578a4f59f0cc68e5116c8d7cabbd45e1409b989d4be085b53f13e"
|
||||
checksum = "9b320e741db58cac564e26c607d3cc1fdc4a88fd36c879568c07856ed83ff3e9"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_edit"
|
||||
version = "0.25.4+spec-1.1.0"
|
||||
version = "0.25.5+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7193cbd0ce53dc966037f54351dbbcf0d5a642c7f0038c382ef9e677ce8c13f2"
|
||||
checksum = "8ca1a40644a28bce036923f6a431df0b34236949d111cc07cb6dca830c9ef2e1"
|
||||
dependencies = [
|
||||
"indexmap 2.13.0",
|
||||
"toml_datetime 1.0.0+spec-1.1.0",
|
||||
"toml_datetime 1.0.1+spec-1.1.0",
|
||||
"toml_parser",
|
||||
"winnow",
|
||||
"winnow 1.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_parser"
|
||||
version = "1.0.9+spec-1.1.0"
|
||||
version = "1.0.10+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "702d4415e08923e7e1ef96cd5727c0dfed80b4d2fa25db9647fe5eb6f7c5a4c4"
|
||||
checksum = "7df25b4befd31c4816df190124375d5a20c6b6921e2cad937316de3fccd63420"
|
||||
dependencies = [
|
||||
"winnow",
|
||||
"winnow 1.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5871,6 +5936,15 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winnow"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a90e88e4667264a994d34e6d1ab2d26d398dcdca8b7f52bec8668957517fc7d8"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.51.0"
|
||||
@@ -6000,7 +6074,7 @@ dependencies = [
|
||||
"nom",
|
||||
"oid-registry",
|
||||
"rusticata-macros",
|
||||
"thiserror",
|
||||
"thiserror 2.0.18",
|
||||
"time",
|
||||
]
|
||||
|
||||
@@ -6038,18 +6112,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.42"
|
||||
version = "0.8.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2578b716f8a7a858b7f02d5bd870c14bf4ddbbcf3a4c05414ba6503640505e3"
|
||||
checksum = "efbb2a062be311f2ba113ce66f697a4dc589f85e78a4aea276200804cea0ed87"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.42"
|
||||
version = "0.8.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7e6cc098ea4d3bd6246687de65af3f920c430e236bee1e3bf2e441463f08a02f"
|
||||
checksum = "0e8bc7269b54418e7aeeef514aa68f8690b8c0489a06b0136e5f57c4c5ccab89"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
[workspace]
|
||||
members = [
|
||||
"crates/*",
|
||||
]
|
||||
members = ["crates/*"]
|
||||
resolver = "3"
|
||||
|
||||
[workspace.lints.clippy]
|
||||
@@ -9,23 +7,23 @@ disallowed-methods = "deny"
|
||||
|
||||
|
||||
[workspace.dependencies]
|
||||
tonic = { version = "0.14.3", features = [
|
||||
tonic = { version = "0.14.5", features = [
|
||||
"deflate",
|
||||
"gzip",
|
||||
"tls-connect-info",
|
||||
"zstd",
|
||||
] }
|
||||
tracing = "0.1.44"
|
||||
tokio = { version = "1.49.0", features = ["full"] }
|
||||
tokio = { version = "1.50.0", features = ["full"] }
|
||||
ed25519-dalek = { version = "3.0.0-pre.6", features = ["rand_core"] }
|
||||
chrono = { version = "0.4.43", features = ["serde"] }
|
||||
chrono = { version = "0.4.44", features = ["serde"] }
|
||||
rand = "0.10.0"
|
||||
rustls = "0.23.36"
|
||||
rustls = { version = "0.23.37", features = ["aws-lc-rs"] }
|
||||
smlang = "0.8.0"
|
||||
miette = { version = "7.6.0", features = ["fancy", "serde"] }
|
||||
thiserror = "2.0.18"
|
||||
async-trait = "0.1.89"
|
||||
futures = "0.3.31"
|
||||
futures = "0.3.32"
|
||||
tokio-stream = { version = "0.1.18", features = ["full"] }
|
||||
kameo = "0.19.2"
|
||||
prost-types = { version = "0.14.3", features = ["chrono"] }
|
||||
@@ -43,3 +41,4 @@ k256 = { version = "0.13.4", features = ["ecdsa", "pkcs8"] }
|
||||
rsa = { version = "0.9", features = ["sha2"] }
|
||||
sha2 = "0.10"
|
||||
spki = "0.7"
|
||||
terrors = { version = "0.5", git = "https://github.com/CleverWild/terrors" }
|
||||
|
||||
@@ -8,9 +8,12 @@ license = "Apache-2.0"
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
evm = ["dep:alloy"]
|
||||
|
||||
[dependencies]
|
||||
arbiter-proto.path = "../arbiter-proto"
|
||||
alloy.workspace = true
|
||||
alloy = { workspace = true, optional = true }
|
||||
tonic.workspace = true
|
||||
tonic.features = ["tls-aws-lc"]
|
||||
tokio.workspace = true
|
||||
@@ -18,5 +21,7 @@ tokio-stream.workspace = true
|
||||
ed25519-dalek.workspace = true
|
||||
thiserror.workspace = true
|
||||
http = "1.4.0"
|
||||
rustls-webpki = { version = "0.103.9", features = ["aws-lc-rs"] }
|
||||
rustls-webpki = { version = "0.103.10", features = ["aws-lc-rs"] }
|
||||
async-trait.workspace = true
|
||||
rand.workspace = true
|
||||
terrors.workspace = true
|
||||
103
server/crates/arbiter-client/src/auth.rs
Normal file
103
server/crates/arbiter-client/src/auth.rs
Normal file
@@ -0,0 +1,103 @@
|
||||
use arbiter_proto::{
|
||||
format_challenge,
|
||||
proto::client::{
|
||||
AuthChallengeRequest, AuthChallengeSolution, AuthResult, ClientRequest,
|
||||
client_request::Payload as ClientRequestPayload,
|
||||
client_response::Payload as ClientResponsePayload,
|
||||
},
|
||||
};
|
||||
use ed25519_dalek::Signer as _;
|
||||
use terrors::OneOf;
|
||||
|
||||
use crate::{
|
||||
errors::{
|
||||
ConnectError, MissingAuthChallengeError, UnexpectedAuthResponseError, map_auth_code_error,
|
||||
},
|
||||
transport::{ClientTransport, next_request_id},
|
||||
};
|
||||
|
||||
async fn send_auth_challenge_request(
|
||||
transport: &mut ClientTransport,
|
||||
key: &ed25519_dalek::SigningKey,
|
||||
) -> std::result::Result<(), ConnectError> {
|
||||
transport
|
||||
.send(ClientRequest {
|
||||
request_id: next_request_id(),
|
||||
payload: Some(ClientRequestPayload::AuthChallengeRequest(
|
||||
AuthChallengeRequest {
|
||||
pubkey: key.verifying_key().to_bytes().to_vec(),
|
||||
},
|
||||
)),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| OneOf::new(UnexpectedAuthResponseError))
|
||||
}
|
||||
|
||||
async fn receive_auth_challenge(
|
||||
transport: &mut ClientTransport,
|
||||
) -> std::result::Result<arbiter_proto::proto::client::AuthChallenge, ConnectError> {
|
||||
let response = transport
|
||||
.recv()
|
||||
.await
|
||||
.map_err(|_| OneOf::new(MissingAuthChallengeError))?;
|
||||
|
||||
let payload = response
|
||||
.payload
|
||||
.ok_or_else(|| OneOf::new(MissingAuthChallengeError))?;
|
||||
match payload {
|
||||
ClientResponsePayload::AuthChallenge(challenge) => Ok(challenge),
|
||||
ClientResponsePayload::AuthResult(result) => Err(map_auth_code_error(result)),
|
||||
_ => Err(OneOf::new(UnexpectedAuthResponseError)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_auth_challenge_solution(
|
||||
transport: &mut ClientTransport,
|
||||
key: &ed25519_dalek::SigningKey,
|
||||
challenge: arbiter_proto::proto::client::AuthChallenge,
|
||||
) -> std::result::Result<(), ConnectError> {
|
||||
let challenge_payload = format_challenge(challenge.nonce, &challenge.pubkey);
|
||||
let signature = key.sign(&challenge_payload).to_bytes().to_vec();
|
||||
|
||||
transport
|
||||
.send(ClientRequest {
|
||||
request_id: next_request_id(),
|
||||
payload: Some(ClientRequestPayload::AuthChallengeSolution(
|
||||
AuthChallengeSolution { signature },
|
||||
)),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| OneOf::new(UnexpectedAuthResponseError))
|
||||
}
|
||||
|
||||
async fn receive_auth_confirmation(
|
||||
transport: &mut ClientTransport,
|
||||
) -> std::result::Result<(), ConnectError> {
|
||||
let response = transport
|
||||
.recv()
|
||||
.await
|
||||
.map_err(|_| OneOf::new(UnexpectedAuthResponseError))?;
|
||||
|
||||
let payload = response
|
||||
.payload
|
||||
.ok_or_else(|| OneOf::new(UnexpectedAuthResponseError))?;
|
||||
match payload {
|
||||
ClientResponsePayload::AuthResult(result)
|
||||
if AuthResult::try_from(result).ok() == Some(AuthResult::Success) =>
|
||||
{
|
||||
Ok(())
|
||||
}
|
||||
ClientResponsePayload::AuthResult(result) => Err(map_auth_code_error(result)),
|
||||
_ => Err(OneOf::new(UnexpectedAuthResponseError)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn authenticate(
|
||||
transport: &mut ClientTransport,
|
||||
key: &ed25519_dalek::SigningKey,
|
||||
) -> std::result::Result<(), ConnectError> {
|
||||
send_auth_challenge_request(transport, key).await?;
|
||||
let challenge = receive_auth_challenge(transport).await?;
|
||||
send_auth_challenge_solution(transport, key, challenge).await?;
|
||||
receive_auth_confirmation(transport).await
|
||||
}
|
||||
82
server/crates/arbiter-client/src/client.rs
Normal file
82
server/crates/arbiter-client/src/client.rs
Normal file
@@ -0,0 +1,82 @@
|
||||
use arbiter_proto::{proto::arbiter_service_client::ArbiterServiceClient, url::ArbiterUrl};
|
||||
use std::sync::Arc;
|
||||
use terrors::{Broaden as _, OneOf};
|
||||
use tokio::sync::{Mutex, mpsc};
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
use tonic::transport::ClientTlsConfig;
|
||||
|
||||
use crate::{
|
||||
auth::authenticate,
|
||||
errors::ConnectError,
|
||||
storage::{FileSigningKeyStorage, SigningKeyStorage},
|
||||
transport::{BUFFER_LENGTH, ClientTransport},
|
||||
};
|
||||
|
||||
#[cfg(feature = "evm")]
|
||||
use crate::errors::{ClientConnectionClosedError, ClientError};
|
||||
|
||||
#[cfg(feature = "evm")]
|
||||
use crate::wallets::evm::ArbiterEvmWallet;
|
||||
|
||||
pub struct ArbiterClient {
|
||||
#[allow(dead_code)]
|
||||
transport: Arc<Mutex<ClientTransport>>,
|
||||
}
|
||||
|
||||
impl ArbiterClient {
|
||||
pub async fn connect(url: ArbiterUrl) -> Result<Self, ConnectError> {
|
||||
let storage = FileSigningKeyStorage::from_default_location().broaden()?;
|
||||
Self::connect_with_storage(url, &storage).await
|
||||
}
|
||||
|
||||
pub async fn connect_with_storage<S: SigningKeyStorage>(
|
||||
url: ArbiterUrl,
|
||||
storage: &S,
|
||||
) -> Result<Self, ConnectError> {
|
||||
let key = storage.load_or_create().broaden()?;
|
||||
Self::connect_with_key(url, key).await
|
||||
}
|
||||
|
||||
pub async fn connect_with_key(
|
||||
url: ArbiterUrl,
|
||||
key: ed25519_dalek::SigningKey,
|
||||
) -> Result<Self, ConnectError> {
|
||||
let anchor = webpki::anchor_from_trusted_cert(&url.ca_cert)
|
||||
.map_err(OneOf::new)?
|
||||
.to_owned();
|
||||
let tls = ClientTlsConfig::new().trust_anchor(anchor);
|
||||
|
||||
let channel = tonic::transport::Channel::from_shared(format!("{}:{}", url.host, url.port))
|
||||
.map_err(OneOf::new)?
|
||||
.tls_config(tls)
|
||||
.map_err(OneOf::new)?
|
||||
.connect()
|
||||
.await
|
||||
.map_err(OneOf::new)?;
|
||||
|
||||
let mut client = ArbiterServiceClient::new(channel);
|
||||
let (tx, rx) = mpsc::channel(BUFFER_LENGTH);
|
||||
let response_stream = client
|
||||
.client(ReceiverStream::new(rx))
|
||||
.await
|
||||
.map_err(OneOf::new)?
|
||||
.into_inner();
|
||||
|
||||
let mut transport = ClientTransport {
|
||||
sender: tx,
|
||||
receiver: response_stream,
|
||||
};
|
||||
|
||||
authenticate(&mut transport, &key).await?;
|
||||
|
||||
Ok(Self {
|
||||
transport: Arc::new(Mutex::new(transport)),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(feature = "evm")]
|
||||
pub async fn evm_wallets(&self) -> Result<Vec<ArbiterEvmWallet>, ClientError> {
|
||||
let _ = &self.transport;
|
||||
Err(OneOf::new(ClientConnectionClosedError))
|
||||
}
|
||||
}
|
||||
127
server/crates/arbiter-client/src/errors.rs
Normal file
127
server/crates/arbiter-client/src/errors.rs
Normal file
@@ -0,0 +1,127 @@
|
||||
use terrors::OneOf;
|
||||
use thiserror::Error;
|
||||
|
||||
#[cfg(feature = "evm")]
|
||||
use alloy::{primitives::ChainId, signers::Error as AlloySignerError};
|
||||
|
||||
pub type StorageError = OneOf<(std::io::Error, InvalidKeyLengthError)>;
|
||||
|
||||
pub type ConnectError = OneOf<(
|
||||
tonic::transport::Error,
|
||||
http::uri::InvalidUri,
|
||||
webpki::Error,
|
||||
tonic::Status,
|
||||
MissingAuthChallengeError,
|
||||
ApprovalDeniedError,
|
||||
NoUserAgentsOnlineError,
|
||||
UnexpectedAuthResponseError,
|
||||
std::io::Error,
|
||||
InvalidKeyLengthError,
|
||||
)>;
|
||||
|
||||
pub type ClientError = OneOf<(tonic::Status, ClientConnectionClosedError)>;
|
||||
|
||||
pub(crate) type ClientTransportError =
|
||||
OneOf<(TransportChannelClosedError, TransportConnectionClosedError)>;
|
||||
|
||||
#[cfg(feature = "evm")]
|
||||
pub(crate) type EvmWalletError = OneOf<(
|
||||
EvmChainIdMismatchError,
|
||||
EvmHashSigningUnsupportedError,
|
||||
EvmTransactionSigningUnsupportedError,
|
||||
)>;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
|
||||
#[error("Invalid signing key length in storage: expected {expected} bytes, got {actual} bytes")]
|
||||
pub struct InvalidKeyLengthError {
|
||||
pub expected: usize,
|
||||
pub actual: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
|
||||
#[error("Auth challenge was not returned by server")]
|
||||
pub struct MissingAuthChallengeError;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
|
||||
#[error("Client approval denied by User Agent")]
|
||||
pub struct ApprovalDeniedError;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
|
||||
#[error("No User Agents online to approve client")]
|
||||
pub struct NoUserAgentsOnlineError;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
|
||||
#[error("Unexpected auth response payload")]
|
||||
pub struct UnexpectedAuthResponseError;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
|
||||
#[error("Connection closed by server")]
|
||||
pub struct ClientConnectionClosedError;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
|
||||
#[error("Transport channel closed")]
|
||||
pub struct TransportChannelClosedError;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
|
||||
#[error("Connection closed by server")]
|
||||
pub struct TransportConnectionClosedError;
|
||||
|
||||
#[cfg(feature = "evm")]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
|
||||
#[error("Transaction chain id mismatch: signer {signer}, tx {tx}")]
|
||||
pub struct EvmChainIdMismatchError {
|
||||
pub signer: ChainId,
|
||||
pub tx: ChainId,
|
||||
}
|
||||
|
||||
#[cfg(feature = "evm")]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
|
||||
#[error("hash-only signing is not supported for ArbiterEvmWallet; use transaction signing")]
|
||||
pub struct EvmHashSigningUnsupportedError;
|
||||
|
||||
#[cfg(feature = "evm")]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
|
||||
#[error("transaction signing is not supported by current arbiter.client protocol")]
|
||||
pub struct EvmTransactionSigningUnsupportedError;
|
||||
|
||||
pub(crate) fn map_auth_code_error(code: i32) -> ConnectError {
|
||||
use arbiter_proto::proto::client::AuthResult;
|
||||
|
||||
match AuthResult::try_from(code).unwrap_or(AuthResult::Unspecified) {
|
||||
AuthResult::ApprovalDenied => OneOf::new(ApprovalDeniedError),
|
||||
AuthResult::NoUserAgentsOnline => OneOf::new(NoUserAgentsOnlineError),
|
||||
AuthResult::Unspecified
|
||||
| AuthResult::Success
|
||||
| AuthResult::InvalidKey
|
||||
| AuthResult::InvalidSignature
|
||||
| AuthResult::Internal => OneOf::new(UnexpectedAuthResponseError),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "evm")]
|
||||
impl From<EvmChainIdMismatchError> for AlloySignerError {
|
||||
fn from(value: EvmChainIdMismatchError) -> Self {
|
||||
AlloySignerError::TransactionChainIdMismatch {
|
||||
signer: value.signer,
|
||||
tx: value.tx,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "evm")]
|
||||
impl From<EvmHashSigningUnsupportedError> for AlloySignerError {
|
||||
fn from(_value: EvmHashSigningUnsupportedError) -> Self {
|
||||
AlloySignerError::other(
|
||||
"hash-only signing is not supported for ArbiterEvmWallet; use transaction signing",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "evm")]
|
||||
impl From<EvmTransactionSigningUnsupportedError> for AlloySignerError {
|
||||
fn from(_value: EvmTransactionSigningUnsupportedError) -> Self {
|
||||
AlloySignerError::other(
|
||||
"transaction signing is not supported by current arbiter.client protocol",
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,272 +1,13 @@
|
||||
use alloy::{
|
||||
consensus::SignableTransaction,
|
||||
network::TxSigner,
|
||||
primitives::{Address, B256, ChainId, Signature},
|
||||
signers::{Error, Result, Signer},
|
||||
};
|
||||
use arbiter_proto::{
|
||||
format_challenge,
|
||||
proto::{
|
||||
arbiter_service_client::ArbiterServiceClient,
|
||||
client::{
|
||||
AuthChallengeRequest, AuthChallengeSolution, ClientRequest, ClientResponse,
|
||||
client_connect_error, client_request::Payload as ClientRequestPayload,
|
||||
client_response::Payload as ClientResponsePayload,
|
||||
},
|
||||
evm::{
|
||||
EvmSignTransactionRequest, evm_sign_transaction_response::Result as SignResponseResult,
|
||||
},
|
||||
},
|
||||
url::ArbiterUrl,
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use ed25519_dalek::Signer as _;
|
||||
use tokio::sync::{Mutex, mpsc};
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
use tonic::transport::ClientTlsConfig;
|
||||
mod auth;
|
||||
mod client;
|
||||
mod errors;
|
||||
mod storage;
|
||||
mod transport;
|
||||
pub mod wallets;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ConnectError {
|
||||
#[error("Could not establish connection")]
|
||||
Connection(#[from] tonic::transport::Error),
|
||||
pub use client::ArbiterClient;
|
||||
pub use errors::{ClientError, ConnectError, StorageError};
|
||||
pub use storage::{FileSigningKeyStorage, SigningKeyStorage};
|
||||
|
||||
#[error("Invalid server URI")]
|
||||
InvalidUri(#[from] http::uri::InvalidUri),
|
||||
|
||||
#[error("Invalid CA certificate")]
|
||||
InvalidCaCert(#[from] webpki::Error),
|
||||
|
||||
#[error("gRPC error")]
|
||||
Grpc(#[from] tonic::Status),
|
||||
|
||||
#[error("Auth challenge was not returned by server")]
|
||||
MissingAuthChallenge,
|
||||
|
||||
#[error("Client approval denied by User Agent")]
|
||||
ApprovalDenied,
|
||||
|
||||
#[error("No User Agents online to approve client")]
|
||||
NoUserAgentsOnline,
|
||||
|
||||
#[error("Unexpected auth response payload")]
|
||||
UnexpectedAuthResponse,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
enum ClientSignError {
|
||||
#[error("Transport channel closed")]
|
||||
ChannelClosed,
|
||||
|
||||
#[error("Connection closed by server")]
|
||||
ConnectionClosed,
|
||||
|
||||
#[error("Invalid response payload")]
|
||||
InvalidResponse,
|
||||
|
||||
#[error("Remote signing was rejected")]
|
||||
Rejected,
|
||||
}
|
||||
|
||||
struct ClientTransport {
|
||||
sender: mpsc::Sender<ClientRequest>,
|
||||
receiver: tonic::Streaming<ClientResponse>,
|
||||
}
|
||||
|
||||
impl ClientTransport {
|
||||
async fn send(&mut self, request: ClientRequest) -> std::result::Result<(), ClientSignError> {
|
||||
self.sender
|
||||
.send(request)
|
||||
.await
|
||||
.map_err(|_| ClientSignError::ChannelClosed)
|
||||
}
|
||||
|
||||
async fn recv(&mut self) -> std::result::Result<ClientResponse, ClientSignError> {
|
||||
match self.receiver.message().await {
|
||||
Ok(Some(resp)) => Ok(resp),
|
||||
Ok(None) => Err(ClientSignError::ConnectionClosed),
|
||||
Err(_) => Err(ClientSignError::ConnectionClosed),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ArbiterSigner {
|
||||
transport: Mutex<ClientTransport>,
|
||||
address: Address,
|
||||
chain_id: Option<ChainId>,
|
||||
}
|
||||
|
||||
impl ArbiterSigner {
|
||||
pub async fn connect_grpc(
|
||||
url: ArbiterUrl,
|
||||
key: ed25519_dalek::SigningKey,
|
||||
address: Address,
|
||||
) -> std::result::Result<Self, ConnectError> {
|
||||
let anchor = webpki::anchor_from_trusted_cert(&url.ca_cert)?.to_owned();
|
||||
let tls = ClientTlsConfig::new().trust_anchor(anchor);
|
||||
|
||||
// NOTE: We intentionally keep the same URL construction strategy as the user-agent crate
|
||||
// to avoid behavior drift between the two clients.
|
||||
let channel = tonic::transport::Channel::from_shared(format!("{}:{}", url.host, url.port))?
|
||||
.tls_config(tls)?
|
||||
.connect()
|
||||
.await?;
|
||||
|
||||
let mut client = ArbiterServiceClient::new(channel);
|
||||
let (tx, rx) = mpsc::channel(16);
|
||||
let response_stream = client.client(ReceiverStream::new(rx)).await?.into_inner();
|
||||
|
||||
let mut transport = ClientTransport {
|
||||
sender: tx,
|
||||
receiver: response_stream,
|
||||
};
|
||||
|
||||
authenticate(&mut transport, key).await?;
|
||||
|
||||
Ok(Self {
|
||||
transport: Mutex::new(transport),
|
||||
address,
|
||||
chain_id: None,
|
||||
})
|
||||
}
|
||||
|
||||
async fn sign_transaction_via_arbiter(
|
||||
&self,
|
||||
tx: &mut dyn SignableTransaction<Signature>,
|
||||
) -> Result<Signature> {
|
||||
if let Some(chain_id) = self.chain_id
|
||||
&& !tx.set_chain_id_checked(chain_id)
|
||||
{
|
||||
return Err(Error::TransactionChainIdMismatch {
|
||||
signer: chain_id,
|
||||
tx: tx.chain_id().unwrap(),
|
||||
});
|
||||
}
|
||||
|
||||
let mut rlp_transaction = Vec::new();
|
||||
tx.encode_for_signing(&mut rlp_transaction);
|
||||
|
||||
let request = ClientRequest {
|
||||
payload: Some(ClientRequestPayload::EvmSignTransaction(
|
||||
EvmSignTransactionRequest {
|
||||
wallet_address: self.address.as_slice().to_vec(),
|
||||
rlp_transaction,
|
||||
},
|
||||
)),
|
||||
};
|
||||
|
||||
let mut transport = self.transport.lock().await;
|
||||
transport.send(request).await.map_err(Error::other)?;
|
||||
let response = transport.recv().await.map_err(Error::other)?;
|
||||
|
||||
let payload = response
|
||||
.payload
|
||||
.ok_or_else(|| Error::other(ClientSignError::InvalidResponse))?;
|
||||
|
||||
let ClientResponsePayload::EvmSignTransaction(sign_response) = payload else {
|
||||
return Err(Error::other(ClientSignError::InvalidResponse));
|
||||
};
|
||||
|
||||
let Some(result) = sign_response.result else {
|
||||
return Err(Error::other(ClientSignError::InvalidResponse));
|
||||
};
|
||||
|
||||
match result {
|
||||
SignResponseResult::Signature(bytes) => {
|
||||
Signature::try_from(bytes.as_slice()).map_err(Error::other)
|
||||
}
|
||||
SignResponseResult::EvalError(_) | SignResponseResult::Error(_) => {
|
||||
Err(Error::other(ClientSignError::Rejected))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn authenticate(
|
||||
transport: &mut ClientTransport,
|
||||
key: ed25519_dalek::SigningKey,
|
||||
) -> std::result::Result<(), ConnectError> {
|
||||
transport
|
||||
.send(ClientRequest {
|
||||
payload: Some(ClientRequestPayload::AuthChallengeRequest(
|
||||
AuthChallengeRequest {
|
||||
pubkey: key.verifying_key().to_bytes().to_vec(),
|
||||
},
|
||||
)),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| ConnectError::UnexpectedAuthResponse)?;
|
||||
|
||||
let response = transport
|
||||
.recv()
|
||||
.await
|
||||
.map_err(|_| ConnectError::MissingAuthChallenge)?;
|
||||
|
||||
let payload = response.payload.ok_or(ConnectError::MissingAuthChallenge)?;
|
||||
match payload {
|
||||
ClientResponsePayload::AuthChallenge(challenge) => {
|
||||
let challenge_payload = format_challenge(challenge.nonce, &challenge.pubkey);
|
||||
let signature = key.sign(&challenge_payload).to_bytes().to_vec();
|
||||
|
||||
transport
|
||||
.send(ClientRequest {
|
||||
payload: Some(ClientRequestPayload::AuthChallengeSolution(
|
||||
AuthChallengeSolution { signature },
|
||||
)),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| ConnectError::UnexpectedAuthResponse)?;
|
||||
|
||||
// Current server flow does not emit `AuthOk` for SDK clients, so we proceed after
|
||||
// sending the solution. If authentication fails, the first business request will return
|
||||
// a `ClientConnectError` or the stream will close.
|
||||
Ok(())
|
||||
}
|
||||
ClientResponsePayload::ClientConnectError(err) => {
|
||||
match client_connect_error::Code::try_from(err.code)
|
||||
.unwrap_or(client_connect_error::Code::Unknown)
|
||||
{
|
||||
client_connect_error::Code::ApprovalDenied => Err(ConnectError::ApprovalDenied),
|
||||
client_connect_error::Code::NoUserAgentsOnline => {
|
||||
Err(ConnectError::NoUserAgentsOnline)
|
||||
}
|
||||
client_connect_error::Code::Unknown => Err(ConnectError::UnexpectedAuthResponse),
|
||||
}
|
||||
}
|
||||
_ => Err(ConnectError::UnexpectedAuthResponse),
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Signer for ArbiterSigner {
|
||||
async fn sign_hash(&self, _hash: &B256) -> Result<Signature> {
|
||||
Err(Error::other(
|
||||
"hash-only signing is not supported for ArbiterSigner; use transaction signing",
|
||||
))
|
||||
}
|
||||
|
||||
fn address(&self) -> Address {
|
||||
self.address
|
||||
}
|
||||
|
||||
fn chain_id(&self) -> Option<ChainId> {
|
||||
self.chain_id
|
||||
}
|
||||
|
||||
fn set_chain_id(&mut self, chain_id: Option<ChainId>) {
|
||||
self.chain_id = chain_id;
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TxSigner<Signature> for ArbiterSigner {
|
||||
fn address(&self) -> Address {
|
||||
self.address
|
||||
}
|
||||
|
||||
async fn sign_transaction(
|
||||
&self,
|
||||
tx: &mut dyn SignableTransaction<Signature>,
|
||||
) -> Result<Signature> {
|
||||
self.sign_transaction_via_arbiter(tx).await
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "evm")]
|
||||
pub use wallets::evm::ArbiterEvmWallet;
|
||||
|
||||
130
server/crates/arbiter-client/src/storage.rs
Normal file
130
server/crates/arbiter-client/src/storage.rs
Normal file
@@ -0,0 +1,130 @@
|
||||
use arbiter_proto::home_path;
|
||||
use std::path::{Path, PathBuf};
|
||||
use terrors::OneOf;
|
||||
|
||||
use crate::errors::{InvalidKeyLengthError, StorageError};
|
||||
|
||||
pub trait SigningKeyStorage {
|
||||
fn load_or_create(&self) -> std::result::Result<ed25519_dalek::SigningKey, StorageError>;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct FileSigningKeyStorage {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl FileSigningKeyStorage {
|
||||
pub const DEFAULT_FILE_NAME: &str = "sdk_client_ed25519.key";
|
||||
|
||||
pub fn new(path: impl Into<PathBuf>) -> Self {
|
||||
Self { path: path.into() }
|
||||
}
|
||||
|
||||
pub fn from_default_location() -> std::result::Result<Self, StorageError> {
|
||||
Ok(Self::new(
|
||||
home_path()
|
||||
.map_err(OneOf::new)?
|
||||
.join(Self::DEFAULT_FILE_NAME),
|
||||
))
|
||||
}
|
||||
|
||||
fn read_key(path: &Path) -> std::result::Result<ed25519_dalek::SigningKey, StorageError> {
|
||||
let bytes = std::fs::read(path).map_err(OneOf::new)?;
|
||||
let raw: [u8; 32] = bytes.try_into().map_err(|v: Vec<u8>| {
|
||||
OneOf::new(InvalidKeyLengthError {
|
||||
expected: 32,
|
||||
actual: v.len(),
|
||||
})
|
||||
})?;
|
||||
Ok(ed25519_dalek::SigningKey::from_bytes(&raw))
|
||||
}
|
||||
}
|
||||
|
||||
impl SigningKeyStorage for FileSigningKeyStorage {
|
||||
fn load_or_create(&self) -> std::result::Result<ed25519_dalek::SigningKey, StorageError> {
|
||||
if let Some(parent) = self.path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(OneOf::new)?;
|
||||
}
|
||||
|
||||
if self.path.exists() {
|
||||
return Self::read_key(&self.path);
|
||||
}
|
||||
|
||||
let key = ed25519_dalek::SigningKey::generate(&mut rand::rng());
|
||||
let raw_key = key.to_bytes();
|
||||
|
||||
// Use create_new to prevent accidental overwrite if another process creates the key first.
|
||||
match std::fs::OpenOptions::new()
|
||||
.create_new(true)
|
||||
.write(true)
|
||||
.open(&self.path)
|
||||
{
|
||||
Ok(mut file) => {
|
||||
use std::io::Write as _;
|
||||
file.write_all(&raw_key).map_err(OneOf::new)?;
|
||||
Ok(key)
|
||||
}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {
|
||||
Self::read_key(&self.path)
|
||||
}
|
||||
Err(err) => Err(OneOf::new(err)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{FileSigningKeyStorage, SigningKeyStorage};
|
||||
use crate::errors::InvalidKeyLengthError;
|
||||
|
||||
fn unique_temp_key_path() -> std::path::PathBuf {
|
||||
let nanos = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.expect("clock should be after unix epoch")
|
||||
.as_nanos();
|
||||
std::env::temp_dir().join(format!(
|
||||
"arbiter-client-key-{}-{}.bin",
|
||||
std::process::id(),
|
||||
nanos
|
||||
))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_storage_creates_and_reuses_key() {
|
||||
let path = unique_temp_key_path();
|
||||
let storage = FileSigningKeyStorage::new(path.clone());
|
||||
|
||||
let key_a = storage
|
||||
.load_or_create()
|
||||
.expect("first load_or_create should create key");
|
||||
let key_b = storage
|
||||
.load_or_create()
|
||||
.expect("second load_or_create should read same key");
|
||||
|
||||
assert_eq!(key_a.to_bytes(), key_b.to_bytes());
|
||||
assert!(path.exists());
|
||||
|
||||
std::fs::remove_file(path).expect("temp key file should be removable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_storage_rejects_invalid_key_length() {
|
||||
let path = unique_temp_key_path();
|
||||
std::fs::write(&path, [42u8; 31]).expect("should write invalid key file");
|
||||
let storage = FileSigningKeyStorage::new(path.clone());
|
||||
|
||||
let err = storage
|
||||
.load_or_create()
|
||||
.expect_err("storage should reject non-32-byte key file");
|
||||
|
||||
match err.narrow::<InvalidKeyLengthError, _>() {
|
||||
Ok(invalid_len) => {
|
||||
assert_eq!(invalid_len.expected, 32);
|
||||
assert_eq!(invalid_len.actual, 31);
|
||||
}
|
||||
Err(other) => panic!("unexpected io error: {other:?}"),
|
||||
}
|
||||
|
||||
std::fs::remove_file(path).expect("temp key file should be removable");
|
||||
}
|
||||
}
|
||||
42
server/crates/arbiter-client/src/transport.rs
Normal file
42
server/crates/arbiter-client/src/transport.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use arbiter_proto::proto::client::{ClientRequest, ClientResponse};
|
||||
use std::sync::atomic::{AtomicI32, Ordering};
|
||||
use terrors::OneOf;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::errors::{
|
||||
ClientTransportError, TransportChannelClosedError, TransportConnectionClosedError,
|
||||
};
|
||||
|
||||
pub(crate) const BUFFER_LENGTH: usize = 16;
|
||||
static NEXT_REQUEST_ID: AtomicI32 = AtomicI32::new(1);
|
||||
|
||||
pub(crate) fn next_request_id() -> i32 {
|
||||
NEXT_REQUEST_ID.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub(crate) struct ClientTransport {
|
||||
pub(crate) sender: mpsc::Sender<ClientRequest>,
|
||||
pub(crate) receiver: tonic::Streaming<ClientResponse>,
|
||||
}
|
||||
|
||||
impl ClientTransport {
|
||||
pub(crate) async fn send(
|
||||
&mut self,
|
||||
request: ClientRequest,
|
||||
) -> std::result::Result<(), ClientTransportError> {
|
||||
self.sender
|
||||
.send(request)
|
||||
.await
|
||||
.map_err(|_| OneOf::new(TransportChannelClosedError))
|
||||
}
|
||||
|
||||
pub(crate) async fn recv(
|
||||
&mut self,
|
||||
) -> std::result::Result<ClientResponse, ClientTransportError> {
|
||||
match self.receiver.message().await {
|
||||
Ok(Some(resp)) => Ok(resp),
|
||||
Ok(None) => Err(OneOf::new(TransportConnectionClosedError)),
|
||||
Err(_) => Err(OneOf::new(TransportConnectionClosedError)),
|
||||
}
|
||||
}
|
||||
}
|
||||
97
server/crates/arbiter-client/src/wallets/evm.rs
Normal file
97
server/crates/arbiter-client/src/wallets/evm.rs
Normal file
@@ -0,0 +1,97 @@
|
||||
use alloy::{
|
||||
consensus::SignableTransaction,
|
||||
network::TxSigner,
|
||||
primitives::{Address, B256, ChainId, Signature},
|
||||
signers::{Result, Signer},
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use std::sync::Arc;
|
||||
use terrors::OneOf;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::{
|
||||
errors::{
|
||||
EvmChainIdMismatchError, EvmHashSigningUnsupportedError,
|
||||
EvmTransactionSigningUnsupportedError, EvmWalletError,
|
||||
},
|
||||
transport::ClientTransport,
|
||||
};
|
||||
|
||||
pub struct ArbiterEvmWallet {
|
||||
transport: Arc<Mutex<ClientTransport>>,
|
||||
address: Address,
|
||||
chain_id: Option<ChainId>,
|
||||
}
|
||||
|
||||
impl ArbiterEvmWallet {
|
||||
#[allow(dead_code)]
|
||||
pub(crate) fn new(transport: Arc<Mutex<ClientTransport>>, address: Address) -> Self {
|
||||
Self {
|
||||
transport,
|
||||
address,
|
||||
chain_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn address(&self) -> Address {
|
||||
self.address
|
||||
}
|
||||
|
||||
pub fn with_chain_id(mut self, chain_id: ChainId) -> Self {
|
||||
self.chain_id = Some(chain_id);
|
||||
self
|
||||
}
|
||||
|
||||
fn validate_chain_id(
|
||||
&self,
|
||||
tx: &mut dyn SignableTransaction<Signature>,
|
||||
) -> std::result::Result<(), EvmWalletError> {
|
||||
if let Some(chain_id) = self.chain_id
|
||||
&& !tx.set_chain_id_checked(chain_id)
|
||||
{
|
||||
return Err(OneOf::new(EvmChainIdMismatchError {
|
||||
signer: chain_id,
|
||||
tx: tx.chain_id().unwrap(),
|
||||
}));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Signer for ArbiterEvmWallet {
|
||||
async fn sign_hash(&self, _hash: &B256) -> Result<Signature> {
|
||||
Err(EvmWalletError::new(EvmHashSigningUnsupportedError).into())
|
||||
}
|
||||
|
||||
fn address(&self) -> Address {
|
||||
self.address
|
||||
}
|
||||
|
||||
fn chain_id(&self) -> Option<ChainId> {
|
||||
self.chain_id
|
||||
}
|
||||
|
||||
fn set_chain_id(&mut self, chain_id: Option<ChainId>) {
|
||||
self.chain_id = chain_id;
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TxSigner<Signature> for ArbiterEvmWallet {
|
||||
fn address(&self) -> Address {
|
||||
self.address
|
||||
}
|
||||
|
||||
async fn sign_transaction(
|
||||
&self,
|
||||
tx: &mut dyn SignableTransaction<Signature>,
|
||||
) -> Result<Signature> {
|
||||
let _transport = self.transport.lock().await;
|
||||
self.validate_chain_id(tx)
|
||||
.map_err(OneOf::into::<alloy::signers::Error>)?;
|
||||
|
||||
Err(EvmWalletError::new(EvmTransactionSigningUnsupportedError).into())
|
||||
}
|
||||
}
|
||||
2
server/crates/arbiter-client/src/wallets/mod.rs
Normal file
2
server/crates/arbiter-client/src/wallets/mod.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
#[cfg(feature = "evm")]
|
||||
pub mod evm;
|
||||
@@ -10,7 +10,7 @@ tonic.workspace = true
|
||||
tokio.workspace = true
|
||||
futures.workspace = true
|
||||
hex = "0.4.3"
|
||||
tonic-prost = "0.14.3"
|
||||
tonic-prost = "0.14.5"
|
||||
prost = "0.14.3"
|
||||
kameo.workspace = true
|
||||
url = "2.5.8"
|
||||
@@ -21,9 +21,10 @@ base64 = "0.22.1"
|
||||
prost-types.workspace = true
|
||||
tracing.workspace = true
|
||||
async-trait.workspace = true
|
||||
tokio-stream.workspace = true
|
||||
|
||||
[build-dependencies]
|
||||
tonic-prost-build = "0.14.3"
|
||||
tonic-prost-build = "0.14.5"
|
||||
protoc-bin-vendored = "3"
|
||||
|
||||
[dev-dependencies]
|
||||
@@ -33,5 +34,3 @@ rcgen.workspace = true
|
||||
|
||||
[package.metadata.cargo-shear]
|
||||
ignored = ["tonic-prost", "prost", "kameo"]
|
||||
|
||||
|
||||
|
||||
@@ -1,27 +1,32 @@
|
||||
use std::path::PathBuf;
|
||||
use tonic_prost_build::configure;
|
||||
|
||||
static PROTOBUF_DIR: &str = "../../../protobufs";
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
if std::env::var("PROTOC").is_err() {
|
||||
println!("cargo:warning=PROTOC environment variable not set, using vendored protoc");
|
||||
let protoc = protoc_bin_vendored::protoc_bin_path().unwrap();
|
||||
unsafe { std::env::set_var("PROTOC", protoc) };
|
||||
let manifest_dir = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR")?);
|
||||
let protobuf_dir = manifest_dir.join(PROTOBUF_DIR);
|
||||
let protoc_include = protoc_bin_vendored::include_path()?;
|
||||
let protoc_path = protoc_bin_vendored::protoc_bin_path()?;
|
||||
|
||||
unsafe {
|
||||
std::env::set_var("PROTOC", &protoc_path);
|
||||
std::env::set_var("PROTOC_INCLUDE", &protoc_include);
|
||||
}
|
||||
|
||||
println!("cargo::rerun-if-changed={PROTOBUF_DIR}");
|
||||
println!("cargo::rerun-if-changed={}", protobuf_dir.display());
|
||||
|
||||
configure()
|
||||
.message_attribute(".", "#[derive(::kameo::Reply)]")
|
||||
.compile_well_known_types(true)
|
||||
.compile_protos(
|
||||
&[
|
||||
format!("{}/arbiter.proto", PROTOBUF_DIR),
|
||||
format!("{}/user_agent.proto", PROTOBUF_DIR),
|
||||
format!("{}/client.proto", PROTOBUF_DIR),
|
||||
format!("{}/evm.proto", PROTOBUF_DIR),
|
||||
protobuf_dir.join("arbiter.proto"),
|
||||
protobuf_dir.join("user_agent.proto"),
|
||||
protobuf_dir.join("client.proto"),
|
||||
protobuf_dir.join("evm.proto"),
|
||||
],
|
||||
&[PROTOBUF_DIR.to_string()],
|
||||
)
|
||||
.unwrap();
|
||||
&[protobuf_dir],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -3,6 +3,12 @@ pub mod url;
|
||||
|
||||
use base64::{Engine, prelude::BASE64_STANDARD};
|
||||
|
||||
pub mod google {
|
||||
pub mod protobuf {
|
||||
tonic::include_proto!("google.protobuf");
|
||||
}
|
||||
}
|
||||
|
||||
pub mod proto {
|
||||
tonic::include_proto!("arbiter");
|
||||
|
||||
|
||||
@@ -1,78 +1,59 @@
|
||||
//! Transport-facing abstractions for protocol/session code.
|
||||
//! Transport-facing abstractions shared by protocol/session code.
|
||||
//!
|
||||
//! This module separates three concerns:
|
||||
//! This module defines a small set of transport traits that actors and other
|
||||
//! protocol code can depend on without knowing anything about the concrete
|
||||
//! transport underneath.
|
||||
//!
|
||||
//! - protocol/session logic wants a small duplex interface ([`Bi`])
|
||||
//! - transport adapters push concrete stream items to an underlying IO layer
|
||||
//! - transport boundaries translate between protocol-facing and transport-facing
|
||||
//! item types via direction-specific converters
|
||||
//! The abstraction is split into:
|
||||
//! - [`Sender`] for outbound delivery
|
||||
//! - [`Receiver`] for inbound delivery
|
||||
//! - [`Bi`] as the combined duplex form (`Sender + Receiver`)
|
||||
//!
|
||||
//! [`Bi`] is intentionally minimal and transport-agnostic:
|
||||
//! - [`Bi::recv`] yields inbound protocol messages
|
||||
//! - [`Bi::send`] accepts outbound protocol/domain items
|
||||
//! This split lets code depend only on the half it actually needs. For
|
||||
//! example, some actor/session code only sends out-of-band messages, while
|
||||
//! auth/state-machine code may need full duplex access.
|
||||
//!
|
||||
//! [`Bi`] remains intentionally minimal and transport-agnostic:
|
||||
//! - [`Receiver::recv`] yields inbound messages
|
||||
//! - [`Sender::send`] accepts outbound messages
|
||||
//!
|
||||
//! Transport-specific adapters, including protobuf or gRPC bridges, live in the
|
||||
//! crates that own those boundaries rather than in `arbiter-proto`.
|
||||
//!
|
||||
//! [`Bi`] deliberately does not model request/response correlation. Some
|
||||
//! transports may carry multiplexed request/response traffic, some may emit
|
||||
//! out-of-band messages, and some may be one-message-at-a-time state machines.
|
||||
//! Correlation concerns such as request IDs, pending response maps, and
|
||||
//! out-of-band routing belong in the adapter or connection layer built on top
|
||||
//! of [`Bi`], not in this abstraction itself.
|
||||
//!
|
||||
//! # Generic Ordering Rule
|
||||
//!
|
||||
//! This module uses a single convention consistently: when a type or trait is
|
||||
//! parameterized by protocol message directions, the generic parameters are
|
||||
//! declared as `Inbound` first, then `Outbound`.
|
||||
//! This module consistently uses `Inbound` first and `Outbound` second in
|
||||
//! generic parameter lists.
|
||||
//!
|
||||
//! For [`Bi`], that means `Bi<Inbound, Outbound>`:
|
||||
//! For [`Receiver`], [`Sender`], and [`Bi`], this means:
|
||||
//! - `Receiver<Inbound>`
|
||||
//! - `Sender<Outbound>`
|
||||
//! - `Bi<Inbound, Outbound>`
|
||||
//!
|
||||
//! Concretely, for [`Bi`]:
|
||||
//! - `recv() -> Option<Inbound>`
|
||||
//! - `send(Outbound)`
|
||||
//!
|
||||
//! For adapter types that are parameterized by direction-specific converters,
|
||||
//! inbound-related converter parameters are declared before outbound-related
|
||||
//! converter parameters.
|
||||
//! [`expect_message`] is a small helper for linear protocol steps: it reads one
|
||||
//! inbound message from a transport and extracts a typed value from it, failing
|
||||
//! if the channel closes or the message shape is not what the caller expected.
|
||||
//!
|
||||
//! [`RecvConverter`] and [`SendConverter`] are infallible conversion traits used
|
||||
//! by adapters to map between protocol-facing and transport-facing item types.
|
||||
//! The traits themselves are not result-aware; adapters decide how transport
|
||||
//! errors are handled before (or instead of) conversion.
|
||||
//!
|
||||
//! [`grpc::GrpcAdapter`] combines:
|
||||
//! - a tonic inbound stream
|
||||
//! - a Tokio sender for outbound transport items
|
||||
//! - a [`RecvConverter`] for the receive path
|
||||
//! - a [`SendConverter`] for the send path
|
||||
//!
|
||||
//! [`DummyTransport`] is a no-op implementation useful for tests and local actor
|
||||
//! execution where no real network stream exists.
|
||||
//!
|
||||
//! # Component Interaction
|
||||
//!
|
||||
//! ```text
|
||||
//! inbound (network -> protocol)
|
||||
//! ============================
|
||||
//!
|
||||
//! tonic::Streaming<RecvTransport>
|
||||
//! -> grpc::GrpcAdapter::recv()
|
||||
//! |
|
||||
//! +--> on `Ok(item)`: RecvConverter::convert(RecvTransport) -> Inbound
|
||||
//! +--> on `Err(status)`: log error and close stream (`None`)
|
||||
//! -> Bi::recv()
|
||||
//! -> protocol/session actor
|
||||
//!
|
||||
//! outbound (protocol -> network)
|
||||
//! ==============================
|
||||
//!
|
||||
//! protocol/session actor
|
||||
//! -> Bi::send(Outbound)
|
||||
//! -> grpc::GrpcAdapter::send()
|
||||
//! |
|
||||
//! +--> SendConverter::convert(Outbound) -> SendTransport
|
||||
//! -> Tokio mpsc::Sender<SendTransport>
|
||||
//! -> tonic response stream
|
||||
//! ```
|
||||
//! [`DummyTransport`] is a no-op implementation useful for tests and local
|
||||
//! actor execution where no real stream exists.
|
||||
//!
|
||||
//! # Design Notes
|
||||
//!
|
||||
//! - `send()` returns [`Error`] only for transport delivery failures (for
|
||||
//! example, when the outbound channel is closed).
|
||||
//! - [`grpc::GrpcAdapter`] logs tonic receive errors and treats them as stream
|
||||
//! closure (`None`).
|
||||
//! - When protocol-facing and transport-facing types are identical, use
|
||||
//! [`IdentityRecvConverter`] / [`IdentitySendConverter`].
|
||||
//! - [`Bi::send`] returns [`Error`] only for transport delivery failures, such
|
||||
//! as a closed outbound channel.
|
||||
//! - [`Bi::recv`] returns `None` when the underlying transport closes.
|
||||
//! - Message translation is intentionally out of scope for this module.
|
||||
|
||||
use std::marker::PhantomData;
|
||||
|
||||
@@ -102,172 +83,35 @@ where
|
||||
extractor(msg).ok_or(Error::UnexpectedMessage)
|
||||
}
|
||||
|
||||
/// Minimal bidirectional transport abstraction used by protocol code.
|
||||
///
|
||||
/// `Bi<Inbound, Outbound>` models a duplex channel with:
|
||||
/// - inbound items of type `Inbound` read via [`Bi::recv`]
|
||||
/// - outbound items of type `Outbound` written via [`Bi::send`]
|
||||
#[async_trait]
|
||||
pub trait Bi<Inbound, Outbound>: Send + Sync + 'static {
|
||||
pub trait Sender<Outbound>: Send + Sync {
|
||||
async fn send(&mut self, item: Outbound) -> Result<(), Error>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait Receiver<Inbound>: Send + Sync {
|
||||
async fn recv(&mut self) -> Option<Inbound>;
|
||||
}
|
||||
|
||||
/// Converts transport-facing inbound items into protocol-facing inbound items.
|
||||
pub trait RecvConverter: Send + Sync + 'static {
|
||||
type Input;
|
||||
type Output;
|
||||
/// Minimal bidirectional transport abstraction used by protocol code.
|
||||
///
|
||||
/// `Bi<Inbound, Outbound>` is the combined duplex form of [`Sender`] and
|
||||
/// [`Receiver`].
|
||||
///
|
||||
/// It models a channel with:
|
||||
/// - inbound items of type `Inbound` read via [`Bi::recv`]
|
||||
/// - outbound items of type `Outbound` written via [`Bi::send`]
|
||||
///
|
||||
/// It does not imply request/response sequencing, one-at-a-time exchange, or
|
||||
/// any built-in correlation mechanism between inbound and outbound items.
|
||||
pub trait Bi<Inbound, Outbound>: Sender<Outbound> + Receiver<Inbound> + Send + Sync {}
|
||||
|
||||
fn convert(&self, item: Self::Input) -> Self::Output;
|
||||
}
|
||||
pub trait SplittableBi<Inbound, Outbound>: Bi<Inbound, Outbound> {
|
||||
type Sender: Sender<Outbound>;
|
||||
type Receiver: Receiver<Inbound>;
|
||||
|
||||
/// Converts protocol/domain outbound items into transport-facing outbound items.
|
||||
pub trait SendConverter: Send + Sync + 'static {
|
||||
type Input;
|
||||
type Output;
|
||||
|
||||
fn convert(&self, item: Self::Input) -> Self::Output;
|
||||
}
|
||||
|
||||
/// A [`RecvConverter`] that forwards values unchanged.
|
||||
pub struct IdentityRecvConverter<T> {
|
||||
_marker: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T> IdentityRecvConverter<T> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
_marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Default for IdentityRecvConverter<T> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> RecvConverter for IdentityRecvConverter<T>
|
||||
where
|
||||
T: Send + Sync + 'static,
|
||||
{
|
||||
type Input = T;
|
||||
type Output = T;
|
||||
|
||||
fn convert(&self, item: Self::Input) -> Self::Output {
|
||||
item
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`SendConverter`] that forwards values unchanged.
|
||||
pub struct IdentitySendConverter<T> {
|
||||
_marker: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T> IdentitySendConverter<T> {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
_marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Default for IdentitySendConverter<T> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> SendConverter for IdentitySendConverter<T>
|
||||
where
|
||||
T: Send + Sync + 'static,
|
||||
{
|
||||
type Input = T;
|
||||
type Output = T;
|
||||
|
||||
fn convert(&self, item: Self::Input) -> Self::Output {
|
||||
item
|
||||
}
|
||||
}
|
||||
|
||||
/// gRPC-specific transport adapters and helpers.
|
||||
pub mod grpc {
|
||||
use async_trait::async_trait;
|
||||
use futures::StreamExt;
|
||||
use tokio::sync::mpsc;
|
||||
use tonic::Streaming;
|
||||
|
||||
use super::{Bi, Error, RecvConverter, SendConverter};
|
||||
|
||||
/// [`Bi`] adapter backed by a tonic gRPC bidirectional stream.
|
||||
///
|
||||
/// Tonic receive errors are logged and treated as stream closure (`None`).
|
||||
/// The receive converter is only invoked for successful inbound transport
|
||||
/// items.
|
||||
pub struct GrpcAdapter<InboundConverter, OutboundConverter>
|
||||
where
|
||||
InboundConverter: RecvConverter,
|
||||
OutboundConverter: SendConverter,
|
||||
{
|
||||
sender: mpsc::Sender<OutboundConverter::Output>,
|
||||
receiver: Streaming<InboundConverter::Input>,
|
||||
inbound_converter: InboundConverter,
|
||||
outbound_converter: OutboundConverter,
|
||||
}
|
||||
|
||||
impl<InboundTransport, Inbound, InboundConverter, OutboundConverter>
|
||||
GrpcAdapter<InboundConverter, OutboundConverter>
|
||||
where
|
||||
InboundConverter: RecvConverter<Input = InboundTransport, Output = Inbound>,
|
||||
OutboundConverter: SendConverter,
|
||||
{
|
||||
pub fn new(
|
||||
sender: mpsc::Sender<OutboundConverter::Output>,
|
||||
receiver: Streaming<InboundTransport>,
|
||||
inbound_converter: InboundConverter,
|
||||
outbound_converter: OutboundConverter,
|
||||
) -> Self {
|
||||
Self {
|
||||
sender,
|
||||
receiver,
|
||||
inbound_converter,
|
||||
outbound_converter,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<InboundConverter, OutboundConverter> Bi<InboundConverter::Output, OutboundConverter::Input>
|
||||
for GrpcAdapter<InboundConverter, OutboundConverter>
|
||||
where
|
||||
InboundConverter: RecvConverter,
|
||||
OutboundConverter: SendConverter,
|
||||
OutboundConverter::Input: Send + 'static,
|
||||
OutboundConverter::Output: Send + 'static,
|
||||
{
|
||||
#[tracing::instrument(level = "trace", skip(self, item))]
|
||||
async fn send(&mut self, item: OutboundConverter::Input) -> Result<(), Error> {
|
||||
let outbound = self.outbound_converter.convert(item);
|
||||
self.sender
|
||||
.send(outbound)
|
||||
.await
|
||||
.map_err(|_| Error::ChannelClosed)
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "trace", skip(self))]
|
||||
async fn recv(&mut self) -> Option<InboundConverter::Output> {
|
||||
match self.receiver.next().await {
|
||||
Some(Ok(item)) => Some(self.inbound_converter.convert(item)),
|
||||
Some(Err(error)) => {
|
||||
tracing::error!(error = ?error, "grpc transport recv failed; closing stream");
|
||||
None
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
fn split(self) -> (Self::Sender, Self::Receiver);
|
||||
fn from_parts(sender: Self::Sender, receiver: Self::Receiver) -> Self;
|
||||
}
|
||||
|
||||
/// No-op [`Bi`] transport for tests and manual actor usage.
|
||||
@@ -278,22 +122,16 @@ pub struct DummyTransport<Inbound, Outbound> {
|
||||
_marker: PhantomData<(Inbound, Outbound)>,
|
||||
}
|
||||
|
||||
impl<Inbound, Outbound> DummyTransport<Inbound, Outbound> {
|
||||
pub fn new() -> Self {
|
||||
impl<Inbound, Outbound> Default for DummyTransport<Inbound, Outbound> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
_marker: PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Inbound, Outbound> Default for DummyTransport<Inbound, Outbound> {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<Inbound, Outbound> Bi<Inbound, Outbound> for DummyTransport<Inbound, Outbound>
|
||||
impl<Inbound, Outbound> Sender<Outbound> for DummyTransport<Inbound, Outbound>
|
||||
where
|
||||
Inbound: Send + Sync + 'static,
|
||||
Outbound: Send + Sync + 'static,
|
||||
@@ -301,9 +139,25 @@ where
|
||||
async fn send(&mut self, _item: Outbound) -> Result<(), Error> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<Inbound, Outbound> Receiver<Inbound> for DummyTransport<Inbound, Outbound>
|
||||
where
|
||||
Inbound: Send + Sync + 'static,
|
||||
Outbound: Send + Sync + 'static,
|
||||
{
|
||||
async fn recv(&mut self) -> Option<Inbound> {
|
||||
std::future::pending::<()>().await;
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl<Inbound, Outbound> Bi<Inbound, Outbound> for DummyTransport<Inbound, Outbound>
|
||||
where
|
||||
Inbound: Send + Sync + 'static,
|
||||
Outbound: Send + Sync + 'static,
|
||||
{
|
||||
}
|
||||
|
||||
pub mod grpc;
|
||||
|
||||
106
server/crates/arbiter-proto/src/transport/grpc.rs
Normal file
106
server/crates/arbiter-proto/src/transport/grpc.rs
Normal file
@@ -0,0 +1,106 @@
|
||||
use async_trait::async_trait;
|
||||
use futures::StreamExt;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
|
||||
use super::{Bi, Receiver, Sender};
|
||||
|
||||
pub struct GrpcSender<Outbound> {
|
||||
tx: mpsc::Sender<Result<Outbound, tonic::Status>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<Outbound> Sender<Result<Outbound, tonic::Status>> for GrpcSender<Outbound>
|
||||
where
|
||||
Outbound: Send + Sync + 'static,
|
||||
{
|
||||
async fn send(&mut self, item: Result<Outbound, tonic::Status>) -> Result<(), super::Error> {
|
||||
self.tx
|
||||
.send(item)
|
||||
.await
|
||||
.map_err(|_| super::Error::ChannelClosed)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GrpcReceiver<Inbound> {
|
||||
rx: tonic::Streaming<Inbound>,
|
||||
}
|
||||
#[async_trait]
|
||||
impl<Inbound> Receiver<Result<Inbound, tonic::Status>> for GrpcReceiver<Inbound>
|
||||
where
|
||||
Inbound: Send + Sync + 'static,
|
||||
{
|
||||
async fn recv(&mut self) -> Option<Result<Inbound, tonic::Status>> {
|
||||
self.rx.next().await
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GrpcBi<Inbound, Outbound> {
|
||||
sender: GrpcSender<Outbound>,
|
||||
receiver: GrpcReceiver<Inbound>,
|
||||
}
|
||||
|
||||
impl<Inbound, Outbound> GrpcBi<Inbound, Outbound>
|
||||
where
|
||||
Inbound: Send + Sync + 'static,
|
||||
Outbound: Send + Sync + 'static,
|
||||
{
|
||||
pub fn from_bi_stream(
|
||||
receiver: tonic::Streaming<Inbound>,
|
||||
) -> (Self, ReceiverStream<Result<Outbound, tonic::Status>>) {
|
||||
let (tx, rx) = mpsc::channel(10);
|
||||
let sender = GrpcSender { tx };
|
||||
let receiver = GrpcReceiver { rx: receiver };
|
||||
let bi = GrpcBi { sender, receiver };
|
||||
(bi, ReceiverStream::new(rx))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<Inbound, Outbound> Sender<Result<Outbound, tonic::Status>> for GrpcBi<Inbound, Outbound>
|
||||
where
|
||||
Inbound: Send + Sync + 'static,
|
||||
Outbound: Send + Sync + 'static,
|
||||
{
|
||||
async fn send(&mut self, item: Result<Outbound, tonic::Status>) -> Result<(), super::Error> {
|
||||
self.sender.send(item).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<Inbound, Outbound> Receiver<Result<Inbound, tonic::Status>> for GrpcBi<Inbound, Outbound>
|
||||
where
|
||||
Inbound: Send + Sync + 'static,
|
||||
Outbound: Send + Sync + 'static,
|
||||
{
|
||||
async fn recv(&mut self) -> Option<Result<Inbound, tonic::Status>> {
|
||||
self.receiver.recv().await
|
||||
}
|
||||
}
|
||||
|
||||
impl<Inbound, Outbound> Bi<Result<Inbound, tonic::Status>, Result<Outbound, tonic::Status>>
|
||||
for GrpcBi<Inbound, Outbound>
|
||||
where
|
||||
Inbound: Send + Sync + 'static,
|
||||
Outbound: Send + Sync + 'static,
|
||||
{
|
||||
}
|
||||
|
||||
impl<Inbound, Outbound>
|
||||
super::SplittableBi<Result<Inbound, tonic::Status>, Result<Outbound, tonic::Status>>
|
||||
for GrpcBi<Inbound, Outbound>
|
||||
where
|
||||
Inbound: Send + Sync + 'static,
|
||||
Outbound: Send + Sync + 'static,
|
||||
{
|
||||
type Sender = GrpcSender<Outbound>;
|
||||
type Receiver = GrpcReceiver<Inbound>;
|
||||
|
||||
fn split(self) -> (Self::Sender, Self::Receiver) {
|
||||
(self.sender, self.receiver)
|
||||
}
|
||||
|
||||
fn from_parts(sender: Self::Sender, receiver: Self::Receiver) -> Self {
|
||||
GrpcBi { sender, receiver }
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,8 @@ license = "Apache-2.0"
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
diesel = { version = "2.3.6", features = ["chrono", "returning_clauses_for_sqlite_3_35", "serde_json", "time", "uuid"] }
|
||||
diesel-async = { version = "0.7.4", features = [
|
||||
diesel = { version = "2.3.7", features = ["chrono", "returning_clauses_for_sqlite_3_35", "serde_json", "time", "uuid"] }
|
||||
diesel-async = { version = "0.8.0", features = [
|
||||
"bb8",
|
||||
"migrations",
|
||||
"sqlite",
|
||||
@@ -27,6 +27,7 @@ rustls.workspace = true
|
||||
smlang.workspace = true
|
||||
miette.workspace = true
|
||||
thiserror.workspace = true
|
||||
fatality = "0.1.1"
|
||||
diesel_migrations = { version = "2.3.1", features = ["sqlite"] }
|
||||
async-trait.workspace = true
|
||||
secrecy = "0.10.3"
|
||||
@@ -43,13 +44,14 @@ x25519-dalek.workspace = true
|
||||
chacha20poly1305 = { version = "0.10.1", features = ["std"] }
|
||||
argon2 = { version = "0.5.3", features = ["zeroize"] }
|
||||
restructed = "0.2.2"
|
||||
strum = { version = "0.27.2", features = ["derive"] }
|
||||
strum = { version = "0.28.0", features = ["derive"] }
|
||||
pem = "3.0.6"
|
||||
k256.workspace = true
|
||||
rsa.workspace = true
|
||||
sha2.workspace = true
|
||||
spki.workspace = true
|
||||
alloy.workspace = true
|
||||
prost-types.workspace = true
|
||||
arbiter-tokens-registry.path = "../arbiter-tokens-registry"
|
||||
|
||||
[dev-dependencies]
|
||||
|
||||
@@ -157,3 +157,5 @@ create table if not exists evm_ether_transfer_grant_target (
|
||||
|
||||
create unique index if not exists uniq_ether_transfer_target on evm_ether_transfer_grant_target(grant_id, address);
|
||||
|
||||
CREATE UNIQUE INDEX program_client_public_key_unique
|
||||
ON program_client (public_key);
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
DROP INDEX IF EXISTS program_client_public_key_unique;
|
||||
@@ -1,2 +0,0 @@
|
||||
CREATE UNIQUE INDEX program_client_public_key_unique
|
||||
ON program_client (public_key);
|
||||
@@ -3,12 +3,7 @@ use diesel::QueryDsl;
|
||||
use diesel_async::RunQueryDsl;
|
||||
use kameo::{Actor, messages};
|
||||
use miette::Diagnostic;
|
||||
use rand::{
|
||||
RngExt,
|
||||
distr::{Alphanumeric},
|
||||
make_rng,
|
||||
rngs::StdRng,
|
||||
};
|
||||
use rand::{RngExt, distr::Alphanumeric, make_rng, rngs::StdRng};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::db::{self, DatabasePool, schema};
|
||||
@@ -61,7 +56,6 @@ impl Bootstrapper {
|
||||
|
||||
drop(conn);
|
||||
|
||||
|
||||
let token = if row_count == 0 {
|
||||
let token = generate_token().await?;
|
||||
Some(token)
|
||||
|
||||
@@ -1,53 +1,62 @@
|
||||
use arbiter_proto::{
|
||||
format_challenge,
|
||||
proto::client::{
|
||||
AuthChallenge, AuthChallengeSolution, ClientConnectError, ClientRequest, ClientResponse,
|
||||
client_connect_error::Code as ConnectErrorCode,
|
||||
client_request::Payload as ClientRequestPayload,
|
||||
client_response::Payload as ClientResponsePayload,
|
||||
},
|
||||
transport::expect_message,
|
||||
transport::{Bi, expect_message},
|
||||
};
|
||||
use diesel::{
|
||||
ExpressionMethods as _, OptionalExtension as _, QueryDsl as _, dsl::insert_into, update,
|
||||
};
|
||||
use diesel::{ExpressionMethods as _, OptionalExtension as _, QueryDsl as _, update};
|
||||
use diesel_async::RunQueryDsl as _;
|
||||
use ed25519_dalek::VerifyingKey;
|
||||
use ed25519_dalek::{Signature, VerifyingKey};
|
||||
use kameo::error::SendError;
|
||||
use tracing::error;
|
||||
|
||||
use crate::{
|
||||
actors::client::ClientConnection,
|
||||
actors::{
|
||||
client::ClientConnection,
|
||||
router::{self, RequestClientApproval},
|
||||
},
|
||||
db::{self, schema::program_client},
|
||||
};
|
||||
|
||||
use super::session::ClientSession;
|
||||
|
||||
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
#[error("Unexpected message payload")]
|
||||
UnexpectedMessagePayload,
|
||||
#[error("Invalid client public key length")]
|
||||
InvalidClientPubkeyLength,
|
||||
#[error("Invalid client public key encoding")]
|
||||
InvalidAuthPubkeyEncoding,
|
||||
#[error("Database pool unavailable")]
|
||||
DatabasePoolUnavailable,
|
||||
#[error("Database operation failed")]
|
||||
DatabaseOperationFailed,
|
||||
#[error("Invalid challenge solution")]
|
||||
InvalidChallengeSolution,
|
||||
#[error("Client not registered")]
|
||||
NotRegistered,
|
||||
#[error("Internal error")]
|
||||
InternalError,
|
||||
#[error("Client approval request failed")]
|
||||
ApproveError(#[from] ApproveError),
|
||||
#[error("Transport error")]
|
||||
Transport,
|
||||
}
|
||||
|
||||
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ApproveError {
|
||||
#[error("Internal error")]
|
||||
Internal,
|
||||
#[error("Client connection denied by user agents")]
|
||||
Denied,
|
||||
#[error("Upstream error: {0}")]
|
||||
Upstream(router::ApprovalError),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Inbound {
|
||||
AuthChallengeRequest { pubkey: VerifyingKey },
|
||||
AuthChallengeSolution { signature: Signature },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Outbound {
|
||||
AuthChallenge { pubkey: VerifyingKey, nonce: i32 },
|
||||
AuthSuccess,
|
||||
}
|
||||
|
||||
/// Atomically reads and increments the nonce for a known client.
|
||||
/// Returns `None` if the pubkey is not registered.
|
||||
async fn get_nonce(
|
||||
db: &db::DatabasePool,
|
||||
pubkey: &VerifyingKey,
|
||||
) -> Result<Option<(i32, i32)>, Error> {
|
||||
async fn get_nonce(db: &db::DatabasePool, pubkey: &VerifyingKey) -> Result<Option<i32>, Error> {
|
||||
let pubkey_bytes = pubkey.as_bytes().to_vec();
|
||||
|
||||
let mut conn = db.get().await.map_err(|e| {
|
||||
@@ -74,7 +83,8 @@ async fn get_nonce(
|
||||
.execute(conn)
|
||||
.await?;
|
||||
|
||||
Ok(Some((client_id, current_nonce)))
|
||||
let _ = client_id;
|
||||
Ok(Some(current_nonce))
|
||||
})
|
||||
})
|
||||
.await
|
||||
@@ -84,47 +94,115 @@ async fn get_nonce(
|
||||
})
|
||||
}
|
||||
|
||||
async fn challenge_client(
|
||||
props: &mut ClientConnection,
|
||||
async fn approve_new_client(
|
||||
actors: &crate::actors::GlobalActors,
|
||||
pubkey: VerifyingKey,
|
||||
) -> Result<(), Error> {
|
||||
let result = actors
|
||||
.router
|
||||
.ask(RequestClientApproval {
|
||||
client_pubkey: pubkey,
|
||||
})
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Ok(true) => Ok(()),
|
||||
Ok(false) => Err(Error::ApproveError(ApproveError::Denied)),
|
||||
Err(SendError::HandlerError(e)) => {
|
||||
error!(error = ?e, "Approval upstream error");
|
||||
Err(Error::ApproveError(ApproveError::Upstream(e)))
|
||||
}
|
||||
Err(e) => {
|
||||
error!(error = ?e, "Approval request to router failed");
|
||||
Err(Error::ApproveError(ApproveError::Internal))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum InsertClientResult {
|
||||
Inserted,
|
||||
AlreadyExists,
|
||||
}
|
||||
|
||||
async fn insert_client(
|
||||
db: &db::DatabasePool,
|
||||
pubkey: &VerifyingKey,
|
||||
) -> Result<InsertClientResult, Error> {
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs() as i32;
|
||||
|
||||
let mut conn = db.get().await.map_err(|e| {
|
||||
error!(error = ?e, "Database pool error");
|
||||
Error::DatabasePoolUnavailable
|
||||
})?;
|
||||
|
||||
match insert_into(program_client::table)
|
||||
.values((
|
||||
program_client::public_key.eq(pubkey.as_bytes().to_vec()),
|
||||
program_client::nonce.eq(1), // pre-incremented; challenge uses 0
|
||||
program_client::created_at.eq(now),
|
||||
program_client::updated_at.eq(now),
|
||||
))
|
||||
.execute(&mut conn)
|
||||
.await
|
||||
{
|
||||
Ok(_) => {}
|
||||
Err(diesel::result::Error::DatabaseError(
|
||||
diesel::result::DatabaseErrorKind::UniqueViolation,
|
||||
_,
|
||||
)) => return Ok(InsertClientResult::AlreadyExists),
|
||||
Err(e) => {
|
||||
error!(error = ?e, "Failed to insert new client");
|
||||
return Err(Error::DatabaseOperationFailed);
|
||||
}
|
||||
}
|
||||
|
||||
let client_id = program_client::table
|
||||
.filter(program_client::public_key.eq(pubkey.as_bytes().to_vec()))
|
||||
.order(program_client::id.desc())
|
||||
.select(program_client::id)
|
||||
.first::<i32>(&mut conn)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!(error = ?e, "Failed to load inserted client id");
|
||||
Error::DatabaseOperationFailed
|
||||
})?;
|
||||
|
||||
let _ = client_id;
|
||||
Ok(InsertClientResult::Inserted)
|
||||
}
|
||||
|
||||
async fn challenge_client<T>(
|
||||
transport: &mut T,
|
||||
pubkey: VerifyingKey,
|
||||
nonce: i32,
|
||||
) -> Result<(), Error> {
|
||||
let challenge = AuthChallenge {
|
||||
pubkey: pubkey.as_bytes().to_vec(),
|
||||
nonce,
|
||||
};
|
||||
|
||||
props
|
||||
.transport
|
||||
.send(Ok(ClientResponse {
|
||||
payload: Some(ClientResponsePayload::AuthChallenge(challenge.clone())),
|
||||
}))
|
||||
) -> Result<(), Error>
|
||||
where
|
||||
T: Bi<Inbound, Result<Outbound, Error>> + ?Sized,
|
||||
{
|
||||
transport
|
||||
.send(Ok(Outbound::AuthChallenge { pubkey, nonce }))
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!(error = ?e, "Failed to send auth challenge");
|
||||
Error::Transport
|
||||
})?;
|
||||
|
||||
let AuthChallengeSolution { signature } =
|
||||
expect_message(&mut *props.transport, |req: ClientRequest| {
|
||||
match req.payload? {
|
||||
ClientRequestPayload::AuthChallengeSolution(s) => Some(s),
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!(error = ?e, "Failed to receive challenge solution");
|
||||
Error::Transport
|
||||
})?;
|
||||
|
||||
let formatted = format_challenge(nonce, &challenge.pubkey);
|
||||
let sig = signature.as_slice().try_into().map_err(|_| {
|
||||
error!("Invalid signature length");
|
||||
Error::InvalidChallengeSolution
|
||||
let signature = expect_message(transport, |req: Inbound| match req {
|
||||
Inbound::AuthChallengeSolution { signature } => Some(signature),
|
||||
_ => None,
|
||||
})
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!(error = ?e, "Failed to receive challenge solution");
|
||||
Error::Transport
|
||||
})?;
|
||||
|
||||
pubkey.verify_strict(&formatted, &sig).map_err(|_| {
|
||||
let formatted = format_challenge(nonce, pubkey.as_bytes());
|
||||
|
||||
pubkey.verify_strict(&formatted, &signature).map_err(|_| {
|
||||
error!("Challenge solution verification failed");
|
||||
Error::InvalidChallengeSolution
|
||||
})?;
|
||||
@@ -132,52 +210,40 @@ async fn challenge_client(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn connect_error_code(err: &Error) -> ConnectErrorCode {
|
||||
match err {
|
||||
Error::NotRegistered => ConnectErrorCode::ApprovalDenied,
|
||||
_ => ConnectErrorCode::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
async fn authenticate(props: &mut ClientConnection) -> Result<(VerifyingKey, i32), Error> {
|
||||
let Some(ClientRequest {
|
||||
payload: Some(ClientRequestPayload::AuthChallengeRequest(challenge)),
|
||||
}) = props.transport.recv().await
|
||||
pub async fn authenticate<T>(
|
||||
props: &mut ClientConnection,
|
||||
transport: &mut T,
|
||||
) -> Result<VerifyingKey, Error>
|
||||
where
|
||||
T: Bi<Inbound, Result<Outbound, Error>> + Send + ?Sized,
|
||||
{
|
||||
let Some(Inbound::AuthChallengeRequest { pubkey }) = transport.recv().await
|
||||
else {
|
||||
return Err(Error::Transport);
|
||||
};
|
||||
|
||||
let pubkey_bytes = challenge
|
||||
.pubkey
|
||||
.as_array()
|
||||
.ok_or(Error::InvalidClientPubkeyLength)?;
|
||||
let pubkey =
|
||||
VerifyingKey::from_bytes(pubkey_bytes).map_err(|_| Error::InvalidAuthPubkeyEncoding)?;
|
||||
|
||||
let (client_id, nonce) = match get_nonce(&props.db, &pubkey).await? {
|
||||
Some((client_id, nonce)) => (client_id, nonce),
|
||||
None => return Err(Error::NotRegistered),
|
||||
let nonce = match get_nonce(&props.db, &pubkey).await? {
|
||||
Some(nonce) => nonce,
|
||||
None => {
|
||||
approve_new_client(&props.actors, pubkey).await?;
|
||||
match insert_client(&props.db, &pubkey).await? {
|
||||
InsertClientResult::Inserted => 0,
|
||||
InsertClientResult::AlreadyExists => match get_nonce(&props.db, &pubkey).await? {
|
||||
Some(nonce) => nonce,
|
||||
None => return Err(Error::DatabaseOperationFailed),
|
||||
},
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
challenge_client(props, pubkey, nonce).await?;
|
||||
challenge_client(transport, pubkey, nonce).await?;
|
||||
transport
|
||||
.send(Ok(Outbound::AuthSuccess))
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!(error = ?e, "Failed to send auth success");
|
||||
Error::Transport
|
||||
})?;
|
||||
|
||||
Ok((pubkey, client_id))
|
||||
}
|
||||
|
||||
pub async fn authenticate_and_create(mut props: ClientConnection) -> Result<ClientSession, Error> {
|
||||
match authenticate(&mut props).await {
|
||||
Ok((_pubkey, client_id)) => Ok(ClientSession::new(props, client_id)),
|
||||
Err(err) => {
|
||||
let code = connect_error_code(&err);
|
||||
let _ = props
|
||||
.transport
|
||||
.send(Ok(ClientResponse {
|
||||
payload: Some(ClientResponsePayload::ClientConnectError(
|
||||
ClientConnectError { code: code.into() },
|
||||
)),
|
||||
}))
|
||||
.await;
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
Ok(pubkey)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
use arbiter_proto::{
|
||||
proto::client::{ClientRequest, ClientResponse},
|
||||
transport::Bi,
|
||||
};
|
||||
use arbiter_proto::transport::Bi;
|
||||
use kameo::actor::Spawn;
|
||||
use tracing::{error, info};
|
||||
|
||||
@@ -10,48 +7,31 @@ use crate::{
|
||||
db,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum ClientError {
|
||||
#[error("Expected message with payload")]
|
||||
MissingRequestPayload,
|
||||
#[error("Unexpected request payload")]
|
||||
UnexpectedRequestPayload,
|
||||
#[error("State machine error")]
|
||||
StateTransitionFailed,
|
||||
#[error("Connection registration failed")]
|
||||
ConnectionRegistrationFailed,
|
||||
#[error(transparent)]
|
||||
Auth(#[from] auth::Error),
|
||||
}
|
||||
|
||||
pub type Transport = Box<dyn Bi<ClientRequest, Result<ClientResponse, ClientError>> + Send>;
|
||||
|
||||
pub struct ClientConnection {
|
||||
pub(crate) db: db::DatabasePool,
|
||||
pub(crate) transport: Transport,
|
||||
pub(crate) actors: GlobalActors,
|
||||
}
|
||||
|
||||
impl ClientConnection {
|
||||
pub fn new(db: db::DatabasePool, transport: Transport, actors: GlobalActors) -> Self {
|
||||
Self {
|
||||
db,
|
||||
transport,
|
||||
actors,
|
||||
}
|
||||
pub fn new(db: db::DatabasePool, actors: GlobalActors) -> Self {
|
||||
Self { db, actors }
|
||||
}
|
||||
}
|
||||
|
||||
pub mod auth;
|
||||
pub mod session;
|
||||
|
||||
pub async fn connect_client(props: ClientConnection) {
|
||||
match auth::authenticate_and_create(props).await {
|
||||
Ok(session) => {
|
||||
ClientSession::spawn(session);
|
||||
pub async fn connect_client<T>(mut props: ClientConnection, transport: &mut T)
|
||||
where
|
||||
T: Bi<auth::Inbound, Result<auth::Outbound, auth::Error>> + Send + ?Sized,
|
||||
{
|
||||
match auth::authenticate(&mut props, transport).await {
|
||||
Ok(_pubkey) => {
|
||||
ClientSession::spawn(ClientSession::new(props));
|
||||
info!("Client authenticated, session started");
|
||||
}
|
||||
Err(err) => {
|
||||
let _ = transport.send(Err(err.clone())).await;
|
||||
error!(?err, "Authentication failed, closing connection");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,92 +1,45 @@
|
||||
use alloy::{consensus::TxEip1559, primitives::Address, rlp::Decodable};
|
||||
use arbiter_proto::proto::{
|
||||
client::{
|
||||
ClientRequest, ClientResponse, client_request::Payload as ClientRequestPayload,
|
||||
client_response::Payload as ClientResponsePayload,
|
||||
},
|
||||
evm::{
|
||||
EvmError, EvmSignTransactionResponse, evm_sign_transaction_response::Result as SignResult,
|
||||
},
|
||||
};
|
||||
use kameo::Actor;
|
||||
use tokio::select;
|
||||
use tracing::{error, info};
|
||||
use kameo::{Actor, messages};
|
||||
use tracing::error;
|
||||
|
||||
use crate::{
|
||||
actors::{
|
||||
GlobalActors,
|
||||
client::{ClientConnection, ClientError},
|
||||
evm::ClientSignTransaction,
|
||||
router::RegisterClient,
|
||||
GlobalActors, client::ClientConnection, keyholder::KeyHolderState, router::RegisterClient,
|
||||
},
|
||||
db,
|
||||
};
|
||||
|
||||
pub struct ClientSession {
|
||||
props: ClientConnection,
|
||||
client_id: i32,
|
||||
}
|
||||
|
||||
impl ClientSession {
|
||||
pub(crate) fn new(props: ClientConnection, client_id: i32) -> Self {
|
||||
Self { props, client_id }
|
||||
}
|
||||
|
||||
pub async fn process_transport_inbound(&mut self, req: ClientRequest) -> Output {
|
||||
let msg = req.payload.ok_or_else(|| {
|
||||
error!(actor = "client", "Received message with no payload");
|
||||
ClientError::MissingRequestPayload
|
||||
})?;
|
||||
|
||||
match msg {
|
||||
ClientRequestPayload::EvmSignTransaction(sign_req) => {
|
||||
let wallet_address: [u8; 20] = sign_req
|
||||
.wallet_address
|
||||
.try_into()
|
||||
.map_err(|_| ClientError::UnexpectedRequestPayload)?;
|
||||
|
||||
let mut rlp_bytes: &[u8] = &sign_req.rlp_transaction;
|
||||
let tx = TxEip1559::decode(&mut rlp_bytes)
|
||||
.map_err(|_| ClientError::UnexpectedRequestPayload)?;
|
||||
|
||||
let result = self
|
||||
.props
|
||||
.actors
|
||||
.evm
|
||||
.ask(ClientSignTransaction {
|
||||
client_id: self.client_id,
|
||||
wallet_address: Address::from_slice(&wallet_address),
|
||||
transaction: tx,
|
||||
})
|
||||
.await;
|
||||
|
||||
let response_result = match result {
|
||||
Ok(signature) => SignResult::Signature(signature.as_bytes().to_vec()),
|
||||
Err(err) => {
|
||||
error!(?err, "client sign transaction failed");
|
||||
SignResult::Error(EvmError::Internal.into())
|
||||
}
|
||||
};
|
||||
|
||||
Ok(ClientResponse {
|
||||
payload: Some(ClientResponsePayload::EvmSignTransaction(
|
||||
EvmSignTransactionResponse {
|
||||
result: Some(response_result),
|
||||
},
|
||||
)),
|
||||
})
|
||||
}
|
||||
_ => Err(ClientError::UnexpectedRequestPayload),
|
||||
}
|
||||
pub(crate) fn new(props: ClientConnection) -> Self {
|
||||
Self { props }
|
||||
}
|
||||
}
|
||||
|
||||
type Output = Result<ClientResponse, ClientError>;
|
||||
#[messages]
|
||||
impl ClientSession {
|
||||
#[message]
|
||||
pub(crate) async fn handle_query_vault_state(&mut self) -> Result<KeyHolderState, Error> {
|
||||
use crate::actors::keyholder::GetState;
|
||||
|
||||
let vault_state = match self.props.actors.key_holder.ask(GetState {}).await {
|
||||
Ok(state) => state,
|
||||
Err(err) => {
|
||||
error!(?err, actor = "client", "keyholder.query.failed");
|
||||
return Err(Error::Internal);
|
||||
}
|
||||
};
|
||||
|
||||
Ok(vault_state)
|
||||
}
|
||||
}
|
||||
|
||||
impl Actor for ClientSession {
|
||||
type Args = Self;
|
||||
|
||||
type Error = ClientError;
|
||||
type Error = Error;
|
||||
|
||||
async fn on_start(
|
||||
args: Self::Args,
|
||||
@@ -97,55 +50,22 @@ impl Actor for ClientSession {
|
||||
.router
|
||||
.ask(RegisterClient { actor: this })
|
||||
.await
|
||||
.map_err(|_| ClientError::ConnectionRegistrationFailed)?;
|
||||
.map_err(|_| Error::ConnectionRegistrationFailed)?;
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
async fn next(
|
||||
&mut self,
|
||||
_actor_ref: kameo::prelude::WeakActorRef<Self>,
|
||||
mailbox_rx: &mut kameo::prelude::MailboxReceiver<Self>,
|
||||
) -> Option<kameo::mailbox::Signal<Self>> {
|
||||
loop {
|
||||
select! {
|
||||
signal = mailbox_rx.recv() => {
|
||||
return signal;
|
||||
}
|
||||
msg = self.props.transport.recv() => {
|
||||
match msg {
|
||||
Some(request) => {
|
||||
match self.process_transport_inbound(request).await {
|
||||
Ok(resp) => {
|
||||
if self.props.transport.send(Ok(resp)).await.is_err() {
|
||||
error!(actor = "client", reason = "channel closed", "send.failed");
|
||||
return Some(kameo::mailbox::Signal::Stop);
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
let _ = self.props.transport.send(Err(err)).await;
|
||||
return Some(kameo::mailbox::Signal::Stop);
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
info!(actor = "client", "transport.closed");
|
||||
return Some(kameo::mailbox::Signal::Stop);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientSession {
|
||||
pub fn new_test(db: db::DatabasePool, actors: GlobalActors) -> Self {
|
||||
use arbiter_proto::transport::DummyTransport;
|
||||
let transport: super::Transport = Box::new(DummyTransport::new());
|
||||
let props = ClientConnection::new(db, transport, actors);
|
||||
Self {
|
||||
props,
|
||||
client_id: 0,
|
||||
}
|
||||
let props = ClientConnection::new(db, actors);
|
||||
Self { props }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
#[error("Connection registration failed")]
|
||||
ConnectionRegistrationFailed,
|
||||
#[error("Internal error")]
|
||||
Internal,
|
||||
}
|
||||
|
||||
@@ -1,21 +1,26 @@
|
||||
use alloy::{consensus::TxEip1559, primitives::Address, signers::Signature};
|
||||
use diesel::{ExpressionMethods, OptionalExtension as _, QueryDsl, SelectableHelper as _, dsl::insert_into};
|
||||
use diesel::{
|
||||
ExpressionMethods, OptionalExtension as _, QueryDsl, SelectableHelper as _, dsl::insert_into,
|
||||
};
|
||||
use diesel_async::RunQueryDsl;
|
||||
use kameo::{Actor, actor::ActorRef, messages};
|
||||
use memsafe::MemSafe;
|
||||
use rand::{SeedableRng, rng, rngs::StdRng};
|
||||
|
||||
use crate::{
|
||||
actors::keyholder::{CreateNew, Decrypt, KeyHolder},
|
||||
db::{self, DatabasePool, models::{self, EvmBasicGrant, SqliteTimestamp}, schema},
|
||||
db::{
|
||||
self, DatabasePool,
|
||||
models::{self, SqliteTimestamp},
|
||||
schema,
|
||||
},
|
||||
evm::{
|
||||
self, RunKind,
|
||||
self, ListGrantsError, RunKind,
|
||||
policies::{
|
||||
FullGrant, SharedGrantSettings, SpecificGrant, SpecificMeaning,
|
||||
ether_transfer::EtherTransfer,
|
||||
token_transfers::TokenTransfer,
|
||||
FullGrant, Grant, SharedGrantSettings, SpecificGrant, SpecificMeaning,
|
||||
ether_transfer::EtherTransfer, token_transfers::TokenTransfer,
|
||||
},
|
||||
},
|
||||
safe_cell::{SafeCell, SafeCellHandle as _},
|
||||
};
|
||||
|
||||
pub use crate::evm::safe_signer;
|
||||
@@ -88,7 +93,12 @@ impl EvmActor {
|
||||
// todo: audit
|
||||
let rng = StdRng::from_rng(&mut rng());
|
||||
let engine = evm::Engine::new(db.clone());
|
||||
Self { keyholder, db, rng, engine }
|
||||
Self {
|
||||
keyholder,
|
||||
db,
|
||||
rng,
|
||||
engine,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,11 +108,7 @@ impl EvmActor {
|
||||
pub async fn generate(&mut self) -> Result<Address, Error> {
|
||||
let (mut key_cell, address) = safe_signer::generate(&mut self.rng);
|
||||
|
||||
// Move raw key bytes into a Vec<u8> MemSafe for KeyHolder
|
||||
let plaintext = {
|
||||
let reader = key_cell.read().expect("MemSafe read");
|
||||
MemSafe::new(reader.to_vec()).expect("MemSafe allocation")
|
||||
};
|
||||
let plaintext = key_cell.read_inline(|reader| SafeCell::new(reader.to_vec()));
|
||||
|
||||
let aead_id: i32 = self
|
||||
.keyholder
|
||||
@@ -149,12 +155,24 @@ impl EvmActor {
|
||||
match grant {
|
||||
SpecificGrant::EtherTransfer(settings) => {
|
||||
self.engine
|
||||
.create_grant::<EtherTransfer>(client_id, FullGrant { basic, specific: settings })
|
||||
.create_grant::<EtherTransfer>(
|
||||
client_id,
|
||||
FullGrant {
|
||||
basic,
|
||||
specific: settings,
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
SpecificGrant::TokenTransfer(settings) => {
|
||||
self.engine
|
||||
.create_grant::<TokenTransfer>(client_id, FullGrant { basic, specific: settings })
|
||||
.create_grant::<TokenTransfer>(
|
||||
client_id,
|
||||
FullGrant {
|
||||
basic,
|
||||
specific: settings,
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
@@ -172,19 +190,12 @@ impl EvmActor {
|
||||
}
|
||||
|
||||
#[message]
|
||||
pub async fn useragent_list_grants(
|
||||
&mut self,
|
||||
wallet_id: Option<i32>,
|
||||
) -> Result<Vec<EvmBasicGrant>, Error> {
|
||||
let mut conn = self.db.get().await?;
|
||||
let mut query = schema::evm_basic_grant::table
|
||||
.select(EvmBasicGrant::as_select())
|
||||
.filter(schema::evm_basic_grant::revoked_at.is_null())
|
||||
.into_boxed();
|
||||
if let Some(wid) = wallet_id {
|
||||
query = query.filter(schema::evm_basic_grant::wallet_id.eq(wid));
|
||||
pub async fn useragent_list_grants(&mut self) -> Result<Vec<Grant<SpecificGrant>>, Error> {
|
||||
match self.engine.list_all_grants().await {
|
||||
Ok(grants) => Ok(grants),
|
||||
Err(ListGrantsError::Database(db)) => Err(Error::Database(db)),
|
||||
Err(ListGrantsError::Pool(pool)) => Err(Error::DatabasePool(pool)),
|
||||
}
|
||||
Ok(query.load(&mut conn).await?)
|
||||
}
|
||||
|
||||
#[message]
|
||||
@@ -204,8 +215,14 @@ impl EvmActor {
|
||||
.ok_or(SignTransactionError::WalletNotFound)?;
|
||||
drop(conn);
|
||||
|
||||
let meaning = self.engine
|
||||
.evaluate_transaction(wallet.id, client_id, transaction.clone(), RunKind::Execution)
|
||||
let meaning = self
|
||||
.engine
|
||||
.evaluate_transaction(
|
||||
wallet.id,
|
||||
client_id,
|
||||
transaction.clone(),
|
||||
RunKind::Execution,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(meaning)
|
||||
@@ -228,16 +245,23 @@ impl EvmActor {
|
||||
.ok_or(SignTransactionError::WalletNotFound)?;
|
||||
drop(conn);
|
||||
|
||||
let raw_key: MemSafe<Vec<u8>> = self
|
||||
let raw_key: SafeCell<Vec<u8>> = self
|
||||
.keyholder
|
||||
.ask(Decrypt { aead_id: wallet.aead_encrypted_id })
|
||||
.ask(Decrypt {
|
||||
aead_id: wallet.aead_encrypted_id,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| SignTransactionError::KeyholderSend)?;
|
||||
|
||||
let signer = safe_signer::SafeSigner::from_memsafe(raw_key)?;
|
||||
let signer = safe_signer::SafeSigner::from_cell(raw_key)?;
|
||||
|
||||
self.engine
|
||||
.evaluate_transaction(wallet.id, client_id, transaction.clone(), RunKind::Execution)
|
||||
.evaluate_transaction(
|
||||
wallet.id,
|
||||
client_id,
|
||||
transaction.clone(),
|
||||
RunKind::Execution,
|
||||
)
|
||||
.await?;
|
||||
|
||||
use alloy::network::TxSignerSync as _;
|
||||
|
||||
@@ -5,12 +5,13 @@ use chacha20poly1305::{
|
||||
AeadInPlace, Key, KeyInit as _, XChaCha20Poly1305, XNonce,
|
||||
aead::{AeadMut, Error, Payload},
|
||||
};
|
||||
use memsafe::MemSafe;
|
||||
use rand::{
|
||||
Rng as _, SeedableRng,
|
||||
rngs::{StdRng, SysRng},
|
||||
};
|
||||
|
||||
use crate::safe_cell::{SafeCell, SafeCellHandle as _};
|
||||
|
||||
pub const ROOT_KEY_TAG: &[u8] = "arbiter/seal/v1".as_bytes();
|
||||
pub const TAG: &[u8] = "arbiter/private-key/v1".as_bytes();
|
||||
|
||||
@@ -47,40 +48,37 @@ impl<'a> TryFrom<&'a [u8]> for Nonce {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct KeyCell(pub MemSafe<Key>);
|
||||
impl From<MemSafe<Key>> for KeyCell {
|
||||
fn from(value: MemSafe<Key>) -> Self {
|
||||
pub struct KeyCell(pub SafeCell<Key>);
|
||||
impl From<SafeCell<Key>> for KeyCell {
|
||||
fn from(value: SafeCell<Key>) -> Self {
|
||||
Self(value)
|
||||
}
|
||||
}
|
||||
impl TryFrom<MemSafe<Vec<u8>>> for KeyCell {
|
||||
impl TryFrom<SafeCell<Vec<u8>>> for KeyCell {
|
||||
type Error = ();
|
||||
|
||||
fn try_from(mut value: MemSafe<Vec<u8>>) -> Result<Self, Self::Error> {
|
||||
let value = value.read().unwrap();
|
||||
fn try_from(mut value: SafeCell<Vec<u8>>) -> Result<Self, Self::Error> {
|
||||
let value = value.read();
|
||||
if value.len() != size_of::<Key>() {
|
||||
return Err(());
|
||||
}
|
||||
let mut cell = MemSafe::new(Key::default()).unwrap();
|
||||
{
|
||||
let mut cell_write = cell.write().unwrap();
|
||||
let cell_slice: &mut [u8] = cell_write.as_mut();
|
||||
cell_slice.copy_from_slice(&value);
|
||||
}
|
||||
let cell = SafeCell::new_inline(|cell_write: &mut Key| {
|
||||
cell_write.copy_from_slice(&value);
|
||||
});
|
||||
Ok(Self(cell))
|
||||
}
|
||||
}
|
||||
|
||||
impl KeyCell {
|
||||
pub fn new_secure_random() -> Self {
|
||||
let mut key = MemSafe::new(Key::default()).unwrap();
|
||||
{
|
||||
let mut key_buffer = key.write().unwrap();
|
||||
let key_buffer: &mut [u8] = key_buffer.as_mut();
|
||||
|
||||
let key = SafeCell::new_inline(|key_buffer: &mut Key| {
|
||||
#[allow(
|
||||
clippy::unwrap_used,
|
||||
reason = "Rng failure is unrecoverable and should panic"
|
||||
)]
|
||||
let mut rng = StdRng::try_from_rng(&mut SysRng).unwrap();
|
||||
rng.fill_bytes(key_buffer);
|
||||
}
|
||||
});
|
||||
|
||||
key.into()
|
||||
}
|
||||
@@ -91,7 +89,7 @@ impl KeyCell {
|
||||
associated_data: &[u8],
|
||||
mut buffer: impl AsMut<Vec<u8>>,
|
||||
) -> Result<(), Error> {
|
||||
let key_reader = self.0.read().unwrap();
|
||||
let key_reader = self.0.read();
|
||||
let key_ref = key_reader.deref();
|
||||
let cipher = XChaCha20Poly1305::new(key_ref);
|
||||
let nonce = XNonce::from_slice(nonce.0.as_ref());
|
||||
@@ -102,13 +100,13 @@ impl KeyCell {
|
||||
&mut self,
|
||||
nonce: &Nonce,
|
||||
associated_data: &[u8],
|
||||
buffer: &mut MemSafe<Vec<u8>>,
|
||||
buffer: &mut SafeCell<Vec<u8>>,
|
||||
) -> Result<(), Error> {
|
||||
let key_reader = self.0.read().unwrap();
|
||||
let key_reader = self.0.read();
|
||||
let key_ref = key_reader.deref();
|
||||
let cipher = XChaCha20Poly1305::new(key_ref);
|
||||
let nonce = XNonce::from_slice(nonce.0.as_ref());
|
||||
let mut buffer = buffer.write().unwrap();
|
||||
let mut buffer = buffer.write();
|
||||
let buffer: &mut Vec<u8> = buffer.as_mut();
|
||||
cipher.decrypt_in_place(nonce, associated_data, buffer)
|
||||
}
|
||||
@@ -119,7 +117,7 @@ impl KeyCell {
|
||||
associated_data: &[u8],
|
||||
plaintext: impl AsRef<[u8]>,
|
||||
) -> Result<Vec<u8>, Error> {
|
||||
let key_reader = self.0.read().unwrap();
|
||||
let key_reader = self.0.read();
|
||||
let key_ref = key_reader.deref();
|
||||
let mut cipher = XChaCha20Poly1305::new(key_ref);
|
||||
let nonce = XNonce::from_slice(nonce.0.as_ref());
|
||||
@@ -139,6 +137,10 @@ pub type Salt = [u8; ArgonSalt::RECOMMENDED_LENGTH];
|
||||
|
||||
pub fn generate_salt() -> Salt {
|
||||
let mut salt = Salt::default();
|
||||
#[allow(
|
||||
clippy::unwrap_used,
|
||||
reason = "Rng failure is unrecoverable and should panic"
|
||||
)]
|
||||
let mut rng = StdRng::try_from_rng(&mut SysRng).unwrap();
|
||||
rng.fill_bytes(&mut salt);
|
||||
salt
|
||||
@@ -146,19 +148,23 @@ pub fn generate_salt() -> Salt {
|
||||
|
||||
/// 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.
|
||||
pub fn derive_seal_key(mut password: MemSafe<Vec<u8>>, salt: &Salt) -> KeyCell {
|
||||
pub fn derive_seal_key(mut password: SafeCell<Vec<u8>>, salt: &Salt) -> KeyCell {
|
||||
#[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 mut key = MemSafe::new(Key::default()).unwrap();
|
||||
{
|
||||
let password_source = password.read().unwrap();
|
||||
let mut key_buffer = key.write().unwrap();
|
||||
let mut key = SafeCell::new(Key::default());
|
||||
password.read_inline(|password_source| {
|
||||
let mut key_buffer = key.write();
|
||||
let key_buffer: &mut [u8] = key_buffer.as_mut();
|
||||
|
||||
#[allow(
|
||||
clippy::unwrap_used,
|
||||
reason = "Better fail completely than return a weak key"
|
||||
)]
|
||||
hasher
|
||||
.hash_password_into(password_source.deref(), salt, key_buffer)
|
||||
.unwrap();
|
||||
}
|
||||
});
|
||||
|
||||
key.into()
|
||||
}
|
||||
@@ -166,20 +172,20 @@ pub fn derive_seal_key(mut password: MemSafe<Vec<u8>>, salt: &Salt) -> KeyCell {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use memsafe::MemSafe;
|
||||
use crate::safe_cell::SafeCell;
|
||||
|
||||
#[test]
|
||||
pub fn derive_seal_key_deterministic() {
|
||||
static PASSWORD: &[u8] = b"password";
|
||||
let password = MemSafe::new(PASSWORD.to_vec()).unwrap();
|
||||
let password2 = MemSafe::new(PASSWORD.to_vec()).unwrap();
|
||||
let password = SafeCell::new(PASSWORD.to_vec());
|
||||
let password2 = SafeCell::new(PASSWORD.to_vec());
|
||||
let salt = generate_salt();
|
||||
|
||||
let mut key1 = derive_seal_key(password, &salt);
|
||||
let mut key2 = derive_seal_key(password2, &salt);
|
||||
|
||||
let key1_reader = key1.0.read().unwrap();
|
||||
let key2_reader = key2.0.read().unwrap();
|
||||
let key1_reader = key1.0.read();
|
||||
let key2_reader = key2.0.read();
|
||||
|
||||
assert_eq!(key1_reader.deref(), key2_reader.deref());
|
||||
}
|
||||
@@ -187,11 +193,11 @@ mod tests {
|
||||
#[test]
|
||||
pub fn successful_derive() {
|
||||
static PASSWORD: &[u8] = b"password";
|
||||
let password = MemSafe::new(PASSWORD.to_vec()).unwrap();
|
||||
let password = SafeCell::new(PASSWORD.to_vec());
|
||||
let salt = generate_salt();
|
||||
|
||||
let mut key = derive_seal_key(password, &salt);
|
||||
let key_reader = key.0.read().unwrap();
|
||||
let key_reader = key.0.read();
|
||||
let key_ref = key_reader.deref();
|
||||
|
||||
assert_ne!(key_ref.as_slice(), &[0u8; 32][..]);
|
||||
@@ -200,7 +206,7 @@ mod tests {
|
||||
#[test]
|
||||
pub fn encrypt_decrypt() {
|
||||
static PASSWORD: &[u8] = b"password";
|
||||
let password = MemSafe::new(PASSWORD.to_vec()).unwrap();
|
||||
let password = SafeCell::new(PASSWORD.to_vec());
|
||||
let salt = generate_salt();
|
||||
|
||||
let mut key = derive_seal_key(password, &salt);
|
||||
@@ -212,12 +218,12 @@ mod tests {
|
||||
.unwrap();
|
||||
assert_ne!(buffer, b"secret data");
|
||||
|
||||
let mut buffer = MemSafe::new(buffer).unwrap();
|
||||
let mut buffer = SafeCell::new(buffer);
|
||||
|
||||
key.decrypt_in_place(&nonce, associated_data, &mut buffer)
|
||||
.unwrap();
|
||||
|
||||
let buffer = buffer.read().unwrap();
|
||||
let buffer = buffer.read();
|
||||
assert_eq!(*buffer, b"secret data");
|
||||
}
|
||||
|
||||
|
||||
@@ -5,21 +5,24 @@ use diesel::{
|
||||
};
|
||||
use diesel_async::{AsyncConnection, RunQueryDsl};
|
||||
use kameo::{Actor, Reply, messages};
|
||||
use memsafe::MemSafe;
|
||||
use strum::{EnumDiscriminants, IntoDiscriminant};
|
||||
use tracing::{error, info};
|
||||
|
||||
use crate::db::{
|
||||
self,
|
||||
models::{self, RootKeyHistory},
|
||||
schema::{self},
|
||||
use crate::safe_cell::SafeCell;
|
||||
use crate::{
|
||||
db::{
|
||||
self,
|
||||
models::{self, RootKeyHistory},
|
||||
schema::{self},
|
||||
},
|
||||
safe_cell::SafeCellHandle as _,
|
||||
};
|
||||
use encryption::v1::{self, KeyCell, Nonce};
|
||||
|
||||
pub mod encryption;
|
||||
|
||||
#[derive(Default, EnumDiscriminants)]
|
||||
#[strum_discriminants(derive(Reply), vis(pub))]
|
||||
#[strum_discriminants(derive(Reply), vis(pub), name(KeyHolderState))]
|
||||
enum State {
|
||||
#[default]
|
||||
Unbootstrapped,
|
||||
@@ -136,7 +139,7 @@ impl KeyHolder {
|
||||
}
|
||||
|
||||
#[message]
|
||||
pub async fn bootstrap(&mut self, seal_key_raw: MemSafe<Vec<u8>>) -> Result<(), Error> {
|
||||
pub async fn bootstrap(&mut self, seal_key_raw: SafeCell<Vec<u8>>) -> Result<(), Error> {
|
||||
if !matches!(self.state, State::Unbootstrapped) {
|
||||
return Err(Error::AlreadyBootstrapped);
|
||||
}
|
||||
@@ -148,16 +151,15 @@ impl KeyHolder {
|
||||
let root_key_nonce = v1::Nonce::default();
|
||||
let data_encryption_nonce = v1::Nonce::default();
|
||||
|
||||
let root_key_ciphertext: Vec<u8> = {
|
||||
let root_key_reader = root_key.0.read().unwrap();
|
||||
let root_key_reader = root_key_reader.as_slice();
|
||||
let root_key_ciphertext: Vec<u8> = root_key.0.read_inline(|reader| {
|
||||
let root_key_reader = reader.as_slice();
|
||||
seal_key
|
||||
.encrypt(&root_key_nonce, v1::ROOT_KEY_TAG, root_key_reader)
|
||||
.map_err(|err| {
|
||||
error!(?err, "Fatal bootstrap error");
|
||||
Error::Encryption(err)
|
||||
})?
|
||||
};
|
||||
})
|
||||
})?;
|
||||
|
||||
let mut conn = self.db.get().await?;
|
||||
|
||||
@@ -199,7 +201,7 @@ impl KeyHolder {
|
||||
}
|
||||
|
||||
#[message]
|
||||
pub async fn try_unseal(&mut self, seal_key_raw: MemSafe<Vec<u8>>) -> Result<(), Error> {
|
||||
pub async fn try_unseal(&mut self, seal_key_raw: SafeCell<Vec<u8>>) -> Result<(), Error> {
|
||||
let State::Sealed {
|
||||
root_key_history_id,
|
||||
} = &self.state
|
||||
@@ -225,7 +227,7 @@ impl KeyHolder {
|
||||
})?;
|
||||
let mut seal_key = v1::derive_seal_key(seal_key_raw, &salt);
|
||||
|
||||
let mut root_key = MemSafe::new(current_key.ciphertext.clone()).unwrap();
|
||||
let mut root_key = SafeCell::new(current_key.ciphertext.clone());
|
||||
|
||||
let nonce = v1::Nonce::try_from(current_key.root_key_encryption_nonce.as_slice()).map_err(
|
||||
|_| {
|
||||
@@ -256,7 +258,7 @@ impl KeyHolder {
|
||||
|
||||
// Decrypts the `aead_encrypted` entry with the given ID and returns the plaintext
|
||||
#[message]
|
||||
pub async fn decrypt(&mut self, aead_id: i32) -> Result<MemSafe<Vec<u8>>, Error> {
|
||||
pub async fn decrypt(&mut self, aead_id: i32) -> Result<SafeCell<Vec<u8>>, Error> {
|
||||
let State::Unsealed { root_key, .. } = &mut self.state else {
|
||||
return Err(Error::NotBootstrapped);
|
||||
};
|
||||
@@ -279,14 +281,14 @@ impl KeyHolder {
|
||||
);
|
||||
Error::BrokenDatabase
|
||||
})?;
|
||||
let mut output = MemSafe::new(row.ciphertext).unwrap();
|
||||
let mut output = SafeCell::new(row.ciphertext);
|
||||
root_key.decrypt_in_place(&nonce, v1::TAG, &mut output)?;
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
// Creates new `aead_encrypted` entry in the database and returns it's ID
|
||||
#[message]
|
||||
pub async fn create_new(&mut self, mut plaintext: MemSafe<Vec<u8>>) -> Result<i32, Error> {
|
||||
pub async fn create_new(&mut self, mut plaintext: SafeCell<Vec<u8>>) -> Result<i32, Error> {
|
||||
let State::Unsealed {
|
||||
root_key,
|
||||
root_key_history_id,
|
||||
@@ -299,7 +301,7 @@ impl KeyHolder {
|
||||
// Borrow checker note: &mut borrow a few lines above is disjoint from this field
|
||||
let nonce = Self::get_new_nonce(&self.db, *root_key_history_id).await?;
|
||||
|
||||
let mut ciphertext_buffer = plaintext.write().unwrap();
|
||||
let mut ciphertext_buffer = plaintext.write();
|
||||
let ciphertext_buffer: &mut Vec<u8> = ciphertext_buffer.as_mut();
|
||||
root_key.encrypt_in_place(&nonce, v1::TAG, &mut *ciphertext_buffer)?;
|
||||
|
||||
@@ -313,7 +315,7 @@ impl KeyHolder {
|
||||
current_nonce: nonce.to_vec(),
|
||||
schema_version: 1,
|
||||
associated_root_key_id: *root_key_history_id,
|
||||
created_at: Utc::now().into()
|
||||
created_at: Utc::now().into(),
|
||||
})
|
||||
.returning(schema::aead_encrypted::id)
|
||||
.get_result(&mut conn)
|
||||
@@ -323,7 +325,7 @@ impl KeyHolder {
|
||||
}
|
||||
|
||||
#[message]
|
||||
pub fn get_state(&self) -> StateDiscriminants {
|
||||
pub fn get_state(&self) -> KeyHolderState {
|
||||
self.state.discriminant()
|
||||
}
|
||||
|
||||
@@ -348,15 +350,17 @@ mod tests {
|
||||
use diesel::SelectableHelper;
|
||||
|
||||
use diesel_async::RunQueryDsl;
|
||||
use memsafe::MemSafe;
|
||||
|
||||
use crate::db::{self};
|
||||
use crate::{
|
||||
db::{self},
|
||||
safe_cell::SafeCell,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
async fn bootstrapped_actor(db: &db::DatabasePool) -> KeyHolder {
|
||||
let mut actor = KeyHolder::new(db.clone()).await.unwrap();
|
||||
let seal_key = MemSafe::new(b"test-seal-key".to_vec()).unwrap();
|
||||
let seal_key = SafeCell::new(b"test-seal-key".to_vec());
|
||||
actor.bootstrap(seal_key).await.unwrap();
|
||||
actor
|
||||
}
|
||||
@@ -391,7 +395,7 @@ mod tests {
|
||||
assert_eq!(root_row.data_encryption_nonce, n2.to_vec());
|
||||
|
||||
let id = actor
|
||||
.create_new(MemSafe::new(b"post-interleave".to_vec()).unwrap())
|
||||
.create_new(SafeCell::new(b"post-interleave".to_vec()))
|
||||
.await
|
||||
.unwrap();
|
||||
let row: models::AeadEncrypted = schema::aead_encrypted::table
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
use std::{collections::HashMap, ops::ControlFlow};
|
||||
|
||||
use ed25519_dalek::VerifyingKey;
|
||||
use kameo::{
|
||||
Actor,
|
||||
actor::{ActorId, ActorRef},
|
||||
messages,
|
||||
prelude::{ActorStopReason, Context, WeakActorRef},
|
||||
reply::DelegatedReply,
|
||||
};
|
||||
use tracing::info;
|
||||
use tokio::{sync::watch, task::JoinSet};
|
||||
use tracing::{info, warn};
|
||||
|
||||
use crate::actors::{client::session::ClientSession, user_agent::session::UserAgentSession};
|
||||
use crate::actors::{
|
||||
client::session::ClientSession,
|
||||
user_agent::session::{RequestNewClientApproval, UserAgentSession},
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct MessageRouter {
|
||||
@@ -50,6 +56,73 @@ impl Actor for MessageRouter {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum ApprovalError {
|
||||
#[error("No user agents connected")]
|
||||
NoUserAgentsConnected,
|
||||
}
|
||||
|
||||
async fn request_client_approval(
|
||||
user_agents: &[WeakActorRef<UserAgentSession>],
|
||||
client_pubkey: VerifyingKey,
|
||||
) -> Result<bool, ApprovalError> {
|
||||
if user_agents.is_empty() {
|
||||
return Err(ApprovalError::NoUserAgentsConnected);
|
||||
}
|
||||
|
||||
let mut pool = JoinSet::new();
|
||||
let (cancel_tx, cancel_rx) = watch::channel(());
|
||||
|
||||
for weak_ref in user_agents {
|
||||
match weak_ref.upgrade() {
|
||||
Some(agent) => {
|
||||
let cancel_rx = cancel_rx.clone();
|
||||
pool.spawn(async move {
|
||||
agent
|
||||
.ask(RequestNewClientApproval {
|
||||
client_pubkey,
|
||||
cancel_flag: cancel_rx.clone(),
|
||||
})
|
||||
.await
|
||||
});
|
||||
}
|
||||
None => {
|
||||
warn!(
|
||||
id = weak_ref.id().to_string(),
|
||||
actor = "MessageRouter",
|
||||
event = "useragent.disconnected_before_approval"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
while let Some(result) = pool.join_next().await {
|
||||
match result {
|
||||
Ok(Ok(approved)) => {
|
||||
// cancel other pending requests
|
||||
let _ = cancel_tx.send(());
|
||||
return Ok(approved);
|
||||
}
|
||||
Ok(Err(err)) => {
|
||||
warn!(
|
||||
?err,
|
||||
actor = "MessageRouter",
|
||||
event = "useragent.approval_error"
|
||||
);
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(
|
||||
?err,
|
||||
actor = "MessageRouter",
|
||||
event = "useragent.approval_task_failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err(ApprovalError::NoUserAgentsConnected)
|
||||
}
|
||||
|
||||
#[messages]
|
||||
impl MessageRouter {
|
||||
#[message(ctx)]
|
||||
@@ -73,4 +146,28 @@ impl MessageRouter {
|
||||
ctx.actor_ref().link(&actor).await;
|
||||
self.clients.insert(actor.id(), actor);
|
||||
}
|
||||
|
||||
#[message(ctx)]
|
||||
pub async fn request_client_approval(
|
||||
&mut self,
|
||||
client_pubkey: VerifyingKey,
|
||||
ctx: &mut Context<Self, DelegatedReply<Result<bool, ApprovalError>>>,
|
||||
) -> DelegatedReply<Result<bool, ApprovalError>> {
|
||||
let (reply, Some(reply_sender)) = ctx.reply_sender() else {
|
||||
unreachable!("Expected `request_client_approval` to have callback channel");
|
||||
};
|
||||
|
||||
let weak_refs = self
|
||||
.user_agents
|
||||
.values()
|
||||
.map(|agent| agent.downgrade())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
tokio::task::spawn(async move {
|
||||
let result = request_client_approval(&weak_refs, client_pubkey).await;
|
||||
reply_sender.send(result);
|
||||
});
|
||||
|
||||
reply
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,114 +1,82 @@
|
||||
use arbiter_proto::proto::user_agent::{
|
||||
AuthChallengeRequest, AuthChallengeSolution, KeyType as ProtoKeyType, UserAgentRequest,
|
||||
user_agent_request::Payload as UserAgentRequestPayload,
|
||||
};
|
||||
use arbiter_proto::transport::Bi;
|
||||
use tracing::error;
|
||||
|
||||
use crate::actors::user_agent::{
|
||||
UserAgentConnection,
|
||||
auth::state::{AuthContext, AuthPublicKey, AuthStateMachine},
|
||||
session::UserAgentSession,
|
||||
AuthPublicKey, UserAgentConnection,
|
||||
auth::state::{AuthContext, AuthStateMachine},
|
||||
};
|
||||
|
||||
#[derive(thiserror::Error, Debug, PartialEq)]
|
||||
pub enum Error {
|
||||
#[error("Unexpected message payload")]
|
||||
UnexpectedMessagePayload,
|
||||
#[error("Invalid client public key length")]
|
||||
InvalidClientPubkeyLength,
|
||||
#[error("Invalid client public key encoding")]
|
||||
InvalidAuthPubkeyEncoding,
|
||||
#[error("Database pool unavailable")]
|
||||
DatabasePoolUnavailable,
|
||||
#[error("Database operation failed")]
|
||||
DatabaseOperationFailed,
|
||||
#[error("Public key not registered")]
|
||||
PublicKeyNotRegistered,
|
||||
#[error("Transport error")]
|
||||
Transport,
|
||||
#[error("Invalid bootstrap token")]
|
||||
InvalidBootstrapToken,
|
||||
#[error("Bootstrapper actor unreachable")]
|
||||
BootstrapperActorUnreachable,
|
||||
#[error("Invalid challenge solution")]
|
||||
InvalidChallengeSolution,
|
||||
}
|
||||
|
||||
mod state;
|
||||
use state::*;
|
||||
|
||||
fn parse_pubkey(key_type: ProtoKeyType, pubkey: Vec<u8>) -> Result<AuthPublicKey, Error> {
|
||||
match key_type {
|
||||
// UNSPECIFIED treated as Ed25519 for backward compatibility
|
||||
ProtoKeyType::Unspecified | ProtoKeyType::Ed25519 => {
|
||||
let pubkey_bytes = pubkey.as_array().ok_or(Error::InvalidClientPubkeyLength)?;
|
||||
let key = ed25519_dalek::VerifyingKey::from_bytes(pubkey_bytes)
|
||||
.map_err(|_| Error::InvalidAuthPubkeyEncoding)?;
|
||||
Ok(AuthPublicKey::Ed25519(key))
|
||||
}
|
||||
ProtoKeyType::EcdsaSecp256k1 => {
|
||||
// Public key is sent as 33-byte SEC1 compressed point
|
||||
let key = k256::ecdsa::VerifyingKey::from_sec1_bytes(&pubkey)
|
||||
.map_err(|_| Error::InvalidAuthPubkeyEncoding)?;
|
||||
Ok(AuthPublicKey::EcdsaSecp256k1(key))
|
||||
}
|
||||
ProtoKeyType::Rsa => {
|
||||
use rsa::pkcs8::DecodePublicKey as _;
|
||||
let key = rsa::RsaPublicKey::from_public_key_der(&pubkey)
|
||||
.map_err(|_| Error::InvalidAuthPubkeyEncoding)?;
|
||||
Ok(AuthPublicKey::Rsa(key))
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Inbound {
|
||||
AuthChallengeRequest {
|
||||
pubkey: AuthPublicKey,
|
||||
bootstrap_token: Option<String>,
|
||||
},
|
||||
AuthChallengeSolution {
|
||||
signature: Vec<u8>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
UnregisteredPublicKey,
|
||||
InvalidChallengeSolution,
|
||||
InvalidBootstrapToken,
|
||||
Internal { details: String },
|
||||
Transport,
|
||||
}
|
||||
|
||||
impl Error {
|
||||
fn internal(details: impl Into<String>) -> Self {
|
||||
Self::Internal {
|
||||
details: details.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_auth_event(payload: UserAgentRequestPayload) -> Result<AuthEvents, Error> {
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Outbound {
|
||||
AuthChallenge { nonce: i32 },
|
||||
AuthSuccess,
|
||||
}
|
||||
|
||||
fn parse_auth_event(payload: Inbound) -> AuthEvents {
|
||||
match payload {
|
||||
UserAgentRequestPayload::AuthChallengeRequest(AuthChallengeRequest {
|
||||
Inbound::AuthChallengeRequest {
|
||||
pubkey,
|
||||
bootstrap_token: None,
|
||||
key_type,
|
||||
}) => {
|
||||
let kt = ProtoKeyType::try_from(key_type).unwrap_or(ProtoKeyType::Unspecified);
|
||||
Ok(AuthEvents::AuthRequest(ChallengeRequest {
|
||||
pubkey: parse_pubkey(kt, pubkey)?,
|
||||
}))
|
||||
}
|
||||
UserAgentRequestPayload::AuthChallengeRequest(AuthChallengeRequest {
|
||||
} => AuthEvents::AuthRequest(ChallengeRequest { pubkey }),
|
||||
Inbound::AuthChallengeRequest {
|
||||
pubkey,
|
||||
bootstrap_token: Some(token),
|
||||
key_type,
|
||||
}) => {
|
||||
let kt = ProtoKeyType::try_from(key_type).unwrap_or(ProtoKeyType::Unspecified);
|
||||
Ok(AuthEvents::BootstrapAuthRequest(BootstrapAuthRequest {
|
||||
pubkey: parse_pubkey(kt, pubkey)?,
|
||||
token,
|
||||
}))
|
||||
}
|
||||
UserAgentRequestPayload::AuthChallengeSolution(AuthChallengeSolution { signature }) => {
|
||||
Ok(AuthEvents::ReceivedSolution(ChallengeSolution {
|
||||
} => AuthEvents::BootstrapAuthRequest(BootstrapAuthRequest { pubkey, token }),
|
||||
Inbound::AuthChallengeSolution { signature } => {
|
||||
AuthEvents::ReceivedSolution(ChallengeSolution {
|
||||
solution: signature,
|
||||
}))
|
||||
})
|
||||
}
|
||||
_ => Err(Error::UnexpectedMessagePayload),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn authenticate(props: &mut UserAgentConnection) -> Result<AuthPublicKey, Error> {
|
||||
let mut state = AuthStateMachine::new(AuthContext::new(props));
|
||||
pub async fn authenticate<T>(
|
||||
props: &mut UserAgentConnection,
|
||||
transport: T,
|
||||
) -> Result<AuthPublicKey, Error>
|
||||
where
|
||||
T: Bi<Inbound, Result<Outbound, Error>> + Send,
|
||||
{
|
||||
let mut state = AuthStateMachine::new(AuthContext::new(props, transport));
|
||||
|
||||
loop {
|
||||
// `state` holds a mutable reference to `props` so we can't access it directly here
|
||||
let transport = state.context_mut().conn.transport.as_mut();
|
||||
let Some(UserAgentRequest {
|
||||
payload: Some(payload),
|
||||
}) = transport.recv().await
|
||||
else {
|
||||
let Some(payload) = state.context_mut().transport.recv().await else {
|
||||
return Err(Error::Transport);
|
||||
};
|
||||
|
||||
let event = parse_auth_event(payload)?;
|
||||
|
||||
match state.process_event(event).await {
|
||||
match state.process_event(parse_auth_event(payload)).await {
|
||||
Ok(AuthStates::AuthOk(key)) => return Ok(key.clone()),
|
||||
Err(AuthError::ActionFailed(err)) => {
|
||||
error!(?err, "State machine action failed");
|
||||
@@ -131,11 +99,3 @@ pub async fn authenticate(props: &mut UserAgentConnection) -> Result<AuthPublicK
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn authenticate_and_create(
|
||||
mut props: UserAgentConnection,
|
||||
) -> Result<UserAgentSession, Error> {
|
||||
let _key = authenticate(&mut props).await?;
|
||||
let session = UserAgentSession::new(props);
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
@@ -1,52 +1,17 @@
|
||||
use arbiter_proto::proto::user_agent::{
|
||||
AuthChallenge, UserAgentResponse, user_agent_response::Payload as UserAgentResponsePayload,
|
||||
};
|
||||
use arbiter_proto::transport::Bi;
|
||||
use diesel::{ExpressionMethods as _, OptionalExtension as _, QueryDsl, update};
|
||||
use diesel_async::RunQueryDsl;
|
||||
use tracing::error;
|
||||
|
||||
use super::Error;
|
||||
use crate::{
|
||||
actors::{bootstrap::ConsumeToken, user_agent::UserAgentConnection},
|
||||
db::{models::KeyType, schema},
|
||||
actors::{
|
||||
bootstrap::ConsumeToken,
|
||||
user_agent::{AuthPublicKey, UserAgentConnection, auth::Outbound},
|
||||
},
|
||||
db::schema,
|
||||
};
|
||||
|
||||
/// Abstraction over Ed25519 / ECDSA-secp256k1 / RSA public keys used during the auth handshake.
|
||||
#[derive(Clone)]
|
||||
pub enum AuthPublicKey {
|
||||
Ed25519(ed25519_dalek::VerifyingKey),
|
||||
/// Compressed SEC1 public key; signature bytes are raw 64-byte (r||s).
|
||||
EcdsaSecp256k1(k256::ecdsa::VerifyingKey),
|
||||
/// RSA-2048+ public key (Windows Hello / KeyCredentialManager); signature bytes are PSS+SHA-256.
|
||||
Rsa(rsa::RsaPublicKey),
|
||||
}
|
||||
|
||||
impl AuthPublicKey {
|
||||
/// Canonical bytes stored in DB and echoed back in the challenge.
|
||||
/// Ed25519: raw 32 bytes. ECDSA: SEC1 compressed 33 bytes. RSA: DER-encoded SPKI.
|
||||
pub fn to_stored_bytes(&self) -> Vec<u8> {
|
||||
match self {
|
||||
AuthPublicKey::Ed25519(k) => k.to_bytes().to_vec(),
|
||||
// SEC1 compressed (33 bytes) is the natural compact format for secp256k1
|
||||
AuthPublicKey::EcdsaSecp256k1(k) => k.to_encoded_point(true).as_bytes().to_vec(),
|
||||
AuthPublicKey::Rsa(k) => {
|
||||
use rsa::pkcs8::EncodePublicKey as _;
|
||||
k.to_public_key_der()
|
||||
.expect("rsa SPKI encoding is infallible")
|
||||
.to_vec()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn key_type(&self) -> KeyType {
|
||||
match self {
|
||||
AuthPublicKey::Ed25519(_) => KeyType::Ed25519,
|
||||
AuthPublicKey::EcdsaSecp256k1(_) => KeyType::EcdsaSecp256k1,
|
||||
AuthPublicKey::Rsa(_) => KeyType::Rsa,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ChallengeRequest {
|
||||
pub pubkey: AuthPublicKey,
|
||||
}
|
||||
@@ -57,7 +22,7 @@ pub struct BootstrapAuthRequest {
|
||||
}
|
||||
|
||||
pub struct ChallengeContext {
|
||||
pub challenge: AuthChallenge,
|
||||
pub challenge_nonce: i32,
|
||||
pub key: AuthPublicKey,
|
||||
}
|
||||
|
||||
@@ -70,15 +35,15 @@ smlang::statemachine!(
|
||||
custom_error: true,
|
||||
transitions: {
|
||||
*Init + AuthRequest(ChallengeRequest) / async prepare_challenge = SentChallenge(ChallengeContext),
|
||||
Init + BootstrapAuthRequest(BootstrapAuthRequest) [async verify_bootstrap_token] / provide_key_bootstrap = AuthOk(AuthPublicKey),
|
||||
SentChallenge(ChallengeContext) + ReceivedSolution(ChallengeSolution) [async verify_solution] / provide_key = AuthOk(AuthPublicKey),
|
||||
Init + BootstrapAuthRequest(BootstrapAuthRequest) / async verify_bootstrap_token = AuthOk(AuthPublicKey),
|
||||
SentChallenge(ChallengeContext) + ReceivedSolution(ChallengeSolution) / async verify_solution = AuthOk(AuthPublicKey),
|
||||
}
|
||||
);
|
||||
|
||||
async fn create_nonce(db: &crate::db::DatabasePool, pubkey_bytes: &[u8]) -> Result<i32, Error> {
|
||||
let mut db_conn = db.get().await.map_err(|e| {
|
||||
error!(error = ?e, "Database pool error");
|
||||
Error::DatabasePoolUnavailable
|
||||
Error::internal("Database unavailable")
|
||||
})?;
|
||||
db_conn
|
||||
.exclusive_transaction(|conn| {
|
||||
@@ -102,11 +67,11 @@ async fn create_nonce(db: &crate::db::DatabasePool, pubkey_bytes: &[u8]) -> Resu
|
||||
.optional()
|
||||
.map_err(|e| {
|
||||
error!(error = ?e, "Database error");
|
||||
Error::DatabaseOperationFailed
|
||||
Error::internal("Database operation failed")
|
||||
})?
|
||||
.ok_or_else(|| {
|
||||
error!(?pubkey_bytes, "Public key not found in database");
|
||||
Error::PublicKeyNotRegistered
|
||||
Error::UnregisteredPublicKey
|
||||
})
|
||||
}
|
||||
|
||||
@@ -115,7 +80,7 @@ async fn register_key(db: &crate::db::DatabasePool, pubkey: &AuthPublicKey) -> R
|
||||
let key_type = pubkey.key_type();
|
||||
let mut conn = db.get().await.map_err(|e| {
|
||||
error!(error = ?e, "Database pool error");
|
||||
Error::DatabasePoolUnavailable
|
||||
Error::internal("Database unavailable")
|
||||
})?;
|
||||
|
||||
diesel::insert_into(schema::useragent_client::table)
|
||||
@@ -128,31 +93,95 @@ async fn register_key(db: &crate::db::DatabasePool, pubkey: &AuthPublicKey) -> R
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!(error = ?e, "Database error");
|
||||
Error::DatabaseOperationFailed
|
||||
Error::internal("Database operation failed")
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub struct AuthContext<'a> {
|
||||
pub struct AuthContext<'a, T> {
|
||||
pub(super) conn: &'a mut UserAgentConnection,
|
||||
pub(super) transport: T,
|
||||
}
|
||||
|
||||
impl<'a> AuthContext<'a> {
|
||||
pub fn new(conn: &'a mut UserAgentConnection) -> Self {
|
||||
Self { conn }
|
||||
impl<'a, T> AuthContext<'a, T> {
|
||||
pub fn new(conn: &'a mut UserAgentConnection, transport: T) -> Self {
|
||||
Self { conn, transport }
|
||||
}
|
||||
}
|
||||
|
||||
impl AuthStateMachineContext for AuthContext<'_> {
|
||||
impl<T> AuthStateMachineContext for AuthContext<'_, T>
|
||||
where
|
||||
T: Bi<super::Inbound, Result<super::Outbound, Error>> + Send,
|
||||
{
|
||||
type Error = Error;
|
||||
|
||||
async fn prepare_challenge(
|
||||
&mut self,
|
||||
ChallengeRequest { pubkey }: ChallengeRequest,
|
||||
) -> Result<ChallengeContext, Self::Error> {
|
||||
let stored_bytes = pubkey.to_stored_bytes();
|
||||
let nonce = create_nonce(&self.conn.db, &stored_bytes).await?;
|
||||
|
||||
self.transport
|
||||
.send(Ok(Outbound::AuthChallenge { nonce }))
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!(?e, "Failed to send auth challenge");
|
||||
Error::Transport
|
||||
})?;
|
||||
|
||||
Ok(ChallengeContext {
|
||||
challenge_nonce: nonce,
|
||||
key: pubkey,
|
||||
})
|
||||
}
|
||||
|
||||
#[allow(missing_docs)]
|
||||
#[allow(clippy::result_unit_err)]
|
||||
async fn verify_bootstrap_token(
|
||||
&mut self,
|
||||
BootstrapAuthRequest { pubkey, token }: BootstrapAuthRequest,
|
||||
) -> Result<AuthPublicKey, Self::Error> {
|
||||
let token_ok: bool = self
|
||||
.conn
|
||||
.actors
|
||||
.bootstrapper
|
||||
.ask(ConsumeToken {
|
||||
token: token.clone(),
|
||||
})
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!(?e, "Failed to consume bootstrap token");
|
||||
Error::internal("Failed to consume bootstrap token")
|
||||
})?;
|
||||
|
||||
if !token_ok {
|
||||
error!("Invalid bootstrap token provided");
|
||||
return Err(Error::InvalidBootstrapToken);
|
||||
}
|
||||
|
||||
register_key(&self.conn.db, &pubkey).await?;
|
||||
|
||||
self.transport
|
||||
.send(Ok(Outbound::AuthSuccess))
|
||||
.await
|
||||
.map_err(|_| Error::Transport)?;
|
||||
|
||||
Ok(pubkey)
|
||||
}
|
||||
|
||||
#[allow(missing_docs)]
|
||||
#[allow(clippy::unused_unit)]
|
||||
async fn verify_solution(
|
||||
&self,
|
||||
ChallengeContext { challenge, key }: &ChallengeContext,
|
||||
ChallengeSolution { solution }: &ChallengeSolution,
|
||||
) -> Result<bool, Self::Error> {
|
||||
let formatted = arbiter_proto::format_challenge(challenge.nonce, &challenge.pubkey);
|
||||
&mut self,
|
||||
ChallengeContext {
|
||||
challenge_nonce,
|
||||
key,
|
||||
}: &ChallengeContext,
|
||||
ChallengeSolution { solution }: ChallengeSolution,
|
||||
) -> Result<AuthPublicKey, Self::Error> {
|
||||
let formatted = arbiter_proto::format_challenge(*challenge_nonce, &key.to_stored_bytes());
|
||||
|
||||
let valid = match key {
|
||||
AuthPublicKey::Ed25519(vk) => {
|
||||
@@ -181,117 +210,13 @@ impl AuthStateMachineContext for AuthContext<'_> {
|
||||
}
|
||||
};
|
||||
|
||||
Ok(valid)
|
||||
}
|
||||
|
||||
async fn prepare_challenge(
|
||||
&mut self,
|
||||
ChallengeRequest { pubkey }: ChallengeRequest,
|
||||
) -> Result<ChallengeContext, Self::Error> {
|
||||
let stored_bytes = pubkey.to_stored_bytes();
|
||||
let nonce = create_nonce(&self.conn.db, &stored_bytes).await?;
|
||||
|
||||
let challenge = AuthChallenge {
|
||||
pubkey: stored_bytes,
|
||||
nonce,
|
||||
};
|
||||
|
||||
self.conn
|
||||
.transport
|
||||
.send(Ok(UserAgentResponse {
|
||||
payload: Some(UserAgentResponsePayload::AuthChallenge(challenge.clone())),
|
||||
}))
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!(?e, "Failed to send auth challenge");
|
||||
Error::Transport
|
||||
})?;
|
||||
|
||||
Ok(ChallengeContext {
|
||||
challenge,
|
||||
key: pubkey,
|
||||
})
|
||||
}
|
||||
|
||||
#[allow(missing_docs)]
|
||||
#[allow(clippy::result_unit_err)]
|
||||
async fn verify_bootstrap_token(
|
||||
&self,
|
||||
BootstrapAuthRequest { pubkey, token }: &BootstrapAuthRequest,
|
||||
) -> Result<bool, Self::Error> {
|
||||
let token_ok: bool = self
|
||||
.conn
|
||||
.actors
|
||||
.bootstrapper
|
||||
.ask(ConsumeToken {
|
||||
token: token.clone(),
|
||||
})
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!(?e, "Failed to consume bootstrap token");
|
||||
Error::BootstrapperActorUnreachable
|
||||
})?;
|
||||
|
||||
if !token_ok {
|
||||
error!("Invalid bootstrap token provided");
|
||||
return Err(Error::InvalidBootstrapToken);
|
||||
if valid {
|
||||
self.transport
|
||||
.send(Ok(Outbound::AuthSuccess))
|
||||
.await
|
||||
.map_err(|_| Error::Transport)?;
|
||||
}
|
||||
|
||||
register_key(&self.conn.db, pubkey).await?;
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn provide_key_bootstrap(
|
||||
&mut self,
|
||||
event_data: BootstrapAuthRequest,
|
||||
) -> Result<AuthPublicKey, Self::Error> {
|
||||
Ok(event_data.pubkey)
|
||||
}
|
||||
|
||||
fn provide_key(
|
||||
&mut self,
|
||||
state_data: &ChallengeContext,
|
||||
_: ChallengeSolution,
|
||||
) -> Result<AuthPublicKey, Self::Error> {
|
||||
// ChallengeContext.key cannot be taken by value because smlang passes it by ref;
|
||||
// we reconstruct stored bytes and return them wrapped in Ed25519 placeholder.
|
||||
// Session uses only the raw bytes, so we carry them via a Vec<u8>.
|
||||
// IMPORTANT: do NOT simplify this by storing the key type separately — the
|
||||
// `AuthPublicKey` enum IS the source of truth for key bytes and type.
|
||||
//
|
||||
// smlang state-machine trait requires returning an owned value from `provide_key`,
|
||||
// but `state_data` is only available by shared reference here. We extract the
|
||||
// stored bytes and re-wrap as the correct variant so the caller can call
|
||||
// `to_stored_bytes()` / `key_type()` without losing information.
|
||||
let bytes = state_data.challenge.pubkey.clone();
|
||||
let key_type = state_data.key.key_type();
|
||||
let rebuilt = match key_type {
|
||||
crate::db::models::KeyType::Ed25519 => {
|
||||
let arr: &[u8; 32] = bytes
|
||||
.as_slice()
|
||||
.try_into()
|
||||
.expect("ed25519 pubkey must be 32 bytes in challenge");
|
||||
AuthPublicKey::Ed25519(
|
||||
ed25519_dalek::VerifyingKey::from_bytes(arr)
|
||||
.expect("key was already validated in parse_auth_event"),
|
||||
)
|
||||
}
|
||||
crate::db::models::KeyType::EcdsaSecp256k1 => {
|
||||
// bytes are SEC1 compressed (33 bytes produced by to_encoded_point(true))
|
||||
AuthPublicKey::EcdsaSecp256k1(
|
||||
k256::ecdsa::VerifyingKey::from_sec1_bytes(&bytes)
|
||||
.expect("ecdsa key was already validated in parse_auth_event"),
|
||||
)
|
||||
}
|
||||
crate::db::models::KeyType::Rsa => {
|
||||
use rsa::pkcs8::DecodePublicKey as _;
|
||||
AuthPublicKey::Rsa(
|
||||
rsa::RsaPublicKey::from_public_key_der(&bytes)
|
||||
.expect("rsa key was already validated in parse_auth_event"),
|
||||
)
|
||||
}
|
||||
};
|
||||
Ok(rebuilt)
|
||||
Ok(key.clone())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,65 +1,94 @@
|
||||
use arbiter_proto::{
|
||||
proto::user_agent::{UserAgentRequest, UserAgentResponse},
|
||||
transport::Bi,
|
||||
};
|
||||
use kameo::actor::Spawn as _;
|
||||
use tracing::{error, info};
|
||||
|
||||
use crate::{
|
||||
actors::{GlobalActors, user_agent::session::UserAgentSession},
|
||||
db::{self},
|
||||
actors::GlobalActors,
|
||||
db::{self, models::KeyType},
|
||||
};
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq)]
|
||||
pub enum TransportResponseError {
|
||||
#[error("Expected message with payload")]
|
||||
MissingRequestPayload,
|
||||
#[error("Unexpected request payload")]
|
||||
UnexpectedRequestPayload,
|
||||
#[error("Invalid state for unseal encrypted key")]
|
||||
InvalidStateForUnsealEncryptedKey,
|
||||
#[error("client_pubkey must be 32 bytes")]
|
||||
InvalidClientPubkeyLength,
|
||||
#[error("State machine error")]
|
||||
StateTransitionFailed,
|
||||
#[error("Vault is not available")]
|
||||
KeyHolderActorUnreachable,
|
||||
#[error(transparent)]
|
||||
Auth(#[from] auth::Error),
|
||||
#[error("Failed registering connection")]
|
||||
ConnectionRegistrationFailed,
|
||||
/// Abstraction over Ed25519 / ECDSA-secp256k1 / RSA public keys used during the auth handshake.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum AuthPublicKey {
|
||||
Ed25519(ed25519_dalek::VerifyingKey),
|
||||
/// Compressed SEC1 public key; signature bytes are raw 64-byte (r||s).
|
||||
EcdsaSecp256k1(k256::ecdsa::VerifyingKey),
|
||||
/// RSA-2048+ public key (Windows Hello / KeyCredentialManager); signature bytes are PSS+SHA-256.
|
||||
Rsa(rsa::RsaPublicKey),
|
||||
}
|
||||
|
||||
pub type Transport =
|
||||
Box<dyn Bi<UserAgentRequest, Result<UserAgentResponse, TransportResponseError>> + Send>;
|
||||
impl AuthPublicKey {
|
||||
/// Canonical bytes stored in DB and echoed back in the challenge.
|
||||
/// Ed25519: raw 32 bytes. ECDSA: SEC1 compressed 33 bytes. RSA: DER-encoded SPKI.
|
||||
pub fn to_stored_bytes(&self) -> Vec<u8> {
|
||||
match self {
|
||||
AuthPublicKey::Ed25519(k) => k.to_bytes().to_vec(),
|
||||
// SEC1 compressed (33 bytes) is the natural compact format for secp256k1
|
||||
AuthPublicKey::EcdsaSecp256k1(k) => k.to_encoded_point(true).as_bytes().to_vec(),
|
||||
AuthPublicKey::Rsa(k) => {
|
||||
use rsa::pkcs8::EncodePublicKey as _;
|
||||
#[allow(clippy::expect_used)]
|
||||
k.to_public_key_der()
|
||||
.expect("rsa SPKI encoding is infallible")
|
||||
.to_vec()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn key_type(&self) -> KeyType {
|
||||
match self {
|
||||
AuthPublicKey::Ed25519(_) => KeyType::Ed25519,
|
||||
AuthPublicKey::EcdsaSecp256k1(_) => KeyType::EcdsaSecp256k1,
|
||||
AuthPublicKey::Rsa(_) => KeyType::Rsa,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<(KeyType, Vec<u8>)> for AuthPublicKey {
|
||||
type Error = &'static str;
|
||||
|
||||
fn try_from(value: (KeyType, Vec<u8>)) -> Result<Self, Self::Error> {
|
||||
let (key_type, bytes) = value;
|
||||
match key_type {
|
||||
KeyType::Ed25519 => {
|
||||
let bytes: [u8; 32] = bytes.try_into().map_err(|_| "invalid Ed25519 key length")?;
|
||||
let key = ed25519_dalek::VerifyingKey::from_bytes(&bytes)
|
||||
.map_err(|_e| "invalid Ed25519 key")?;
|
||||
Ok(AuthPublicKey::Ed25519(key))
|
||||
}
|
||||
KeyType::EcdsaSecp256k1 => {
|
||||
let point =
|
||||
k256::EncodedPoint::from_bytes(&bytes).map_err(|_e| "invalid ECDSA key")?;
|
||||
let key = k256::ecdsa::VerifyingKey::from_encoded_point(&point)
|
||||
.map_err(|_e| "invalid ECDSA key")?;
|
||||
Ok(AuthPublicKey::EcdsaSecp256k1(key))
|
||||
}
|
||||
KeyType::Rsa => {
|
||||
use rsa::pkcs8::DecodePublicKey as _;
|
||||
let key = rsa::RsaPublicKey::from_public_key_der(&bytes)
|
||||
.map_err(|_e| "invalid RSA key")?;
|
||||
Ok(AuthPublicKey::Rsa(key))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Messages, sent by user agent to connection client without having a request
|
||||
#[derive(Debug)]
|
||||
pub enum OutOfBand {
|
||||
ClientConnectionRequest { pubkey: ed25519_dalek::VerifyingKey },
|
||||
ClientConnectionCancel,
|
||||
}
|
||||
|
||||
pub struct UserAgentConnection {
|
||||
db: db::DatabasePool,
|
||||
actors: GlobalActors,
|
||||
transport: Transport,
|
||||
pub(crate) db: db::DatabasePool,
|
||||
pub(crate) actors: GlobalActors,
|
||||
}
|
||||
|
||||
impl UserAgentConnection {
|
||||
pub fn new(db: db::DatabasePool, actors: GlobalActors, transport: Transport) -> Self {
|
||||
Self {
|
||||
db,
|
||||
actors,
|
||||
transport,
|
||||
}
|
||||
pub fn new(db: db::DatabasePool, actors: GlobalActors) -> Self {
|
||||
Self { db, actors }
|
||||
}
|
||||
}
|
||||
|
||||
pub mod auth;
|
||||
pub mod session;
|
||||
|
||||
pub async fn connect_user_agent(props: UserAgentConnection) {
|
||||
match auth::authenticate_and_create(props).await {
|
||||
Ok(session) => {
|
||||
UserAgentSession::spawn(session);
|
||||
info!("User authenticated, session started");
|
||||
}
|
||||
Err(err) => {
|
||||
error!(?err, "Authentication failed, closing connection");
|
||||
}
|
||||
}
|
||||
}
|
||||
pub use auth::authenticate;
|
||||
pub use session::UserAgentSession;
|
||||
|
||||
@@ -1,523 +1,116 @@
|
||||
use std::{ops::DerefMut, sync::Mutex};
|
||||
use std::borrow::Cow;
|
||||
|
||||
use arbiter_proto::proto::{
|
||||
evm as evm_proto,
|
||||
user_agent::{
|
||||
SdkClientApproveRequest, SdkClientApproveResponse, SdkClientEntry,
|
||||
SdkClientError as ProtoSdkClientError, SdkClientList, SdkClientListResponse,
|
||||
SdkClientRevokeRequest, SdkClientRevokeResponse, UnsealEncryptedKey, UnsealResult,
|
||||
UnsealStart, UnsealStartResponse, UserAgentRequest, UserAgentResponse,
|
||||
sdk_client_approve_response, sdk_client_list_response, sdk_client_revoke_response,
|
||||
user_agent_request::Payload as UserAgentRequestPayload,
|
||||
user_agent_response::Payload as UserAgentResponsePayload,
|
||||
},
|
||||
};
|
||||
use chacha20poly1305::{AeadInPlace, XChaCha20Poly1305, XNonce, aead::KeyInit};
|
||||
use diesel::{ExpressionMethods as _, QueryDsl as _, dsl::insert_into};
|
||||
use diesel_async::RunQueryDsl as _;
|
||||
use kameo::{Actor, error::SendError, prelude::Context};
|
||||
use memsafe::MemSafe;
|
||||
use tokio::select;
|
||||
use tracing::{error, info};
|
||||
use x25519_dalek::{EphemeralSecret, PublicKey};
|
||||
use arbiter_proto::transport::Sender;
|
||||
use async_trait::async_trait;
|
||||
use ed25519_dalek::VerifyingKey;
|
||||
use kameo::{Actor, messages};
|
||||
use thiserror::Error;
|
||||
use tokio::sync::watch;
|
||||
use tracing::error;
|
||||
|
||||
use crate::{
|
||||
actors::{
|
||||
evm::{Generate, ListWallets},
|
||||
keyholder::{self, TryUnseal},
|
||||
router::RegisterUserAgent,
|
||||
user_agent::{TransportResponseError, UserAgentConnection},
|
||||
},
|
||||
db::schema::program_client,
|
||||
use crate::actors::{
|
||||
router::RegisterUserAgent,
|
||||
user_agent::{OutOfBand, UserAgentConnection},
|
||||
};
|
||||
|
||||
mod state;
|
||||
use state::{DummyContext, UnsealContext, UserAgentEvents, UserAgentStateMachine, UserAgentStates};
|
||||
use state::{DummyContext, UserAgentEvents, UserAgentStateMachine};
|
||||
|
||||
// Error for consumption by other actors
|
||||
#[derive(Debug, thiserror::Error, PartialEq)]
|
||||
#[derive(Debug, Error)]
|
||||
pub enum Error {
|
||||
#[error("User agent session ended due to connection loss")]
|
||||
ConnectionLost,
|
||||
#[error("State transition failed")]
|
||||
State,
|
||||
|
||||
#[error("User agent session ended due to unexpected message")]
|
||||
UnexpectedMessage,
|
||||
#[error("Internal error: {message}")]
|
||||
Internal { message: Cow<'static, str> },
|
||||
}
|
||||
|
||||
impl Error {
|
||||
pub fn internal(message: impl Into<Cow<'static, str>>) -> Self {
|
||||
Self::Internal {
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UserAgentSession {
|
||||
props: UserAgentConnection,
|
||||
state: UserAgentStateMachine<DummyContext>,
|
||||
#[allow(dead_code, reason = "The session keeps ownership of the outbound transport even before the state-machine flow starts using it directly")]
|
||||
sender: Box<dyn Sender<OutOfBand>>,
|
||||
}
|
||||
|
||||
mod connection;
|
||||
pub(crate) use connection::{
|
||||
BootstrapError, HandleBootstrapEncryptedKey, HandleEvmWalletCreate, HandleEvmWalletList,
|
||||
HandleGrantCreate, HandleGrantDelete, HandleGrantList, HandleQueryVaultState,
|
||||
};
|
||||
pub use connection::{HandleUnsealEncryptedKey, HandleUnsealRequest, UnsealError};
|
||||
|
||||
impl UserAgentSession {
|
||||
pub(crate) fn new(props: UserAgentConnection) -> Self {
|
||||
pub(crate) fn new(props: UserAgentConnection, sender: Box<dyn Sender<OutOfBand>>) -> Self {
|
||||
Self {
|
||||
props,
|
||||
state: UserAgentStateMachine::new(DummyContext),
|
||||
sender,
|
||||
}
|
||||
}
|
||||
|
||||
fn transition(&mut self, event: UserAgentEvents) -> Result<(), TransportResponseError> {
|
||||
pub fn new_test(db: crate::db::DatabasePool, actors: crate::actors::GlobalActors) -> Self {
|
||||
struct DummySender;
|
||||
|
||||
#[async_trait]
|
||||
impl Sender<OutOfBand> for DummySender {
|
||||
async fn send(
|
||||
&mut self,
|
||||
_item: OutOfBand,
|
||||
) -> Result<(), arbiter_proto::transport::Error> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
Self::new(UserAgentConnection::new(db, actors), Box::new(DummySender))
|
||||
}
|
||||
|
||||
fn transition(&mut self, event: UserAgentEvents) -> Result<(), Error> {
|
||||
self.state.process_event(event).map_err(|e| {
|
||||
error!(?e, "State transition failed");
|
||||
TransportResponseError::StateTransitionFailed
|
||||
Error::State
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_msg<Reply: kameo::Reply>(
|
||||
#[messages]
|
||||
impl UserAgentSession {
|
||||
#[message]
|
||||
pub async fn request_new_client_approval(
|
||||
&mut self,
|
||||
msg: UserAgentResponsePayload,
|
||||
_ctx: &mut Context<Self, Reply>,
|
||||
) -> Result<(), Error> {
|
||||
self.props
|
||||
.transport
|
||||
.send(Ok(response(msg)))
|
||||
.await
|
||||
.map_err(|_| {
|
||||
error!(
|
||||
actor = "useragent",
|
||||
reason = "channel closed",
|
||||
"send.failed"
|
||||
);
|
||||
Error::ConnectionLost
|
||||
client_pubkey: VerifyingKey,
|
||||
mut cancel_flag: watch::Receiver<()>,
|
||||
) -> Result<bool, ()> {
|
||||
if self
|
||||
.sender
|
||||
.send(OutOfBand::ClientConnectionRequest {
|
||||
pubkey: client_pubkey,
|
||||
})
|
||||
}
|
||||
|
||||
async fn expect_msg<Extractor, Msg, Reply>(
|
||||
&mut self,
|
||||
extractor: Extractor,
|
||||
ctx: &mut Context<Self, Reply>,
|
||||
) -> Result<Msg, Error>
|
||||
where
|
||||
Extractor: FnOnce(UserAgentRequestPayload) -> Option<Msg>,
|
||||
Reply: kameo::Reply,
|
||||
{
|
||||
let msg = self.props.transport.recv().await.ok_or_else(|| {
|
||||
error!(
|
||||
actor = "useragent",
|
||||
reason = "channel closed",
|
||||
"recv.failed"
|
||||
);
|
||||
ctx.stop();
|
||||
Error::ConnectionLost
|
||||
})?;
|
||||
|
||||
msg.payload.and_then(extractor).ok_or_else(|| {
|
||||
error!(
|
||||
actor = "useragent",
|
||||
reason = "unexpected message",
|
||||
"recv.failed"
|
||||
);
|
||||
ctx.stop();
|
||||
Error::UnexpectedMessage
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl UserAgentSession {
|
||||
pub async fn process_transport_inbound(&mut self, req: UserAgentRequest) -> Output {
|
||||
let msg = req.payload.ok_or_else(|| {
|
||||
error!(actor = "useragent", "Received message with no payload");
|
||||
TransportResponseError::MissingRequestPayload
|
||||
})?;
|
||||
|
||||
match msg {
|
||||
UserAgentRequestPayload::UnsealStart(unseal_start) => {
|
||||
self.handle_unseal_request(unseal_start).await
|
||||
}
|
||||
UserAgentRequestPayload::UnsealEncryptedKey(unseal_encrypted_key) => {
|
||||
self.handle_unseal_encrypted_key(unseal_encrypted_key).await
|
||||
}
|
||||
UserAgentRequestPayload::EvmWalletCreate(_) => self.handle_evm_wallet_create().await,
|
||||
UserAgentRequestPayload::EvmWalletList(_) => self.handle_evm_wallet_list().await,
|
||||
UserAgentRequestPayload::SdkClientApprove(req) => {
|
||||
self.handle_sdk_client_approve(req).await
|
||||
}
|
||||
UserAgentRequestPayload::SdkClientRevoke(req) => {
|
||||
self.handle_sdk_client_revoke(req).await
|
||||
}
|
||||
UserAgentRequestPayload::SdkClientList(_) => self.handle_sdk_client_list().await,
|
||||
_ => Err(TransportResponseError::UnexpectedRequestPayload),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type Output = Result<UserAgentResponse, TransportResponseError>;
|
||||
|
||||
fn response(payload: UserAgentResponsePayload) -> UserAgentResponse {
|
||||
UserAgentResponse {
|
||||
payload: Some(payload),
|
||||
}
|
||||
}
|
||||
|
||||
impl UserAgentSession {
|
||||
async fn handle_unseal_request(&mut self, req: UnsealStart) -> Output {
|
||||
let secret = EphemeralSecret::random();
|
||||
let public_key = PublicKey::from(&secret);
|
||||
|
||||
let client_pubkey_bytes: [u8; 32] = req
|
||||
.client_pubkey
|
||||
.try_into()
|
||||
.map_err(|_| TransportResponseError::InvalidClientPubkeyLength)?;
|
||||
|
||||
let client_public_key = PublicKey::from(client_pubkey_bytes);
|
||||
|
||||
self.transition(UserAgentEvents::UnsealRequest(UnsealContext {
|
||||
secret: Mutex::new(Some(secret)),
|
||||
client_public_key,
|
||||
}))?;
|
||||
|
||||
Ok(response(UserAgentResponsePayload::UnsealStartResponse(
|
||||
UnsealStartResponse {
|
||||
server_pubkey: public_key.as_bytes().to_vec(),
|
||||
},
|
||||
)))
|
||||
}
|
||||
|
||||
async fn handle_unseal_encrypted_key(&mut self, req: UnsealEncryptedKey) -> Output {
|
||||
let UserAgentStates::WaitingForUnsealKey(unseal_context) = self.state.state() else {
|
||||
error!("Received unseal encrypted key in invalid state");
|
||||
return Err(TransportResponseError::InvalidStateForUnsealEncryptedKey);
|
||||
};
|
||||
let ephemeral_secret = {
|
||||
let mut secret_lock = unseal_context.secret.lock().unwrap();
|
||||
let secret = secret_lock.take();
|
||||
match secret {
|
||||
Some(secret) => secret,
|
||||
None => {
|
||||
drop(secret_lock);
|
||||
error!("Ephemeral secret already taken");
|
||||
self.transition(UserAgentEvents::ReceivedInvalidKey)?;
|
||||
return Ok(response(UserAgentResponsePayload::UnsealResult(
|
||||
UnsealResult::InvalidKey.into(),
|
||||
)));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let nonce = XNonce::from_slice(&req.nonce);
|
||||
|
||||
let shared_secret = ephemeral_secret.diffie_hellman(&unseal_context.client_public_key);
|
||||
let cipher = XChaCha20Poly1305::new(shared_secret.as_bytes().into());
|
||||
|
||||
let mut seal_key_buffer = MemSafe::new(req.ciphertext.clone()).unwrap();
|
||||
|
||||
let decryption_result = {
|
||||
let mut write_handle = seal_key_buffer.write().unwrap();
|
||||
let write_handle = write_handle.deref_mut();
|
||||
cipher.decrypt_in_place(nonce, &req.associated_data, write_handle)
|
||||
};
|
||||
|
||||
match decryption_result {
|
||||
Ok(_) => {
|
||||
match self
|
||||
.props
|
||||
.actors
|
||||
.key_holder
|
||||
.ask(TryUnseal {
|
||||
seal_key_raw: seal_key_buffer,
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
info!("Successfully unsealed key with client-provided key");
|
||||
self.transition(UserAgentEvents::ReceivedValidKey)?;
|
||||
Ok(response(UserAgentResponsePayload::UnsealResult(
|
||||
UnsealResult::Success.into(),
|
||||
)))
|
||||
}
|
||||
Err(SendError::HandlerError(keyholder::Error::InvalidKey)) => {
|
||||
self.transition(UserAgentEvents::ReceivedInvalidKey)?;
|
||||
Ok(response(UserAgentResponsePayload::UnsealResult(
|
||||
UnsealResult::InvalidKey.into(),
|
||||
)))
|
||||
}
|
||||
Err(SendError::HandlerError(err)) => {
|
||||
error!(?err, "Keyholder failed to unseal key");
|
||||
self.transition(UserAgentEvents::ReceivedInvalidKey)?;
|
||||
Ok(response(UserAgentResponsePayload::UnsealResult(
|
||||
UnsealResult::InvalidKey.into(),
|
||||
)))
|
||||
}
|
||||
Err(err) => {
|
||||
error!(?err, "Failed to send unseal request to keyholder");
|
||||
self.transition(UserAgentEvents::ReceivedInvalidKey)?;
|
||||
Err(TransportResponseError::KeyHolderActorUnreachable)
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
error!(?err, "Failed to decrypt unseal key");
|
||||
self.transition(UserAgentEvents::ReceivedInvalidKey)?;
|
||||
Ok(response(UserAgentResponsePayload::UnsealResult(
|
||||
UnsealResult::InvalidKey.into(),
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UserAgentSession {
|
||||
async fn handle_evm_wallet_create(&mut self) -> Output {
|
||||
use evm_proto::wallet_create_response::Result as CreateResult;
|
||||
|
||||
let result = match self.props.actors.evm.ask(Generate {}).await {
|
||||
Ok(address) => CreateResult::Wallet(evm_proto::WalletEntry {
|
||||
address: address.as_slice().to_vec(),
|
||||
}),
|
||||
Err(err) => CreateResult::Error(map_evm_error("wallet create", err).into()),
|
||||
};
|
||||
|
||||
Ok(response(UserAgentResponsePayload::EvmWalletCreate(
|
||||
evm_proto::WalletCreateResponse {
|
||||
result: Some(result),
|
||||
},
|
||||
)))
|
||||
}
|
||||
|
||||
async fn handle_evm_wallet_list(&mut self) -> Output {
|
||||
use evm_proto::wallet_list_response::Result as ListResult;
|
||||
|
||||
let result = match self.props.actors.evm.ask(ListWallets {}).await {
|
||||
Ok(wallets) => ListResult::Wallets(evm_proto::WalletList {
|
||||
wallets: wallets
|
||||
.into_iter()
|
||||
.map(|addr| evm_proto::WalletEntry {
|
||||
address: addr.as_slice().to_vec(),
|
||||
})
|
||||
.collect(),
|
||||
}),
|
||||
Err(err) => ListResult::Error(map_evm_error("wallet list", err).into()),
|
||||
};
|
||||
|
||||
Ok(response(UserAgentResponsePayload::EvmWalletList(
|
||||
evm_proto::WalletListResponse {
|
||||
result: Some(result),
|
||||
},
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
impl UserAgentSession {
|
||||
async fn handle_sdk_client_approve(&mut self, req: SdkClientApproveRequest) -> Output {
|
||||
use sdk_client_approve_response::Result as ApproveResult;
|
||||
|
||||
if req.pubkey.len() != 32 {
|
||||
return Ok(response(UserAgentResponsePayload::SdkClientApprove(
|
||||
SdkClientApproveResponse {
|
||||
result: Some(ApproveResult::Error(ProtoSdkClientError::Internal.into())),
|
||||
},
|
||||
)));
|
||||
}
|
||||
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs() as i32;
|
||||
|
||||
let mut conn = match self.props.db.get().await {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
error!(?e, "Failed to get DB connection for sdk_client_approve");
|
||||
return Ok(response(UserAgentResponsePayload::SdkClientApprove(
|
||||
SdkClientApproveResponse {
|
||||
result: Some(ApproveResult::Error(ProtoSdkClientError::Internal.into())),
|
||||
},
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
let pubkey_bytes = req.pubkey.clone();
|
||||
let insert_result = insert_into(program_client::table)
|
||||
.values((
|
||||
program_client::public_key.eq(&pubkey_bytes),
|
||||
program_client::nonce.eq(1), // pre-incremented; challenge will use nonce=0
|
||||
program_client::created_at.eq(now),
|
||||
program_client::updated_at.eq(now),
|
||||
))
|
||||
.execute(&mut conn)
|
||||
.await;
|
||||
|
||||
match insert_result {
|
||||
Ok(_) => {
|
||||
match program_client::table
|
||||
.filter(program_client::public_key.eq(&pubkey_bytes))
|
||||
.order(program_client::id.desc())
|
||||
.select((
|
||||
program_client::id,
|
||||
program_client::public_key,
|
||||
program_client::created_at,
|
||||
))
|
||||
.first::<(i32, Vec<u8>, i32)>(&mut conn)
|
||||
.await
|
||||
{
|
||||
Ok((id, pubkey, created_at)) => Ok(response(
|
||||
UserAgentResponsePayload::SdkClientApprove(SdkClientApproveResponse {
|
||||
result: Some(ApproveResult::Client(SdkClientEntry {
|
||||
id,
|
||||
pubkey,
|
||||
created_at,
|
||||
})),
|
||||
}),
|
||||
)),
|
||||
Err(e) => {
|
||||
error!(?e, "Failed to fetch inserted SDK client");
|
||||
Ok(response(UserAgentResponsePayload::SdkClientApprove(
|
||||
SdkClientApproveResponse {
|
||||
result: Some(ApproveResult::Error(
|
||||
ProtoSdkClientError::Internal.into(),
|
||||
)),
|
||||
},
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(diesel::result::Error::DatabaseError(
|
||||
diesel::result::DatabaseErrorKind::UniqueViolation,
|
||||
_,
|
||||
)) => Ok(response(UserAgentResponsePayload::SdkClientApprove(
|
||||
SdkClientApproveResponse {
|
||||
result: Some(ApproveResult::Error(
|
||||
ProtoSdkClientError::AlreadyExists.into(),
|
||||
)),
|
||||
},
|
||||
))),
|
||||
Err(e) => {
|
||||
error!(?e, "Failed to insert SDK client");
|
||||
Ok(response(UserAgentResponsePayload::SdkClientApprove(
|
||||
SdkClientApproveResponse {
|
||||
result: Some(ApproveResult::Error(ProtoSdkClientError::Internal.into())),
|
||||
},
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_sdk_client_list(&mut self) -> Output {
|
||||
let mut conn = match self.props.db.get().await {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
error!(?e, "Failed to get DB connection for sdk_client_list");
|
||||
return Ok(response(UserAgentResponsePayload::SdkClientList(
|
||||
SdkClientListResponse {
|
||||
result: Some(sdk_client_list_response::Result::Error(
|
||||
ProtoSdkClientError::Internal.into(),
|
||||
)),
|
||||
},
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
match program_client::table
|
||||
.select((
|
||||
program_client::id,
|
||||
program_client::public_key,
|
||||
program_client::created_at,
|
||||
))
|
||||
.load::<(i32, Vec<u8>, i32)>(&mut conn)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
Ok(rows) => Ok(response(UserAgentResponsePayload::SdkClientList(
|
||||
SdkClientListResponse {
|
||||
result: Some(sdk_client_list_response::Result::Clients(SdkClientList {
|
||||
clients: rows
|
||||
.into_iter()
|
||||
.map(|(id, pubkey, created_at)| SdkClientEntry {
|
||||
id,
|
||||
pubkey,
|
||||
created_at,
|
||||
})
|
||||
.collect(),
|
||||
})),
|
||||
},
|
||||
))),
|
||||
Err(e) => {
|
||||
error!(?e, "Failed to list SDK clients");
|
||||
Ok(response(UserAgentResponsePayload::SdkClientList(
|
||||
SdkClientListResponse {
|
||||
result: Some(sdk_client_list_response::Result::Error(
|
||||
ProtoSdkClientError::Internal.into(),
|
||||
)),
|
||||
},
|
||||
)))
|
||||
}
|
||||
return Err(());
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_sdk_client_revoke(&mut self, req: SdkClientRevokeRequest) -> Output {
|
||||
use sdk_client_revoke_response::Result as RevokeResult;
|
||||
let _ = cancel_flag.changed().await;
|
||||
|
||||
let mut conn = match self.props.db.get().await {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
error!(?e, "Failed to get DB connection for sdk_client_revoke");
|
||||
return Ok(response(UserAgentResponsePayload::SdkClientRevoke(
|
||||
SdkClientRevokeResponse {
|
||||
result: Some(RevokeResult::Error(ProtoSdkClientError::Internal.into())),
|
||||
},
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
match diesel::delete(program_client::table)
|
||||
.filter(program_client::id.eq(req.client_id))
|
||||
.execute(&mut conn)
|
||||
.await
|
||||
{
|
||||
Ok(0) => Ok(response(UserAgentResponsePayload::SdkClientRevoke(
|
||||
SdkClientRevokeResponse {
|
||||
result: Some(RevokeResult::Error(ProtoSdkClientError::NotFound.into())),
|
||||
},
|
||||
))),
|
||||
Ok(_) => Ok(response(UserAgentResponsePayload::SdkClientRevoke(
|
||||
SdkClientRevokeResponse {
|
||||
result: Some(RevokeResult::Ok(())),
|
||||
},
|
||||
))),
|
||||
Err(diesel::result::Error::DatabaseError(
|
||||
diesel::result::DatabaseErrorKind::ForeignKeyViolation,
|
||||
_,
|
||||
)) => Ok(response(UserAgentResponsePayload::SdkClientRevoke(
|
||||
SdkClientRevokeResponse {
|
||||
result: Some(RevokeResult::Error(
|
||||
ProtoSdkClientError::HasRelatedData.into(),
|
||||
)),
|
||||
},
|
||||
))),
|
||||
Err(e) => {
|
||||
error!(?e, "Failed to delete SDK client");
|
||||
Ok(response(UserAgentResponsePayload::SdkClientRevoke(
|
||||
SdkClientRevokeResponse {
|
||||
result: Some(RevokeResult::Error(ProtoSdkClientError::Internal.into())),
|
||||
},
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn map_evm_error<M>(op: &str, err: SendError<M, crate::actors::evm::Error>) -> evm_proto::EvmError {
|
||||
use crate::actors::{evm::Error as EvmError, keyholder::Error as KhError};
|
||||
match err {
|
||||
SendError::HandlerError(EvmError::Keyholder(KhError::NotBootstrapped)) => {
|
||||
evm_proto::EvmError::VaultSealed
|
||||
}
|
||||
SendError::HandlerError(err) => {
|
||||
error!(?err, "EVM {op} failed");
|
||||
evm_proto::EvmError::Internal
|
||||
}
|
||||
_ => {
|
||||
error!("EVM actor unreachable during {op}");
|
||||
evm_proto::EvmError::Internal
|
||||
}
|
||||
let _ = self.sender.send(OutOfBand::ClientConnectionCancel).await;
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
impl Actor for UserAgentSession {
|
||||
type Args = Self;
|
||||
|
||||
type Error = TransportResponseError;
|
||||
type Error = Error;
|
||||
|
||||
async fn on_start(
|
||||
args: Self::Args,
|
||||
@@ -532,56 +125,8 @@ impl Actor for UserAgentSession {
|
||||
.await
|
||||
.map_err(|err| {
|
||||
error!(?err, "Failed to register user agent connection with router");
|
||||
TransportResponseError::ConnectionRegistrationFailed
|
||||
Error::internal("Failed to register user agent connection with router")
|
||||
})?;
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
async fn next(
|
||||
&mut self,
|
||||
_actor_ref: kameo::prelude::WeakActorRef<Self>,
|
||||
mailbox_rx: &mut kameo::prelude::MailboxReceiver<Self>,
|
||||
) -> Option<kameo::mailbox::Signal<Self>> {
|
||||
loop {
|
||||
select! {
|
||||
signal = mailbox_rx.recv() => {
|
||||
return signal;
|
||||
}
|
||||
msg = self.props.transport.recv() => {
|
||||
match msg {
|
||||
Some(request) => {
|
||||
match self.process_transport_inbound(request).await {
|
||||
Ok(response) => {
|
||||
if self.props.transport.send(Ok(response)).await.is_err() {
|
||||
error!(actor = "useragent", reason = "channel closed", "send.failed");
|
||||
return Some(kameo::mailbox::Signal::Stop);
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
let _ = self.props.transport.send(Err(err)).await;
|
||||
return Some(kameo::mailbox::Signal::Stop);
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
info!(actor = "useragent", "transport.closed");
|
||||
return Some(kameo::mailbox::Signal::Stop);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UserAgentSession {
|
||||
pub fn new_test(db: crate::db::DatabasePool, actors: crate::actors::GlobalActors) -> Self {
|
||||
use arbiter_proto::transport::DummyTransport;
|
||||
let transport: super::Transport = Box::new(DummyTransport::new());
|
||||
let props = UserAgentConnection::new(db, actors, transport);
|
||||
Self {
|
||||
props,
|
||||
state: UserAgentStateMachine::new(DummyContext),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
use std::sync::Mutex;
|
||||
|
||||
use alloy::primitives::Address;
|
||||
use chacha20poly1305::{AeadInPlace, XChaCha20Poly1305, XNonce, aead::KeyInit};
|
||||
use kameo::error::SendError;
|
||||
use kameo::messages;
|
||||
use tracing::{error, info};
|
||||
use x25519_dalek::{EphemeralSecret, PublicKey};
|
||||
|
||||
use crate::actors::keyholder::KeyHolderState;
|
||||
use crate::actors::user_agent::session::Error;
|
||||
use crate::evm::policies::{Grant, SpecificGrant};
|
||||
use crate::safe_cell::SafeCell;
|
||||
use crate::{
|
||||
actors::{
|
||||
evm::{
|
||||
Generate, ListWallets, UseragentCreateGrant, UseragentDeleteGrant, UseragentListGrants,
|
||||
},
|
||||
keyholder::{self, Bootstrap, TryUnseal},
|
||||
user_agent::session::{
|
||||
UserAgentSession,
|
||||
state::{UnsealContext, UserAgentEvents, UserAgentStates},
|
||||
},
|
||||
},
|
||||
safe_cell::SafeCellHandle as _,
|
||||
};
|
||||
|
||||
impl UserAgentSession {
|
||||
fn take_unseal_secret(&mut self) -> Result<(EphemeralSecret, PublicKey), Error> {
|
||||
let UserAgentStates::WaitingForUnsealKey(unseal_context) = self.state.state() else {
|
||||
error!("Received encrypted key in invalid state");
|
||||
return Err(Error::internal("Invalid state for unseal encrypted key"));
|
||||
};
|
||||
|
||||
let ephemeral_secret = {
|
||||
#[allow(
|
||||
clippy::unwrap_used,
|
||||
reason = "Mutex poison is unrecoverable and should panic"
|
||||
)]
|
||||
let mut secret_lock = unseal_context.secret.lock().unwrap();
|
||||
let secret = secret_lock.take();
|
||||
match secret {
|
||||
Some(secret) => secret,
|
||||
None => {
|
||||
drop(secret_lock);
|
||||
error!("Ephemeral secret already taken");
|
||||
return Err(Error::internal("Ephemeral secret already taken"));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
Ok((ephemeral_secret, unseal_context.client_public_key))
|
||||
}
|
||||
|
||||
fn decrypt_client_key_material(
|
||||
ephemeral_secret: EphemeralSecret,
|
||||
client_public_key: PublicKey,
|
||||
nonce: &[u8],
|
||||
ciphertext: &[u8],
|
||||
associated_data: &[u8],
|
||||
) -> Result<SafeCell<Vec<u8>>, ()> {
|
||||
let nonce = XNonce::from_slice(nonce);
|
||||
|
||||
let shared_secret = ephemeral_secret.diffie_hellman(&client_public_key);
|
||||
let cipher = XChaCha20Poly1305::new(shared_secret.as_bytes().into());
|
||||
|
||||
let mut key_buffer = SafeCell::new(ciphertext.to_vec());
|
||||
|
||||
let decryption_result = key_buffer.write_inline(|write_handle| {
|
||||
cipher.decrypt_in_place(nonce, associated_data, write_handle)
|
||||
});
|
||||
|
||||
match decryption_result {
|
||||
Ok(_) => Ok(key_buffer),
|
||||
Err(err) => {
|
||||
error!(?err, "Failed to decrypt encrypted key material");
|
||||
Err(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UnsealStartResponse {
|
||||
pub server_pubkey: PublicKey,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum UnsealError {
|
||||
#[error("Invalid key provided for unsealing")]
|
||||
InvalidKey,
|
||||
#[error("Internal error during unsealing process")]
|
||||
General(#[from] super::Error),
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum BootstrapError {
|
||||
#[error("Invalid key provided for bootstrapping")]
|
||||
InvalidKey,
|
||||
#[error("Vault is already bootstrapped")]
|
||||
AlreadyBootstrapped,
|
||||
|
||||
#[error("Internal error during bootstrapping process")]
|
||||
General(#[from] super::Error),
|
||||
}
|
||||
|
||||
#[messages]
|
||||
impl UserAgentSession {
|
||||
#[message]
|
||||
pub async fn handle_unseal_request(
|
||||
&mut self,
|
||||
client_pubkey: x25519_dalek::PublicKey,
|
||||
) -> Result<UnsealStartResponse, Error> {
|
||||
let secret = EphemeralSecret::random();
|
||||
let public_key = PublicKey::from(&secret);
|
||||
|
||||
self.transition(UserAgentEvents::UnsealRequest(UnsealContext {
|
||||
secret: Mutex::new(Some(secret)),
|
||||
client_public_key: client_pubkey,
|
||||
}))?;
|
||||
|
||||
Ok(UnsealStartResponse {
|
||||
server_pubkey: public_key,
|
||||
})
|
||||
}
|
||||
|
||||
#[message]
|
||||
pub async fn handle_unseal_encrypted_key(
|
||||
&mut self,
|
||||
nonce: Vec<u8>,
|
||||
ciphertext: Vec<u8>,
|
||||
associated_data: Vec<u8>,
|
||||
) -> Result<(), UnsealError> {
|
||||
let (ephemeral_secret, client_public_key) = match self.take_unseal_secret() {
|
||||
Ok(values) => values,
|
||||
Err(Error::State) => {
|
||||
self.transition(UserAgentEvents::ReceivedInvalidKey)?;
|
||||
return Err(UnsealError::InvalidKey);
|
||||
}
|
||||
Err(_err) => {
|
||||
return Err(Error::internal("Failed to take unseal secret").into());
|
||||
}
|
||||
};
|
||||
|
||||
let seal_key_buffer = match Self::decrypt_client_key_material(
|
||||
ephemeral_secret,
|
||||
client_public_key,
|
||||
&nonce,
|
||||
&ciphertext,
|
||||
&associated_data,
|
||||
) {
|
||||
Ok(buffer) => buffer,
|
||||
Err(()) => {
|
||||
self.transition(UserAgentEvents::ReceivedInvalidKey)?;
|
||||
return Err(UnsealError::InvalidKey);
|
||||
}
|
||||
};
|
||||
|
||||
match self
|
||||
.props
|
||||
.actors
|
||||
.key_holder
|
||||
.ask(TryUnseal {
|
||||
seal_key_raw: seal_key_buffer,
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
info!("Successfully unsealed key with client-provided key");
|
||||
self.transition(UserAgentEvents::ReceivedValidKey)?;
|
||||
Ok(())
|
||||
}
|
||||
Err(SendError::HandlerError(keyholder::Error::InvalidKey)) => {
|
||||
self.transition(UserAgentEvents::ReceivedInvalidKey)?;
|
||||
Err(UnsealError::InvalidKey)
|
||||
}
|
||||
Err(SendError::HandlerError(err)) => {
|
||||
error!(?err, "Keyholder failed to unseal key");
|
||||
self.transition(UserAgentEvents::ReceivedInvalidKey)?;
|
||||
Err(UnsealError::InvalidKey)
|
||||
}
|
||||
Err(err) => {
|
||||
error!(?err, "Failed to send unseal request to keyholder");
|
||||
self.transition(UserAgentEvents::ReceivedInvalidKey)?;
|
||||
Err(Error::internal("Vault actor error").into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[message]
|
||||
pub(crate) async fn handle_bootstrap_encrypted_key(
|
||||
&mut self,
|
||||
nonce: Vec<u8>,
|
||||
ciphertext: Vec<u8>,
|
||||
associated_data: Vec<u8>,
|
||||
) -> Result<(), BootstrapError> {
|
||||
let (ephemeral_secret, client_public_key) = match self.take_unseal_secret() {
|
||||
Ok(values) => values,
|
||||
Err(Error::State) => {
|
||||
self.transition(UserAgentEvents::ReceivedInvalidKey)?;
|
||||
return Err(BootstrapError::InvalidKey);
|
||||
}
|
||||
Err(err) => return Err(err.into()),
|
||||
};
|
||||
|
||||
let seal_key_buffer = match Self::decrypt_client_key_material(
|
||||
ephemeral_secret,
|
||||
client_public_key,
|
||||
&nonce,
|
||||
&ciphertext,
|
||||
&associated_data,
|
||||
) {
|
||||
Ok(buffer) => buffer,
|
||||
Err(()) => {
|
||||
self.transition(UserAgentEvents::ReceivedInvalidKey)?;
|
||||
return Err(BootstrapError::InvalidKey);
|
||||
}
|
||||
};
|
||||
|
||||
match self
|
||||
.props
|
||||
.actors
|
||||
.key_holder
|
||||
.ask(Bootstrap {
|
||||
seal_key_raw: seal_key_buffer,
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
info!("Successfully bootstrapped vault with client-provided key");
|
||||
self.transition(UserAgentEvents::ReceivedValidKey)?;
|
||||
Ok(())
|
||||
}
|
||||
Err(SendError::HandlerError(keyholder::Error::AlreadyBootstrapped)) => {
|
||||
self.transition(UserAgentEvents::ReceivedInvalidKey)?;
|
||||
Err(BootstrapError::AlreadyBootstrapped)
|
||||
}
|
||||
Err(SendError::HandlerError(err)) => {
|
||||
error!(?err, "Keyholder failed to bootstrap vault");
|
||||
self.transition(UserAgentEvents::ReceivedInvalidKey)?;
|
||||
Err(BootstrapError::InvalidKey)
|
||||
}
|
||||
Err(err) => {
|
||||
error!(?err, "Failed to send bootstrap request to keyholder");
|
||||
self.transition(UserAgentEvents::ReceivedInvalidKey)?;
|
||||
Err(BootstrapError::General(Error::internal(
|
||||
"Vault actor error",
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[messages]
|
||||
impl UserAgentSession {
|
||||
#[message]
|
||||
pub(crate) async fn handle_query_vault_state(&mut self) -> Result<KeyHolderState, Error> {
|
||||
use crate::actors::keyholder::GetState;
|
||||
|
||||
let vault_state = match self.props.actors.key_holder.ask(GetState {}).await {
|
||||
Ok(state) => state,
|
||||
Err(err) => {
|
||||
error!(?err, actor = "useragent", "keyholder.query.failed");
|
||||
return Err(Error::internal("Vault is in broken state"));
|
||||
}
|
||||
};
|
||||
|
||||
Ok(vault_state)
|
||||
}
|
||||
}
|
||||
|
||||
#[messages]
|
||||
impl UserAgentSession {
|
||||
#[message]
|
||||
pub(crate) async fn handle_evm_wallet_create(&mut self) -> Result<Address, Error> {
|
||||
match self.props.actors.evm.ask(Generate {}).await {
|
||||
Ok(address) => Ok(address),
|
||||
Err(SendError::HandlerError(err)) => Err(Error::internal(format!(
|
||||
"EVM wallet generation failed: {err}"
|
||||
))),
|
||||
Err(err) => {
|
||||
error!(?err, "EVM actor unreachable during wallet create");
|
||||
Err(Error::internal("EVM actor unreachable"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[message]
|
||||
pub(crate) async fn handle_evm_wallet_list(&mut self) -> Result<Vec<Address>, Error> {
|
||||
match self.props.actors.evm.ask(ListWallets {}).await {
|
||||
Ok(wallets) => Ok(wallets),
|
||||
Err(err) => {
|
||||
error!(?err, "EVM wallet list failed");
|
||||
Err(Error::internal("Failed to list EVM wallets"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[messages]
|
||||
impl UserAgentSession {
|
||||
#[message]
|
||||
pub(crate) async fn handle_grant_list(&mut self) -> Result<Vec<Grant<SpecificGrant>>, Error> {
|
||||
match self.props.actors.evm.ask(UseragentListGrants {}).await {
|
||||
Ok(grants) => Ok(grants),
|
||||
Err(err) => {
|
||||
error!(?err, "EVM grant list failed");
|
||||
Err(Error::internal("Failed to list EVM grants"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[message]
|
||||
pub(crate) async fn handle_grant_create(
|
||||
&mut self,
|
||||
client_id: i32,
|
||||
basic: crate::evm::policies::SharedGrantSettings,
|
||||
grant: crate::evm::policies::SpecificGrant,
|
||||
) -> Result<i32, Error> {
|
||||
match self
|
||||
.props
|
||||
.actors
|
||||
.evm
|
||||
.ask(UseragentCreateGrant {
|
||||
client_id,
|
||||
basic,
|
||||
grant,
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(grant_id) => Ok(grant_id),
|
||||
Err(err) => {
|
||||
error!(?err, "EVM grant create failed");
|
||||
Err(Error::internal("Failed to create EVM grant"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[message]
|
||||
pub(crate) async fn handle_grant_delete(&mut self, grant_id: i32) -> Result<(), Error> {
|
||||
match self
|
||||
.props
|
||||
.actors
|
||||
.evm
|
||||
.ask(UseragentDeleteGrant { grant_id })
|
||||
.await
|
||||
{
|
||||
Ok(()) => Ok(()),
|
||||
Err(err) => {
|
||||
error!(?err, "EVM grant delete failed");
|
||||
Err(Error::internal("Failed to delete EVM grant"))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ use rcgen::{
|
||||
BasicConstraints, Certificate, CertificateParams, CertifiedIssuer, DistinguishedName, DnType,
|
||||
IsCa, Issuer, KeyPair, KeyUsagePurpose,
|
||||
};
|
||||
use rustls::pki_types::{pem::PemObject};
|
||||
use rustls::pki_types::pem::PemObject;
|
||||
use thiserror::Error;
|
||||
use tonic::transport::CertificateDer;
|
||||
|
||||
@@ -59,10 +59,7 @@ pub enum InitError {
|
||||
pub type PemCert = String;
|
||||
|
||||
pub fn encode_cert_to_pem(cert: &CertificateDer) -> PemCert {
|
||||
pem::encode_config(
|
||||
&Pem::new("CERTIFICATE", cert.to_vec()),
|
||||
ENCODE_CONFIG,
|
||||
)
|
||||
pem::encode_config(&Pem::new("CERTIFICATE", cert.to_vec()), ENCODE_CONFIG)
|
||||
}
|
||||
|
||||
#[allow(unused)]
|
||||
@@ -94,6 +91,10 @@ impl TlsCa {
|
||||
|
||||
let cert_key_pem = certified_issuer.key().serialize_pem();
|
||||
|
||||
#[allow(
|
||||
clippy::unwrap_used,
|
||||
reason = "Broken cert couldn't bootstrap server anyway"
|
||||
)]
|
||||
let issuer = Issuer::from_ca_cert_pem(
|
||||
&certified_issuer.pem(),
|
||||
KeyPair::from_pem(cert_key_pem.as_ref()).unwrap(),
|
||||
|
||||
@@ -44,6 +44,14 @@ pub enum DatabaseSetupError {
|
||||
Pool(#[from] PoolInitError),
|
||||
}
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum DatabaseError {
|
||||
#[error("Database connection error")]
|
||||
Pool(#[from] PoolError),
|
||||
#[error("Database query error")]
|
||||
Connection(#[from] diesel::result::Error),
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "info")]
|
||||
fn database_path() -> Result<std::path::PathBuf, DatabaseSetupError> {
|
||||
let arbiter_home = arbiter_proto::home_path().map_err(DatabaseSetupError::HomeDir)?;
|
||||
@@ -92,6 +100,7 @@ fn initialize_database(url: &str) -> Result<(), DatabaseSetupError> {
|
||||
#[tracing::instrument(level = "info")]
|
||||
pub async fn create_pool(url: Option<&str>) -> Result<DatabasePool, DatabaseSetupError> {
|
||||
let database_url = url.map(String::from).unwrap_or(
|
||||
#[allow(clippy::expect_used)]
|
||||
database_path()?
|
||||
.to_str()
|
||||
.expect("database path is not valid UTF-8")
|
||||
@@ -135,11 +144,13 @@ pub async fn create_test_pool() -> DatabasePool {
|
||||
let tempfile_name = Alphanumeric.sample_string(&mut rand::rng(), 16);
|
||||
|
||||
let file = std::env::temp_dir().join(tempfile_name);
|
||||
#[allow(clippy::expect_used)]
|
||||
let url = file
|
||||
.to_str()
|
||||
.expect("temp file path is not valid UTF-8")
|
||||
.to_string();
|
||||
|
||||
#[allow(clippy::expect_used)]
|
||||
create_pool(Some(&url))
|
||||
.await
|
||||
.expect("Failed to create test database pool")
|
||||
|
||||
@@ -117,9 +117,7 @@ async fn check_shared_constraints(
|
||||
let now = Utc::now();
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
@@ -127,9 +125,9 @@ async fn check_shared_constraints(
|
||||
let fee_exceeded = shared
|
||||
.max_gas_fee_per_gas
|
||||
.is_some_and(|cap| U256::from(context.max_fee_per_gas) > cap);
|
||||
let priority_exceeded = shared.max_priority_fee_per_gas.is_some_and(|cap| {
|
||||
U256::from(context.max_priority_fee_per_gas) > cap
|
||||
});
|
||||
let priority_exceeded = shared
|
||||
.max_priority_fee_per_gas
|
||||
.is_some_and(|cap| U256::from(context.max_priority_fee_per_gas) > cap);
|
||||
if fee_exceeded || priority_exceeded {
|
||||
violations.push(EvalViolation::GasLimitExceeded {
|
||||
max_gas_fee_per_gas: shared.max_gas_fee_per_gas,
|
||||
|
||||
@@ -66,6 +66,7 @@ pub enum EvalViolation {
|
||||
|
||||
pub type DatabaseID = i32;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Grant<PolicySettings> {
|
||||
pub id: DatabaseID,
|
||||
pub shared_grant_id: DatabaseID, // ID of the basic grant for shared-logic checks like rate limits and validity periods
|
||||
@@ -73,7 +74,6 @@ pub struct Grant<PolicySettings> {
|
||||
pub settings: PolicySettings,
|
||||
}
|
||||
|
||||
|
||||
pub trait Policy: Sized {
|
||||
type Settings: Send + Sync + 'static + Into<SpecificGrant>;
|
||||
type Meaning: Display + std::fmt::Debug + Send + Sync + 'static + Into<SpecificMeaning>;
|
||||
@@ -146,6 +146,7 @@ pub struct VolumeRateLimit {
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct SharedGrantSettings {
|
||||
pub wallet_id: i32,
|
||||
pub client_id: i32,
|
||||
pub chain: ChainId,
|
||||
|
||||
pub valid_from: Option<DateTime<Utc>>,
|
||||
@@ -161,6 +162,7 @@ impl SharedGrantSettings {
|
||||
fn try_from_model(model: EvmBasicGrant) -> QueryResult<Self> {
|
||||
Ok(Self {
|
||||
wallet_id: model.wallet_id,
|
||||
client_id: model.client_id,
|
||||
chain: model.chain_id as u64, // safe because chain_id is stored as i32 but is guaranteed to be a valid ChainId by the API when creating grants
|
||||
valid_from: model.valid_from.map(Into::into),
|
||||
valid_until: model.valid_until.map(Into::into),
|
||||
@@ -198,6 +200,7 @@ impl SharedGrantSettings {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum SpecificGrant {
|
||||
EtherTransfer(ether_transfer::Settings),
|
||||
TokenTransfer(token_transfers::Settings),
|
||||
|
||||
@@ -51,9 +51,10 @@ impl From<Meaning> for SpecificMeaning {
|
||||
}
|
||||
|
||||
// A grant for ether transfers, which can be scoped to specific target addresses and volume limits
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Settings {
|
||||
target: Vec<Address>,
|
||||
limit: VolumeRateLimit,
|
||||
pub target: Vec<Address>,
|
||||
pub limit: VolumeRateLimit,
|
||||
}
|
||||
|
||||
impl From<Settings> for SpecificGrant {
|
||||
|
||||
@@ -9,9 +9,7 @@ use crate::db::{
|
||||
schema::{evm_basic_grant, evm_transaction_log},
|
||||
};
|
||||
use crate::evm::{
|
||||
policies::{
|
||||
EvalContext, EvalViolation, Grant, Policy, SharedGrantSettings, VolumeRateLimit,
|
||||
},
|
||||
policies::{EvalContext, EvalViolation, Grant, Policy, SharedGrantSettings, VolumeRateLimit},
|
||||
utils,
|
||||
};
|
||||
|
||||
@@ -76,6 +74,7 @@ fn shared() -> SharedGrantSettings {
|
||||
max_gas_fee_per_gas: None,
|
||||
max_priority_fee_per_gas: None,
|
||||
rate_limit: None,
|
||||
client_id: CLIENT_ID,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -58,10 +58,11 @@ impl From<Meaning> for SpecificMeaning {
|
||||
}
|
||||
|
||||
// A grant for token transfers, which can be scoped to specific target addresses and volume limits
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Settings {
|
||||
token_contract: Address,
|
||||
target: Option<Address>,
|
||||
volume_limits: Vec<VolumeRateLimit>,
|
||||
pub token_contract: Address,
|
||||
pub target: Option<Address>,
|
||||
pub volume_limits: Vec<VolumeRateLimit>,
|
||||
}
|
||||
impl From<Settings> for SpecificGrant {
|
||||
fn from(val: Settings) -> SpecificGrant {
|
||||
|
||||
@@ -93,6 +93,7 @@ fn shared() -> SharedGrantSettings {
|
||||
max_gas_fee_per_gas: None,
|
||||
max_priority_fee_per_gas: None,
|
||||
rate_limit: None,
|
||||
client_id: CLIENT_ID,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,10 +141,18 @@ async fn evaluate_rejects_nonzero_eth_value() {
|
||||
let mut context = ctx(DAI, calldata);
|
||||
context.value = U256::from(1u64); // ETH attached to an ERC-20 call
|
||||
|
||||
let m = TokenTransfer::analyze(&EvalContext { value: U256::ZERO, ..context.clone() })
|
||||
let m = TokenTransfer::analyze(&EvalContext {
|
||||
value: U256::ZERO,
|
||||
..context.clone()
|
||||
})
|
||||
.unwrap();
|
||||
let v = TokenTransfer::evaluate(&context, &m, &grant, &mut *conn)
|
||||
.await
|
||||
.unwrap();
|
||||
let v = TokenTransfer::evaluate(&context, &m, &grant, &mut *conn).await.unwrap();
|
||||
assert!(v.iter().any(|e| matches!(e, EvalViolation::InvalidTransactionType)));
|
||||
assert!(
|
||||
v.iter()
|
||||
.any(|e| matches!(e, EvalViolation::InvalidTransactionType))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -160,7 +169,9 @@ async fn evaluate_passes_any_recipient_when_no_restriction() {
|
||||
let calldata = transfer_calldata(RECIPIENT, U256::from(100u64));
|
||||
let context = ctx(DAI, calldata);
|
||||
let m = TokenTransfer::analyze(&context).unwrap();
|
||||
let v = TokenTransfer::evaluate(&context, &m, &grant, &mut *conn).await.unwrap();
|
||||
let v = TokenTransfer::evaluate(&context, &m, &grant, &mut *conn)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(v.is_empty());
|
||||
}
|
||||
|
||||
@@ -178,7 +189,9 @@ async fn evaluate_passes_matching_restricted_recipient() {
|
||||
let calldata = transfer_calldata(RECIPIENT, U256::from(100u64));
|
||||
let context = ctx(DAI, calldata);
|
||||
let m = TokenTransfer::analyze(&context).unwrap();
|
||||
let v = TokenTransfer::evaluate(&context, &m, &grant, &mut *conn).await.unwrap();
|
||||
let v = TokenTransfer::evaluate(&context, &m, &grant, &mut *conn)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(v.is_empty());
|
||||
}
|
||||
|
||||
@@ -196,8 +209,13 @@ async fn evaluate_rejects_wrong_restricted_recipient() {
|
||||
let calldata = transfer_calldata(OTHER, U256::from(100u64));
|
||||
let context = ctx(DAI, calldata);
|
||||
let m = TokenTransfer::analyze(&context).unwrap();
|
||||
let v = TokenTransfer::evaluate(&context, &m, &grant, &mut *conn).await.unwrap();
|
||||
assert!(v.iter().any(|e| matches!(e, EvalViolation::InvalidTarget { .. })));
|
||||
let v = TokenTransfer::evaluate(&context, &m, &grant, &mut *conn)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
v.iter()
|
||||
.any(|e| matches!(e, EvalViolation::InvalidTarget { .. }))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -207,7 +225,9 @@ async fn evaluate_passes_volume_within_limit() {
|
||||
|
||||
let basic = insert_basic(&mut conn, false).await;
|
||||
let settings = make_settings(None, Some(1_000));
|
||||
let grant_id = TokenTransfer::create_grant(&basic, &settings, &mut *conn).await.unwrap();
|
||||
let grant_id = TokenTransfer::create_grant(&basic, &settings, &mut *conn)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Record a past transfer of 500 (within 1000 limit)
|
||||
use crate::db::{models::NewEvmTokenTransferLog, schema::evm_token_transfer_log};
|
||||
@@ -224,12 +244,22 @@ async fn evaluate_passes_volume_within_limit() {
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let grant = Grant { id: grant_id, shared_grant_id: basic.id, shared: shared(), settings };
|
||||
let grant = Grant {
|
||||
id: grant_id,
|
||||
shared_grant_id: basic.id,
|
||||
shared: shared(),
|
||||
settings,
|
||||
};
|
||||
let calldata = transfer_calldata(RECIPIENT, U256::from(100u64));
|
||||
let context = ctx(DAI, calldata);
|
||||
let m = TokenTransfer::analyze(&context).unwrap();
|
||||
let v = TokenTransfer::evaluate(&context, &m, &grant, &mut *conn).await.unwrap();
|
||||
assert!(!v.iter().any(|e| matches!(e, EvalViolation::VolumetricLimitExceeded)));
|
||||
let v = TokenTransfer::evaluate(&context, &m, &grant, &mut *conn)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
!v.iter()
|
||||
.any(|e| matches!(e, EvalViolation::VolumetricLimitExceeded))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -239,7 +269,9 @@ async fn evaluate_rejects_volume_over_limit() {
|
||||
|
||||
let basic = insert_basic(&mut conn, false).await;
|
||||
let settings = make_settings(None, Some(1_000));
|
||||
let grant_id = TokenTransfer::create_grant(&basic, &settings, &mut *conn).await.unwrap();
|
||||
let grant_id = TokenTransfer::create_grant(&basic, &settings, &mut *conn)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
use crate::db::{models::NewEvmTokenTransferLog, schema::evm_token_transfer_log};
|
||||
insert_into(evm_token_transfer_log::table)
|
||||
@@ -255,12 +287,22 @@ async fn evaluate_rejects_volume_over_limit() {
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let grant = Grant { id: grant_id, shared_grant_id: basic.id, shared: shared(), settings };
|
||||
let grant = Grant {
|
||||
id: grant_id,
|
||||
shared_grant_id: basic.id,
|
||||
shared: shared(),
|
||||
settings,
|
||||
};
|
||||
let calldata = transfer_calldata(RECIPIENT, U256::from(100u64));
|
||||
let context = ctx(DAI, calldata);
|
||||
let m = TokenTransfer::analyze(&context).unwrap();
|
||||
let v = TokenTransfer::evaluate(&context, &m, &grant, &mut *conn).await.unwrap();
|
||||
assert!(v.iter().any(|e| matches!(e, EvalViolation::VolumetricLimitExceeded)));
|
||||
let v = TokenTransfer::evaluate(&context, &m, &grant, &mut *conn)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
v.iter()
|
||||
.any(|e| matches!(e, EvalViolation::VolumetricLimitExceeded))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -277,8 +319,13 @@ async fn evaluate_no_volume_limits_always_passes() {
|
||||
let calldata = transfer_calldata(RECIPIENT, U256::from(u64::MAX));
|
||||
let context = ctx(DAI, calldata);
|
||||
let m = TokenTransfer::analyze(&context).unwrap();
|
||||
let v = TokenTransfer::evaluate(&context, &m, &grant, &mut *conn).await.unwrap();
|
||||
assert!(!v.iter().any(|e| matches!(e, EvalViolation::VolumetricLimitExceeded)));
|
||||
let v = TokenTransfer::evaluate(&context, &m, &grant, &mut *conn)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
!v.iter()
|
||||
.any(|e| matches!(e, EvalViolation::VolumetricLimitExceeded))
|
||||
);
|
||||
}
|
||||
|
||||
// ── try_find_grant ───────────────────────────────────────────────────────
|
||||
@@ -290,7 +337,9 @@ async fn try_find_grant_roundtrip() {
|
||||
|
||||
let basic = insert_basic(&mut conn, false).await;
|
||||
let settings = make_settings(Some(RECIPIENT), Some(5_000));
|
||||
TokenTransfer::create_grant(&basic, &settings, &mut *conn).await.unwrap();
|
||||
TokenTransfer::create_grant(&basic, &settings, &mut *conn)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let calldata = transfer_calldata(RECIPIENT, U256::from(100u64));
|
||||
let found = TokenTransfer::try_find_grant(&ctx(DAI, calldata), &mut *conn)
|
||||
@@ -312,7 +361,9 @@ async fn try_find_grant_revoked_returns_none() {
|
||||
|
||||
let basic = insert_basic(&mut conn, true).await;
|
||||
let settings = make_settings(None, None);
|
||||
TokenTransfer::create_grant(&basic, &settings, &mut *conn).await.unwrap();
|
||||
TokenTransfer::create_grant(&basic, &settings, &mut *conn)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let calldata = transfer_calldata(RECIPIENT, U256::from(1u64));
|
||||
let found = TokenTransfer::try_find_grant(&ctx(DAI, calldata), &mut *conn)
|
||||
@@ -328,7 +379,9 @@ async fn try_find_grant_unknown_token_returns_none() {
|
||||
|
||||
let basic = insert_basic(&mut conn, false).await;
|
||||
let settings = make_settings(None, None);
|
||||
TokenTransfer::create_grant(&basic, &settings, &mut *conn).await.unwrap();
|
||||
TokenTransfer::create_grant(&basic, &settings, &mut *conn)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Query with a different token contract
|
||||
let calldata = transfer_calldata(RECIPIENT, U256::from(1u64));
|
||||
@@ -355,9 +408,13 @@ async fn find_all_grants_excludes_revoked() {
|
||||
|
||||
let settings = make_settings(None, Some(1_000));
|
||||
let active = insert_basic(&mut conn, false).await;
|
||||
TokenTransfer::create_grant(&active, &settings, &mut *conn).await.unwrap();
|
||||
TokenTransfer::create_grant(&active, &settings, &mut *conn)
|
||||
.await
|
||||
.unwrap();
|
||||
let revoked = insert_basic(&mut conn, true).await;
|
||||
TokenTransfer::create_grant(&revoked, &settings, &mut *conn).await.unwrap();
|
||||
TokenTransfer::create_grant(&revoked, &settings, &mut *conn)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let all = TokenTransfer::find_all_grants(&mut *conn).await.unwrap();
|
||||
assert_eq!(all.len(), 1);
|
||||
@@ -370,12 +427,17 @@ async fn find_all_grants_loads_volume_limits() {
|
||||
|
||||
let basic = insert_basic(&mut conn, false).await;
|
||||
let settings = make_settings(None, Some(9_999));
|
||||
TokenTransfer::create_grant(&basic, &settings, &mut *conn).await.unwrap();
|
||||
TokenTransfer::create_grant(&basic, &settings, &mut *conn)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let all = TokenTransfer::find_all_grants(&mut *conn).await.unwrap();
|
||||
assert_eq!(all.len(), 1);
|
||||
assert_eq!(all[0].settings.volume_limits.len(), 1);
|
||||
assert_eq!(all[0].settings.volume_limits[0].max_volume, U256::from(9_999u64));
|
||||
assert_eq!(
|
||||
all[0].settings.volume_limits[0].max_volume,
|
||||
U256::from(9_999u64)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -388,9 +450,13 @@ async fn find_all_grants_multiple_grants_batch_loaded() {
|
||||
.await
|
||||
.unwrap();
|
||||
let b2 = insert_basic(&mut conn, false).await;
|
||||
TokenTransfer::create_grant(&b2, &make_settings(Some(RECIPIENT), Some(2_000)), &mut *conn)
|
||||
.await
|
||||
.unwrap();
|
||||
TokenTransfer::create_grant(
|
||||
&b2,
|
||||
&make_settings(Some(RECIPIENT), Some(2_000)),
|
||||
&mut *conn,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let all = TokenTransfer::find_all_grants(&mut *conn).await.unwrap();
|
||||
assert_eq!(all.len(), 2);
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
use std::sync::Mutex;
|
||||
|
||||
use crate::safe_cell::{SafeCell, SafeCellHandle as _};
|
||||
use alloy::{
|
||||
consensus::SignableTransaction,
|
||||
network::{TxSigner, TxSignerSync},
|
||||
primitives::{Address, ChainId, Signature, B256},
|
||||
primitives::{Address, B256, ChainId, Signature},
|
||||
signers::{Error, Result, Signer, SignerSync, utils::secret_key_to_address},
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use k256::ecdsa::{self, signature::hazmat::PrehashSigner, RecoveryId, SigningKey};
|
||||
use memsafe::MemSafe;
|
||||
use k256::ecdsa::{self, RecoveryId, SigningKey, signature::hazmat::PrehashSigner};
|
||||
|
||||
/// An Ethereum signer that stores its secp256k1 secret key inside a
|
||||
/// hardware-protected [`MemSafe`] cell.
|
||||
@@ -20,7 +20,7 @@ use memsafe::MemSafe;
|
||||
/// Because [`MemSafe::read`] requires `&mut self` while the [`Signer`] trait
|
||||
/// requires `&self`, the cell is wrapped in a [`Mutex`].
|
||||
pub struct SafeSigner {
|
||||
key: Mutex<MemSafe<SigningKey>>,
|
||||
key: Mutex<SafeCell<SigningKey>>,
|
||||
address: Address,
|
||||
chain_id: Option<ChainId>,
|
||||
}
|
||||
@@ -42,14 +42,13 @@ impl std::fmt::Debug for SafeSigner {
|
||||
/// rejection, but we retry to be correct).
|
||||
///
|
||||
/// Returns the protected key bytes and the derived Ethereum address.
|
||||
pub fn generate(rng: &mut impl rand::Rng) -> (MemSafe<[u8; 32]>, Address) {
|
||||
pub fn generate(rng: &mut impl rand::Rng) -> (SafeCell<[u8; 32]>, Address) {
|
||||
loop {
|
||||
let mut cell = MemSafe::new([0u8; 32]).expect("MemSafe allocation");
|
||||
{
|
||||
let mut w = cell.write().expect("MemSafe write");
|
||||
rng.fill_bytes(w.as_mut());
|
||||
}
|
||||
let reader = cell.read().expect("MemSafe read");
|
||||
let mut cell = SafeCell::new_inline(|w: &mut [u8; 32]| {
|
||||
rng.fill_bytes(w);
|
||||
});
|
||||
|
||||
let reader = cell.read();
|
||||
if let Ok(sk) = SigningKey::from_slice(reader.as_ref()) {
|
||||
let address = secret_key_to_address(&sk);
|
||||
drop(reader);
|
||||
@@ -64,8 +63,8 @@ impl SafeSigner {
|
||||
/// The key bytes are read from protected memory, parsed as a secp256k1
|
||||
/// scalar, and immediately moved into a new [`MemSafe`] cell. The raw
|
||||
/// bytes are never exposed outside this function.
|
||||
pub fn from_memsafe(mut cell: MemSafe<Vec<u8>>) -> Result<Self> {
|
||||
let reader = cell.read().map_err(Error::other)?;
|
||||
pub fn from_cell(mut cell: SafeCell<Vec<u8>>) -> Result<Self> {
|
||||
let reader = cell.read();
|
||||
let sk = SigningKey::from_slice(reader.as_slice()).map_err(Error::other)?;
|
||||
drop(reader);
|
||||
Self::new(sk)
|
||||
@@ -75,7 +74,7 @@ impl SafeSigner {
|
||||
/// memory region.
|
||||
pub fn new(key: SigningKey) -> Result<Self> {
|
||||
let address = secret_key_to_address(&key);
|
||||
let cell = MemSafe::new(key).map_err(Error::other)?;
|
||||
let cell = SafeCell::new(key);
|
||||
Ok(Self {
|
||||
key: Mutex::new(cell),
|
||||
address,
|
||||
@@ -84,25 +83,25 @@ impl SafeSigner {
|
||||
}
|
||||
|
||||
fn sign_hash_inner(&self, hash: &B256) -> Result<Signature> {
|
||||
#[allow(clippy::expect_used)]
|
||||
let mut cell = self.key.lock().expect("SafeSigner mutex poisoned");
|
||||
let reader = cell.read().map_err(Error::other)?;
|
||||
let reader = cell.read();
|
||||
let sig: (ecdsa::Signature, RecoveryId) = reader.sign_prehash(hash.as_ref())?;
|
||||
Ok(sig.into())
|
||||
}
|
||||
|
||||
fn sign_tx_inner(
|
||||
&self,
|
||||
tx: &mut dyn SignableTransaction<Signature>,
|
||||
) -> Result<Signature> {
|
||||
fn sign_tx_inner(&self, tx: &mut dyn SignableTransaction<Signature>) -> Result<Signature> {
|
||||
if let Some(chain_id) = self.chain_id
|
||||
&& !tx.set_chain_id_checked(chain_id)
|
||||
{
|
||||
return Err(Error::TransactionChainIdMismatch {
|
||||
signer: chain_id,
|
||||
tx: tx.chain_id().unwrap(),
|
||||
#[allow(clippy::expect_used)]
|
||||
tx: tx.chain_id().expect("Chain ID is guaranteed to be set"),
|
||||
});
|
||||
}
|
||||
self.sign_hash_inner(&tx.signature_hash()).map_err(Error::other)
|
||||
self.sign_hash_inner(&tx.signature_hash())
|
||||
.map_err(Error::other)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
137
server/crates/arbiter-server/src/grpc/client.rs
Normal file
137
server/crates/arbiter-server/src/grpc/client.rs
Normal file
@@ -0,0 +1,137 @@
|
||||
use arbiter_proto::{
|
||||
proto::client::{
|
||||
ClientRequest, ClientResponse, VaultState as ProtoVaultState,
|
||||
client_request::Payload as ClientRequestPayload,
|
||||
client_response::Payload as ClientResponsePayload,
|
||||
},
|
||||
transport::{Receiver, Sender, grpc::GrpcBi},
|
||||
};
|
||||
use kameo::{
|
||||
actor::{ActorRef, Spawn as _},
|
||||
error::SendError,
|
||||
};
|
||||
use tonic::Status;
|
||||
use tracing::{info, warn};
|
||||
|
||||
use crate::{
|
||||
actors::{
|
||||
client::{
|
||||
self, ClientConnection,
|
||||
session::{ClientSession, Error, HandleQueryVaultState},
|
||||
},
|
||||
keyholder::KeyHolderState,
|
||||
},
|
||||
grpc::request_tracker::RequestTracker,
|
||||
utils::defer,
|
||||
};
|
||||
|
||||
mod auth;
|
||||
|
||||
async fn dispatch_loop(
|
||||
mut bi: GrpcBi<ClientRequest, ClientResponse>,
|
||||
actor: ActorRef<ClientSession>,
|
||||
mut request_tracker: RequestTracker,
|
||||
) {
|
||||
loop {
|
||||
let Some(conn) = bi.recv().await else {
|
||||
return;
|
||||
};
|
||||
|
||||
if dispatch_conn_message(&mut bi, &actor, &mut request_tracker, conn)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn dispatch_conn_message(
|
||||
bi: &mut GrpcBi<ClientRequest, ClientResponse>,
|
||||
actor: &ActorRef<ClientSession>,
|
||||
request_tracker: &mut RequestTracker,
|
||||
conn: Result<ClientRequest, Status>,
|
||||
) -> Result<(), ()> {
|
||||
let conn = match conn {
|
||||
Ok(conn) => conn,
|
||||
Err(err) => {
|
||||
warn!(error = ?err, "Failed to receive client request");
|
||||
return Err(());
|
||||
}
|
||||
};
|
||||
|
||||
let request_id = match request_tracker.request(conn.request_id) {
|
||||
Ok(request_id) => request_id,
|
||||
Err(err) => {
|
||||
let _ = bi.send(Err(err)).await;
|
||||
return Err(());
|
||||
}
|
||||
};
|
||||
let Some(payload) = conn.payload else {
|
||||
let _ = bi
|
||||
.send(Err(Status::invalid_argument(
|
||||
"Missing client request payload",
|
||||
)))
|
||||
.await;
|
||||
return Err(());
|
||||
};
|
||||
|
||||
let payload = match payload {
|
||||
ClientRequestPayload::QueryVaultState(_) => ClientResponsePayload::VaultState(
|
||||
match actor.ask(HandleQueryVaultState {}).await {
|
||||
Ok(KeyHolderState::Unbootstrapped) => ProtoVaultState::Unbootstrapped,
|
||||
Ok(KeyHolderState::Sealed) => ProtoVaultState::Sealed,
|
||||
Ok(KeyHolderState::Unsealed) => ProtoVaultState::Unsealed,
|
||||
Err(SendError::HandlerError(Error::Internal)) => ProtoVaultState::Error,
|
||||
Err(err) => {
|
||||
warn!(error = ?err, "Failed to query vault state");
|
||||
ProtoVaultState::Error
|
||||
}
|
||||
}
|
||||
.into(),
|
||||
),
|
||||
payload => {
|
||||
warn!(?payload, "Unsupported post-auth client request");
|
||||
let _ = bi
|
||||
.send(Err(Status::invalid_argument("Unsupported client request")))
|
||||
.await;
|
||||
return Err(());
|
||||
}
|
||||
};
|
||||
|
||||
bi.send(Ok(ClientResponse {
|
||||
request_id: Some(request_id),
|
||||
payload: Some(payload),
|
||||
}))
|
||||
.await
|
||||
.map_err(|_| ())
|
||||
}
|
||||
|
||||
pub async fn start(conn: ClientConnection, mut bi: GrpcBi<ClientRequest, ClientResponse>) {
|
||||
let mut conn = conn;
|
||||
let mut request_tracker = RequestTracker::default();
|
||||
let mut response_id = None;
|
||||
|
||||
match auth::start(&mut conn, &mut bi, &mut request_tracker, &mut response_id).await {
|
||||
Ok(_) => {
|
||||
let actor =
|
||||
client::session::ClientSession::spawn(client::session::ClientSession::new(conn));
|
||||
let actor_for_cleanup = actor.clone();
|
||||
let _ = defer(move || {
|
||||
actor_for_cleanup.kill();
|
||||
});
|
||||
|
||||
info!("Client authenticated successfully");
|
||||
dispatch_loop(bi, actor, request_tracker).await;
|
||||
}
|
||||
Err(e) => {
|
||||
let mut transport = auth::AuthTransportAdapter::new(
|
||||
&mut bi,
|
||||
&mut request_tracker,
|
||||
&mut response_id,
|
||||
);
|
||||
let _ = transport.send(Err(e.clone())).await;
|
||||
warn!(error = ?e, "Authentication failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
173
server/crates/arbiter-server/src/grpc/client/auth.rs
Normal file
173
server/crates/arbiter-server/src/grpc/client/auth.rs
Normal file
@@ -0,0 +1,173 @@
|
||||
use arbiter_proto::{
|
||||
proto::client::{
|
||||
AuthChallenge as ProtoAuthChallenge, AuthChallengeRequest as ProtoAuthChallengeRequest,
|
||||
AuthChallengeSolution as ProtoAuthChallengeSolution, AuthResult as ProtoAuthResult,
|
||||
ClientRequest, ClientResponse, client_request::Payload as ClientRequestPayload,
|
||||
client_response::Payload as ClientResponsePayload,
|
||||
},
|
||||
transport::{Bi, Error as TransportError, Receiver, Sender, grpc::GrpcBi},
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use tonic::Status;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::{
|
||||
actors::client::{self, ClientConnection, auth},
|
||||
grpc::request_tracker::RequestTracker,
|
||||
};
|
||||
|
||||
pub struct AuthTransportAdapter<'a> {
|
||||
bi: &'a mut GrpcBi<ClientRequest, ClientResponse>,
|
||||
request_tracker: &'a mut RequestTracker,
|
||||
response_id: &'a mut Option<i32>,
|
||||
}
|
||||
|
||||
impl<'a> AuthTransportAdapter<'a> {
|
||||
pub fn new(
|
||||
bi: &'a mut GrpcBi<ClientRequest, ClientResponse>,
|
||||
request_tracker: &'a mut RequestTracker,
|
||||
response_id: &'a mut Option<i32>,
|
||||
) -> Self {
|
||||
Self {
|
||||
bi,
|
||||
request_tracker,
|
||||
response_id,
|
||||
}
|
||||
}
|
||||
|
||||
fn response_to_proto(response: auth::Outbound) -> ClientResponsePayload {
|
||||
match response {
|
||||
auth::Outbound::AuthChallenge { pubkey, nonce } => {
|
||||
ClientResponsePayload::AuthChallenge(ProtoAuthChallenge {
|
||||
pubkey: pubkey.to_bytes().to_vec(),
|
||||
nonce,
|
||||
})
|
||||
}
|
||||
auth::Outbound::AuthSuccess => {
|
||||
ClientResponsePayload::AuthResult(ProtoAuthResult::Success.into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn error_to_proto(error: auth::Error) -> ClientResponsePayload {
|
||||
ClientResponsePayload::AuthResult(
|
||||
match error {
|
||||
auth::Error::InvalidChallengeSolution => ProtoAuthResult::InvalidSignature,
|
||||
auth::Error::ApproveError(auth::ApproveError::Denied) => {
|
||||
ProtoAuthResult::ApprovalDenied
|
||||
}
|
||||
auth::Error::ApproveError(auth::ApproveError::Upstream(
|
||||
crate::actors::router::ApprovalError::NoUserAgentsConnected,
|
||||
)) => ProtoAuthResult::NoUserAgentsOnline,
|
||||
auth::Error::ApproveError(auth::ApproveError::Internal)
|
||||
| auth::Error::DatabasePoolUnavailable
|
||||
| auth::Error::DatabaseOperationFailed
|
||||
| auth::Error::Transport => ProtoAuthResult::Internal,
|
||||
}
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
|
||||
async fn send_client_response(
|
||||
&mut self,
|
||||
payload: ClientResponsePayload,
|
||||
) -> Result<(), TransportError> {
|
||||
let request_id = self.response_id.take();
|
||||
|
||||
self.bi
|
||||
.send(Ok(ClientResponse {
|
||||
request_id,
|
||||
payload: Some(payload),
|
||||
}))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn send_auth_result(&mut self, result: ProtoAuthResult) -> Result<(), TransportError> {
|
||||
self.send_client_response(ClientResponsePayload::AuthResult(result.into()))
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Sender<Result<auth::Outbound, auth::Error>> for AuthTransportAdapter<'_> {
|
||||
async fn send(
|
||||
&mut self,
|
||||
item: Result<auth::Outbound, auth::Error>,
|
||||
) -> Result<(), TransportError> {
|
||||
let payload = match item {
|
||||
Ok(message) => AuthTransportAdapter::response_to_proto(message),
|
||||
Err(err) => AuthTransportAdapter::error_to_proto(err),
|
||||
};
|
||||
|
||||
self.send_client_response(payload).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Receiver<auth::Inbound> for AuthTransportAdapter<'_> {
|
||||
async fn recv(&mut self) -> Option<auth::Inbound> {
|
||||
let request = match self.bi.recv().await? {
|
||||
Ok(request) => request,
|
||||
Err(error) => {
|
||||
warn!(error = ?error, "grpc client recv failed; closing stream");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let request_id = match self.request_tracker.request(request.request_id) {
|
||||
Ok(request_id) => request_id,
|
||||
Err(error) => {
|
||||
let _ = self.bi.send(Err(error)).await;
|
||||
return None;
|
||||
}
|
||||
};
|
||||
*self.response_id = Some(request_id);
|
||||
|
||||
let payload = request.payload?;
|
||||
|
||||
match payload {
|
||||
ClientRequestPayload::AuthChallengeRequest(ProtoAuthChallengeRequest { pubkey }) => {
|
||||
let Ok(pubkey) = <[u8; 32]>::try_from(pubkey) else {
|
||||
let _ = self.send_auth_result(ProtoAuthResult::InvalidKey).await;
|
||||
return None;
|
||||
};
|
||||
let Ok(pubkey) = ed25519_dalek::VerifyingKey::from_bytes(&pubkey) else {
|
||||
let _ = self.send_auth_result(ProtoAuthResult::InvalidKey).await;
|
||||
return None;
|
||||
};
|
||||
Some(auth::Inbound::AuthChallengeRequest { pubkey })
|
||||
}
|
||||
ClientRequestPayload::AuthChallengeSolution(ProtoAuthChallengeSolution {
|
||||
signature,
|
||||
}) => {
|
||||
let Ok(signature) = ed25519_dalek::Signature::try_from(signature.as_slice()) else {
|
||||
let _ = self
|
||||
.send_auth_result(ProtoAuthResult::InvalidSignature)
|
||||
.await;
|
||||
return None;
|
||||
};
|
||||
Some(auth::Inbound::AuthChallengeSolution { signature })
|
||||
}
|
||||
_ => {
|
||||
let _ = self
|
||||
.bi
|
||||
.send(Err(Status::invalid_argument("Unsupported client auth request")))
|
||||
.await;
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Bi<auth::Inbound, Result<auth::Outbound, auth::Error>> for AuthTransportAdapter<'_> {}
|
||||
|
||||
pub async fn start(
|
||||
conn: &mut ClientConnection,
|
||||
bi: &mut GrpcBi<ClientRequest, ClientResponse>,
|
||||
request_tracker: &mut RequestTracker,
|
||||
response_id: &mut Option<i32>,
|
||||
) -> Result<(), auth::Error> {
|
||||
let mut transport = AuthTransportAdapter::new(bi, request_tracker, response_id);
|
||||
client::auth::authenticate(conn, &mut transport).await?;
|
||||
Ok(())
|
||||
}
|
||||
62
server/crates/arbiter-server/src/grpc/mod.rs
Normal file
62
server/crates/arbiter-server/src/grpc/mod.rs
Normal file
@@ -0,0 +1,62 @@
|
||||
use arbiter_proto::{
|
||||
proto::{
|
||||
client::{ClientRequest, ClientResponse},
|
||||
user_agent::{UserAgentRequest, UserAgentResponse},
|
||||
},
|
||||
transport::grpc::GrpcBi,
|
||||
};
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
use tonic::{Request, Response, Status, async_trait};
|
||||
use tracing::info;
|
||||
|
||||
use crate::{
|
||||
actors::{client::ClientConnection, user_agent::UserAgentConnection},
|
||||
grpc::user_agent::start,
|
||||
};
|
||||
|
||||
pub mod client;
|
||||
mod request_tracker;
|
||||
pub mod user_agent;
|
||||
|
||||
#[async_trait]
|
||||
impl arbiter_proto::proto::arbiter_service_server::ArbiterService for super::Server {
|
||||
type UserAgentStream = ReceiverStream<Result<UserAgentResponse, Status>>;
|
||||
type ClientStream = ReceiverStream<Result<ClientResponse, Status>>;
|
||||
|
||||
#[tracing::instrument(level = "debug", skip(self))]
|
||||
async fn client(
|
||||
&self,
|
||||
request: Request<tonic::Streaming<ClientRequest>>,
|
||||
) -> Result<Response<Self::ClientStream>, Status> {
|
||||
let req_stream = request.into_inner();
|
||||
let (bi, rx) = GrpcBi::from_bi_stream(req_stream);
|
||||
let props = ClientConnection::new(self.context.db.clone(), self.context.actors.clone());
|
||||
tokio::spawn(client::start(props, bi));
|
||||
|
||||
info!(event = "connection established", "grpc.client");
|
||||
|
||||
Ok(Response::new(rx))
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug", skip(self))]
|
||||
async fn user_agent(
|
||||
&self,
|
||||
request: Request<tonic::Streaming<UserAgentRequest>>,
|
||||
) -> Result<Response<Self::UserAgentStream>, Status> {
|
||||
let req_stream = request.into_inner();
|
||||
|
||||
let (bi, rx) = GrpcBi::from_bi_stream(req_stream);
|
||||
|
||||
tokio::spawn(start(
|
||||
UserAgentConnection {
|
||||
db: self.context.db.clone(),
|
||||
actors: self.context.actors.clone(),
|
||||
},
|
||||
bi,
|
||||
));
|
||||
|
||||
info!(event = "connection established", "grpc.user_agent");
|
||||
|
||||
Ok(Response::new(rx))
|
||||
}
|
||||
}
|
||||
20
server/crates/arbiter-server/src/grpc/request_tracker.rs
Normal file
20
server/crates/arbiter-server/src/grpc/request_tracker.rs
Normal file
@@ -0,0 +1,20 @@
|
||||
use tonic::Status;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct RequestTracker {
|
||||
next_request_id: i32,
|
||||
}
|
||||
|
||||
impl RequestTracker {
|
||||
pub fn request(&mut self, id: i32) -> Result<i32, Status> {
|
||||
if id < self.next_request_id {
|
||||
return Err(Status::invalid_argument("Duplicate request id"));
|
||||
}
|
||||
|
||||
self.next_request_id = id
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| Status::invalid_argument("Invalid request id"))?;
|
||||
|
||||
Ok(id)
|
||||
}
|
||||
}
|
||||
604
server/crates/arbiter-server/src/grpc/user_agent.rs
Normal file
604
server/crates/arbiter-server/src/grpc/user_agent.rs
Normal file
@@ -0,0 +1,604 @@
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use arbiter_proto::{
|
||||
google::protobuf::{Empty as ProtoEmpty, Timestamp as ProtoTimestamp},
|
||||
proto::{
|
||||
evm::{
|
||||
EtherTransferSettings as ProtoEtherTransferSettings, EvmError as ProtoEvmError,
|
||||
EvmGrantCreateRequest, EvmGrantCreateResponse, EvmGrantDeleteRequest,
|
||||
EvmGrantDeleteResponse, EvmGrantList, EvmGrantListResponse, GrantEntry,
|
||||
SharedSettings as ProtoSharedSettings, SpecificGrant as ProtoSpecificGrant,
|
||||
TokenTransferSettings as ProtoTokenTransferSettings,
|
||||
TransactionRateLimit as ProtoTransactionRateLimit,
|
||||
VolumeRateLimit as ProtoVolumeRateLimit, WalletCreateResponse, WalletEntry, WalletList,
|
||||
WalletListResponse, evm_grant_create_response::Result as EvmGrantCreateResult,
|
||||
evm_grant_delete_response::Result as EvmGrantDeleteResult,
|
||||
evm_grant_list_response::Result as EvmGrantListResult,
|
||||
specific_grant::Grant as ProtoSpecificGrantType,
|
||||
wallet_create_response::Result as WalletCreateResult,
|
||||
wallet_list_response::Result as WalletListResult,
|
||||
},
|
||||
user_agent::{
|
||||
BootstrapEncryptedKey as ProtoBootstrapEncryptedKey,
|
||||
BootstrapResult as ProtoBootstrapResult,
|
||||
SdkClientConnectionResponse as ProtoSdkClientConnectionResponse,
|
||||
UnsealEncryptedKey as ProtoUnsealEncryptedKey, UnsealResult as ProtoUnsealResult,
|
||||
UnsealStart, UserAgentRequest, UserAgentResponse, VaultState as ProtoVaultState,
|
||||
user_agent_request::Payload as UserAgentRequestPayload,
|
||||
user_agent_response::Payload as UserAgentResponsePayload,
|
||||
},
|
||||
},
|
||||
transport::{Error as TransportError, Receiver, Sender, grpc::GrpcBi},
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use chrono::{TimeZone, Utc};
|
||||
use kameo::{
|
||||
actor::{ActorRef, Spawn as _},
|
||||
error::SendError,
|
||||
};
|
||||
use tonic::Status;
|
||||
use tracing::{info, warn};
|
||||
|
||||
use crate::{
|
||||
actors::{
|
||||
keyholder::KeyHolderState,
|
||||
user_agent::{
|
||||
OutOfBand, UserAgentConnection, UserAgentSession,
|
||||
session::{
|
||||
BootstrapError, Error, HandleBootstrapEncryptedKey, HandleEvmWalletCreate,
|
||||
HandleEvmWalletList, HandleGrantCreate, HandleGrantDelete, HandleGrantList,
|
||||
HandleQueryVaultState, HandleUnsealEncryptedKey, HandleUnsealRequest, UnsealError,
|
||||
},
|
||||
},
|
||||
},
|
||||
evm::policies::{
|
||||
Grant, SharedGrantSettings, SpecificGrant, TransactionRateLimit, VolumeRateLimit,
|
||||
ether_transfer, token_transfers,
|
||||
},
|
||||
grpc::request_tracker::RequestTracker,
|
||||
utils::defer,
|
||||
};
|
||||
use alloy::primitives::{Address, U256};
|
||||
mod auth;
|
||||
|
||||
pub struct OutOfBandAdapter(mpsc::Sender<OutOfBand>);
|
||||
|
||||
#[async_trait]
|
||||
impl Sender<OutOfBand> for OutOfBandAdapter {
|
||||
async fn send(&mut self, item: OutOfBand) -> Result<(), TransportError> {
|
||||
self.0.send(item).await.map_err(|e| {
|
||||
warn!(error = ?e, "Failed to send out-of-band message");
|
||||
TransportError::ChannelClosed
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async fn dispatch_loop(
|
||||
mut bi: GrpcBi<UserAgentRequest, UserAgentResponse>,
|
||||
actor: ActorRef<UserAgentSession>,
|
||||
mut receiver: mpsc::Receiver<OutOfBand>,
|
||||
mut request_tracker: RequestTracker,
|
||||
) {
|
||||
loop {
|
||||
tokio::select! {
|
||||
oob = receiver.recv() => {
|
||||
let Some(oob) = oob else {
|
||||
return;
|
||||
};
|
||||
|
||||
if send_out_of_band(&mut bi, oob).await.is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
conn = bi.recv() => {
|
||||
let Some(conn) = conn else {
|
||||
return;
|
||||
};
|
||||
|
||||
if dispatch_conn_message(&mut bi, &actor, &mut request_tracker, conn)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn dispatch_conn_message(
|
||||
bi: &mut GrpcBi<UserAgentRequest, UserAgentResponse>,
|
||||
actor: &ActorRef<UserAgentSession>,
|
||||
request_tracker: &mut RequestTracker,
|
||||
conn: Result<UserAgentRequest, Status>,
|
||||
) -> Result<(), ()> {
|
||||
let conn = match conn {
|
||||
Ok(conn) => conn,
|
||||
Err(err) => {
|
||||
warn!(error = ?err, "Failed to receive user agent request");
|
||||
return Err(());
|
||||
}
|
||||
};
|
||||
|
||||
let request_id = match request_tracker.request(conn.id) {
|
||||
Ok(request_id) => request_id,
|
||||
Err(err) => {
|
||||
let _ = bi.send(Err(err)).await;
|
||||
return Err(());
|
||||
}
|
||||
};
|
||||
|
||||
let Some(payload) = conn.payload else {
|
||||
let _ = bi
|
||||
.send(Err(Status::invalid_argument(
|
||||
"Missing user-agent request payload",
|
||||
)))
|
||||
.await;
|
||||
return Err(());
|
||||
};
|
||||
|
||||
let payload = match payload {
|
||||
UserAgentRequestPayload::UnsealStart(UnsealStart { client_pubkey }) => {
|
||||
let client_pubkey = match <[u8; 32]>::try_from(client_pubkey) {
|
||||
Ok(bytes) => x25519_dalek::PublicKey::from(bytes),
|
||||
Err(_) => {
|
||||
let _ = bi
|
||||
.send(Err(Status::invalid_argument("Invalid X25519 public key")))
|
||||
.await;
|
||||
return Err(());
|
||||
}
|
||||
};
|
||||
|
||||
match actor.ask(HandleUnsealRequest { client_pubkey }).await {
|
||||
Ok(response) => UserAgentResponsePayload::UnsealStartResponse(
|
||||
arbiter_proto::proto::user_agent::UnsealStartResponse {
|
||||
server_pubkey: response.server_pubkey.as_bytes().to_vec(),
|
||||
},
|
||||
),
|
||||
Err(err) => {
|
||||
warn!(error = ?err, "Failed to handle unseal start request");
|
||||
let _ = bi
|
||||
.send(Err(Status::internal("Failed to start unseal flow")))
|
||||
.await;
|
||||
return Err(());
|
||||
}
|
||||
}
|
||||
}
|
||||
UserAgentRequestPayload::UnsealEncryptedKey(ProtoUnsealEncryptedKey {
|
||||
nonce,
|
||||
ciphertext,
|
||||
associated_data,
|
||||
}) => UserAgentResponsePayload::UnsealResult(
|
||||
match actor
|
||||
.ask(HandleUnsealEncryptedKey {
|
||||
nonce,
|
||||
ciphertext,
|
||||
associated_data,
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(()) => ProtoUnsealResult::Success,
|
||||
Err(SendError::HandlerError(UnsealError::InvalidKey)) => {
|
||||
ProtoUnsealResult::InvalidKey
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(error = ?err, "Failed to handle unseal request");
|
||||
let _ = bi
|
||||
.send(Err(Status::internal("Failed to unseal vault")))
|
||||
.await;
|
||||
return Err(());
|
||||
}
|
||||
}
|
||||
.into(),
|
||||
),
|
||||
UserAgentRequestPayload::BootstrapEncryptedKey(ProtoBootstrapEncryptedKey {
|
||||
nonce,
|
||||
ciphertext,
|
||||
associated_data,
|
||||
}) => UserAgentResponsePayload::BootstrapResult(
|
||||
match actor
|
||||
.ask(HandleBootstrapEncryptedKey {
|
||||
nonce,
|
||||
ciphertext,
|
||||
associated_data,
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(()) => ProtoBootstrapResult::Success,
|
||||
Err(SendError::HandlerError(BootstrapError::InvalidKey)) => {
|
||||
ProtoBootstrapResult::InvalidKey
|
||||
}
|
||||
Err(SendError::HandlerError(BootstrapError::AlreadyBootstrapped)) => {
|
||||
ProtoBootstrapResult::AlreadyBootstrapped
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(error = ?err, "Failed to handle bootstrap request");
|
||||
let _ = bi
|
||||
.send(Err(Status::internal("Failed to bootstrap vault")))
|
||||
.await;
|
||||
return Err(());
|
||||
}
|
||||
}
|
||||
.into(),
|
||||
),
|
||||
UserAgentRequestPayload::QueryVaultState(_) => UserAgentResponsePayload::VaultState(
|
||||
match actor.ask(HandleQueryVaultState {}).await {
|
||||
Ok(KeyHolderState::Unbootstrapped) => ProtoVaultState::Unbootstrapped,
|
||||
Ok(KeyHolderState::Sealed) => ProtoVaultState::Sealed,
|
||||
Ok(KeyHolderState::Unsealed) => ProtoVaultState::Unsealed,
|
||||
Err(err) => {
|
||||
warn!(error = ?err, "Failed to query vault state");
|
||||
ProtoVaultState::Error
|
||||
}
|
||||
}
|
||||
.into(),
|
||||
),
|
||||
UserAgentRequestPayload::EvmWalletCreate(_) => UserAgentResponsePayload::EvmWalletCreate(
|
||||
EvmGrantOrWallet::wallet_create_response(actor.ask(HandleEvmWalletCreate {}).await),
|
||||
),
|
||||
UserAgentRequestPayload::EvmWalletList(_) => UserAgentResponsePayload::EvmWalletList(
|
||||
EvmGrantOrWallet::wallet_list_response(actor.ask(HandleEvmWalletList {}).await),
|
||||
),
|
||||
UserAgentRequestPayload::EvmGrantList(_) => UserAgentResponsePayload::EvmGrantList(
|
||||
EvmGrantOrWallet::grant_list_response(actor.ask(HandleGrantList {}).await),
|
||||
),
|
||||
UserAgentRequestPayload::EvmGrantCreate(EvmGrantCreateRequest {
|
||||
client_id,
|
||||
shared,
|
||||
specific,
|
||||
}) => {
|
||||
let (basic, grant) = match parse_grant_request(shared, specific) {
|
||||
Ok(values) => values,
|
||||
Err(status) => {
|
||||
let _ = bi.send(Err(status)).await;
|
||||
return Err(());
|
||||
}
|
||||
};
|
||||
|
||||
UserAgentResponsePayload::EvmGrantCreate(EvmGrantOrWallet::grant_create_response(
|
||||
actor
|
||||
.ask(HandleGrantCreate {
|
||||
client_id,
|
||||
basic,
|
||||
grant,
|
||||
})
|
||||
.await,
|
||||
))
|
||||
}
|
||||
UserAgentRequestPayload::EvmGrantDelete(EvmGrantDeleteRequest { grant_id }) => {
|
||||
UserAgentResponsePayload::EvmGrantDelete(EvmGrantOrWallet::grant_delete_response(
|
||||
actor.ask(HandleGrantDelete { grant_id }).await,
|
||||
))
|
||||
}
|
||||
payload => {
|
||||
warn!(?payload, "Unsupported post-auth user agent request");
|
||||
let _ = bi
|
||||
.send(Err(Status::invalid_argument(
|
||||
"Unsupported user-agent request",
|
||||
)))
|
||||
.await;
|
||||
return Err(());
|
||||
}
|
||||
};
|
||||
|
||||
bi.send(Ok(UserAgentResponse {
|
||||
id: Some(request_id),
|
||||
payload: Some(payload),
|
||||
}))
|
||||
.await
|
||||
.map_err(|_| ())
|
||||
}
|
||||
|
||||
async fn send_out_of_band(
|
||||
bi: &mut GrpcBi<UserAgentRequest, UserAgentResponse>,
|
||||
oob: OutOfBand,
|
||||
) -> Result<(), ()> {
|
||||
let payload = match oob {
|
||||
// The current protobuf response payload carries only an approval boolean.
|
||||
// Keep emitting this shape until a dedicated out-of-band request/cancel payload
|
||||
// is reintroduced in the protocol definition.
|
||||
OutOfBand::ClientConnectionRequest { pubkey: _ } => {
|
||||
UserAgentResponsePayload::SdkClientConnectionResponse(
|
||||
ProtoSdkClientConnectionResponse { approved: false },
|
||||
)
|
||||
}
|
||||
OutOfBand::ClientConnectionCancel => UserAgentResponsePayload::SdkClientConnectionResponse(
|
||||
ProtoSdkClientConnectionResponse { approved: false },
|
||||
),
|
||||
};
|
||||
|
||||
bi.send(Ok(UserAgentResponse {
|
||||
id: None,
|
||||
payload: Some(payload),
|
||||
}))
|
||||
.await
|
||||
.map_err(|_| ())
|
||||
}
|
||||
|
||||
fn parse_grant_request(
|
||||
shared: Option<ProtoSharedSettings>,
|
||||
specific: Option<ProtoSpecificGrant>,
|
||||
) -> Result<(SharedGrantSettings, SpecificGrant), Status> {
|
||||
let shared = shared.ok_or_else(|| Status::invalid_argument("Missing shared grant settings"))?;
|
||||
let specific =
|
||||
specific.ok_or_else(|| Status::invalid_argument("Missing specific grant settings"))?;
|
||||
|
||||
Ok((
|
||||
shared_settings_from_proto(shared)?,
|
||||
specific_grant_from_proto(specific)?,
|
||||
))
|
||||
}
|
||||
|
||||
fn shared_settings_from_proto(shared: ProtoSharedSettings) -> Result<SharedGrantSettings, Status> {
|
||||
Ok(SharedGrantSettings {
|
||||
wallet_id: shared.wallet_id,
|
||||
client_id: 0,
|
||||
chain: shared.chain_id,
|
||||
valid_from: shared.valid_from.map(proto_timestamp_to_utc).transpose()?,
|
||||
valid_until: shared.valid_until.map(proto_timestamp_to_utc).transpose()?,
|
||||
max_gas_fee_per_gas: shared
|
||||
.max_gas_fee_per_gas
|
||||
.as_deref()
|
||||
.map(u256_from_proto_bytes)
|
||||
.transpose()?,
|
||||
max_priority_fee_per_gas: shared
|
||||
.max_priority_fee_per_gas
|
||||
.as_deref()
|
||||
.map(u256_from_proto_bytes)
|
||||
.transpose()?,
|
||||
rate_limit: shared.rate_limit.map(|limit| TransactionRateLimit {
|
||||
count: limit.count,
|
||||
window: chrono::Duration::seconds(limit.window_secs),
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
fn specific_grant_from_proto(specific: ProtoSpecificGrant) -> Result<SpecificGrant, Status> {
|
||||
match specific.grant {
|
||||
Some(ProtoSpecificGrantType::EtherTransfer(ProtoEtherTransferSettings {
|
||||
targets,
|
||||
limit,
|
||||
})) => Ok(SpecificGrant::EtherTransfer(ether_transfer::Settings {
|
||||
target: targets
|
||||
.into_iter()
|
||||
.map(address_from_bytes)
|
||||
.collect::<Result<_, _>>()?,
|
||||
limit: volume_rate_limit_from_proto(limit.ok_or_else(|| {
|
||||
Status::invalid_argument("Missing ether transfer volume rate limit")
|
||||
})?)?,
|
||||
})),
|
||||
Some(ProtoSpecificGrantType::TokenTransfer(ProtoTokenTransferSettings {
|
||||
token_contract,
|
||||
target,
|
||||
volume_limits,
|
||||
})) => Ok(SpecificGrant::TokenTransfer(token_transfers::Settings {
|
||||
token_contract: address_from_bytes(token_contract)?,
|
||||
target: target.map(address_from_bytes).transpose()?,
|
||||
volume_limits: volume_limits
|
||||
.into_iter()
|
||||
.map(volume_rate_limit_from_proto)
|
||||
.collect::<Result<_, _>>()?,
|
||||
})),
|
||||
None => Err(Status::invalid_argument("Missing specific grant kind")),
|
||||
}
|
||||
}
|
||||
|
||||
fn volume_rate_limit_from_proto(limit: ProtoVolumeRateLimit) -> Result<VolumeRateLimit, Status> {
|
||||
Ok(VolumeRateLimit {
|
||||
max_volume: u256_from_proto_bytes(&limit.max_volume)?,
|
||||
window: chrono::Duration::seconds(limit.window_secs),
|
||||
})
|
||||
}
|
||||
|
||||
fn address_from_bytes(bytes: Vec<u8>) -> Result<Address, Status> {
|
||||
if bytes.len() != 20 {
|
||||
return Err(Status::invalid_argument("Invalid EVM address"));
|
||||
}
|
||||
|
||||
Ok(Address::from_slice(&bytes))
|
||||
}
|
||||
|
||||
fn u256_from_proto_bytes(bytes: &[u8]) -> Result<U256, Status> {
|
||||
if bytes.len() > 32 {
|
||||
return Err(Status::invalid_argument("Invalid U256 byte length"));
|
||||
}
|
||||
|
||||
Ok(U256::from_be_slice(bytes))
|
||||
}
|
||||
|
||||
fn proto_timestamp_to_utc(timestamp: ProtoTimestamp) -> Result<chrono::DateTime<Utc>, Status> {
|
||||
Utc.timestamp_opt(timestamp.seconds, timestamp.nanos as u32)
|
||||
.single()
|
||||
.ok_or_else(|| Status::invalid_argument("Invalid timestamp"))
|
||||
}
|
||||
|
||||
fn shared_settings_to_proto(shared: SharedGrantSettings) -> ProtoSharedSettings {
|
||||
ProtoSharedSettings {
|
||||
wallet_id: shared.wallet_id,
|
||||
chain_id: shared.chain,
|
||||
valid_from: shared.valid_from.map(|time| ProtoTimestamp {
|
||||
seconds: time.timestamp(),
|
||||
nanos: time.timestamp_subsec_nanos() as i32,
|
||||
}),
|
||||
valid_until: shared.valid_until.map(|time| ProtoTimestamp {
|
||||
seconds: time.timestamp(),
|
||||
nanos: time.timestamp_subsec_nanos() as i32,
|
||||
}),
|
||||
max_gas_fee_per_gas: shared
|
||||
.max_gas_fee_per_gas
|
||||
.map(|value| value.to_be_bytes::<32>().to_vec()),
|
||||
max_priority_fee_per_gas: shared
|
||||
.max_priority_fee_per_gas
|
||||
.map(|value| value.to_be_bytes::<32>().to_vec()),
|
||||
rate_limit: shared.rate_limit.map(|limit| ProtoTransactionRateLimit {
|
||||
count: limit.count,
|
||||
window_secs: limit.window.num_seconds(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn specific_grant_to_proto(grant: SpecificGrant) -> ProtoSpecificGrant {
|
||||
let grant = match grant {
|
||||
SpecificGrant::EtherTransfer(settings) => {
|
||||
ProtoSpecificGrantType::EtherTransfer(ProtoEtherTransferSettings {
|
||||
targets: settings
|
||||
.target
|
||||
.into_iter()
|
||||
.map(|address| address.to_vec())
|
||||
.collect(),
|
||||
limit: Some(ProtoVolumeRateLimit {
|
||||
max_volume: settings.limit.max_volume.to_be_bytes::<32>().to_vec(),
|
||||
window_secs: settings.limit.window.num_seconds(),
|
||||
}),
|
||||
})
|
||||
}
|
||||
SpecificGrant::TokenTransfer(settings) => {
|
||||
ProtoSpecificGrantType::TokenTransfer(ProtoTokenTransferSettings {
|
||||
token_contract: settings.token_contract.to_vec(),
|
||||
target: settings.target.map(|address| address.to_vec()),
|
||||
volume_limits: settings
|
||||
.volume_limits
|
||||
.into_iter()
|
||||
.map(|limit| ProtoVolumeRateLimit {
|
||||
max_volume: limit.max_volume.to_be_bytes::<32>().to_vec(),
|
||||
window_secs: limit.window.num_seconds(),
|
||||
})
|
||||
.collect(),
|
||||
})
|
||||
}
|
||||
};
|
||||
|
||||
ProtoSpecificGrant { grant: Some(grant) }
|
||||
}
|
||||
|
||||
struct EvmGrantOrWallet;
|
||||
|
||||
impl EvmGrantOrWallet {
|
||||
fn wallet_create_response<M>(
|
||||
result: Result<Address, SendError<M, Error>>,
|
||||
) -> WalletCreateResponse {
|
||||
let result = match result {
|
||||
Ok(wallet) => WalletCreateResult::Wallet(WalletEntry {
|
||||
address: wallet.to_vec(),
|
||||
}),
|
||||
Err(err) => {
|
||||
warn!(error = ?err, "Failed to create EVM wallet");
|
||||
WalletCreateResult::Error(ProtoEvmError::Internal.into())
|
||||
}
|
||||
};
|
||||
|
||||
WalletCreateResponse {
|
||||
result: Some(result),
|
||||
}
|
||||
}
|
||||
|
||||
fn wallet_list_response<M>(
|
||||
result: Result<Vec<Address>, SendError<M, Error>>,
|
||||
) -> WalletListResponse {
|
||||
let result = match result {
|
||||
Ok(wallets) => WalletListResult::Wallets(WalletList {
|
||||
wallets: wallets
|
||||
.into_iter()
|
||||
.map(|wallet| WalletEntry {
|
||||
address: wallet.to_vec(),
|
||||
})
|
||||
.collect(),
|
||||
}),
|
||||
Err(err) => {
|
||||
warn!(error = ?err, "Failed to list EVM wallets");
|
||||
WalletListResult::Error(ProtoEvmError::Internal.into())
|
||||
}
|
||||
};
|
||||
|
||||
WalletListResponse {
|
||||
result: Some(result),
|
||||
}
|
||||
}
|
||||
|
||||
fn grant_create_response<M>(
|
||||
result: Result<i32, SendError<M, Error>>,
|
||||
) -> EvmGrantCreateResponse {
|
||||
let result = match result {
|
||||
Ok(grant_id) => EvmGrantCreateResult::GrantId(grant_id),
|
||||
Err(err) => {
|
||||
warn!(error = ?err, "Failed to create EVM grant");
|
||||
EvmGrantCreateResult::Error(ProtoEvmError::Internal.into())
|
||||
}
|
||||
};
|
||||
|
||||
EvmGrantCreateResponse {
|
||||
result: Some(result),
|
||||
}
|
||||
}
|
||||
|
||||
fn grant_delete_response<M>(result: Result<(), SendError<M, Error>>) -> EvmGrantDeleteResponse {
|
||||
let result = match result {
|
||||
Ok(()) => EvmGrantDeleteResult::Ok(ProtoEmpty {}),
|
||||
Err(err) => {
|
||||
warn!(error = ?err, "Failed to delete EVM grant");
|
||||
EvmGrantDeleteResult::Error(ProtoEvmError::Internal.into())
|
||||
}
|
||||
};
|
||||
|
||||
EvmGrantDeleteResponse {
|
||||
result: Some(result),
|
||||
}
|
||||
}
|
||||
|
||||
fn grant_list_response<M>(
|
||||
result: Result<Vec<Grant<SpecificGrant>>, SendError<M, Error>>,
|
||||
) -> EvmGrantListResponse {
|
||||
let result = match result {
|
||||
Ok(grants) => EvmGrantListResult::Grants(EvmGrantList {
|
||||
grants: grants
|
||||
.into_iter()
|
||||
.map(|grant| GrantEntry {
|
||||
id: grant.id,
|
||||
client_id: grant.shared.client_id,
|
||||
shared: Some(shared_settings_to_proto(grant.shared)),
|
||||
specific: Some(specific_grant_to_proto(grant.settings)),
|
||||
})
|
||||
.collect(),
|
||||
}),
|
||||
Err(err) => {
|
||||
warn!(error = ?err, "Failed to list EVM grants");
|
||||
EvmGrantListResult::Error(ProtoEvmError::Internal.into())
|
||||
}
|
||||
};
|
||||
|
||||
EvmGrantListResponse {
|
||||
result: Some(result),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn start(
|
||||
mut conn: UserAgentConnection,
|
||||
mut bi: GrpcBi<UserAgentRequest, UserAgentResponse>,
|
||||
) {
|
||||
let mut request_tracker = RequestTracker::default();
|
||||
let mut response_id = None;
|
||||
|
||||
let pubkey = match auth::start(&mut conn, &mut bi, &mut request_tracker, &mut response_id).await
|
||||
{
|
||||
Ok(pubkey) => pubkey,
|
||||
Err(e) => {
|
||||
warn!(error = ?e, "Authentication failed");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let (oob_sender, oob_receiver) = mpsc::channel(16);
|
||||
let oob_adapter = OutOfBandAdapter(oob_sender);
|
||||
|
||||
let actor = UserAgentSession::spawn(UserAgentSession::new(conn, Box::new(oob_adapter)));
|
||||
let actor_for_cleanup = actor.clone();
|
||||
|
||||
let _ = defer(move || {
|
||||
actor_for_cleanup.kill();
|
||||
});
|
||||
|
||||
info!(?pubkey, "User authenticated successfully");
|
||||
dispatch_loop(bi, actor, oob_receiver, request_tracker).await;
|
||||
}
|
||||
180
server/crates/arbiter-server/src/grpc/user_agent/auth.rs
Normal file
180
server/crates/arbiter-server/src/grpc/user_agent/auth.rs
Normal file
@@ -0,0 +1,180 @@
|
||||
use arbiter_proto::{
|
||||
proto::user_agent::{
|
||||
AuthChallenge as ProtoAuthChallenge, AuthChallengeRequest as ProtoAuthChallengeRequest,
|
||||
AuthChallengeSolution as ProtoAuthChallengeSolution, AuthResult as ProtoAuthResult,
|
||||
KeyType as ProtoKeyType, UserAgentRequest, UserAgentResponse,
|
||||
user_agent_request::Payload as UserAgentRequestPayload,
|
||||
user_agent_response::Payload as UserAgentResponsePayload,
|
||||
},
|
||||
transport::{Bi, Error as TransportError, Receiver, Sender, grpc::GrpcBi},
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use tonic::Status;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::{
|
||||
actors::user_agent::{AuthPublicKey, UserAgentConnection, auth},
|
||||
db::models::KeyType,
|
||||
grpc::request_tracker::RequestTracker,
|
||||
};
|
||||
|
||||
pub struct AuthTransportAdapter<'a> {
|
||||
bi: &'a mut GrpcBi<UserAgentRequest, UserAgentResponse>,
|
||||
request_tracker: &'a mut RequestTracker,
|
||||
response_id: &'a mut Option<i32>,
|
||||
}
|
||||
|
||||
impl<'a> AuthTransportAdapter<'a> {
|
||||
pub fn new(
|
||||
bi: &'a mut GrpcBi<UserAgentRequest, UserAgentResponse>,
|
||||
request_tracker: &'a mut RequestTracker,
|
||||
response_id: &'a mut Option<i32>,
|
||||
) -> Self {
|
||||
Self {
|
||||
bi,
|
||||
request_tracker,
|
||||
response_id,
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_user_agent_response(
|
||||
&mut self,
|
||||
payload: UserAgentResponsePayload,
|
||||
) -> Result<(), TransportError> {
|
||||
let id = self.response_id.take();
|
||||
|
||||
self.bi
|
||||
.send(Ok(UserAgentResponse {
|
||||
id,
|
||||
payload: Some(payload),
|
||||
}))
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Sender<Result<auth::Outbound, auth::Error>> for AuthTransportAdapter<'_> {
|
||||
async fn send(
|
||||
&mut self,
|
||||
item: Result<auth::Outbound, auth::Error>,
|
||||
) -> Result<(), TransportError> {
|
||||
use auth::{Error, Outbound};
|
||||
let payload = match item {
|
||||
Ok(Outbound::AuthChallenge { nonce }) => {
|
||||
UserAgentResponsePayload::AuthChallenge(ProtoAuthChallenge { nonce })
|
||||
}
|
||||
Ok(Outbound::AuthSuccess) => {
|
||||
UserAgentResponsePayload::AuthResult(ProtoAuthResult::Success.into())
|
||||
}
|
||||
Err(Error::UnregisteredPublicKey) => {
|
||||
UserAgentResponsePayload::AuthResult(ProtoAuthResult::InvalidKey.into())
|
||||
}
|
||||
Err(Error::InvalidChallengeSolution) => {
|
||||
UserAgentResponsePayload::AuthResult(ProtoAuthResult::InvalidSignature.into())
|
||||
}
|
||||
Err(Error::InvalidBootstrapToken) => {
|
||||
UserAgentResponsePayload::AuthResult(ProtoAuthResult::TokenInvalid.into())
|
||||
}
|
||||
Err(Error::Internal { details }) => return self.bi.send(Err(Status::internal(details))).await,
|
||||
Err(Error::Transport) => {
|
||||
return self.bi.send(Err(Status::unavailable("transport error"))).await;
|
||||
}
|
||||
};
|
||||
|
||||
self.send_user_agent_response(payload).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Receiver<auth::Inbound> for AuthTransportAdapter<'_> {
|
||||
async fn recv(&mut self) -> Option<auth::Inbound> {
|
||||
let request = match self.bi.recv().await? {
|
||||
Ok(request) => request,
|
||||
Err(error) => {
|
||||
warn!(error = ?error, "Failed to receive user agent auth request");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let request_id = match self.request_tracker.request(request.id) {
|
||||
Ok(request_id) => request_id,
|
||||
Err(error) => {
|
||||
let _ = self.bi.send(Err(error)).await;
|
||||
return None;
|
||||
}
|
||||
};
|
||||
*self.response_id = Some(request_id);
|
||||
|
||||
let Some(payload) = request.payload else {
|
||||
warn!(
|
||||
event = "received request with empty payload",
|
||||
"grpc.useragent.auth_adapter"
|
||||
);
|
||||
return None;
|
||||
};
|
||||
|
||||
match payload {
|
||||
UserAgentRequestPayload::AuthChallengeRequest(ProtoAuthChallengeRequest {
|
||||
pubkey,
|
||||
bootstrap_token,
|
||||
key_type,
|
||||
}) => {
|
||||
let Ok(key_type) = ProtoKeyType::try_from(key_type) else {
|
||||
warn!(
|
||||
event = "received request with invalid key type",
|
||||
"grpc.useragent.auth_adapter"
|
||||
);
|
||||
return None;
|
||||
};
|
||||
let key_type = match key_type {
|
||||
ProtoKeyType::Ed25519 => KeyType::Ed25519,
|
||||
ProtoKeyType::EcdsaSecp256k1 => KeyType::EcdsaSecp256k1,
|
||||
ProtoKeyType::Rsa => KeyType::Rsa,
|
||||
ProtoKeyType::Unspecified => {
|
||||
warn!(
|
||||
event = "received request with unspecified key type",
|
||||
"grpc.useragent.auth_adapter"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let Ok(pubkey) = AuthPublicKey::try_from((key_type, pubkey)) else {
|
||||
warn!(
|
||||
event = "received request with invalid public key",
|
||||
"grpc.useragent.auth_adapter"
|
||||
);
|
||||
return None;
|
||||
};
|
||||
|
||||
Some(auth::Inbound::AuthChallengeRequest {
|
||||
pubkey,
|
||||
bootstrap_token,
|
||||
})
|
||||
}
|
||||
UserAgentRequestPayload::AuthChallengeSolution(ProtoAuthChallengeSolution {
|
||||
signature,
|
||||
}) => Some(auth::Inbound::AuthChallengeSolution { signature }),
|
||||
_ => {
|
||||
let _ = self
|
||||
.bi
|
||||
.send(Err(Status::invalid_argument(
|
||||
"Unsupported user-agent auth request",
|
||||
)))
|
||||
.await;
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Bi<auth::Inbound, Result<auth::Outbound, auth::Error>> for AuthTransportAdapter<'_> {}
|
||||
|
||||
pub async fn start(
|
||||
conn: &mut UserAgentConnection,
|
||||
bi: &mut GrpcBi<UserAgentRequest, UserAgentResponse>,
|
||||
request_tracker: &mut RequestTracker,
|
||||
response_id: &mut Option<i32>,
|
||||
) -> Result<AuthPublicKey, auth::Error> {
|
||||
let transport = AuthTransportAdapter::new(bi, request_tracker, response_id);
|
||||
auth::authenticate(conn, transport).await
|
||||
}
|
||||
@@ -1,136 +1,13 @@
|
||||
#![forbid(unsafe_code)]
|
||||
use arbiter_proto::{
|
||||
proto::{
|
||||
client::{ClientRequest, ClientResponse},
|
||||
user_agent::{UserAgentRequest, UserAgentResponse},
|
||||
},
|
||||
transport::{IdentityRecvConverter, SendConverter, grpc},
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use tonic::{Request, Response, Status};
|
||||
use tracing::info;
|
||||
|
||||
use crate::{
|
||||
actors::{
|
||||
client::{self, ClientConnection as ClientConnectionProps, ClientError, connect_client},
|
||||
user_agent::{self, TransportResponseError, UserAgentConnection, connect_user_agent},
|
||||
},
|
||||
context::ServerContext,
|
||||
};
|
||||
use crate::context::ServerContext;
|
||||
|
||||
pub mod actors;
|
||||
pub mod context;
|
||||
pub mod db;
|
||||
pub mod evm;
|
||||
|
||||
const DEFAULT_CHANNEL_SIZE: usize = 1000;
|
||||
|
||||
struct UserAgentGrpcSender;
|
||||
|
||||
impl SendConverter for UserAgentGrpcSender {
|
||||
type Input = Result<UserAgentResponse, TransportResponseError>;
|
||||
type Output = Result<UserAgentResponse, Status>;
|
||||
|
||||
fn convert(&self, item: Self::Input) -> Self::Output {
|
||||
match item {
|
||||
Ok(message) => Ok(message),
|
||||
Err(err) => Err(user_agent_error_status(err)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ClientGrpcSender;
|
||||
|
||||
impl SendConverter for ClientGrpcSender {
|
||||
type Input = Result<ClientResponse, ClientError>;
|
||||
type Output = Result<ClientResponse, Status>;
|
||||
|
||||
fn convert(&self, item: Self::Input) -> Self::Output {
|
||||
match item {
|
||||
Ok(message) => Ok(message),
|
||||
Err(err) => Err(client_error_status(err)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn client_error_status(value: ClientError) -> Status {
|
||||
match value {
|
||||
ClientError::MissingRequestPayload | ClientError::UnexpectedRequestPayload => {
|
||||
Status::invalid_argument("Expected message with payload")
|
||||
}
|
||||
ClientError::StateTransitionFailed => Status::internal("State machine error"),
|
||||
ClientError::Auth(ref err) => client_auth_error_status(err),
|
||||
ClientError::ConnectionRegistrationFailed => {
|
||||
Status::internal("Connection registration failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn client_auth_error_status(value: &client::auth::Error) -> Status {
|
||||
use client::auth::Error;
|
||||
match value {
|
||||
Error::UnexpectedMessagePayload | Error::InvalidClientPubkeyLength => {
|
||||
Status::invalid_argument(value.to_string())
|
||||
}
|
||||
Error::InvalidAuthPubkeyEncoding => {
|
||||
Status::invalid_argument("Failed to convert pubkey to VerifyingKey")
|
||||
}
|
||||
Error::InvalidChallengeSolution => Status::unauthenticated(value.to_string()),
|
||||
Error::NotRegistered => Status::permission_denied(value.to_string()),
|
||||
Error::Transport => Status::internal("Transport error"),
|
||||
Error::DatabasePoolUnavailable => Status::internal("Database pool error"),
|
||||
Error::DatabaseOperationFailed => Status::internal("Database error"),
|
||||
Error::InternalError => Status::internal("Internal error"),
|
||||
}
|
||||
}
|
||||
|
||||
fn user_agent_error_status(value: TransportResponseError) -> Status {
|
||||
match value {
|
||||
TransportResponseError::MissingRequestPayload
|
||||
| TransportResponseError::UnexpectedRequestPayload => {
|
||||
Status::invalid_argument("Expected message with payload")
|
||||
}
|
||||
TransportResponseError::InvalidStateForUnsealEncryptedKey => {
|
||||
Status::failed_precondition("Invalid state for unseal encrypted key")
|
||||
}
|
||||
TransportResponseError::InvalidClientPubkeyLength => {
|
||||
Status::invalid_argument("client_pubkey must be 32 bytes")
|
||||
}
|
||||
TransportResponseError::StateTransitionFailed => Status::internal("State machine error"),
|
||||
TransportResponseError::KeyHolderActorUnreachable => {
|
||||
Status::internal("Vault is not available")
|
||||
}
|
||||
TransportResponseError::Auth(ref err) => auth_error_status(err),
|
||||
TransportResponseError::ConnectionRegistrationFailed => {
|
||||
Status::internal("Failed registering connection")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn auth_error_status(value: &user_agent::auth::Error) -> Status {
|
||||
use user_agent::auth::Error;
|
||||
match value {
|
||||
Error::UnexpectedMessagePayload | Error::InvalidClientPubkeyLength => {
|
||||
Status::invalid_argument(value.to_string())
|
||||
}
|
||||
Error::InvalidAuthPubkeyEncoding => {
|
||||
Status::invalid_argument("Failed to convert pubkey to VerifyingKey")
|
||||
}
|
||||
Error::PublicKeyNotRegistered | Error::InvalidChallengeSolution => {
|
||||
Status::unauthenticated(value.to_string())
|
||||
}
|
||||
Error::InvalidBootstrapToken => Status::invalid_argument("Invalid bootstrap token"),
|
||||
Error::Transport => Status::internal("Transport error"),
|
||||
Error::BootstrapperActorUnreachable => {
|
||||
Status::internal("Bootstrap token consumption failed")
|
||||
}
|
||||
Error::DatabasePoolUnavailable => Status::internal("Database pool error"),
|
||||
Error::DatabaseOperationFailed => Status::internal("Database error"),
|
||||
}
|
||||
}
|
||||
pub mod grpc;
|
||||
pub mod safe_cell;
|
||||
pub mod utils;
|
||||
|
||||
pub struct Server {
|
||||
context: ServerContext,
|
||||
@@ -141,61 +18,3 @@ impl Server {
|
||||
Self { context }
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl arbiter_proto::proto::arbiter_service_server::ArbiterService for Server {
|
||||
type UserAgentStream = ReceiverStream<Result<UserAgentResponse, Status>>;
|
||||
type ClientStream = ReceiverStream<Result<ClientResponse, Status>>;
|
||||
|
||||
#[tracing::instrument(level = "debug", skip(self))]
|
||||
async fn client(
|
||||
&self,
|
||||
request: Request<tonic::Streaming<ClientRequest>>,
|
||||
) -> Result<Response<Self::ClientStream>, Status> {
|
||||
let req_stream = request.into_inner();
|
||||
let (tx, rx) = mpsc::channel(DEFAULT_CHANNEL_SIZE);
|
||||
|
||||
let transport = grpc::GrpcAdapter::new(
|
||||
tx,
|
||||
req_stream,
|
||||
IdentityRecvConverter::<ClientRequest>::new(),
|
||||
ClientGrpcSender,
|
||||
);
|
||||
let props = ClientConnectionProps::new(
|
||||
self.context.db.clone(),
|
||||
Box::new(transport),
|
||||
self.context.actors.clone(),
|
||||
);
|
||||
tokio::spawn(connect_client(props));
|
||||
|
||||
info!(event = "connection established", "grpc.client");
|
||||
|
||||
Ok(Response::new(ReceiverStream::new(rx)))
|
||||
}
|
||||
|
||||
#[tracing::instrument(level = "debug", skip(self))]
|
||||
async fn user_agent(
|
||||
&self,
|
||||
request: Request<tonic::Streaming<UserAgentRequest>>,
|
||||
) -> Result<Response<Self::UserAgentStream>, Status> {
|
||||
let req_stream = request.into_inner();
|
||||
let (tx, rx) = mpsc::channel(DEFAULT_CHANNEL_SIZE);
|
||||
|
||||
let transport = grpc::GrpcAdapter::new(
|
||||
tx,
|
||||
req_stream,
|
||||
IdentityRecvConverter::<UserAgentRequest>::new(),
|
||||
UserAgentGrpcSender,
|
||||
);
|
||||
let props = UserAgentConnection::new(
|
||||
self.context.db.clone(),
|
||||
self.context.actors.clone(),
|
||||
Box::new(transport),
|
||||
);
|
||||
tokio::spawn(connect_user_agent(props));
|
||||
|
||||
info!(event = "connection established", "grpc.user_agent");
|
||||
|
||||
Ok(Response::new(ReceiverStream::new(rx)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ use std::net::SocketAddr;
|
||||
use arbiter_proto::{proto::arbiter_service_server::ArbiterServiceServer, url::ArbiterUrl};
|
||||
use arbiter_server::{Server, actors::bootstrap::GetToken, context::ServerContext, db};
|
||||
use miette::miette;
|
||||
use rustls::crypto::aws_lc_rs;
|
||||
use tonic::transport::{Identity, ServerTlsConfig};
|
||||
use tracing::info;
|
||||
|
||||
@@ -10,6 +11,8 @@ const PORT: u16 = 50051;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> miette::Result<()> {
|
||||
aws_lc_rs::default_provider().install_default().unwrap();
|
||||
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
|
||||
111
server/crates/arbiter-server/src/safe_cell.rs
Normal file
111
server/crates/arbiter-server/src/safe_cell.rs
Normal file
@@ -0,0 +1,111 @@
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::{any::type_name, fmt};
|
||||
|
||||
use memsafe::MemSafe;
|
||||
|
||||
pub trait SafeCellHandle<T> {
|
||||
type CellRead<'a>: Deref<Target = T>
|
||||
where
|
||||
Self: 'a,
|
||||
T: 'a;
|
||||
type CellWrite<'a>: Deref<Target = T> + DerefMut<Target = T>
|
||||
where
|
||||
Self: 'a,
|
||||
T: 'a;
|
||||
|
||||
fn new(value: T) -> Self
|
||||
where
|
||||
Self: Sized;
|
||||
|
||||
fn read(&mut self) -> Self::CellRead<'_>;
|
||||
fn write(&mut self) -> Self::CellWrite<'_>;
|
||||
|
||||
fn new_inline<F>(f: F) -> Self
|
||||
where
|
||||
Self: Sized,
|
||||
T: Default,
|
||||
F: for<'a> FnOnce(&'a mut T),
|
||||
{
|
||||
let mut cell = Self::new(T::default());
|
||||
{
|
||||
let mut handle = cell.write();
|
||||
f(handle.deref_mut());
|
||||
}
|
||||
cell
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn read_inline<F, R>(&mut self, f: F) -> R
|
||||
where
|
||||
F: FnOnce(&T) -> R,
|
||||
{
|
||||
f(&*self.read())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn write_inline<F, R>(&mut self, f: F) -> R
|
||||
where
|
||||
F: FnOnce(&mut T) -> R,
|
||||
{
|
||||
f(&mut *self.write())
|
||||
}
|
||||
}
|
||||
|
||||
pub struct MemSafeCell<T>(MemSafe<T>);
|
||||
|
||||
impl<T> fmt::Debug for MemSafeCell<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("MemSafeCell")
|
||||
.field("inner", &format_args!("<protected {}>", type_name::<T>()))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> SafeCellHandle<T> for MemSafeCell<T> {
|
||||
type CellRead<'a>
|
||||
= memsafe::MemSafeRead<'a, T>
|
||||
where
|
||||
Self: 'a,
|
||||
T: 'a;
|
||||
type CellWrite<'a>
|
||||
= memsafe::MemSafeWrite<'a, T>
|
||||
where
|
||||
Self: 'a,
|
||||
T: 'a;
|
||||
|
||||
fn new(value: T) -> Self {
|
||||
match MemSafe::new(value) {
|
||||
Ok(inner) => Self(inner),
|
||||
Err(err) => {
|
||||
// If protected memory cannot be allocated, process integrity is compromised.
|
||||
abort_memory_breach("safe cell allocation", &err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn read(&mut self) -> Self::CellRead<'_> {
|
||||
match self.0.read() {
|
||||
Ok(inner) => inner,
|
||||
Err(err) => abort_memory_breach("safe cell read", &err),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn write(&mut self) -> Self::CellWrite<'_> {
|
||||
match self.0.write() {
|
||||
Ok(inner) => inner,
|
||||
Err(err) => {
|
||||
// If protected memory becomes unwritable here, treat it as a fatal memory breach.
|
||||
abort_memory_breach("safe cell write", &err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn abort_memory_breach(action: &str, err: &memsafe::error::MemoryError) -> ! {
|
||||
eprintln!("fatal {action}: {err}");
|
||||
std::process::abort();
|
||||
}
|
||||
|
||||
pub type SafeCell<T> = MemSafeCell<T>;
|
||||
16
server/crates/arbiter-server/src/utils.rs
Normal file
16
server/crates/arbiter-server/src/utils.rs
Normal file
@@ -0,0 +1,16 @@
|
||||
struct DeferClosure<F: FnOnce()> {
|
||||
f: Option<F>,
|
||||
}
|
||||
|
||||
impl<F: FnOnce()> Drop for DeferClosure<F> {
|
||||
fn drop(&mut self) {
|
||||
if let Some(f) = self.f.take() {
|
||||
f();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Run some code when a scope is exited, similar to Go's defer statement
|
||||
pub fn defer<F: FnOnce()>(f: F) -> impl Drop + Sized {
|
||||
DeferClosure { f: Some(f) }
|
||||
}
|
||||
@@ -1,20 +1,7 @@
|
||||
use alloy::{
|
||||
consensus::TxEip1559,
|
||||
primitives::{Address, Bytes, TxKind, U256},
|
||||
rlp::Encodable,
|
||||
};
|
||||
use arbiter_proto::proto::{
|
||||
client::{
|
||||
AuthChallengeRequest, AuthChallengeSolution, ClientRequest,
|
||||
client_request::Payload as ClientRequestPayload,
|
||||
client_response::Payload as ClientResponsePayload,
|
||||
},
|
||||
evm::EvmSignTransactionRequest,
|
||||
};
|
||||
use arbiter_proto::transport::Bi;
|
||||
use arbiter_proto::transport::{Receiver, Sender};
|
||||
use arbiter_server::actors::GlobalActors;
|
||||
use arbiter_server::{
|
||||
actors::client::{ClientConnection, connect_client},
|
||||
actors::client::{ClientConnection, auth, connect_client},
|
||||
db::{self, schema},
|
||||
};
|
||||
use diesel::{ExpressionMethods as _, insert_into};
|
||||
@@ -30,19 +17,17 @@ pub async fn test_unregistered_pubkey_rejected() {
|
||||
|
||||
let (server_transport, mut test_transport) = ChannelTransport::new();
|
||||
let actors = GlobalActors::spawn(db.clone()).await.unwrap();
|
||||
let props = ClientConnection::new(db.clone(), Box::new(server_transport), actors);
|
||||
let task = tokio::spawn(connect_client(props));
|
||||
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;
|
||||
});
|
||||
|
||||
let new_key = ed25519_dalek::SigningKey::generate(&mut rand::rng());
|
||||
let pubkey_bytes = new_key.verifying_key().to_bytes().to_vec();
|
||||
|
||||
test_transport
|
||||
.send(ClientRequest {
|
||||
payload: Some(ClientRequestPayload::AuthChallengeRequest(
|
||||
AuthChallengeRequest {
|
||||
pubkey: pubkey_bytes,
|
||||
},
|
||||
)),
|
||||
.send(auth::Inbound::AuthChallengeRequest {
|
||||
pubkey: new_key.verifying_key(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -71,17 +56,16 @@ pub async fn test_challenge_auth() {
|
||||
let (server_transport, mut test_transport) = ChannelTransport::new();
|
||||
let actors = GlobalActors::spawn(db.clone()).await.unwrap();
|
||||
|
||||
let props = ClientConnection::new(db.clone(), Box::new(server_transport), actors);
|
||||
let task = tokio::spawn(connect_client(props));
|
||||
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;
|
||||
});
|
||||
|
||||
// Send challenge request
|
||||
test_transport
|
||||
.send(ClientRequest {
|
||||
payload: Some(ClientRequestPayload::AuthChallengeRequest(
|
||||
AuthChallengeRequest {
|
||||
pubkey: pubkey_bytes,
|
||||
},
|
||||
)),
|
||||
.send(auth::Inbound::AuthChallengeRequest {
|
||||
pubkey: new_key.verifying_key(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -92,131 +76,33 @@ pub async fn test_challenge_auth() {
|
||||
.await
|
||||
.expect("should receive challenge");
|
||||
let challenge = match response {
|
||||
Ok(resp) => match resp.payload {
|
||||
Some(ClientResponsePayload::AuthChallenge(c)) => c,
|
||||
Ok(resp) => match resp {
|
||||
auth::Outbound::AuthChallenge { pubkey, nonce } => (pubkey, nonce),
|
||||
other => panic!("Expected AuthChallenge, got {other:?}"),
|
||||
},
|
||||
Err(err) => panic!("Expected Ok response, got Err({err:?})"),
|
||||
};
|
||||
|
||||
// Sign the challenge and send solution
|
||||
let formatted_challenge = arbiter_proto::format_challenge(challenge.nonce, &challenge.pubkey);
|
||||
let formatted_challenge = arbiter_proto::format_challenge(challenge.1, challenge.0.as_bytes());
|
||||
let signature = new_key.sign(&formatted_challenge);
|
||||
|
||||
test_transport
|
||||
.send(ClientRequest {
|
||||
payload: Some(ClientRequestPayload::AuthChallengeSolution(
|
||||
AuthChallengeSolution {
|
||||
signature: signature.to_bytes().to_vec(),
|
||||
},
|
||||
)),
|
||||
})
|
||||
.send(auth::Inbound::AuthChallengeSolution { signature })
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let response = test_transport
|
||||
.recv()
|
||||
.await
|
||||
.expect("should receive auth success");
|
||||
match response {
|
||||
Ok(auth::Outbound::AuthSuccess) => {}
|
||||
Ok(other) => panic!("Expected AuthSuccess, got {other:?}"),
|
||||
Err(err) => panic!("Expected Ok response, got Err({err:?})"),
|
||||
}
|
||||
|
||||
// Auth completes, session spawned
|
||||
task.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[test_log::test]
|
||||
pub async fn test_evm_sign_request_payload_is_handled() {
|
||||
let db = db::create_test_pool().await;
|
||||
|
||||
let new_key = ed25519_dalek::SigningKey::generate(&mut rand::rng());
|
||||
let pubkey_bytes = new_key.verifying_key().to_bytes().to_vec();
|
||||
|
||||
{
|
||||
let mut conn = db.get().await.unwrap();
|
||||
insert_into(schema::program_client::table)
|
||||
.values(schema::program_client::public_key.eq(pubkey_bytes.clone()))
|
||||
.execute(&mut conn)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let (server_transport, mut test_transport) = ChannelTransport::new();
|
||||
let actors = GlobalActors::spawn(db.clone()).await.unwrap();
|
||||
|
||||
let props = ClientConnection::new(db.clone(), Box::new(server_transport), actors);
|
||||
let task = tokio::spawn(connect_client(props));
|
||||
|
||||
test_transport
|
||||
.send(ClientRequest {
|
||||
payload: Some(ClientRequestPayload::AuthChallengeRequest(
|
||||
AuthChallengeRequest {
|
||||
pubkey: pubkey_bytes,
|
||||
},
|
||||
)),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let response = test_transport
|
||||
.recv()
|
||||
.await
|
||||
.expect("should receive challenge");
|
||||
let challenge = match response {
|
||||
Ok(resp) => match resp.payload {
|
||||
Some(ClientResponsePayload::AuthChallenge(c)) => c,
|
||||
other => panic!("Expected AuthChallenge, got {other:?}"),
|
||||
},
|
||||
Err(err) => panic!("Expected Ok response, got Err({err:?})"),
|
||||
};
|
||||
|
||||
let formatted_challenge = arbiter_proto::format_challenge(challenge.nonce, &challenge.pubkey);
|
||||
let signature = new_key.sign(&formatted_challenge);
|
||||
|
||||
test_transport
|
||||
.send(ClientRequest {
|
||||
payload: Some(ClientRequestPayload::AuthChallengeSolution(
|
||||
AuthChallengeSolution {
|
||||
signature: signature.to_bytes().to_vec(),
|
||||
},
|
||||
)),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
task.await.unwrap();
|
||||
|
||||
let tx = TxEip1559 {
|
||||
chain_id: 1,
|
||||
nonce: 0,
|
||||
gas_limit: 21_000,
|
||||
max_fee_per_gas: 1,
|
||||
max_priority_fee_per_gas: 1,
|
||||
to: TxKind::Call(Address::from_slice(&[0x11; 20])),
|
||||
value: U256::ZERO,
|
||||
input: Bytes::new(),
|
||||
access_list: Default::default(),
|
||||
};
|
||||
|
||||
let mut rlp_transaction = Vec::new();
|
||||
tx.encode(&mut rlp_transaction);
|
||||
|
||||
test_transport
|
||||
.send(ClientRequest {
|
||||
payload: Some(ClientRequestPayload::EvmSignTransaction(
|
||||
EvmSignTransactionRequest {
|
||||
wallet_address: [0x22; 20].to_vec(),
|
||||
rlp_transaction,
|
||||
},
|
||||
)),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let response = test_transport
|
||||
.recv()
|
||||
.await
|
||||
.expect("should receive sign response");
|
||||
|
||||
match response {
|
||||
Ok(resp) => match resp.payload {
|
||||
Some(ClientResponsePayload::EvmSignTransaction(_)) => {}
|
||||
other => panic!("Expected EvmSignTransaction response, got {other:?}"),
|
||||
},
|
||||
Err(err) => panic!("Expected Ok response, got Err({err:?})"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
use arbiter_proto::transport::{Bi, Error};
|
||||
use arbiter_proto::transport::{Bi, Error, Receiver, Sender};
|
||||
use arbiter_server::{
|
||||
actors::keyholder::KeyHolder,
|
||||
db::{self, schema},
|
||||
safe_cell::{SafeCell, SafeCellHandle as _},
|
||||
};
|
||||
use async_trait::async_trait;
|
||||
use diesel::QueryDsl;
|
||||
use diesel_async::RunQueryDsl;
|
||||
use memsafe::MemSafe;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
#[allow(dead_code)]
|
||||
pub async fn bootstrapped_keyholder(db: &db::DatabasePool) -> KeyHolder {
|
||||
let mut actor = KeyHolder::new(db.clone()).await.unwrap();
|
||||
actor
|
||||
.bootstrap(MemSafe::new(b"test-seal-key".to_vec()).unwrap())
|
||||
.bootstrap(SafeCell::new(b"test-seal-key".to_vec()))
|
||||
.await
|
||||
.unwrap();
|
||||
actor
|
||||
@@ -55,10 +55,10 @@ impl<T, Y> ChannelTransport<T, Y> {
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<T, Y> Bi<T, Y> for ChannelTransport<T, Y>
|
||||
impl<T, Y> Sender<Y> for ChannelTransport<T, Y>
|
||||
where
|
||||
T: Send + 'static,
|
||||
Y: Send + 'static,
|
||||
T: Send + Sync + 'static,
|
||||
Y: Send + Sync + 'static,
|
||||
{
|
||||
async fn send(&mut self, item: Y) -> Result<(), Error> {
|
||||
self.sender
|
||||
@@ -66,8 +66,22 @@ where
|
||||
.await
|
||||
.map_err(|_| Error::ChannelClosed)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<T, Y> Receiver<T> for ChannelTransport<T, Y>
|
||||
where
|
||||
T: Send + Sync + 'static,
|
||||
Y: Send + Sync + 'static,
|
||||
{
|
||||
async fn recv(&mut self) -> Option<T> {
|
||||
self.receiver.recv().await
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, Y> Bi<T, Y> for ChannelTransport<T, Y>
|
||||
where
|
||||
T: Send + Sync + 'static,
|
||||
Y: Send + Sync + 'static,
|
||||
{
|
||||
}
|
||||
|
||||
@@ -3,11 +3,11 @@ use std::collections::{HashMap, HashSet};
|
||||
use arbiter_server::{
|
||||
actors::keyholder::{CreateNew, Error, KeyHolder},
|
||||
db::{self, models, schema},
|
||||
safe_cell::{SafeCell, SafeCellHandle as _},
|
||||
};
|
||||
use diesel::{ExpressionMethods as _, QueryDsl, SelectableHelper, dsl::sql_query};
|
||||
use diesel_async::RunQueryDsl;
|
||||
use kameo::actor::{ActorRef, Spawn as _};
|
||||
use memsafe::MemSafe;
|
||||
use tokio::task::JoinSet;
|
||||
|
||||
use crate::common;
|
||||
@@ -24,7 +24,7 @@ async fn write_concurrently(
|
||||
let plaintext = format!("{prefix}-{i}").into_bytes();
|
||||
let id = actor
|
||||
.ask(CreateNew {
|
||||
plaintext: MemSafe::new(plaintext.clone()).unwrap(),
|
||||
plaintext: SafeCell::new(plaintext.clone()),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -118,7 +118,7 @@ async fn insert_failure_does_not_create_partial_row() {
|
||||
drop(conn);
|
||||
|
||||
let err = actor
|
||||
.create_new(MemSafe::new(b"should fail".to_vec()).unwrap())
|
||||
.create_new(SafeCell::new(b"should fail".to_vec()))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, Error::DatabaseTransaction(_)));
|
||||
@@ -162,12 +162,12 @@ async fn decrypt_roundtrip_after_high_concurrency() {
|
||||
|
||||
let mut decryptor = KeyHolder::new(db.clone()).await.unwrap();
|
||||
decryptor
|
||||
.try_unseal(MemSafe::new(b"test-seal-key".to_vec()).unwrap())
|
||||
.try_unseal(SafeCell::new(b"test-seal-key".to_vec()))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
for (id, plaintext) in expected {
|
||||
let mut decrypted = decryptor.decrypt(id).await.unwrap();
|
||||
assert_eq!(*decrypted.read().unwrap(), plaintext);
|
||||
assert_eq!(*decrypted.read(), plaintext);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use arbiter_server::{
|
||||
actors::keyholder::{Error, KeyHolder},
|
||||
db::{self, models, schema},
|
||||
safe_cell::{SafeCell, SafeCellHandle as _},
|
||||
};
|
||||
use diesel::{QueryDsl, SelectableHelper};
|
||||
use diesel_async::RunQueryDsl;
|
||||
use memsafe::MemSafe;
|
||||
|
||||
use crate::common;
|
||||
|
||||
@@ -14,7 +14,7 @@ async fn test_bootstrap() {
|
||||
let db = db::create_test_pool().await;
|
||||
let mut actor = KeyHolder::new(db.clone()).await.unwrap();
|
||||
|
||||
let seal_key = MemSafe::new(b"test-seal-key".to_vec()).unwrap();
|
||||
let seal_key = SafeCell::new(b"test-seal-key".to_vec());
|
||||
actor.bootstrap(seal_key).await.unwrap();
|
||||
|
||||
let mut conn = db.get().await.unwrap();
|
||||
@@ -43,7 +43,7 @@ async fn test_bootstrap_rejects_double() {
|
||||
let db = db::create_test_pool().await;
|
||||
let mut actor = common::bootstrapped_keyholder(&db).await;
|
||||
|
||||
let seal_key2 = MemSafe::new(b"test-seal-key".to_vec()).unwrap();
|
||||
let seal_key2 = SafeCell::new(b"test-seal-key".to_vec());
|
||||
let err = actor.bootstrap(seal_key2).await.unwrap_err();
|
||||
assert!(matches!(err, Error::AlreadyBootstrapped));
|
||||
}
|
||||
@@ -55,7 +55,7 @@ async fn test_create_new_before_bootstrap_fails() {
|
||||
let mut actor = KeyHolder::new(db).await.unwrap();
|
||||
|
||||
let err = actor
|
||||
.create_new(MemSafe::new(b"data".to_vec()).unwrap())
|
||||
.create_new(SafeCell::new(b"data".to_vec()))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, Error::NotBootstrapped));
|
||||
@@ -91,17 +91,17 @@ async fn test_unseal_correct_password() {
|
||||
|
||||
let plaintext = b"survive a restart";
|
||||
let aead_id = actor
|
||||
.create_new(MemSafe::new(plaintext.to_vec()).unwrap())
|
||||
.create_new(SafeCell::new(plaintext.to_vec()))
|
||||
.await
|
||||
.unwrap();
|
||||
drop(actor);
|
||||
|
||||
let mut actor = KeyHolder::new(db.clone()).await.unwrap();
|
||||
let seal_key = MemSafe::new(b"test-seal-key".to_vec()).unwrap();
|
||||
let seal_key = SafeCell::new(b"test-seal-key".to_vec());
|
||||
actor.try_unseal(seal_key).await.unwrap();
|
||||
|
||||
let mut decrypted = actor.decrypt(aead_id).await.unwrap();
|
||||
assert_eq!(*decrypted.read().unwrap(), plaintext);
|
||||
assert_eq!(*decrypted.read(), plaintext);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -112,20 +112,20 @@ async fn test_unseal_wrong_then_correct_password() {
|
||||
|
||||
let plaintext = b"important data";
|
||||
let aead_id = actor
|
||||
.create_new(MemSafe::new(plaintext.to_vec()).unwrap())
|
||||
.create_new(SafeCell::new(plaintext.to_vec()))
|
||||
.await
|
||||
.unwrap();
|
||||
drop(actor);
|
||||
|
||||
let mut actor = KeyHolder::new(db.clone()).await.unwrap();
|
||||
|
||||
let bad_key = MemSafe::new(b"wrong-password".to_vec()).unwrap();
|
||||
let bad_key = SafeCell::new(b"wrong-password".to_vec());
|
||||
let err = actor.try_unseal(bad_key).await.unwrap_err();
|
||||
assert!(matches!(err, Error::InvalidKey));
|
||||
|
||||
let good_key = MemSafe::new(b"test-seal-key".to_vec()).unwrap();
|
||||
let good_key = SafeCell::new(b"test-seal-key".to_vec());
|
||||
actor.try_unseal(good_key).await.unwrap();
|
||||
|
||||
let mut decrypted = actor.decrypt(aead_id).await.unwrap();
|
||||
assert_eq!(*decrypted.read().unwrap(), plaintext);
|
||||
assert_eq!(*decrypted.read(), plaintext);
|
||||
}
|
||||
|
||||
@@ -3,10 +3,10 @@ use std::collections::HashSet;
|
||||
use arbiter_server::{
|
||||
actors::keyholder::{Error, encryption::v1},
|
||||
db::{self, models, schema},
|
||||
safe_cell::{SafeCell, SafeCellHandle as _},
|
||||
};
|
||||
use diesel::{ExpressionMethods as _, QueryDsl, SelectableHelper, dsl::update};
|
||||
use diesel_async::RunQueryDsl;
|
||||
use memsafe::MemSafe;
|
||||
|
||||
use crate::common;
|
||||
|
||||
@@ -18,12 +18,12 @@ async fn test_create_decrypt_roundtrip() {
|
||||
|
||||
let plaintext = b"hello arbiter";
|
||||
let aead_id = actor
|
||||
.create_new(MemSafe::new(plaintext.to_vec()).unwrap())
|
||||
.create_new(SafeCell::new(plaintext.to_vec()))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let mut decrypted = actor.decrypt(aead_id).await.unwrap();
|
||||
assert_eq!(*decrypted.read().unwrap(), plaintext);
|
||||
assert_eq!(*decrypted.read(), plaintext);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -44,11 +44,11 @@ async fn test_ciphertext_differs_across_entries() {
|
||||
|
||||
let plaintext = b"same content";
|
||||
let id1 = actor
|
||||
.create_new(MemSafe::new(plaintext.to_vec()).unwrap())
|
||||
.create_new(SafeCell::new(plaintext.to_vec()))
|
||||
.await
|
||||
.unwrap();
|
||||
let id2 = actor
|
||||
.create_new(MemSafe::new(plaintext.to_vec()).unwrap())
|
||||
.create_new(SafeCell::new(plaintext.to_vec()))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
@@ -70,8 +70,8 @@ async fn test_ciphertext_differs_across_entries() {
|
||||
|
||||
let mut d1 = actor.decrypt(id1).await.unwrap();
|
||||
let mut d2 = actor.decrypt(id2).await.unwrap();
|
||||
assert_eq!(*d1.read().unwrap(), plaintext);
|
||||
assert_eq!(*d2.read().unwrap(), plaintext);
|
||||
assert_eq!(*d1.read(), plaintext);
|
||||
assert_eq!(*d2.read(), plaintext);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -83,7 +83,7 @@ async fn test_nonce_never_reused() {
|
||||
let n = 5;
|
||||
for i in 0..n {
|
||||
actor
|
||||
.create_new(MemSafe::new(format!("secret {i}").into_bytes()).unwrap())
|
||||
.create_new(SafeCell::new(format!("secret {i}").into_bytes()))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
@@ -137,7 +137,7 @@ async fn broken_db_nonce_format_fails_closed() {
|
||||
drop(conn);
|
||||
|
||||
let err = actor
|
||||
.create_new(MemSafe::new(b"must fail".to_vec()).unwrap())
|
||||
.create_new(SafeCell::new(b"must fail".to_vec()))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, Error::BrokenDatabase));
|
||||
@@ -145,7 +145,7 @@ async fn broken_db_nonce_format_fails_closed() {
|
||||
let db = db::create_test_pool().await;
|
||||
let mut actor = common::bootstrapped_keyholder(&db).await;
|
||||
let id = actor
|
||||
.create_new(MemSafe::new(b"decrypt target".to_vec()).unwrap())
|
||||
.create_new(SafeCell::new(b"decrypt target".to_vec()))
|
||||
.await
|
||||
.unwrap();
|
||||
let mut conn = db.get().await.unwrap();
|
||||
|
||||
@@ -2,7 +2,5 @@ mod common;
|
||||
|
||||
#[path = "user_agent/auth.rs"]
|
||||
mod auth;
|
||||
#[path = "user_agent/sdk_client.rs"]
|
||||
mod sdk_client;
|
||||
#[path = "user_agent/unseal.rs"]
|
||||
mod unseal;
|
||||
|
||||
@@ -1,14 +1,9 @@
|
||||
use arbiter_proto::proto::user_agent::{
|
||||
AuthChallengeRequest, AuthChallengeSolution, KeyType as ProtoKeyType, UserAgentRequest,
|
||||
user_agent_request::Payload as UserAgentRequestPayload,
|
||||
user_agent_response::Payload as UserAgentResponsePayload,
|
||||
};
|
||||
use arbiter_proto::transport::Bi;
|
||||
use arbiter_proto::transport::{Receiver, Sender};
|
||||
use arbiter_server::{
|
||||
actors::{
|
||||
GlobalActors,
|
||||
bootstrap::GetToken,
|
||||
user_agent::{UserAgentConnection, connect_user_agent},
|
||||
user_agent::{AuthPublicKey, UserAgentConnection, auth},
|
||||
},
|
||||
db::{self, schema},
|
||||
};
|
||||
@@ -26,26 +21,31 @@ pub async fn test_bootstrap_token_auth() {
|
||||
let token = actors.bootstrapper.ask(GetToken).await.unwrap().unwrap();
|
||||
|
||||
let (server_transport, mut test_transport) = ChannelTransport::new();
|
||||
let props = UserAgentConnection::new(db.clone(), actors, Box::new(server_transport));
|
||||
let task = tokio::spawn(connect_user_agent(props));
|
||||
let db_for_task = db.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
let mut props = UserAgentConnection::new(db_for_task, actors);
|
||||
auth::authenticate(&mut props, server_transport).await
|
||||
});
|
||||
|
||||
let new_key = ed25519_dalek::SigningKey::generate(&mut rand::rng());
|
||||
let pubkey_bytes = new_key.verifying_key().to_bytes().to_vec();
|
||||
|
||||
test_transport
|
||||
.send(UserAgentRequest {
|
||||
payload: Some(UserAgentRequestPayload::AuthChallengeRequest(
|
||||
AuthChallengeRequest {
|
||||
pubkey: pubkey_bytes,
|
||||
bootstrap_token: Some(token),
|
||||
key_type: ProtoKeyType::Ed25519.into(),
|
||||
},
|
||||
)),
|
||||
.send(auth::Inbound::AuthChallengeRequest {
|
||||
pubkey: AuthPublicKey::Ed25519(new_key.verifying_key()),
|
||||
bootstrap_token: Some(token),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
task.await.unwrap();
|
||||
let response = test_transport
|
||||
.recv()
|
||||
.await
|
||||
.expect("should receive auth result");
|
||||
match response {
|
||||
Ok(auth::Outbound::AuthSuccess) => {}
|
||||
other => panic!("Expected AuthSuccess, got {other:?}"),
|
||||
}
|
||||
|
||||
task.await.unwrap().unwrap();
|
||||
|
||||
let mut conn = db.get().await.unwrap();
|
||||
let stored_pubkey: Vec<u8> = schema::useragent_client::table
|
||||
@@ -63,27 +63,25 @@ pub async fn test_bootstrap_invalid_token_auth() {
|
||||
let actors = GlobalActors::spawn(db.clone()).await.unwrap();
|
||||
|
||||
let (server_transport, mut test_transport) = ChannelTransport::new();
|
||||
let props = UserAgentConnection::new(db.clone(), actors, Box::new(server_transport));
|
||||
let task = tokio::spawn(connect_user_agent(props));
|
||||
let db_for_task = db.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
let mut props = UserAgentConnection::new(db_for_task, actors);
|
||||
auth::authenticate(&mut props, server_transport).await
|
||||
});
|
||||
|
||||
let new_key = ed25519_dalek::SigningKey::generate(&mut rand::rng());
|
||||
let pubkey_bytes = new_key.verifying_key().to_bytes().to_vec();
|
||||
|
||||
test_transport
|
||||
.send(UserAgentRequest {
|
||||
payload: Some(UserAgentRequestPayload::AuthChallengeRequest(
|
||||
AuthChallengeRequest {
|
||||
pubkey: pubkey_bytes,
|
||||
bootstrap_token: Some("invalid_token".to_string()),
|
||||
key_type: ProtoKeyType::Ed25519.into(),
|
||||
},
|
||||
)),
|
||||
.send(auth::Inbound::AuthChallengeRequest {
|
||||
pubkey: AuthPublicKey::Ed25519(new_key.verifying_key()),
|
||||
bootstrap_token: Some("invalid_token".to_string()),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Auth fails, connect_user_agent returns, transport drops
|
||||
task.await.unwrap();
|
||||
assert!(matches!(
|
||||
task.await.unwrap(),
|
||||
Err(auth::Error::InvalidBootstrapToken)
|
||||
));
|
||||
|
||||
// Verify no key was registered
|
||||
let mut conn = db.get().await.unwrap();
|
||||
@@ -118,19 +116,17 @@ pub async fn test_challenge_auth() {
|
||||
}
|
||||
|
||||
let (server_transport, mut test_transport) = ChannelTransport::new();
|
||||
let props = UserAgentConnection::new(db.clone(), actors, Box::new(server_transport));
|
||||
let task = tokio::spawn(connect_user_agent(props));
|
||||
let db_for_task = db.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
let mut props = UserAgentConnection::new(db_for_task, actors);
|
||||
auth::authenticate(&mut props, server_transport).await
|
||||
});
|
||||
|
||||
// Send challenge request
|
||||
test_transport
|
||||
.send(UserAgentRequest {
|
||||
payload: Some(UserAgentRequestPayload::AuthChallengeRequest(
|
||||
AuthChallengeRequest {
|
||||
pubkey: pubkey_bytes,
|
||||
bootstrap_token: None,
|
||||
key_type: ProtoKeyType::Ed25519.into(),
|
||||
},
|
||||
)),
|
||||
.send(auth::Inbound::AuthChallengeRequest {
|
||||
pubkey: AuthPublicKey::Ed25519(new_key.verifying_key()),
|
||||
bootstrap_token: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -141,28 +137,31 @@ pub async fn test_challenge_auth() {
|
||||
.await
|
||||
.expect("should receive challenge");
|
||||
let challenge = match response {
|
||||
Ok(resp) => match resp.payload {
|
||||
Some(UserAgentResponsePayload::AuthChallenge(c)) => c,
|
||||
Ok(resp) => match resp {
|
||||
auth::Outbound::AuthChallenge { nonce } => nonce,
|
||||
other => panic!("Expected AuthChallenge, got {other:?}"),
|
||||
},
|
||||
Err(err) => panic!("Expected Ok response, got Err({err:?})"),
|
||||
};
|
||||
|
||||
// Sign the challenge and send solution
|
||||
let formatted_challenge = arbiter_proto::format_challenge(challenge.nonce, &challenge.pubkey);
|
||||
let formatted_challenge = arbiter_proto::format_challenge(challenge, &pubkey_bytes);
|
||||
let signature = new_key.sign(&formatted_challenge);
|
||||
|
||||
test_transport
|
||||
.send(UserAgentRequest {
|
||||
payload: Some(UserAgentRequestPayload::AuthChallengeSolution(
|
||||
AuthChallengeSolution {
|
||||
signature: signature.to_bytes().to_vec(),
|
||||
},
|
||||
)),
|
||||
.send(auth::Inbound::AuthChallengeSolution {
|
||||
signature: signature.to_bytes().to_vec(),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Auth completes, session spawned
|
||||
task.await.unwrap();
|
||||
let response = test_transport
|
||||
.recv()
|
||||
.await
|
||||
.expect("should receive auth result");
|
||||
match response {
|
||||
Ok(auth::Outbound::AuthSuccess) => {}
|
||||
other => panic!("Expected AuthSuccess, got {other:?}"),
|
||||
}
|
||||
|
||||
task.await.unwrap().unwrap();
|
||||
}
|
||||
|
||||
@@ -1,270 +0,0 @@
|
||||
use arbiter_proto::proto::user_agent::{
|
||||
SdkClientApproveRequest, SdkClientError as ProtoSdkClientError, SdkClientRevokeRequest,
|
||||
UserAgentRequest, sdk_client_approve_response, sdk_client_list_response,
|
||||
sdk_client_revoke_response, user_agent_request::Payload as UserAgentRequestPayload,
|
||||
user_agent_response::Payload as UserAgentResponsePayload,
|
||||
};
|
||||
use arbiter_server::{
|
||||
actors::{GlobalActors, user_agent::session::UserAgentSession},
|
||||
db,
|
||||
};
|
||||
|
||||
/// Shared helper: create a session and register a client pubkey via sdk_client_approve.
|
||||
async fn make_session(db: &db::DatabasePool) -> UserAgentSession {
|
||||
let actors = GlobalActors::spawn(db.clone()).await.unwrap();
|
||||
UserAgentSession::new_test(db.clone(), actors)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[test_log::test]
|
||||
async fn test_sdk_client_approve_registers_client() {
|
||||
let db = db::create_test_pool().await;
|
||||
let mut session = make_session(&db).await;
|
||||
|
||||
let pubkey = [0x42u8; 32];
|
||||
|
||||
let response = session
|
||||
.process_transport_inbound(UserAgentRequest {
|
||||
payload: Some(UserAgentRequestPayload::SdkClientApprove(
|
||||
SdkClientApproveRequest {
|
||||
pubkey: pubkey.to_vec(),
|
||||
},
|
||||
)),
|
||||
})
|
||||
.await
|
||||
.expect("handler should succeed");
|
||||
|
||||
let entry = match response.payload.unwrap() {
|
||||
UserAgentResponsePayload::SdkClientApprove(resp) => match resp.result.unwrap() {
|
||||
sdk_client_approve_response::Result::Client(e) => e,
|
||||
sdk_client_approve_response::Result::Error(e) => {
|
||||
panic!("Expected Client, got error {:?}", e)
|
||||
}
|
||||
},
|
||||
other => panic!("Expected SdkClientApprove, got {other:?}"),
|
||||
};
|
||||
|
||||
assert_eq!(entry.pubkey, pubkey.to_vec());
|
||||
assert!(entry.id > 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[test_log::test]
|
||||
async fn test_sdk_client_approve_duplicate_returns_already_exists() {
|
||||
let db = db::create_test_pool().await;
|
||||
let mut session = make_session(&db).await;
|
||||
|
||||
let pubkey = [0x11u8; 32];
|
||||
let req = UserAgentRequest {
|
||||
payload: Some(UserAgentRequestPayload::SdkClientApprove(
|
||||
SdkClientApproveRequest {
|
||||
pubkey: pubkey.to_vec(),
|
||||
},
|
||||
)),
|
||||
};
|
||||
|
||||
session
|
||||
.process_transport_inbound(req.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let response = session
|
||||
.process_transport_inbound(req)
|
||||
.await
|
||||
.expect("second insert should not panic");
|
||||
|
||||
match response.payload.unwrap() {
|
||||
UserAgentResponsePayload::SdkClientApprove(resp) => match resp.result.unwrap() {
|
||||
sdk_client_approve_response::Result::Error(code) => {
|
||||
assert_eq!(code, ProtoSdkClientError::AlreadyExists as i32);
|
||||
}
|
||||
sdk_client_approve_response::Result::Client(_) => {
|
||||
panic!("Expected AlreadyExists error for duplicate pubkey")
|
||||
}
|
||||
},
|
||||
other => panic!("Expected SdkClientApprove, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[test_log::test]
|
||||
async fn test_sdk_client_list_shows_registered_clients() {
|
||||
let db = db::create_test_pool().await;
|
||||
let mut session = make_session(&db).await;
|
||||
|
||||
let pubkey_a = [0x0Au8; 32];
|
||||
let pubkey_b = [0x0Bu8; 32];
|
||||
|
||||
for pubkey in [pubkey_a, pubkey_b] {
|
||||
session
|
||||
.process_transport_inbound(UserAgentRequest {
|
||||
payload: Some(UserAgentRequestPayload::SdkClientApprove(
|
||||
SdkClientApproveRequest {
|
||||
pubkey: pubkey.to_vec(),
|
||||
},
|
||||
)),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let response = session
|
||||
.process_transport_inbound(UserAgentRequest {
|
||||
payload: Some(UserAgentRequestPayload::SdkClientList(())),
|
||||
})
|
||||
.await
|
||||
.expect("list should succeed");
|
||||
|
||||
let clients = match response.payload.unwrap() {
|
||||
UserAgentResponsePayload::SdkClientList(resp) => match resp.result.unwrap() {
|
||||
sdk_client_list_response::Result::Clients(list) => list.clients,
|
||||
sdk_client_list_response::Result::Error(e) => {
|
||||
panic!("Expected Clients, got error {:?}", e)
|
||||
}
|
||||
},
|
||||
other => panic!("Expected SdkClientList, got {other:?}"),
|
||||
};
|
||||
|
||||
assert_eq!(clients.len(), 2);
|
||||
let pubkeys: Vec<Vec<u8>> = clients.into_iter().map(|e| e.pubkey).collect();
|
||||
assert!(pubkeys.contains(&pubkey_a.to_vec()));
|
||||
assert!(pubkeys.contains(&pubkey_b.to_vec()));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[test_log::test]
|
||||
async fn test_sdk_client_revoke_removes_client() {
|
||||
let db = db::create_test_pool().await;
|
||||
let mut session = make_session(&db).await;
|
||||
|
||||
let pubkey = [0xBBu8; 32];
|
||||
|
||||
// Register a client and get its id
|
||||
let approve_response = session
|
||||
.process_transport_inbound(UserAgentRequest {
|
||||
payload: Some(UserAgentRequestPayload::SdkClientApprove(
|
||||
SdkClientApproveRequest {
|
||||
pubkey: pubkey.to_vec(),
|
||||
},
|
||||
)),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let client_id = match approve_response.payload.unwrap() {
|
||||
UserAgentResponsePayload::SdkClientApprove(resp) => match resp.result.unwrap() {
|
||||
sdk_client_approve_response::Result::Client(e) => e.id,
|
||||
sdk_client_approve_response::Result::Error(e) => panic!("approve failed: {:?}", e),
|
||||
},
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
|
||||
// Revoke the client
|
||||
let revoke_response = session
|
||||
.process_transport_inbound(UserAgentRequest {
|
||||
payload: Some(UserAgentRequestPayload::SdkClientRevoke(
|
||||
SdkClientRevokeRequest { client_id },
|
||||
)),
|
||||
})
|
||||
.await
|
||||
.expect("revoke should succeed");
|
||||
|
||||
match revoke_response.payload.unwrap() {
|
||||
UserAgentResponsePayload::SdkClientRevoke(resp) => match resp.result.unwrap() {
|
||||
sdk_client_revoke_response::Result::Ok(_) => {}
|
||||
sdk_client_revoke_response::Result::Error(e) => {
|
||||
panic!("Expected Ok, got error {:?}", e)
|
||||
}
|
||||
},
|
||||
other => panic!("Expected SdkClientRevoke, got {other:?}"),
|
||||
}
|
||||
|
||||
// List should now be empty
|
||||
let list_response = session
|
||||
.process_transport_inbound(UserAgentRequest {
|
||||
payload: Some(UserAgentRequestPayload::SdkClientList(())),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let clients = match list_response.payload.unwrap() {
|
||||
UserAgentResponsePayload::SdkClientList(resp) => match resp.result.unwrap() {
|
||||
sdk_client_list_response::Result::Clients(list) => list.clients,
|
||||
sdk_client_list_response::Result::Error(e) => panic!("list error: {:?}", e),
|
||||
},
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
assert!(clients.is_empty(), "client should be removed after revoke");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[test_log::test]
|
||||
async fn test_sdk_client_revoke_not_found_returns_error() {
|
||||
let db = db::create_test_pool().await;
|
||||
let mut session = make_session(&db).await;
|
||||
|
||||
let response = session
|
||||
.process_transport_inbound(UserAgentRequest {
|
||||
payload: Some(UserAgentRequestPayload::SdkClientRevoke(
|
||||
SdkClientRevokeRequest { client_id: 9999 },
|
||||
)),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
match response.payload.unwrap() {
|
||||
UserAgentResponsePayload::SdkClientRevoke(resp) => match resp.result.unwrap() {
|
||||
sdk_client_revoke_response::Result::Error(code) => {
|
||||
assert_eq!(code, ProtoSdkClientError::NotFound as i32);
|
||||
}
|
||||
sdk_client_revoke_response::Result::Ok(_) => {
|
||||
panic!("Expected NotFound error for missing client_id")
|
||||
}
|
||||
},
|
||||
other => panic!("Expected SdkClientRevoke, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[test_log::test]
|
||||
async fn test_sdk_client_approve_rejected_client_cannot_auth() {
|
||||
// Verify the core flow: only pre-approved clients can authenticate
|
||||
use arbiter_proto::proto::client::{
|
||||
AuthChallengeRequest, ClientRequest, client_request::Payload as ClientRequestPayload,
|
||||
client_response::Payload as ClientResponsePayload,
|
||||
};
|
||||
use arbiter_proto::transport::Bi as _;
|
||||
use arbiter_server::actors::client::{ClientConnection, connect_client};
|
||||
|
||||
let db = db::create_test_pool().await;
|
||||
let actors = GlobalActors::spawn(db.clone()).await.unwrap();
|
||||
|
||||
let new_key = ed25519_dalek::SigningKey::generate(&mut rand::rng());
|
||||
let pubkey_bytes = new_key.verifying_key().to_bytes().to_vec();
|
||||
|
||||
let (server_transport, mut test_transport) = super::common::ChannelTransport::<_, _>::new();
|
||||
let props = ClientConnection::new(db.clone(), Box::new(server_transport), actors.clone());
|
||||
let task = tokio::spawn(connect_client(props));
|
||||
|
||||
test_transport
|
||||
.send(ClientRequest {
|
||||
payload: Some(ClientRequestPayload::AuthChallengeRequest(
|
||||
AuthChallengeRequest {
|
||||
pubkey: pubkey_bytes.clone(),
|
||||
},
|
||||
)),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let response = test_transport.recv().await.unwrap().unwrap();
|
||||
assert!(
|
||||
matches!(
|
||||
response.payload.unwrap(),
|
||||
ClientResponsePayload::ClientConnectError(_)
|
||||
),
|
||||
"unregistered client should be rejected"
|
||||
);
|
||||
|
||||
task.await.unwrap();
|
||||
}
|
||||
@@ -1,63 +1,55 @@
|
||||
use arbiter_proto::proto::user_agent::{
|
||||
UnsealEncryptedKey, UnsealResult, UnsealStart, UserAgentRequest,
|
||||
user_agent_request::Payload as UserAgentRequestPayload,
|
||||
user_agent_response::Payload as UserAgentResponsePayload,
|
||||
};
|
||||
use arbiter_server::{
|
||||
actors::{
|
||||
GlobalActors,
|
||||
keyholder::{Bootstrap, Seal},
|
||||
user_agent::session::UserAgentSession,
|
||||
user_agent::session::{
|
||||
HandleUnsealEncryptedKey, HandleUnsealRequest, UnsealError, UserAgentSession,
|
||||
},
|
||||
},
|
||||
db,
|
||||
safe_cell::{SafeCell, SafeCellHandle as _},
|
||||
};
|
||||
use chacha20poly1305::{AeadInPlace, XChaCha20Poly1305, XNonce, aead::KeyInit};
|
||||
use memsafe::MemSafe;
|
||||
use kameo::actor::Spawn as _;
|
||||
use x25519_dalek::{EphemeralSecret, PublicKey};
|
||||
|
||||
async fn setup_sealed_user_agent(
|
||||
seal_key: &[u8],
|
||||
) -> (db::DatabasePool, UserAgentSession) {
|
||||
) -> (db::DatabasePool, kameo::actor::ActorRef<UserAgentSession>) {
|
||||
let db = db::create_test_pool().await;
|
||||
let actors = GlobalActors::spawn(db.clone()).await.unwrap();
|
||||
|
||||
actors
|
||||
.key_holder
|
||||
.ask(Bootstrap {
|
||||
seal_key_raw: MemSafe::new(seal_key.to_vec()).unwrap(),
|
||||
seal_key_raw: SafeCell::new(seal_key.to_vec()),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
actors.key_holder.ask(Seal).await.unwrap();
|
||||
|
||||
let session = UserAgentSession::new_test(db.clone(), actors);
|
||||
let session = UserAgentSession::spawn(UserAgentSession::new_test(db.clone(), actors));
|
||||
|
||||
(db, session)
|
||||
}
|
||||
|
||||
async fn client_dh_encrypt(
|
||||
user_agent: &mut UserAgentSession,
|
||||
user_agent: &kameo::actor::ActorRef<UserAgentSession>,
|
||||
key_to_send: &[u8],
|
||||
) -> UnsealEncryptedKey {
|
||||
) -> HandleUnsealEncryptedKey {
|
||||
let client_secret = EphemeralSecret::random();
|
||||
let client_public = PublicKey::from(&client_secret);
|
||||
|
||||
let response = user_agent
|
||||
.process_transport_inbound(UserAgentRequest {
|
||||
payload: Some(UserAgentRequestPayload::UnsealStart(UnsealStart {
|
||||
client_pubkey: client_public.as_bytes().to_vec(),
|
||||
})),
|
||||
.ask(HandleUnsealRequest {
|
||||
client_pubkey: client_public,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let server_pubkey = match response.payload.unwrap() {
|
||||
UserAgentResponsePayload::UnsealStartResponse(resp) => resp.server_pubkey,
|
||||
other => panic!("Expected UnsealStartResponse, got {other:?}"),
|
||||
};
|
||||
let server_public = PublicKey::from(<[u8; 32]>::try_from(server_pubkey.as_slice()).unwrap());
|
||||
let server_pubkey = response.server_pubkey;
|
||||
|
||||
let shared_secret = client_secret.diffie_hellman(&server_public);
|
||||
let shared_secret = client_secret.diffie_hellman(&server_pubkey);
|
||||
let cipher = XChaCha20Poly1305::new(shared_secret.as_bytes().into());
|
||||
let nonce = XNonce::from([0u8; 24]);
|
||||
let associated_data = b"unseal";
|
||||
@@ -66,119 +58,94 @@ async fn client_dh_encrypt(
|
||||
.encrypt_in_place(&nonce, associated_data, &mut ciphertext)
|
||||
.unwrap();
|
||||
|
||||
UnsealEncryptedKey {
|
||||
HandleUnsealEncryptedKey {
|
||||
nonce: nonce.to_vec(),
|
||||
ciphertext,
|
||||
associated_data: associated_data.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
fn unseal_key_request(req: UnsealEncryptedKey) -> UserAgentRequest {
|
||||
UserAgentRequest {
|
||||
payload: Some(UserAgentRequestPayload::UnsealEncryptedKey(req)),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[test_log::test]
|
||||
pub async fn test_unseal_success() {
|
||||
let seal_key = b"test-seal-key";
|
||||
let (_db, mut user_agent) = setup_sealed_user_agent(seal_key).await;
|
||||
let (_db, user_agent) = setup_sealed_user_agent(seal_key).await;
|
||||
|
||||
let encrypted_key = client_dh_encrypt(&mut user_agent, seal_key).await;
|
||||
let encrypted_key = client_dh_encrypt(&user_agent, seal_key).await;
|
||||
|
||||
let response = user_agent
|
||||
.process_transport_inbound(unseal_key_request(encrypted_key))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
response.payload.unwrap(),
|
||||
UserAgentResponsePayload::UnsealResult(UnsealResult::Success.into()),
|
||||
);
|
||||
let response = user_agent.ask(encrypted_key).await;
|
||||
assert!(matches!(response, Ok(())));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[test_log::test]
|
||||
pub async fn test_unseal_wrong_seal_key() {
|
||||
let (_db, mut user_agent) = setup_sealed_user_agent(b"correct-key").await;
|
||||
let (_db, user_agent) = setup_sealed_user_agent(b"correct-key").await;
|
||||
|
||||
let encrypted_key = client_dh_encrypt(&mut user_agent, b"wrong-key").await;
|
||||
let encrypted_key = client_dh_encrypt(&user_agent, b"wrong-key").await;
|
||||
|
||||
let response = user_agent
|
||||
.process_transport_inbound(unseal_key_request(encrypted_key))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
response.payload.unwrap(),
|
||||
UserAgentResponsePayload::UnsealResult(UnsealResult::InvalidKey.into()),
|
||||
);
|
||||
let response = user_agent.ask(encrypted_key).await;
|
||||
assert!(matches!(
|
||||
response,
|
||||
Err(kameo::error::SendError::HandlerError(
|
||||
UnsealError::InvalidKey
|
||||
))
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[test_log::test]
|
||||
pub async fn test_unseal_corrupted_ciphertext() {
|
||||
let (_db, mut user_agent) = setup_sealed_user_agent(b"test-key").await;
|
||||
let (_db, user_agent) = setup_sealed_user_agent(b"test-key").await;
|
||||
|
||||
let client_secret = EphemeralSecret::random();
|
||||
let client_public = PublicKey::from(&client_secret);
|
||||
|
||||
user_agent
|
||||
.process_transport_inbound(UserAgentRequest {
|
||||
payload: Some(UserAgentRequestPayload::UnsealStart(UnsealStart {
|
||||
client_pubkey: client_public.as_bytes().to_vec(),
|
||||
})),
|
||||
.ask(HandleUnsealRequest {
|
||||
client_pubkey: client_public,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let response = user_agent
|
||||
.process_transport_inbound(unseal_key_request(UnsealEncryptedKey {
|
||||
.ask(HandleUnsealEncryptedKey {
|
||||
nonce: vec![0u8; 24],
|
||||
ciphertext: vec![0u8; 32],
|
||||
associated_data: vec![],
|
||||
}))
|
||||
.await
|
||||
.unwrap();
|
||||
})
|
||||
.await;
|
||||
|
||||
assert_eq!(
|
||||
response.payload.unwrap(),
|
||||
UserAgentResponsePayload::UnsealResult(UnsealResult::InvalidKey.into()),
|
||||
);
|
||||
assert!(matches!(
|
||||
response,
|
||||
Err(kameo::error::SendError::HandlerError(
|
||||
UnsealError::InvalidKey
|
||||
))
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[test_log::test]
|
||||
pub async fn test_unseal_retry_after_invalid_key() {
|
||||
let seal_key = b"real-seal-key";
|
||||
let (_db, mut user_agent) = setup_sealed_user_agent(seal_key).await;
|
||||
let (_db, user_agent) = setup_sealed_user_agent(seal_key).await;
|
||||
|
||||
{
|
||||
let encrypted_key = client_dh_encrypt(&mut user_agent, b"wrong-key").await;
|
||||
let encrypted_key = client_dh_encrypt(&user_agent, b"wrong-key").await;
|
||||
|
||||
let response = user_agent
|
||||
.process_transport_inbound(unseal_key_request(encrypted_key))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
response.payload.unwrap(),
|
||||
UserAgentResponsePayload::UnsealResult(UnsealResult::InvalidKey.into()),
|
||||
);
|
||||
let response = user_agent.ask(encrypted_key).await;
|
||||
assert!(matches!(
|
||||
response,
|
||||
Err(kameo::error::SendError::HandlerError(
|
||||
UnsealError::InvalidKey
|
||||
))
|
||||
));
|
||||
}
|
||||
|
||||
{
|
||||
let encrypted_key = client_dh_encrypt(&mut user_agent, seal_key).await;
|
||||
let encrypted_key = client_dh_encrypt(&user_agent, seal_key).await;
|
||||
|
||||
let response = user_agent
|
||||
.process_transport_inbound(unseal_key_request(encrypted_key))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
response.payload.unwrap(),
|
||||
UserAgentResponsePayload::UnsealResult(UnsealResult::Success.into()),
|
||||
);
|
||||
let response = user_agent.ask(encrypted_key).await;
|
||||
assert!(matches!(response, Ok(())));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
[package]
|
||||
name = "arbiter-terrors-poc"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
terrors = "0.3"
|
||||
@@ -1,139 +0,0 @@
|
||||
use crate::errors::{InternalError1, InternalError2, InvalidSignature, NotRegistered};
|
||||
use terrors::OneOf;
|
||||
|
||||
use crate::errors::ProtoError;
|
||||
|
||||
// Each sub-call's error type already implements DrainInto<ProtoError>, so we convert
|
||||
// directly to ProtoError without broaden — no turbofish needed anywhere.
|
||||
//
|
||||
// Call chain:
|
||||
// load_config() → OneOf<(InternalError2,)> → ProtoError::from
|
||||
// get_nonce() → OneOf<(InternalError1, InternalError2)> → ProtoError::from
|
||||
// verify_sig() → OneOf<(InvalidSignature,)> → ProtoError::from
|
||||
pub fn process_request(id: u32, sig: &str) -> Result<String, ProtoError> {
|
||||
if id == 0 {
|
||||
return Err(ProtoError::NotRegistered);
|
||||
}
|
||||
|
||||
let config = load_config(id).map_err(ProtoError::from)?;
|
||||
let nonce = crate::db::get_nonce(id).map_err(ProtoError::from)?;
|
||||
verify_signature(nonce, sig).map_err(ProtoError::from)?;
|
||||
|
||||
Ok(format!("config={config} nonce={nonce} sig={sig}"))
|
||||
}
|
||||
|
||||
// Simulates loading a config value.
|
||||
// id=97 triggers InternalError2 ("config read failed").
|
||||
fn load_config(id: u32) -> Result<String, OneOf<(InternalError2,)>> {
|
||||
if id == 97 {
|
||||
return Err(OneOf::new(InternalError2("config read failed".to_owned())));
|
||||
}
|
||||
Ok(format!("cfg-{id}"))
|
||||
}
|
||||
|
||||
pub fn verify_signature(_nonce: u32, sig: &str) -> Result<(), OneOf<(InvalidSignature,)>> {
|
||||
if sig != "ok" {
|
||||
return Err(OneOf::new(InvalidSignature));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
type AuthError = OneOf<(
|
||||
NotRegistered,
|
||||
InvalidSignature,
|
||||
InternalError1,
|
||||
InternalError2,
|
||||
)>;
|
||||
|
||||
pub fn authenticate(id: u32, sig: &str) -> Result<u32, AuthError> {
|
||||
if id == 0 {
|
||||
return Err(OneOf::new(NotRegistered));
|
||||
}
|
||||
|
||||
// Return type AuthError lets the compiler infer the broaden target.
|
||||
let nonce = crate::db::get_nonce(id).map_err(OneOf::broaden)?;
|
||||
verify_signature(nonce, sig).map_err(OneOf::broaden)?;
|
||||
|
||||
Ok(nonce)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn verify_signature_ok() {
|
||||
assert!(verify_signature(42, "ok").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verify_signature_bad() {
|
||||
let err = verify_signature(42, "bad").unwrap_err();
|
||||
assert!(err.narrow::<crate::errors::InvalidSignature, _>().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authenticate_success() {
|
||||
assert_eq!(authenticate(1, "ok").unwrap(), 42);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authenticate_not_registered() {
|
||||
let err = authenticate(0, "ok").unwrap_err();
|
||||
assert!(err.narrow::<crate::errors::NotRegistered, _>().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authenticate_invalid_signature() {
|
||||
let err = authenticate(1, "bad").unwrap_err();
|
||||
assert!(err.narrow::<crate::errors::InvalidSignature, _>().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authenticate_internal_error1() {
|
||||
let err = authenticate(99, "ok").unwrap_err();
|
||||
assert!(err.narrow::<crate::errors::InternalError1, _>().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn authenticate_internal_error2() {
|
||||
let err = authenticate(98, "ok").unwrap_err();
|
||||
assert!(err.narrow::<crate::errors::InternalError2, _>().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_request_success() {
|
||||
let result = process_request(1, "ok").unwrap();
|
||||
assert!(result.contains("nonce=42"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_request_not_registered() {
|
||||
let err = process_request(0, "ok").unwrap_err();
|
||||
assert!(matches!(err, crate::errors::ProtoError::NotRegistered));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_request_invalid_signature() {
|
||||
let err = process_request(1, "bad").unwrap_err();
|
||||
assert!(matches!(err, crate::errors::ProtoError::InvalidSignature));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_request_internal_from_config() {
|
||||
// id=97 → load_config returns InternalError2
|
||||
let err = process_request(97, "ok").unwrap_err();
|
||||
assert!(
|
||||
matches!(err, crate::errors::ProtoError::Internal(ref msg) if msg == "config read failed")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn process_request_internal_from_db() {
|
||||
// id=99 → get_nonce returns InternalError1
|
||||
let err = process_request(99, "ok").unwrap_err();
|
||||
assert!(
|
||||
matches!(err, crate::errors::ProtoError::Internal(ref msg) if msg == "db pool unavailable")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
use crate::errors::{InternalError1, InternalError2};
|
||||
use terrors::OneOf;
|
||||
|
||||
// Simulates fetching a nonce from a database.
|
||||
// id=99 → InternalError1 (pool unavailable)
|
||||
// id=98 → InternalError2 (query timeout)
|
||||
pub fn get_nonce(id: u32) -> Result<u32, OneOf<(InternalError1, InternalError2)>> {
|
||||
match id {
|
||||
99 => Err(OneOf::new(InternalError1("db pool unavailable".to_owned()))),
|
||||
98 => Err(OneOf::new(InternalError2("query timeout".to_owned()))),
|
||||
_ => Ok(42),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn get_nonce_returns_nonce_for_valid_id() {
|
||||
assert_eq!(get_nonce(1).unwrap(), 42);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_nonce_returns_internal_error1_for_sentinel() {
|
||||
let err = get_nonce(99).unwrap_err();
|
||||
let internal = err.narrow::<crate::errors::InternalError1, _>().unwrap();
|
||||
assert_eq!(internal.0, "db pool unavailable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn get_nonce_returns_internal_error2_for_sentinel() {
|
||||
let err = get_nonce(98).unwrap_err();
|
||||
let e = err.narrow::<crate::errors::InternalError1, _>().unwrap_err();
|
||||
let internal = e.take::<crate::errors::InternalError2>();
|
||||
assert_eq!(internal.0, "query timeout");
|
||||
}
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
use terrors::OneOf;
|
||||
|
||||
// Wire boundary type — what would go into a proto response
|
||||
#[derive(Debug)]
|
||||
pub enum ProtoError {
|
||||
NotRegistered,
|
||||
InvalidSignature,
|
||||
Internal(String), // Or Box<dyn Error>, who cares?
|
||||
}
|
||||
|
||||
// Internal terrors types
|
||||
#[derive(Debug)]
|
||||
pub struct NotRegistered;
|
||||
#[derive(Debug)]
|
||||
pub struct InvalidSignature;
|
||||
#[derive(Debug)]
|
||||
pub struct InternalError1(pub String);
|
||||
#[derive(Debug)]
|
||||
pub struct InternalError2(pub String);
|
||||
|
||||
// Errors can be scattered across the codebase as long as they implement Into<ProtoError>
|
||||
impl From<NotRegistered> for ProtoError {
|
||||
fn from(_: NotRegistered) -> Self {
|
||||
ProtoError::NotRegistered
|
||||
}
|
||||
}
|
||||
|
||||
impl From<InvalidSignature> for ProtoError {
|
||||
fn from(_: InvalidSignature) -> Self {
|
||||
ProtoError::InvalidSignature
|
||||
}
|
||||
}
|
||||
|
||||
impl From<InternalError1> for ProtoError {
|
||||
fn from(e: InternalError1) -> Self {
|
||||
ProtoError::Internal(e.0)
|
||||
}
|
||||
}
|
||||
impl From<InternalError2> for ProtoError {
|
||||
fn from(e: InternalError2) -> Self {
|
||||
ProtoError::Internal(e.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Private helper trait for converting from OneOf<T...> where each T can be converted
|
||||
/// into the target type `O` by recursively narrowing until a match is found.
|
||||
///
|
||||
/// IDK why this isn't already in terrors.
|
||||
trait DrainInto<O>: terrors::TypeSet + Sized {
|
||||
fn drain(e: OneOf<Self>) -> O;
|
||||
}
|
||||
|
||||
macro_rules! impl_drain_into {
|
||||
($head:ident) => {
|
||||
impl<$head, O> DrainInto<O> for ($head,)
|
||||
where
|
||||
$head: Into<O> + 'static,
|
||||
{
|
||||
fn drain(e: OneOf<($head,)>) -> O {
|
||||
e.take().into()
|
||||
}
|
||||
}
|
||||
};
|
||||
($head:ident, $($tail:ident),+) => {
|
||||
impl<$head, $($tail),+, O> DrainInto<O> for ($head, $($tail),+)
|
||||
where
|
||||
$head: Into<O> + 'static,
|
||||
($($tail,)+): DrainInto<O>,
|
||||
{
|
||||
fn drain(e: OneOf<($head, $($tail),+)>) -> O {
|
||||
match e.narrow::<$head, _>() {
|
||||
Ok(h) => h.into(),
|
||||
Err(rest) => <($($tail,)+)>::drain(rest),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl_drain_into!($($tail),+);
|
||||
};
|
||||
}
|
||||
|
||||
// Generates impls for all tuple sizes from 1 up to 7 (restricted by terrors internal impl).
|
||||
// Each invocation produces one impl then recurses on the tail.
|
||||
impl_drain_into!(A, B, C, D, E, F, G, H, I);
|
||||
|
||||
// Blanket From impl: body delegates to the recursive drain.
|
||||
impl<E: DrainInto<ProtoError>> From<OneOf<E>> for ProtoError {
|
||||
fn from(e: OneOf<E>) -> Self {
|
||||
E::drain(e)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn not_registered_converts_to_proto() {
|
||||
let e: ProtoError = NotRegistered.into();
|
||||
assert!(matches!(e, ProtoError::NotRegistered));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_signature_converts_to_proto() {
|
||||
let e: ProtoError = InvalidSignature.into();
|
||||
assert!(matches!(e, ProtoError::InvalidSignature));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn internal_converts_to_proto() {
|
||||
let e: ProtoError = InternalError1("boom".into()).into();
|
||||
assert!(matches!(e, ProtoError::Internal(msg) if msg == "boom"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_of_remainder_converts_to_proto_invalid_signature() {
|
||||
use terrors::OneOf;
|
||||
let e: OneOf<(InvalidSignature, InternalError1)> = OneOf::new(InvalidSignature);
|
||||
let proto = ProtoError::from(e);
|
||||
assert!(matches!(proto, ProtoError::InvalidSignature));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_of_remainder_converts_to_proto_internal() {
|
||||
use terrors::OneOf;
|
||||
let e: OneOf<(InvalidSignature, InternalError1)> =
|
||||
OneOf::new(InternalError1("db fail".into()));
|
||||
let proto = ProtoError::from(e);
|
||||
assert!(matches!(proto, ProtoError::Internal(msg) if msg == "db fail"));
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
mod auth;
|
||||
mod db;
|
||||
mod errors;
|
||||
|
||||
use errors::ProtoError;
|
||||
|
||||
fn run(id: u32, sig: &str) {
|
||||
print!("authenticate(id={id}, sig={sig:?}) => ");
|
||||
match auth::authenticate(id, sig) {
|
||||
Ok(nonce) => println!("Ok(nonce={nonce})"),
|
||||
Err(e) => match e.narrow::<errors::NotRegistered, _>() {
|
||||
Ok(_) => println!("Err(NotRegistered) — handled locally"),
|
||||
Err(remaining) => {
|
||||
let proto = ProtoError::from(remaining);
|
||||
println!("Err(ProtoError::{proto:?}) — forwarded to wire");
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn run_process(id: u32, sig: &str) {
|
||||
print!("process_request(id={id}, sig={sig:?}) => ");
|
||||
match auth::process_request(id, sig) {
|
||||
Ok(s) => println!("Ok({s})"),
|
||||
Err(e) => println!("Err(ProtoError::{e:?})"),
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("=== authenticate ===");
|
||||
run(0, "ok"); // NotRegistered
|
||||
run(1, "bad"); // InvalidSignature
|
||||
run(99, "ok"); // InternalError1
|
||||
run(98, "ok"); // InternalError2
|
||||
run(1, "ok"); // success
|
||||
|
||||
println!("\n=== process_request (Try chain) ===");
|
||||
run_process(0, "ok"); // NotRegistered (guard, no I/O)
|
||||
run_process(97, "ok"); // InternalError2 from load_config
|
||||
run_process(99, "ok"); // InternalError1 from get_nonce
|
||||
run_process(1, "bad"); // InvalidSignature from verify_signature
|
||||
run_process(1, "ok"); // success
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
[package]
|
||||
name = "arbiter-useragent"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = "Apache-2.0"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
arbiter-proto.path = "../arbiter-proto"
|
||||
kameo.workspace = true
|
||||
tokio = {workspace = true, features = ["net"]}
|
||||
tonic.workspace = true
|
||||
tonic.features = ["tls-aws-lc"]
|
||||
tracing.workspace = true
|
||||
ed25519-dalek.workspace = true
|
||||
smlang.workspace = true
|
||||
x25519-dalek.workspace = true
|
||||
k256.workspace = true
|
||||
rsa.workspace = true
|
||||
sha2.workspace = true
|
||||
spki.workspace = true
|
||||
rand.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio-stream.workspace = true
|
||||
http = "1.4.0"
|
||||
rustls-webpki = { version = "0.103.9", features = ["aws-lc-rs"] }
|
||||
async-trait.workspace = true
|
||||
@@ -1,70 +0,0 @@
|
||||
use arbiter_proto::{
|
||||
proto::{
|
||||
arbiter_service_client::ArbiterServiceClient,
|
||||
user_agent::{UserAgentRequest, UserAgentResponse},
|
||||
},
|
||||
transport::{IdentityRecvConverter, IdentitySendConverter, grpc},
|
||||
url::ArbiterUrl,
|
||||
};
|
||||
use kameo::actor::{ActorRef, Spawn};
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_stream::wrappers::ReceiverStream;
|
||||
|
||||
use tonic::transport::ClientTlsConfig;
|
||||
|
||||
use super::{SigningKeyEnum, UserAgentActor};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ConnectError {
|
||||
#[error("Could establish connection")]
|
||||
Connection(#[from] tonic::transport::Error),
|
||||
|
||||
#[error("Invalid server URI")]
|
||||
InvalidUri(#[from] http::uri::InvalidUri),
|
||||
|
||||
#[error("Invalid CA certificate")]
|
||||
InvalidCaCert(#[from] webpki::Error),
|
||||
|
||||
#[error("gRPC error")]
|
||||
Grpc(#[from] tonic::Status),
|
||||
}
|
||||
|
||||
pub type UserAgentGrpc = ActorRef<
|
||||
UserAgentActor<
|
||||
grpc::GrpcAdapter<
|
||||
IdentityRecvConverter<UserAgentResponse>,
|
||||
IdentitySendConverter<UserAgentRequest>,
|
||||
>,
|
||||
>,
|
||||
>;
|
||||
pub async fn connect_grpc(
|
||||
url: ArbiterUrl,
|
||||
key: SigningKeyEnum,
|
||||
) -> Result<UserAgentGrpc, ConnectError> {
|
||||
let bootstrap_token = url.bootstrap_token.clone();
|
||||
let anchor = webpki::anchor_from_trusted_cert(&url.ca_cert)?.to_owned();
|
||||
let tls = ClientTlsConfig::new().trust_anchor(anchor);
|
||||
|
||||
// TODO: if `host` is localhost, we need to verify server's process authenticity
|
||||
let channel = tonic::transport::Channel::from_shared(format!("{}:{}", url.host, url.port))?
|
||||
.tls_config(tls)?
|
||||
.connect()
|
||||
.await?;
|
||||
|
||||
let mut client = ArbiterServiceClient::new(channel);
|
||||
let (tx, rx) = mpsc::channel(16);
|
||||
let bistream = client.user_agent(ReceiverStream::new(rx)).await?;
|
||||
let bistream = bistream.into_inner();
|
||||
|
||||
let adapter = grpc::GrpcAdapter::new(
|
||||
tx,
|
||||
bistream,
|
||||
IdentityRecvConverter::new(),
|
||||
IdentitySendConverter::new(),
|
||||
);
|
||||
|
||||
let actor = UserAgentActor::spawn(UserAgentActor::new(key, bootstrap_token, adapter));
|
||||
|
||||
Ok(actor)
|
||||
}
|
||||
@@ -1,257 +0,0 @@
|
||||
use arbiter_proto::{
|
||||
format_challenge,
|
||||
proto::user_agent::{
|
||||
AuthChallengeRequest, AuthChallengeSolution, AuthOk, KeyType as ProtoKeyType,
|
||||
UserAgentRequest, UserAgentResponse,
|
||||
user_agent_request::Payload as UserAgentRequestPayload,
|
||||
user_agent_response::Payload as UserAgentResponsePayload,
|
||||
},
|
||||
transport::Bi,
|
||||
};
|
||||
use kameo::{Actor, actor::ActorRef};
|
||||
use smlang::statemachine;
|
||||
use tokio::select;
|
||||
use tracing::{error, info};
|
||||
|
||||
/// Signing key variants supported by the user-agent auth protocol.
|
||||
pub enum SigningKeyEnum {
|
||||
Ed25519(ed25519_dalek::SigningKey),
|
||||
/// secp256k1 ECDSA; public key is sent as SEC1 compressed 33 bytes; signature is raw 64-byte (r||s).
|
||||
EcdsaSecp256k1(k256::ecdsa::SigningKey),
|
||||
/// RSA for Windows Hello (KeyCredentialManager); public key is DER SPKI; signature is PSS+SHA-256.
|
||||
Rsa(rsa::RsaPrivateKey),
|
||||
}
|
||||
|
||||
impl SigningKeyEnum {
|
||||
/// Returns the canonical public key bytes to include in `AuthChallengeRequest.pubkey`.
|
||||
pub fn pubkey_bytes(&self) -> Vec<u8> {
|
||||
match self {
|
||||
SigningKeyEnum::Ed25519(k) => k.verifying_key().to_bytes().to_vec(),
|
||||
// 33-byte SEC1 compressed point — compact and natively supported by secp256k1 tooling
|
||||
SigningKeyEnum::EcdsaSecp256k1(k) => {
|
||||
k.verifying_key().to_encoded_point(true).as_bytes().to_vec()
|
||||
}
|
||||
SigningKeyEnum::Rsa(k) => {
|
||||
use rsa::pkcs8::EncodePublicKey as _;
|
||||
k.to_public_key()
|
||||
.to_public_key_der()
|
||||
.expect("rsa SPKI encoding is infallible")
|
||||
.to_vec()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the proto `KeyType` discriminant to send in `AuthChallengeRequest.key_type`.
|
||||
pub fn proto_key_type(&self) -> ProtoKeyType {
|
||||
match self {
|
||||
SigningKeyEnum::Ed25519(_) => ProtoKeyType::Ed25519,
|
||||
SigningKeyEnum::EcdsaSecp256k1(_) => ProtoKeyType::EcdsaSecp256k1,
|
||||
SigningKeyEnum::Rsa(_) => ProtoKeyType::Rsa,
|
||||
}
|
||||
}
|
||||
|
||||
/// Signs `msg` and returns raw signature bytes matching the server-side verification.
|
||||
pub fn sign(&self, msg: &[u8]) -> Vec<u8> {
|
||||
match self {
|
||||
SigningKeyEnum::Ed25519(k) => {
|
||||
use ed25519_dalek::Signer as _;
|
||||
k.sign(msg).to_bytes().to_vec()
|
||||
}
|
||||
SigningKeyEnum::EcdsaSecp256k1(k) => {
|
||||
use k256::ecdsa::signature::Signer as _;
|
||||
let sig: k256::ecdsa::Signature = k.sign(msg);
|
||||
sig.to_bytes().to_vec()
|
||||
}
|
||||
SigningKeyEnum::Rsa(k) => {
|
||||
use rsa::signature::RandomizedSigner as _;
|
||||
let signing_key = rsa::pss::BlindedSigningKey::<sha2::Sha256>::new(k.clone());
|
||||
// Use rand_core OsRng from the rsa crate's re-exported rand_core (0.6.x),
|
||||
// which is the version rsa's signature API expects.
|
||||
let sig = signing_key.sign_with_rng(&mut rsa::rand_core::OsRng, msg);
|
||||
use rsa::signature::SignatureEncoding as _;
|
||||
sig.to_vec()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
statemachine! {
|
||||
name: UserAgent,
|
||||
custom_error: false,
|
||||
transitions: {
|
||||
*Init + SentAuthChallengeRequest = WaitingForServerAuth,
|
||||
WaitingForServerAuth + ReceivedAuthChallenge = WaitingForAuthOk,
|
||||
WaitingForServerAuth + ReceivedAuthOk = Authenticated,
|
||||
WaitingForAuthOk + ReceivedAuthOk = Authenticated,
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DummyContext;
|
||||
impl UserAgentStateMachineContext for DummyContext {}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum InboundError {
|
||||
#[error("Invalid user agent response")]
|
||||
InvalidResponse,
|
||||
#[error("Expected response payload")]
|
||||
MissingResponsePayload,
|
||||
#[error("Unexpected response payload")]
|
||||
UnexpectedResponsePayload,
|
||||
#[error("Invalid state for auth challenge")]
|
||||
InvalidStateForAuthChallenge,
|
||||
#[error("Invalid state for auth ok")]
|
||||
InvalidStateForAuthOk,
|
||||
#[error("State machine error")]
|
||||
StateTransitionFailed,
|
||||
#[error("Transport send failed")]
|
||||
TransportSendFailed,
|
||||
}
|
||||
|
||||
pub struct UserAgentActor<Transport>
|
||||
where
|
||||
Transport: Bi<UserAgentResponse, UserAgentRequest>,
|
||||
{
|
||||
key: SigningKeyEnum,
|
||||
bootstrap_token: Option<String>,
|
||||
state: UserAgentStateMachine<DummyContext>,
|
||||
transport: Transport,
|
||||
}
|
||||
|
||||
impl<Transport> UserAgentActor<Transport>
|
||||
where
|
||||
Transport: Bi<UserAgentResponse, UserAgentRequest>,
|
||||
{
|
||||
pub fn new(key: SigningKeyEnum, bootstrap_token: Option<String>, transport: Transport) -> Self {
|
||||
Self {
|
||||
key,
|
||||
bootstrap_token,
|
||||
state: UserAgentStateMachine::new(DummyContext),
|
||||
transport,
|
||||
}
|
||||
}
|
||||
|
||||
fn transition(&mut self, event: UserAgentEvents) -> Result<(), InboundError> {
|
||||
self.state.process_event(event).map_err(|e| {
|
||||
error!(?e, "useragent state transition failed");
|
||||
InboundError::StateTransitionFailed
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_auth_challenge_request(&mut self) -> Result<(), InboundError> {
|
||||
let req = AuthChallengeRequest {
|
||||
pubkey: self.key.pubkey_bytes(),
|
||||
bootstrap_token: self.bootstrap_token.take(),
|
||||
key_type: self.key.proto_key_type().into(),
|
||||
};
|
||||
|
||||
self.transition(UserAgentEvents::SentAuthChallengeRequest)?;
|
||||
|
||||
self.transport
|
||||
.send(UserAgentRequest {
|
||||
payload: Some(UserAgentRequestPayload::AuthChallengeRequest(req)),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| InboundError::TransportSendFailed)?;
|
||||
|
||||
info!(actor = "useragent", "auth.request.sent");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_auth_challenge(
|
||||
&mut self,
|
||||
challenge: arbiter_proto::proto::user_agent::AuthChallenge,
|
||||
) -> Result<(), InboundError> {
|
||||
self.transition(UserAgentEvents::ReceivedAuthChallenge)?;
|
||||
|
||||
let formatted = format_challenge(challenge.nonce, &challenge.pubkey);
|
||||
let signature_bytes = self.key.sign(&formatted);
|
||||
let solution = AuthChallengeSolution {
|
||||
signature: signature_bytes,
|
||||
};
|
||||
|
||||
self.transport
|
||||
.send(UserAgentRequest {
|
||||
payload: Some(UserAgentRequestPayload::AuthChallengeSolution(solution)),
|
||||
})
|
||||
.await
|
||||
.map_err(|_| InboundError::TransportSendFailed)?;
|
||||
|
||||
info!(actor = "useragent", "auth.solution.sent");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_auth_ok(&mut self, _ok: AuthOk) -> Result<(), InboundError> {
|
||||
self.transition(UserAgentEvents::ReceivedAuthOk)?;
|
||||
info!(actor = "useragent", "auth.ok");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn process_inbound_transport(
|
||||
&mut self,
|
||||
inbound: UserAgentResponse,
|
||||
) -> Result<(), InboundError> {
|
||||
let payload = inbound
|
||||
.payload
|
||||
.ok_or(InboundError::MissingResponsePayload)?;
|
||||
|
||||
match payload {
|
||||
UserAgentResponsePayload::AuthChallenge(challenge) => {
|
||||
self.handle_auth_challenge(challenge).await
|
||||
}
|
||||
UserAgentResponsePayload::AuthOk(ok) => self.handle_auth_ok(ok),
|
||||
_ => Err(InboundError::UnexpectedResponsePayload),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<Transport> Actor for UserAgentActor<Transport>
|
||||
where
|
||||
Transport: Bi<UserAgentResponse, UserAgentRequest>,
|
||||
{
|
||||
type Args = Self;
|
||||
|
||||
type Error = ();
|
||||
|
||||
async fn on_start(
|
||||
mut args: Self::Args,
|
||||
_actor_ref: ActorRef<Self>,
|
||||
) -> Result<Self, Self::Error> {
|
||||
if let Err(err) = args.send_auth_challenge_request().await {
|
||||
error!(?err, actor = "useragent", "auth.start.failed");
|
||||
return Err(());
|
||||
}
|
||||
Ok(args)
|
||||
}
|
||||
|
||||
async fn next(
|
||||
&mut self,
|
||||
_actor_ref: kameo::prelude::WeakActorRef<Self>,
|
||||
mailbox_rx: &mut kameo::prelude::MailboxReceiver<Self>,
|
||||
) -> Option<kameo::mailbox::Signal<Self>> {
|
||||
loop {
|
||||
select! {
|
||||
signal = mailbox_rx.recv() => {
|
||||
return signal;
|
||||
}
|
||||
inbound = self.transport.recv() => {
|
||||
match inbound {
|
||||
Some(inbound) => {
|
||||
if let Err(err) = self.process_inbound_transport(inbound).await {
|
||||
error!(?err, actor = "useragent", "transport.inbound.failed");
|
||||
return Some(kameo::mailbox::Signal::Stop);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
info!(actor = "useragent", "transport.closed");
|
||||
return Some(kameo::mailbox::Signal::Stop);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
mod grpc;
|
||||
pub use grpc::{ConnectError, connect_grpc};
|
||||
@@ -1,146 +0,0 @@
|
||||
use arbiter_proto::{
|
||||
format_challenge,
|
||||
proto::user_agent::{
|
||||
AuthChallenge, AuthOk, UserAgentRequest, UserAgentResponse,
|
||||
user_agent_request::Payload as UserAgentRequestPayload,
|
||||
user_agent_response::Payload as UserAgentResponsePayload,
|
||||
},
|
||||
transport::Bi,
|
||||
};
|
||||
use arbiter_useragent::{SigningKeyEnum, UserAgentActor};
|
||||
use async_trait::async_trait;
|
||||
use ed25519_dalek::SigningKey;
|
||||
use kameo::actor::Spawn;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::{Duration, timeout};
|
||||
|
||||
struct TestTransport {
|
||||
inbound_rx: mpsc::Receiver<UserAgentResponse>,
|
||||
outbound_tx: mpsc::Sender<UserAgentRequest>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl Bi<UserAgentResponse, UserAgentRequest> for TestTransport {
|
||||
async fn send(
|
||||
&mut self,
|
||||
item: UserAgentRequest,
|
||||
) -> Result<(), arbiter_proto::transport::Error> {
|
||||
self.outbound_tx
|
||||
.send(item)
|
||||
.await
|
||||
.map_err(|_| arbiter_proto::transport::Error::ChannelClosed)
|
||||
}
|
||||
|
||||
async fn recv(&mut self) -> Option<UserAgentResponse> {
|
||||
self.inbound_rx.recv().await
|
||||
}
|
||||
}
|
||||
|
||||
fn make_transport() -> (
|
||||
TestTransport,
|
||||
mpsc::Sender<UserAgentResponse>,
|
||||
mpsc::Receiver<UserAgentRequest>,
|
||||
) {
|
||||
let (inbound_tx, inbound_rx) = mpsc::channel(8);
|
||||
let (outbound_tx, outbound_rx) = mpsc::channel(8);
|
||||
(
|
||||
TestTransport {
|
||||
inbound_rx,
|
||||
outbound_tx,
|
||||
},
|
||||
inbound_tx,
|
||||
outbound_rx,
|
||||
)
|
||||
}
|
||||
|
||||
fn test_key() -> SigningKeyEnum {
|
||||
SigningKeyEnum::Ed25519(SigningKey::from_bytes(&[7u8; 32]))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sends_auth_request_on_start_with_bootstrap_token() {
|
||||
let key = test_key();
|
||||
let pubkey = key.pubkey_bytes();
|
||||
let bootstrap_token = Some("bootstrap-123".to_string());
|
||||
let (transport, inbound_tx, mut outbound_rx) = make_transport();
|
||||
|
||||
let actor = UserAgentActor::spawn(UserAgentActor::new(key, bootstrap_token.clone(), transport));
|
||||
|
||||
let outbound = timeout(Duration::from_secs(1), outbound_rx.recv())
|
||||
.await
|
||||
.expect("timed out waiting for auth request")
|
||||
.expect("channel closed before auth request");
|
||||
|
||||
let UserAgentRequest {
|
||||
payload: Some(UserAgentRequestPayload::AuthChallengeRequest(req)),
|
||||
} = outbound
|
||||
else {
|
||||
panic!("expected auth challenge request");
|
||||
};
|
||||
|
||||
assert_eq!(req.pubkey, pubkey);
|
||||
assert_eq!(req.bootstrap_token, bootstrap_token);
|
||||
|
||||
drop(inbound_tx);
|
||||
drop(actor);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn challenge_flow_sends_solution_from_transport_inbound() {
|
||||
let key = test_key();
|
||||
let pubkey_bytes = key.pubkey_bytes();
|
||||
let (transport, inbound_tx, mut outbound_rx) = make_transport();
|
||||
|
||||
let actor = UserAgentActor::spawn(UserAgentActor::new(key, None, transport));
|
||||
|
||||
let _initial_auth_request = timeout(Duration::from_secs(1), outbound_rx.recv())
|
||||
.await
|
||||
.expect("timed out waiting for initial auth request")
|
||||
.expect("missing initial auth request");
|
||||
|
||||
let challenge = AuthChallenge {
|
||||
pubkey: pubkey_bytes.clone(),
|
||||
nonce: 42,
|
||||
};
|
||||
inbound_tx
|
||||
.send(UserAgentResponse {
|
||||
payload: Some(UserAgentResponsePayload::AuthChallenge(challenge.clone())),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let outbound = timeout(Duration::from_secs(1), outbound_rx.recv())
|
||||
.await
|
||||
.expect("timed out waiting for challenge solution")
|
||||
.expect("missing challenge solution");
|
||||
|
||||
let UserAgentRequest {
|
||||
payload: Some(UserAgentRequestPayload::AuthChallengeSolution(solution)),
|
||||
} = outbound
|
||||
else {
|
||||
panic!("expected auth challenge solution");
|
||||
};
|
||||
|
||||
// Verify the signature using the Ed25519 verifying key
|
||||
let formatted = format_challenge(challenge.nonce, &challenge.pubkey);
|
||||
let raw_key = SigningKey::from_bytes(&[7u8; 32]);
|
||||
let sig: ed25519_dalek::Signature = solution
|
||||
.signature
|
||||
.as_slice()
|
||||
.try_into()
|
||||
.expect("signature bytes length");
|
||||
raw_key
|
||||
.verifying_key()
|
||||
.verify_strict(&formatted, &sig)
|
||||
.expect("solution signature should verify");
|
||||
|
||||
inbound_tx
|
||||
.send(UserAgentResponse {
|
||||
payload: Some(UserAgentResponsePayload::AuthOk(AuthOk {})),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
drop(inbound_tx);
|
||||
drop(actor);
|
||||
}
|
||||
0
server/rules/.gitkeep
Normal file
0
server/rules/.gitkeep
Normal file
10
server/rules/safecell/new-inline.yaml
Normal file
10
server/rules/safecell/new-inline.yaml
Normal file
@@ -0,0 +1,10 @@
|
||||
id: safecell-new-inline
|
||||
language: Rust
|
||||
rule:
|
||||
pattern: $CELL.write_inline(|$W| $BODY);
|
||||
follows:
|
||||
pattern: let mut $CELL = SafeCell::new($INIT);
|
||||
fix:
|
||||
template: let mut $CELL = SafeCell::new_inline(|$W| $BODY);
|
||||
expandStart:
|
||||
pattern: let mut $CELL = SafeCell::new($INIT)
|
||||
17
server/rules/safecell/read-inline.yaml
Normal file
17
server/rules/safecell/read-inline.yaml
Normal file
@@ -0,0 +1,17 @@
|
||||
id: safecell-read-inline
|
||||
language: Rust
|
||||
rule:
|
||||
pattern:
|
||||
context: |
|
||||
{
|
||||
let $READ = $CELL.read();
|
||||
$$$BODY
|
||||
}
|
||||
selector: block
|
||||
inside:
|
||||
kind: block
|
||||
fix:
|
||||
template: |
|
||||
$CELL.read_inline(|$READ| {
|
||||
$$$BODY
|
||||
});
|
||||
13
server/rules/safecell/write-inline.yaml
Normal file
13
server/rules/safecell/write-inline.yaml
Normal file
@@ -0,0 +1,13 @@
|
||||
id: safecell-write-inline
|
||||
language: Rust
|
||||
rule:
|
||||
pattern: |
|
||||
{
|
||||
let mut $WRITE = $CELL.write();
|
||||
$$$BODY
|
||||
}
|
||||
fix:
|
||||
template: |
|
||||
$CELL.write_inline(|$WRITE| {
|
||||
$$$BODY
|
||||
});
|
||||
2
server/sgconfig.yml
Normal file
2
server/sgconfig.yml
Normal file
@@ -0,0 +1,2 @@
|
||||
ruleDirs:
|
||||
- ./rules
|
||||
@@ -1,31 +0,0 @@
|
||||
Extension Discovery Cache
|
||||
=========================
|
||||
|
||||
This folder is used by `package:extension_discovery` to cache lists of
|
||||
packages that contains extensions for other packages.
|
||||
|
||||
DO NOT USE THIS FOLDER
|
||||
----------------------
|
||||
|
||||
* Do not read (or rely) the contents of this folder.
|
||||
* Do write to this folder.
|
||||
|
||||
If you're interested in the lists of extensions stored in this folder use the
|
||||
API offered by package `extension_discovery` to get this information.
|
||||
|
||||
If this package doesn't work for your use-case, then don't try to read the
|
||||
contents of this folder. It may change, and will not remain stable.
|
||||
|
||||
Use package `extension_discovery`
|
||||
---------------------------------
|
||||
|
||||
If you want to access information from this folder.
|
||||
|
||||
Feel free to delete this folder
|
||||
-------------------------------
|
||||
|
||||
Files in this folder act as a cache, and the cache is discarded if the files
|
||||
are older than the modification time of `.dart_tool/package_config.json`.
|
||||
|
||||
Hence, it should never be necessary to clear this cache manually, if you find a
|
||||
need to do please file a bug.
|
||||
@@ -1 +0,0 @@
|
||||
{"version":2,"entries":[{"package":"arbiter","rootUri":"../","packageUri":"lib/"}]}
|
||||
@@ -1,172 +0,0 @@
|
||||
{
|
||||
"configVersion": 2,
|
||||
"packages": [
|
||||
{
|
||||
"name": "async",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/async-2.13.0",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.4"
|
||||
},
|
||||
{
|
||||
"name": "boolean_selector",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/boolean_selector-2.1.2",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.1"
|
||||
},
|
||||
{
|
||||
"name": "characters",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/characters-1.4.0",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.4"
|
||||
},
|
||||
{
|
||||
"name": "clock",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/clock-1.1.2",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.4"
|
||||
},
|
||||
{
|
||||
"name": "collection",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/collection-1.19.1",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.4"
|
||||
},
|
||||
{
|
||||
"name": "fake_async",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/fake_async-1.3.3",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.3"
|
||||
},
|
||||
{
|
||||
"name": "flutter",
|
||||
"rootUri": "file:///Users/kaska/.local/share/mise/installs/flutter/3.38.9-stable/packages/flutter",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.8"
|
||||
},
|
||||
{
|
||||
"name": "flutter_lints",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/flutter_lints-6.0.0",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.8"
|
||||
},
|
||||
{
|
||||
"name": "flutter_test",
|
||||
"rootUri": "file:///Users/kaska/.local/share/mise/installs/flutter/3.38.9-stable/packages/flutter_test",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.8"
|
||||
},
|
||||
{
|
||||
"name": "leak_tracker",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/leak_tracker-11.0.2",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.2"
|
||||
},
|
||||
{
|
||||
"name": "leak_tracker_flutter_testing",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/leak_tracker_flutter_testing-3.0.10",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.2"
|
||||
},
|
||||
{
|
||||
"name": "leak_tracker_testing",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/leak_tracker_testing-3.0.2",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.2"
|
||||
},
|
||||
{
|
||||
"name": "lints",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/lints-6.1.0",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.8"
|
||||
},
|
||||
{
|
||||
"name": "matcher",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/matcher-0.12.17",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.4"
|
||||
},
|
||||
{
|
||||
"name": "material_color_utilities",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/material_color_utilities-0.11.1",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "2.17"
|
||||
},
|
||||
{
|
||||
"name": "meta",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/meta-1.17.0",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.5"
|
||||
},
|
||||
{
|
||||
"name": "path",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/path-1.9.1",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.4"
|
||||
},
|
||||
{
|
||||
"name": "sky_engine",
|
||||
"rootUri": "file:///Users/kaska/.local/share/mise/installs/flutter/3.38.9-stable/bin/cache/pkg/sky_engine",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.8"
|
||||
},
|
||||
{
|
||||
"name": "source_span",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/source_span-1.10.2",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.1"
|
||||
},
|
||||
{
|
||||
"name": "stack_trace",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/stack_trace-1.12.1",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.4"
|
||||
},
|
||||
{
|
||||
"name": "stream_channel",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/stream_channel-2.1.4",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.3"
|
||||
},
|
||||
{
|
||||
"name": "string_scanner",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/string_scanner-1.4.1",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.1"
|
||||
},
|
||||
{
|
||||
"name": "term_glyph",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/term_glyph-1.2.2",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.1"
|
||||
},
|
||||
{
|
||||
"name": "test_api",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/test_api-0.7.7",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.5"
|
||||
},
|
||||
{
|
||||
"name": "vector_math",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/vector_math-2.2.0",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.1"
|
||||
},
|
||||
{
|
||||
"name": "vm_service",
|
||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/vm_service-15.0.2",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.5"
|
||||
},
|
||||
{
|
||||
"name": "arbiter",
|
||||
"rootUri": "../",
|
||||
"packageUri": "lib/",
|
||||
"languageVersion": "3.10"
|
||||
}
|
||||
],
|
||||
"generator": "pub",
|
||||
"generatorVersion": "3.10.8",
|
||||
"flutterRoot": "file:///Users/kaska/.local/share/mise/installs/flutter/3.38.9-stable",
|
||||
"flutterVersion": "3.38.9",
|
||||
"pubCache": "file:///Users/kaska/.pub-cache"
|
||||
}
|
||||
@@ -1,224 +0,0 @@
|
||||
{
|
||||
"roots": [
|
||||
"arbiter"
|
||||
],
|
||||
"packages": [
|
||||
{
|
||||
"name": "arbiter",
|
||||
"version": "0.1.0",
|
||||
"dependencies": [
|
||||
"flutter"
|
||||
],
|
||||
"devDependencies": [
|
||||
"flutter_lints",
|
||||
"flutter_test"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "flutter_lints",
|
||||
"version": "6.0.0",
|
||||
"dependencies": [
|
||||
"lints"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "flutter_test",
|
||||
"version": "0.0.0",
|
||||
"dependencies": [
|
||||
"clock",
|
||||
"collection",
|
||||
"fake_async",
|
||||
"flutter",
|
||||
"leak_tracker_flutter_testing",
|
||||
"matcher",
|
||||
"meta",
|
||||
"path",
|
||||
"stack_trace",
|
||||
"stream_channel",
|
||||
"test_api",
|
||||
"vector_math"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "flutter",
|
||||
"version": "0.0.0",
|
||||
"dependencies": [
|
||||
"characters",
|
||||
"collection",
|
||||
"material_color_utilities",
|
||||
"meta",
|
||||
"sky_engine",
|
||||
"vector_math"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "lints",
|
||||
"version": "6.1.0",
|
||||
"dependencies": []
|
||||
},
|
||||
{
|
||||
"name": "stream_channel",
|
||||
"version": "2.1.4",
|
||||
"dependencies": [
|
||||
"async"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "meta",
|
||||
"version": "1.17.0",
|
||||
"dependencies": []
|
||||
},
|
||||
{
|
||||
"name": "collection",
|
||||
"version": "1.19.1",
|
||||
"dependencies": []
|
||||
},
|
||||
{
|
||||
"name": "leak_tracker_flutter_testing",
|
||||
"version": "3.0.10",
|
||||
"dependencies": [
|
||||
"flutter",
|
||||
"leak_tracker",
|
||||
"leak_tracker_testing",
|
||||
"matcher",
|
||||
"meta"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "vector_math",
|
||||
"version": "2.2.0",
|
||||
"dependencies": []
|
||||
},
|
||||
{
|
||||
"name": "stack_trace",
|
||||
"version": "1.12.1",
|
||||
"dependencies": [
|
||||
"path"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "clock",
|
||||
"version": "1.1.2",
|
||||
"dependencies": []
|
||||
},
|
||||
{
|
||||
"name": "fake_async",
|
||||
"version": "1.3.3",
|
||||
"dependencies": [
|
||||
"clock",
|
||||
"collection"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "path",
|
||||
"version": "1.9.1",
|
||||
"dependencies": []
|
||||
},
|
||||
{
|
||||
"name": "matcher",
|
||||
"version": "0.12.17",
|
||||
"dependencies": [
|
||||
"async",
|
||||
"meta",
|
||||
"stack_trace",
|
||||
"term_glyph",
|
||||
"test_api"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "test_api",
|
||||
"version": "0.7.7",
|
||||
"dependencies": [
|
||||
"async",
|
||||
"boolean_selector",
|
||||
"collection",
|
||||
"meta",
|
||||
"source_span",
|
||||
"stack_trace",
|
||||
"stream_channel",
|
||||
"string_scanner",
|
||||
"term_glyph"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "sky_engine",
|
||||
"version": "0.0.0",
|
||||
"dependencies": []
|
||||
},
|
||||
{
|
||||
"name": "material_color_utilities",
|
||||
"version": "0.11.1",
|
||||
"dependencies": [
|
||||
"collection"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "characters",
|
||||
"version": "1.4.0",
|
||||
"dependencies": []
|
||||
},
|
||||
{
|
||||
"name": "async",
|
||||
"version": "2.13.0",
|
||||
"dependencies": [
|
||||
"collection",
|
||||
"meta"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "leak_tracker_testing",
|
||||
"version": "3.0.2",
|
||||
"dependencies": [
|
||||
"leak_tracker",
|
||||
"matcher",
|
||||
"meta"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "leak_tracker",
|
||||
"version": "11.0.2",
|
||||
"dependencies": [
|
||||
"clock",
|
||||
"collection",
|
||||
"meta",
|
||||
"path",
|
||||
"vm_service"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "term_glyph",
|
||||
"version": "1.2.2",
|
||||
"dependencies": []
|
||||
},
|
||||
{
|
||||
"name": "string_scanner",
|
||||
"version": "1.4.1",
|
||||
"dependencies": [
|
||||
"source_span"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "source_span",
|
||||
"version": "1.10.2",
|
||||
"dependencies": [
|
||||
"collection",
|
||||
"path",
|
||||
"term_glyph"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "boolean_selector",
|
||||
"version": "2.1.2",
|
||||
"dependencies": [
|
||||
"source_span",
|
||||
"string_scanner"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "vm_service",
|
||||
"version": "15.0.2",
|
||||
"dependencies": []
|
||||
}
|
||||
],
|
||||
"configVersion": 1
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
3.38.9
|
||||
@@ -1,4 +1,4 @@
|
||||
# app
|
||||
# useragent
|
||||
|
||||
A new Flutter project.
|
||||
|
||||
|
||||
14
useragent/android/.gitignore
vendored
Normal file
14
useragent/android/.gitignore
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
gradle-wrapper.jar
|
||||
/.gradle
|
||||
/captures/
|
||||
/gradlew
|
||||
/gradlew.bat
|
||||
/local.properties
|
||||
GeneratedPluginRegistrant.java
|
||||
.cxx/
|
||||
|
||||
# Remember to never publicly share your keystore.
|
||||
# See https://flutter.dev/to/reference-keystore
|
||||
key.properties
|
||||
**/*.keystore
|
||||
**/*.jks
|
||||
44
useragent/android/app/build.gradle.kts
Normal file
44
useragent/android/app/build.gradle.kts
Normal file
@@ -0,0 +1,44 @@
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("kotlin-android")
|
||||
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
|
||||
id("dev.flutter.flutter-gradle-plugin")
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.example.useragent"
|
||||
compileSdk = flutter.compileSdkVersion
|
||||
ndkVersion = flutter.ndkVersion
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
kotlinOptions {
|
||||
jvmTarget = JavaVersion.VERSION_17.toString()
|
||||
}
|
||||
|
||||
defaultConfig {
|
||||
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
|
||||
applicationId = "com.example.useragent"
|
||||
// You can update the following values to match your application needs.
|
||||
// For more information, see: https://flutter.dev/to/review-gradle-config.
|
||||
minSdk = flutter.minSdkVersion
|
||||
targetSdk = flutter.targetSdkVersion
|
||||
versionCode = flutter.versionCode
|
||||
versionName = flutter.versionName
|
||||
}
|
||||
|
||||
buildTypes {
|
||||
release {
|
||||
// TODO: Add your own signing config for the release build.
|
||||
// Signing with the debug keys for now, so `flutter run --release` works.
|
||||
signingConfig = signingConfigs.getByName("debug")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
flutter {
|
||||
source = "../.."
|
||||
}
|
||||
7
useragent/android/app/src/debug/AndroidManifest.xml
Normal file
7
useragent/android/app/src/debug/AndroidManifest.xml
Normal file
@@ -0,0 +1,7 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<!-- The INTERNET permission is required for development. Specifically,
|
||||
the Flutter tool needs it to communicate with the running application
|
||||
to allow setting breakpoints, to provide hot reload, etc.
|
||||
-->
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
</manifest>
|
||||
45
useragent/android/app/src/main/AndroidManifest.xml
Normal file
45
useragent/android/app/src/main/AndroidManifest.xml
Normal file
@@ -0,0 +1,45 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<application
|
||||
android:label="useragent"
|
||||
android:name="${applicationName}"
|
||||
android:icon="@mipmap/ic_launcher">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTop"
|
||||
android:taskAffinity=""
|
||||
android:theme="@style/LaunchTheme"
|
||||
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
|
||||
android:hardwareAccelerated="true"
|
||||
android:windowSoftInputMode="adjustResize">
|
||||
<!-- Specifies an Android theme to apply to this Activity as soon as
|
||||
the Android process has started. This theme is visible to the user
|
||||
while the Flutter UI initializes. After that, this theme continues
|
||||
to determine the Window background behind the Flutter UI. -->
|
||||
<meta-data
|
||||
android:name="io.flutter.embedding.android.NormalTheme"
|
||||
android:resource="@style/NormalTheme"
|
||||
/>
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN"/>
|
||||
<category android:name="android.intent.category.LAUNCHER"/>
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<!-- Don't delete the meta-data below.
|
||||
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
|
||||
<meta-data
|
||||
android:name="flutterEmbedding"
|
||||
android:value="2" />
|
||||
</application>
|
||||
<!-- Required to query activities that can process text, see:
|
||||
https://developer.android.com/training/package-visibility and
|
||||
https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.
|
||||
|
||||
In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
|
||||
<queries>
|
||||
<intent>
|
||||
<action android:name="android.intent.action.PROCESS_TEXT"/>
|
||||
<data android:mimeType="text/plain"/>
|
||||
</intent>
|
||||
</queries>
|
||||
</manifest>
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.example.useragent
|
||||
|
||||
import io.flutter.embedding.android.FlutterActivity
|
||||
|
||||
class MainActivity : FlutterActivity()
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Modify this file to customize your launch splash screen -->
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item android:drawable="?android:colorBackground" />
|
||||
|
||||
<!-- You can insert your own image assets here -->
|
||||
<!-- <item>
|
||||
<bitmap
|
||||
android:gravity="center"
|
||||
android:src="@mipmap/launch_image" />
|
||||
</item> -->
|
||||
</layer-list>
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- Modify this file to customize your launch splash screen -->
|
||||
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<item android:drawable="@android:color/white" />
|
||||
|
||||
<!-- You can insert your own image assets here -->
|
||||
<!-- <item>
|
||||
<bitmap
|
||||
android:gravity="center"
|
||||
android:src="@mipmap/launch_image" />
|
||||
</item> -->
|
||||
</layer-list>
|
||||
BIN
useragent/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
Normal file
BIN
useragent/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 544 B |
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user