Compare commits
5 Commits
42760bbd79
...
key-altern
| Author | SHA1 | Date | |
|---|---|---|---|
| d65e9319d9 | |||
| dfc852e815 | |||
| 5b711acb15 | |||
| 19f19a56e5 | |||
| f108e64d13 |
2
.gitignore
vendored
@@ -1,3 +1 @@
|
|||||||
target/
|
target/
|
||||||
scripts/__pycache__/
|
|
||||||
.DS_Store
|
|
||||||
2
.vscode/settings.json
vendored
@@ -1,2 +0,0 @@
|
|||||||
{
|
|
||||||
}
|
|
||||||
@@ -8,7 +8,7 @@ when:
|
|||||||
include: ['.woodpecker/server-*.yaml', 'server/**']
|
include: ['.woodpecker/server-*.yaml', 'server/**']
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: audit
|
- name: test
|
||||||
image: jdxcode/mise:latest
|
image: jdxcode/mise:latest
|
||||||
directory: server
|
directory: server
|
||||||
environment:
|
environment:
|
||||||
|
|||||||
@@ -1,25 +0,0 @@
|
|||||||
when:
|
|
||||||
- event: pull_request
|
|
||||||
path:
|
|
||||||
include: ['.woodpecker/server-*.yaml', 'server/**']
|
|
||||||
- event: push
|
|
||||||
branch: main
|
|
||||||
path:
|
|
||||||
include: ['.woodpecker/server-*.yaml', 'server/**']
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: lint
|
|
||||||
image: jdxcode/mise:latest
|
|
||||||
directory: server
|
|
||||||
environment:
|
|
||||||
CARGO_TERM_COLOR: always
|
|
||||||
CARGO_TARGET_DIR: /usr/local/cargo/target
|
|
||||||
CARGO_HOME: /usr/local/cargo/registry
|
|
||||||
volumes:
|
|
||||||
- cargo-target:/usr/local/cargo/target
|
|
||||||
- cargo-registry:/usr/local/cargo/registry
|
|
||||||
commands:
|
|
||||||
- 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
|
|
||||||
@@ -8,7 +8,7 @@ when:
|
|||||||
include: ['.woodpecker/server-*.yaml', 'server/**']
|
include: ['.woodpecker/server-*.yaml', 'server/**']
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: vet
|
- name: test
|
||||||
image: jdxcode/mise:latest
|
image: jdxcode/mise:latest
|
||||||
directory: server
|
directory: server
|
||||||
environment:
|
environment:
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
Arbiter is a permissioned signing service for cryptocurrency wallets. It runs as a background service on the user's machine with an optional client application for vault management.
|
Arbiter is a permissioned signing service for cryptocurrency wallets. It runs as a background service on the user's machine with an optional client application for vault management.
|
||||||
|
|
||||||
**Core principle:** The vault NEVER exposes key material. It only produces signatures when a request satisfies the configured policies.
|
**Core principle:** The vault NEVER exposes key material. It only produces signatures when a request satisfies the configured policies.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 1. Peer Types
|
## 1. Peer Types
|
||||||
|
|||||||
@@ -4,52 +4,6 @@ This document covers concrete technology choices and dependencies. For the archi
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Client Connection Flow
|
|
||||||
|
|
||||||
### 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.
|
|
||||||
|
|
||||||
```mermaid
|
|
||||||
flowchart TD
|
|
||||||
A([Client connects]) --> B[Receive AuthChallengeRequest]
|
|
||||||
B --> C{pubkey in DB?}
|
|
||||||
|
|
||||||
C -- yes --> D[Read nonce\nIncrement nonce in DB]
|
|
||||||
D --> G
|
|
||||||
|
|
||||||
C -- no --> E[Ask all UserAgents:\nClientConnectionRequest]
|
|
||||||
E --> F{First response}
|
|
||||||
F -- denied --> Z([Reject connection])
|
|
||||||
F -- approved --> F2[Cancel remaining\nUserAgent requests]
|
|
||||||
F2 --> F3[INSERT client\nnonce = 1]
|
|
||||||
F3 --> G[Send AuthChallenge\nwith nonce]
|
|
||||||
|
|
||||||
G --> H[Receive AuthChallengeSolution]
|
|
||||||
H --> I{Signature valid?}
|
|
||||||
I -- no --> Z
|
|
||||||
I -- yes --> J([Session started])
|
|
||||||
```
|
|
||||||
|
|
||||||
### Known Issue: Concurrent Registration Race (TOCTOU)
|
|
||||||
|
|
||||||
Two connections presenting the same previously-unknown public key can race through the approval flow simultaneously:
|
|
||||||
|
|
||||||
1. Both check the DB → neither is registered.
|
|
||||||
2. Both request approval from user agents → both receive approval.
|
|
||||||
3. Both `INSERT` the client record → the second insert silently overwrites the first, resetting the nonce.
|
|
||||||
|
|
||||||
This means the first connection's nonce is invalidated by the second, causing its challenge verification to fail. A fix requires either serialising new-client registration (e.g. an in-memory lock keyed on pubkey) or replacing the separate check + insert with an `INSERT OR IGNORE` / upsert guarded by a unique constraint on `public_key`.
|
|
||||||
|
|
||||||
### Nonce Semantics
|
|
||||||
|
|
||||||
The `program_client.nonce` column stores the **next usable nonce** — i.e. it is always one ahead of the nonce last issued in a challenge.
|
|
||||||
|
|
||||||
- **New client:** inserted with `nonce = 1`; the first challenge is issued with `nonce = 0`.
|
|
||||||
- **Existing client:** the current DB value is read and used as the challenge nonce, then immediately incremented within the same exclusive transaction, preventing replay.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Cryptography
|
## Cryptography
|
||||||
|
|
||||||
### Authentication
|
### Authentication
|
||||||
@@ -73,82 +27,6 @@ The `program_client.nonce` column stores the **next usable nonce** — i.e. it i
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## EVM Policy Engine
|
|
||||||
|
|
||||||
### Overview
|
|
||||||
|
|
||||||
The EVM engine classifies incoming transactions, enforces grant constraints, and records executions. It is the sole path through which a wallet key is used for signing.
|
|
||||||
|
|
||||||
The central abstraction is the `Policy` trait. Each implementation handles one semantic transaction category and owns its own database tables for grant storage and transaction logging.
|
|
||||||
|
|
||||||
### Transaction Evaluation Flow
|
|
||||||
|
|
||||||
`Engine::evaluate_transaction` runs the following steps in order:
|
|
||||||
|
|
||||||
1. **Classify** — Each registered policy's `analyze(context)` inspects the transaction fields (`chain`, `to`, `value`, `calldata`). The first one returning `Some(meaning)` wins. If none match, the transaction is rejected as `UnsupportedTransactionType`.
|
|
||||||
2. **Find grant** — `Policy::try_find_grant` queries for a non-revoked grant covering this wallet, client, chain, and target address.
|
|
||||||
3. **Check shared constraints** — `check_shared_constraints` runs in the engine before any policy-specific logic. It enforces the validity window, gas fee caps, and transaction count rate limit (see below).
|
|
||||||
4. **Evaluate** — `Policy::evaluate` checks the decoded meaning against the grant's policy-specific constraints and returns any violations.
|
|
||||||
5. **Record** — If `RunKind::Execution` and there are no violations, the engine writes to `evm_transaction_log` and calls `Policy::record_transaction` for any policy-specific logging (e.g., token transfer volume).
|
|
||||||
|
|
||||||
### Policy Trait
|
|
||||||
|
|
||||||
| Method | Purpose |
|
|
||||||
|---|---|
|
|
||||||
| `analyze` | Pure — classifies a transaction into a typed `Meaning`, or `None` if this policy doesn't apply |
|
|
||||||
| `evaluate` | Checks the `Meaning` against a `Grant`; returns a list of `EvalViolation`s |
|
|
||||||
| `create_grant` | Inserts policy-specific rows; returns the specific grant ID |
|
|
||||||
| `try_find_grant` | Finds a matching non-revoked grant for the given `EvalContext` |
|
|
||||||
| `find_all_grants` | Returns all non-revoked grants (used for listing) |
|
|
||||||
| `record_transaction` | Persists policy-specific data after execution |
|
|
||||||
|
|
||||||
`analyze` and `evaluate` are intentionally separate: classification is pure and cheap, while evaluation may involve DB queries (e.g., fetching past transfer volume).
|
|
||||||
|
|
||||||
### Registered Policies
|
|
||||||
|
|
||||||
**EtherTransfer** — plain ETH transfers (empty calldata)
|
|
||||||
|
|
||||||
- Grant requires: allowlist of recipient addresses + one volumetric rate limit (max ETH over a time window)
|
|
||||||
- Violations: recipient not in allowlist, cumulative ETH volume exceeded
|
|
||||||
|
|
||||||
**TokenTransfer** — ERC-20 `transfer(address,uint256)` calls
|
|
||||||
|
|
||||||
- Recognised by ABI-decoding the `transfer(address,uint256)` selector against a static registry of known token contracts (`arbiter_tokens_registry`)
|
|
||||||
- Grant requires: token contract address, optional recipient restriction, zero or more volumetric rate limits
|
|
||||||
- Violations: recipient mismatch, any volumetric limit exceeded
|
|
||||||
|
|
||||||
### Grant Model
|
|
||||||
|
|
||||||
Every grant has two layers:
|
|
||||||
|
|
||||||
- **Shared (`evm_basic_grant`)** — wallet, chain, validity period, gas fee caps, transaction count rate limit. One row per grant regardless of type.
|
|
||||||
- **Specific** — policy-owned tables (`evm_ether_transfer_grant`, `evm_token_transfer_grant`, etc.) holding type-specific configuration.
|
|
||||||
|
|
||||||
`find_all_grants` uses a `#[diesel::auto_type]` base join between the specific and shared tables, then batch-loads related rows (targets, volume limits) in two additional queries to avoid N+1.
|
|
||||||
|
|
||||||
The engine exposes `list_all_grants` which collects across all policy types into `Vec<Grant<SpecificGrant>>` via a blanket `From<Grant<S>> for Grant<SpecificGrant>` conversion.
|
|
||||||
|
|
||||||
### Shared Constraints (enforced by the engine)
|
|
||||||
|
|
||||||
These are checked centrally in `check_shared_constraints` before policy evaluation:
|
|
||||||
|
|
||||||
| Constraint | Fields | Behaviour |
|
|
||||||
|---|---|---|
|
|
||||||
| Validity window | `valid_from`, `valid_until` | Emits `InvalidTime` if current time is outside the range |
|
|
||||||
| Gas fee cap | `max_gas_fee_per_gas`, `max_priority_fee_per_gas` | Emits `GasLimitExceeded` if either cap is breached |
|
|
||||||
| Tx count rate limit | `rate_limit` (`count` + `window`) | Counts rows in `evm_transaction_log` within the window; emits `RateLimitExceeded` if at or above the limit |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### Known Limitations
|
|
||||||
|
|
||||||
- **Only EIP-1559 transactions are supported.** Legacy and EIP-2930 types are rejected outright.
|
|
||||||
- **No opaque-calldata (unknown contract) grant type.** The architecture describes a category for unrecognised contracts, but no policy implements it yet. Any transaction that is not a plain ETH transfer or a known ERC-20 transfer is unconditionally rejected.
|
|
||||||
- **Token registry is static.** Tokens are recognised only if they appear in the hard-coded `arbiter_tokens_registry` crate. There is no mechanism to register additional contracts at runtime.
|
|
||||||
- **Nonce management is not implemented.** The architecture lists nonce deduplication as a core responsibility, but no nonce tracking or enforcement exists yet.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Memory Protection
|
## Memory Protection
|
||||||
|
|
||||||
The unsealed root key must be held in a hardened memory cell resistant to dumps, page swaps, and hibernation.
|
The unsealed root key must be held in a hardened memory cell resistant to dumps, page swaps, and hibernation.
|
||||||
|
|||||||
190
LICENSE
@@ -1,190 +0,0 @@
|
|||||||
Apache License
|
|
||||||
Version 2.0, January 2004
|
|
||||||
http://www.apache.org/licenses/
|
|
||||||
|
|
||||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
||||||
|
|
||||||
1. Definitions.
|
|
||||||
|
|
||||||
"License" shall mean the terms and conditions for use, reproduction,
|
|
||||||
and distribution as defined by Sections 1 through 9 of this document.
|
|
||||||
|
|
||||||
"Licensor" shall mean the copyright owner or entity authorized by
|
|
||||||
the copyright owner that is granting the License.
|
|
||||||
|
|
||||||
"Legal Entity" shall mean the union of the acting entity and all
|
|
||||||
other entities that control, are controlled by, or are under common
|
|
||||||
control with that entity. For the purposes of this definition,
|
|
||||||
"control" means (i) the power, direct or indirect, to cause the
|
|
||||||
direction or management of such entity, whether by contract or
|
|
||||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
||||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
||||||
|
|
||||||
"You" (or "Your") shall mean an individual or Legal Entity
|
|
||||||
exercising permissions granted by this License.
|
|
||||||
|
|
||||||
"Source" form shall mean the preferred form for making modifications,
|
|
||||||
including but not limited to software source code, documentation
|
|
||||||
source, and configuration files.
|
|
||||||
|
|
||||||
"Object" form shall mean any form resulting from mechanical
|
|
||||||
transformation or translation of a Source form, including but
|
|
||||||
not limited to compiled object code, generated documentation,
|
|
||||||
and conversions to other media types.
|
|
||||||
|
|
||||||
"Work" shall mean the work of authorship, whether in Source or
|
|
||||||
Object form, made available under the License, as indicated by a
|
|
||||||
copyright notice that is included in or attached to the work
|
|
||||||
(an example is provided in the Appendix below).
|
|
||||||
|
|
||||||
"Derivative Works" shall mean any work, whether in Source or Object
|
|
||||||
form, that is based on (or derived from) the Work and for which the
|
|
||||||
editorial revisions, annotations, elaborations, or other modifications
|
|
||||||
represent, as a whole, an original work of authorship. For the purposes
|
|
||||||
of this License, Derivative Works shall not include works that remain
|
|
||||||
separable from, or merely link (or bind by name) to the interfaces of,
|
|
||||||
the Work and Derivative Works thereof.
|
|
||||||
|
|
||||||
"Contribution" shall mean any work of authorship, including
|
|
||||||
the original version of the Work and any modifications or additions
|
|
||||||
to that Work or Derivative Works thereof, that is intentionally
|
|
||||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
||||||
or by an individual or Legal Entity authorized to submit on behalf of
|
|
||||||
the copyright owner. For the purposes of this definition, "submitted"
|
|
||||||
means any form of electronic, verbal, or written communication sent
|
|
||||||
to the Licensor or its representatives, including but not limited to
|
|
||||||
communication on electronic mailing lists, source code control systems,
|
|
||||||
and issue tracking systems that are managed by, or on behalf of, the
|
|
||||||
Licensor for the purpose of discussing and improving the Work, but
|
|
||||||
excluding communication that is conspicuously marked or otherwise
|
|
||||||
designated in writing by the copyright owner as "Not a Contribution."
|
|
||||||
|
|
||||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
||||||
on behalf of whom a Contribution has been received by Licensor and
|
|
||||||
subsequently incorporated within the Work.
|
|
||||||
|
|
||||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
|
||||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
||||||
copyright license to reproduce, prepare Derivative Works of,
|
|
||||||
publicly display, publicly perform, sublicense, and distribute the
|
|
||||||
Work and such Derivative Works in Source or Object form.
|
|
||||||
|
|
||||||
3. Grant of Patent License. Subject to the terms and conditions of
|
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
|
||||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
||||||
(except as stated in this section) patent license to make, have made,
|
|
||||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
||||||
where such license applies only to those patent claims licensable
|
|
||||||
by such Contributor that are necessarily infringed by their
|
|
||||||
Contribution(s) alone or by combination of their Contribution(s)
|
|
||||||
with the Work to which such Contribution(s) was submitted. If You
|
|
||||||
institute patent litigation against any entity (including a
|
|
||||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
||||||
or a Contribution incorporated within the Work constitutes direct
|
|
||||||
or contributory patent infringement, then any patent licenses
|
|
||||||
granted to You under this License for that Work shall terminate
|
|
||||||
as of the date such litigation is filed.
|
|
||||||
|
|
||||||
4. Redistribution. You may reproduce and distribute copies of the
|
|
||||||
Work or Derivative Works thereof in any medium, with or without
|
|
||||||
modifications, and in Source or Object form, provided that You
|
|
||||||
meet the following conditions:
|
|
||||||
|
|
||||||
(a) You must give any other recipients of the Work or
|
|
||||||
Derivative Works a copy of this License; and
|
|
||||||
|
|
||||||
(b) You must cause any modified files to carry prominent notices
|
|
||||||
stating that You changed the files; and
|
|
||||||
|
|
||||||
(c) You must retain, in the Source form of any Derivative Works
|
|
||||||
that You distribute, all copyright, patent, trademark, and
|
|
||||||
attribution notices from the Source form of the Work,
|
|
||||||
excluding those notices that do not pertain to any part of
|
|
||||||
the Derivative Works; and
|
|
||||||
|
|
||||||
(d) If the Work includes a "NOTICE" text file as part of its
|
|
||||||
distribution, then any Derivative Works that You distribute must
|
|
||||||
include a readable copy of the attribution notices contained
|
|
||||||
within such NOTICE file, excluding those notices that do not
|
|
||||||
pertain to any part of the Derivative Works, in at least one
|
|
||||||
of the following places: within a NOTICE text file distributed
|
|
||||||
as part of the Derivative Works; within the Source form or
|
|
||||||
documentation, if provided along with the Derivative Works; or,
|
|
||||||
within a display generated by the Derivative Works, if and
|
|
||||||
wherever such third-party notices normally appear. The contents
|
|
||||||
of the NOTICE file are for informational purposes only and
|
|
||||||
do not modify the License. You may add Your own attribution
|
|
||||||
notices within Derivative Works that You distribute, alongside
|
|
||||||
or as an addendum to the NOTICE text from the Work, provided
|
|
||||||
that such additional attribution notices cannot be construed
|
|
||||||
as modifying the License.
|
|
||||||
|
|
||||||
You may add Your own copyright statement to Your modifications and
|
|
||||||
may provide additional or different license terms and conditions
|
|
||||||
for use, reproduction, or distribution of Your modifications, or
|
|
||||||
for any such Derivative Works as a whole, provided Your use,
|
|
||||||
reproduction, and distribution of the Work otherwise complies with
|
|
||||||
the conditions stated in this License.
|
|
||||||
|
|
||||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
||||||
any Contribution intentionally submitted for inclusion in the Work
|
|
||||||
by You to the Licensor shall be under the terms and conditions of
|
|
||||||
this License, without any additional terms or conditions.
|
|
||||||
Notwithstanding the above, nothing herein shall supersede or modify
|
|
||||||
the terms of any separate license agreement you may have executed
|
|
||||||
with Licensor regarding such Contributions.
|
|
||||||
|
|
||||||
6. Trademarks. This License does not grant permission to use the trade
|
|
||||||
names, trademarks, service marks, or product names of the Licensor,
|
|
||||||
except as required for reasonable and customary use in describing the
|
|
||||||
origin of the Work and reproducing the content of the NOTICE file.
|
|
||||||
|
|
||||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
||||||
agreed to in writing, Licensor provides the Work (and each
|
|
||||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
||||||
implied, including, without limitation, any warranties or conditions
|
|
||||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
||||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
||||||
appropriateness of using or redistributing the Work and assume any
|
|
||||||
risks associated with Your exercise of permissions under this License.
|
|
||||||
|
|
||||||
8. Limitation of Liability. In no event and under no legal theory,
|
|
||||||
whether in tort (including negligence), contract, or otherwise,
|
|
||||||
unless required by applicable law (such as deliberate and grossly
|
|
||||||
negligent acts) or agreed to in writing, shall any Contributor be
|
|
||||||
liable to You for damages, including any direct, indirect, special,
|
|
||||||
incidental, or consequential damages of any character arising as a
|
|
||||||
result of this License or out of the use or inability to use the
|
|
||||||
Work (including but not limited to damages for loss of goodwill,
|
|
||||||
work stoppage, computer failure or malfunction, or any and all
|
|
||||||
other commercial damages or losses), even if such Contributor
|
|
||||||
has been advised of the possibility of such damages.
|
|
||||||
|
|
||||||
9. Accepting Warranty or Additional Liability. While redistributing
|
|
||||||
the Work or Derivative Works thereof, You may choose to offer,
|
|
||||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
||||||
or other liability obligations and/or rights consistent with this
|
|
||||||
License. However, in accepting such obligations, You may act only
|
|
||||||
on Your own behalf and on Your sole responsibility, not on behalf
|
|
||||||
of any other Contributor, and only if You agree to indemnify,
|
|
||||||
defend, and hold each Contributor harmless for any liability
|
|
||||||
incurred by, or claims asserted against, such Contributor by reason
|
|
||||||
of your accepting any such warranty or additional liability.
|
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
|
||||||
|
|
||||||
Copyright 2026 MarketTakers
|
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
you may not use this file except in compliance with the License.
|
|
||||||
You may obtain a copy of the License at
|
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
See the License for the specific language governing permissions and
|
|
||||||
limitations under the License.
|
|
||||||
13
README.md
@@ -1,13 +0,0 @@
|
|||||||
# Arbiter
|
|
||||||
> Policy-first multi-client wallet daemon, allowing permissioned transactions across blockchains
|
|
||||||
|
|
||||||
## Security warning
|
|
||||||
Arbiter can't meaningfully protect against host compromise. Potential attack flow:
|
|
||||||
- Attacker steals TLS keys from database
|
|
||||||
- Pretends to be server; just accepts user agent challenge solutions
|
|
||||||
- Pretend to be in sealed state and performing DH with client
|
|
||||||
- Steals user password and derives seal key
|
|
||||||
|
|
||||||
While this attack is highly targetive, it's still possible.
|
|
||||||
|
|
||||||
> This software is experimental. Do not use with funds you cannot afford to lose.
|
|
||||||
@@ -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":"app","rootUri":"../","packageUri":"lib/"}]}
|
|
||||||
@@ -1,178 +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": "cupertino_icons",
|
|
||||||
"rootUri": "file:///Users/kaska/.pub-cache/hosted/pub.dev/cupertino_icons-1.0.8",
|
|
||||||
"packageUri": "lib/",
|
|
||||||
"languageVersion": "3.1"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"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": "app",
|
|
||||||
"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,230 +0,0 @@
|
|||||||
{
|
|
||||||
"roots": [
|
|
||||||
"app"
|
|
||||||
],
|
|
||||||
"packages": [
|
|
||||||
{
|
|
||||||
"name": "app",
|
|
||||||
"version": "1.0.0+1",
|
|
||||||
"dependencies": [
|
|
||||||
"cupertino_icons",
|
|
||||||
"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": "cupertino_icons",
|
|
||||||
"version": "1.0.8",
|
|
||||||
"dependencies": []
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"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
|
|
||||||
0
useragent/.gitignore → app/.gitignore
vendored
@@ -1,11 +0,0 @@
|
|||||||
// This is a generated file; do not edit or check into version control.
|
|
||||||
FLUTTER_ROOT=/Users/kaska/.local/share/mise/installs/flutter/3.38.9-stable
|
|
||||||
FLUTTER_APPLICATION_PATH=/Users/kaska/Documents/Projects/Major/arbiter/app
|
|
||||||
COCOAPODS_PARALLEL_CODE_SIGN=true
|
|
||||||
FLUTTER_BUILD_DIR=build
|
|
||||||
FLUTTER_BUILD_NAME=1.0.0
|
|
||||||
FLUTTER_BUILD_NUMBER=1
|
|
||||||
DART_OBFUSCATION=false
|
|
||||||
TRACK_WIDGET_CREATION=true
|
|
||||||
TREE_SHAKE_ICONS=false
|
|
||||||
PACKAGE_CONFIG=.dart_tool/package_config.json
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
# This is a generated file; do not edit or check into version control.
|
|
||||||
export "FLUTTER_ROOT=/Users/kaska/.local/share/mise/installs/flutter/3.38.9-stable"
|
|
||||||
export "FLUTTER_APPLICATION_PATH=/Users/kaska/Documents/Projects/Major/arbiter/app"
|
|
||||||
export "COCOAPODS_PARALLEL_CODE_SIGN=true"
|
|
||||||
export "FLUTTER_BUILD_DIR=build"
|
|
||||||
export "FLUTTER_BUILD_NAME=1.0.0"
|
|
||||||
export "FLUTTER_BUILD_NUMBER=1"
|
|
||||||
export "DART_OBFUSCATION=false"
|
|
||||||
export "TRACK_WIDGET_CREATION=true"
|
|
||||||
export "TREE_SHAKE_ICONS=false"
|
|
||||||
export "PACKAGE_CONFIG=.dart_tool/package_config.json"
|
|
||||||
|
Before Width: | Height: | Size: 101 KiB After Width: | Height: | Size: 101 KiB |
|
Before Width: | Height: | Size: 5.5 KiB After Width: | Height: | Size: 5.5 KiB |
|
Before Width: | Height: | Size: 520 B After Width: | Height: | Size: 520 B |
|
Before Width: | Height: | Size: 14 KiB After Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 1.0 KiB After Width: | Height: | Size: 1.0 KiB |
|
Before Width: | Height: | Size: 36 KiB After Width: | Height: | Size: 36 KiB |
|
Before Width: | Height: | Size: 2.2 KiB After Width: | Height: | Size: 2.2 KiB |
@@ -41,6 +41,14 @@ packages:
|
|||||||
url: "https://pub.dev"
|
url: "https://pub.dev"
|
||||||
source: hosted
|
source: hosted
|
||||||
version: "1.19.1"
|
version: "1.19.1"
|
||||||
|
cupertino_icons:
|
||||||
|
dependency: "direct main"
|
||||||
|
description:
|
||||||
|
name: cupertino_icons
|
||||||
|
sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6
|
||||||
|
url: "https://pub.dev"
|
||||||
|
source: hosted
|
||||||
|
version: "1.0.8"
|
||||||
fake_async:
|
fake_async:
|
||||||
dependency: transitive
|
dependency: transitive
|
||||||
description:
|
description:
|
||||||
89
app/pubspec.yaml
Normal file
@@ -0,0 +1,89 @@
|
|||||||
|
name: app
|
||||||
|
description: "A new Flutter project."
|
||||||
|
# The following line prevents the package from being accidentally published to
|
||||||
|
# pub.dev using `flutter pub publish`. This is preferred for private packages.
|
||||||
|
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
|
||||||
|
|
||||||
|
# The following defines the version and build number for your application.
|
||||||
|
# A version number is three numbers separated by dots, like 1.2.43
|
||||||
|
# followed by an optional build number separated by a +.
|
||||||
|
# Both the version and the builder number may be overridden in flutter
|
||||||
|
# build by specifying --build-name and --build-number, respectively.
|
||||||
|
# In Android, build-name is used as versionName while build-number used as versionCode.
|
||||||
|
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
|
||||||
|
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
|
||||||
|
# Read more about iOS versioning at
|
||||||
|
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
|
||||||
|
# In Windows, build-name is used as the major, minor, and patch parts
|
||||||
|
# of the product and file versions while build-number is used as the build suffix.
|
||||||
|
version: 1.0.0+1
|
||||||
|
|
||||||
|
environment:
|
||||||
|
sdk: ^3.10.8
|
||||||
|
|
||||||
|
# Dependencies specify other packages that your package needs in order to work.
|
||||||
|
# To automatically upgrade your package dependencies to the latest versions
|
||||||
|
# consider running `flutter pub upgrade --major-versions`. Alternatively,
|
||||||
|
# dependencies can be manually updated by changing the version numbers below to
|
||||||
|
# the latest version available on pub.dev. To see which dependencies have newer
|
||||||
|
# versions available, run `flutter pub outdated`.
|
||||||
|
dependencies:
|
||||||
|
flutter:
|
||||||
|
sdk: flutter
|
||||||
|
|
||||||
|
# The following adds the Cupertino Icons font to your application.
|
||||||
|
# Use with the CupertinoIcons class for iOS style icons.
|
||||||
|
cupertino_icons: ^1.0.8
|
||||||
|
|
||||||
|
dev_dependencies:
|
||||||
|
flutter_test:
|
||||||
|
sdk: flutter
|
||||||
|
|
||||||
|
# The "flutter_lints" package below contains a set of recommended lints to
|
||||||
|
# encourage good coding practices. The lint set provided by the package is
|
||||||
|
# activated in the `analysis_options.yaml` file located at the root of your
|
||||||
|
# package. See that file for information about deactivating specific lint
|
||||||
|
# rules and activating additional ones.
|
||||||
|
flutter_lints: ^6.0.0
|
||||||
|
|
||||||
|
# For information on the generic Dart part of this file, see the
|
||||||
|
# following page: https://dart.dev/tools/pub/pubspec
|
||||||
|
|
||||||
|
# The following section is specific to Flutter packages.
|
||||||
|
flutter:
|
||||||
|
|
||||||
|
# The following line ensures that the Material Icons font is
|
||||||
|
# included with your application, so that you can use the icons in
|
||||||
|
# the material Icons class.
|
||||||
|
uses-material-design: true
|
||||||
|
|
||||||
|
# To add assets to your application, add an assets section, like this:
|
||||||
|
# assets:
|
||||||
|
# - images/a_dot_burr.jpeg
|
||||||
|
# - images/a_dot_ham.jpeg
|
||||||
|
|
||||||
|
# An image asset can refer to one or more resolution-specific "variants", see
|
||||||
|
# https://flutter.dev/to/resolution-aware-images
|
||||||
|
|
||||||
|
# For details regarding adding assets from package dependencies, see
|
||||||
|
# https://flutter.dev/to/asset-from-package
|
||||||
|
|
||||||
|
# To add custom fonts to your application, add a fonts section here,
|
||||||
|
# in this "flutter" section. Each entry in this list should have a
|
||||||
|
# "family" key with the font family name, and a "fonts" key with a
|
||||||
|
# list giving the asset and other descriptors for the font. For
|
||||||
|
# example:
|
||||||
|
# fonts:
|
||||||
|
# - family: Schyler
|
||||||
|
# fonts:
|
||||||
|
# - asset: fonts/Schyler-Regular.ttf
|
||||||
|
# - asset: fonts/Schyler-Italic.ttf
|
||||||
|
# style: italic
|
||||||
|
# - family: Trajan Pro
|
||||||
|
# fonts:
|
||||||
|
# - asset: fonts/TrajanPro.ttf
|
||||||
|
# - asset: fonts/TrajanPro_Bold.ttf
|
||||||
|
# weight: 700
|
||||||
|
#
|
||||||
|
# For details regarding fonts from package dependencies,
|
||||||
|
# see https://flutter.dev/to/font-from-package
|
||||||
|
Before Width: | Height: | Size: 33 KiB After Width: | Height: | Size: 33 KiB |
13
mise.lock
@@ -10,10 +10,6 @@ backend = "cargo:cargo-features"
|
|||||||
version = "0.11.1"
|
version = "0.11.1"
|
||||||
backend = "cargo:cargo-features-manager"
|
backend = "cargo:cargo-features-manager"
|
||||||
|
|
||||||
[[tools."cargo:cargo-insta"]]
|
|
||||||
version = "1.46.3"
|
|
||||||
backend = "cargo:cargo-insta"
|
|
||||||
|
|
||||||
[[tools."cargo:cargo-nextest"]]
|
[[tools."cargo:cargo-nextest"]]
|
||||||
version = "0.9.126"
|
version = "0.9.126"
|
||||||
backend = "cargo:cargo-nextest"
|
backend = "cargo:cargo-nextest"
|
||||||
@@ -55,15 +51,6 @@ backend = "aqua:protocolbuffers/protobuf/protoc"
|
|||||||
"platforms.macos-x64" = { checksum = "sha256:312f04713946921cc0187ef34df80241ddca1bab6f564c636885fd2cc90d3f88", url = "https://github.com/protocolbuffers/protobuf/releases/download/v29.6/protoc-29.6-osx-x86_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"}
|
"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.rust]]
|
[[tools.rust]]
|
||||||
version = "1.93.0"
|
version = "1.93.0"
|
||||||
backend = "core:rust"
|
backend = "core:rust"
|
||||||
|
|||||||
@@ -2,11 +2,10 @@
|
|||||||
"cargo:diesel_cli" = { version = "2.3.6", features = "sqlite,sqlite-bundled", default-features = false }
|
"cargo:diesel_cli" = { version = "2.3.6", features = "sqlite,sqlite-bundled", default-features = false }
|
||||||
"cargo:cargo-audit" = "0.22.1"
|
"cargo:cargo-audit" = "0.22.1"
|
||||||
"cargo:cargo-vet" = "0.10.2"
|
"cargo:cargo-vet" = "0.10.2"
|
||||||
|
|
||||||
flutter = "3.38.9-stable"
|
flutter = "3.38.9-stable"
|
||||||
protoc = "29.6"
|
protoc = "29.6"
|
||||||
"rust" = {version = "1.93.0", components = "clippy"}
|
rust = "1.93.1"
|
||||||
"cargo:cargo-features-manager" = "0.11.1"
|
"cargo:cargo-features-manager" = "0.11.1"
|
||||||
"cargo:cargo-nextest" = "0.9.126"
|
"cargo:cargo-nextest" = "0.9.126"
|
||||||
"cargo:cargo-shear" = "latest"
|
"cargo:cargo-shear" = "latest"
|
||||||
"cargo:cargo-insta" = "1.46.3"
|
|
||||||
python = "3.14.3"
|
|
||||||
|
|||||||
@@ -2,15 +2,113 @@ syntax = "proto3";
|
|||||||
|
|
||||||
package arbiter;
|
package arbiter;
|
||||||
|
|
||||||
import "client.proto";
|
import "auth.proto";
|
||||||
import "user_agent.proto";
|
|
||||||
|
message ClientRequest {
|
||||||
|
oneof payload {
|
||||||
|
arbiter.auth.ClientMessage auth_message = 1;
|
||||||
|
CertRotationAck cert_rotation_ack = 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
message ClientResponse {
|
||||||
|
oneof payload {
|
||||||
|
arbiter.auth.ServerMessage auth_message = 1;
|
||||||
|
CertRotationNotification cert_rotation_notification = 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
message UserAgentRequest {
|
||||||
|
oneof payload {
|
||||||
|
arbiter.auth.ClientMessage auth_message = 1;
|
||||||
|
CertRotationAck cert_rotation_ack = 2;
|
||||||
|
UnsealRequest unseal_request = 3;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
message UserAgentResponse {
|
||||||
|
oneof payload {
|
||||||
|
arbiter.auth.ServerMessage auth_message = 1;
|
||||||
|
CertRotationNotification cert_rotation_notification = 2;
|
||||||
|
UnsealResponse unseal_response = 3;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
message ServerInfo {
|
message ServerInfo {
|
||||||
string version = 1;
|
string version = 1;
|
||||||
bytes cert_public_key = 2;
|
bytes cert_public_key = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
service ArbiterService {
|
// TLS Certificate Rotation Protocol
|
||||||
rpc Client(stream arbiter.client.ClientRequest) returns (stream arbiter.client.ClientResponse);
|
message CertRotationNotification {
|
||||||
rpc UserAgent(stream arbiter.user_agent.UserAgentRequest) returns (stream arbiter.user_agent.UserAgentResponse);
|
// New public certificate (DER-encoded)
|
||||||
|
bytes new_cert = 1;
|
||||||
|
|
||||||
|
// Unix timestamp when rotation will be executed (if all ACKs received)
|
||||||
|
int64 rotation_scheduled_at = 2;
|
||||||
|
|
||||||
|
// Unix timestamp deadline for ACK (7 days from now)
|
||||||
|
int64 ack_deadline = 3;
|
||||||
|
|
||||||
|
// Rotation ID for tracking
|
||||||
|
int32 rotation_id = 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
message CertRotationAck {
|
||||||
|
// Rotation ID (from CertRotationNotification)
|
||||||
|
int32 rotation_id = 1;
|
||||||
|
|
||||||
|
// Client public key for identification
|
||||||
|
bytes client_public_key = 2;
|
||||||
|
|
||||||
|
// Confirmation that client saved the new certificate
|
||||||
|
bool cert_saved = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Vault Unseal Protocol (X25519 ECDH + ChaCha20Poly1305)
|
||||||
|
message UnsealRequest {
|
||||||
|
oneof payload {
|
||||||
|
EphemeralKeyRequest ephemeral_key_request = 1;
|
||||||
|
SealedPassword sealed_password = 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
message UnsealResponse {
|
||||||
|
oneof payload {
|
||||||
|
EphemeralKeyResponse ephemeral_key_response = 1;
|
||||||
|
UnsealResult unseal_result = 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
message EphemeralKeyRequest {}
|
||||||
|
|
||||||
|
message EphemeralKeyResponse {
|
||||||
|
// Server's X25519 ephemeral public key (32 bytes)
|
||||||
|
bytes server_pubkey = 1;
|
||||||
|
|
||||||
|
// Unix timestamp when this key expires (60 seconds from generation)
|
||||||
|
int64 expires_at = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
message SealedPassword {
|
||||||
|
// Client's X25519 ephemeral public key (32 bytes)
|
||||||
|
bytes client_pubkey = 1;
|
||||||
|
|
||||||
|
// ChaCha20Poly1305 encrypted password (ciphertext + tag)
|
||||||
|
bytes encrypted_password = 2;
|
||||||
|
|
||||||
|
// 12-byte nonce for ChaCha20Poly1305
|
||||||
|
bytes nonce = 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
message UnsealResult {
|
||||||
|
// Whether unseal was successful
|
||||||
|
bool success = 1;
|
||||||
|
|
||||||
|
// Error message if unseal failed
|
||||||
|
optional string error_message = 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
service ArbiterService {
|
||||||
|
rpc Client(stream ClientRequest) returns (stream ClientResponse);
|
||||||
|
rpc UserAgent(stream UserAgentRequest) returns (stream UserAgentResponse);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
syntax = "proto3";
|
syntax = "proto3";
|
||||||
|
|
||||||
package arbiter.client;
|
package arbiter.auth;
|
||||||
|
|
||||||
import "evm.proto";
|
import "google/protobuf/timestamp.proto";
|
||||||
|
|
||||||
message AuthChallengeRequest {
|
message AuthChallengeRequest {
|
||||||
bytes pubkey = 1;
|
bytes pubkey = 1;
|
||||||
|
optional string bootstrap_token = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
message AuthChallenge {
|
message AuthChallenge {
|
||||||
@@ -19,28 +20,16 @@ message AuthChallengeSolution {
|
|||||||
|
|
||||||
message AuthOk {}
|
message AuthOk {}
|
||||||
|
|
||||||
message ClientRequest {
|
message ClientMessage {
|
||||||
oneof payload {
|
oneof payload {
|
||||||
AuthChallengeRequest auth_challenge_request = 1;
|
AuthChallengeRequest auth_challenge_request = 1;
|
||||||
AuthChallengeSolution auth_challenge_solution = 2;
|
AuthChallengeSolution auth_challenge_solution = 2;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
message ClientConnectError {
|
message ServerMessage {
|
||||||
enum Code {
|
|
||||||
UNKNOWN = 0;
|
|
||||||
APPROVAL_DENIED = 1;
|
|
||||||
NO_USER_AGENTS_ONLINE = 2;
|
|
||||||
}
|
|
||||||
Code code = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message ClientResponse {
|
|
||||||
oneof payload {
|
oneof payload {
|
||||||
AuthChallenge auth_challenge = 1;
|
AuthChallenge auth_challenge = 1;
|
||||||
AuthOk auth_ok = 2;
|
AuthOk auth_ok = 2;
|
||||||
ClientConnectError client_connect_error = 5;
|
|
||||||
arbiter.evm.EvmSignTransactionResponse evm_sign_transaction = 3;
|
|
||||||
arbiter.evm.EvmAnalyzeTransactionResponse evm_analyze_transaction = 4;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,216 +0,0 @@
|
|||||||
syntax = "proto3";
|
|
||||||
|
|
||||||
package arbiter.evm;
|
|
||||||
|
|
||||||
import "google/protobuf/empty.proto";
|
|
||||||
import "google/protobuf/timestamp.proto";
|
|
||||||
|
|
||||||
enum EvmError {
|
|
||||||
EVM_ERROR_UNSPECIFIED = 0;
|
|
||||||
EVM_ERROR_VAULT_SEALED = 1;
|
|
||||||
EVM_ERROR_INTERNAL = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
message WalletEntry {
|
|
||||||
bytes address = 1; // 20-byte Ethereum address
|
|
||||||
}
|
|
||||||
|
|
||||||
message WalletList {
|
|
||||||
repeated WalletEntry wallets = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message WalletCreateResponse {
|
|
||||||
oneof result {
|
|
||||||
WalletEntry wallet = 1;
|
|
||||||
EvmError error = 2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
message WalletListResponse {
|
|
||||||
oneof result {
|
|
||||||
WalletList wallets = 1;
|
|
||||||
EvmError error = 2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Grant types ---
|
|
||||||
|
|
||||||
message TransactionRateLimit {
|
|
||||||
uint32 count = 1;
|
|
||||||
int64 window_secs = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
message VolumeRateLimit {
|
|
||||||
bytes max_volume = 1; // U256 as big-endian bytes
|
|
||||||
int64 window_secs = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
message SharedSettings {
|
|
||||||
int32 wallet_id = 1;
|
|
||||||
uint64 chain_id = 2;
|
|
||||||
optional google.protobuf.Timestamp valid_from = 3;
|
|
||||||
optional google.protobuf.Timestamp valid_until = 4;
|
|
||||||
optional bytes max_gas_fee_per_gas = 5; // U256 as big-endian bytes
|
|
||||||
optional bytes max_priority_fee_per_gas = 6; // U256 as big-endian bytes
|
|
||||||
optional TransactionRateLimit rate_limit = 7;
|
|
||||||
}
|
|
||||||
|
|
||||||
message EtherTransferSettings {
|
|
||||||
repeated bytes targets = 1; // list of 20-byte Ethereum addresses
|
|
||||||
VolumeRateLimit limit = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
message TokenTransferSettings {
|
|
||||||
bytes token_contract = 1; // 20-byte Ethereum address
|
|
||||||
optional bytes target = 2; // 20-byte Ethereum address; absent means any recipient allowed
|
|
||||||
repeated VolumeRateLimit volume_limits = 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
message SpecificGrant {
|
|
||||||
oneof grant {
|
|
||||||
EtherTransferSettings ether_transfer = 1;
|
|
||||||
TokenTransferSettings token_transfer = 2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
message EtherTransferMeaning {
|
|
||||||
bytes to = 1; // 20-byte Ethereum address
|
|
||||||
bytes value = 2; // U256 as big-endian bytes
|
|
||||||
}
|
|
||||||
|
|
||||||
message TokenInfo {
|
|
||||||
string symbol = 1;
|
|
||||||
bytes address = 2; // 20-byte Ethereum address
|
|
||||||
uint64 chain_id = 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mirror of token_transfers::Meaning
|
|
||||||
message TokenTransferMeaning {
|
|
||||||
TokenInfo token = 1;
|
|
||||||
bytes to = 2; // 20-byte Ethereum address
|
|
||||||
bytes value = 3; // U256 as big-endian bytes
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mirror of policies::SpecificMeaning
|
|
||||||
message SpecificMeaning {
|
|
||||||
oneof meaning {
|
|
||||||
EtherTransferMeaning ether_transfer = 1;
|
|
||||||
TokenTransferMeaning token_transfer = 2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Eval error types ---
|
|
||||||
message GasLimitExceededViolation {
|
|
||||||
optional bytes max_gas_fee_per_gas = 1; // U256 as big-endian bytes
|
|
||||||
optional bytes max_priority_fee_per_gas = 2; // U256 as big-endian bytes
|
|
||||||
}
|
|
||||||
|
|
||||||
message EvalViolation {
|
|
||||||
oneof kind {
|
|
||||||
bytes invalid_target = 1; // 20-byte Ethereum address
|
|
||||||
GasLimitExceededViolation gas_limit_exceeded = 2;
|
|
||||||
google.protobuf.Empty rate_limit_exceeded = 3;
|
|
||||||
google.protobuf.Empty volumetric_limit_exceeded = 4;
|
|
||||||
google.protobuf.Empty invalid_time = 5;
|
|
||||||
google.protobuf.Empty invalid_transaction_type = 6;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Transaction was classified but no grant covers it
|
|
||||||
message NoMatchingGrantError {
|
|
||||||
SpecificMeaning meaning = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Transaction was classified and a grant was found, but constraints were violated
|
|
||||||
message PolicyViolationsError {
|
|
||||||
SpecificMeaning meaning = 1;
|
|
||||||
repeated EvalViolation violations = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
// top-level error returned when transaction evaluation fails
|
|
||||||
message TransactionEvalError {
|
|
||||||
oneof kind {
|
|
||||||
google.protobuf.Empty contract_creation_not_supported = 1;
|
|
||||||
google.protobuf.Empty unsupported_transaction_type = 2;
|
|
||||||
NoMatchingGrantError no_matching_grant = 3;
|
|
||||||
PolicyViolationsError policy_violations = 4;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- UserAgent grant management ---
|
|
||||||
message EvmGrantCreateRequest {
|
|
||||||
int32 client_id = 1;
|
|
||||||
SharedSettings shared = 2;
|
|
||||||
SpecificGrant specific = 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
message EvmGrantCreateResponse {
|
|
||||||
oneof result {
|
|
||||||
int32 grant_id = 1;
|
|
||||||
EvmError error = 2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
message EvmGrantDeleteRequest {
|
|
||||||
int32 grant_id = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message EvmGrantDeleteResponse {
|
|
||||||
oneof result {
|
|
||||||
google.protobuf.Empty ok = 1;
|
|
||||||
EvmError error = 2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Basic grant info returned in grant listings
|
|
||||||
message GrantEntry {
|
|
||||||
int32 id = 1;
|
|
||||||
int32 client_id = 2;
|
|
||||||
SharedSettings shared = 3;
|
|
||||||
SpecificGrant specific = 4;
|
|
||||||
}
|
|
||||||
|
|
||||||
message EvmGrantListRequest {
|
|
||||||
optional int32 wallet_id = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message EvmGrantListResponse {
|
|
||||||
oneof result {
|
|
||||||
EvmGrantList grants = 1;
|
|
||||||
EvmError error = 2;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
message EvmGrantList {
|
|
||||||
repeated GrantEntry grants = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Client transaction operations ---
|
|
||||||
|
|
||||||
message EvmSignTransactionRequest {
|
|
||||||
bytes wallet_address = 1; // 20-byte Ethereum address
|
|
||||||
bytes rlp_transaction = 2; // RLP-encoded EIP-1559 transaction (unsigned)
|
|
||||||
}
|
|
||||||
|
|
||||||
// oneof because signing and evaluation happen atomically — a signing failure
|
|
||||||
// is always either an eval error or an internal error, never a partial success
|
|
||||||
message EvmSignTransactionResponse {
|
|
||||||
oneof result {
|
|
||||||
bytes signature = 1; // 65-byte signature: r[32] || s[32] || v[1]
|
|
||||||
TransactionEvalError eval_error = 2;
|
|
||||||
EvmError error = 3;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
message EvmAnalyzeTransactionRequest {
|
|
||||||
bytes wallet_address = 1; // 20-byte Ethereum address
|
|
||||||
bytes rlp_transaction = 2; // RLP-encoded EIP-1559 transaction
|
|
||||||
}
|
|
||||||
|
|
||||||
message EvmAnalyzeTransactionResponse {
|
|
||||||
oneof result {
|
|
||||||
SpecificMeaning meaning = 1;
|
|
||||||
TransactionEvalError eval_error = 2;
|
|
||||||
EvmError error = 3;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
46
protobufs/google/protobuf/timestamp.proto
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
// Protocol Buffers - Google's data interchange format
|
||||||
|
// Copyright 2008 Google Inc. All rights reserved.
|
||||||
|
//
|
||||||
|
// Redistribution and use in source and binary forms, with or without
|
||||||
|
// modification, are permitted provided that the following conditions are
|
||||||
|
// met:
|
||||||
|
//
|
||||||
|
// * Redistributions of source code must retain the above copyright
|
||||||
|
// notice, this list of conditions and the following disclaimer.
|
||||||
|
// * Redistributions in binary form must reproduce the above
|
||||||
|
// copyright notice, this list of conditions and the following disclaimer
|
||||||
|
// in the documentation and/or other materials provided with the
|
||||||
|
// distribution.
|
||||||
|
// * Neither the name of Google Inc. nor the names of its
|
||||||
|
// contributors may be used to endorse or promote products derived from
|
||||||
|
// this software without specific prior written permission.
|
||||||
|
|
||||||
|
syntax = "proto3";
|
||||||
|
|
||||||
|
package google.protobuf;
|
||||||
|
|
||||||
|
option csharp_namespace = "Google.Protobuf.WellKnownTypes";
|
||||||
|
option cc_enable_arenas = true;
|
||||||
|
option go_package = "google.golang.org/protobuf/types/known/timestamppb";
|
||||||
|
option java_package = "com.google.protobuf";
|
||||||
|
option java_outer_classname = "TimestampProto";
|
||||||
|
option java_multiple_files = true;
|
||||||
|
option objc_class_prefix = "GPB";
|
||||||
|
|
||||||
|
// A Timestamp represents a point in time independent of any time zone or local
|
||||||
|
// calendar, encoded as a count of seconds and fractions of seconds at
|
||||||
|
// nanosecond resolution. The count is relative to an epoch at UTC midnight on
|
||||||
|
// January 1, 1970, in the proleptic Gregorian calendar which extends the
|
||||||
|
// Gregorian calendar backwards to year one.
|
||||||
|
message Timestamp {
|
||||||
|
// Represents seconds of UTC time since Unix epoch
|
||||||
|
// 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
|
||||||
|
// 9999-12-31T23:59:59Z inclusive.
|
||||||
|
int64 seconds = 1;
|
||||||
|
|
||||||
|
// Non-negative fractions of a second at nanosecond resolution. Negative
|
||||||
|
// second values with fractions must still have non-negative nanos values
|
||||||
|
// that count forward in time. Must be from 0 to 999,999,999
|
||||||
|
// inclusive.
|
||||||
|
int32 nanos = 2;
|
||||||
|
}
|
||||||
14
protobufs/unseal.proto
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
syntax = "proto3";
|
||||||
|
|
||||||
|
package arbiter.unseal;
|
||||||
|
|
||||||
|
message UserAgentKeyRequest {}
|
||||||
|
|
||||||
|
message ServerKeyResponse {
|
||||||
|
bytes pubkey = 1;
|
||||||
|
}
|
||||||
|
message UserAgentSealedKey {
|
||||||
|
bytes sealed_key = 1;
|
||||||
|
bytes pubkey = 2;
|
||||||
|
bytes nonce = 3;
|
||||||
|
}
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
syntax = "proto3";
|
|
||||||
|
|
||||||
package arbiter.user_agent;
|
|
||||||
|
|
||||||
import "google/protobuf/empty.proto";
|
|
||||||
import "evm.proto";
|
|
||||||
|
|
||||||
enum KeyType {
|
|
||||||
KEY_TYPE_UNSPECIFIED = 0;
|
|
||||||
KEY_TYPE_ED25519 = 1;
|
|
||||||
KEY_TYPE_ECDSA_SECP256K1 = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
message AuthChallengeRequest {
|
|
||||||
bytes pubkey = 1;
|
|
||||||
optional string bootstrap_token = 2;
|
|
||||||
KeyType key_type = 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
message AuthChallenge {
|
|
||||||
bytes pubkey = 1;
|
|
||||||
int32 nonce = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
message AuthChallengeSolution {
|
|
||||||
bytes signature = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message AuthOk {}
|
|
||||||
|
|
||||||
message UnsealStart {
|
|
||||||
bytes client_pubkey = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message UnsealStartResponse {
|
|
||||||
bytes server_pubkey = 1;
|
|
||||||
}
|
|
||||||
message UnsealEncryptedKey {
|
|
||||||
bytes nonce = 1;
|
|
||||||
bytes ciphertext = 2;
|
|
||||||
bytes associated_data = 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
enum UnsealResult {
|
|
||||||
UNSEAL_RESULT_UNSPECIFIED = 0;
|
|
||||||
UNSEAL_RESULT_SUCCESS = 1;
|
|
||||||
UNSEAL_RESULT_INVALID_KEY = 2;
|
|
||||||
UNSEAL_RESULT_UNBOOTSTRAPPED = 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
enum VaultState {
|
|
||||||
VAULT_STATE_UNSPECIFIED = 0;
|
|
||||||
VAULT_STATE_UNBOOTSTRAPPED = 1;
|
|
||||||
VAULT_STATE_SEALED = 2;
|
|
||||||
VAULT_STATE_UNSEALED = 3;
|
|
||||||
VAULT_STATE_ERROR = 4;
|
|
||||||
}
|
|
||||||
|
|
||||||
message ClientConnectionRequest {
|
|
||||||
bytes pubkey = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message ClientConnectionResponse {
|
|
||||||
bool approved = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message ClientConnectionCancel {}
|
|
||||||
|
|
||||||
message UserAgentRequest {
|
|
||||||
oneof payload {
|
|
||||||
AuthChallengeRequest auth_challenge_request = 1;
|
|
||||||
AuthChallengeSolution auth_challenge_solution = 2;
|
|
||||||
UnsealStart unseal_start = 3;
|
|
||||||
UnsealEncryptedKey unseal_encrypted_key = 4;
|
|
||||||
google.protobuf.Empty query_vault_state = 5;
|
|
||||||
google.protobuf.Empty evm_wallet_create = 6;
|
|
||||||
google.protobuf.Empty evm_wallet_list = 7;
|
|
||||||
arbiter.evm.EvmGrantCreateRequest evm_grant_create = 8;
|
|
||||||
arbiter.evm.EvmGrantDeleteRequest evm_grant_delete = 9;
|
|
||||||
arbiter.evm.EvmGrantListRequest evm_grant_list = 10;
|
|
||||||
ClientConnectionResponse client_connection_response = 11;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
message UserAgentResponse {
|
|
||||||
oneof payload {
|
|
||||||
AuthChallenge auth_challenge = 1;
|
|
||||||
AuthOk auth_ok = 2;
|
|
||||||
UnsealStartResponse unseal_start_response = 3;
|
|
||||||
UnsealResult unseal_result = 4;
|
|
||||||
VaultState vault_state = 5;
|
|
||||||
arbiter.evm.WalletCreateResponse evm_wallet_create = 6;
|
|
||||||
arbiter.evm.WalletListResponse evm_wallet_list = 7;
|
|
||||||
arbiter.evm.EvmGrantCreateResponse evm_grant_create = 8;
|
|
||||||
arbiter.evm.EvmGrantDeleteResponse evm_grant_delete = 9;
|
|
||||||
arbiter.evm.EvmGrantListResponse evm_grant_list = 10;
|
|
||||||
ClientConnectionRequest client_connection_request = 11;
|
|
||||||
ClientConnectionCancel client_connection_cancel = 12;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,150 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""
|
|
||||||
Fetch the Uniswap default token list and emit Rust `TokenInfo` statics.
|
|
||||||
|
|
||||||
Usage:
|
|
||||||
python3 gen_erc20_registry.py # fetch from IPFS
|
|
||||||
python3 gen_erc20_registry.py tokens.json # local file
|
|
||||||
python3 gen_erc20_registry.py tokens.json out.rs # custom output file
|
|
||||||
"""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import re
|
|
||||||
import sys
|
|
||||||
import unicodedata
|
|
||||||
import urllib.request
|
|
||||||
|
|
||||||
UNISWAP_URL = "https://ipfs.io/ipns/tokens.uniswap.org"
|
|
||||||
|
|
||||||
SOLANA_CHAIN_ID = 501000101
|
|
||||||
IDENTIFIER_RE = re.compile(r"[^A-Za-z0-9]+")
|
|
||||||
|
|
||||||
|
|
||||||
def load_tokens(source=None):
|
|
||||||
if source:
|
|
||||||
with open(source) as f:
|
|
||||||
return json.load(f)
|
|
||||||
req = urllib.request.Request(
|
|
||||||
UNISWAP_URL,
|
|
||||||
headers={"Accept": "application/json", "User-Agent": "gen_tokens/1.0"},
|
|
||||||
)
|
|
||||||
with urllib.request.urlopen(req, timeout=60) as resp:
|
|
||||||
return json.loads(resp.read())
|
|
||||||
|
|
||||||
|
|
||||||
def escape(s: str) -> str:
|
|
||||||
return s.replace("\\", "\\\\").replace('"', '\\"')
|
|
||||||
|
|
||||||
|
|
||||||
def to_screaming_case(name: str) -> str:
|
|
||||||
normalized = unicodedata.normalize("NFKD", name or "")
|
|
||||||
ascii_name = normalized.encode("ascii", "ignore").decode("ascii")
|
|
||||||
snake = IDENTIFIER_RE.sub("_", ascii_name).strip("_").upper()
|
|
||||||
if not snake:
|
|
||||||
snake = "TOKEN"
|
|
||||||
if snake[0].isdigit():
|
|
||||||
snake = f"TOKEN_{snake}"
|
|
||||||
return snake
|
|
||||||
|
|
||||||
|
|
||||||
def static_name_for_token(token: dict, used_names: set[str]) -> str:
|
|
||||||
base = to_screaming_case(token.get("name", ""))
|
|
||||||
if base not in used_names:
|
|
||||||
used_names.add(base)
|
|
||||||
return base
|
|
||||||
|
|
||||||
address = token["address"]
|
|
||||||
suffix = f"{token['chainId']}_{address[2:].upper()[-8:]}"
|
|
||||||
candidate = f"{base}_{suffix}"
|
|
||||||
|
|
||||||
i = 2
|
|
||||||
while candidate in used_names:
|
|
||||||
candidate = f"{base}_{suffix}_{i}"
|
|
||||||
i += 1
|
|
||||||
|
|
||||||
used_names.add(candidate)
|
|
||||||
return candidate
|
|
||||||
|
|
||||||
|
|
||||||
def main():
|
|
||||||
source = sys.argv[1] if len(sys.argv) > 1 else None
|
|
||||||
output = sys.argv[2] if len(sys.argv) > 2 else "generated_tokens.rs"
|
|
||||||
data = load_tokens(source)
|
|
||||||
tokens = data["tokens"]
|
|
||||||
|
|
||||||
# Deduplicate by (chainId, address)
|
|
||||||
seen = set()
|
|
||||||
unique = []
|
|
||||||
for t in tokens:
|
|
||||||
key = (t["chainId"], t["address"].lower())
|
|
||||||
if key not in seen:
|
|
||||||
seen.add(key)
|
|
||||||
unique.append(t)
|
|
||||||
|
|
||||||
unique.sort(key=lambda t: (t["chainId"], t.get("symbol", "").upper()))
|
|
||||||
evm_tokens = [t for t in unique if t["chainId"] != SOLANA_CHAIN_ID]
|
|
||||||
|
|
||||||
ver = data["version"]
|
|
||||||
lines = []
|
|
||||||
w = lines.append
|
|
||||||
|
|
||||||
w(
|
|
||||||
f"// Auto-generated from Uniswap token list v{ver['major']}.{ver['minor']}.{ver['patch']}"
|
|
||||||
)
|
|
||||||
w(f"// {len(evm_tokens)} tokens")
|
|
||||||
w("// DO NOT EDIT - regenerate with gen_erc20_registry.py")
|
|
||||||
w("")
|
|
||||||
|
|
||||||
used_static_names = set()
|
|
||||||
token_statics = []
|
|
||||||
for t in evm_tokens:
|
|
||||||
static_name = static_name_for_token(t, used_static_names)
|
|
||||||
token_statics.append((static_name, t))
|
|
||||||
|
|
||||||
for static_name, t in token_statics:
|
|
||||||
addr = t["address"]
|
|
||||||
name = escape(t.get("name", ""))
|
|
||||||
symbol = escape(t.get("symbol", ""))
|
|
||||||
decimals = t.get("decimals", 18)
|
|
||||||
logo = t.get("logoURI")
|
|
||||||
chain = t["chainId"]
|
|
||||||
|
|
||||||
logo_val = f'Some("{escape(logo)}")' if logo else "None"
|
|
||||||
|
|
||||||
w(f"pub static {static_name}: TokenInfo = TokenInfo {{")
|
|
||||||
w(f' name: "{name}",')
|
|
||||||
w(f' symbol: "{symbol}",')
|
|
||||||
w(f" decimals: {decimals},")
|
|
||||||
w(f' contract: address!("{addr}"),')
|
|
||||||
w(f" chain: {chain},")
|
|
||||||
w(f" logo_uri: {logo_val},")
|
|
||||||
w("};")
|
|
||||||
w("")
|
|
||||||
|
|
||||||
w("pub static TOKENS: &[&TokenInfo] = &[")
|
|
||||||
for static_name, _ in token_statics:
|
|
||||||
w(f" &{static_name},")
|
|
||||||
w("];")
|
|
||||||
w("")
|
|
||||||
w("pub fn get_token(")
|
|
||||||
w(" chain_id: alloy::primitives::ChainId,")
|
|
||||||
w(" address: alloy::primitives::Address,")
|
|
||||||
w(") -> Option<&'static TokenInfo> {")
|
|
||||||
w(" match (chain_id, address) {")
|
|
||||||
for static_name, t in token_statics:
|
|
||||||
w(
|
|
||||||
f' ({t["chainId"]}, addr) if addr == address!("{t["address"]}") => Some(&{static_name}),'
|
|
||||||
)
|
|
||||||
w(" _ => None,")
|
|
||||||
w(" }")
|
|
||||||
w("}")
|
|
||||||
w("")
|
|
||||||
|
|
||||||
with open(output, "w") as f:
|
|
||||||
f.write("\n".join(lines))
|
|
||||||
|
|
||||||
print(f"Wrote {len(token_statics)} tokens to {output}")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
main()
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
[target.'cfg(windows)'.profile.dev]
|
|
||||||
# Override global Cranelift backend only on Windows.
|
|
||||||
# Cranelift does not propagate cargo:rustc-link-lib from native dependencies
|
|
||||||
# (aws-lc-sys etc.) to lld-link, causing undefined symbol errors.
|
|
||||||
codegen-backend = "llvm"
|
|
||||||
2941
server/Cargo.lock
generated
@@ -1,17 +1,15 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
members = [
|
||||||
"crates/*",
|
"crates/arbiter-client",
|
||||||
|
"crates/arbiter-proto",
|
||||||
|
"crates/arbiter-server",
|
||||||
|
"crates/arbiter-useragent",
|
||||||
]
|
]
|
||||||
resolver = "3"
|
resolver = "3"
|
||||||
|
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
tonic = { version = "0.14.3", features = [
|
tonic = { version = "0.14.3", features = ["deflate", "gzip", "tls-connect-info", "zstd"] }
|
||||||
"deflate",
|
|
||||||
"gzip",
|
|
||||||
"tls-connect-info",
|
|
||||||
"zstd",
|
|
||||||
] }
|
|
||||||
tracing = "0.1.44"
|
tracing = "0.1.44"
|
||||||
tokio = { version = "1.49.0", features = ["full"] }
|
tokio = { version = "1.49.0", features = ["full"] }
|
||||||
ed25519-dalek = { version = "3.0.0-pre.6", features = ["rand_core"] }
|
ed25519-dalek = { version = "3.0.0-pre.6", features = ["rand_core"] }
|
||||||
@@ -26,14 +24,3 @@ futures = "0.3.31"
|
|||||||
tokio-stream = { version = "0.1.18", features = ["full"] }
|
tokio-stream = { version = "0.1.18", features = ["full"] }
|
||||||
kameo = "0.19.2"
|
kameo = "0.19.2"
|
||||||
prost-types = { version = "0.14.3", features = ["chrono"] }
|
prost-types = { version = "0.14.3", features = ["chrono"] }
|
||||||
x25519-dalek = { version = "2.0.1", features = ["getrandom"] }
|
|
||||||
rstest = "0.26.1"
|
|
||||||
rustls-pki-types = "1.14.0"
|
|
||||||
alloy = "1.7.3"
|
|
||||||
rcgen = { version = "0.14.7", features = [
|
|
||||||
"aws_lc_rs",
|
|
||||||
"pem",
|
|
||||||
"x509-parser",
|
|
||||||
"zeroize",
|
|
||||||
], default-features = false }
|
|
||||||
k256 = { version = "0.13.4", features = ["ecdsa", "pkcs8"] }
|
|
||||||
|
|||||||
@@ -3,6 +3,5 @@ name = "arbiter-client"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
repository = "https://git.markettakers.org/MarketTakers/arbiter"
|
repository = "https://git.markettakers.org/MarketTakers/arbiter"
|
||||||
license = "Apache-2.0"
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ name = "arbiter-proto"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
repository = "https://git.markettakers.org/MarketTakers/arbiter"
|
repository = "https://git.markettakers.org/MarketTakers/arbiter"
|
||||||
license = "Apache-2.0"
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
tonic.workspace = true
|
tonic.workspace = true
|
||||||
@@ -13,25 +12,11 @@ hex = "0.4.3"
|
|||||||
tonic-prost = "0.14.3"
|
tonic-prost = "0.14.3"
|
||||||
prost = "0.14.3"
|
prost = "0.14.3"
|
||||||
kameo.workspace = true
|
kameo.workspace = true
|
||||||
url = "2.5.8"
|
|
||||||
miette.workspace = true
|
|
||||||
thiserror.workspace = true
|
|
||||||
rustls-pki-types.workspace = true
|
|
||||||
base64 = "0.22.1"
|
|
||||||
prost-types.workspace = true
|
prost-types.workspace = true
|
||||||
tracing.workspace = true
|
|
||||||
async-trait.workspace = true
|
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
|
prost-build = "0.14.3"
|
||||||
|
serde_json = "1"
|
||||||
tonic-prost-build = "0.14.3"
|
tonic-prost-build = "0.14.3"
|
||||||
protoc-bin-vendored = "3"
|
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
rstest.workspace = true
|
|
||||||
rand.workspace = true
|
|
||||||
rcgen.workspace = true
|
|
||||||
|
|
||||||
[package.metadata.cargo-shear]
|
|
||||||
ignored = ["tonic-prost", "prost", "kameo"]
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,27 +1,15 @@
|
|||||||
use tonic_prost_build::configure;
|
|
||||||
|
|
||||||
static PROTOBUF_DIR: &str = "../../../protobufs";
|
static PROTOBUF_DIR: &str = "../../../protobufs";
|
||||||
|
|
||||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
if std::env::var("PROTOC").is_err() {
|
let proto_files = vec![
|
||||||
println!("cargo:warning=PROTOC environment variable not set, using vendored protoc");
|
format!("{}/arbiter.proto", PROTOBUF_DIR),
|
||||||
let protoc = protoc_bin_vendored::protoc_bin_path().unwrap();
|
format!("{}/auth.proto", PROTOBUF_DIR),
|
||||||
unsafe { std::env::set_var("PROTOC", protoc) };
|
];
|
||||||
}
|
|
||||||
|
|
||||||
println!("cargo::rerun-if-changed={PROTOBUF_DIR}");
|
// Компилируем protobuf (tonic-prost-build автоматически использует prost_types для google.protobuf)
|
||||||
|
tonic_prost_build::configure()
|
||||||
configure()
|
|
||||||
.message_attribute(".", "#[derive(::kameo::Reply)]")
|
.message_attribute(".", "#[derive(::kameo::Reply)]")
|
||||||
.compile_protos(
|
.compile_protos(&proto_files, &[PROTOBUF_DIR.to_string()])?;
|
||||||
&[
|
|
||||||
format!("{}/arbiter.proto", PROTOBUF_DIR),
|
|
||||||
format!("{}/user_agent.proto", PROTOBUF_DIR),
|
|
||||||
format!("{}/client.proto", PROTOBUF_DIR),
|
|
||||||
format!("{}/evm.proto", PROTOBUF_DIR),
|
|
||||||
],
|
|
||||||
&[PROTOBUF_DIR.to_string()],
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,25 +1,16 @@
|
|||||||
pub mod transport;
|
use crate::proto::auth::AuthChallenge;
|
||||||
pub mod url;
|
|
||||||
|
|
||||||
use base64::{Engine, prelude::BASE64_STANDARD};
|
|
||||||
|
|
||||||
pub mod proto {
|
pub mod proto {
|
||||||
tonic::include_proto!("arbiter");
|
tonic::include_proto!("arbiter");
|
||||||
|
|
||||||
pub mod user_agent {
|
pub mod auth {
|
||||||
tonic::include_proto!("arbiter.user_agent");
|
tonic::include_proto!("arbiter.auth");
|
||||||
}
|
|
||||||
|
|
||||||
pub mod client {
|
|
||||||
tonic::include_proto!("arbiter.client");
|
|
||||||
}
|
|
||||||
|
|
||||||
pub mod evm {
|
|
||||||
tonic::include_proto!("arbiter.evm");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub static BOOTSTRAP_PATH: &str = "bootstrap_token";
|
pub mod transport;
|
||||||
|
|
||||||
|
pub static BOOTSTRAP_TOKEN_PATH: &str = "bootstrap_token";
|
||||||
|
|
||||||
pub fn home_path() -> Result<std::path::PathBuf, std::io::Error> {
|
pub fn home_path() -> Result<std::path::PathBuf, std::io::Error> {
|
||||||
static ARBITER_HOME: &str = ".arbiter";
|
static ARBITER_HOME: &str = ".arbiter";
|
||||||
@@ -34,7 +25,7 @@ pub fn home_path() -> Result<std::path::PathBuf, std::io::Error> {
|
|||||||
Ok(arbiter_home)
|
Ok(arbiter_home)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn format_challenge(nonce: i32, pubkey: &[u8]) -> Vec<u8> {
|
pub fn format_challenge(challenge: &AuthChallenge) -> Vec<u8> {
|
||||||
let concat_form = format!("{}:{}", nonce, BASE64_STANDARD.encode(pubkey));
|
let concat_form = format!("{}:{}", challenge.nonce, hex::encode(&challenge.pubkey));
|
||||||
concat_form.into_bytes()
|
concat_form.into_bytes().to_vec()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,309 +1,46 @@
|
|||||||
//! Transport-facing abstractions for protocol/session code.
|
use futures::{Stream, StreamExt};
|
||||||
//!
|
use tokio::sync::mpsc::{self, error::SendError};
|
||||||
//! This module separates three concerns:
|
use tonic::{Status, Streaming};
|
||||||
//!
|
|
||||||
//! - 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
|
|
||||||
//!
|
|
||||||
//! [`Bi`] is intentionally minimal and transport-agnostic:
|
|
||||||
//! - [`Bi::recv`] yields inbound protocol messages
|
|
||||||
//! - [`Bi::send`] accepts outbound protocol/domain items
|
|
||||||
//!
|
|
||||||
//! # 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`.
|
|
||||||
//!
|
|
||||||
//! For [`Bi`], that means `Bi<Inbound, Outbound>`:
|
|
||||||
//! - `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.
|
|
||||||
//!
|
|
||||||
//! [`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
|
|
||||||
//! ```
|
|
||||||
//!
|
|
||||||
//! # 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`].
|
|
||||||
|
|
||||||
use std::marker::PhantomData;
|
|
||||||
|
|
||||||
use async_trait::async_trait;
|
// Abstraction for stream for sans-io capabilities
|
||||||
|
pub trait Bi<T, U>: Stream<Item = Result<T, Status>> + Send + Sync + 'static {
|
||||||
/// Errors returned by transport adapters implementing [`Bi`].
|
type Error;
|
||||||
#[derive(thiserror::Error, Debug)]
|
fn send(
|
||||||
pub enum Error {
|
&mut self,
|
||||||
#[error("Transport channel is closed")]
|
item: Result<U, Status>,
|
||||||
ChannelClosed,
|
) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send;
|
||||||
#[error("Unexpected message received")]
|
|
||||||
UnexpectedMessage,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Receives one message from `transport` and extracts a value from it using
|
// Bi-directional stream abstraction for handling gRPC streaming requests and responses
|
||||||
/// `extractor`. Returns [`Error::ChannelClosed`] if the transport closes and
|
pub struct BiStream<T, U> {
|
||||||
/// [`Error::UnexpectedMessage`] if `extractor` returns `None`.
|
pub request_stream: Streaming<T>,
|
||||||
pub async fn expect_message<T, Inbound, Outbound, Target, F>(
|
pub response_sender: mpsc::Sender<Result<U, Status>>,
|
||||||
transport: &mut T,
|
}
|
||||||
extractor: F,
|
|
||||||
) -> Result<Target, Error>
|
impl<T, U> Stream for BiStream<T, U>
|
||||||
where
|
where
|
||||||
T: Bi<Inbound, Outbound> + ?Sized,
|
T: Send + 'static,
|
||||||
F: FnOnce(Inbound) -> Option<Target>,
|
U: Send + 'static,
|
||||||
{
|
{
|
||||||
let msg = transport.recv().await.ok_or(Error::ChannelClosed)?;
|
type Item = Result<T, Status>;
|
||||||
extractor(msg).ok_or(Error::UnexpectedMessage)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Minimal bidirectional transport abstraction used by protocol code.
|
fn poll_next(
|
||||||
///
|
mut self: std::pin::Pin<&mut Self>,
|
||||||
/// `Bi<Inbound, Outbound>` models a duplex channel with:
|
cx: &mut std::task::Context<'_>,
|
||||||
/// - inbound items of type `Inbound` read via [`Bi::recv`]
|
) -> std::task::Poll<Option<Self::Item>> {
|
||||||
/// - outbound items of type `Outbound` written via [`Bi::send`]
|
self.request_stream.poll_next_unpin(cx)
|
||||||
#[async_trait]
|
|
||||||
pub trait Bi<Inbound, Outbound>: Send + Sync + 'static {
|
|
||||||
async fn send(&mut self, item: Outbound) -> Result<(), Error>;
|
|
||||||
|
|
||||||
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;
|
|
||||||
|
|
||||||
fn convert(&self, item: Self::Input) -> Self::Output;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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> {
|
impl<T, U> Bi<T, U> for BiStream<T, U>
|
||||||
fn default() -> Self {
|
|
||||||
Self::new()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> RecvConverter for IdentityRecvConverter<T>
|
|
||||||
where
|
where
|
||||||
T: Send + Sync + 'static,
|
T: Send + 'static,
|
||||||
|
U: Send + 'static,
|
||||||
{
|
{
|
||||||
type Input = T;
|
type Error = SendError<Result<U, Status>>;
|
||||||
type Output = T;
|
|
||||||
|
|
||||||
fn convert(&self, item: Self::Input) -> Self::Output {
|
async fn send(&mut self, item: Result<U, Status>) -> Result<(), Self::Error> {
|
||||||
item
|
self.response_sender.send(item).await
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// No-op [`Bi`] transport for tests and manual actor usage.
|
|
||||||
///
|
|
||||||
/// `send` drops all items and succeeds. [`Bi::recv`] never resolves and therefore
|
|
||||||
/// does not busy-wait or spuriously close the stream.
|
|
||||||
pub struct DummyTransport<Inbound, Outbound> {
|
|
||||||
_marker: PhantomData<(Inbound, Outbound)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<Inbound, Outbound> DummyTransport<Inbound, Outbound> {
|
|
||||||
pub fn new() -> 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>
|
|
||||||
where
|
|
||||||
Inbound: Send + Sync + 'static,
|
|
||||||
Outbound: Send + Sync + 'static,
|
|
||||||
{
|
|
||||||
async fn send(&mut self, _item: Outbound) -> Result<(), Error> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn recv(&mut self) -> Option<Inbound> {
|
|
||||||
std::future::pending::<()>().await;
|
|
||||||
None
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,128 +0,0 @@
|
|||||||
use std::fmt::Display;
|
|
||||||
|
|
||||||
use base64::{Engine as _, prelude::BASE64_URL_SAFE};
|
|
||||||
use rustls_pki_types::CertificateDer;
|
|
||||||
|
|
||||||
const ARBITER_URL_SCHEME: &str = "arbiter";
|
|
||||||
const CERT_QUERY_KEY: &str = "cert";
|
|
||||||
const BOOTSTRAP_TOKEN_QUERY_KEY: &str = "bootstrap_token";
|
|
||||||
|
|
||||||
pub struct ArbiterUrl {
|
|
||||||
pub host: String,
|
|
||||||
pub port: u16,
|
|
||||||
pub ca_cert: CertificateDer<'static>,
|
|
||||||
pub bootstrap_token: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Display for ArbiterUrl {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
let mut base = format!(
|
|
||||||
"{ARBITER_URL_SCHEME}://{}:{}?{CERT_QUERY_KEY}={}",
|
|
||||||
self.host,
|
|
||||||
self.port,
|
|
||||||
BASE64_URL_SAFE.encode(&self.ca_cert)
|
|
||||||
);
|
|
||||||
if let Some(token) = &self.bootstrap_token {
|
|
||||||
base.push_str(&format!("&{BOOTSTRAP_TOKEN_QUERY_KEY}={}", token));
|
|
||||||
}
|
|
||||||
f.write_str(&base)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, thiserror::Error, miette::Diagnostic)]
|
|
||||||
pub enum Error {
|
|
||||||
#[error("Invalid URL scheme, expected '{ARBITER_URL_SCHEME}://'")]
|
|
||||||
#[diagnostic(
|
|
||||||
code(arbiter::url::invalid_scheme),
|
|
||||||
help("The URL must start with '{ARBITER_URL_SCHEME}://'")
|
|
||||||
)]
|
|
||||||
InvalidScheme,
|
|
||||||
#[error("Missing host in URL")]
|
|
||||||
#[diagnostic(
|
|
||||||
code(arbiter::url::missing_host),
|
|
||||||
help("The URL must include a host, e.g., '{ARBITER_URL_SCHEME}://127.0.0.1:<port>'")
|
|
||||||
)]
|
|
||||||
MissingHost,
|
|
||||||
#[error("Missing port in URL")]
|
|
||||||
#[diagnostic(
|
|
||||||
code(arbiter::url::missing_port),
|
|
||||||
help("The URL must include a port, e.g., '{ARBITER_URL_SCHEME}://127.0.0.1:1234'")
|
|
||||||
)]
|
|
||||||
MissingPort,
|
|
||||||
#[error("Missing 'cert' query parameter in URL")]
|
|
||||||
#[diagnostic(
|
|
||||||
code(arbiter::url::missing_cert),
|
|
||||||
help("The URL must include a 'cert' query parameter")
|
|
||||||
)]
|
|
||||||
MissingCert,
|
|
||||||
#[error("Invalid base64 in 'cert' query parameter: {0}")]
|
|
||||||
#[diagnostic(code(arbiter::url::invalid_cert_base64))]
|
|
||||||
InvalidCertBase64(#[from] base64::DecodeError),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> TryFrom<&'a str> for ArbiterUrl {
|
|
||||||
type Error = Error;
|
|
||||||
|
|
||||||
fn try_from(value: &'a str) -> Result<Self, Self::Error> {
|
|
||||||
let url = url::Url::parse(value).map_err(|_| Error::InvalidScheme)?;
|
|
||||||
|
|
||||||
if url.scheme() != ARBITER_URL_SCHEME {
|
|
||||||
return Err(Error::InvalidScheme);
|
|
||||||
}
|
|
||||||
|
|
||||||
let host = url.host_str().ok_or(Error::MissingHost)?.to_string();
|
|
||||||
let port = url.port().ok_or(Error::MissingPort)?;
|
|
||||||
let cert_str = url
|
|
||||||
.query_pairs()
|
|
||||||
.find(|(k, _)| k == CERT_QUERY_KEY)
|
|
||||||
.ok_or(Error::MissingCert)?
|
|
||||||
.1;
|
|
||||||
|
|
||||||
let cert = BASE64_URL_SAFE.decode(cert_str.as_ref())?;
|
|
||||||
let cert = CertificateDer::from_slice(&cert).into_owned();
|
|
||||||
|
|
||||||
let bootstrap_token = url
|
|
||||||
.query_pairs()
|
|
||||||
.find(|(k, _)| k == BOOTSTRAP_TOKEN_QUERY_KEY)
|
|
||||||
.map(|(_, v)| v.to_string());
|
|
||||||
|
|
||||||
Ok(ArbiterUrl {
|
|
||||||
host,
|
|
||||||
port,
|
|
||||||
ca_cert: cert,
|
|
||||||
bootstrap_token,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use rcgen::generate_simple_self_signed;
|
|
||||||
use rstest::rstest;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[rstest]
|
|
||||||
|
|
||||||
fn test_parsing_correctness(
|
|
||||||
#[values("127.0.0.1", "localhost", "192.168.1.1", "some.domain.com")] host: &str,
|
|
||||||
|
|
||||||
#[values(None, Some("token123".to_string()))] bootstrap_token: Option<String>,
|
|
||||||
) {
|
|
||||||
let cert = generate_simple_self_signed(&["Arbiter CA".into()]).unwrap();
|
|
||||||
let cert = cert.cert.der();
|
|
||||||
|
|
||||||
let url = ArbiterUrl {
|
|
||||||
host: host.to_string(),
|
|
||||||
port: 1234,
|
|
||||||
ca_cert: cert.clone().into_owned(),
|
|
||||||
bootstrap_token,
|
|
||||||
};
|
|
||||||
let url_str = url.to_string();
|
|
||||||
let parsed_url = ArbiterUrl::try_from(url_str.as_str()).unwrap();
|
|
||||||
assert_eq!(url.host, parsed_url.host);
|
|
||||||
assert_eq!(url.port, parsed_url.port);
|
|
||||||
assert_eq!(url.ca_cert.to_vec(), parsed_url.ca_cert.to_vec());
|
|
||||||
assert_eq!(url.bootstrap_token, parsed_url.bootstrap_token);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
BIN
server/crates/arbiter-server/.DS_Store
vendored
@@ -3,10 +3,15 @@ name = "arbiter-server"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
repository = "https://git.markettakers.org/MarketTakers/arbiter"
|
repository = "https://git.markettakers.org/MarketTakers/arbiter"
|
||||||
license = "Apache-2.0"
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
diesel = { version = "2.3.6", features = ["chrono", "returning_clauses_for_sqlite_3_35", "serde_json", "time", "uuid"] }
|
diesel = { version = "2.3.6", features = [
|
||||||
|
"sqlite",
|
||||||
|
"uuid",
|
||||||
|
"time",
|
||||||
|
"chrono",
|
||||||
|
"serde_json",
|
||||||
|
] }
|
||||||
diesel-async = { version = "0.7.4", features = [
|
diesel-async = { version = "0.7.4", features = [
|
||||||
"bb8",
|
"bb8",
|
||||||
"migrations",
|
"migrations",
|
||||||
@@ -16,9 +21,7 @@ diesel-async = { version = "0.7.4", features = [
|
|||||||
ed25519-dalek.workspace = true
|
ed25519-dalek.workspace = true
|
||||||
arbiter-proto.path = "../arbiter-proto"
|
arbiter-proto.path = "../arbiter-proto"
|
||||||
tracing.workspace = true
|
tracing.workspace = true
|
||||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
|
||||||
tonic.workspace = true
|
tonic.workspace = true
|
||||||
tonic.features = ["tls-aws-lc"]
|
|
||||||
tokio.workspace = true
|
tokio.workspace = true
|
||||||
rustls.workspace = true
|
rustls.workspace = true
|
||||||
smlang.workspace = true
|
smlang.workspace = true
|
||||||
@@ -31,21 +34,20 @@ futures.workspace = true
|
|||||||
tokio-stream.workspace = true
|
tokio-stream.workspace = true
|
||||||
dashmap = "6.1.0"
|
dashmap = "6.1.0"
|
||||||
rand.workspace = true
|
rand.workspace = true
|
||||||
rcgen.workspace = true
|
rcgen = { version = "0.14.7", features = [
|
||||||
|
"aws_lc_rs",
|
||||||
|
"pem",
|
||||||
|
"x509-parser",
|
||||||
|
"zeroize",
|
||||||
|
], default-features = false }
|
||||||
chrono.workspace = true
|
chrono.workspace = true
|
||||||
memsafe = "0.4.0"
|
memsafe = "0.4.0"
|
||||||
zeroize = { version = "1.8.2", features = ["std", "simd"] }
|
zeroize = { version = "1.8.2", features = ["std", "simd"] }
|
||||||
|
argon2 = { version = "0.5", features = ["std"] }
|
||||||
kameo.workspace = true
|
kameo.workspace = true
|
||||||
x25519-dalek.workspace = true
|
hex = "0.4.3"
|
||||||
chacha20poly1305 = { version = "0.10.1", features = ["std"] }
|
chacha20poly1305 = "0.10.1"
|
||||||
argon2 = { version = "0.5.3", features = ["zeroize"] }
|
x25519-dalek = { version = "2.0", features = ["static_secrets"] }
|
||||||
restructed = "0.2.2"
|
|
||||||
strum = { version = "0.27.2", features = ["derive"] }
|
|
||||||
pem = "3.0.6"
|
|
||||||
k256.workspace = true
|
|
||||||
alloy.workspace = true
|
|
||||||
arbiter-tokens-registry.path = "../arbiter-tokens-registry"
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
insta = "1.46.3"
|
|
||||||
test-log = { version = "0.2", default-features = false, features = ["trace"] }
|
test-log = { version = "0.2", default-features = false, features = ["trace"] }
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
-- Rollback TLS rotation tables
|
||||||
|
|
||||||
|
-- Удалить добавленную колонку из arbiter_settings
|
||||||
|
ALTER TABLE arbiter_settings DROP COLUMN current_cert_id;
|
||||||
|
|
||||||
|
-- Удалить таблицы в обратном порядке
|
||||||
|
DROP TABLE IF EXISTS tls_rotation_history;
|
||||||
|
DROP TABLE IF EXISTS rotation_client_acks;
|
||||||
|
DROP TABLE IF EXISTS tls_rotation_state;
|
||||||
|
DROP INDEX IF EXISTS idx_tls_certificates_active;
|
||||||
|
DROP TABLE IF EXISTS tls_certificates;
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
-- История всех сертификатов
|
||||||
|
CREATE TABLE IF NOT EXISTS tls_certificates (
|
||||||
|
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||||
|
cert BLOB NOT NULL, -- DER-encoded
|
||||||
|
cert_key BLOB NOT NULL, -- PEM-encoded
|
||||||
|
not_before INTEGER NOT NULL, -- Unix timestamp
|
||||||
|
not_after INTEGER NOT NULL, -- Unix timestamp
|
||||||
|
created_at INTEGER NOT NULL DEFAULT(unixepoch('now')),
|
||||||
|
is_active BOOLEAN NOT NULL DEFAULT 0 -- Только один active=1
|
||||||
|
) STRICT;
|
||||||
|
|
||||||
|
CREATE INDEX idx_tls_certificates_active ON tls_certificates(is_active, not_after);
|
||||||
|
|
||||||
|
-- Tracking процесса ротации
|
||||||
|
CREATE TABLE IF NOT EXISTS tls_rotation_state (
|
||||||
|
id INTEGER NOT NULL PRIMARY KEY CHECK(id = 1), -- Singleton
|
||||||
|
state TEXT NOT NULL DEFAULT('normal') CHECK(state IN ('normal', 'initiated', 'waiting_acks', 'ready')),
|
||||||
|
new_cert_id INTEGER REFERENCES tls_certificates(id),
|
||||||
|
initiated_at INTEGER,
|
||||||
|
timeout_at INTEGER -- Таймаут для ожидания ACKs (initiated_at + 7 дней)
|
||||||
|
) STRICT;
|
||||||
|
|
||||||
|
-- Tracking ACKs от клиентов
|
||||||
|
CREATE TABLE IF NOT EXISTS rotation_client_acks (
|
||||||
|
rotation_id INTEGER NOT NULL, -- Ссылка на new_cert_id
|
||||||
|
client_key TEXT NOT NULL, -- Публичный ключ клиента (hex)
|
||||||
|
ack_received_at INTEGER NOT NULL DEFAULT(unixepoch('now')),
|
||||||
|
PRIMARY KEY (rotation_id, client_key)
|
||||||
|
) STRICT;
|
||||||
|
|
||||||
|
-- Audit trail событий ротации
|
||||||
|
CREATE TABLE IF NOT EXISTS tls_rotation_history (
|
||||||
|
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||||
|
cert_id INTEGER NOT NULL REFERENCES tls_certificates(id),
|
||||||
|
event_type TEXT NOT NULL CHECK(event_type IN ('created', 'rotation_initiated', 'acks_complete', 'activated', 'timeout')),
|
||||||
|
timestamp INTEGER NOT NULL DEFAULT(unixepoch('now')),
|
||||||
|
details TEXT -- JSON с доп. информацией
|
||||||
|
) STRICT;
|
||||||
|
|
||||||
|
-- Миграция существующего сертификата
|
||||||
|
INSERT INTO tls_certificates (id, cert, cert_key, not_before, not_after, is_active, created_at)
|
||||||
|
SELECT
|
||||||
|
1,
|
||||||
|
cert,
|
||||||
|
cert_key,
|
||||||
|
unixepoch('now') as not_before,
|
||||||
|
unixepoch('now') + (90 * 24 * 60 * 60) as not_after, -- 90 дней
|
||||||
|
1 as is_active,
|
||||||
|
unixepoch('now')
|
||||||
|
FROM arbiter_settings WHERE id = 1;
|
||||||
|
|
||||||
|
-- Инициализация rotation_state
|
||||||
|
INSERT INTO tls_rotation_state (id, state) VALUES (1, 'normal');
|
||||||
|
|
||||||
|
-- Добавить ссылку на текущий сертификат
|
||||||
|
ALTER TABLE arbiter_settings ADD COLUMN current_cert_id INTEGER REFERENCES tls_certificates(id);
|
||||||
|
UPDATE arbiter_settings SET current_cert_id = 1 WHERE id = 1;
|
||||||
@@ -1,159 +1,31 @@
|
|||||||
create table if not exists root_key_history (
|
|
||||||
id INTEGER not null PRIMARY KEY,
|
|
||||||
-- root key stored as aead encrypted artifact, with only difference that it's decrypted by unseal key (derived from user password)
|
|
||||||
root_key_encryption_nonce blob not null default(1), -- if re-encrypted, this should be incremented. Used for encrypting root key
|
|
||||||
data_encryption_nonce blob not null default(1), -- nonce used for encrypting with key itself
|
|
||||||
ciphertext blob not null,
|
|
||||||
tag blob not null,
|
|
||||||
schema_version integer not null default(1), -- server would need to reencrypt, because this means that we have changed algorithm
|
|
||||||
salt blob not null -- for key deriviation
|
|
||||||
) STRICT;
|
|
||||||
|
|
||||||
create table if not exists aead_encrypted (
|
create table if not exists aead_encrypted (
|
||||||
id INTEGER not null PRIMARY KEY,
|
id INTEGER not null PRIMARY KEY,
|
||||||
current_nonce blob not null default(1), -- if re-encrypted, this should be incremented
|
current_nonce integer not null default(1), -- if re-encrypted, this should be incremented
|
||||||
ciphertext blob not null,
|
ciphertext blob not null,
|
||||||
tag blob not null,
|
tag blob not null,
|
||||||
schema_version integer not null default(1), -- server would need to reencrypt, because this means that we have changed algorithm
|
schema_version integer not null default(1) -- server would need to reencrypt, because this means that we have changed algorithm
|
||||||
associated_root_key_id integer not null references root_key_history (id) on delete RESTRICT,
|
|
||||||
created_at integer not null default(unixepoch ('now'))
|
|
||||||
) STRICT;
|
|
||||||
|
|
||||||
create unique index if not exists uniq_nonce_per_root_key on aead_encrypted (
|
|
||||||
current_nonce,
|
|
||||||
associated_root_key_id
|
|
||||||
);
|
|
||||||
|
|
||||||
create table if not exists tls_history (
|
|
||||||
id INTEGER not null PRIMARY KEY,
|
|
||||||
cert text not null,
|
|
||||||
cert_key text not null, -- PEM Encoded private key
|
|
||||||
ca_cert text not null,
|
|
||||||
ca_key text not null, -- PEM Encoded private key
|
|
||||||
created_at integer not null default(unixepoch ('now'))
|
|
||||||
) STRICT;
|
) STRICT;
|
||||||
|
|
||||||
-- This is a singleton
|
-- This is a singleton
|
||||||
create table if not exists arbiter_settings (
|
create table if not exists arbiter_settings (
|
||||||
id INTEGER not null PRIMARY KEY CHECK (id = 1), -- singleton row, id must be 1
|
id INTEGER not null PRIMARY KEY CHECK (id = 1), -- singleton row, id must be 1
|
||||||
root_key_id integer references root_key_history (id) on delete RESTRICT, -- if null, means wasn't bootstrapped yet
|
root_key_id integer references aead_encrypted (id) on delete RESTRICT, -- if null, means wasn't bootstrapped yet
|
||||||
tls_id integer references tls_history (id) on delete RESTRICT
|
cert_key blob not null,
|
||||||
|
cert blob not null
|
||||||
) STRICT;
|
) STRICT;
|
||||||
|
|
||||||
insert into arbiter_settings (id) values (1) on conflict do nothing; -- ensure singleton row exists
|
|
||||||
|
|
||||||
create table if not exists useragent_client (
|
create table if not exists useragent_client (
|
||||||
id integer not null primary key,
|
id integer not null primary key,
|
||||||
nonce integer not null default(1), -- used for auth challenge
|
nonce integer not null default (1), -- used for auth challenge
|
||||||
public_key blob not null,
|
public_key blob not null,
|
||||||
key_type integer not null default(1), -- 1=Ed25519, 2=ECDSA(secp256k1)
|
|
||||||
created_at integer not null default(unixepoch ('now')),
|
created_at integer not null default(unixepoch ('now')),
|
||||||
updated_at integer not null default(unixepoch ('now'))
|
updated_at integer not null default(unixepoch ('now'))
|
||||||
) STRICT;
|
) STRICT;
|
||||||
|
|
||||||
create table if not exists program_client (
|
create table if not exists program_client (
|
||||||
id integer not null primary key,
|
id integer not null primary key,
|
||||||
nonce integer not null default(1), -- used for auth challenge
|
nonce integer not null default (1), -- used for auth challenge
|
||||||
public_key blob not null,
|
public_key blob not null,
|
||||||
created_at integer not null default(unixepoch ('now')),
|
created_at integer not null default(unixepoch ('now')),
|
||||||
updated_at integer not null default(unixepoch ('now'))
|
updated_at integer not null default(unixepoch ('now'))
|
||||||
) STRICT;
|
) STRICT;
|
||||||
|
|
||||||
create table if not exists evm_wallet (
|
|
||||||
id integer not null primary key,
|
|
||||||
address blob not null, -- 20-byte Ethereum address
|
|
||||||
aead_encrypted_id integer not null references aead_encrypted (id) on delete RESTRICT,
|
|
||||||
created_at integer not null default(unixepoch ('now'))
|
|
||||||
) STRICT;
|
|
||||||
|
|
||||||
create unique index if not exists uniq_evm_wallet_address on evm_wallet (address);
|
|
||||||
create unique index if not exists uniq_evm_wallet_aead on evm_wallet (aead_encrypted_id);
|
|
||||||
|
|
||||||
create table if not exists evm_ether_transfer_limit (
|
|
||||||
id integer not null primary key,
|
|
||||||
window_secs integer not null, -- window duration in seconds
|
|
||||||
max_volume blob not null -- big-endian 32-byte U256
|
|
||||||
) STRICT;
|
|
||||||
|
|
||||||
-- Shared grant properties: client scope, timeframe, fee caps, and rate limit
|
|
||||||
create table if not exists evm_basic_grant (
|
|
||||||
id integer not null primary key,
|
|
||||||
wallet_id integer not null references evm_wallet(id) on delete restrict,
|
|
||||||
client_id integer not null references program_client(id) on delete restrict,
|
|
||||||
chain_id integer not null, -- EIP-155 chain ID
|
|
||||||
valid_from integer, -- unix timestamp (seconds), null = no lower bound
|
|
||||||
valid_until integer, -- unix timestamp (seconds), null = no upper bound
|
|
||||||
max_gas_fee_per_gas blob, -- big-endian 32-byte U256, null = unlimited
|
|
||||||
max_priority_fee_per_gas blob, -- big-endian 32-byte U256, null = unlimited
|
|
||||||
rate_limit_count integer, -- max transactions in window, null = unlimited
|
|
||||||
rate_limit_window_secs integer, -- window duration in seconds, null = unlimited
|
|
||||||
revoked_at integer, -- unix timestamp when revoked, null = still active
|
|
||||||
created_at integer not null default(unixepoch('now'))
|
|
||||||
) STRICT;
|
|
||||||
|
|
||||||
-- Shared transaction log for all EVM grants, used for rate limit tracking and auditing
|
|
||||||
create table if not exists evm_transaction_log (
|
|
||||||
id integer not null primary key,
|
|
||||||
grant_id integer not null references evm_basic_grant(id) on delete restrict,
|
|
||||||
client_id integer not null references program_client(id) on delete restrict,
|
|
||||||
wallet_id integer not null references evm_wallet(id) on delete restrict,
|
|
||||||
chain_id integer not null,
|
|
||||||
eth_value blob not null, -- always present on any EVM tx
|
|
||||||
signed_at integer not null default(unixepoch('now'))
|
|
||||||
) STRICT;
|
|
||||||
|
|
||||||
create index if not exists idx_evm_basic_grant_wallet_chain on evm_basic_grant(client_id, wallet_id, chain_id);
|
|
||||||
|
|
||||||
-- ===============================
|
|
||||||
-- ERC20 token transfer grant
|
|
||||||
-- ===============================
|
|
||||||
create table if not exists evm_token_transfer_grant (
|
|
||||||
id integer not null primary key,
|
|
||||||
basic_grant_id integer not null unique references evm_basic_grant(id) on delete cascade,
|
|
||||||
token_contract blob not null, -- 20-byte ERC20 contract address
|
|
||||||
receiver blob -- 20-byte recipient address or null if every recipient allowed
|
|
||||||
) STRICT;
|
|
||||||
|
|
||||||
-- Per-window volume limits for token transfer grants
|
|
||||||
create table if not exists evm_token_transfer_volume_limit (
|
|
||||||
id integer not null primary key,
|
|
||||||
grant_id integer not null references evm_token_transfer_grant(id) on delete cascade,
|
|
||||||
window_secs integer not null, -- window duration in seconds
|
|
||||||
max_volume blob not null -- big-endian 32-byte U256
|
|
||||||
) STRICT;
|
|
||||||
|
|
||||||
-- Log table for token transfer grant usage
|
|
||||||
create table if not exists evm_token_transfer_log (
|
|
||||||
id integer not null primary key,
|
|
||||||
grant_id integer not null references evm_token_transfer_grant(id) on delete restrict,
|
|
||||||
log_id integer not null references evm_transaction_log(id) on delete restrict,
|
|
||||||
chain_id integer not null, -- EIP-155 chain ID
|
|
||||||
token_contract blob not null, -- 20-byte ERC20 contract address
|
|
||||||
recipient_address blob not null, -- 20-byte recipient address
|
|
||||||
value blob not null, -- big-endian 32-byte U256
|
|
||||||
created_at integer not null default(unixepoch('now'))
|
|
||||||
) STRICT;
|
|
||||||
|
|
||||||
create index if not exists idx_token_transfer_log_grant on evm_token_transfer_log(grant_id);
|
|
||||||
create index if not exists idx_token_transfer_log_log_id on evm_token_transfer_log(log_id);
|
|
||||||
create index if not exists idx_token_transfer_log_chain on evm_token_transfer_log(chain_id);
|
|
||||||
|
|
||||||
|
|
||||||
-- ===============================
|
|
||||||
-- Ether transfer grant (uses base log)
|
|
||||||
-- ===============================
|
|
||||||
create table if not exists evm_ether_transfer_grant (
|
|
||||||
id integer not null primary key,
|
|
||||||
basic_grant_id integer not null unique references evm_basic_grant(id) on delete cascade,
|
|
||||||
limit_id integer not null references evm_ether_transfer_limit(id) on delete restrict
|
|
||||||
) STRICT;
|
|
||||||
|
|
||||||
-- Specific recipient addresses for an ether transfer grant
|
|
||||||
create table if not exists evm_ether_transfer_grant_target (
|
|
||||||
id integer not null primary key,
|
|
||||||
grant_id integer not null references evm_ether_transfer_grant(id) on delete cascade,
|
|
||||||
address blob not null -- 20-byte recipient address
|
|
||||||
) STRICT;
|
|
||||||
|
|
||||||
create unique index if not exists uniq_ether_transfer_target on evm_ether_transfer_grant_target(grant_id, address);
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-- Remove argon2_salt column
|
||||||
|
ALTER TABLE aead_encrypted DROP COLUMN argon2_salt;
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-- Add argon2_salt column to store password derivation salt
|
||||||
|
ALTER TABLE aead_encrypted ADD COLUMN argon2_salt TEXT;
|
||||||
2
server/crates/arbiter-server/src/actors.rs
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
pub mod user_agent;
|
||||||
|
pub mod client;
|
||||||
12
server/crates/arbiter-server/src/actors/client.rs
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
use arbiter_proto::{
|
||||||
|
proto::{ClientRequest, ClientResponse},
|
||||||
|
transport::Bi,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::ServerContext;
|
||||||
|
|
||||||
|
pub(crate) async fn handle_client(
|
||||||
|
_context: ServerContext,
|
||||||
|
_bistream: impl Bi<ClientRequest, ClientResponse>,
|
||||||
|
) {
|
||||||
|
}
|
||||||
@@ -1,251 +0,0 @@
|
|||||||
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,
|
|
||||||
};
|
|
||||||
use diesel::{
|
|
||||||
ExpressionMethods as _, OptionalExtension as _, QueryDsl as _, dsl::insert_into, update,
|
|
||||||
};
|
|
||||||
use diesel_async::RunQueryDsl as _;
|
|
||||||
use ed25519_dalek::VerifyingKey;
|
|
||||||
use kameo::error::SendError;
|
|
||||||
use tracing::error;
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
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 approval request failed")]
|
|
||||||
ApproveError(#[from] ApproveError),
|
|
||||||
#[error("Internal error")]
|
|
||||||
InternalError,
|
|
||||||
#[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),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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>, Error> {
|
|
||||||
let pubkey_bytes = pubkey.as_bytes().to_vec();
|
|
||||||
|
|
||||||
let mut conn = db.get().await.map_err(|e| {
|
|
||||||
error!(error = ?e, "Database pool error");
|
|
||||||
Error::DatabasePoolUnavailable
|
|
||||||
})?;
|
|
||||||
|
|
||||||
conn.exclusive_transaction(|conn| {
|
|
||||||
let pubkey_bytes = pubkey_bytes.clone();
|
|
||||||
Box::pin(async move {
|
|
||||||
let Some(current_nonce) = program_client::table
|
|
||||||
.filter(program_client::public_key.eq(&pubkey_bytes))
|
|
||||||
.select(program_client::nonce)
|
|
||||||
.first::<i32>(conn)
|
|
||||||
.await
|
|
||||||
.optional()?
|
|
||||||
else {
|
|
||||||
return Result::<_, diesel::result::Error>::Ok(None);
|
|
||||||
};
|
|
||||||
|
|
||||||
update(program_client::table)
|
|
||||||
.filter(program_client::public_key.eq(&pubkey_bytes))
|
|
||||||
.set(program_client::nonce.eq(current_nonce + 1))
|
|
||||||
.execute(conn)
|
|
||||||
.await?;
|
|
||||||
|
|
||||||
Ok(Some(current_nonce))
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.map_err(|e| {
|
|
||||||
error!(error = ?e, "Database error");
|
|
||||||
Error::DatabaseOperationFailed
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
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))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn insert_client(db: &db::DatabasePool, pubkey: &VerifyingKey) -> Result<(), 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
|
|
||||||
})?;
|
|
||||||
|
|
||||||
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
|
|
||||||
.map_err(|e| {
|
|
||||||
error!(error = ?e, "Failed to insert new client");
|
|
||||||
Error::DatabaseOperationFailed
|
|
||||||
})?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn challenge_client(
|
|
||||||
props: &mut ClientConnection,
|
|
||||||
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())),
|
|
||||||
}))
|
|
||||||
.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
|
|
||||||
})?;
|
|
||||||
|
|
||||||
pubkey.verify_strict(&formatted, &sig).map_err(|_| {
|
|
||||||
error!("Challenge solution verification failed");
|
|
||||||
Error::InvalidChallengeSolution
|
|
||||||
})?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn connect_error_code(err: &Error) -> ConnectErrorCode {
|
|
||||||
match err {
|
|
||||||
Error::ApproveError(ApproveError::Denied) => ConnectErrorCode::ApprovalDenied,
|
|
||||||
Error::ApproveError(ApproveError::Upstream(router::ApprovalError::NoUserAgentsConnected)) => {
|
|
||||||
ConnectErrorCode::NoUserAgentsOnline
|
|
||||||
}
|
|
||||||
_ => ConnectErrorCode::Unknown,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn authenticate(props: &mut ClientConnection) -> Result<VerifyingKey, Error> {
|
|
||||||
let Some(ClientRequest {
|
|
||||||
payload: Some(ClientRequestPayload::AuthChallengeRequest(challenge)),
|
|
||||||
}) = props.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 nonce = match get_nonce(&props.db, &pubkey).await? {
|
|
||||||
Some(nonce) => nonce,
|
|
||||||
None => {
|
|
||||||
approve_new_client(&props.actors, pubkey).await?;
|
|
||||||
insert_client(&props.db, &pubkey).await?;
|
|
||||||
0
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
challenge_client(props, pubkey, nonce).await?;
|
|
||||||
|
|
||||||
Ok(pubkey)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn authenticate_and_create(mut props: ClientConnection) -> Result<ClientSession, Error> {
|
|
||||||
match authenticate(&mut props).await {
|
|
||||||
Ok(pubkey) => Ok(ClientSession::new(props, pubkey)),
|
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
use arbiter_proto::{
|
|
||||||
proto::client::{ClientRequest, ClientResponse},
|
|
||||||
transport::Bi,
|
|
||||||
};
|
|
||||||
use kameo::actor::Spawn;
|
|
||||||
use tracing::{error, info};
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
actors::{GlobalActors, client::session::ClientSession},
|
|
||||||
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 mod auth;
|
|
||||||
pub mod session;
|
|
||||||
|
|
||||||
pub async fn connect_client(props: ClientConnection) {
|
|
||||||
match auth::authenticate_and_create(props).await {
|
|
||||||
Ok(session) => {
|
|
||||||
ClientSession::spawn(session);
|
|
||||||
info!("Client authenticated, session started");
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
error!(?err, "Authentication failed, closing connection");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
use arbiter_proto::proto::client::{ClientRequest, ClientResponse};
|
|
||||||
use ed25519_dalek::VerifyingKey;
|
|
||||||
use kameo::Actor;
|
|
||||||
use tokio::select;
|
|
||||||
use tracing::{error, info};
|
|
||||||
|
|
||||||
use crate::{actors::{
|
|
||||||
GlobalActors, client::{ClientError, ClientConnection}, router::RegisterClient
|
|
||||||
}, db};
|
|
||||||
|
|
||||||
pub struct ClientSession {
|
|
||||||
props: ClientConnection,
|
|
||||||
key: VerifyingKey,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ClientSession {
|
|
||||||
pub(crate) fn new(props: ClientConnection, key: VerifyingKey) -> Self {
|
|
||||||
Self { props, key }
|
|
||||||
}
|
|
||||||
|
|
||||||
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 {
|
|
||||||
_ => Err(ClientError::UnexpectedRequestPayload),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Output = Result<ClientResponse, ClientError>;
|
|
||||||
|
|
||||||
impl Actor for ClientSession {
|
|
||||||
type Args = Self;
|
|
||||||
|
|
||||||
type Error = ClientError;
|
|
||||||
|
|
||||||
async fn on_start(
|
|
||||||
args: Self::Args,
|
|
||||||
this: kameo::prelude::ActorRef<Self>,
|
|
||||||
) -> Result<Self, Self::Error> {
|
|
||||||
args.props
|
|
||||||
.actors
|
|
||||||
.router
|
|
||||||
.ask(RegisterClient { actor: this })
|
|
||||||
.await
|
|
||||||
.map_err(|_| ClientError::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);
|
|
||||||
let key = VerifyingKey::from_bytes(&[0u8; 32]).unwrap();
|
|
||||||
Self { props, key }
|
|
||||||
}
|
|
||||||
}
|
|
||||||