├── src ├── idempotent-proxy-cf-worker │ ├── .env │ ├── eslint.config.js │ ├── .prettierrc.json │ ├── .dev.vars │ ├── tsconfig.json │ ├── src │ │ ├── index.test.ts │ │ ├── auth.ts │ │ ├── util.ts │ │ └── index.ts │ ├── package.json │ ├── wrangler.toml │ ├── .eslintrc.js │ └── README.md ├── idempotent-proxy-types │ ├── Cargo.toml │ ├── src │ │ ├── lib.rs │ │ └── auth.rs │ └── README.md ├── idempotent-proxy-canister │ ├── Cargo.toml │ ├── src │ │ ├── tasks.rs │ │ ├── ecdsa.rs │ │ ├── lib.rs │ │ ├── cose.rs │ │ ├── cycles.rs │ │ ├── agent.rs │ │ ├── api_admin.rs │ │ ├── init.rs │ │ ├── store.rs │ │ └── api.rs │ ├── idempotent-proxy-canister.did │ └── README.md └── idempotent-proxy-server │ ├── Cargo.toml │ ├── src │ ├── cache │ │ ├── redis.rs │ │ ├── memory.rs │ │ └── mod.rs │ ├── main.rs │ └── handler.rs │ └── README.md ├── idempotent-proxy.webp ├── canister_ids.json ├── idempotent-proxy-canister.webp ├── idempotent-proxy-cf-worker.webp ├── examples ├── eth-canister-lite │ ├── eth-canister-lite.did │ ├── Cargo.toml │ ├── README.md │ ├── dfx.json │ └── src │ │ ├── lib.rs │ │ └── jsonrpc.rs └── eth-canister │ ├── dfx.json │ ├── Cargo.toml │ ├── eth-canister.did │ ├── src │ ├── tasks.rs │ ├── lib.rs │ ├── init.rs │ ├── jsonrpc.rs │ ├── ecdsa.rs │ ├── agent.rs │ └── store.rs │ └── README.md ├── enclave ├── .env ├── setup.sh ├── supervisord.conf ├── amd64.Dockerfile └── arm64.Dockerfile ├── .github └── workflows │ ├── publish-crates.yml │ ├── test.yml │ ├── release.yml │ └── build-dockers.yml ├── linux.Dockerfile ├── .gitignore ├── dfx.json ├── .env ├── LICENSE-MIT ├── Makefile ├── Cargo.toml ├── Dockerfile ├── LICENSE-APACHE └── README.md /src/idempotent-proxy-cf-worker/.env: -------------------------------------------------------------------------------- 1 | WRANGLER_LOG=debug 2 | -------------------------------------------------------------------------------- /idempotent-proxy.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ldclabs/idempotent-proxy/HEAD/idempotent-proxy.webp -------------------------------------------------------------------------------- /canister_ids.json: -------------------------------------------------------------------------------- 1 | { 2 | "idempotent-proxy-canister": { 3 | "ic": "hpudd-yqaaa-aaaap-ahnbq-cai" 4 | } 5 | } -------------------------------------------------------------------------------- /idempotent-proxy-canister.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ldclabs/idempotent-proxy/HEAD/idempotent-proxy-canister.webp -------------------------------------------------------------------------------- /idempotent-proxy-cf-worker.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ldclabs/idempotent-proxy/HEAD/idempotent-proxy-cf-worker.webp -------------------------------------------------------------------------------- /src/idempotent-proxy-cf-worker/eslint.config.js: -------------------------------------------------------------------------------- 1 | import eslintConfigPrettier from "eslint-config-prettier" 2 | 3 | export default [ 4 | eslintConfigPrettier, 5 | ] -------------------------------------------------------------------------------- /examples/eth-canister-lite/eth-canister-lite.did: -------------------------------------------------------------------------------- 1 | type Result = variant { Ok : text; Err : text }; 2 | service : { eth_chain_id : () -> (Result); get_best_block : () -> (Result) } 3 | -------------------------------------------------------------------------------- /src/idempotent-proxy-cf-worker/.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "htmlWhitespaceSensitivity": "strict", 3 | "quoteProps": "preserve", 4 | "semi": false, 5 | "trailingComma": "none", 6 | "singleQuote": true 7 | } -------------------------------------------------------------------------------- /src/idempotent-proxy-cf-worker/.dev.vars: -------------------------------------------------------------------------------- 1 | # ECDSA_PUB_KEY_1="AnaAOT8AfspCg9Y68nICPNuecvPpw4Dv8u3rU0dDlO3P" 2 | # ECDSA_PUB_KEY_2="xxxxxx" 3 | 4 | URL_HTTPBIN="https://httpbin.org/get?api-key=abc123" 5 | # URL_XXX=... 6 | 7 | HEADER_TOKEN="Bearer xyz123456" 8 | # HEADER_XXX=... 9 | -------------------------------------------------------------------------------- /src/idempotent-proxy-cf-worker/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "noEmit": true, 4 | "module": "esnext", 5 | "target": "esnext", 6 | "lib": ["esnext"], 7 | "strict": true, 8 | "moduleResolution": "node", 9 | "types": ["@cloudflare/workers-types"] 10 | }, 11 | "exclude": ["node_modules", "dist", "test"] 12 | } 13 | -------------------------------------------------------------------------------- /enclave/.env: -------------------------------------------------------------------------------- 1 | SERVER_ADDR=127.0.0.1:8080 2 | POLL_INTERVAL=100 # in milliseconds 3 | REQUEST_TIMEOUT=20000 # in milliseconds 4 | LOG_LEVEL=warn # debug, info, warn, error 5 | # cert file path to enable https, for example: /etc/https/mydomain.crt 6 | TLS_CERT_FILE = "" 7 | # key file path to enable https, for example: /etc/https/mydomain.key 8 | TLS_KEY_FILE = "" 9 | -------------------------------------------------------------------------------- /.github/workflows/publish-crates.yml: -------------------------------------------------------------------------------- 1 | name: Crates 2 | on: 3 | push: 4 | tags: 5 | - 'v*' 6 | jobs: 7 | publish: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v4 11 | - uses: katyo/publish-crates@v2 12 | with: 13 | registry-token: ${{ secrets.CARGO_REGISTRY_TOKEN }} 14 | ignore-unpublished-changes: true 15 | -------------------------------------------------------------------------------- /examples/eth-canister/dfx.json: -------------------------------------------------------------------------------- 1 | { 2 | "canisters": { 3 | "eth-canister": { 4 | "candid": "eth-canister.did", 5 | "package": "eth-canister", 6 | "crate": "eth_canister", 7 | "type": "rust" 8 | } 9 | }, 10 | "defaults": { 11 | "build": { 12 | "args": "", 13 | "packtool": "" 14 | } 15 | }, 16 | "output_env_file": ".env", 17 | "version": 1 18 | } -------------------------------------------------------------------------------- /examples/eth-canister-lite/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "eth-canister-lite" 3 | version = "0.1.0" 4 | edition = "2021" 5 | publish = false 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [lib] 10 | crate-type = ["cdylib"] 11 | 12 | [dependencies] 13 | candid = "0.10" 14 | ic-cdk = "0.14" 15 | serde = { workspace = true } 16 | serde_json = { workspace = true } 17 | -------------------------------------------------------------------------------- /linux.Dockerfile: -------------------------------------------------------------------------------- 1 | # syntax=docker/dockerfile:1 2 | 3 | FROM --platform=$BUILDPLATFORM rust:slim-bookworm AS builder 4 | 5 | RUN apt-get update \ 6 | && apt-get install -y gcc g++ libc6-dev pkg-config libssl-dev 7 | 8 | WORKDIR /src 9 | COPY src ./src 10 | COPY Cargo.toml Cargo.lock ./ 11 | RUN cargo build --release --locked -p idempotent-proxy-server 12 | RUN ls target/release 13 | 14 | FROM scratch AS exporter 15 | WORKDIR /app 16 | COPY --from=builder /src/target/release/idempotent-proxy-server ./ 17 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | on: 3 | push: 4 | branches: [ "main" ] 5 | pull_request: 6 | branches: [ "main" ] 7 | jobs: 8 | test: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v4 12 | - name: Run clippy 13 | run: cargo clippy --verbose --all-targets --all-features 14 | - name: Run tests 15 | run: cargo test --verbose --workspace -- --nocapture 16 | - name: Run all tests 17 | run: cargo test --verbose --workspace -- --nocapture --include-ignored 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | debug/ 4 | target/ 5 | node_modules/ 6 | 7 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 8 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 9 | Cargo.lock 10 | 11 | # These are backup files generated by rustfmt 12 | **/*.rs.bk 13 | 14 | # MSVC Windows builds of rustc generate these, which store debugging information 15 | *.pdb 16 | debug 17 | .wrangler 18 | .dfx 19 | .dfx_env 20 | 21 | examples/**/.env 22 | src/**/.env -------------------------------------------------------------------------------- /dfx.json: -------------------------------------------------------------------------------- 1 | { 2 | "canisters": { 3 | "idempotent-proxy-canister": { 4 | "candid": "src/idempotent-proxy-canister/idempotent-proxy-canister.did", 5 | "declarations": { 6 | "node_compatibility": true 7 | }, 8 | "package": "idempotent-proxy-canister", 9 | "crate": "idempotent_proxy_canister", 10 | "optimize": "cycles", 11 | "gzip": true, 12 | "type": "rust" 13 | } 14 | }, 15 | "defaults": { 16 | "build": { 17 | "args": "", 18 | "packtool": "" 19 | } 20 | }, 21 | "output_env_file": ".dfx_env", 22 | "version": 1 23 | } -------------------------------------------------------------------------------- /examples/eth-canister/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "eth-canister" 3 | version = "0.1.0" 4 | edition = "2021" 5 | publish = false 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [lib] 10 | crate-type = ["cdylib"] 11 | 12 | [dependencies] 13 | async-trait = "0.1" 14 | candid = "0.10" 15 | ic-cdk = "0.14" 16 | ic-cdk-timers = "0.8" 17 | ic-stable-structures = "0.6" 18 | # getrandom = { version = "0.2", features = ["custom"] } 19 | base64 = { workspace = true } 20 | ciborium = { workspace = true } 21 | serde = { workspace = true } 22 | serde_json = { workspace = true } 23 | serde_bytes = { workspace = true } 24 | sha3 = { workspace = true } 25 | -------------------------------------------------------------------------------- /src/idempotent-proxy-cf-worker/src/index.test.ts: -------------------------------------------------------------------------------- 1 | import { unstable_dev } from 'wrangler' 2 | import type { UnstableDevWorker } from 'wrangler' 3 | import { describe, expect, it, beforeAll, afterAll } from 'vitest' 4 | 5 | describe('Worker', () => { 6 | let worker: UnstableDevWorker 7 | 8 | beforeAll(async () => { 9 | worker = await unstable_dev('src/index.ts', { 10 | experimental: { disableExperimentalWarning: true } 11 | }) 12 | }) 13 | 14 | afterAll(async () => { 15 | await worker.stop() 16 | }) 17 | 18 | it('should ok', async () => { 19 | const resp = await worker.fetch() 20 | expect(resp.status).toBe(200) 21 | const text = await resp.text() 22 | expect(text).toBe('idempotent-proxy-cf-worker') 23 | }) 24 | }) 25 | -------------------------------------------------------------------------------- /examples/eth-canister/eth-canister.did: -------------------------------------------------------------------------------- 1 | type ChainArgs = variant { Upgrade : record {}; Init : InitArgs }; 2 | type InitArgs = record { ecdsa_key_name : text }; 3 | type RPCAgent = record { 4 | proxy_token : opt text; 5 | api_token : opt text; 6 | endpoint : text; 7 | name : text; 8 | max_cycles : nat64; 9 | }; 10 | type Result = variant { Ok; Err : text }; 11 | type Result_1 = variant { Ok : text; Err : text }; 12 | type Result_2 = variant { Ok : State; Err }; 13 | type State = record { 14 | ecdsa_key_name : text; 15 | rpc_proxy_public_key : text; 16 | rpc_agents : vec RPCAgent; 17 | }; 18 | service : (opt ChainArgs) -> { 19 | admin_set_agents : (vec RPCAgent) -> (Result); 20 | eth_chain_id : () -> (Result_1); 21 | get_best_block : () -> (Result_1); 22 | get_state : () -> (Result_2) query; 23 | } 24 | -------------------------------------------------------------------------------- /examples/eth-canister-lite/README.md: -------------------------------------------------------------------------------- 1 | # Example: `eth-canister-lite` 2 | 3 | ## Running the project locally 4 | 5 | If you want to test your project locally, you can use the following commands: 6 | 7 | ```bash 8 | cd examples/eth-canister-lite 9 | # Starts the replica, running in the background 10 | dfx start --background 11 | 12 | # deploy the canister 13 | dfx deploy eth-canister-lite 14 | 15 | dfx canister call eth-canister-lite eth_chain_id '()' 16 | 17 | dfx canister call eth-canister-lite get_best_block '()' 18 | ``` 19 | 20 | `idempotent-proxy-cf-worker` does not enable `proxy-authorization`, so it can be accessed. 21 | 22 | ## License 23 | Copyright © 2024 [LDC Labs](https://github.com/ldclabs). 24 | 25 | `ldclabs/idempotent-proxy` is licensed under the MIT License. See [LICENSE](../../LICENSE-MIT) for the full license text. -------------------------------------------------------------------------------- /.env: -------------------------------------------------------------------------------- 1 | SERVER_ADDR=127.0.0.1:8080 2 | # if not set, use in-memory cache 3 | # REDIS_URL=127.0.0.1:6379 4 | POLL_INTERVAL=100 # in milliseconds 5 | REQUEST_TIMEOUT=30000 # in milliseconds 6 | LOG_LEVEL=info # debug, info, warn, error 7 | # cert file path to enable https, for example: /etc/https/mydomain.crt 8 | TLS_CERT_FILE = "" 9 | # key file path to enable https, for example: /etc/https/mydomain.key 10 | TLS_KEY_FILE = "" 11 | 12 | # ECDSA_PUB_KEY_1="A6t1U8kc10AbLJ3-V1avU4rYvmAsYjXuzY0kPublttot" # ECDSA/secp256k1 13 | # ECDSA_PUB_KEY_2="xxxxxx" 14 | 15 | # ALLOW_AGENTS="agent1,agent2" 16 | 17 | URL_HTTPBIN="https://httpbin.org/get?api-key=abc123" 18 | # URL_DOGE_TEST="http://192.168.1.80:44555/" 19 | # URL_XXX=... 20 | 21 | # HEADER_API_TOKEN="Basic SUNQYW5kYTpJVEZDNlJjam56RkdEQnd0SzByYV9kS0swR29lSElqVUl3V2lEb3VrRWU0" 22 | # HEADER_XXX=... 23 | -------------------------------------------------------------------------------- /examples/eth-canister-lite/dfx.json: -------------------------------------------------------------------------------- 1 | { 2 | "canisters": { 3 | "eth-canister-lite": { 4 | "candid": "eth-canister-lite.did", 5 | "package": "eth-canister-lite", 6 | "crate": "eth_canister_lite", 7 | "type": "rust" 8 | }, 9 | "idempotent-proxy-canister": { 10 | "candid": "https://github.com/ldclabs/idempotent-proxy/releases/download/v1.0.3/idempotent_proxy_canister.did", 11 | "type": "custom", 12 | "wasm": "https://github.com/ldclabs/idempotent-proxy/releases/download/v1.0.3/idempotent_proxy_canister.wasm.gz", 13 | "metadata": [ 14 | { 15 | "name": "candid:service" 16 | } 17 | ] 18 | } 19 | }, 20 | "defaults": { 21 | "build": { 22 | "args": "", 23 | "packtool": "" 24 | } 25 | }, 26 | "output_env_file": ".env", 27 | "version": 1 28 | } -------------------------------------------------------------------------------- /src/idempotent-proxy-types/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "idempotent-proxy-types" 3 | description = "types of idempotent-proxy" 4 | repository = "https://github.com/ldclabs/idempotent-proxy/tree/main/src/idempotent-proxy-types" 5 | publish = true 6 | 7 | version.workspace = true 8 | edition.workspace = true 9 | keywords.workspace = true 10 | categories.workspace = true 11 | license.workspace = true 12 | 13 | [lib] 14 | 15 | [dependencies] 16 | http = { workspace = true } 17 | serde = { workspace = true } 18 | serde_bytes = { workspace = true } 19 | ciborium = { workspace = true } 20 | k256 = { workspace = true } 21 | ed25519-dalek = { workspace = true } 22 | sha3 = { workspace = true } 23 | 24 | [dev-dependencies] 25 | base64 = { workspace = true } 26 | rand_core = "0.6" 27 | hex = { package = "hex-conservative", version = "0.2", default-features = false, features = [ 28 | "alloc", 29 | ] } 30 | -------------------------------------------------------------------------------- /src/idempotent-proxy-canister/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "idempotent-proxy-canister" 3 | description = "A ICP canister Make Idempotent Proxy service on-chain." 4 | repository = "https://github.com/ldclabs/idempotent-proxy/tree/main/src/idempotent-proxy-canister" 5 | publish = false 6 | 7 | version.workspace = true 8 | edition.workspace = true 9 | keywords.workspace = true 10 | categories.workspace = true 11 | license.workspace = true 12 | 13 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 14 | 15 | [lib] 16 | crate-type = ["cdylib"] 17 | 18 | [dependencies] 19 | http = { workspace = true } 20 | base64 = { workspace = true } 21 | ciborium = { workspace = true } 22 | futures = { workspace = true } 23 | serde = { workspace = true } 24 | serde_bytes = { workspace = true } 25 | candid = "0.10" 26 | ic-cdk = "0.16" 27 | ic-cdk-timers = "0.10" 28 | ic-stable-structures = "0.6" 29 | ic_cose_types = "0.3" 30 | getrandom = { version = "0.2", features = ["custom"] } 31 | -------------------------------------------------------------------------------- /src/idempotent-proxy-cf-worker/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "idempotent-proxy-cf-worker", 3 | "version": "1.2.2", 4 | "publish": false, 5 | "description": "Reverse proxy server with build-in idempotency support runing as a Cloudflare Worker.", 6 | "homepage": "https://github.com/ldclabs/idempotent-proxy/tree/main/src/idempotent-proxy-cf-worker", 7 | "scripts": { 8 | "deploy": "wrangler deploy src/index.ts", 9 | "dev": "wrangler dev", 10 | "start": "wrangler dev", 11 | "test": "vitest run" 12 | }, 13 | "devDependencies": { 14 | "@cloudflare/workers-types": "^4.20241018.0", 15 | "@types/eslint": "^9.6.1", 16 | "@typescript-eslint/eslint-plugin": "^8.10.0", 17 | "@typescript-eslint/parser": "^8.10.0", 18 | "eslint": "^9.13.0", 19 | "eslint-config-prettier": "^9.1.0", 20 | "eslint-plugin-import": "^2.31.0", 21 | "eslint-plugin-prettier": "^5.2.1", 22 | "prettier": "^3.3.3", 23 | "typescript": "^5.6.3", 24 | "vitest": "^2.1.3", 25 | "wrangler": "^3.81.0" 26 | }, 27 | "dependencies": { 28 | "@noble/curves": "^1.6.0", 29 | "@noble/hashes": "^1.5.0", 30 | "cborg": "^4.2.4" 31 | } 32 | } -------------------------------------------------------------------------------- /src/idempotent-proxy-cf-worker/wrangler.toml: -------------------------------------------------------------------------------- 1 | name = "idempotent-proxy-cf-worker" 2 | main = "./src/index.ts" 3 | compatibility_date = "2024-04-03" 4 | 5 | [dev] 6 | port = 8080 7 | 8 | # Variable bindings. These are arbitrary, plaintext strings (similar to environment variables) 9 | # Note: Use secrets to store sensitive data. 10 | # Docs: https://developers.cloudflare.com/workers/platform/environment-variables 11 | [vars] 12 | POLL_INTERVAL = 100 # in milliseconds 13 | REQUEST_TIMEOUT = 20000 # in milliseconds 14 | ALLOW_AGENTS = [] # Optional: List of allowed agents, ["agent1", "agent2"] 15 | 16 | # Bind a Durable Object. Durable objects are a scale-to-zero compute primitive based on the actor model. 17 | # Durable Objects can live for as long as needed. Use these when you need a long-running "server", such as in realtime apps. 18 | # Docs: https://developers.cloudflare.com/workers/runtime-apis/durable-objects 19 | [[durable_objects.bindings]] 20 | name = "CACHER" 21 | class_name = "Cacher" 22 | 23 | [[migrations]] 24 | tag = "v1" # Should be unique for each entry 25 | new_classes = ["Cacher"] 26 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 LDC Labs 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /examples/eth-canister-lite/src/lib.rs: -------------------------------------------------------------------------------- 1 | mod jsonrpc; 2 | 3 | use candid::Principal; 4 | 5 | use crate::jsonrpc::EthereumRPC; 6 | 7 | #[ic_cdk::update] 8 | async fn eth_chain_id() -> Result { 9 | let rpc = EthereumRPC { 10 | provider: "URL_CF_ETH".to_string(), 11 | proxy: Principal::from_text("hpudd-yqaaa-aaaap-ahnbq-cai") 12 | .map_err(|err| err.to_string())?, 13 | api_token: None, 14 | }; 15 | let res = rpc.eth_chain_id("eth_chain_id".to_string()).await?; 16 | Ok(res) 17 | } 18 | 19 | #[ic_cdk::update] 20 | async fn get_best_block() -> Result { 21 | let rpc = EthereumRPC { 22 | provider: "https://rpc.ankr.com/eth".to_string(), 23 | proxy: Principal::from_text("hpudd-yqaaa-aaaap-ahnbq-cai") 24 | .map_err(|err| err.to_string())?, 25 | api_token: None, 26 | }; 27 | let ts = ic_cdk::api::time() / 1_000_000_000; 28 | let key = format!("blk-best-{ts}"); 29 | let res = rpc.get_best_block(key).await?; 30 | let res = serde_json::to_string(&res).map_err(|e| e.to_string())?; 31 | Ok(res) 32 | } 33 | 34 | ic_cdk::export_candid!(); 35 | -------------------------------------------------------------------------------- /src/idempotent-proxy-types/src/lib.rs: -------------------------------------------------------------------------------- 1 | use http::header::HeaderName; 2 | use std::time::{SystemTime, UNIX_EPOCH}; 3 | 4 | pub mod auth; 5 | 6 | pub static HEADER_PROXY_AUTHORIZATION: HeaderName = HeaderName::from_static("proxy-authorization"); 7 | pub static HEADER_X_FORWARDED_FOR: HeaderName = HeaderName::from_static("x-forwarded-for"); 8 | pub static HEADER_X_FORWARDED_HOST: HeaderName = HeaderName::from_static("x-forwarded-host"); 9 | pub static HEADER_X_FORWARDED_PROTO: HeaderName = HeaderName::from_static("x-forwarded-proto"); 10 | pub static HEADER_IDEMPOTENCY_KEY: HeaderName = HeaderName::from_static("idempotency-key"); 11 | pub static HEADER_X_JSON_MASK: HeaderName = HeaderName::from_static("x-json-mask"); 12 | pub static HEADER_RESPONSE_HEADERS: HeaderName = HeaderName::from_static("response-headers"); 13 | 14 | pub fn err_string(err: impl std::fmt::Display) -> String { 15 | err.to_string() 16 | } 17 | 18 | /// Returns the current unix timestamp in milliseconds. 19 | pub fn unix_ms() -> u64 { 20 | let ts = SystemTime::now() 21 | .duration_since(UNIX_EPOCH) 22 | .expect("system time before Unix epoch"); 23 | ts.as_millis() as u64 24 | } 25 | -------------------------------------------------------------------------------- /enclave/setup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # setting an address for loopback 4 | ifconfig lo 127.0.0.1 5 | ifconfig 6 | 7 | # Debian: failed to initialize nft: Protocol not supported 8 | update-alternatives --set iptables /usr/sbin/iptables-legacy 9 | # update-alternatives --set ip6tables /usr/sbin/ip6tables-legacy 10 | # update-alternatives --set arptables /usr/sbin/arptables-legacy 11 | # update-alternatives --set ebtables /usr/sbin/ebtables-legacy 12 | 13 | # adding a default route 14 | ip route add default via 127.0.0.1 dev lo 15 | route -n 16 | 17 | # iptables rules to route traffic to transparent proxy 18 | iptables -A OUTPUT -t nat -p tcp --dport 1:65535 ! -d 127.0.0.1 -j DNAT --to-destination 127.0.0.1:1200 19 | # replace the source address with 127.0.0.1 for outgoing packets with a source of 0.0.0.0 20 | # ensures returning packets have 127.0.0.1 as the destination and not 0.0.0.0 21 | iptables -t nat -A POSTROUTING -o lo -s 0.0.0.0 -j SNAT --to-source 127.0.0.1 22 | iptables -L -t nat -v -n 23 | 24 | # generate identity key 25 | /app/keygen --secret /app/id.sec --public /app/id.pub 26 | 27 | # your custom setup goes here 28 | 29 | # starting supervisord 30 | cat /etc/supervisord.conf 31 | /app/supervisord 32 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | on: 3 | push: 4 | tags: 5 | - 'v*' 6 | jobs: 7 | test: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v4 11 | - uses: Swatinem/rust-cache@v2 12 | # - uses: dfinity/setup-dfx@main 13 | - name: Build canisters 14 | run: | 15 | rustup target add wasm32-unknown-unknown 16 | cargo install ic-wasm 17 | mkdir out 18 | cargo build --target wasm32-unknown-unknown --release --locked -p idempotent-proxy-canister 19 | CAN="idempotent_proxy_canister" 20 | cp "target/wasm32-unknown-unknown/release/$CAN.wasm" out/ 21 | cp src/idempotent-proxy-canister/idempotent-proxy-canister.did "out/$CAN.did" 22 | ic-wasm "out/$CAN.wasm" -o "out/$CAN.wasm" metadata candid:service -f "out/$CAN.did" -v public 23 | ic-wasm "out/$CAN.wasm" -o "out/$CAN.wasm" shrink 24 | ic-wasm "out/$CAN.wasm" -o "out/$CAN.wasm" optimize O3 --inline-functions-with-loops 25 | gzip "out/$CAN.wasm" 26 | SHA256="$(sha256sum < "out/$CAN.wasm.gz" | sed 's/ .*$//g')" 27 | echo $SHA256 > "out/$CAN.wasm.gz.$SHA256.txt" 28 | ls -lah out 29 | - name: Release 30 | uses: softprops/action-gh-release@v2 31 | with: 32 | files: out/* 33 | -------------------------------------------------------------------------------- /examples/eth-canister/src/tasks.rs: -------------------------------------------------------------------------------- 1 | use std::collections::BTreeMap; 2 | 3 | use crate::{agent, ecdsa, store, SECONDS}; 4 | 5 | pub const REFRESH_PROXY_TOKEN_INTERVAL: u64 = 60 * 60; // 60 minutes 6 | 7 | pub async fn refresh_proxy_token() { 8 | let (ecdsa_key_name, rpc_agent) = 9 | store::state::with(|s| (s.ecdsa_key_name.clone(), s.rpc_agents.clone())); 10 | update_proxy_token(ecdsa_key_name, rpc_agent).await; 11 | } 12 | 13 | pub async fn update_proxy_token(ecdsa_key_name: String, mut rpc_agents: Vec) { 14 | if rpc_agents.is_empty() { 15 | return; 16 | } 17 | 18 | let mut tokens: BTreeMap = BTreeMap::new(); 19 | for agent in rpc_agents.iter_mut() { 20 | if let Some(token) = tokens.get(&agent.name) { 21 | agent.proxy_token = Some(token.clone()); 22 | continue; 23 | } 24 | 25 | let token = ecdsa::sign_proxy_token( 26 | &ecdsa_key_name, 27 | (ic_cdk::api::time() / SECONDS) + REFRESH_PROXY_TOKEN_INTERVAL + 120, 28 | &agent.name, 29 | ) 30 | .await 31 | .expect("failed to sign proxy token"); 32 | tokens.insert(agent.name.clone(), token.clone()); 33 | agent.proxy_token = Some(token); 34 | } 35 | 36 | store::state::with_mut(|r| r.rpc_agents = rpc_agents); 37 | } 38 | -------------------------------------------------------------------------------- /src/idempotent-proxy-server/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "idempotent-proxy-server" 3 | description = "Idempotent proxy server" 4 | repository = "https://github.com/ldclabs/idempotent-proxy/tree/main/src/idempotent-proxy-server" 5 | publish = true 6 | 7 | version.workspace = true 8 | edition.workspace = true 9 | keywords.workspace = true 10 | categories.workspace = true 11 | license.workspace = true 12 | 13 | [[bin]] 14 | name = "idempotent-proxy-server" 15 | 16 | [dependencies] 17 | axum = { workspace = true } 18 | axum-server = { workspace = true } 19 | tokio = { workspace = true } 20 | futures = { workspace = true } 21 | reqwest = { workspace = true } 22 | dotenvy = { workspace = true } 23 | log = { workspace = true } 24 | structured-logger = { workspace = true } 25 | http = { workspace = true } 26 | rustis = { workspace = true } 27 | async-trait = { workspace = true } 28 | serde = { workspace = true } 29 | serde_bytes = { workspace = true } 30 | serde_json = { workspace = true } 31 | ciborium = { workspace = true } 32 | k256 = { workspace = true } 33 | ed25519-dalek = { workspace = true } 34 | base64 = { workspace = true } 35 | idempotent-proxy-types = { path = "../idempotent-proxy-types", version = "1" } 36 | 37 | [dev-dependencies] 38 | hex = { package = "hex-conservative", version = "0.2", default-features = false, features = [ 39 | "alloc", 40 | ] } 41 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # options 2 | ignore_output = &> /dev/null 3 | 4 | .PHONY: run-dev test lint fix 5 | 6 | run-dev: 7 | @cargo run 8 | 9 | test: 10 | @cargo test --workspace -- --nocapture 11 | 12 | test-all: 13 | @cargo test --workspace -- --nocapture --include-ignored 14 | 15 | lint: 16 | @cargo clippy --all-targets --all-features --workspace --tests 17 | 18 | fix: 19 | @cargo clippy --fix --workspace --tests 20 | 21 | build: 22 | @DOCKER_BUILDKIT=1 docker build -f Dockerfile -t ldclabs/idempotent-proxy:latest . 23 | 24 | build-linux: 25 | @DOCKER_BUILDKIT=1 docker build --output target -f linux.Dockerfile . 26 | 27 | # cargo install ic-wasm 28 | build-wasm: 29 | @cargo build --release --target wasm32-unknown-unknown --package idempotent-proxy-canister 30 | @cargo build --release --target wasm32-unknown-unknown --package eth-canister 31 | @cargo build --release --target wasm32-unknown-unknown --package eth-canister-lite 32 | 33 | # cargo install candid-extractor 34 | build-did: 35 | @candid-extractor target/wasm32-unknown-unknown/release/idempotent_proxy_canister.wasm > src/idempotent-proxy-canister/idempotent-proxy-canister.did 36 | @candid-extractor target/wasm32-unknown-unknown/release/eth_canister.wasm > examples/eth-canister/eth-canister.did 37 | @candid-extractor target/wasm32-unknown-unknown/release/eth_canister_lite.wasm > examples/eth-canister-lite/eth-canister-lite.did 38 | -------------------------------------------------------------------------------- /src/idempotent-proxy-canister/src/tasks.rs: -------------------------------------------------------------------------------- 1 | use std::collections::BTreeMap; 2 | 3 | use crate::{agent::Agent, store}; 4 | 5 | const SECONDS: u64 = 1_000_000_000; 6 | 7 | pub async fn refresh_proxy_token() { 8 | let (signer, proxy_token_refresh_interval, agents) = 9 | store::state::with(|s| (s.signer(), s.proxy_token_refresh_interval, s.agents.clone())); 10 | update_proxy_token(signer, proxy_token_refresh_interval, agents).await; 11 | } 12 | 13 | pub async fn update_proxy_token( 14 | signer: store::Signer, 15 | proxy_token_refresh_interval: u64, 16 | mut agents: Vec, 17 | ) { 18 | if agents.is_empty() { 19 | return; 20 | } 21 | 22 | let mut tokens: BTreeMap = BTreeMap::new(); 23 | for agent in agents.iter_mut() { 24 | if let Some(token) = tokens.get(&agent.name) { 25 | agent.proxy_token = Some(token.clone()); 26 | continue; 27 | } 28 | 29 | let token = signer 30 | .sign_proxy_token( 31 | (ic_cdk::api::time() / SECONDS) + proxy_token_refresh_interval + 120, 32 | &agent.name, 33 | ) 34 | .await 35 | .expect("failed to sign proxy token"); 36 | tokens.insert(agent.name.clone(), token.clone()); 37 | agent.proxy_token = Some(token); 38 | } 39 | 40 | store::state::with_mut(|r| r.agents = agents); 41 | } 42 | -------------------------------------------------------------------------------- /src/idempotent-proxy-canister/src/ecdsa.rs: -------------------------------------------------------------------------------- 1 | use ic_cdk::api::management_canister::ecdsa; 2 | 3 | pub async fn sign_with( 4 | key_name: &str, 5 | derivation_path: Vec>, 6 | message_hash: [u8; 32], 7 | ) -> Result, String> { 8 | let args = ecdsa::SignWithEcdsaArgument { 9 | message_hash: message_hash.to_vec(), 10 | derivation_path, 11 | key_id: ecdsa::EcdsaKeyId { 12 | curve: ecdsa::EcdsaCurve::Secp256k1, 13 | name: key_name.to_string(), 14 | }, 15 | }; 16 | 17 | let (response,): (ecdsa::SignWithEcdsaResponse,) = ecdsa::sign_with_ecdsa(args) 18 | .await 19 | .map_err(|err| format!("sign_with_ecdsa failed {:?}", err))?; 20 | 21 | Ok(response.signature) 22 | } 23 | 24 | pub async fn public_key_with( 25 | key_name: &str, 26 | derivation_path: Vec>, 27 | ) -> Result { 28 | let args = ecdsa::EcdsaPublicKeyArgument { 29 | canister_id: None, 30 | derivation_path, 31 | key_id: ecdsa::EcdsaKeyId { 32 | curve: ecdsa::EcdsaCurve::Secp256k1, 33 | name: key_name.to_string(), 34 | }, 35 | }; 36 | 37 | let (response,): (ecdsa::EcdsaPublicKeyResponse,) = ecdsa::ecdsa_public_key(args) 38 | .await 39 | .map_err(|err| format!("ecdsa_public_key failed {:?}", err))?; 40 | 41 | Ok(response) 42 | } 43 | -------------------------------------------------------------------------------- /src/idempotent-proxy-canister/src/lib.rs: -------------------------------------------------------------------------------- 1 | use candid::Principal; 2 | use ic_cdk::api::management_canister::http_request::{CanisterHttpRequestArgument, HttpResponse}; 3 | use std::collections::BTreeSet; 4 | 5 | mod agent; 6 | mod api; 7 | mod api_admin; 8 | mod cose; 9 | mod cycles; 10 | mod ecdsa; 11 | mod init; 12 | mod store; 13 | mod tasks; 14 | 15 | use api::StateInfo; 16 | use init::ChainArgs; 17 | 18 | fn is_controller() -> Result<(), String> { 19 | let caller = ic_cdk::caller(); 20 | if ic_cdk::api::is_controller(&caller) { 21 | Ok(()) 22 | } else { 23 | Err("user is not a controller".to_string()) 24 | } 25 | } 26 | 27 | fn is_controller_or_manager() -> Result<(), String> { 28 | let caller = ic_cdk::caller(); 29 | if ic_cdk::api::is_controller(&caller) || store::state::is_manager(&caller) { 30 | Ok(()) 31 | } else { 32 | Err("user is not a controller or manager".to_string()) 33 | } 34 | } 35 | 36 | #[cfg(all( 37 | target_arch = "wasm32", 38 | target_vendor = "unknown", 39 | target_os = "unknown" 40 | ))] 41 | /// A getrandom implementation that always fails 42 | pub fn always_fail(_buf: &mut [u8]) -> Result<(), getrandom::Error> { 43 | Err(getrandom::Error::UNSUPPORTED) 44 | } 45 | 46 | #[cfg(all( 47 | target_arch = "wasm32", 48 | target_vendor = "unknown", 49 | target_os = "unknown" 50 | ))] 51 | getrandom::register_custom_getrandom!(always_fail); 52 | 53 | ic_cdk::export_candid!(); 54 | -------------------------------------------------------------------------------- /.github/workflows/build-dockers.yml: -------------------------------------------------------------------------------- 1 | name: Dockers 2 | on: 3 | push: 4 | tags: 5 | - 'v*' 6 | env: 7 | REGISTRY: ghcr.io 8 | IMAGE_NAME: ldclabs/idempotent-proxy 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v4 14 | - uses: Swatinem/rust-cache@v2 15 | - name: Build the Docker image 16 | run: | 17 | docker run --rm --privileged multiarch/qemu-user-static --reset -p yes 18 | docker buildx create --use 19 | docker login --username ${{ github.actor }} --password ${{ secrets.GITHUB_TOKEN }} ${{ env.REGISTRY }} 20 | IMAGE_TAG="${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.ref_name }}" 21 | LATEST_TAG="${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest" 22 | TAGS="-t ${IMAGE_TAG} -t ${LATEST_TAG}" 23 | docker buildx build --platform='linux/amd64,linux/arm64' $TAGS --push . 24 | IMAGE_TAG="${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}_enclave_arm64:${{ github.ref_name }}" 25 | LATEST_TAG="${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}_enclave_arm64:latest" 26 | TAGS="-t ${IMAGE_TAG} -t ${LATEST_TAG}" 27 | docker build -f enclave/arm64.Dockerfile $TAGS --push . 28 | IMAGE_TAG="${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}_enclave_amd64:${{ github.ref_name }}" 29 | LATEST_TAG="${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}_enclave_amd64:latest" 30 | TAGS="-t ${IMAGE_TAG} -t ${LATEST_TAG}" 31 | docker build -f enclave/amd64.Dockerfile $TAGS --push . 32 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "src/idempotent-proxy-types", 4 | "src/idempotent-proxy-server", 5 | "src/idempotent-proxy-canister", 6 | "examples/eth-canister", 7 | "examples/eth-canister-lite", 8 | ] 9 | resolver = "2" 10 | 11 | [profile.release] 12 | debug = false 13 | lto = true 14 | strip = true 15 | opt-level = 's' 16 | 17 | [workspace.package] 18 | version = "1.2.2" 19 | edition = "2021" 20 | repository = "https://github.com/ldclabs/idempotent-proxy" 21 | keywords = ["idempotent", "reverse", "proxy", "icp"] 22 | categories = ["web-programming"] 23 | license = "MIT OR Apache-2.0" 24 | 25 | [workspace.dependencies] 26 | axum = { version = "0.7", features = [ 27 | "http1", 28 | "http2", 29 | "json", 30 | "macros", 31 | "matched-path", 32 | "tokio", 33 | "query", 34 | ], default-features = true } 35 | axum-server = { version = "0.7", features = ["tls-rustls"] } 36 | tokio = { version = "1", features = ["full"] } 37 | reqwest = { version = "0.12", features = [ 38 | "rustls-tls", 39 | "rustls-tls-native-roots", 40 | "json", 41 | "gzip", 42 | "stream", 43 | "http2", 44 | # "hickory-dns", 45 | ], default-features = true } 46 | dotenvy = "0.15" 47 | futures = "0.3" 48 | log = "0.4" 49 | structured-logger = "1" 50 | http = "1" 51 | rustis = { version = "0.13", features = ["pool"] } 52 | async-trait = "0.1" 53 | serde = "1" 54 | serde_json = "1" 55 | serde_bytes = "0.11" 56 | ciborium = "0.2" 57 | k256 = { version = "0.13", features = ["ecdsa"] } 58 | ed25519-dalek = "2" 59 | base64 = "0.22" 60 | sha3 = "0.10" 61 | -------------------------------------------------------------------------------- /examples/eth-canister/README.md: -------------------------------------------------------------------------------- 1 | # Example: `eth-canister` 2 | 3 | ## Running the project locally 4 | 5 | If you want to test your project locally, you can use the following commands: 6 | 7 | ```bash 8 | cd examples/eth-canister 9 | # Starts the replica, running in the background 10 | dfx start --background 11 | 12 | # deploy the canister 13 | dfx deploy eth-canister --argument "(opt variant {Init = 14 | record { 15 | ecdsa_key_name = \"dfx_test_key\"; 16 | } 17 | })" 18 | 19 | dfx canister call eth-canister get_state '()' 20 | 21 | # set RPC agent 22 | # URL_CF_ETH: https://cloudflare-eth.com 23 | # URL_ANKR_ETH: https://rpc.ankr.com/eth 24 | dfx canister call eth-canister admin_set_agents ' 25 | (vec { 26 | record { 27 | name = "LDCLabs"; 28 | endpoint = "https://idempotent-proxy-cf-worker.zensh.workers.dev/URL_CF_ETH"; 29 | max_cycles = 100000000000; 30 | proxy_token = null; 31 | api_token = null 32 | }; record { 33 | name = "LDCLabs"; 34 | endpoint = "https://idempotent-proxy-cf-worker.zensh.workers.dev/URL_ANKR_ETH"; 35 | max_cycles = 100000000000; 36 | proxy_token = null; 37 | api_token = null 38 | } 39 | }) 40 | ' 41 | 42 | dfx canister call eth-canister eth_chain_id '()' 43 | 44 | dfx canister call eth-canister get_best_block '()' 45 | ``` 46 | 47 | `idempotent-proxy-cf-worker` does not enable `proxy-authorization`, so it can be accessed. 48 | 49 | ## License 50 | Copyright © 2024 [LDC Labs](https://github.com/ldclabs). 51 | 52 | `ldclabs/idempotent-proxy` is licensed under the MIT License. See [LICENSE](../../LICENSE-MIT) for the full license text. -------------------------------------------------------------------------------- /src/idempotent-proxy-types/README.md: -------------------------------------------------------------------------------- 1 | # Idempotent Proxy 2 | Reverse proxy server with build-in idempotency support written in Rust. 3 | 4 | ## Overview 5 | 6 | The idempotent-proxy is a reverse proxy service written in Rust with built-in idempotency support. 7 | 8 | When multiple requests with the same idempotency-key arrive within a specific timeframe, only the first request is forwarded to the target service. The response is cached in Redis, and subsequent requests poll Redis to retrieve and return the first request's response. 9 | 10 | This service can be used to proxy [HTTPS outcalls](https://internetcomputer.org/docs/current/developer-docs/smart-contracts/advanced-features/https-outcalls/https-outcalls-overview) for [ICP canisters](https://internetcomputer.org/docs/current/developer-docs/smart-contracts/overview/introduction), enabling integration with any Web2 http service. It supports hiding secret information, access control, returning only the necessary headers and, for JSON or CBOR data, allows response filtering based on JSON Mask to return only required fields, thus saving cycles consumption in ICP canisters. 11 | 12 | ![Idempotent Proxy](../../idempotent-proxy.png) 13 | 14 | ## Features 15 | - [x] Reverse proxy with build-in idempotency support 16 | - [x] JSON response filtering 17 | - [x] Access control 18 | - [x] Response headers filtering 19 | - [x] HTTPS support 20 | - [x] Running as Cloudflare Worker 21 | - [x] Docker image 22 | 23 | More information: https://github.com/ldclabs/idempotent-proxy 24 | 25 | ## License 26 | Copyright © 2024 [LDC Labs](https://github.com/ldclabs). 27 | 28 | `ldclabs/idempotent-proxy` is licensed under the MIT License. See [LICENSE](../../LICENSE-MIT) for the full license text. -------------------------------------------------------------------------------- /enclave/supervisord.conf: -------------------------------------------------------------------------------- 1 | [supervisord] 2 | loglevel=debug 3 | logfile=/dev/stdout 4 | logfile_maxbytes=0 5 | 6 | # attestation server 7 | [program:attestation-server] 8 | command=/app/attestation-server --ip-addr 127.0.0.1:1300 --pub-key /app/id.pub 9 | autorestart=true 10 | stdout_logfile=/dev/stdout 11 | stdout_logfile_maxbytes=0 12 | stderr_logfile=/dev/stdout 13 | stderr_logfile_maxbytes=0 14 | 15 | # attestation server proxy 16 | [program:attestation-proxy] 17 | command=/app/vsock-to-ip --vsock-addr 88:1300 --ip-addr 127.0.0.1:1300 18 | autorestart=true 19 | stdout_logfile=/dev/stdout 20 | stdout_logfile_maxbytes=0 21 | stderr_logfile=/dev/stdout 22 | stderr_logfile_maxbytes=0 23 | 24 | # transparent proxy component inside enclave 25 | [program:ip-to-vsock-transparent] 26 | command=/app/ip-to-vsock-transparent --vsock-addr 3:1200 --ip-addr 127.0.0.1:1200 27 | autorestart=true 28 | stdout_logfile=/dev/stdout 29 | stdout_logfile_maxbytes=0 30 | stderr_logfile=/dev/stdout 31 | stderr_logfile_maxbytes=0 32 | 33 | # DNS-over-HTTPS provider 34 | [program:dnsproxy] 35 | command=/app/dnsproxy -u https://1.1.1.1/dns-query -v 36 | autorestart=true 37 | stdout_logfile=/dev/stdout 38 | stdout_logfile_maxbytes=0 39 | stderr_logfile=/dev/stdout 40 | stderr_logfile_maxbytes=0 41 | 42 | [program:idempotent-proxy-server-proxy] 43 | command=/app/vsock-to-ip --vsock-addr 88:80 --ip-addr 127.0.0.1:8080 44 | autorestart=true 45 | stdout_logfile=/dev/stdout 46 | stdout_logfile_maxbytes=0 47 | stderr_logfile=/dev/stdout 48 | stderr_logfile_maxbytes=0 49 | 50 | # your custom programs go here 51 | [program:idempotent-proxy-server] 52 | command=/app/idempotent-proxy-server 53 | autorestart=true 54 | stdout_logfile=/dev/stdout 55 | stdout_logfile_maxbytes=0 56 | stderr_logfile=/dev/stdout 57 | stderr_logfile_maxbytes=0 58 | -------------------------------------------------------------------------------- /examples/eth-canister/src/lib.rs: -------------------------------------------------------------------------------- 1 | mod agent; 2 | mod ecdsa; 3 | mod init; 4 | mod jsonrpc; 5 | mod store; 6 | mod tasks; 7 | 8 | use crate::{init::ChainArgs, jsonrpc::EthereumRPC}; 9 | 10 | pub const SECONDS: u64 = 1_000_000_000; 11 | 12 | #[ic_cdk::update(guard = "is_controller")] 13 | async fn admin_set_agents(agents: Vec) -> Result<(), String> { 14 | if agents.is_empty() { 15 | return Err("agents cannot be empty".to_string()); 16 | } 17 | 18 | let ecdsa_key_name = store::state::with(|s| s.ecdsa_key_name.clone()); 19 | tasks::update_proxy_token(ecdsa_key_name, agents).await; 20 | Ok(()) 21 | } 22 | 23 | fn is_controller() -> Result<(), String> { 24 | let caller = ic_cdk::caller(); 25 | if ic_cdk::api::is_controller(&caller) { 26 | Ok(()) 27 | } else { 28 | Err("user is not a controller".to_string()) 29 | } 30 | } 31 | 32 | #[ic_cdk::query] 33 | fn get_state() -> Result { 34 | let mut s = store::state::with(|s| s.clone()); 35 | if is_controller().is_err() { 36 | s.rpc_agents.clear(); 37 | } 38 | Ok(s) 39 | } 40 | 41 | #[ic_cdk::update] 42 | async fn eth_chain_id() -> Result { 43 | let agent = store::state::get_agent(); 44 | let res = EthereumRPC::eth_chain_id(&agent, "eth_chain_id".to_string()).await?; 45 | Ok(res) 46 | } 47 | 48 | #[ic_cdk::update] 49 | async fn get_best_block() -> Result { 50 | let agent = store::state::get_agent(); 51 | let ts = ic_cdk::api::time() / SECONDS; 52 | let key = format!("blk-best-{ts}"); 53 | let res = EthereumRPC::get_best_block(&agent, key).await?; 54 | let res = serde_json::to_string(&res).map_err(|e| e.to_string())?; 55 | Ok(res) 56 | } 57 | 58 | ic_cdk::export_candid!(); 59 | -------------------------------------------------------------------------------- /src/idempotent-proxy-cf-worker/.eslintrc.js: -------------------------------------------------------------------------------- 1 | /** @type {import('eslint').Linter.Config} */ 2 | module.exports = { 3 | root: true, 4 | env: { 5 | browser: true, 6 | esnext: true, 7 | node: true 8 | }, 9 | extends: [ 10 | 'eslint:recommended', 11 | 'standard', 12 | 'prettier/@typescript-eslint', 13 | 'plugin:@typescript-eslint/recommended', 14 | 'plugin:import/recommended', 15 | 'plugin:prettier/recommended', 16 | 'prettier' 17 | ], 18 | parser: '@typescript-eslint/parser', 19 | parserOptions: { 20 | ecmaVersion: 'latest', 21 | sourceType: 'module', 22 | project: 'tsconfig.json', 23 | extraFileExtensions: [] 24 | }, 25 | plugins: ['@typescript-eslint', 'import', 'prettier'], 26 | rules: { 27 | '@typescript-eslint/consistent-type-exports': [ 28 | 'error', 29 | { fixMixedExportsWithInlineTypeSpecifier: true } 30 | ], 31 | '@typescript-eslint/consistent-type-imports': [ 32 | 'error', 33 | { fixStyle: 'inline-type-imports' } 34 | ], 35 | '@typescript-eslint/no-empty-function': 'off', 36 | '@typescript-eslint/no-empty-interface': 'off', 37 | '@typescript-eslint/no-unused-vars': 'off', 38 | 'import/named': 'off', 39 | 'import/newline-after-import': 'error', 40 | 'import/no-unresolved': 'off', 41 | 'import/order': [ 42 | 'error', 43 | { 44 | groups: [ 45 | ['builtin', 'external', 'internal'], 46 | 'parent', 47 | ['sibling', 'index'] 48 | ], 49 | 'newlines-between': 'never', 50 | alphabetize: { order: 'ignore' } 51 | } 52 | ], 53 | 'no-console': 'warn', 54 | 'no-restricted-imports': [ 55 | 'error', 56 | { 57 | 'paths': [] 58 | } 59 | ], 60 | 'no-useless-rename': 'error', 61 | 'object-shorthand': ['error', 'always'] 62 | }, 63 | settings: { 64 | 'import/internal-regex': '^#' 65 | }, 66 | ignorePatterns: ['dist', 'node_modules', 'examples', 'scripts'] 67 | } 68 | -------------------------------------------------------------------------------- /src/idempotent-proxy-canister/src/cose.rs: -------------------------------------------------------------------------------- 1 | use candid::{utils::ArgumentEncoder, CandidType, Principal}; 2 | use ic_cose_types::types::{PublicKeyInput, PublicKeyOutput, SignInput}; 3 | use serde::{Deserialize, Serialize}; 4 | use serde_bytes::ByteBuf; 5 | 6 | #[derive(CandidType, Clone, Debug, Deserialize, Serialize)] 7 | pub struct CoseClient { 8 | pub id: Principal, 9 | pub namespace: String, 10 | } 11 | 12 | impl CoseClient { 13 | pub async fn ecdsa_public_key(&self, derivation_path: Vec) -> Result { 14 | let output: Result = call( 15 | self.id, 16 | "ecdsa_public_key", 17 | (Some(PublicKeyInput { 18 | ns: self.namespace.clone(), 19 | derivation_path, 20 | }),), 21 | 0, 22 | ) 23 | .await?; 24 | let output = output?; 25 | Ok(output.public_key) 26 | } 27 | 28 | pub async fn ecdsa_sign( 29 | &self, 30 | derivation_path: Vec, 31 | message: ByteBuf, 32 | ) -> Result { 33 | let output: Result = call( 34 | self.id, 35 | "ecdsa_sign", 36 | (SignInput { 37 | ns: self.namespace.clone(), 38 | derivation_path, 39 | message, 40 | },), 41 | 0, 42 | ) 43 | .await?; 44 | output 45 | } 46 | } 47 | 48 | async fn call(id: Principal, method: &str, args: In, cycles: u128) -> Result 49 | where 50 | In: ArgumentEncoder + Send, 51 | Out: candid::CandidType + for<'a> candid::Deserialize<'a>, 52 | { 53 | let (res,): (Out,) = ic_cdk::api::call::call_with_payment128(id, method, args, cycles) 54 | .await 55 | .map_err(|(code, msg)| { 56 | format!( 57 | "failed to call {} on {:?}, code: {}, message: {}", 58 | method, &id, code as u32, msg 59 | ) 60 | })?; 61 | Ok(res) 62 | } 63 | -------------------------------------------------------------------------------- /src/idempotent-proxy-cf-worker/README.md: -------------------------------------------------------------------------------- 1 | # idempotent-proxy-cf-worker 2 | Reverse proxy server with build-in idempotency support running as a Cloudflare Worker. 3 | 4 | ## Overview 5 | 6 | The idempotent-proxy is a reverse proxy service with built-in idempotency support that running as a Cloudflare Worker. 7 | 8 | When multiple requests with the same idempotency-key arrive within a specific timeframe, only the first request is forwarded to the target service. The response is cached in **Durable Object**, and subsequent requests poll the Durable Object to retrieve and return the first request's response. 9 | 10 | This service can be used to proxy [HTTPS outcalls](https://internetcomputer.org/docs/current/developer-docs/smart-contracts/advanced-features/https-outcalls/https-outcalls-overview) for [ICP canisters](https://internetcomputer.org/docs/current/developer-docs/smart-contracts/overview/introduction), enabling integration with any Web2 service. It supports returning only the necessary headers and, for JSON data, allows response filtering based on JSON Mask to return only required fields, thus saving cycles consumption in ICP canisters. 11 | 12 | ![Idempotent Proxy](../../idempotent-proxy-cf-worker.webp) 13 | 14 | ## Run proxy in local development mode 15 | 16 | Run proxy: 17 | ```bash 18 | npm i 19 | npx wrangler dev 20 | ``` 21 | 22 | 23 | ## Deploy to Cloudflare Worker 24 | 25 | In order to use Durable Objects, you must switch to a paid plan. 26 | 27 | ```bash 28 | npm i 29 | npx wrangler deploy 30 | ``` 31 | 32 | And then update settings in the Cloudflare dashboard to use the Worker. 33 | 34 | A online version for testing is available at: 35 | 36 | https://idempotent-proxy-cf-worker.zensh.workers.dev 37 | 38 | Try it out: 39 | ``` 40 | curl -v -X GET 'https://idempotent-proxy-cf-worker.zensh.workers.dev/URL_HTTPBIN' \ 41 | -H 'idempotency-key: id_001' \ 42 | -H 'content-type: application/json' 43 | ``` 44 | 45 | More information: https://github.com/ldclabs/idempotent-proxy 46 | 47 | ## License 48 | Copyright © 2024 [LDC Labs](https://github.com/ldclabs). 49 | 50 | `ldclabs/idempotent-proxy` is licensed under the MIT License. See [LICENSE](../../LICENSE-MIT) for the full license text. -------------------------------------------------------------------------------- /enclave/amd64.Dockerfile: -------------------------------------------------------------------------------- 1 | # base image 2 | FROM --platform=amd64 rust:slim-bookworm AS builder 3 | 4 | RUN apt-get update \ 5 | && apt-get install -y gcc g++ libc6-dev pkg-config libssl-dev 6 | 7 | WORKDIR /src 8 | COPY src ./src 9 | COPY examples ./examples 10 | COPY Cargo.toml Cargo.lock .env ./ 11 | RUN cargo build --release --locked -p idempotent-proxy-server 12 | 13 | FROM debian:bookworm-slim AS runtime 14 | 15 | # install dependency tools 16 | RUN apt-get update \ 17 | && apt-get install -y net-tools iptables iproute2 wget ca-certificates tzdata curl openssl \ 18 | && update-ca-certificates \ 19 | && rm -rf /var/lib/apt/lists/* 20 | 21 | # working directory 22 | WORKDIR /app 23 | 24 | # supervisord to manage programs 25 | RUN wget -O supervisord http://public.artifacts.marlin.pro/projects/enclaves/supervisord_master_linux_amd64 26 | RUN chmod +x supervisord 27 | 28 | # transparent proxy component inside the enclave to enable outgoing connections 29 | RUN wget -O ip-to-vsock-transparent http://public.artifacts.marlin.pro/projects/enclaves/ip-to-vsock-transparent_v1.0.0_linux_amd64 30 | RUN chmod +x ip-to-vsock-transparent 31 | 32 | # key generator to generate static keys 33 | RUN wget -O keygen http://public.artifacts.marlin.pro/projects/enclaves/keygen_v1.0.0_linux_amd64 34 | RUN chmod +x keygen 35 | 36 | # attestation server inside the enclave that generates attestations 37 | RUN wget -O attestation-server http://public.artifacts.marlin.pro/projects/enclaves/attestation-server_v1.0.0_linux_amd64 38 | RUN chmod +x attestation-server 39 | 40 | # proxy to expose attestation server outside the enclave 41 | RUN wget -O vsock-to-ip http://public.artifacts.marlin.pro/projects/enclaves/vsock-to-ip_v1.0.0_linux_amd64 42 | RUN chmod +x vsock-to-ip 43 | 44 | # dnsproxy to provide DNS services inside the enclave 45 | RUN wget -O dnsproxy http://public.artifacts.marlin.pro/projects/enclaves/dnsproxy_v0.46.5_linux_amd64 46 | RUN chmod +x dnsproxy 47 | 48 | # supervisord config 49 | COPY enclave/supervisord.conf /etc/supervisord.conf 50 | 51 | # setup.sh script that will act as entrypoint 52 | COPY enclave/setup.sh ./ 53 | RUN chmod +x setup.sh 54 | 55 | # your custom setup goes here 56 | # COPY enclave/.env ./.env 57 | COPY enclave/.env ../.env 58 | COPY --from=builder /src/target/release/idempotent-proxy-server ./idempotent-proxy-server 59 | 60 | # entry point 61 | ENTRYPOINT [ "/app/setup.sh" ] -------------------------------------------------------------------------------- /enclave/arm64.Dockerfile: -------------------------------------------------------------------------------- 1 | # base image 2 | FROM --platform=arm64 rust:slim-bookworm AS builder 3 | 4 | RUN apt-get update \ 5 | && apt-get install -y gcc g++ libc6-dev pkg-config libssl-dev 6 | 7 | WORKDIR /src 8 | COPY src ./src 9 | COPY examples ./examples 10 | COPY Cargo.toml Cargo.lock .env ./ 11 | RUN cargo build --release --locked -p idempotent-proxy-server 12 | 13 | FROM debian:bookworm-slim AS runtime 14 | 15 | # install dependency tools 16 | RUN apt-get update \ 17 | && apt-get install -y net-tools iptables iproute2 wget ca-certificates tzdata curl openssl \ 18 | && update-ca-certificates \ 19 | && rm -rf /var/lib/apt/lists/* 20 | 21 | # working directory 22 | WORKDIR /app 23 | 24 | # supervisord to manage programs 25 | RUN wget -O supervisord http://public.artifacts.marlin.pro/projects/enclaves/supervisord_master_linux_arm64 26 | RUN chmod +x supervisord 27 | 28 | # transparent proxy component inside the enclave to enable outgoing connections 29 | RUN wget -O ip-to-vsock-transparent http://public.artifacts.marlin.pro/projects/enclaves/ip-to-vsock-transparent_v1.0.0_linux_arm64 30 | RUN chmod +x ip-to-vsock-transparent 31 | 32 | # key generator to generate static keys 33 | RUN wget -O keygen http://public.artifacts.marlin.pro/projects/enclaves/keygen_v1.0.0_linux_arm64 34 | RUN chmod +x keygen 35 | 36 | # attestation server inside the enclave that generates attestations 37 | RUN wget -O attestation-server http://public.artifacts.marlin.pro/projects/enclaves/attestation-server_v1.0.0_linux_arm64 38 | RUN chmod +x attestation-server 39 | 40 | # proxy to expose attestation server outside the enclave 41 | RUN wget -O vsock-to-ip http://public.artifacts.marlin.pro/projects/enclaves/vsock-to-ip_v1.0.0_linux_arm64 42 | RUN chmod +x vsock-to-ip 43 | 44 | # dnsproxy to provide DNS services inside the enclave 45 | RUN wget -O dnsproxy http://public.artifacts.marlin.pro/projects/enclaves/dnsproxy_v0.46.5_linux_arm64 46 | RUN chmod +x dnsproxy 47 | 48 | # supervisord config 49 | COPY enclave/supervisord.conf /etc/supervisord.conf 50 | 51 | # setup.sh script that will act as entrypoint 52 | COPY enclave/setup.sh ./ 53 | RUN chmod +x setup.sh 54 | 55 | # your custom setup goes here 56 | # COPY enclave/.env ./.env 57 | COPY enclave/.env ../.env 58 | COPY --from=builder /src/target/release/idempotent-proxy-server ./idempotent-proxy-server 59 | 60 | # entry point 61 | ENTRYPOINT [ "./idempotent-proxy-server" ] -------------------------------------------------------------------------------- /src/idempotent-proxy-cf-worker/src/auth.ts: -------------------------------------------------------------------------------- 1 | import { sha3_256 as sha3 } from '@noble/hashes/sha3' 2 | import { ed25519 } from '@noble/curves/ed25519' 3 | import { encode, decode } from 'cborg' 4 | import { secp256k1 } from '@noble/curves/secp256k1' 5 | 6 | const PERMITTED_DRIFT = 10 // seconds 7 | 8 | // Token format: [expire_at in seconds, agent, signature] 9 | export type Token = [number, string, Uint8Array] 10 | 11 | export function ed25519Sign( 12 | privateKey: Uint8Array, 13 | expire_at: number, 14 | agent: String 15 | ): Uint8Array { 16 | const sig = ed25519.sign(encode([expire_at, agent]), privateKey) 17 | return encode([expire_at, agent, sig]) 18 | } 19 | 20 | export function ed25519Verify( 21 | pubKeys: Array, 22 | data: Uint8Array 23 | ): Token { 24 | const token: Token = decode(data) 25 | if (token[0] + PERMITTED_DRIFT < Date.now() / 1000) { 26 | throw new Error('token expired') 27 | } 28 | 29 | const msg = encode(token.slice(0, 2)) 30 | for (const pubKey of pubKeys) { 31 | if (ed25519.verify(token[2], msg, pubKey)) { 32 | return token 33 | } 34 | } 35 | 36 | throw new Error('failed to verify Ed25519 signature') 37 | } 38 | 39 | export function ecdsaSign( 40 | privateKey: Uint8Array, 41 | expire_at: number, 42 | agent: String 43 | ): Uint8Array { 44 | const digest = sha3(encode([expire_at, agent])) 45 | const sig = secp256k1.sign(digest, privateKey) 46 | return encode([expire_at, agent, sig]) 47 | } 48 | 49 | export function ecdsaVerify( 50 | pubKeys: Array, 51 | data: Uint8Array 52 | ): Token { 53 | const token: Token = decode(data) 54 | if (token[0] + PERMITTED_DRIFT < Date.now() / 1000) { 55 | throw new Error('token expired') 56 | } 57 | 58 | const digest = sha3(encode(token.slice(0, 2))) 59 | for (const pubKey of pubKeys) { 60 | if (secp256k1.verify(token[2], digest, pubKey)) { 61 | return token 62 | } 63 | } 64 | 65 | throw new Error('failed to verify ECDSA/Secp256k1 signature') 66 | } 67 | 68 | export function bytesToBase64Url(bytes: Uint8Array): string { 69 | return btoa(String.fromCodePoint(...bytes)) 70 | .replaceAll('+', '-') 71 | .replaceAll('/', '_') 72 | .replaceAll('=', '') 73 | } 74 | 75 | export function base64ToBytes(str: string): Uint8Array { 76 | return Uint8Array.from( 77 | atob(str.replaceAll('-', '+').replaceAll('_', '/')), 78 | (m) => m.codePointAt(0)! 79 | ) 80 | } 81 | -------------------------------------------------------------------------------- /examples/eth-canister/src/init.rs: -------------------------------------------------------------------------------- 1 | use candid::CandidType; 2 | use serde::Deserialize; 3 | use std::time::Duration; 4 | 5 | use crate::{store, tasks}; 6 | 7 | #[derive(Clone, Debug, CandidType, Deserialize)] 8 | pub enum ChainArgs { 9 | Init(InitArgs), 10 | Upgrade(UpgradeArgs), 11 | } 12 | 13 | #[derive(Clone, Debug, CandidType, Deserialize)] 14 | pub struct InitArgs { 15 | ecdsa_key_name: String, // Use "dfx_test_key" for local replica and "test_key_1" for a testing key for testnet and mainnet 16 | } 17 | 18 | #[derive(Clone, Debug, CandidType, Deserialize)] 19 | pub struct UpgradeArgs {} 20 | 21 | #[ic_cdk::init] 22 | fn init(args: Option) { 23 | match args.expect("Init args is missing") { 24 | ChainArgs::Init(args) => { 25 | store::state::with_mut(|s| { 26 | s.ecdsa_key_name = args.ecdsa_key_name; 27 | }); 28 | } 29 | ChainArgs::Upgrade(_) => { 30 | ic_cdk::trap( 31 | "Cannot initialize the canister with an Upgrade args. Please provide an Init args.", 32 | ); 33 | } 34 | } 35 | 36 | ic_cdk_timers::set_timer(Duration::from_secs(0), || { 37 | ic_cdk::spawn(async { 38 | store::state::init_ecdsa_public_key().await; 39 | tasks::refresh_proxy_token().await; 40 | }) 41 | }); 42 | 43 | ic_cdk_timers::set_timer_interval( 44 | Duration::from_secs(tasks::REFRESH_PROXY_TOKEN_INTERVAL), 45 | || ic_cdk::spawn(tasks::refresh_proxy_token()), 46 | ); 47 | } 48 | 49 | #[ic_cdk::pre_upgrade] 50 | fn pre_upgrade() { 51 | store::state::save(); 52 | } 53 | 54 | #[ic_cdk::post_upgrade] 55 | fn post_upgrade(args: Option) { 56 | store::state::load(); 57 | 58 | match args { 59 | Some(ChainArgs::Upgrade(_args)) => {} 60 | Some(ChainArgs::Init(_)) => { 61 | ic_cdk::trap( 62 | "Cannot upgrade the canister with an Init args. Please provide an Upgrade args.", 63 | ); 64 | } 65 | _ => {} 66 | } 67 | 68 | ic_cdk_timers::set_timer(Duration::from_secs(0), || { 69 | ic_cdk::spawn(async { 70 | tasks::refresh_proxy_token().await; 71 | }) 72 | }); 73 | 74 | ic_cdk_timers::set_timer_interval( 75 | Duration::from_secs(tasks::REFRESH_PROXY_TOKEN_INTERVAL), 76 | || ic_cdk::spawn(tasks::refresh_proxy_token()), 77 | ); 78 | } 79 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Cross-compiling using Docker multi-platform builds/images and `xx`. 2 | # 3 | # https://docs.docker.com/build/building/multi-platform/ 4 | # https://github.com/tonistiigi/xx 5 | FROM --platform=${BUILDPLATFORM:-linux/amd64} tonistiigi/xx AS xx 6 | 7 | # Utilizing Docker layer caching with `cargo-chef`. 8 | # 9 | # https://www.lpalmieri.com/posts/fast-rust-docker-builds/ 10 | FROM --platform=${BUILDPLATFORM:-linux/amd64} lukemathwalker/cargo-chef:latest-rust-slim-bookworm AS chef 11 | 12 | 13 | FROM chef AS planner 14 | WORKDIR /src 15 | COPY . . 16 | RUN cargo chef prepare --recipe-path recipe.json 17 | 18 | FROM chef as builder 19 | WORKDIR /src 20 | 21 | COPY --from=xx / / 22 | RUN apt-get update && apt-get install -y clang lld cmake 23 | 24 | # `ARG`/`ENV` pair is a workaround for `docker build` backward-compatibility. 25 | # 26 | # https://github.com/docker/buildx/issues/510 27 | ARG BUILDPLATFORM 28 | ENV BUILDPLATFORM=${BUILDPLATFORM:-linux/amd64} 29 | RUN case "$BUILDPLATFORM" in \ 30 | */amd64 ) PLATFORM=x86_64 ;; \ 31 | */arm64 | */arm64/* ) PLATFORM=aarch64 ;; \ 32 | * ) echo "Unexpected BUILDPLATFORM '$BUILDPLATFORM'" >&2; exit 1 ;; \ 33 | esac; 34 | 35 | # `ARG`/`ENV` pair is a workaround for `docker build` backward-compatibility. 36 | # 37 | # https://github.com/docker/buildx/issues/510 38 | ARG TARGETPLATFORM 39 | ENV TARGETPLATFORM=${TARGETPLATFORM:-linux/amd64} 40 | 41 | RUN xx-apt-get install -y gcc g++ libc6-dev pkg-config libssl-dev 42 | 43 | ENV OPENSSL_INCLUDE_DIR=/usr/include/openssl 44 | ENV AARCH64_UNKNOWN_LINUX_GNU_OPENSSL_INCLUDE_DIR=/usr/include/aarch64-linux-gnu/openssl 45 | ENV X86_64_UNKNOWN_LINUX_GNU_OPENSSL_INCLUDE_DIR=/usr/include/x86_64-linux-gnu/openssl 46 | ENV AARCH64_UNKNOWN_LINUX_GNU_OPENSSL_LIB_DIR=/usr/lib/aarch64-linux-gnu 47 | ENV X86_64_UNKNOWN_LINUX_GNU_OPENSSL_LIB_DIR=/usr/lib/x86_64-linux-gnu 48 | ENV OPENSSL_LIB_DIR=/usr/lib/x86_64-linux-gnu 49 | 50 | COPY --from=planner /src/recipe.json recipe.json 51 | RUN xx-cargo chef cook --release --recipe-path recipe.json 52 | 53 | COPY . . 54 | RUN xx-cargo build --release --locked -p idempotent-proxy-server \ 55 | && xx-verify target/$(xx-cargo --print-target-triple)/release/idempotent-proxy-server \ 56 | && mv target/$(xx-cargo --print-target-triple)/release /src/release 57 | 58 | FROM debian:bookworm-slim AS runtime 59 | 60 | RUN apt-get update \ 61 | && apt-get install -y ca-certificates tzdata curl openssl \ 62 | && update-ca-certificates \ 63 | && rm -rf /var/lib/apt/lists/* 64 | 65 | ENV AARCH64_UNKNOWN_LINUX_GNU_OPENSSL_LIB_DIR=/usr/lib/aarch64-linux-gnu 66 | ENV OPENSSL_LIB_DIR=/usr/lib/x86_64-linux-gnu 67 | 68 | WORKDIR /app 69 | COPY --from=builder /src/.env ./.env 70 | COPY --from=builder /src/release/idempotent-proxy-server ./idempotent-proxy-server 71 | 72 | ENTRYPOINT ["./idempotent-proxy-server"] 73 | -------------------------------------------------------------------------------- /examples/eth-canister/src/jsonrpc.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use serde::{de::DeserializeOwned, Deserialize, Serialize}; 3 | use serde_json::{to_vec, Value}; 4 | 5 | use crate::ecdsa::err_string; 6 | 7 | pub static APP_AGENT: &str = concat!( 8 | "Mozilla/5.0 eth-canister ", 9 | env!("CARGO_PKG_NAME"), 10 | "/", 11 | env!("CARGO_PKG_VERSION"), 12 | ); 13 | 14 | #[async_trait] 15 | pub trait JsonRPCAgent { 16 | async fn post(&self, idempotency_key: String, body: Vec) -> Result, String>; 17 | } 18 | 19 | pub struct EthereumRPC {} 20 | 21 | #[derive(Debug, Serialize)] 22 | pub struct RPCRequest<'a> { 23 | jsonrpc: &'a str, 24 | method: &'a str, 25 | params: &'a [Value], 26 | id: u64, 27 | } 28 | 29 | #[derive(Debug, Deserialize)] 30 | pub struct RPCResponse { 31 | result: Option, 32 | error: Option, 33 | } 34 | 35 | impl EthereumRPC { 36 | pub async fn eth_chain_id( 37 | agent: impl JsonRPCAgent, 38 | idempotency_key: String, 39 | ) -> Result { 40 | Self::call(agent, idempotency_key, "eth_chainId", &[]).await 41 | } 42 | 43 | pub async fn get_best_block( 44 | agent: impl JsonRPCAgent, 45 | idempotency_key: String, 46 | ) -> Result { 47 | Self::call( 48 | agent, 49 | idempotency_key, 50 | "eth_getBlockByNumber", 51 | &["latest".into(), false.into()], 52 | ) 53 | .await 54 | } 55 | 56 | pub async fn send_raw_transaction( 57 | agent: impl JsonRPCAgent, 58 | idempotency_key: String, 59 | raw_tx: String, 60 | ) -> Result { 61 | Self::call( 62 | agent, 63 | idempotency_key, 64 | "eth_sendTransaction", 65 | &[raw_tx.into()], 66 | ) 67 | .await 68 | } 69 | 70 | // you can add more methods here 71 | 72 | pub async fn call( 73 | agent: impl JsonRPCAgent, 74 | idempotency_key: String, 75 | method: &str, 76 | params: &[Value], 77 | ) -> Result { 78 | let input = RPCRequest { 79 | jsonrpc: "2.0", 80 | method, 81 | params, 82 | id: 1, 83 | }; 84 | let input = to_vec(&input).map_err(err_string)?; 85 | let data = agent.post(idempotency_key, input).await?; 86 | 87 | let output: RPCResponse = serde_json::from_slice(&data).map_err(err_string)?; 88 | 89 | if let Some(error) = output.error { 90 | return Err(serde_json::to_string(&error).map_err(err_string)?); 91 | } 92 | 93 | match output.result { 94 | Some(result) => Ok(result), 95 | None => serde_json::from_value(Value::Null).map_err(err_string), 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /examples/eth-canister/src/ecdsa.rs: -------------------------------------------------------------------------------- 1 | use base64::{engine::general_purpose::URL_SAFE_NO_PAD as base64_url, Engine}; 2 | use ciborium::into_writer; 3 | use ic_cdk::api::management_canister::ecdsa; 4 | use serde_bytes::ByteBuf; 5 | use sha3::{Digest, Sha3_256}; 6 | 7 | // use Idempotent Proxy's Token: Token(pub u64, pub String, pub ByteBuf); 8 | // https://github.com/ldclabs/idempotent-proxy/blob/main/src/idempotent-proxy-types/src/auth.rs#L15 9 | pub async fn sign_proxy_token( 10 | key_name: &str, 11 | expire_at: u64, // UNIX timestamp, in seconds 12 | message: &str, // use RPCAgent.name as message 13 | ) -> Result { 14 | let mut buf: Vec = Vec::new(); 15 | into_writer(&(expire_at, message), &mut buf).expect("failed to encode Token in CBOR format"); 16 | let digest = sha3_256(&buf); 17 | let sig = sign_with(key_name, vec![b"sign_proxy_token".to_vec()], digest) 18 | .await 19 | .map_err(err_string)?; 20 | buf.clear(); 21 | into_writer(&(expire_at, message, ByteBuf::from(sig)), &mut buf).map_err(err_string)?; 22 | Ok(base64_url.encode(buf)) 23 | } 24 | 25 | pub async fn get_proxy_token_public_key(key_name: &str) -> Result { 26 | let pk = public_key_with(key_name, vec![b"sign_proxy_token".to_vec()]).await?; 27 | Ok(base64_url.encode(pk.public_key)) 28 | } 29 | 30 | pub async fn sign_with( 31 | key_name: &str, 32 | derivation_path: Vec>, 33 | message_hash: [u8; 32], 34 | ) -> Result, String> { 35 | let args = ecdsa::SignWithEcdsaArgument { 36 | message_hash: message_hash.to_vec(), 37 | derivation_path, 38 | key_id: ecdsa::EcdsaKeyId { 39 | curve: ecdsa::EcdsaCurve::Secp256k1, 40 | name: key_name.to_string(), 41 | }, 42 | }; 43 | 44 | let (response,): (ecdsa::SignWithEcdsaResponse,) = ecdsa::sign_with_ecdsa(args) 45 | .await 46 | .map_err(|err| format!("sign_with_ecdsa failed {:?}", err))?; 47 | 48 | Ok(response.signature) 49 | } 50 | 51 | pub async fn public_key_with( 52 | key_name: &str, 53 | derivation_path: Vec>, 54 | ) -> Result { 55 | let args = ecdsa::EcdsaPublicKeyArgument { 56 | canister_id: None, 57 | derivation_path, 58 | key_id: ecdsa::EcdsaKeyId { 59 | curve: ecdsa::EcdsaCurve::Secp256k1, 60 | name: key_name.to_string(), 61 | }, 62 | }; 63 | 64 | let (response,): (ecdsa::EcdsaPublicKeyResponse,) = ecdsa::ecdsa_public_key(args) 65 | .await 66 | .map_err(|err| format!("ecdsa_public_key failed {:?}", err))?; 67 | 68 | Ok(response) 69 | } 70 | 71 | pub fn err_string(err: impl std::fmt::Display) -> String { 72 | err.to_string() 73 | } 74 | 75 | pub fn sha3_256(data: &[u8]) -> [u8; 32] { 76 | let mut hasher = Sha3_256::new(); 77 | hasher.update(data); 78 | hasher.finalize().into() 79 | } 80 | -------------------------------------------------------------------------------- /src/idempotent-proxy-canister/idempotent-proxy-canister.did: -------------------------------------------------------------------------------- 1 | type Agent = record { 2 | proxy_token : opt text; 3 | endpoint : text; 4 | name : text; 5 | max_cycles : nat64; 6 | }; 7 | type CanisterHttpRequestArgument = record { 8 | url : text; 9 | method : HttpMethod; 10 | max_response_bytes : opt nat64; 11 | body : opt blob; 12 | transform : opt TransformContext; 13 | headers : vec HttpHeader; 14 | }; 15 | type ChainArgs = variant { Upgrade : UpgradeArgs; Init : InitArgs }; 16 | type CoseClient = record { id : principal; namespace : text }; 17 | type HttpHeader = record { value : text; name : text }; 18 | type HttpMethod = variant { get; head; post }; 19 | type HttpResponse = record { 20 | status : nat; 21 | body : blob; 22 | headers : vec HttpHeader; 23 | }; 24 | type InitArgs = record { 25 | service_fee : nat64; 26 | ecdsa_key_name : text; 27 | cose : opt CoseClient; 28 | proxy_token_refresh_interval : nat64; 29 | subnet_size : nat64; 30 | }; 31 | type Result = variant { Ok : bool; Err : text }; 32 | type Result_1 = variant { Ok; Err : text }; 33 | type Result_2 = variant { Ok : text; Err : text }; 34 | type StateInfo = record { 35 | proxy_token_public_key : text; 36 | service_fee : nat64; 37 | ecdsa_key_name : text; 38 | managers : vec principal; 39 | cose : opt CoseClient; 40 | uncollectible_cycles : nat; 41 | callers : nat64; 42 | agents : vec Agent; 43 | incoming_cycles : nat; 44 | proxy_token_refresh_interval : nat64; 45 | subnet_size : nat64; 46 | }; 47 | type TransformArgs = record { context : blob; response : HttpResponse }; 48 | type TransformContext = record { 49 | function : func (TransformArgs) -> (HttpResponse) query; 50 | context : blob; 51 | }; 52 | type UpgradeArgs = record { 53 | service_fee : opt nat64; 54 | cose : opt CoseClient; 55 | proxy_token_refresh_interval : opt nat64; 56 | subnet_size : opt nat64; 57 | }; 58 | service : (opt ChainArgs) -> { 59 | admin_add_caller : (principal) -> (Result); 60 | admin_add_callers : (vec principal) -> (Result_1); 61 | admin_add_managers : (vec principal) -> (Result_1); 62 | admin_remove_callers : (vec principal) -> (Result_1); 63 | admin_remove_managers : (vec principal) -> (Result_1); 64 | admin_set_agents : (vec Agent) -> (Result_1); 65 | caller_info : (principal) -> (opt record { nat; nat64 }) query; 66 | parallel_call_all_ok : (CanisterHttpRequestArgument) -> (HttpResponse); 67 | parallel_call_any_ok : (CanisterHttpRequestArgument) -> (HttpResponse); 68 | parallel_call_cost : (CanisterHttpRequestArgument) -> (nat) query; 69 | proxy_http_request : (CanisterHttpRequestArgument) -> (HttpResponse); 70 | proxy_http_request_cost : (CanisterHttpRequestArgument) -> (nat) query; 71 | state_info : () -> (StateInfo) query; 72 | validate2_admin_add_managers : (vec principal) -> (Result_2); 73 | validate2_admin_remove_managers : (vec principal) -> (Result_2); 74 | validate2_admin_set_agents : (vec Agent) -> (Result_2); 75 | validate_admin_add_managers : (vec principal) -> (Result_1); 76 | validate_admin_remove_managers : (vec principal) -> (Result_1); 77 | validate_admin_set_agents : (vec Agent) -> (Result_1); 78 | } 79 | -------------------------------------------------------------------------------- /src/idempotent-proxy-canister/src/cycles.rs: -------------------------------------------------------------------------------- 1 | use ic_cdk::api::management_canister::http_request::{CanisterHttpRequestArgument, HttpResponse}; 2 | 3 | #[derive(Clone)] 4 | pub struct Calculator { 5 | pub subnet_size: u64, 6 | pub service_fee: u64, 7 | } 8 | 9 | // https://github.com/internet-computer-protocol/evm-rpc-canister/blob/main/src/accounting.rs#L34 10 | impl Calculator { 11 | // HTTP outcall cost calculation 12 | // See https://internetcomputer.org/docs/current/developer-docs/gas-cost#special-features 13 | pub const INGRESS_MESSAGE_RECEIVED_COST: u64 = 1_200_000; 14 | pub const INGRESS_MESSAGE_BYTE_RECEIVED_COST: u64 = 2_000; 15 | pub const HTTP_OUTCALL_REQUEST_BASE_COST: u64 = 3_000_000; 16 | pub const HTTP_OUTCALL_REQUEST_PER_NODE_COST: u64 = 60_000; 17 | pub const HTTP_OUTCALL_REQUEST_COST_PER_BYTE: u64 = 400; 18 | pub const HTTP_OUTCALL_RESPONSE_COST_PER_BYTE: u64 = 800; 19 | // Additional headers added to the request 20 | pub const HTTP_OUTCALL_REQUEST_OVERHEAD_BYTES: u64 = 150; 21 | // Additional cost of operating the canister per subnet node 22 | pub const CANISTER_OVERHEAD: u64 = 1_000_000; 23 | 24 | pub fn count_request_bytes(&self, req: &CanisterHttpRequestArgument) -> usize { 25 | if self.subnet_size == 0 { 26 | return 0; 27 | } 28 | let mut total = req.url.len() + req.body.as_ref().map(|v| v.len()).unwrap_or_default(); 29 | for header in &req.headers { 30 | total += header.name.len() + header.value.len() + 3; 31 | } 32 | total 33 | } 34 | 35 | pub fn count_response_bytes(&self, res: &HttpResponse) -> usize { 36 | if self.subnet_size == 0 { 37 | return 0; 38 | } 39 | let mut total = 4 + res.body.as_slice().len(); 40 | for header in &res.headers { 41 | total += header.name.len() + header.value.len() + 3; 42 | } 43 | total 44 | } 45 | 46 | pub fn ingress_cost(&self, ingress_bytes: usize) -> u128 { 47 | if self.subnet_size == 0 { 48 | return 0; 49 | } 50 | let cost_per_node = Self::INGRESS_MESSAGE_RECEIVED_COST 51 | + Self::INGRESS_MESSAGE_BYTE_RECEIVED_COST * ingress_bytes as u64; 52 | cost_per_node as u128 * self.subnet_size as u128 53 | } 54 | 55 | pub fn http_outcall_request_cost(&self, request_bytes: usize, duplicates: usize) -> u128 { 56 | if self.subnet_size == 0 { 57 | return 0; 58 | } 59 | let cost_per_node = Self::HTTP_OUTCALL_REQUEST_BASE_COST 60 | + Self::HTTP_OUTCALL_REQUEST_PER_NODE_COST * self.subnet_size 61 | + Self::HTTP_OUTCALL_REQUEST_COST_PER_BYTE 62 | * (Self::HTTP_OUTCALL_REQUEST_OVERHEAD_BYTES + request_bytes as u64) 63 | + Self::CANISTER_OVERHEAD; 64 | self.service_fee as u128 65 | + cost_per_node as u128 * (self.subnet_size * duplicates as u64) as u128 66 | } 67 | 68 | pub fn http_outcall_response_cost(&self, response_bytes: usize, duplicates: usize) -> u128 { 69 | if self.subnet_size == 0 { 70 | return 0; 71 | } 72 | let cost_per_node = Self::HTTP_OUTCALL_RESPONSE_COST_PER_BYTE * response_bytes as u64; 73 | cost_per_node as u128 * (self.subnet_size * duplicates as u64) as u128 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/idempotent-proxy-canister/src/agent.rs: -------------------------------------------------------------------------------- 1 | use candid::{CandidType, Nat}; 2 | use http::Uri; 3 | use ic_cdk::api::management_canister::http_request::{ 4 | http_request, CanisterHttpRequestArgument, HttpHeader, HttpResponse, TransformArgs, 5 | TransformContext, 6 | }; 7 | use serde::{Deserialize, Serialize}; 8 | 9 | #[derive(CandidType, Default, Clone, Deserialize, Serialize)] 10 | pub struct Agent { 11 | pub name: String, // used as a prefix for idempotency_key and message in sign_proxy_token to separate different business processes. 12 | pub endpoint: String, 13 | pub max_cycles: u64, 14 | pub proxy_token: Option, 15 | } 16 | 17 | impl Agent { 18 | fn build_request(&self, req: &mut CanisterHttpRequestArgument) -> Result<(), String> { 19 | if !req.headers.iter().any(|h| h.name == "idempotency-key") { 20 | Err("idempotency-key header is missing".to_string())?; 21 | } 22 | 23 | if req.url.starts_with("URL_") { 24 | req.url = format!("{}/{}", self.endpoint, req.url); 25 | } else { 26 | let url: Uri = req 27 | .url 28 | .parse() 29 | .map_err(|err| format!("parse url {} error: {}", req.url, err))?; 30 | let host = url 31 | .host() 32 | .ok_or_else(|| format!("url host is empty: {}", req.url))?; 33 | req.headers.push(HttpHeader { 34 | name: "x-forwarded-host".to_string(), 35 | value: host.to_string(), 36 | }); 37 | 38 | let path_query = url.path_and_query().map(|v| v.as_str()).unwrap_or("/"); 39 | 40 | req.url = format!("{}{}", self.endpoint, path_query); 41 | } 42 | 43 | if !req.headers.iter().any(|h| h.name == "response-headers") { 44 | req.headers.push(HttpHeader { 45 | name: "response-headers".to_string(), 46 | value: "date".to_string(), 47 | }); 48 | } 49 | 50 | if let Some(proxy_token) = &self.proxy_token { 51 | req.headers.push(HttpHeader { 52 | name: "proxy-authorization".to_string(), 53 | value: format!("Bearer {}", proxy_token), 54 | }); 55 | } 56 | 57 | req.transform = Some(TransformContext::from_name( 58 | "inner_transform_response".to_string(), 59 | vec![], 60 | )); 61 | 62 | Ok(()) 63 | } 64 | 65 | pub async fn call( 66 | &self, 67 | mut req: CanisterHttpRequestArgument, 68 | ) -> Result { 69 | if let Err(err) = self.build_request(&mut req) { 70 | return Ok(HttpResponse { 71 | status: Nat::from(400u64), 72 | body: err.into_bytes(), 73 | headers: vec![], 74 | }); 75 | } 76 | 77 | match http_request(req, self.max_cycles as u128).await { 78 | Ok((res,)) if res.status <= 500u64 => Ok(res), 79 | Ok((res,)) => Err(res), 80 | Err((code, message)) => Err(HttpResponse { 81 | status: Nat::from(503u64), 82 | body: format!("http_request resulted into error. code: {code:?}, error: {message}") 83 | .into_bytes(), 84 | headers: vec![], 85 | }), 86 | } 87 | } 88 | } 89 | 90 | #[ic_cdk::query(hidden = true)] 91 | fn inner_transform_response(args: TransformArgs) -> HttpResponse { 92 | HttpResponse { 93 | status: args.response.status, 94 | body: args.response.body, 95 | // Remove headers (which may contain a timestamp) for consensus 96 | headers: vec![], 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/idempotent-proxy-canister/src/api_admin.rs: -------------------------------------------------------------------------------- 1 | use candid::Principal; 2 | use ic_cose_types::{validate_principals, ANONYMOUS}; 3 | use std::collections::BTreeSet; 4 | 5 | use crate::{agent, is_controller, is_controller_or_manager, store, tasks}; 6 | 7 | #[ic_cdk::update(guard = "is_controller")] 8 | fn admin_add_managers(mut args: BTreeSet) -> Result<(), String> { 9 | validate_principals(&args)?; 10 | store::state::with_mut(|r| { 11 | r.managers.append(&mut args); 12 | Ok(()) 13 | }) 14 | } 15 | 16 | #[ic_cdk::update(guard = "is_controller")] 17 | fn admin_remove_managers(args: BTreeSet) -> Result<(), String> { 18 | validate_principals(&args)?; 19 | store::state::with_mut(|r| { 20 | r.managers.retain(|p| !args.contains(p)); 21 | Ok(()) 22 | }) 23 | } 24 | 25 | #[ic_cdk::update(guard = "is_controller_or_manager")] 26 | fn admin_add_caller(id: Principal) -> Result { 27 | if id == ANONYMOUS { 28 | Err("anonymous caller cannot be added".to_string())?; 29 | } 30 | 31 | store::state::with_mut(|r| { 32 | let has = r.callers.contains_key(&id); 33 | r.callers.entry(id).or_insert((0, 0)); 34 | Ok(!has) 35 | }) 36 | } 37 | 38 | #[ic_cdk::update(guard = "is_controller_or_manager")] 39 | fn admin_add_callers(args: BTreeSet) -> Result<(), String> { 40 | validate_principals(&args)?; 41 | store::state::with_mut(|r| { 42 | args.into_iter().for_each(|p| { 43 | r.callers.entry(p).or_insert((0, 0)); 44 | }); 45 | Ok(()) 46 | }) 47 | } 48 | 49 | #[ic_cdk::update(guard = "is_controller_or_manager")] 50 | fn admin_remove_callers(args: BTreeSet) -> Result<(), String> { 51 | validate_principals(&args)?; 52 | store::state::with_mut(|r| { 53 | args.iter().for_each(|p| { 54 | r.callers.remove(p); 55 | }); 56 | Ok(()) 57 | }) 58 | } 59 | 60 | #[ic_cdk::update(guard = "is_controller_or_manager")] 61 | async fn admin_set_agents(agents: Vec) -> Result<(), String> { 62 | validate_admin_set_agents(agents.clone())?; 63 | 64 | let (signer, proxy_token_refresh_interval) = 65 | store::state::with(|s| (s.signer(), s.proxy_token_refresh_interval)); 66 | tasks::update_proxy_token(signer, proxy_token_refresh_interval, agents).await; 67 | Ok(()) 68 | } 69 | 70 | // Use validate2_admin_add_managers instead of validate_admin_add_managers 71 | #[ic_cdk::update] 72 | fn validate_admin_add_managers(args: BTreeSet) -> Result<(), String> { 73 | validate_principals(&args)?; 74 | Ok(()) 75 | } 76 | 77 | #[ic_cdk::update] 78 | fn validate2_admin_add_managers(args: BTreeSet) -> Result { 79 | validate_principals(&args)?; 80 | Ok("ok".to_string()) 81 | } 82 | 83 | // Use validate2_admin_remove_managers instead of validate_admin_remove_managers 84 | #[ic_cdk::update] 85 | fn validate_admin_remove_managers(args: BTreeSet) -> Result<(), String> { 86 | validate_principals(&args)?; 87 | Ok(()) 88 | } 89 | 90 | #[ic_cdk::update] 91 | fn validate2_admin_remove_managers(args: BTreeSet) -> Result { 92 | validate_principals(&args)?; 93 | Ok("ok".to_string()) 94 | } 95 | 96 | // Use validate2_admin_set_agents instead of validate_admin_set_agents 97 | #[ic_cdk::update] 98 | fn validate_admin_set_agents(agents: Vec) -> Result<(), String> { 99 | if agents.is_empty() { 100 | return Err("agents cannot be empty".to_string()); 101 | } 102 | 103 | Ok(()) 104 | } 105 | 106 | #[ic_cdk::update] 107 | fn validate2_admin_set_agents(agents: Vec) -> Result { 108 | if agents.is_empty() { 109 | return Err("agents cannot be empty".to_string()); 110 | } 111 | 112 | Ok("ok".to_string()) 113 | } 114 | -------------------------------------------------------------------------------- /examples/eth-canister/src/agent.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use candid::CandidType; 3 | use ic_cdk::api::management_canister::http_request::{ 4 | http_request, CanisterHttpRequestArgument, HttpHeader, HttpMethod, HttpResponse, TransformArgs, 5 | TransformContext, 6 | }; 7 | use serde::{Deserialize, Serialize}; 8 | 9 | use crate::jsonrpc::{JsonRPCAgent, APP_AGENT}; 10 | 11 | #[derive(CandidType, Default, Clone, Deserialize, Serialize)] 12 | pub struct RPCAgent { 13 | pub name: String, // used as a prefix for idempotency_key and message in sign_proxy_token to separate different business processes. 14 | pub endpoint: String, 15 | pub max_cycles: u64, 16 | pub proxy_token: Option, 17 | pub api_token: Option, 18 | } 19 | 20 | #[async_trait] 21 | impl JsonRPCAgent for &RPCAgent { 22 | async fn post(&self, idempotency_key: String, body: Vec) -> Result, String> { 23 | let mut request_headers = vec![ 24 | HttpHeader { 25 | name: "content-type".to_string(), 26 | value: "application/json".to_string(), 27 | }, 28 | HttpHeader { 29 | name: "user-agent".to_string(), 30 | value: APP_AGENT.to_string(), 31 | }, 32 | // filter out all headers except "content-type", "content-length" and "date" 33 | // because this 3 headers will allways be returned from the server side 34 | HttpHeader { 35 | name: "response-headers".to_string(), 36 | value: "date".to_string(), 37 | }, 38 | HttpHeader { 39 | name: "idempotency-key".to_string(), 40 | value: idempotency_key.clone(), 41 | }, 42 | ]; 43 | 44 | if let Some(proxy_token) = &self.proxy_token { 45 | request_headers.push(HttpHeader { 46 | name: "proxy-authorization".to_string(), 47 | value: format!("Bearer {}", proxy_token), 48 | }); 49 | } 50 | 51 | if let Some(api_token) = &self.api_token { 52 | request_headers.push(HttpHeader { 53 | name: "authorization".to_string(), 54 | value: api_token.clone(), 55 | }); 56 | } 57 | 58 | let request = CanisterHttpRequestArgument { 59 | url: self.endpoint.to_string(), 60 | max_response_bytes: None, //optional for request 61 | method: HttpMethod::POST, 62 | headers: request_headers, 63 | body: Some(body), 64 | transform: Some(TransformContext::from_name( 65 | "transform_jsonrpc".to_string(), 66 | vec![], 67 | )), 68 | }; 69 | 70 | match http_request(request, self.max_cycles as u128).await { 71 | Ok((res,)) => { 72 | if res.status >= 200u64 && res.status < 300u64 { 73 | Ok(res.body) 74 | } else { 75 | Err(format!( 76 | "failed to request url: {}, idempotency-key: {}, status: {}, body: {}", 77 | self.endpoint, 78 | idempotency_key, 79 | res.status, 80 | String::from_utf8(res.body).unwrap_or_default(), 81 | )) 82 | } 83 | } 84 | Err((code, message)) => Err(format!( 85 | "the http_request resulted into error. code: {code:?}, error: {message}" 86 | )), 87 | } 88 | } 89 | } 90 | 91 | #[ic_cdk::query(hidden = true)] 92 | fn transform_jsonrpc(args: TransformArgs) -> HttpResponse { 93 | HttpResponse { 94 | status: args.response.status, 95 | body: args.response.body, 96 | // Remove headers (which may contain a timestamp) for consensus 97 | headers: vec![], 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/idempotent-proxy-server/src/cache/redis.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use idempotent_proxy_types::err_string; 3 | use rustis::bb8::{CustomizeConnection, ErrorSink, Pool}; 4 | use rustis::client::PooledClientManager; 5 | use rustis::commands::{GenericCommands, SetCondition, SetExpiration, StringCommands}; 6 | use rustis::resp::BulkString; 7 | use tokio::time::{sleep, Duration}; 8 | 9 | use super::Cacher; 10 | 11 | pub struct RedisClient { 12 | pool: Pool, 13 | } 14 | 15 | impl RedisClient { 16 | pub async fn new(url: &str) -> Result { 17 | let manager = PooledClientManager::new(url).unwrap(); 18 | let pool = Pool::builder() 19 | .max_size(10) 20 | .min_idle(Some(1)) 21 | .max_lifetime(None) 22 | .idle_timeout(Some(Duration::from_secs(600))) 23 | .connection_timeout(Duration::from_secs(3)) 24 | .error_sink(Box::new(RedisMonitor {})) 25 | .connection_customizer(Box::new(RedisMonitor {})) 26 | .build(manager) 27 | .await?; 28 | Ok(RedisClient { pool }) 29 | } 30 | } 31 | 32 | #[derive(Debug, Clone, Copy)] 33 | struct RedisMonitor; 34 | 35 | impl ErrorSink for RedisMonitor { 36 | fn sink(&self, error: E) { 37 | log::error!(target: "redis", "{}", error); 38 | } 39 | 40 | fn boxed_clone(&self) -> Box> { 41 | Box::new(*self) 42 | } 43 | } 44 | 45 | #[async_trait] 46 | impl CustomizeConnection for RedisMonitor { 47 | async fn on_acquire(&self, _connection: &mut C) -> Result<(), E> { 48 | log::info!(target: "redis", "connection acquired"); 49 | Ok(()) 50 | } 51 | } 52 | 53 | #[async_trait] 54 | impl Cacher for RedisClient { 55 | async fn obtain(&self, key: &str, ttl: u64) -> Result { 56 | let conn = self.pool.get().await.map_err(err_string)?; 57 | let res = conn 58 | .set_with_options( 59 | key, 60 | BulkString::from(vec![0]), 61 | SetCondition::NX, 62 | SetExpiration::Px(ttl), 63 | false, 64 | ) 65 | .await 66 | .map_err(err_string)?; 67 | Ok(res) 68 | } 69 | 70 | async fn polling_get( 71 | &self, 72 | key: &str, 73 | poll_interval: u64, 74 | counter: u64, 75 | ) -> Result, String> { 76 | let conn = self.pool.get().await.map_err(err_string)?; 77 | let mut counter = counter; 78 | while counter > 0 { 79 | let res: Option = conn.get(key).await.map_err(err_string)?; 80 | match res { 81 | None => return Err("not obtained".to_string()), 82 | Some(bs) => { 83 | if bs.len() > 1 { 84 | return Ok(bs.into()); 85 | } 86 | } 87 | } 88 | 89 | counter -= 1; 90 | sleep(Duration::from_millis(poll_interval)).await; 91 | } 92 | 93 | Err(("polling get cache timeout").to_string()) 94 | } 95 | 96 | async fn set(&self, key: &str, val: Vec, ttl: u64) -> Result { 97 | let conn = self.pool.get().await.map_err(err_string)?; 98 | let res = conn 99 | .set_with_options( 100 | key, 101 | BulkString::from(val), 102 | SetCondition::XX, 103 | SetExpiration::Px(ttl), 104 | false, 105 | ) 106 | .await 107 | .map_err(err_string)?; 108 | Ok(res) 109 | } 110 | 111 | async fn del(&self, key: &str) -> Result<(), String> { 112 | let conn = self.pool.get().await.map_err(err_string)?; 113 | let _ = conn.del(key).await.map_err(err_string)?; 114 | Ok(()) 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /examples/eth-canister/src/store.rs: -------------------------------------------------------------------------------- 1 | use candid::CandidType; 2 | use ciborium::{from_reader, into_writer}; 3 | use ic_stable_structures::{ 4 | memory_manager::{MemoryId, MemoryManager, VirtualMemory}, 5 | storable::Bound, 6 | DefaultMemoryImpl, StableCell, Storable, 7 | }; 8 | use serde::{Deserialize, Serialize}; 9 | use std::{borrow::Cow, cell::RefCell}; 10 | 11 | use crate::agent::RPCAgent; 12 | use crate::ecdsa::get_proxy_token_public_key; 13 | 14 | type Memory = VirtualMemory; 15 | 16 | #[derive(CandidType, Clone, Default, Deserialize, Serialize)] 17 | pub struct State { 18 | /// The name of the [EcdsaKeyId]. Use "dfx_test_key" for local replica and "test_key_1" for 19 | /// a testing key for testnet and mainnet 20 | pub ecdsa_key_name: String, 21 | 22 | pub rpc_proxy_public_key: String, 23 | 24 | pub rpc_agents: Vec, 25 | } 26 | 27 | impl Storable for State { 28 | const BOUND: Bound = Bound::Unbounded; 29 | 30 | fn to_bytes(&self) -> Cow<[u8]> { 31 | let mut buf = vec![]; 32 | into_writer(self, &mut buf).expect("failed to encode State data"); 33 | Cow::Owned(buf) 34 | } 35 | 36 | fn from_bytes(bytes: Cow<'_, [u8]>) -> Self { 37 | from_reader(&bytes[..]).expect("failed to decode State data") 38 | } 39 | } 40 | 41 | const STATE_MEMORY_ID: MemoryId = MemoryId::new(0); 42 | 43 | thread_local! { 44 | static STATE: RefCell = RefCell::new(State::default()); 45 | 46 | static MEMORY_MANAGER: RefCell> = 47 | RefCell::new(MemoryManager::init(DefaultMemoryImpl::default())); 48 | 49 | static STATE_STORE: RefCell> = RefCell::new( 50 | StableCell::init( 51 | MEMORY_MANAGER.with_borrow(|m| m.get(STATE_MEMORY_ID)), 52 | State::default() 53 | ).expect("failed to init STATE store") 54 | ); 55 | 56 | } 57 | 58 | pub mod state { 59 | use super::*; 60 | 61 | pub fn get_agent() -> RPCAgent { 62 | STATE.with(|r| r.borrow().rpc_agents.first().expect("no RPCAgent").clone()) 63 | } 64 | 65 | // pub fn get_attest_agents() -> Vec { 66 | // STATE.with(|r| { 67 | // r.borrow() 68 | // .rpc_agents 69 | // .split_first() 70 | // .map(|(_, v)| v.to_vec()) 71 | // .unwrap_or_default() 72 | // }) 73 | // } 74 | 75 | pub fn with(f: impl FnOnce(&State) -> R) -> R { 76 | STATE.with(|r| f(&r.borrow())) 77 | } 78 | 79 | pub fn with_mut(f: impl FnOnce(&mut State) -> R) -> R { 80 | STATE.with(|r| f(&mut r.borrow_mut())) 81 | } 82 | 83 | pub async fn init_ecdsa_public_key() { 84 | let ecdsa_key_name = with(|r| { 85 | if r.rpc_proxy_public_key.is_empty() && !r.ecdsa_key_name.is_empty() { 86 | Some(r.ecdsa_key_name.clone()) 87 | } else { 88 | None 89 | } 90 | }); 91 | 92 | if let Some(ecdsa_key_name) = ecdsa_key_name { 93 | let pk = get_proxy_token_public_key(&ecdsa_key_name) 94 | .await 95 | .unwrap_or_else(|err| { 96 | ic_cdk::trap(&format!("failed to retrieve ECDSA public key: {err}")) 97 | }); 98 | with_mut(|r| { 99 | r.rpc_proxy_public_key = pk; 100 | }); 101 | } 102 | } 103 | 104 | pub fn load() { 105 | STATE_STORE.with(|r| { 106 | let s = r.borrow_mut().get().clone(); 107 | STATE.with(|h| { 108 | *h.borrow_mut() = s; 109 | }); 110 | }); 111 | } 112 | 113 | pub fn save() { 114 | STATE.with(|h| { 115 | STATE_STORE.with(|r| { 116 | r.borrow_mut() 117 | .set(h.borrow().clone()) 118 | .expect("failed to set STATE data"); 119 | }); 120 | }); 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /src/idempotent-proxy-canister/src/init.rs: -------------------------------------------------------------------------------- 1 | use candid::CandidType; 2 | use serde::Deserialize; 3 | use std::time::Duration; 4 | 5 | use crate::{cose::CoseClient, store, tasks}; 6 | 7 | #[derive(Clone, Debug, CandidType, Deserialize)] 8 | pub enum ChainArgs { 9 | Init(InitArgs), 10 | Upgrade(UpgradeArgs), 11 | } 12 | 13 | #[derive(Clone, Debug, CandidType, Deserialize)] 14 | pub struct InitArgs { 15 | ecdsa_key_name: String, // Use "dfx_test_key" for local replica and "test_key_1" for a testing key for testnet and mainnet 16 | proxy_token_refresh_interval: u64, // seconds 17 | subnet_size: u64, // set to 0 to disable receiving cycles 18 | service_fee: u64, // in cycles 19 | cose: Option, 20 | } 21 | 22 | #[derive(Clone, Debug, CandidType, Deserialize)] 23 | pub struct UpgradeArgs { 24 | proxy_token_refresh_interval: Option, // seconds 25 | subnet_size: Option, 26 | service_fee: Option, // in cycles 27 | cose: Option, 28 | } 29 | 30 | #[ic_cdk::init] 31 | fn init(args: Option) { 32 | match args.expect("init args is missing") { 33 | ChainArgs::Init(args) => { 34 | store::state::with_mut(|s| { 35 | s.ecdsa_key_name = args.ecdsa_key_name; 36 | s.subnet_size = args.subnet_size; 37 | s.proxy_token_refresh_interval = if args.proxy_token_refresh_interval >= 10 { 38 | args.proxy_token_refresh_interval 39 | } else { 40 | 3600 41 | }; 42 | s.service_fee = if args.service_fee > 0 { 43 | args.service_fee 44 | } else { 45 | 100_000_000 46 | }; 47 | s.cose = args.cose; 48 | }); 49 | } 50 | ChainArgs::Upgrade(_) => { 51 | ic_cdk::trap( 52 | "cannot initialize the canister with an Upgrade args. Please provide an Init args.", 53 | ); 54 | } 55 | } 56 | 57 | ic_cdk_timers::set_timer(Duration::from_secs(0), || { 58 | ic_cdk::spawn(async { 59 | store::state::init_ecdsa_public_key().await; 60 | tasks::refresh_proxy_token().await; 61 | }) 62 | }); 63 | 64 | let proxy_token_refresh_interval = store::state::with(|s| s.proxy_token_refresh_interval); 65 | ic_cdk_timers::set_timer_interval(Duration::from_secs(proxy_token_refresh_interval), || { 66 | ic_cdk::spawn(tasks::refresh_proxy_token()) 67 | }); 68 | } 69 | 70 | #[ic_cdk::pre_upgrade] 71 | fn pre_upgrade() { 72 | store::state::save(); 73 | } 74 | 75 | #[ic_cdk::post_upgrade] 76 | fn post_upgrade(args: Option) { 77 | store::state::load(); 78 | 79 | match args { 80 | Some(ChainArgs::Upgrade(args)) => { 81 | store::state::with_mut(|s| { 82 | if let Some(proxy_token_refresh_interval) = args.proxy_token_refresh_interval { 83 | if proxy_token_refresh_interval < 10 { 84 | ic_cdk::trap("proxy_token_refresh_interval must be at least 10 seconds"); 85 | } 86 | 87 | s.proxy_token_refresh_interval = proxy_token_refresh_interval; 88 | } 89 | if let Some(subnet_size) = args.subnet_size { 90 | s.subnet_size = subnet_size; 91 | } 92 | if let Some(service_fee) = args.service_fee { 93 | s.service_fee = service_fee; 94 | } 95 | if let Some(cose) = args.cose { 96 | s.cose = Some(cose); 97 | } 98 | }); 99 | } 100 | Some(ChainArgs::Init(_)) => { 101 | ic_cdk::trap( 102 | "cannot upgrade the canister with an Init args. Please provide an Upgrade args.", 103 | ); 104 | } 105 | _ => {} 106 | } 107 | 108 | ic_cdk_timers::set_timer(Duration::from_secs(0), || { 109 | ic_cdk::spawn(async { 110 | store::state::init_ecdsa_public_key().await; 111 | tasks::refresh_proxy_token().await; 112 | }) 113 | }); 114 | 115 | let proxy_token_refresh_interval = store::state::with(|s| s.proxy_token_refresh_interval); 116 | ic_cdk_timers::set_timer_interval(Duration::from_secs(proxy_token_refresh_interval), || { 117 | ic_cdk::spawn(tasks::refresh_proxy_token()) 118 | }); 119 | } 120 | -------------------------------------------------------------------------------- /src/idempotent-proxy-canister/README.md: -------------------------------------------------------------------------------- 1 | # `idempotent-proxy-canister` 2 | 3 | The `idempotent-proxy-canister` is an ICP smart contract that can connect to 1 to N Idempotent Proxy services deployed by `idempotent-proxy-server` or `idempotent-proxy-cf-worker`. It provides on-chain HTTPS outcalls with idempotency for other smart contracts. 4 | 5 | The `idempotent-proxy-canister` automatically updates the proxy token periodically and offers the following three proxy interfaces to accommodate different business scenarios: 6 | 7 | 1. `proxy_http_request`: Prioritizes the first agent. If it fails (status code > 500), it attempts the next agent until it succeeds. 8 | 2. `parallel_call_any_ok`: Calls all agents in parallel. If any one succeeds, it returns the successful result; otherwise, it returns the last failed result. 9 | 3. `parallel_call_all_ok`: Calls all agents in parallel. Only returns a successful result if all agents succeed and the results are identical; otherwise, it returns a 500 error with an array of all results. 10 | 11 | Note: If only one agent is configured, all three interfaces are equivalent. 12 | 13 | ![Idempotent Proxy Canister](../../idempotent-proxy-canister.webp) 14 | 15 | ## Online Demo 16 | 17 | idempotent-proxy-canister: https://a4gq6-oaaaa-aaaab-qaa4q-cai.raw.icp0.io/?id=hpudd-yqaaa-aaaap-ahnbq-cai 18 | 19 | ## Running the project locally 20 | 21 | If you want to test your project locally, you can use the following commands: 22 | 23 | ```bash 24 | # Starts the replica, running in the background 25 | dfx start --background 26 | 27 | # deploy the canister 28 | dfx deploy idempotent-proxy-canister --argument "(opt variant {Init = 29 | record { 30 | ecdsa_key_name = \"dfx_test_key\"; 31 | proxy_token_refresh_interval = 3600; 32 | subnet_size = 1; 33 | service_fee = 10_000_000; 34 | } 35 | })" 36 | 37 | dfx canister call idempotent-proxy-canister get_state '()' 38 | 39 | # upgrade 40 | dfx deploy idempotent-proxy-canister --argument "(opt variant {Upgrade = 41 | record { 42 | proxy_token_refresh_interval = null; 43 | subnet_size = opt 13; 44 | service_fee = opt 100_000_000; 45 | } 46 | })" 47 | 48 | # 3 same agents for testing 49 | dfx canister call idempotent-proxy-canister admin_set_agents ' 50 | (vec { 51 | record { 52 | name = "LDCLabs"; 53 | endpoint = "https://idempotent-proxy-cf-worker.zensh.workers.dev"; 54 | max_cycles = 100000000000; 55 | proxy_token = null; 56 | }; record { 57 | name = "LDCLabs"; 58 | endpoint = "https://idempotent-proxy-cf-worker.zensh.workers.dev"; 59 | max_cycles = 100000000000; 60 | proxy_token = null; 61 | }; record { 62 | name = "LDCLabs"; 63 | endpoint = "https://idempotent-proxy-cf-worker.zensh.workers.dev"; 64 | max_cycles = 100000000000; 65 | proxy_token = null; 66 | }; 67 | }) 68 | ' 69 | 70 | MYID=$(dfx identity get-principal) 71 | 72 | dfx canister call idempotent-proxy-canister admin_add_managers "(vec {principal \"$MYID\"})" 73 | 74 | dfx canister call idempotent-proxy-canister admin_add_callers "(vec {principal \"$MYID\"})" 75 | 76 | dfx canister call idempotent-proxy-canister get_state '()' 77 | 78 | # URL_HTTPBIN == "https://httpbin.org/get?api-key=abc123" 79 | dfx canister call idempotent-proxy-canister proxy_http_request "(record { 80 | url = \"URL_HTTPBIN\"; 81 | method = variant{ \"get\" }; 82 | max_response_bytes = null; 83 | body = null; 84 | transform = null; 85 | headers = vec { 86 | record { name = \"idempotency-key\"; value = \"idempotency_key_001\"; }; 87 | }; 88 | })" 89 | 90 | dfx canister call idempotent-proxy-canister parallel_call_any_ok "(record { 91 | url = \"https://httpbin.org/get?api-key=abc123\"; 92 | method = variant{ \"get\" }; 93 | max_response_bytes = null; 94 | body = null; 95 | transform = null; 96 | headers = vec { 97 | record { name = \"idempotency-key\"; value = \"idempotency_key_001\"; }; 98 | }; 99 | })" 100 | 101 | dfx canister call idempotent-proxy-canister parallel_call_all_ok "(record { 102 | url = \"URL_HTTPBIN\"; 103 | method = variant{ \"get\" }; 104 | max_response_bytes = null; 105 | body = null; 106 | transform = null; 107 | headers = vec { 108 | record { name = \"idempotency-key\"; value = \"idempotency_key_001\"; }; 109 | }; 110 | })" 111 | 112 | ``` 113 | 114 | `idempotent-proxy-cf-worker` does not enable `proxy-authorization`, so it can be accessed. 115 | 116 | ## License 117 | Copyright © 2024 [LDC Labs](https://github.com/ldclabs). 118 | 119 | `ldclabs/idempotent-proxy` is licensed under the MIT License. See [LICENSE](../../LICENSE-MIT) for the full license text. -------------------------------------------------------------------------------- /src/idempotent-proxy-cf-worker/src/util.ts: -------------------------------------------------------------------------------- 1 | import { base64ToBytes, ed25519Verify, ecdsaVerify } from './auth' 2 | import { encode, decode } from 'cborg' 3 | 4 | export interface Pubkeys { 5 | ecdsa: Array // ECDSA/secp256k1 6 | ed25519: Array 7 | } 8 | 9 | export class EnvVars { 10 | private _env: any 11 | private _pubKeys: Pubkeys 12 | 13 | constructor(env: any = {}) { 14 | this._env = env 15 | this._pubKeys = { 16 | ecdsa: [], 17 | ed25519: [] 18 | } 19 | } 20 | 21 | getString(key: string): string { 22 | return this._env[key] || '' 23 | } 24 | 25 | parsePubkeys(): boolean { 26 | for (const key of Object.keys(this._env)) { 27 | if (key.startsWith('ECDSA_PUB_KEY')) { 28 | this._pubKeys.ecdsa.push(base64ToBytes(this._env[key])) 29 | } else if (key.startsWith('ED25519_PUB_KEY')) { 30 | this._pubKeys.ed25519.push(base64ToBytes(this._env[key])) 31 | } 32 | } 33 | 34 | return this._pubKeys.ecdsa.length > 0 || this._pubKeys.ed25519.length > 0 35 | } 36 | 37 | // return the agent name if the token is valid 38 | verifyToken(token: string): string { 39 | if (!token.startsWith('Bearer ')) { 40 | throw new Error('invalid bearer token') 41 | } 42 | 43 | const data = base64ToBytes(token.slice(7)) 44 | if (this._pubKeys.ecdsa.length > 0) { 45 | return ecdsaVerify(this._pubKeys.ecdsa, data)[1] 46 | } else if (this._pubKeys.ed25519.length > 0) { 47 | return ed25519Verify(this._pubKeys.ecdsa, data)[1] 48 | } 49 | 50 | throw new Error('no public key found') 51 | } 52 | } 53 | 54 | export class ResponseData { 55 | status: number 56 | headers: Array<[string, string]> 57 | body: Uint8Array | null 58 | mime: string 59 | 60 | static fromBytes(data: Uint8Array): ResponseData { 61 | const obj = decode(data) 62 | const rd = new ResponseData(obj.status) 63 | rd.headers = obj.headers 64 | rd.body = obj.body 65 | rd.mime = obj.mime 66 | return rd 67 | } 68 | 69 | constructor(status: number = 200) { 70 | this.status = status 71 | this.headers = [] 72 | this.body = null 73 | this.mime = 'text/plain' 74 | } 75 | 76 | setHeaders(headers: Headers, filtering: string): this { 77 | const fi = filtering 78 | .toLocaleLowerCase() 79 | .split(',') 80 | .map((v) => v.trim()) 81 | .filter((v) => v.length > 0) 82 | for (const [key, value] of headers) { 83 | if (key == 'content-type') { 84 | this.mime = value 85 | } else if ( 86 | key != 'content-length' && key != 'transfer-encoding' && 87 | (fi.length == 0 || fi.includes(key)) 88 | ) { 89 | this.headers.push([key, value]) 90 | } 91 | } 92 | return this 93 | } 94 | 95 | setBody(body: Uint8Array, filtering: string): this { 96 | const fi = filtering 97 | .split(',') 98 | .map((v) => v.trim()) 99 | .filter((v) => v.length > 0) 100 | if ( 101 | fi.length > 0 && 102 | this.status < 300 && 103 | this.mime.includes('application/json') 104 | ) { 105 | const decoder = new TextDecoder() 106 | const str = decoder.decode(body) 107 | const obj = JSON.parse(str) 108 | const newObj = {} as any 109 | for (const key of fi) { 110 | if (Object.hasOwn(obj, key)) { 111 | newObj[key] = obj[key] 112 | } 113 | } 114 | 115 | this.body = new TextEncoder().encode(JSON.stringify(newObj)) 116 | } else if ( 117 | fi.length > 0 && 118 | this.status < 300 && 119 | this.mime.includes('application/cbor') 120 | ) { 121 | const obj = decode(body) 122 | const newObj = {} as any 123 | for (const key of fi) { 124 | if (Object.hasOwn(obj, key)) { 125 | newObj[key] = obj[key] 126 | } 127 | } 128 | this.body = encode(newObj) 129 | } else { 130 | this.body = body 131 | } 132 | 133 | return this 134 | } 135 | 136 | toBytes(): Uint8Array { 137 | return encode({ 138 | headers: this.headers, 139 | body: this.body, 140 | mime: this.mime, 141 | status: this.status 142 | }) 143 | } 144 | 145 | toResponse(): Response { 146 | const headers = new Headers(this.headers) 147 | headers.set('content-type', this.mime) 148 | 149 | return new Response(this.body, { 150 | headers, 151 | status: 200 152 | }) 153 | } 154 | } 155 | 156 | const filterHeaders = [ 157 | 'host', 158 | 'forwarded', 159 | 'proxy-authorization', 160 | 'x-forwarded-for', 161 | 'x-forwarded-host', 162 | 'x-forwarded-proto', 163 | 'idempotency-key' 164 | ] 165 | 166 | export function proxyRequestHeaders(headers: Headers, ev: EnvVars): Headers { 167 | const newHeaders = new Headers() 168 | for (const [key, value] of headers) { 169 | if (!filterHeaders.includes(key)) { 170 | newHeaders.append( 171 | key, 172 | value.startsWith('HEADER_') ? ev.getString(value) : value 173 | ) 174 | } 175 | } 176 | return newHeaders 177 | } 178 | -------------------------------------------------------------------------------- /src/idempotent-proxy-server/README.md: -------------------------------------------------------------------------------- 1 | # Idempotent Proxy 2 | Reverse proxy server with build-in idempotency support written in Rust. 3 | 4 | ## Overview 5 | 6 | The idempotent-proxy is a reverse proxy service written in Rust with built-in idempotency support. 7 | 8 | When multiple requests with the same idempotency-key arrive within a specific timeframe, only the first request is forwarded to the target service. The response is cached in Redis, and subsequent requests poll Redis to retrieve and return the first request's response. 9 | 10 | This service can be used to proxy [HTTPS outcalls](https://internetcomputer.org/docs/current/developer-docs/smart-contracts/advanced-features/https-outcalls/https-outcalls-overview) for [ICP canisters](https://internetcomputer.org/docs/current/developer-docs/smart-contracts/overview/introduction), enabling integration with any Web2 http service. It supports hiding secret information, access control, returning only the necessary headers and, for JSON or CBOR data, allows response filtering based on JSON Mask to return only required fields, thus saving cycles consumption in ICP canisters. 11 | 12 | ![Idempotent Proxy](../../idempotent-proxy.png) 13 | 14 | ## Features 15 | - [x] Reverse proxy with build-in idempotency support 16 | - [x] JSON response filtering 17 | - [x] Access control 18 | - [x] Response headers filtering 19 | - [x] HTTPS support 20 | - [x] Running as Cloudflare Worker 21 | - [x] Docker image 22 | 23 | ## Deploy 24 | 25 | ### Run proxy in development mode 26 | 27 | Run proxy: 28 | ```bash 29 | # docker run --name redis -d -p 6379:6379 redis:latest # optional redis 30 | cargo run -p idempotent-proxy-server 31 | ``` 32 | 33 | ### Building and running AWS Nitro Enclave image 34 | 35 | #### Setup host machine 36 | 37 | https://docs.marlin.org/learn/oyster/core-concepts/networking/outgoing 38 | 39 | ```bash 40 | wget -O vsock-to-ip-transparent http://public.artifacts.marlin.pro/projects/enclaves/vsock-to-ip-transparent_v1.0.0_linux_amd64 41 | chmod +x vsock-to-ip-transparent 42 | ./vsock-to-ip-transparent --vsock-addr 3:1200 43 | ``` 44 | 45 | https://docs.marlin.org/learn/oyster/core-concepts/networking/incoming 46 | 47 | iptables rules: 48 | ```bash 49 | # route incoming packets on port 80 to the transparent proxy 50 | iptables -A PREROUTING -t nat -p tcp --dport 80 -i ens5 -j REDIRECT --to-port 1200 51 | # route incoming packets on port 443 to the transparent proxy 52 | iptables -A PREROUTING -t nat -p tcp --dport 443 -i ens5 -j REDIRECT --to-port 1200 53 | # route incoming packets on port 1025:65535 to the transparent proxy 54 | iptables -A PREROUTING -t nat -p tcp --dport 1025:65535 -i ens5 -j REDIRECT --to-port 1200 55 | ``` 56 | 57 | ```bash 58 | wget -O port-to-vsock-transparent http://public.artifacts.marlin.pro/projects/enclaves/port-to-vsock-transparent_v1.0.0_linux_amd64 59 | chmod +x port-to-vsock-transparent 60 | ./port-to-vsock-transparent --vsock 88 --ip-addr 0.0.0.0:1200 61 | ``` 62 | 63 | #### Build and run enclave 64 | 65 | The following steps should be run in AWS Nitro-based instances. 66 | 67 | https://docs.aws.amazon.com/enclaves/latest/user/getting-started.html 68 | 69 | ```bash 70 | sudo nitro-cli build-enclave --docker-uri ghcr.io/ldclabs/idempotent-proxy_enclave_amd64:latest --output-file idempotent-proxy_enclave_amd64.eif 71 | # Start building the Enclave Image... 72 | # Using the locally available Docker image... 73 | # Enclave Image successfully created. 74 | # { 75 | # "Measurements": { 76 | # "HashAlgorithm": "Sha384 { ... }", 77 | # "PCR0": "bbfe317cdaba604e1364fbd254150ce25516d83e31a87f8b3d8acb163286f57f51d8b3f6b2a482ac209b758334d996d9", 78 | # "PCR1": "4b4d5b3661b3efc12920900c80e126e4ce783c522de6c02a2a5bf7af3a2b9327b86776f188e4be1c1c404a129dbda493", 79 | # "PCR2": "9ea2080d6e6bd61f03a62357a1cbbae278b070db5df6b1fe5c57821ff249b77add0f95dab0a5beec7aa6ef6735f27b14" 80 | # } 81 | # } 82 | sudo nitro-cli run-enclave --cpu-count 2 --memory 512 --enclave-cid 88 --eif-path idempotent-proxy_enclave_amd64.eif --debug-mode 83 | # Started enclave with enclave-cid: 88, memory: 512 MiB, cpu-ids: [1, 3] 84 | # { 85 | # "EnclaveName": "idempotent-proxy_enclave_amd64", 86 | # "EnclaveID": "i-056e1ab9a31cd77a0-enc190ca7263013fd3", 87 | # "ProcessID": 21493, 88 | # "EnclaveCID": 88, 89 | # "NumberOfCPUs": 2, 90 | # "CPUIDs": [ 91 | # 1, 92 | # 3 93 | # ], 94 | # "MemoryMiB": 512 95 | # } 96 | sudo nitro-cli describe-enclaves 97 | sudo nitro-cli console --enclave-id i-056e1ab9a31cd77a0-enc190ca7263013fd3 98 | sudo nitro-cli terminate-enclave --enclave-id i-056e1ab9a31cd77a0-enc190ca7263013fd3 99 | ``` 100 | 101 | 102 | #### Make a request 103 | 104 | ```bash 105 | curl -v -X POST \ 106 | --url http://YOUR_HOST/ \ 107 | --header 'content-type: application/json' \ 108 | --header 'x-forwarded-host: cloudflare-eth.com' \ 109 | --header 'idempotency-key: key_001' \ 110 | --data '{ 111 | "id": 1, 112 | "jsonrpc": "2.0", 113 | "method": "eth_getBlockByNumber", 114 | "params": ["latest", false] 115 | }' 116 | ``` 117 | 118 | ## License 119 | Copyright © 2024 [LDC Labs](https://github.com/ldclabs). 120 | 121 | `ldclabs/idempotent-proxy` is licensed under the MIT License. See [LICENSE](../../LICENSE-MIT) for the full license text. -------------------------------------------------------------------------------- /examples/eth-canister-lite/src/jsonrpc.rs: -------------------------------------------------------------------------------- 1 | use candid::Principal; 2 | use ic_cdk::api::management_canister::http_request::{ 3 | CanisterHttpRequestArgument, HttpHeader, HttpMethod, HttpResponse, 4 | }; 5 | use serde::{de::DeserializeOwned, Deserialize, Serialize}; 6 | use serde_json::{to_vec, Value}; 7 | 8 | pub static APP_AGENT: &str = concat!( 9 | "Mozilla/5.0 eth-canister ", 10 | env!("CARGO_PKG_NAME"), 11 | "/", 12 | env!("CARGO_PKG_VERSION"), 13 | ); 14 | 15 | pub struct EthereumRPC { 16 | pub provider: String, // provider url or `URL_` constant defined in the Idempotent Proxy 17 | pub proxy: Principal, // idempotent-proxy-canister id 18 | pub api_token: Option, 19 | } 20 | 21 | #[derive(Debug, Serialize)] 22 | pub struct RPCRequest<'a> { 23 | jsonrpc: &'a str, 24 | method: &'a str, 25 | params: &'a [Value], 26 | id: u64, 27 | } 28 | 29 | #[derive(Debug, Deserialize)] 30 | pub struct RPCResponse { 31 | result: Option, 32 | error: Option, 33 | } 34 | 35 | impl EthereumRPC { 36 | pub async fn eth_chain_id(&self, idempotency_key: String) -> Result { 37 | self.call("proxy_http_request", idempotency_key, "eth_chainId", &[]) 38 | .await 39 | } 40 | 41 | pub async fn get_best_block(&self, idempotency_key: String) -> Result { 42 | self.call( 43 | "parallel_call_all_ok", 44 | idempotency_key, 45 | "eth_getBlockByNumber", 46 | &["latest".into(), false.into()], 47 | ) 48 | .await 49 | } 50 | 51 | pub async fn send_raw_transaction( 52 | &self, 53 | idempotency_key: String, 54 | raw_tx: String, 55 | ) -> Result { 56 | self.call( 57 | "parallel_call_any_ok", 58 | idempotency_key, 59 | "eth_sendTransaction", 60 | &[raw_tx.into()], 61 | ) 62 | .await 63 | } 64 | 65 | // you can add more methods here 66 | 67 | pub async fn call( 68 | &self, 69 | proxy_method: &str, // "proxy_http_request" | "parallel_call_any_ok" | "parallel_call_all_ok" 70 | idempotency_key: String, 71 | method: &str, 72 | params: &[Value], 73 | ) -> Result { 74 | let input = RPCRequest { 75 | jsonrpc: "2.0", 76 | method, 77 | params, 78 | id: 1, 79 | }; 80 | let input = to_vec(&input).map_err(|err| err.to_string())?; 81 | let data = self.proxy(proxy_method, idempotency_key, input).await?; 82 | 83 | let output: RPCResponse = 84 | serde_json::from_slice(&data).map_err(|err| err.to_string())?; 85 | 86 | if let Some(error) = output.error { 87 | return Err(serde_json::to_string(&error).map_err(|err| err.to_string())?); 88 | } 89 | 90 | match output.result { 91 | Some(result) => Ok(result), 92 | None => serde_json::from_value(Value::Null).map_err(|err| err.to_string()), 93 | } 94 | } 95 | 96 | async fn proxy( 97 | &self, 98 | proxy_method: &str, 99 | idempotency_key: String, 100 | body: Vec, 101 | ) -> Result, String> { 102 | let mut request_headers = vec![ 103 | HttpHeader { 104 | name: "content-type".to_string(), 105 | value: "application/json".to_string(), 106 | }, 107 | HttpHeader { 108 | name: "user-agent".to_string(), 109 | value: APP_AGENT.to_string(), 110 | }, 111 | HttpHeader { 112 | name: "idempotency-key".to_string(), 113 | value: idempotency_key.clone(), 114 | }, 115 | ]; 116 | 117 | if let Some(api_token) = &self.api_token { 118 | request_headers.push(HttpHeader { 119 | name: "authorization".to_string(), 120 | value: api_token.clone(), 121 | }); 122 | } 123 | 124 | let request = CanisterHttpRequestArgument { 125 | url: self.provider.clone(), 126 | max_response_bytes: None, //optional for request 127 | method: HttpMethod::POST, 128 | headers: request_headers, 129 | body: Some(body), 130 | transform: None, 131 | }; 132 | 133 | let (res,): (HttpResponse,) = ic_cdk::api::call::call_with_payment128( 134 | self.proxy, 135 | proxy_method, 136 | (request,), 137 | 1_000_000_000, // max cycles, unspent cycles will be refunded 138 | ) 139 | .await 140 | .map_err(|(code, msg)| { 141 | format!( 142 | "failed to call {} on {:?}, code: {}, message: {}", 143 | proxy_method, &self.proxy, code as u32, msg 144 | ) 145 | })?; 146 | 147 | if res.status >= 200u64 && res.status < 300u64 { 148 | Ok(res.body) 149 | } else { 150 | Err(format!( 151 | "failed to request provider: {}, idempotency-key: {}, status: {}, body: {}", 152 | self.provider, 153 | idempotency_key, 154 | res.status, 155 | String::from_utf8(res.body).unwrap_or_default(), 156 | )) 157 | } 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /src/idempotent-proxy-types/src/auth.rs: -------------------------------------------------------------------------------- 1 | use ciborium::{from_reader, into_writer}; 2 | use ed25519_dalek::Signer; 3 | use k256::{ 4 | ecdsa, 5 | ecdsa::signature::hazmat::{PrehashSigner, PrehashVerifier}, 6 | }; 7 | use serde::{Deserialize, Serialize}; 8 | use serde_bytes::ByteBuf; 9 | use sha3::{Digest, Sha3_256}; 10 | 11 | use crate::unix_ms; 12 | 13 | const PERMITTED_DRIFT: u64 = 10; // seconds 14 | 15 | // Token format: [expire_at in seconds, agent, signature] 16 | #[derive(Debug, Deserialize, Serialize, PartialEq, Eq, Clone)] 17 | pub struct Token(pub u64, pub String, pub ByteBuf); 18 | 19 | pub fn ed25519_sign(key: &ed25519_dalek::SigningKey, expire_at: u64, agent: String) -> Vec { 20 | let mut buf: Vec = Vec::new(); 21 | into_writer(&(expire_at, &agent), &mut buf).expect("failed to encode data in CBOR format"); 22 | 23 | let sig = key.sign(&buf).to_bytes(); 24 | buf.clear(); 25 | into_writer(&(expire_at, agent, ByteBuf::from(sig)), &mut buf) 26 | .expect("failed to encode in CBOR format"); 27 | buf 28 | } 29 | 30 | pub fn ed25519_verify(keys: &[ed25519_dalek::VerifyingKey], data: &[u8]) -> Result { 31 | let token: Token = from_reader(data).map_err(|_err| "failed to decode CBOR data")?; 32 | if token.0 + PERMITTED_DRIFT < unix_ms() / 1000 { 33 | return Err("token expired".to_string()); 34 | } 35 | let sig = ed25519_dalek::Signature::from_slice(token.2.as_slice()) 36 | .map_err(|_err| "failed to parse Ed25519 signature")?; 37 | let mut buf: Vec = Vec::new(); 38 | into_writer(&(token.0, &token.1), &mut buf).expect("failed to encode data in CBOR format"); 39 | for key in keys.iter() { 40 | if key.verify_strict(&buf, &sig).is_ok() { 41 | return Ok(token); 42 | } 43 | } 44 | 45 | Err("failed to verify Ed25519 signature".to_string()) 46 | } 47 | 48 | // Secp256k1 49 | pub fn ecdsa_sign(key: &ecdsa::SigningKey, expire_at: u64, agent: String) -> Vec { 50 | let mut buf: Vec = Vec::new(); 51 | into_writer(&(expire_at, &agent), &mut buf).expect("failed to encode data in CBOR format"); 52 | let digest = sha3_256(&buf); 53 | let sig: ecdsa::Signature = key 54 | .sign_prehash(&digest) 55 | .expect("failed to sign Secp256k1 signature"); 56 | buf.clear(); 57 | into_writer(&(expire_at, agent, ByteBuf::from(sig.to_vec())), &mut buf) 58 | .expect("failed to encode in CBOR format"); 59 | buf 60 | } 61 | 62 | // Secp256k1 63 | pub fn ecdsa_verify(keys: &[ecdsa::VerifyingKey], data: &[u8]) -> Result { 64 | let token: Token = from_reader(data).map_err(|_err| "failed to decode CBOR data")?; 65 | if token.0 + PERMITTED_DRIFT < unix_ms() / 1000 { 66 | return Err("token expired".to_string()); 67 | } 68 | let sig = ecdsa::Signature::try_from(token.2.as_slice()) 69 | .map_err(|_err| "failed to parse Secp256k1 signature")?; 70 | let mut buf: Vec = Vec::new(); 71 | into_writer(&(token.0, &token.1), &mut buf).expect("failed to encode data in CBOR format"); 72 | let digest = sha3_256(&buf); 73 | 74 | for key in keys.iter() { 75 | if key.verify_prehash(digest.as_slice(), &sig).is_ok() { 76 | return Ok(token); 77 | } 78 | } 79 | 80 | Err("failed to verify ECDSA/Secp256k1 signature".to_string()) 81 | } 82 | 83 | pub fn sha3_256(data: &[u8]) -> [u8; 32] { 84 | let mut hasher = Sha3_256::new(); 85 | hasher.update(data); 86 | hasher.finalize().into() 87 | } 88 | 89 | #[cfg(test)] 90 | mod test { 91 | use super::*; 92 | use base64::{engine::general_purpose, Engine}; 93 | use k256::PublicKey; 94 | use rand_core::{OsRng, RngCore}; 95 | 96 | #[test] 97 | fn test_ed25519_token() { 98 | let mut secret_key = [0u8; 32]; 99 | OsRng.fill_bytes(&mut secret_key); 100 | let signing_key: ed25519_dalek::SigningKey = 101 | ed25519_dalek::SigningKey::from_bytes(&secret_key); 102 | let agent = "alice".to_string(); 103 | let expire_at = unix_ms() / 1000 + 3600; 104 | let signed = super::ed25519_sign(&signing_key, expire_at, agent.clone()); 105 | let token = super::ed25519_verify(&[signing_key.verifying_key()], &signed).unwrap(); 106 | assert_eq!(token.0, expire_at); 107 | assert_eq!(token.1, agent); 108 | } 109 | 110 | #[test] 111 | #[ignore] 112 | fn test_secp256k1_token() { 113 | let signing_key = ecdsa::SigningKey::random(&mut OsRng); 114 | let agent = "alice".to_string(); 115 | let expire_at = unix_ms() / 1000 + 3600; 116 | let signed = super::ecdsa_sign(&signing_key, expire_at, agent.clone()); 117 | let token = 118 | super::ecdsa_verify(&[ecdsa::VerifyingKey::from(&signing_key)], &signed).unwrap(); 119 | assert_eq!(token.0, expire_at); 120 | assert_eq!(token.1, agent); 121 | 122 | println!( 123 | "token: {:?}", 124 | general_purpose::URL_SAFE_NO_PAD.encode(&signed) 125 | ); 126 | 127 | let pk: PublicKey = signing_key.verifying_key().into(); 128 | let pk = pk.to_sec1_bytes(); 129 | let pk = general_purpose::URL_SAFE_NO_PAD.encode(&pk); 130 | println!("{:?}", pk); 131 | 132 | // let pk = general_purpose::URL_SAFE_NO_PAD 133 | // .decode("A44DZpzDwDvq9HwW3_dynOfDgkMJHKgOxUyCOrv5Pl3O") 134 | // .expect("invalid base64"); 135 | // let pk = ecdsa::VerifyingKey::from_sec1_bytes(&pk).expect("invalid ecdsa public key"); 136 | // let data = general_purpose::URL_SAFE_NO_PAD 137 | // .decode("gxpmZDmJaklDUGFuZGFEQU9YQMQr36UI8JV2jJEM_PMe96GsgymHzjfsbZyAsFSHF0FUNsuj6LKsqHg2dzYG9RoxQRtrcGsphYsNiQJwG3g9Ju4") 138 | // .expect("invalid base64"); 139 | // let token = super::ecdsa_verify(&[pk], &data).unwrap(); 140 | println!("{:?}", token); 141 | // Token(1717844361, "ICPandaDAO", [196, 43, 223, ... 61, 38, 238]) 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /src/idempotent-proxy-cf-worker/src/index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Welcome to Cloudflare Workers! This is your first worker. 3 | * 4 | * - Run `npm run dev` in your terminal to start a development server 5 | * - Open a browser tab at http://localhost:8787/ to see your worker in action 6 | * - Run `npm run deploy` to publish your worker 7 | * 8 | * Learn more at https://developers.cloudflare.com/workers/ 9 | */ 10 | 11 | import { DurableObject } from 'cloudflare:workers' 12 | import { EnvVars, ResponseData, proxyRequestHeaders } from './util' 13 | 14 | const HEADER_PROXY_AUTHORIZATION = 'proxy-authorization' 15 | const HEADER_X_FORWARDED_HOST = 'x-forwarded-host' 16 | const HEADER_IDEMPOTENCY_KEY = 'idempotency-key' 17 | const HEADER_X_JSON_MASK = 'x-json-mask' 18 | const HEADER_RESPONSE_HEADERS = 'response-headers' 19 | 20 | export interface Env { 21 | POLL_INTERVAL: number // in milliseconds 22 | REQUEST_TIMEOUT: number // in milliseconds 23 | ALLOW_AGENTS: string[] 24 | MY_DURABLE_OBJECT: DurableObjectNamespace 25 | CACHER: DurableObjectNamespace 26 | } 27 | 28 | // Worker 29 | export default { 30 | async fetch( 31 | req: Request, 32 | env: Env, 33 | _ctx: ExecutionContext 34 | ): Promise { 35 | const ev = new EnvVars(env) 36 | let agent = 'ANON' 37 | if (ev.parsePubkeys()) { 38 | try { 39 | agent = ev.verifyToken( 40 | req.headers.get(HEADER_PROXY_AUTHORIZATION) || '' 41 | ) 42 | } catch (err) { 43 | return new Response(`${err}`, { status: 407 }) 44 | } 45 | } 46 | 47 | if (env.ALLOW_AGENTS.length > 0 && !env.ALLOW_AGENTS.includes(agent)) { 48 | return new Response(`agent ${agent} is not allowed`, { status: 403 }) 49 | } 50 | 51 | let url = new URL(req.url) 52 | if (req.method == 'GET' && url.pathname == '/') { 53 | return new Response('idempotent-proxy-cf-worker', { 54 | headers: { 'content-type': 'text/plain' } 55 | }) 56 | } 57 | 58 | if (url.pathname.startsWith('/URL_')) { 59 | url = new URL(ev.getString(url.pathname.slice(1))) 60 | } else { 61 | const host = req.headers.get(HEADER_X_FORWARDED_HOST) 62 | if (!host) { 63 | return new Response('missing header: ' + HEADER_X_FORWARDED_HOST, { 64 | status: 400 65 | }) 66 | } 67 | url.port = '' 68 | url.protocol = 'https' 69 | url.host = host 70 | } 71 | 72 | const idempotencyKey = req.headers.get(HEADER_IDEMPOTENCY_KEY) 73 | if (!idempotencyKey) { 74 | return new Response('missing header: ' + HEADER_IDEMPOTENCY_KEY, { 75 | status: 400 76 | }) 77 | } 78 | 79 | const id = env.CACHER.idFromName(`${agent}:${req.method}:${idempotencyKey}`) 80 | const stub = env.CACHER.get(id) 81 | 82 | try { 83 | const lock = await stub.obtain() 84 | if (!lock) { 85 | const data = await polling_get( 86 | stub, 87 | env.POLL_INTERVAL, 88 | Math.floor(env.REQUEST_TIMEOUT / env.POLL_INTERVAL) 89 | ) 90 | const rd = ResponseData.fromBytes(data) 91 | return rd.toResponse() 92 | } 93 | 94 | const res = await fetch(url, { 95 | method: req.method, 96 | headers: proxyRequestHeaders(req.headers, ev), 97 | body: req.body 98 | }) 99 | 100 | if (res.status >= 200 && res.status <= 500) { 101 | const data = await res.arrayBuffer() 102 | const rd = new ResponseData(res.status) 103 | .setHeaders( 104 | new Headers(res.headers), 105 | req.headers.get(HEADER_RESPONSE_HEADERS) || '' 106 | ) 107 | .setBody( 108 | new Uint8Array(data), 109 | req.headers.get(HEADER_X_JSON_MASK) || '' 110 | ) 111 | await stub.set(rd.toBytes()) 112 | return rd.toResponse() 113 | } 114 | 115 | stub.del() 116 | return new Response(await res.text(), { 117 | status: res.status 118 | }) 119 | } catch (err) { 120 | stub.del() 121 | return new Response(String(err), { status: 500 }) 122 | } 123 | } 124 | } 125 | 126 | async function polling_get( 127 | stub: DurableObjectStub, 128 | poll_interval: number, 129 | counter: number 130 | ): Promise { 131 | while (counter > 0) { 132 | const value = await stub.get() 133 | if (value) { 134 | return new Uint8Array(value) 135 | } 136 | 137 | counter -= 1 138 | await new Promise((resolve) => setTimeout(resolve, poll_interval)) 139 | } 140 | 141 | throw new Error('polling get cache timeout') 142 | } 143 | 144 | // Durable Object 145 | export class Cacher extends DurableObject { 146 | private readonly ttl: number 147 | private status: number // 0, 1, 2 148 | 149 | constructor(ctx: DurableObjectState, env: Env) { 150 | super(ctx, env) 151 | this.status = 0 152 | this.ttl = env.REQUEST_TIMEOUT || 10 * 1000 153 | 154 | this.ctx.blockConcurrencyWhile(async () => { 155 | this.status = (await this.ctx.storage.get('s')) || 0 156 | }) 157 | if (this.ctx.storage.getAlarm() == null) { 158 | this.ctx.storage.setAlarm(Date.now() + this.ttl) 159 | } 160 | } 161 | 162 | async obtain(): Promise { 163 | if (this.status == 0) { 164 | this.status = 1 165 | this.ctx.storage.put('s', this.status) 166 | return true 167 | } 168 | return false 169 | } 170 | 171 | async get(): Promise { 172 | if (this.status == 0) { 173 | throw new Error('not obtained') 174 | } else if (this.status != 2) { 175 | return null 176 | } 177 | return (await this.ctx.storage.get('v')) || null 178 | } 179 | 180 | async set(value: Uint8Array): Promise { 181 | this.status = 2 182 | this.ctx.storage.setAlarm(Date.now() + this.ttl) 183 | await Promise.all([ 184 | this.ctx.storage.put('s', this.status), 185 | this.ctx.storage.put('v', value) 186 | ]) 187 | } 188 | 189 | async del(): Promise { 190 | this.status = 0 191 | await Promise.all([ 192 | this.ctx.storage.deleteAlarm(), 193 | this.ctx.storage.deleteAll() 194 | ]) 195 | } 196 | 197 | async alarm() { 198 | this.del() 199 | } 200 | } 201 | -------------------------------------------------------------------------------- /src/idempotent-proxy-server/src/main.rs: -------------------------------------------------------------------------------- 1 | use axum::{routing, Router}; 2 | use axum_server::tls_rustls::RustlsConfig; 3 | use base64::{engine::general_purpose, Engine}; 4 | use dotenvy::dotenv; 5 | use http::HeaderValue; 6 | use k256::ecdsa; 7 | use reqwest::ClientBuilder; 8 | use std::{ 9 | collections::{BTreeSet, HashMap}, 10 | net::SocketAddr, 11 | sync::Arc, 12 | time::Duration, 13 | }; 14 | use structured_logger::{async_json::new_writer, get_env_level, Builder}; 15 | use tokio::signal; 16 | 17 | mod cache; 18 | mod handler; 19 | 20 | const APP_NAME: &str = env!("CARGO_PKG_NAME"); 21 | const APP_VERSION: &str = env!("CARGO_PKG_VERSION"); 22 | 23 | #[tokio::main] 24 | async fn main() { 25 | dotenv().expect(".env file not found"); 26 | 27 | Builder::with_level(&get_env_level().to_string()) 28 | .with_target_writer("*", new_writer(tokio::io::stdout())) 29 | .init(); 30 | 31 | let req_timeout: u64 = std::env::var("REQUEST_TIMEOUT") 32 | .map(|n| n.parse().unwrap()) 33 | .unwrap_or(10000u64) 34 | .max(1000u64); 35 | let poll_interval: u64 = std::env::var("POLL_INTERVAL") 36 | .map(|n| n.parse().unwrap()) 37 | .unwrap_or(100u64) 38 | .max(10u64); 39 | 40 | let http_client = ClientBuilder::new() 41 | .http2_keep_alive_interval(Some(Duration::from_secs(25))) 42 | .http2_keep_alive_timeout(Duration::from_secs(15)) 43 | .http2_keep_alive_while_idle(true) 44 | .connect_timeout(Duration::from_secs(10)) 45 | .timeout(Duration::from_millis(req_timeout)) 46 | .gzip(true) 47 | .build() 48 | .unwrap(); 49 | 50 | let cacher_entry = match std::env::var("REDIS_URL") { 51 | Ok(url) => { 52 | let redis_client = cache::RedisClient::new(&url).await.unwrap(); 53 | cache::CacherEntry::Redis(redis_client) 54 | } 55 | Err(_) => cache::CacherEntry::Memory(cache::MemoryCacher::default()), 56 | }; 57 | 58 | let agents: BTreeSet = std::env::var("ALLOW_AGENTS") 59 | .unwrap_or_default() 60 | .split(',') 61 | .filter_map(|s| { 62 | let s = s.trim(); 63 | if s.is_empty() { 64 | None 65 | } else { 66 | Some(s.to_string()) 67 | } 68 | }) 69 | .collect(); 70 | 71 | let url_vars: HashMap = std::env::vars() 72 | .filter(|(k, _)| k.starts_with("URL_")) 73 | .collect(); 74 | 75 | let header_vars: HashMap = std::env::vars() 76 | .filter(|(k, _)| k.starts_with("HEADER_")) 77 | .map(|(k, v)| (k, v.parse().expect("invalid header value"))) 78 | .collect(); 79 | 80 | let ecdsa_pub_keys: Vec = std::env::vars() 81 | .filter(|(k, _)| k.starts_with("ECDSA_PUB_KEY")) 82 | .map(|(_, v)| { 83 | let v = general_purpose::URL_SAFE_NO_PAD 84 | .decode(v) 85 | .expect("invalid base64"); 86 | ecdsa::VerifyingKey::from_sec1_bytes(&v).expect("invalid ecdsa key") 87 | }) 88 | .collect(); 89 | 90 | let ed25519_pub_keys: Vec = std::env::vars() 91 | .filter(|(k, _)| k.starts_with("ED25519_PUB_KEY")) 92 | .map(|(_, v)| { 93 | let v = general_purpose::URL_SAFE_NO_PAD 94 | .decode(v) 95 | .expect("invalid base64"); 96 | if v.len() != 32 { 97 | panic!("invalid eddsa key"); 98 | } 99 | let mut key = [0u8; 32]; 100 | key.copy_from_slice(&v); 101 | ed25519_dalek::VerifyingKey::from_bytes(&key).expect("invalid ecdsa key") 102 | }) 103 | .collect(); 104 | 105 | let handle = axum_server::Handle::new(); 106 | let app = Router::new() 107 | .route("/*any", routing::any(handler::proxy)) 108 | .with_state(handler::AppState { 109 | http_client: Arc::new(http_client), 110 | cacher: Arc::new(cache::HybridCacher::new( 111 | poll_interval, 112 | req_timeout, 113 | cacher_entry, 114 | )), 115 | agents: Arc::new(agents), 116 | url_vars: Arc::new(url_vars), 117 | header_vars: Arc::new(header_vars), 118 | ecdsa_pub_keys: Arc::new(ecdsa_pub_keys), 119 | ed25519_pub_keys: Arc::new(ed25519_pub_keys), 120 | }); 121 | 122 | let addr: SocketAddr = std::env::var("SERVER_ADDR") 123 | .unwrap_or("127.0.0.1:8080".to_string()) 124 | .parse() 125 | .unwrap(); 126 | 127 | let cert_file = std::env::var("TLS_CERT_FILE").unwrap_or_default(); 128 | let key_file = std::env::var("TLS_KEY_FILE").unwrap_or_default(); 129 | match key_file.is_empty() { 130 | true => { 131 | let listener = tokio::net::TcpListener::bind(&addr).await.unwrap(); 132 | log::warn!(target: "server", "{}@{} listening on {:?}", APP_NAME, APP_VERSION, addr); 133 | axum::serve(listener, app) 134 | .with_graceful_shutdown(shutdown_signal(handle)) 135 | .await 136 | .unwrap(); 137 | } 138 | false => { 139 | let config = RustlsConfig::from_pem_file(&cert_file, &key_file) 140 | .await 141 | .unwrap_or_else(|_| panic!("read tls file failed: {}, {}", cert_file, key_file)); 142 | log::warn!(target: "server", "{}@{} listening on {:?} with tls", APP_NAME, APP_VERSION,addr); 143 | axum_server::bind_rustls(addr, config) 144 | .handle(handle) 145 | .serve(app.into_make_service()) 146 | .await 147 | .unwrap(); 148 | } 149 | } 150 | } 151 | 152 | async fn shutdown_signal(handle: axum_server::Handle) { 153 | let ctrl_c = async { 154 | signal::ctrl_c() 155 | .await 156 | .expect("failed to install Ctrl+C handler"); 157 | }; 158 | 159 | #[cfg(unix)] 160 | let terminate = async { 161 | signal::unix::signal(signal::unix::SignalKind::terminate()) 162 | .expect("failed to install signal handler") 163 | .recv() 164 | .await; 165 | }; 166 | 167 | #[cfg(not(unix))] 168 | let terminate = std::future::pending::<()>(); 169 | 170 | tokio::select! { 171 | _ = ctrl_c => {}, 172 | _ = terminate => {}, 173 | } 174 | 175 | log::warn!(target: "server", "received termination signal, starting graceful shutdown"); 176 | // 10 secs is how long server will wait to force shutdown 177 | handle.graceful_shutdown(Some(Duration::from_secs(10))); 178 | } 179 | -------------------------------------------------------------------------------- /src/idempotent-proxy-server/src/cache/memory.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use idempotent_proxy_types::unix_ms; 3 | use std::{ 4 | collections::{ 5 | hash_map::{Entry, HashMap}, 6 | BTreeSet, 7 | }, 8 | sync::Arc, 9 | }; 10 | use tokio::{ 11 | sync::RwLock, 12 | time::{sleep, Duration}, 13 | }; 14 | 15 | use super::Cacher; 16 | 17 | #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq)] 18 | struct PriorityKey(u64, String); 19 | 20 | type KV = HashMap)>; 21 | 22 | #[derive(Clone, Default)] 23 | pub struct MemoryCacher { 24 | priority_queue: Arc>>, 25 | kv: Arc>, 26 | } 27 | 28 | impl MemoryCacher { 29 | fn clean_expired_values(&self) -> tokio::task::JoinHandle<()> { 30 | let kv = self.kv.clone(); 31 | let priority_queue = self.priority_queue.clone(); 32 | tokio::spawn(async move { 33 | let now = unix_ms(); 34 | let mut pq = priority_queue.write().await; 35 | let mut kv = kv.write().await; 36 | while let Some(PriorityKey(expire_at, key)) = pq.pop_first() { 37 | if expire_at > now { 38 | pq.insert(PriorityKey(expire_at, key)); 39 | break; 40 | } 41 | 42 | kv.remove(&key); 43 | } 44 | }) 45 | } 46 | } 47 | 48 | #[async_trait] 49 | impl Cacher for MemoryCacher { 50 | async fn obtain(&self, key: &str, ttl: u64) -> Result { 51 | let mut kv = self.kv.write().await; 52 | let now = unix_ms(); 53 | match kv.entry(key.to_string()) { 54 | Entry::Occupied(mut entry) => { 55 | let (expire_at, value) = entry.get_mut(); 56 | if *expire_at > now { 57 | return Ok(false); 58 | } 59 | 60 | let mut pq = self.priority_queue.write().await; 61 | pq.remove(&PriorityKey(*expire_at, key.to_string())); 62 | 63 | *expire_at = now + ttl; 64 | *value = vec![]; 65 | pq.insert(PriorityKey(*expire_at, key.to_string())); 66 | Ok(true) 67 | } 68 | Entry::Vacant(entry) => { 69 | let expire_at = now + ttl; 70 | entry.insert((expire_at, vec![])); 71 | self.priority_queue 72 | .write() 73 | .await 74 | .insert(PriorityKey(expire_at, key.to_string())); 75 | Ok(true) 76 | } 77 | } 78 | } 79 | 80 | async fn polling_get( 81 | &self, 82 | key: &str, 83 | poll_interval: u64, 84 | mut counter: u64, 85 | ) -> Result, String> { 86 | while counter > 0 { 87 | let kv = self.kv.read().await; 88 | let res = kv.get(key); 89 | match res { 90 | None => return Err("not obtained".to_string()), 91 | Some((expire_at, value)) => { 92 | if *expire_at <= unix_ms() { 93 | self.clean_expired_values(); 94 | } 95 | 96 | if !value.is_empty() { 97 | return Ok(value.clone()); 98 | } 99 | } 100 | } 101 | 102 | counter -= 1; 103 | sleep(Duration::from_millis(poll_interval)).await; 104 | } 105 | 106 | Err(("polling get cache timeout").to_string()) 107 | } 108 | 109 | async fn set(&self, key: &str, val: Vec, ttl: u64) -> Result { 110 | let mut kv = self.kv.write().await; 111 | match kv.get_mut(key) { 112 | Some((expire_at, value)) => { 113 | let now = unix_ms(); 114 | if *expire_at <= now { 115 | kv.remove(key); 116 | self.clean_expired_values(); 117 | return Err("value expired".to_string()); 118 | } 119 | 120 | let mut pq = self.priority_queue.write().await; 121 | pq.remove(&PriorityKey(*expire_at, key.to_string())); 122 | 123 | *expire_at = now + ttl; 124 | *value = val; 125 | pq.insert(PriorityKey(*expire_at, key.to_string())); 126 | Ok(true) 127 | } 128 | None => Err("not obtained".to_string()), 129 | } 130 | } 131 | 132 | async fn del(&self, key: &str) -> Result<(), String> { 133 | let mut kv = self.kv.write().await; 134 | if let Some(val) = kv.remove(key) { 135 | let mut pq = self.priority_queue.write().await; 136 | pq.remove(&PriorityKey(val.0, key.to_string())); 137 | } 138 | self.clean_expired_values(); 139 | Ok(()) 140 | } 141 | } 142 | 143 | #[cfg(test)] 144 | mod test { 145 | use super::*; 146 | 147 | #[tokio::test] 148 | async fn memory_cacher() { 149 | let mc = MemoryCacher::default(); 150 | 151 | assert!(mc.obtain("key1", 100).await.unwrap()); 152 | assert!(!mc.obtain("key1", 100).await.unwrap()); 153 | assert!(mc.polling_get("key1", 10, 2).await.is_err()); 154 | assert!(mc.set("key", vec![1, 2, 3, 4], 100).await.is_err()); 155 | assert!(mc.set("key1", vec![1, 2, 3, 4], 100).await.is_ok()); 156 | assert!(!mc.obtain("key1", 100).await.unwrap()); 157 | assert_eq!( 158 | mc.polling_get("key1", 10, 2).await.unwrap(), 159 | vec![1, 2, 3, 4] 160 | ); 161 | assert_eq!( 162 | mc.polling_get("key1", 10, 2).await.unwrap(), 163 | vec![1, 2, 3, 4] 164 | ); 165 | 166 | assert!(mc.del("key").await.is_ok()); 167 | assert!(mc.del("key1").await.is_ok()); 168 | assert!(mc.polling_get("key1", 10, 2).await.is_err()); 169 | assert!(mc.set("key1", vec![1, 2, 3, 4], 100).await.is_err()); 170 | assert!(mc.obtain("key1", 100).await.unwrap()); 171 | assert!(mc.set("key1", vec![1, 2, 3, 4], 100).await.is_ok()); 172 | assert_eq!( 173 | mc.polling_get("key1", 10, 2).await.unwrap(), 174 | vec![1, 2, 3, 4] 175 | ); 176 | 177 | sleep(Duration::from_millis(200)).await; 178 | assert!(mc.polling_get("key1", 10, 2).await.is_ok()); 179 | assert!(mc.set("key1", vec![1, 2, 3, 4], 100).await.is_err()); 180 | assert!(mc.del("key1").await.is_ok()); 181 | 182 | assert!(mc.obtain("key1", 100).await.unwrap()); 183 | sleep(Duration::from_millis(200)).await; 184 | let _ = mc.clean_expired_values().await; 185 | println!("{:?}", mc.priority_queue.read().await); 186 | 187 | let res = futures::try_join!( 188 | mc.obtain("key1", 100), 189 | mc.obtain("key1", 100), 190 | mc.obtain("key1", 100), 191 | ) 192 | .unwrap(); 193 | match res { 194 | (true, false, false) | (false, true, false) | (false, false, true) => {} 195 | _ => panic!("unexpected result"), 196 | } 197 | 198 | assert_eq!(mc.kv.read().await.len(), 1); 199 | assert_eq!(mc.priority_queue.read().await.len(), 1); 200 | 201 | sleep(Duration::from_millis(200)).await; 202 | assert_eq!(mc.kv.read().await.len(), 1); 203 | assert_eq!(mc.priority_queue.read().await.len(), 1); 204 | let _ = mc.clean_expired_values().await; 205 | 206 | assert!(mc.kv.read().await.is_empty()); 207 | assert!(mc.priority_queue.read().await.is_empty()); 208 | } 209 | } 210 | -------------------------------------------------------------------------------- /src/idempotent-proxy-canister/src/store.rs: -------------------------------------------------------------------------------- 1 | use base64::{engine::general_purpose::URL_SAFE_NO_PAD as base64_url, Engine}; 2 | use candid::Principal; 3 | use ciborium::{from_reader, into_writer}; 4 | use ic_cose_types::cose::{format_error, sha3_256}; 5 | use ic_stable_structures::{ 6 | memory_manager::{MemoryId, MemoryManager, VirtualMemory}, 7 | storable::Bound, 8 | DefaultMemoryImpl, StableCell, Storable, 9 | }; 10 | use serde::{Deserialize, Serialize}; 11 | use serde_bytes::ByteBuf; 12 | use std::{ 13 | borrow::Cow, 14 | cell::RefCell, 15 | collections::{BTreeMap, BTreeSet}, 16 | }; 17 | 18 | use crate::{ 19 | agent::Agent, 20 | cose::CoseClient, 21 | cycles::Calculator, 22 | ecdsa::{public_key_with, sign_with}, 23 | }; 24 | 25 | type Memory = VirtualMemory; 26 | 27 | #[derive(Clone, Default, Deserialize, Serialize)] 28 | pub struct State { 29 | pub ecdsa_key_name: String, 30 | pub proxy_token_public_key: String, 31 | pub proxy_token_refresh_interval: u64, // seconds 32 | pub agents: Vec, 33 | pub managers: BTreeSet, 34 | pub allowed_callers: BTreeSet, //deprecated 35 | #[serde(default)] 36 | pub callers: BTreeMap, 37 | #[serde(default)] 38 | pub subnet_size: u64, 39 | #[serde(default)] 40 | pub service_fee: u64, // in cycles 41 | #[serde(default)] 42 | pub incoming_cycles: u128, 43 | #[serde(default)] 44 | pub uncollectible_cycles: u128, 45 | 46 | #[serde(default)] 47 | pub cose: Option, 48 | } 49 | 50 | impl State { 51 | pub fn signer(&self) -> Signer { 52 | Signer { 53 | key_name: self.ecdsa_key_name.clone(), 54 | cose: self.cose.clone(), 55 | } 56 | } 57 | } 58 | 59 | impl Storable for State { 60 | const BOUND: Bound = Bound::Unbounded; 61 | 62 | fn to_bytes(&self) -> Cow<[u8]> { 63 | let mut buf = vec![]; 64 | into_writer(self, &mut buf).expect("failed to encode State data"); 65 | Cow::Owned(buf) 66 | } 67 | 68 | fn from_bytes(bytes: Cow<'_, [u8]>) -> Self { 69 | from_reader(&bytes[..]).expect("failed to decode State data") 70 | } 71 | } 72 | 73 | pub struct Signer { 74 | pub key_name: String, 75 | pub cose: Option, 76 | } 77 | 78 | static SIGN_PROXY_TOKEN_PATH: &[u8] = b"sign_proxy_token"; 79 | 80 | impl Signer { 81 | pub async fn ecdsa_public_key(&self) -> Result { 82 | match self.cose { 83 | Some(ref cose) => cose 84 | .ecdsa_public_key(vec![ByteBuf::from(SIGN_PROXY_TOKEN_PATH)]) 85 | .await 86 | .map(|v| base64_url.encode(v)), 87 | None => public_key_with(&self.key_name, vec![SIGN_PROXY_TOKEN_PATH.to_vec()]) 88 | .await 89 | .map(|v| base64_url.encode(v.public_key)), 90 | } 91 | } 92 | 93 | // use Idempotent Proxy's Token: Token(pub u64, pub String, pub ByteBuf); 94 | // https://github.com/ldclabs/idempotent-proxy/blob/main/src/idempotent-proxy-types/src/auth.rs#L15 95 | pub async fn sign_proxy_token( 96 | &self, 97 | expire_at: u64, // UNIX timestamp, in seconds 98 | message: &str, // use RPCAgent.name as message 99 | ) -> Result { 100 | let mut buf: Vec = Vec::new(); 101 | into_writer(&(expire_at, message), &mut buf) 102 | .expect("failed to encode Token in CBOR format"); 103 | let digest = sha3_256(&buf); 104 | 105 | let sig = match self.cose { 106 | Some(ref cose) => { 107 | cose.ecdsa_sign( 108 | vec![ByteBuf::from(SIGN_PROXY_TOKEN_PATH)], 109 | ByteBuf::from(digest), 110 | ) 111 | .await 112 | } 113 | None => sign_with(&self.key_name, vec![SIGN_PROXY_TOKEN_PATH.to_vec()], digest) 114 | .await 115 | .map(ByteBuf::from), 116 | }; 117 | 118 | buf.clear(); 119 | into_writer(&(expire_at, message, sig?), &mut buf).map_err(format_error)?; 120 | Ok(base64_url.encode(buf)) 121 | } 122 | } 123 | 124 | const STATE_MEMORY_ID: MemoryId = MemoryId::new(0); 125 | 126 | thread_local! { 127 | static STATE: RefCell = RefCell::new(State::default()); 128 | 129 | static MEMORY_MANAGER: RefCell> = 130 | RefCell::new(MemoryManager::init(DefaultMemoryImpl::default())); 131 | 132 | static STATE_STORE: RefCell> = RefCell::new( 133 | StableCell::init( 134 | MEMORY_MANAGER.with_borrow(|m| m.get(STATE_MEMORY_ID)), 135 | State::default() 136 | ).expect("failed to init STATE_STORE store") 137 | ); 138 | 139 | } 140 | 141 | pub mod state { 142 | use super::*; 143 | 144 | pub fn get_agents() -> Vec { 145 | STATE.with(|r| r.borrow().agents.clone()) 146 | } 147 | 148 | pub fn cycles_calculator() -> Calculator { 149 | STATE.with(|r| { 150 | let s = r.borrow(); 151 | Calculator { 152 | subnet_size: s.subnet_size, 153 | service_fee: s.service_fee, 154 | } 155 | }) 156 | } 157 | 158 | pub fn is_manager(caller: &Principal) -> bool { 159 | STATE.with(|r| r.borrow().managers.contains(caller)) 160 | } 161 | 162 | pub fn is_allowed(caller: &Principal) -> bool { 163 | STATE.with(|r| r.borrow().callers.contains_key(caller)) 164 | } 165 | 166 | pub fn update_caller_state(caller: &Principal, cycles: u128, now_ms: u64) { 167 | STATE.with(|r| { 168 | r.borrow_mut().callers.get_mut(caller).map(|v| { 169 | v.0 = v.0.saturating_add(cycles); 170 | v.1 = now_ms; 171 | }) 172 | }); 173 | } 174 | 175 | pub fn with(f: impl FnOnce(&State) -> R) -> R { 176 | STATE.with(|r| f(&r.borrow())) 177 | } 178 | 179 | pub fn with_mut(f: impl FnOnce(&mut State) -> R) -> R { 180 | STATE.with(|r| f(&mut r.borrow_mut())) 181 | } 182 | 183 | pub fn receive_cycles(cycles: u128, ignore_insufficient: bool) { 184 | if cycles == 0 { 185 | return; 186 | } 187 | 188 | let received = ic_cdk::api::call::msg_cycles_accept128(cycles); 189 | with_mut(|r| { 190 | r.incoming_cycles = r.incoming_cycles.saturating_add(received); 191 | if cycles > received { 192 | r.uncollectible_cycles = r.uncollectible_cycles.saturating_add(cycles - received); 193 | 194 | if !ignore_insufficient { 195 | ic_cdk::trap("insufficient cycles"); 196 | } 197 | } 198 | }); 199 | } 200 | 201 | pub fn load() { 202 | STATE_STORE.with(|r| { 203 | let mut s = r.borrow().get().clone(); 204 | if !s.allowed_callers.is_empty() { 205 | s.allowed_callers.iter().for_each(|p| { 206 | s.callers.entry(*p).or_insert((0, 0)); 207 | }); 208 | s.allowed_callers.clear(); 209 | } 210 | 211 | STATE.with(|h| { 212 | *h.borrow_mut() = s; 213 | }); 214 | }); 215 | } 216 | 217 | pub fn save() { 218 | STATE.with(|h| { 219 | STATE_STORE.with(|r| { 220 | r.borrow_mut() 221 | .set(h.borrow().clone()) 222 | .expect("failed to set STATE data"); 223 | }); 224 | }); 225 | } 226 | 227 | pub async fn init_ecdsa_public_key() { 228 | let signer = with(|r| r.signer()); 229 | 230 | match signer.ecdsa_public_key().await { 231 | Ok(public_key) => { 232 | ic_cdk::print("successfully retrieved ECDSA public key"); 233 | with_mut(|r| { 234 | r.proxy_token_public_key = public_key; 235 | }); 236 | } 237 | Err(err) => { 238 | ic_cdk::print(format!("failed to retrieve ECDSA public key: {err}")); 239 | } 240 | } 241 | } 242 | } 243 | -------------------------------------------------------------------------------- /src/idempotent-proxy-server/src/handler.rs: -------------------------------------------------------------------------------- 1 | use axum::{ 2 | body::to_bytes, 3 | extract::{Request, State}, 4 | response::IntoResponse, 5 | }; 6 | use base64::{engine::general_purpose, Engine}; 7 | use http::{header::AsHeaderName, HeaderMap, HeaderValue, StatusCode}; 8 | use idempotent_proxy_types::*; 9 | use k256::ecdsa; 10 | use reqwest::Client; 11 | use std::{ 12 | collections::{BTreeSet, HashMap}, 13 | sync::Arc, 14 | }; 15 | 16 | use crate::cache::{Cacher, HybridCacher, ResponseData}; 17 | 18 | #[derive(Clone)] 19 | pub struct AppState { 20 | pub http_client: Arc, 21 | pub cacher: Arc, 22 | pub agents: Arc>, 23 | pub url_vars: Arc>, 24 | pub header_vars: Arc>, 25 | pub ecdsa_pub_keys: Arc>, 26 | pub ed25519_pub_keys: Arc>, 27 | } 28 | 29 | impl AppState { 30 | pub fn alter_headers(&self, headers: &mut HeaderMap) { 31 | headers.remove(&http::header::HOST); 32 | headers.remove(&http::header::FORWARDED); 33 | headers.remove(&HEADER_PROXY_AUTHORIZATION); 34 | headers.remove(&HEADER_X_FORWARDED_FOR); 35 | headers.remove(&HEADER_X_FORWARDED_HOST); 36 | headers.remove(&HEADER_X_FORWARDED_PROTO); 37 | 38 | if !self.header_vars.is_empty() { 39 | for val in headers.values_mut() { 40 | if let Ok(s) = val.to_str() { 41 | if let Some(v) = self.header_vars.get(s) { 42 | *val = v.clone(); 43 | } 44 | } 45 | } 46 | } 47 | } 48 | 49 | // TODO: support JWT and CWT 50 | pub fn verify_token(&self, access_token: &str) -> Result { 51 | if !access_token.starts_with("Bearer ") { 52 | return Err("invalid proxy-authorization header".to_string()); 53 | } 54 | let token = general_purpose::URL_SAFE_NO_PAD 55 | .decode(access_token.strip_prefix("Bearer ").unwrap().as_bytes()) 56 | .map_err(|err| err.to_string())?; 57 | if !self.ecdsa_pub_keys.is_empty() { 58 | return auth::ecdsa_verify(&self.ecdsa_pub_keys, &token) 59 | .map(|t| t.1) 60 | .map_err(|err| format!("proxy authentication verify failed: {}", err)); 61 | } 62 | if !self.ed25519_pub_keys.is_empty() { 63 | return auth::ed25519_verify(&self.ed25519_pub_keys, &token) 64 | .map(|t| t.1) 65 | .map_err(|err| format!("proxy authentication verify failed: {}", err)); 66 | } 67 | 68 | Err("proxy authentication verify failed".to_string()) 69 | } 70 | } 71 | 72 | pub async fn proxy( 73 | State(app): State, 74 | req: Request, 75 | ) -> Result { 76 | // Access control 77 | let agent = if !app.ecdsa_pub_keys.is_empty() || !app.ed25519_pub_keys.is_empty() { 78 | let token = extract_header(req.headers(), &HEADER_PROXY_AUTHORIZATION, || { 79 | "".to_string() 80 | }); 81 | 82 | match app.verify_token(&token) { 83 | Err(err) => return Err((StatusCode::PROXY_AUTHENTICATION_REQUIRED, err)), 84 | Ok(agent) => agent, 85 | } 86 | } else { 87 | "ANON".to_string() 88 | }; 89 | 90 | if !app.agents.is_empty() && !app.agents.contains(&agent) { 91 | return Err(( 92 | StatusCode::FORBIDDEN, 93 | format!("agent {} is not allowed", agent), 94 | )); 95 | } 96 | 97 | let method = req.method().to_string(); 98 | let path = req.uri().path(); 99 | let url = if path.starts_with("/URL_") { 100 | let url = app 101 | .url_vars 102 | .get(path.strip_prefix('/').unwrap()) 103 | .map(|s| s.to_string()) 104 | .unwrap_or_default(); 105 | if !url.starts_with("http") { 106 | return Err((StatusCode::BAD_REQUEST, format!("invalid url: {}", url))); 107 | } 108 | 109 | url 110 | } else { 111 | let host = extract_header(req.headers(), &HEADER_X_FORWARDED_HOST, || "".to_string()); 112 | if host.is_empty() { 113 | return Err(( 114 | StatusCode::BAD_REQUEST, 115 | "missing header: x-forwarded-host".to_string(), 116 | )); 117 | } 118 | 119 | let path_query = req 120 | .uri() 121 | .path_and_query() 122 | .map(|v| v.as_str()) 123 | .unwrap_or(path); 124 | format!("https://{}{}", host, path_query) 125 | }; 126 | 127 | let url = 128 | reqwest::Url::parse(&url).map_err(|err| (StatusCode::BAD_REQUEST, err.to_string()))?; 129 | let idempotency_key = extract_header(req.headers(), &HEADER_IDEMPOTENCY_KEY, || "".to_string()); 130 | if idempotency_key.is_empty() { 131 | return Err(( 132 | StatusCode::BAD_REQUEST, 133 | "missing header: idempotency-key".to_string(), 134 | )); 135 | } 136 | 137 | let idempotency_key = format!("{}:{}:{}", agent, method, idempotency_key); 138 | 139 | let lock = app 140 | .cacher 141 | .obtain(&idempotency_key, app.cacher.cache_ttl) 142 | .await 143 | .map_err(bad_gateway)?; 144 | if !lock { 145 | let data = app 146 | .cacher 147 | .polling_get( 148 | &idempotency_key, 149 | app.cacher.poll_interval, 150 | app.cacher.cache_ttl / app.cacher.poll_interval, 151 | ) 152 | .await 153 | .map_err(bad_gateway)?; 154 | 155 | let res = ResponseData::try_from(&data[..]).map_err(bad_gateway)?; 156 | log::info!(target: "handler", 157 | action = "cachehit", 158 | method = method, 159 | url = url.to_string(), 160 | status = res.status, 161 | agent = agent, 162 | idempotency_key = idempotency_key; 163 | ""); 164 | return Ok(res); 165 | } 166 | 167 | let res = { 168 | let method = req.method(); 169 | let json_mask = extract_header(req.headers(), &HEADER_X_JSON_MASK, || "".to_string()); 170 | let response_headers = 171 | extract_header(req.headers(), &HEADER_RESPONSE_HEADERS, || "".to_string()); 172 | 173 | let mut headers = req.headers().clone(); 174 | app.alter_headers(&mut headers); 175 | 176 | let mut rreq = reqwest::Request::new(method.clone(), url.clone()); 177 | *rreq.headers_mut() = headers; 178 | 179 | if !method.is_safe() { 180 | let body = to_bytes(req.into_body(), 1024 * 1024) 181 | .await 182 | .map_err(|err| (StatusCode::BAD_REQUEST, err.to_string()))?; 183 | *rreq.body_mut() = Some(reqwest::Body::from(body)); 184 | } 185 | 186 | let rres = app.http_client.execute(rreq).await.map_err(bad_gateway)?; 187 | let status = rres.status(); 188 | let headers = rres.headers().to_owned(); 189 | let res_body = rres.bytes().await.map_err(bad_gateway)?; 190 | 191 | // If the HTTP status code is 500 or below, it's considered a server response and should be cached; any exceptions should be handled by the client. Otherwise, it's considered a non-response from the server and should not be cached. 192 | if status >= StatusCode::OK && status <= StatusCode::INTERNAL_SERVER_ERROR { 193 | let mut rd = ResponseData::new(status.as_u16()); 194 | rd.with_headers(&headers, &response_headers); 195 | rd.with_body(&res_body, &json_mask).map_err(bad_gateway)?; 196 | let data = rd.to_bytes().map_err(bad_gateway)?; 197 | 198 | let _ = app 199 | .cacher 200 | .set(&idempotency_key, data, app.cacher.cache_ttl) 201 | .await 202 | .map_err(bad_gateway)?; 203 | 204 | Ok(rd) 205 | } else { 206 | Err((status, String::from_utf8_lossy(&res_body).to_string())) 207 | } 208 | }; 209 | 210 | match res { 211 | Ok(res) => { 212 | log::info!(target: "handler", 213 | action = "proxying", 214 | method = method, 215 | url = url.to_string(), 216 | status = 200u16, 217 | agent = agent, 218 | idempotency_key = idempotency_key; 219 | ""); 220 | Ok(res) 221 | } 222 | Err((status, msg)) => { 223 | let _ = app.cacher.del(&idempotency_key).await; 224 | log::warn!(target: "handler", 225 | action = "proxying", 226 | method = method, 227 | url = url.to_string(), 228 | status = status.as_u16(), 229 | agent = agent, 230 | idempotency_key = idempotency_key; 231 | "{}", msg); 232 | Err((status, msg)) 233 | } 234 | } 235 | } 236 | 237 | fn bad_gateway(err: impl std::fmt::Display) -> (StatusCode, String) { 238 | (StatusCode::BAD_GATEWAY, err.to_string()) 239 | } 240 | 241 | fn extract_header(hm: &HeaderMap, key: K, or: impl FnOnce() -> String) -> String 242 | where 243 | K: AsHeaderName, 244 | { 245 | match hm.get(key) { 246 | None => or(), 247 | Some(v) => match v.to_str() { 248 | Ok(s) => s.to_string(), 249 | Err(_) => or(), 250 | }, 251 | } 252 | } 253 | 254 | #[cfg(test)] 255 | mod test { 256 | 257 | #[test] 258 | fn test_challenge() {} 259 | } 260 | -------------------------------------------------------------------------------- /src/idempotent-proxy-canister/src/api.rs: -------------------------------------------------------------------------------- 1 | use candid::{CandidType, Nat, Principal}; 2 | use ciborium::into_writer; 3 | use futures::FutureExt; 4 | use ic_cdk::api::management_canister::http_request::{CanisterHttpRequestArgument, HttpResponse}; 5 | use serde::{Deserialize, Serialize}; 6 | use std::collections::BTreeSet; 7 | 8 | use crate::{agent::Agent, cose::CoseClient, store}; 9 | 10 | const MILLISECONDS: u64 = 1_000_000; 11 | 12 | #[derive(CandidType, Deserialize, Serialize)] 13 | pub struct StateInfo { 14 | pub ecdsa_key_name: String, 15 | pub proxy_token_public_key: String, 16 | pub proxy_token_refresh_interval: u64, // seconds 17 | pub agents: Vec, 18 | pub managers: BTreeSet, 19 | pub callers: u64, 20 | pub subnet_size: u64, 21 | pub service_fee: u64, // in cycles 22 | pub incoming_cycles: u128, 23 | pub uncollectible_cycles: u128, 24 | pub cose: Option, 25 | } 26 | 27 | #[ic_cdk::query] 28 | fn state_info() -> StateInfo { 29 | store::state::with(|s| StateInfo { 30 | ecdsa_key_name: s.ecdsa_key_name.clone(), 31 | proxy_token_public_key: s.proxy_token_public_key.clone(), 32 | proxy_token_refresh_interval: s.proxy_token_refresh_interval, 33 | agents: s 34 | .agents 35 | .iter() 36 | .map(|a| Agent { 37 | name: a.name.clone(), 38 | endpoint: a.endpoint.clone(), 39 | max_cycles: a.max_cycles, 40 | proxy_token: None, 41 | }) 42 | .collect(), 43 | managers: s.managers.clone(), 44 | callers: s.callers.len() as u64, 45 | subnet_size: s.subnet_size, 46 | service_fee: s.service_fee, 47 | incoming_cycles: s.incoming_cycles, 48 | uncollectible_cycles: s.uncollectible_cycles, 49 | cose: s.cose.clone(), 50 | }) 51 | } 52 | 53 | #[ic_cdk::query] 54 | fn caller_info(id: Principal) -> Option<(u128, u64)> { 55 | store::state::with(|s| s.callers.get(&id).copied()) 56 | } 57 | 58 | #[ic_cdk::query] 59 | async fn proxy_http_request_cost(req: CanisterHttpRequestArgument) -> u128 { 60 | let calc = store::state::cycles_calculator(); 61 | calc.ingress_cost(ic_cdk::api::call::arg_data_raw_size()) 62 | + calc.http_outcall_request_cost(calc.count_request_bytes(&req), 1) 63 | + calc.http_outcall_response_cost(req.max_response_bytes.unwrap_or(10240) as usize, 1) 64 | } 65 | 66 | #[ic_cdk::query] 67 | async fn parallel_call_cost(req: CanisterHttpRequestArgument) -> u128 { 68 | let agents = store::state::get_agents(); 69 | let calc = store::state::cycles_calculator(); 70 | calc.ingress_cost(ic_cdk::api::call::arg_data_raw_size()) 71 | + calc.http_outcall_request_cost(calc.count_request_bytes(&req), agents.len()) 72 | + calc.http_outcall_response_cost( 73 | req.max_response_bytes.unwrap_or(10240) as usize, 74 | agents.len(), 75 | ) 76 | } 77 | 78 | /// Proxy HTTP request by all agents in sequence until one returns an status <= 500 result. 79 | #[ic_cdk::update] 80 | async fn proxy_http_request(req: CanisterHttpRequestArgument) -> HttpResponse { 81 | let caller = ic_cdk::caller(); 82 | if !store::state::is_allowed(&caller) { 83 | return HttpResponse { 84 | status: Nat::from(403u64), 85 | body: "caller is not allowed".as_bytes().to_vec(), 86 | headers: vec![], 87 | }; 88 | } 89 | 90 | let agents = store::state::get_agents(); 91 | if agents.is_empty() { 92 | return HttpResponse { 93 | status: Nat::from(503u64), 94 | body: "no agents available".as_bytes().to_vec(), 95 | headers: vec![], 96 | }; 97 | } 98 | 99 | let balance = ic_cdk::api::call::msg_cycles_available128(); 100 | let calc = store::state::cycles_calculator(); 101 | store::state::receive_cycles( 102 | calc.ingress_cost(ic_cdk::api::call::arg_data_raw_size()), 103 | false, 104 | ); 105 | 106 | let req_size = calc.count_request_bytes(&req); 107 | let mut last_err: Option = None; 108 | for agent in agents { 109 | store::state::receive_cycles(calc.http_outcall_request_cost(req_size, 1), false); 110 | match agent.call(req.clone()).await { 111 | Ok(res) => { 112 | let cycles = calc.http_outcall_response_cost(calc.count_response_bytes(&res), 1); 113 | store::state::receive_cycles(cycles, true); 114 | store::state::update_caller_state( 115 | &caller, 116 | balance - ic_cdk::api::call::msg_cycles_available128(), 117 | ic_cdk::api::time() / MILLISECONDS, 118 | ); 119 | return res; 120 | } 121 | Err(res) => last_err = Some(res), 122 | } 123 | } 124 | 125 | store::state::update_caller_state( 126 | &caller, 127 | balance - ic_cdk::api::call::msg_cycles_available128(), 128 | ic_cdk::api::time() / MILLISECONDS, 129 | ); 130 | last_err.unwrap() 131 | } 132 | 133 | /// Proxy HTTP request by all agents in parallel and return the result if all are the same, 134 | /// or a 500 HttpResponse with all result. 135 | #[ic_cdk::update] 136 | async fn parallel_call_all_ok(req: CanisterHttpRequestArgument) -> HttpResponse { 137 | let caller = ic_cdk::caller(); 138 | if !store::state::is_allowed(&caller) { 139 | return HttpResponse { 140 | status: Nat::from(403u64), 141 | body: "caller is not allowed".as_bytes().to_vec(), 142 | headers: vec![], 143 | }; 144 | } 145 | 146 | let agents = store::state::get_agents(); 147 | if agents.is_empty() { 148 | return HttpResponse { 149 | status: Nat::from(503u64), 150 | body: "no agents available".as_bytes().to_vec(), 151 | headers: vec![], 152 | }; 153 | } 154 | 155 | let balance = ic_cdk::api::call::msg_cycles_available128(); 156 | let calc = store::state::cycles_calculator(); 157 | let cycles = calc.ingress_cost(ic_cdk::api::call::arg_data_raw_size()) 158 | + calc.http_outcall_request_cost(calc.count_request_bytes(&req), agents.len()); 159 | store::state::receive_cycles(cycles, false); 160 | 161 | let results = 162 | futures::future::try_join_all(agents.iter().map(|agent| agent.call(req.clone()))).await; 163 | let result = match results { 164 | Err(res) => res, 165 | Ok(res) => { 166 | let mut results = res.into_iter(); 167 | let base_result = results.next().unwrap_or_else(|| HttpResponse { 168 | status: Nat::from(503u64), 169 | body: "no agents available".as_bytes().to_vec(), 170 | headers: vec![], 171 | }); 172 | 173 | let cycles = calc 174 | .http_outcall_response_cost(calc.count_response_bytes(&base_result), agents.len()); 175 | store::state::receive_cycles(cycles, true); 176 | 177 | let mut inconsistent_results: Vec<_> = 178 | results.filter(|result| result != &base_result).collect(); 179 | if !inconsistent_results.is_empty() { 180 | inconsistent_results.push(base_result); 181 | let mut buf = vec![]; 182 | into_writer(&inconsistent_results, &mut buf) 183 | .expect("failed to encode inconsistent results"); 184 | HttpResponse { 185 | status: Nat::from(500u64), 186 | body: buf, 187 | headers: vec![], 188 | } 189 | } else { 190 | base_result 191 | } 192 | } 193 | }; 194 | 195 | store::state::update_caller_state( 196 | &caller, 197 | balance - ic_cdk::api::call::msg_cycles_available128(), 198 | ic_cdk::api::time() / MILLISECONDS, 199 | ); 200 | result 201 | } 202 | 203 | /// Proxy HTTP request by all agents in parallel and return the first (status <= 500) result. 204 | #[ic_cdk::update] 205 | async fn parallel_call_any_ok(req: CanisterHttpRequestArgument) -> HttpResponse { 206 | let caller = ic_cdk::caller(); 207 | if !store::state::is_allowed(&caller) { 208 | return HttpResponse { 209 | status: Nat::from(403u64), 210 | body: "caller is not allowed".as_bytes().to_vec(), 211 | headers: vec![], 212 | }; 213 | } 214 | 215 | let agents = store::state::get_agents(); 216 | if agents.is_empty() { 217 | return HttpResponse { 218 | status: Nat::from(503u64), 219 | body: "no agents available".as_bytes().to_vec(), 220 | headers: vec![], 221 | }; 222 | } 223 | 224 | let balance = ic_cdk::api::call::msg_cycles_available128(); 225 | let calc = store::state::cycles_calculator(); 226 | let cycles = calc.ingress_cost(ic_cdk::api::call::arg_data_raw_size()) 227 | + calc.http_outcall_request_cost(calc.count_request_bytes(&req), agents.len()); 228 | store::state::receive_cycles(cycles, false); 229 | 230 | let result = 231 | futures::future::select_ok(agents.iter().map(|agent| agent.call(req.clone()).boxed())) 232 | .await; 233 | let result = match result { 234 | Ok((res, _)) => { 235 | let cycles = 236 | calc.http_outcall_response_cost(calc.count_response_bytes(&res), agents.len()); 237 | store::state::receive_cycles(cycles, true); 238 | res 239 | } 240 | Err(res) => res, 241 | }; 242 | 243 | store::state::update_caller_state( 244 | &caller, 245 | balance - ic_cdk::api::call::msg_cycles_available128(), 246 | ic_cdk::api::time() / MILLISECONDS, 247 | ); 248 | result 249 | } 250 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/idempotent-proxy-server/src/cache/mod.rs: -------------------------------------------------------------------------------- 1 | use async_trait::async_trait; 2 | use axum::{ 3 | body::Body, 4 | response::{IntoResponse, Response}, 5 | }; 6 | use ciborium::{from_reader, into_writer, Value}; 7 | use http::{ 8 | header::{HeaderMap, HeaderName, HeaderValue}, 9 | StatusCode, 10 | }; 11 | use idempotent_proxy_types::err_string; 12 | use serde::{Deserialize, Serialize}; 13 | use serde_bytes::ByteBuf; 14 | 15 | mod memory; 16 | mod redis; 17 | 18 | pub use memory::*; 19 | pub use redis::*; 20 | 21 | pub struct HybridCacher { 22 | pub poll_interval: u64, 23 | pub cache_ttl: u64, 24 | cache: CacherEntry, 25 | } 26 | 27 | impl HybridCacher { 28 | pub fn new(poll_interval: u64, cache_ttl: u64, cache: CacherEntry) -> Self { 29 | Self { 30 | poll_interval, 31 | cache_ttl, 32 | cache, 33 | } 34 | } 35 | } 36 | 37 | pub enum CacherEntry { 38 | Memory(MemoryCacher), 39 | Redis(RedisClient), 40 | } 41 | 42 | #[async_trait] 43 | pub trait Cacher { 44 | async fn obtain(&self, key: &str, ttl_ms: u64) -> Result; 45 | async fn polling_get( 46 | &self, 47 | key: &str, 48 | poll_interval_ms: u64, 49 | counter: u64, 50 | ) -> Result, String>; 51 | async fn set(&self, key: &str, val: Vec, ttl_ms: u64) -> Result; 52 | async fn del(&self, key: &str) -> Result<(), String>; 53 | } 54 | 55 | #[async_trait] 56 | impl Cacher for HybridCacher { 57 | async fn obtain(&self, key: &str, ttl: u64) -> Result { 58 | match &self.cache { 59 | CacherEntry::Memory(cacher) => cacher.obtain(key, ttl).await, 60 | CacherEntry::Redis(cacher) => cacher.obtain(key, ttl).await, 61 | } 62 | } 63 | 64 | async fn polling_get( 65 | &self, 66 | key: &str, 67 | poll_interval: u64, 68 | counter: u64, 69 | ) -> Result, String> { 70 | match &self.cache { 71 | CacherEntry::Memory(cacher) => cacher.polling_get(key, poll_interval, counter).await, 72 | CacherEntry::Redis(cacher) => cacher.polling_get(key, poll_interval, counter).await, 73 | } 74 | } 75 | 76 | async fn set(&self, key: &str, val: Vec, ttl: u64) -> Result { 77 | match &self.cache { 78 | CacherEntry::Memory(cacher) => cacher.set(key, val, ttl).await, 79 | CacherEntry::Redis(cacher) => cacher.set(key, val, ttl).await, 80 | } 81 | } 82 | 83 | async fn del(&self, key: &str) -> Result<(), String> { 84 | match &self.cache { 85 | CacherEntry::Memory(cacher) => cacher.del(key).await, 86 | CacherEntry::Redis(cacher) => cacher.del(key).await, 87 | } 88 | } 89 | } 90 | 91 | #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] 92 | pub struct ResponseData { 93 | pub status: u16, 94 | pub headers: Vec<(String, String)>, 95 | pub body: ByteBuf, 96 | pub mime: String, 97 | } 98 | 99 | impl Default for ResponseData { 100 | fn default() -> Self { 101 | Self::new(200) 102 | } 103 | } 104 | 105 | impl ResponseData { 106 | pub fn new(status: u16) -> Self { 107 | Self { 108 | status, 109 | headers: Vec::new(), 110 | body: ByteBuf::new(), 111 | mime: "text/plain".to_string(), 112 | } 113 | } 114 | 115 | pub fn with_headers(&mut self, headers: &HeaderMap, filtering: &str) { 116 | let filtering = filtering.to_ascii_lowercase(); 117 | let filtering: Vec<&str> = split_filtering(filtering.as_str()); 118 | self.headers.reserve_exact(if filtering.is_empty() { 119 | headers.len() 120 | } else { 121 | filtering.len() 122 | }); 123 | 124 | for (k, v) in headers.iter() { 125 | if let Ok(v) = v.to_str() { 126 | match k.as_str() { 127 | "content-type" => { 128 | self.mime = v.to_string(); 129 | } 130 | "content-length" | "transfer-encoding" => { 131 | continue; 132 | } 133 | k if filtering.is_empty() || filtering.contains(&k) => { 134 | self.headers.push((k.to_string(), v.to_string())); 135 | } 136 | _ => {} 137 | } 138 | } 139 | } 140 | } 141 | 142 | pub fn with_body(&mut self, body: &[u8], filtering: &str) -> Result<(), String> { 143 | let filtering: Vec<&str> = split_filtering(filtering); 144 | if self.status >= 300 || filtering.is_empty() { 145 | self.body.extend_from_slice(body); 146 | return Ok(()); 147 | } 148 | 149 | match &self.mime { 150 | v if !filtering.is_empty() && v.contains("application/json") => { 151 | let obj: serde_json::Value = serde_json::from_slice(body).map_err(err_string)?; 152 | let mut new_obj = serde_json::Map::with_capacity(filtering.len()); 153 | for k in filtering { 154 | if let Some(v) = obj.get(k) { 155 | new_obj.insert(k.to_string(), v.to_owned()); 156 | } 157 | } 158 | self.body = ByteBuf::from(serde_json::to_vec(&new_obj).map_err(err_string)?); 159 | } 160 | v if !filtering.is_empty() && v.contains("application/cbor") => { 161 | let obj: Value = from_reader(body).map_err(err_string)?; 162 | let obj = obj 163 | .into_map() 164 | .map(|mut list| { 165 | list.retain(|v| v.0.as_text().is_some_and(|t| filtering.contains(&t))); 166 | list 167 | }) 168 | .map(Value::Map); 169 | let mut buf = Vec::new(); 170 | match obj { 171 | Ok(v) => into_writer(&v, &mut buf).map_err(err_string)?, 172 | Err(_) => into_writer(&Value::Map(vec![]), &mut buf).map_err(err_string)?, 173 | } 174 | self.body = ByteBuf::from(buf); 175 | } 176 | _ => { 177 | self.body.extend_from_slice(body); 178 | } 179 | } 180 | Ok(()) 181 | } 182 | 183 | pub fn to_bytes(&self) -> Result, String> { 184 | let mut buf = Vec::new(); 185 | into_writer(self, &mut buf).map_err(err_string)?; 186 | Ok(buf) 187 | } 188 | } 189 | 190 | impl TryFrom<&[u8]> for ResponseData { 191 | type Error = String; 192 | 193 | fn try_from(value: &[u8]) -> Result { 194 | from_reader(value).map_err(err_string) 195 | } 196 | } 197 | 198 | fn split_filtering(filtering: &str) -> Vec<&str> { 199 | filtering 200 | .split(',') 201 | .filter_map(|s| { 202 | let s = s.trim(); 203 | if s.is_empty() { 204 | None 205 | } else { 206 | Some(s) 207 | } 208 | }) 209 | .collect() 210 | } 211 | 212 | impl IntoResponse for ResponseData { 213 | fn into_response(self) -> Response { 214 | let body = self.body.into_vec(); 215 | let len = body.len(); 216 | let mut res = Response::new(Body::from(body)); 217 | *res.status_mut() = StatusCode::from_u16(self.status).unwrap_or(StatusCode::OK); 218 | for (ref k, v) in self.headers { 219 | res.headers_mut().append( 220 | HeaderName::from_bytes(k.as_bytes()).unwrap(), 221 | HeaderValue::from_bytes(v.as_bytes()).unwrap(), 222 | ); 223 | } 224 | 225 | res.headers_mut().insert( 226 | http::header::CONTENT_TYPE, 227 | HeaderValue::from_bytes(self.mime.as_bytes()).unwrap(), 228 | ); 229 | res.headers_mut() 230 | .insert(http::header::CONTENT_LENGTH, len.into()); 231 | res 232 | } 233 | } 234 | 235 | #[cfg(test)] 236 | mod test { 237 | use super::*; 238 | use hex::prelude::*; 239 | 240 | #[test] 241 | fn test_split_filtering() { 242 | assert_eq!(split_filtering("").len(), 0); 243 | assert_eq!(split_filtering("args,url"), vec!["args", "url"]); 244 | assert_eq!(split_filtering("args, url"), vec!["args", "url"]); 245 | } 246 | 247 | #[test] 248 | fn test_response_data() { 249 | let mut rd = ResponseData::new(200); 250 | rd.headers 251 | .push(("accept".to_string(), "application/json".to_string())); 252 | rd.body.extend_from_slice(b"Hello, World!"); 253 | let data = rd.to_bytes().unwrap(); 254 | let rd2 = ResponseData::try_from(data.as_slice()).unwrap(); 255 | assert_eq!(rd2, rd); 256 | println!("rd: {}", data.to_lower_hex_string()); 257 | 258 | let mut rd = ResponseData::new(200); 259 | let mut headers = HeaderMap::new(); 260 | headers.insert("Date", "Wed, 22 May 2024 11:11:17 GMT".parse().unwrap()); 261 | headers.insert("Content-Length", "123".parse().unwrap()); 262 | headers.insert("Content-Type", "application/json".parse().unwrap()); 263 | rd.with_headers(&headers, "date, content-type, Content-Length"); 264 | assert_eq!(rd.mime, "application/json"); 265 | assert_eq!( 266 | rd.headers, 267 | vec![( 268 | "date".to_string(), 269 | "Wed, 22 May 2024 11:11:17 GMT".to_string() 270 | )] 271 | ) 272 | } 273 | 274 | #[test] 275 | fn test_response_data_in_json() { 276 | use serde_json::json; 277 | 278 | let mut rd = ResponseData::new(200); 279 | let mut headers = HeaderMap::new(); 280 | headers.insert("Date", "Wed, 22 May 2024 11:11:17 GMT".parse().unwrap()); 281 | headers.insert("Content-Length", "123".parse().unwrap()); 282 | headers.insert("Content-Type", "application/json".parse().unwrap()); 283 | rd.with_headers(&headers, "date, content-type, Content-Length"); 284 | assert_eq!(rd.mime, "application/json"); 285 | let body = json!({ 286 | "args": {"api-key": "abc123"}, 287 | "headers": {"Accept": "*/*"}, 288 | "origin": "120.204.60.218", 289 | "url": "https://httpbin.org/get?api-key=abc123", 290 | }); 291 | 292 | rd.with_body( 293 | serde_json::to_vec(&body).unwrap().as_slice(), 294 | "args,url,Origin", 295 | ) 296 | .unwrap(); 297 | assert_eq!( 298 | rd.body.as_slice(), 299 | r#"{"args":{"api-key":"abc123"},"url":"https://httpbin.org/get?api-key=abc123"}"# 300 | .as_bytes() 301 | ); 302 | } 303 | 304 | #[test] 305 | fn test_response_data_in_cbor() { 306 | use ciborium::cbor; 307 | let mut rd = ResponseData::new(200); 308 | let mut headers = HeaderMap::new(); 309 | headers.insert("Date", "Wed, 22 May 2024 11:11:17 GMT".parse().unwrap()); 310 | headers.insert("Content-Length", "123".parse().unwrap()); 311 | headers.insert("Content-Type", "application/cbor".parse().unwrap()); 312 | rd.with_headers(&headers, "date, content-type, Content-Length"); 313 | assert_eq!(rd.mime, "application/cbor"); 314 | let body = cbor!({ 315 | "args" => {"api-key" => "abc123"}, 316 | "headers" => {"Accept" => "*/*"}, 317 | "origin" => "120.204.60.218", 318 | "url" => "https://httpbin.org/get?api-key=abc123", 319 | }) 320 | .unwrap(); 321 | let mut buf = Vec::new(); 322 | into_writer(&body, &mut buf).unwrap(); 323 | rd.with_body(&buf, "args,url,Origin").unwrap(); 324 | 325 | let body = cbor!({ 326 | "args" => {"api-key" => "abc123"}, 327 | "url" => "https://httpbin.org/get?api-key=abc123", 328 | }) 329 | .unwrap(); 330 | buf.clear(); 331 | into_writer(&body, &mut buf).unwrap(); 332 | assert_eq!(rd.body.as_slice(), buf.as_slice()); 333 | } 334 | } 335 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Idempotent Proxy 2 | 💈 Reverse proxy server with built-in idempotency support, written in Rust & Cloudflare Worker. 3 | 4 | 💝 This project received a [**$5k Developer Grant**](https://forum.dfinity.org/t/idempotent-proxy-proxy-https-outcalls-to-any-web2-service/30624) from the [DFINITY Foundation](https://dfinity.org/grants). 5 | 6 | ## Overview 7 | 8 | The idempotent-proxy is a reverse proxy service written in Rust with built-in idempotency support. 9 | 10 | When multiple requests with the same idempotency key arrive within a specific timeframe, only the first request is forwarded to the target service. The response is cached in Redis (or DurableObject in Cloudflare Worker), and subsequent requests retrieve the cached response, ensuring consistent results. 11 | 12 | This service can be used to proxy [HTTPS outcalls](https://internetcomputer.org/docs/current/references/https-outcalls-how-it-works) for [ICP canisters](https://internetcomputer.org/docs/current/developer-docs/smart-contracts/overview/introduction), enabling integration with any Web2 http service. 13 | 14 | ![Idempotent Proxy](./idempotent-proxy.webp) 15 | 16 | ## Features 17 | - Reverse proxy with built-in idempotency support 18 | - Confidential information masking 19 | - JSON and CBOR response filtering 20 | - Response headers filtering 21 | - Access control using Secp256k1 and Ed25519 22 | - Deployable with Docker or Cloudflare Worker 23 | - On-chain Idempotent Proxy service on the ICP 24 | 25 | ## Libraries 26 | 27 | | Library | Description | 28 | | :----------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------- | 29 | | [idempotent-proxy-server](https://github.com/ldclabs/idempotent-proxy/tree/main/src/idempotent-proxy-server) | Idempotent Proxy implemented in Rust. | 30 | | [idempotent-proxy-cf-worker](https://github.com/ldclabs/idempotent-proxy/tree/main/src/idempotent-proxy-cf-worker) | Idempotent Proxy implemented as Cloudflare Worker. | 31 | | [idempotent-proxy-canister](https://github.com/ldclabs/idempotent-proxy/tree/main/src/idempotent-proxy-canister) | A ICP canister Make Idempotent Proxy service on-chain. | 32 | | [idempotent-proxy-types](https://github.com/ldclabs/idempotent-proxy/tree/main/src/idempotent-proxy-types) | Idempotent Proxy types in Rust. Should not be used in ICP canister! | 33 | | [examples/eth-canister](https://github.com/ldclabs/idempotent-proxy/tree/main/examples/eth-canister) | A ICP canister integration with Ethereum JSON-RPC API. | 34 | | [examples/eth-canister-lite](https://github.com/ldclabs/idempotent-proxy/tree/main/examples/eth-canister-lite) | A ICP canister integration with Ethereum JSON-RPC API through idempotent-proxy-canister | 35 | 36 | ## Who's using? 37 | 38 | - [CK-Doge](https://github.com/ldclabs/ck-doge): An on-chain integration with the Dogecoin network on the Internet Computer. 39 | 40 | If you plan to use this project and have any questions, feel free to open an issue. I will address it as soon as possible. 41 | 42 | ## Usage 43 | 44 | ### On-chain Idempotent Proxy 45 | 46 | The `idempotent-proxy-canister` is an ICP smart contract that can connect to 1 to N Idempotent Proxy services deployed by `idempotent-proxy-server` or `idempotent-proxy-cf-worker`. It provides on-chain HTTPS outcalls with idempotency for other smart contracts. 47 | 48 | ![Idempotent Proxy Canister](./idempotent-proxy-canister.webp) 49 | 50 | Go to the [idempotent-proxy-canister](./src/idempotent-proxy-canister) directory for more information. 51 | 52 | **Online Demo**: https://a4gq6-oaaaa-aaaab-qaa4q-cai.raw.icp0.io/?id=hpudd-yqaaa-aaaap-ahnbq-cai 53 | 54 | ### ICP Canister Integration Examples 55 | 56 | - [examples/eth-canister-lite](./examples/eth-canister-lite): A ICP canister integration with Ethereum JSON-RPC API through idempotent-proxy-canister. 57 | - [examples/eth-canister](./examples/eth-canister): A ICP canister integration with Ethereum JSON-RPC API. 58 | 59 | ### Run proxy in development mode 60 | 61 | Run proxy: 62 | ```bash 63 | cargo run -p idempotent-proxy-server 64 | ``` 65 | 66 | Make a request: 67 | ```bash 68 | curl -v -X POST \ 69 | --url http://YOUR_HOST/eth \ 70 | --header 'content-type: application/json' \ 71 | --header 'x-forwarded-host: rpc.ankr.com' \ 72 | --header 'idempotency-key: key_001' \ 73 | --data '{ 74 | "id": 1, 75 | "jsonrpc": "2.0", 76 | "method": "eth_getBlockByNumber", 77 | "params": ["latest", false] 78 | }' 79 | ``` 80 | 81 | ### Building enclave image for Marlin Oyster 82 | 83 | https://docs.marlin.org/user-guides/oyster/instances/quickstart/build 84 | 85 | ```bash 86 | sudo docker run --rm --privileged --name nitro-cli -v `pwd`:/mnt/my-server marlinorg/nitro-cli 87 | ``` 88 | 89 | In a new terminal, run: 90 | ```bash 91 | cd /mnt/my-server 92 | sudo docker exec -it nitro-cli sh 93 | nitro-cli build-enclave --docker-uri ghcr.io/ldclabs/idempotent-proxy_enclave_amd64:latest --output-file idempotent-proxy_enclave_amd64.eif 94 | ``` 95 | 96 | The image URL to deploy on Marlin Oyster: 97 | ```text 98 | https://pub-eea759c16b114748bd3b170eadbb2c30.r2.dev/idempotent-proxy_enclave_amd64.eif 99 | ``` 100 | 101 | Go to the [idempotent-proxy-server](./src/idempotent-proxy-server) directory for more information. 102 | 103 | ### Running as Cloudflare Worker 104 | 105 | Idempotent Proxy can be running as a Cloudflare Worker. In order to use Durable Objects, you must switch to a paid plan. 106 | 107 | ```bash 108 | cd src/idempotent-proxy-cf-worker 109 | npm i 110 | npx wrangler deploy 111 | ``` 112 | 113 | A online version for testing is available at: 114 | 115 | https://idempotent-proxy-cf-worker.zensh.workers.dev 116 | 117 | Try it out: 118 | ``` 119 | curl -v -X GET 'https://idempotent-proxy-cf-worker.zensh.workers.dev/URL_HTTPBIN' \ 120 | -H 'idempotency-key: idempotency_key_001' \ 121 | -H 'content-type: application/json' 122 | ``` 123 | 124 | More `URL_` constants: 125 | - URL_CF_ETH: https://cloudflare-eth.com 126 | - URL_ANKR_ETH: https://rpc.ankr.com/eth 127 | 128 | `idempotent-proxy-cf-worker` does not enable `proxy-authorization`, so it can be accessed. 129 | 130 | Go to the [idempotent-proxy-cf-worker](./src/idempotent-proxy-cf-worker) directory for more information. 131 | 132 | ### Run proxy with Docker 133 | 134 | files in `/mnt/idempotent-proxy` directory: 135 | ``` 136 | /mnt/idempotent-proxy/.env 137 | /mnt/idempotent-proxy/keys/doge-test-rpc.panda.fans.key 138 | /mnt/idempotent-proxy/keys/doge-test-rpc.panda.fans.pem 139 | ``` 140 | 141 | `.env` file: 142 | ```text 143 | SERVER_ADDR=0.0.0.0:443 144 | REDIS_URL=172.16.32.1:6379 145 | POLL_INTERVAL=100 # in milliseconds 146 | REQUEST_TIMEOUT=10000 # in milliseconds 147 | LOG_LEVEL=info # debug, info, warn, error 148 | # cert file path to enable https, for example: /etc/https/mydomain.crt 149 | TLS_CERT_FILE = "keys/doge-test-rpc.panda.fans.pem" 150 | # key file path to enable https, for example: /etc/https/mydomain.key 151 | TLS_KEY_FILE = "keys/doge-test-rpc.panda.fans.key" 152 | 153 | ECDSA_PUB_KEY_1="A44DZpzDwDvq9HwW3_dynOfDgkMJHKgOxUyCOrv5Pl3O" 154 | 155 | # ECDSA_PUB_KEY_2="xxxxxx" 156 | 157 | ALLOW_AGENTS="ICPanda" 158 | 159 | URL_DOGE_TEST="http://172.16.32.1:44555/" 160 | URL_DOGE="http://172.16.32.1:22555/" 161 | # URL_XXX=... 162 | 163 | HEADER_API_TOKEN="Basic SUNQYW5kYTpJVEZDNlJjam56RkdEQnd0SzByYV9kS0swR29lSElqVUl3V2lEb3VrRWU0" 164 | # HEADER_XXX=... 165 | ``` 166 | 167 | Run proxy with Docker: 168 | ```bash 169 | docker run --restart=always -v /mnt/idempotent-proxy/.env:/app/.env -v /mnt/idempotent-proxy/keys:/app/keys --name proxy -d -p 443:443 ghcr.io/ldclabs/idempotent-proxy:latest 170 | ``` 171 | 172 | ## Request Examples 173 | 174 | ### Regular Proxy Request Example 175 | 176 | Make a request: 177 | ```bash 178 | curl -v -X GET 'http://localhost:8080/get' \ 179 | -H 'x-forwarded-host: httpbin.org' \ 180 | -H 'idempotency-key: idempotency_key_001' \ 181 | -H 'content-type: application/json' 182 | ``` 183 | 184 | Response: 185 | ```text 186 | < HTTP/1.1 200 OK 187 | < date: Wed, 22 May 2024 11:03:33 GMT 188 | < content-type: application/json 189 | < content-length: 375 190 | < server: gunicorn/19.9.0 191 | < access-control-allow-origin: * 192 | < access-control-allow-credentials: true 193 | < 194 | { 195 | "args": {}, 196 | "headers": { 197 | "Accept": "*/*", 198 | "Accept-Encoding": "gzip", 199 | "Content-Type": "application/json", 200 | "Host": "httpbin.org", 201 | "Idempotency-Key": "idempotency_key_001", 202 | "User-Agent": "curl/8.6.0", 203 | "X-Amzn-Trace-Id": "Root=1-664dd105-7930bcc43ae6081a4508d114" 204 | }, 205 | "origin": "120.204.60.218", 206 | "url": "https://httpbin.org/get" 207 | } 208 | ``` 209 | 210 | Request again with the same idempotency key will return the same response. 211 | 212 | ### Proxy Request Example with `URL_` Constant Defined 213 | 214 | Setting in .env file: 215 | ```text 216 | URL_HTTPBIN="https://httpbin.org/get?api-key=abc123" 217 | ``` 218 | 219 | Make a request with `URL_HTTPBIN` constant in url path: 220 | ```bash 221 | curl -v -X GET 'http://localhost:8080/URL_HTTPBIN' \ 222 | -H 'idempotency-key: idempotency_key_001' \ 223 | -H 'content-type: application/json' 224 | ``` 225 | 226 | Response: 227 | ```text 228 | < HTTP/1.1 200 OK 229 | < date: Wed, 22 May 2024 11:07:05 GMT 230 | < content-type: application/json 231 | < content-length: 417 232 | < server: gunicorn/19.9.0 233 | < access-control-allow-origin: * 234 | < access-control-allow-credentials: true 235 | < 236 | { 237 | "args": { 238 | "api-key": "abc123" 239 | }, 240 | "headers": { 241 | "Accept": "*/*", 242 | "Accept-Encoding": "gzip", 243 | "Content-Type": "application/json", 244 | "Host": "httpbin.org", 245 | "Idempotency-Key": "idempotency_key_001", 246 | "User-Agent": "curl/8.6.0", 247 | "X-Amzn-Trace-Id": "Root=1-664dd1d9-6612bfd076e95b814dd9329d" 248 | }, 249 | "origin": "120.204.60.218", 250 | "url": "https://httpbin.org/get?api-key=abc123" 251 | } 252 | ``` 253 | 254 | ### Proxy Request Example with `HEADER_` Constant Defined 255 | 256 | Setting in .env file: 257 | ```text 258 | URL_HTTPBIN="https://httpbin.org/get?api-key=abc123" 259 | HEADER_TOKEN="Bearer xyz123456" 260 | ``` 261 | 262 | Make a request with `HEADER_TOKEN` constant in header: 263 | ```bash 264 | curl -v -X GET 'http://localhost:8080/URL_HTTPBIN' \ 265 | -H 'idempotency-key: idempotency_key_001' \ 266 | -H 'authorization: HEADER_TOKEN' \ 267 | -H 'content-type: application/json' 268 | ``` 269 | 270 | Response: 271 | ```text 272 | < HTTP/1.1 200 OK 273 | < date: Wed, 22 May 2024 11:11:17 GMT 274 | < content-type: application/json 275 | < content-length: 459 276 | < server: gunicorn/19.9.0 277 | < access-control-allow-origin: * 278 | < access-control-allow-credentials: true 279 | < 280 | { 281 | "args": { 282 | "api-key": "abc123" 283 | }, 284 | "headers": { 285 | "Accept": "*/*", 286 | "Accept-Encoding": "gzip", 287 | "Authorization": "Bearer xyz123456", 288 | "Content-Type": "application/json", 289 | "Host": "httpbin.org", 290 | "Idempotency-Key": "idempotency_key_001", 291 | "User-Agent": "curl/8.6.0", 292 | "X-Amzn-Trace-Id": "Root=1-664dd2d5-15b233f974a01ca34bd9a8ab" 293 | }, 294 | "origin": "120.204.60.218", 295 | "url": "https://httpbin.org/get?api-key=abc123" 296 | } 297 | ``` 298 | 299 | ### Proxy Request Example with Response Headers Filtered 300 | 301 | Make a request with `response-headers` header: 302 | ```bash 303 | curl -v -X GET 'http://localhost:8080/URL_HTTPBIN' \ 304 | -H 'idempotency-key: idempotency_key_001' \ 305 | -H 'authorization: HEADER_TOKEN' \ 306 | -H 'response-headers: content-type,content-length' \ 307 | -H 'content-type: application/json' 308 | ``` 309 | 310 | Response: 311 | ```text 312 | < HTTP/1.1 200 OK 313 | < content-type: application/json 314 | < content-length: 515 315 | < date: Wed, 22 May 2024 11:13:39 GMT 316 | < 317 | { 318 | "args": { 319 | "api-key": "abc123" 320 | }, 321 | "headers": { 322 | "Accept": "*/*", 323 | "Accept-Encoding": "gzip", 324 | "Authorization": "Bearer xyz123456", 325 | "Content-Type": "application/json", 326 | "Host": "httpbin.org", 327 | "Idempotency-Key": "idempotency_key_001", 328 | "Response-Headers": "content-type,content-length", 329 | "User-Agent": "curl/8.6.0", 330 | "X-Amzn-Trace-Id": "Root=1-664dd363-2bbae4420bf9add8512f5930" 331 | }, 332 | "origin": "120.204.60.218", 333 | "url": "https://httpbin.org/get?api-key=abc123" 334 | } 335 | ``` 336 | 337 | ### Proxy Request Example with JSON Response Filtered 338 | 339 | Make a request with `x-json-mask` header: 340 | ```bash 341 | curl -v -X GET 'http://localhost:8080/URL_HTTPBIN' \ 342 | -H 'idempotency-key: idempotency_key_001' \ 343 | -H 'authorization: HEADER_TOKEN' \ 344 | -H 'response-headers: content-type,content-length' \ 345 | -H 'x-json-mask: args,url' \ 346 | -H 'content-type: application/json' 347 | ``` 348 | 349 | Response: 350 | ```text 351 | < HTTP/1.1 200 OK 352 | < content-type: application/json 353 | < content-length: 76 354 | < date: Wed, 22 May 2024 12:19:03 GMT 355 | < 356 | * Connection #0 to host localhost left intact 357 | {"args":{"api-key":"abc123"},"url":"https://httpbin.org/get?api-key=abc123"} 358 | ``` 359 | 360 | ### Proxy Request Example with Access Control Added 361 | 362 | Setting in .env file: 363 | ```text 364 | ECDSA_PUB_KEY_1="A6t1U8kc10AbLJ3-V1avU4rYvmAsYjXuzY0kPublttot" 365 | ``` 366 | 367 | You can add other public keys by adding `ECDSA_PUB_KEY_2`, `ECDSA_PUB_KEY_abc` for key rotation. 368 | 369 | Make a request with `proxy-authorization` header, the bearer token is signed with the private key: 370 | ```bash 371 | curl -v -X GET 'http://localhost:8080/URL_HTTPBIN' \ 372 | -H 'idempotency-key: idempotency_key_001' \ 373 | -H 'proxy-authorization: Bearer 6LduPbIpAAAAANSOUfb-8bU45eilZFSmlSguN5TO' \ 374 | -H 'authorization: HEADER_TOKEN' \ 375 | -H 'response-headers: content-type,content-length' \ 376 | -H 'x-json-mask: args,url' \ 377 | -H 'content-type: application/json' 378 | ``` 379 | 380 | A 407 response: 381 | ```text 382 | < HTTP/1.1 407 Proxy Authentication Required 383 | < content-type: text/plain; charset=utf-8 384 | < content-length: 34 385 | < date: Wed, 22 May 2024 12:24:40 GMT 386 | < 387 | * Connection #0 to host localhost left intact 388 | proxy authentication verify failed: failed to decode CBOR data 389 | ``` 390 | 391 | ## License 392 | Copyright © 2024 [LDC Labs](https://github.com/ldclabs). 393 | 394 | `ldclabs/idempotent-proxy` is licensed under the MIT License. See [LICENSE](LICENSE-MIT) for the full license text. --------------------------------------------------------------------------------