mirror of
https://github.com/n0-computer/iroh.git
synced 2026-11-29 08:01:13 +00:00
feat(iroh): Pluggable crypto backends (#3992)
## Description - Introduces a `ring` feature flag that enables turning off the ring dependency - Introduces a `aws-lc-rs` feature flag that enables using aws-lc-rs as the crypto provider for rustls for everything TLS in iroh - Adds `iroh::endpoint::Builder::crypto_provider` allowing anyone to configure custom crypto providers beyond ring and aws-lc-rs. This is a required call when neither `ring` nor `aws-lc-rs` are enabled, but will default to either (preferring ring) if the features are enabled. - Adds `presets::Empty` and `presets::Minimal`. The latter sets the minimal set of required options on the builder, but is only available on the `ring` or `aws-lc-rs` feature flags. - Removes `Endpoint::empty_builder` in favor of `Endpoint::builder` together with either the `presets::Empty` or `presets::Minimal`. Depends on https://github.com/n0-computer/noq/pull/496 ## Breaking Changes - Added `iroh::endpoint::Builder::crypto_provider` for configuring the crypto provider. After having built the Endpoint, you can get back the crypto provider via `endpoint.tls_config().crypto_provider()`. - Removed `Endpoint::empty_builder`. Use `Endpoint::builder(presets::Empty)` or `Endpoint::builder(presets::Minimal)` instead. - **Behavioral**: If you don't call `iroh::endpoint::Builder::crypto_provider`, you will get an error when building in the call `Builder::bind()`. ## Notes & Open Questions It's probably worth asking ourselves if we want to change the way we run CI now. Most of our tests are cfg-ed out when you disable *both* the ring and aws-lc-rs features. However, maybe we should add another test category that's like `--no-default-features --feature ring/aws-lc-rs`? We could call it `minimal` (and I guess we'd have to decide to use either ring or aws-lc-rs).
This commit is contained in:
@@ -200,10 +200,10 @@ jobs:
|
||||
run: cargo build --target wasm32-unknown-unknown -p iroh-base --all-features
|
||||
|
||||
- name: wasm32 build (iroh-relay)
|
||||
run: cargo build --target wasm32-unknown-unknown -p iroh-relay --no-default-features
|
||||
run: cargo build --target wasm32-unknown-unknown -p iroh-relay
|
||||
|
||||
- name: wasm32 build (iroh)
|
||||
run: cargo build --target wasm32-unknown-unknown -p iroh --no-default-features
|
||||
run: cargo build --target wasm32-unknown-unknown -p iroh
|
||||
|
||||
# If the Wasm file contains any 'import "env"' declarations, then
|
||||
# some non-Wasm-compatible code made it into the final code.
|
||||
@@ -216,7 +216,7 @@ jobs:
|
||||
! wasm-tools print --skeleton target/wasm32-unknown-unknown/debug/iroh.wasm | grep 'import "env"'
|
||||
|
||||
- name: Run integration test in wasm
|
||||
run: cargo test -p iroh --test integration --target=wasm32-unknown-unknown --no-default-features
|
||||
run: cargo test -p iroh --test integration --target=wasm32-unknown-unknown
|
||||
|
||||
check_semver:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -317,11 +317,13 @@ jobs:
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- name: Verify optional deps are absent without features
|
||||
run: |
|
||||
tree=$(cargo tree -p iroh --no-default-features --edges normal)
|
||||
fail=0
|
||||
for dep in portmapper igd-next swarm-discovery; do
|
||||
if echo "$tree" | grep -q "$dep"; then
|
||||
for dep in portmapper igd-next swarm-discovery ring aws-lc-rs; do
|
||||
echo "cargo tree -p iroh --no-default-features --edges normal --target all -i $dep";
|
||||
output=$(cargo tree -p iroh --no-default-features --edges normal --target all -i "$dep" 2>&1) || true
|
||||
if ! echo "$output" | grep -qE "(nothing to print|did not match any packages)"; then
|
||||
echo "ERROR: $dep should not be in the dependency tree without its feature"
|
||||
echo "$output"
|
||||
fail=1
|
||||
fi
|
||||
done
|
||||
|
||||
Generated
+129
-19
@@ -279,6 +279,28 @@ version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
|
||||
|
||||
[[package]]
|
||||
name = "aws-lc-rs"
|
||||
version = "1.16.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94bffc006df10ac2a68c83692d734a465f8ee6c5b384d8545a636f81d858f4bf"
|
||||
dependencies = [
|
||||
"aws-lc-sys",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aws-lc-sys"
|
||||
version = "0.38.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4321e568ed89bb5a7d291a7f37997c2c0df89809d7b6d12062c81ddb54aa782e"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cmake",
|
||||
"dunce",
|
||||
"fs_extra",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "axum"
|
||||
version = "0.8.8"
|
||||
@@ -487,6 +509,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aebf35691d1bfb0ac386a69bac2fde4dd276fb618cf8bf4f5318fe285e821bb2"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"jobserver",
|
||||
"libc",
|
||||
"shlex",
|
||||
]
|
||||
|
||||
@@ -599,6 +623,21 @@ version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a822ea5bc7590f9d40f1ba12c0dc3c2760f3482c6984db1573ad11031420831"
|
||||
|
||||
[[package]]
|
||||
name = "cmake"
|
||||
version = "0.1.57"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "75443c44cd6b379beb8c5b45d85d0773baf31cce901fe7bb252f4eff3008ef7d"
|
||||
dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cmov"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "de0758edba32d61d1fd9f4d69491b47604b91ee2f7e6b33de7e54ca4ebe55dc3"
|
||||
|
||||
[[package]]
|
||||
name = "cobs"
|
||||
version = "0.3.0"
|
||||
@@ -825,6 +864,15 @@ dependencies = [
|
||||
"cipher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ctutils"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1005a6d4446f5120ef475ad3d2af2b30c49c2c9c6904258e3bb30219bebed5e4"
|
||||
dependencies = [
|
||||
"cmov",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "curve25519-dalek"
|
||||
version = "5.0.0-pre.1"
|
||||
@@ -1119,6 +1167,12 @@ dependencies = [
|
||||
"litrs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dunce"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
|
||||
|
||||
[[package]]
|
||||
name = "dyn-clone"
|
||||
version = "1.0.20"
|
||||
@@ -1312,6 +1366,12 @@ dependencies = [
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fs_extra"
|
||||
version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
|
||||
|
||||
[[package]]
|
||||
name = "futures"
|
||||
version = "0.3.32"
|
||||
@@ -2090,12 +2150,14 @@ version = "0.97.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"backon",
|
||||
"blake3",
|
||||
"bytes",
|
||||
"cfg_aliases",
|
||||
"chrono",
|
||||
"clap",
|
||||
"console",
|
||||
"console_error_panic_hook",
|
||||
"ctutils",
|
||||
"data-encoding",
|
||||
"derive_more",
|
||||
"ed25519-dalek",
|
||||
@@ -2127,7 +2189,7 @@ dependencies = [
|
||||
"pretty_assertions",
|
||||
"rand",
|
||||
"rand_chacha",
|
||||
"reqwest",
|
||||
"reqwest 0.13.2",
|
||||
"rustc-hash",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
@@ -2227,7 +2289,7 @@ dependencies = [
|
||||
"rcgen",
|
||||
"redb",
|
||||
"regex",
|
||||
"reqwest",
|
||||
"reqwest 0.13.2",
|
||||
"rustls",
|
||||
"serde",
|
||||
"serde_json",
|
||||
@@ -2264,7 +2326,7 @@ dependencies = [
|
||||
"n0-error",
|
||||
"portable-atomic",
|
||||
"postcard",
|
||||
"reqwest",
|
||||
"reqwest 0.12.28",
|
||||
"ryu",
|
||||
"serde",
|
||||
"tokio",
|
||||
@@ -2318,7 +2380,7 @@ dependencies = [
|
||||
"rand_chacha",
|
||||
"rcgen",
|
||||
"reloadable-state",
|
||||
"reqwest",
|
||||
"reqwest 0.13.2",
|
||||
"rustls",
|
||||
"rustls-cert-file-reader",
|
||||
"rustls-cert-reloadable-resolver",
|
||||
@@ -2389,6 +2451,16 @@ version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130"
|
||||
|
||||
[[package]]
|
||||
name = "jobserver"
|
||||
version = "0.1.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.91"
|
||||
@@ -2816,8 +2888,7 @@ checksum = "38bf9645c8b145698bb0b18a4637dcacbc421ea49bef2317e4fd8065a387cf21"
|
||||
[[package]]
|
||||
name = "noq"
|
||||
version = "0.17.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8df966fb44ac763bc86da97fa6c811c54ae82ef656575949f93c6dae0c9f09bf"
|
||||
source = "git+https://github.com/n0-computer/noq?branch=main#8adda44486fdf33f08ae7481b2c3b3a4db587548"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"cfg_aliases",
|
||||
@@ -2826,7 +2897,7 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
"rustc-hash",
|
||||
"rustls",
|
||||
"socket2 0.6.3",
|
||||
"socket2 0.5.10",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tokio-stream",
|
||||
@@ -2837,10 +2908,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "noq-proto"
|
||||
version = "0.16.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5c61b72abd670eebc05b5cf720e077b04a3ef3354bc7bc19f1c3524cb424db7b"
|
||||
source = "git+https://github.com/n0-computer/noq?branch=main#8adda44486fdf33f08ae7481b2c3b3a4db587548"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"aws-lc-rs",
|
||||
"bytes",
|
||||
"derive_more",
|
||||
"enum-assoc",
|
||||
@@ -2866,12 +2937,11 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "noq-udp"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bb9be4fedd6b98f3ba82ccd3506f4d0219fb723c3f97c67e12fe1494aa020e44"
|
||||
source = "git+https://github.com/n0-computer/noq?branch=main#8adda44486fdf33f08ae7481b2c3b3a4db587548"
|
||||
dependencies = [
|
||||
"cfg_aliases",
|
||||
"libc",
|
||||
"socket2 0.6.3",
|
||||
"socket2 0.5.10",
|
||||
"tracing",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
@@ -3200,7 +3270,7 @@ dependencies = [
|
||||
"lru",
|
||||
"mainline",
|
||||
"ntimestamp",
|
||||
"reqwest",
|
||||
"reqwest 0.12.28",
|
||||
"self_cell",
|
||||
"serde",
|
||||
"sha1_smol",
|
||||
@@ -3701,8 +3771,6 @@ dependencies = [
|
||||
"base64",
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"h2",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
@@ -3722,6 +3790,45 @@ dependencies = [
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tower",
|
||||
"tower-http",
|
||||
"tower-service",
|
||||
"url",
|
||||
"wasm-bindgen",
|
||||
"wasm-bindgen-futures",
|
||||
"web-sys",
|
||||
"webpki-roots",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "reqwest"
|
||||
version = "0.13.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ab3f43e3283ab1488b624b44b0e988d0acea0b3214e694730a055cb6b2efa801"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bytes",
|
||||
"futures-core",
|
||||
"futures-util",
|
||||
"h2",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"hyper",
|
||||
"hyper-rustls",
|
||||
"hyper-util",
|
||||
"js-sys",
|
||||
"log",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
"rustls-platform-verifier",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sync_wrapper",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tokio-util",
|
||||
"tower",
|
||||
"tower-http",
|
||||
@@ -3731,7 +3838,6 @@ dependencies = [
|
||||
"wasm-bindgen-futures",
|
||||
"wasm-streams",
|
||||
"web-sys",
|
||||
"webpki-roots",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3797,6 +3903,7 @@ version = "0.23.37"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"log",
|
||||
"once_cell",
|
||||
"ring",
|
||||
@@ -3895,6 +4002,7 @@ version = "0.103.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"untrusted",
|
||||
@@ -4630,7 +4738,7 @@ dependencies = [
|
||||
"pem",
|
||||
"proc-macro2",
|
||||
"rcgen",
|
||||
"reqwest",
|
||||
"reqwest 0.12.28",
|
||||
"ring",
|
||||
"rustls",
|
||||
"serde",
|
||||
@@ -4675,6 +4783,7 @@ version = "0.12.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b1b6348ebfaaecd771cecb69e832961d277f59845d4220a584701f72728152b7"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"base64",
|
||||
"bytes",
|
||||
"futures-core",
|
||||
@@ -4685,6 +4794,7 @@ dependencies = [
|
||||
"rand",
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"sha1_smol",
|
||||
"simdutf8",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
@@ -5211,9 +5321,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "wasm-streams"
|
||||
version = "0.4.2"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65"
|
||||
checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb"
|
||||
dependencies = [
|
||||
"futures-util",
|
||||
"js-sys",
|
||||
|
||||
@@ -40,3 +40,8 @@ unexpected_cfgs = { level = "warn", check-cfg = ["cfg(iroh_docsrs)", "cfg(iroh_l
|
||||
|
||||
[workspace.lints.clippy]
|
||||
unused-async = "warn"
|
||||
|
||||
[patch.crates-io]
|
||||
noq = { git = "https://github.com/n0-computer/noq", branch = "main" }
|
||||
noq-proto = { git = "https://github.com/n0-computer/noq", branch = "main" }
|
||||
noq-udp = { git = "https://github.com/n0-computer/noq", branch = "main" }
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[bans]
|
||||
multiple-versions = "allow"
|
||||
deny = ["aws-lc", "aws-lc-rs", "aws-lc-sys", "native-tls", "openssl"]
|
||||
deny = ["native-tls", "openssl"]
|
||||
|
||||
[licenses]
|
||||
allow = [
|
||||
@@ -16,6 +16,7 @@ allow = [
|
||||
"MPL-2.0", # https://fossa.com/blog/open-source-software-licenses-101-mozilla-public-license-2-0/
|
||||
"Unicode-3.0",
|
||||
"Unlicense", # https://unlicense.org/
|
||||
"OpenSSL", # aws-lc-rs
|
||||
]
|
||||
|
||||
|
||||
@@ -26,4 +27,4 @@ ignore = [
|
||||
]
|
||||
|
||||
[sources]
|
||||
allow-git = []
|
||||
allow-git = ["https://github.com/n0-computer/noq"]
|
||||
|
||||
+15
-1
@@ -11,7 +11,7 @@ use std::{
|
||||
|
||||
use curve25519_dalek::edwards::CompressedEdwardsY;
|
||||
use ed25519_dalek::{SigningKey, VerifyingKey};
|
||||
use n0_error::{ensure, stack_error};
|
||||
use n0_error::{e, ensure, stack_error};
|
||||
use rand_core::CryptoRng;
|
||||
use serde::{Deserialize, Serialize, de, ser};
|
||||
|
||||
@@ -396,6 +396,20 @@ impl Display for Signature {
|
||||
}
|
||||
}
|
||||
|
||||
#[stack_error(derive, add_meta)]
|
||||
#[error("Could not parse ed25519 signature")]
|
||||
pub struct SignatureParsingError;
|
||||
|
||||
impl TryFrom<&[u8]> for Signature {
|
||||
type Error = SignatureParsingError;
|
||||
|
||||
fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
|
||||
let signature =
|
||||
ed25519_dalek::Signature::from_slice(bytes).map_err(|_| e!(SignatureParsingError))?;
|
||||
Ok(Self(signature))
|
||||
}
|
||||
}
|
||||
|
||||
impl Signature {
|
||||
/// The length of an ed25519 `Signature`, in bytes.
|
||||
pub const LENGTH: usize = ed25519_dalek::Signature::BYTE_SIZE;
|
||||
|
||||
@@ -35,17 +35,14 @@ pkarr = { version = "5", features = ["dht"], default-features = false }
|
||||
rcgen = "0.14"
|
||||
redb = "3.1.0"
|
||||
regex = "1.10.3"
|
||||
rustls = { version = "0.23.33", default-features = false, features = ["ring"] }
|
||||
rustls = { version = "0.23.33", default-features = false }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
struct_iterable = "0.1.1"
|
||||
n0-error = "0.1"
|
||||
strum = { version = "0.28", features = ["derive"] }
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
tokio-rustls = { version = "0.26", default-features = false, features = [
|
||||
"logging",
|
||||
"ring",
|
||||
] }
|
||||
tokio-rustls = { version = "0.26", default-features = false, features = ["logging"] }
|
||||
tokio-rustls-acme = { version = "0.9", features = ["axum"] }
|
||||
tokio-stream = "0.1.14"
|
||||
tokio-util = "0.7"
|
||||
@@ -67,16 +64,24 @@ n0-tracing-test = "0.3"
|
||||
pkarr = { version = "5", features = ["relays", "dht"], default-features = false }
|
||||
rand = "0.9.2"
|
||||
rand_chacha = "0.9"
|
||||
reqwest = { version = "0.12", default-features = false, features = [
|
||||
"rustls-tls", "http2"
|
||||
reqwest = { version = "0.13", default-features = false, features = [
|
||||
"rustls-no-provider", "http2", "json"
|
||||
] }
|
||||
serde_json = "1.0.145"
|
||||
tempfile = "3.23.0"
|
||||
|
||||
[features]
|
||||
default = ["ring"]
|
||||
ring = ["rustls/ring", "tokio-rustls/ring"]
|
||||
|
||||
[[bench]]
|
||||
name = "write"
|
||||
harness = false
|
||||
|
||||
[[example]]
|
||||
name = "publish"
|
||||
required-features = ["ring"]
|
||||
|
||||
[build-dependencies]
|
||||
vergen-gitcl = "1.0.8"
|
||||
|
||||
|
||||
@@ -506,9 +506,13 @@ mod tests {
|
||||
}
|
||||
|
||||
pub(super) fn insecure_tls_config() -> ClientConfig {
|
||||
let mut cfg = ClientConfig::builder()
|
||||
.with_root_certificates(RootCertStore::empty())
|
||||
.with_no_client_auth();
|
||||
let mut cfg = ClientConfig::builder_with_provider(Arc::new(
|
||||
rustls::crypto::ring::default_provider(),
|
||||
))
|
||||
.with_safe_default_protocol_versions()
|
||||
.unwrap()
|
||||
.with_root_certificates(RootCertStore::empty())
|
||||
.with_no_client_auth();
|
||||
cfg.dangerous()
|
||||
.set_certificate_verifier(Arc::new(NoCertificateVerification::default()));
|
||||
cfg
|
||||
|
||||
@@ -11,7 +11,10 @@ use axum_server::{
|
||||
};
|
||||
use n0_error::{Result, StackResultExt, StdResultExt, bail_any};
|
||||
use n0_future::{FutureExt, future::Boxed as BoxFuture};
|
||||
use rustls::pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject};
|
||||
use rustls::{
|
||||
ServerConfig,
|
||||
pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tokio_rustls_acme::{AcmeConfig, axum::AxumAcceptor, caches::DirCache};
|
||||
@@ -77,15 +80,29 @@ impl TlsAcceptor {
|
||||
async fn self_signed(domains: Vec<String>) -> Result<Self> {
|
||||
let rcgen::CertifiedKey { cert, signing_key } =
|
||||
rcgen::generate_simple_self_signed(domains).anyerr()?;
|
||||
let config = RustlsConfig::from_der(vec![cert.der().to_vec()], signing_key.serialize_der())
|
||||
.await
|
||||
.anyerr()?;
|
||||
let acceptor = RustlsAcceptor::new(config);
|
||||
let key = PrivateKeyDer::try_from(signing_key.serialize_der())?;
|
||||
|
||||
let mut config =
|
||||
ServerConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
|
||||
.with_safe_default_protocol_versions()
|
||||
.anyerr()?
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(vec![cert.der().clone()], key)
|
||||
.anyerr()?;
|
||||
|
||||
config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
|
||||
let acceptor = RustlsAcceptor::new(RustlsConfig::from_config(Arc::new(config)));
|
||||
Ok(Self::Manual(acceptor))
|
||||
}
|
||||
|
||||
async fn manual(domains: Vec<String>, dir: PathBuf) -> Result<Self> {
|
||||
let config = rustls::ServerConfig::builder().with_no_client_auth();
|
||||
let config = rustls::ServerConfig::builder_with_provider(Arc::new(
|
||||
rustls::crypto::ring::default_provider(),
|
||||
))
|
||||
.with_safe_default_protocol_versions()
|
||||
.anyerr()?
|
||||
.with_no_client_auth();
|
||||
|
||||
if domains.len() != 1 {
|
||||
bail_any!("Multiple domains in manual mode are not supported");
|
||||
}
|
||||
|
||||
+25
-17
@@ -46,13 +46,11 @@ postcard = { version = "1", default-features = false, features = [
|
||||
"use-std",
|
||||
"experimental-derive",
|
||||
] }
|
||||
noq = { version = "0.17.0", default-features = false, features = ["rustls-ring"] }
|
||||
noq-proto = "0.16.0"
|
||||
noq = { version = "0.17.0", default-features = false, features = ["rustls"] }
|
||||
noq-proto = { version = "0.16.0", default-features = false }
|
||||
rand = "0.9.2"
|
||||
reqwest = { version = "0.12", default-features = false, features = [
|
||||
"rustls-tls",
|
||||
] }
|
||||
rustls = { version = "0.23.33", default-features = false, features = ["ring"] }
|
||||
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider"] }
|
||||
rustls = { version = "0.23.33", default-features = false }
|
||||
rustls-platform-verifier = { version = "0.6.2", optional = true }
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_bytes = "0.11.17"
|
||||
@@ -63,10 +61,7 @@ tokio = { version = "1", features = [
|
||||
"sync",
|
||||
"rt",
|
||||
] }
|
||||
tokio-rustls = { version = "0.26", default-features = false, features = [
|
||||
"logging",
|
||||
"ring",
|
||||
] }
|
||||
tokio-rustls = { version = "0.26", default-features = false, features = ["logging"] }
|
||||
tokio-util = { version = "0.7", features = ["io-util", "io", "codec", "rt"] }
|
||||
tracing = "0.1"
|
||||
url = { version = "2.5.3", features = ["serde"] }
|
||||
@@ -84,18 +79,16 @@ rustls-cert-reloadable-resolver = { version = "0.7.1", optional = true }
|
||||
rustls-cert-file-reader = { version = "0.4.2", optional = true }
|
||||
time = { version = "0.3.37", optional = true }
|
||||
tokio-rustls-acme = { version = "0.9", optional = true }
|
||||
tokio-websockets = { version = "0.12", features = ["rustls-bring-your-own-connector", "ring", "getrandom", "rand", "server"], optional = true } # server-side websocket implementation
|
||||
tokio-websockets = { version = "0.12", features = ["rustls-bring-your-own-connector", "getrandom", "rand", "server", "sha1_smol"], optional = true } # server-side websocket implementation
|
||||
simdutf8 = { version = "0.1.5", optional = true } # minimal version fix
|
||||
sha1 = { version = "0.11.0-rc.2", optional = true }
|
||||
toml = { version = "1.0", optional = true }
|
||||
serde_json = { version = "1", optional = true }
|
||||
tracing-subscriber = { version = "0.3", features = [
|
||||
"env-filter",
|
||||
], optional = true }
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"], optional = true }
|
||||
|
||||
# non-wasm-in-browser dependencies
|
||||
[target.'cfg(not(all(target_family = "wasm", target_os = "unknown")))'.dependencies]
|
||||
hickory-resolver = { version = "0.25.1", features = ["tokio", "https-ring"] }
|
||||
hickory-resolver = { version = "0.25.1", features = ["tokio", "system-config"] }
|
||||
tokio = { version = "1", features = [
|
||||
"io-util",
|
||||
"macros",
|
||||
@@ -105,7 +98,7 @@ tokio = { version = "1", features = [
|
||||
"fs",
|
||||
"io-std",
|
||||
] }
|
||||
tokio-websockets = { version = "0.12", features = ["rustls-bring-your-own-connector", "ring", "getrandom", "rand", "client"] }
|
||||
tokio-websockets = { version = "0.12", features = ["rustls-bring-your-own-connector", "getrandom", "rand", "client", "sha1_smol"] }
|
||||
|
||||
# wasm-in-browser dependencies
|
||||
[target.'cfg(all(target_family = "wasm", target_os = "unknown"))'.dependencies]
|
||||
@@ -135,7 +128,7 @@ cfg_aliases = "0.2.1"
|
||||
vergen-gitcl = "1.0.8"
|
||||
|
||||
[features]
|
||||
default = ["metrics"]
|
||||
default = ["metrics", "tls-ring"]
|
||||
# Enables fetching TLS trust anchors from the operating system
|
||||
platform-verifier = ["dep:rustls-platform-verifier"]
|
||||
server = [
|
||||
@@ -159,9 +152,24 @@ server = [
|
||||
"noq/platform-verifier",
|
||||
"noq/runtime-tokio",
|
||||
"iroh-metrics/service",
|
||||
"tls-ring",
|
||||
]
|
||||
metrics = ["iroh-metrics/metrics"]
|
||||
test-utils = []
|
||||
tls-ring = [
|
||||
"noq/ring",
|
||||
"rustls/ring",
|
||||
"tokio-rustls/ring",
|
||||
"tokio-websockets/ring",
|
||||
"hickory-resolver/https-ring",
|
||||
]
|
||||
tls-aws-lc-rs = [
|
||||
"noq/aws-lc-rs",
|
||||
"rustls/aws-lc-rs",
|
||||
"tokio-rustls/aws-lc-rs",
|
||||
"tokio-websockets/aws_lc_rs",
|
||||
"hickory-resolver/https-aws-lc-rs",
|
||||
]
|
||||
|
||||
[[bin]]
|
||||
name = "iroh-relay"
|
||||
|
||||
@@ -6,6 +6,7 @@ fn main() {
|
||||
cfg_aliases! {
|
||||
// Convenience aliases
|
||||
wasm_browser: { all(target_family = "wasm", target_os = "unknown") },
|
||||
with_crypto_provider: { any(feature = "tls-ring", feature = "tls-aws-lc-rs") }
|
||||
}
|
||||
|
||||
// Emit build-time environment variables
|
||||
|
||||
+29
-67
@@ -17,8 +17,6 @@ use n0_future::{
|
||||
split::{SplitSink, SplitStream, split},
|
||||
time,
|
||||
};
|
||||
#[cfg(any(test, feature = "test-utils"))]
|
||||
use tracing::warn;
|
||||
use tracing::{Level, debug, event, trace};
|
||||
use url::Url;
|
||||
|
||||
@@ -86,6 +84,10 @@ pub enum ConnectError {
|
||||
#[error(std_err)]
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error(
|
||||
"No rustls crypto provider configured while both ring and aws-lc-rs feature flags are disabled"
|
||||
)]
|
||||
MissingCryptoProvider,
|
||||
#[cfg(wasm_browser)]
|
||||
#[error("The relay protocol is not available in browsers")]
|
||||
RelayProtoNotAvailable {},
|
||||
@@ -169,6 +171,27 @@ impl ClientBuilder {
|
||||
}
|
||||
|
||||
/// Sets a custom TLS config.
|
||||
///
|
||||
/// This is a required option.
|
||||
///
|
||||
/// You can construct a [`rustls::ClientConfig`] by combining a [`rustls::crypto::CryptoProvider`]
|
||||
/// with a [`tls::CaRootsConfig`] using [`tls::CaRootsConfig::client_config`], for example:
|
||||
///
|
||||
/// ```no_run
|
||||
/// use std::sync::Arc;
|
||||
///
|
||||
/// use iroh_relay::tls::CaRootsConfig;
|
||||
///
|
||||
/// let crypto_provider: rustls::crypto::CryptoProvider = todo!();
|
||||
/// let client_config = CaRootsConfig::default().client_config(Arc::new(crypto_provider));
|
||||
/// ```
|
||||
///
|
||||
/// If you enable the tls-ring or tls-aws-lc-rs feature, you can use the enabled crypto provider
|
||||
/// by using [`tls::default_provider`].
|
||||
///
|
||||
/// [`tls::CaRootsConfig`]: crate::tls::CaRootsConfig
|
||||
/// [`tls::CaRootsConfig::client_config`]: crate::tls::CaRootsConfig::client_config
|
||||
/// [`tls::default_provider`]: crate::tls::default_provider
|
||||
pub fn tls_client_config(mut self, tls_config: rustls::ClientConfig) -> Self {
|
||||
self.tls_config = Some(tls_config);
|
||||
self
|
||||
@@ -209,7 +232,6 @@ impl ClientBuilder {
|
||||
use crate::{
|
||||
http::{CLIENT_AUTH_HEADER, RELAY_PROTOCOL_VERSION},
|
||||
protos::{handshake::KeyMaterialClientAuth, relay::MAX_FRAME_SIZE},
|
||||
tls::{CaRootsConfig, default_provider},
|
||||
};
|
||||
|
||||
let mut dial_url = (*self.url).clone();
|
||||
@@ -230,10 +252,10 @@ impl ClientBuilder {
|
||||
|
||||
debug!(%dial_url, "Dialing relay by websocket");
|
||||
|
||||
let tls_config = match self.tls_config.clone() {
|
||||
Some(config) => config,
|
||||
None => CaRootsConfig::default().client_config(default_provider())?,
|
||||
};
|
||||
let tls_config = self
|
||||
.tls_config
|
||||
.clone()
|
||||
.ok_or_else(|| e!(ConnectError::MissingCryptoProvider))?;
|
||||
|
||||
#[allow(unused_mut)]
|
||||
let mut builder =
|
||||
@@ -466,63 +488,3 @@ impl Stream for ClientStream {
|
||||
Pin::new(&mut self.stream).poll_next(cx)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-utils"))]
|
||||
/// Creates a client config that trusts any servers without verifying their TLS certificate.
|
||||
///
|
||||
/// Should be used for testing local relay setups only.
|
||||
pub fn make_dangerous_client_config() -> rustls::ClientConfig {
|
||||
warn!(
|
||||
"Insecure config: SSL certificates from relay servers will be trusted without verification"
|
||||
);
|
||||
rustls::client::ClientConfig::builder_with_provider(Arc::new(
|
||||
rustls::crypto::ring::default_provider(),
|
||||
))
|
||||
.with_protocol_versions(&[&rustls::version::TLS13])
|
||||
.expect("protocols supported by ring")
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(Arc::new(NoCertVerifier))
|
||||
.with_no_client_auth()
|
||||
}
|
||||
|
||||
/// Used to allow self signed certificates in tests
|
||||
#[cfg(any(test, feature = "test-utils"))]
|
||||
#[derive(Debug)]
|
||||
struct NoCertVerifier;
|
||||
|
||||
#[cfg(any(test, feature = "test-utils"))]
|
||||
impl rustls::client::danger::ServerCertVerifier for NoCertVerifier {
|
||||
fn verify_server_cert(
|
||||
&self,
|
||||
_end_entity: &rustls::pki_types::CertificateDer,
|
||||
_intermediates: &[rustls::pki_types::CertificateDer],
|
||||
_server_name: &rustls::pki_types::ServerName,
|
||||
_ocsp_response: &[u8],
|
||||
_now: rustls::pki_types::UnixTime,
|
||||
) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
|
||||
Ok(rustls::client::danger::ServerCertVerified::assertion())
|
||||
}
|
||||
fn verify_tls12_signature(
|
||||
&self,
|
||||
_message: &[u8],
|
||||
_cert: &rustls::pki_types::CertificateDer<'_>,
|
||||
_dss: &rustls::DigitallySignedStruct,
|
||||
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
|
||||
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
|
||||
}
|
||||
|
||||
fn verify_tls13_signature(
|
||||
&self,
|
||||
_message: &[u8],
|
||||
_cert: &rustls::pki_types::CertificateDer<'_>,
|
||||
_dss: &rustls::DigitallySignedStruct,
|
||||
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
|
||||
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
|
||||
}
|
||||
|
||||
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
|
||||
rustls::crypto::ring::default_provider()
|
||||
.signature_verification_algorithms
|
||||
.supported_schemes()
|
||||
}
|
||||
}
|
||||
|
||||
+12
-3
@@ -25,7 +25,6 @@ use n0_future::{
|
||||
boxed::BoxFuture,
|
||||
time::{self, Duration},
|
||||
};
|
||||
use rustls::ClientConfig;
|
||||
use tokio::sync::RwLock;
|
||||
use tracing::debug;
|
||||
use url::Url;
|
||||
@@ -124,7 +123,8 @@ impl<E: StackError + 'static> StaggeredError<E> {
|
||||
pub struct Builder {
|
||||
use_system_defaults: bool,
|
||||
nameservers: Vec<(SocketAddr, DnsProtocol)>,
|
||||
tls_client_config: Option<ClientConfig>,
|
||||
#[cfg(with_crypto_provider)]
|
||||
tls_client_config: Option<rustls::ClientConfig>,
|
||||
}
|
||||
|
||||
/// Protocols over which DNS records can be resolved.
|
||||
@@ -145,12 +145,14 @@ pub enum DnsProtocol {
|
||||
/// Performs DNS lookups over TLS-encrypted TCP connections, as defined in [RFC 7858].
|
||||
///
|
||||
/// [RFC 7858]: https://www.rfc-editor.org/rfc/rfc7858.html
|
||||
#[cfg(with_crypto_provider)]
|
||||
Tls,
|
||||
/// DNS over HTTPS
|
||||
///
|
||||
/// Performs DNS lookups over HTTPS, as defined in [RFC 8484].
|
||||
///
|
||||
/// [RFC 8484]: https://www.rfc-editor.org/rfc/rfc8484.html
|
||||
#[cfg(with_crypto_provider)]
|
||||
Https,
|
||||
}
|
||||
|
||||
@@ -160,7 +162,9 @@ impl DnsProtocol {
|
||||
match self {
|
||||
DnsProtocol::Udp => Protocol::Udp,
|
||||
DnsProtocol::Tcp => Protocol::Tcp,
|
||||
#[cfg(with_crypto_provider)]
|
||||
DnsProtocol::Tls => Protocol::Tls,
|
||||
#[cfg(with_crypto_provider)]
|
||||
DnsProtocol::Https => Protocol::Https,
|
||||
}
|
||||
}
|
||||
@@ -193,7 +197,11 @@ impl Builder {
|
||||
}
|
||||
|
||||
/// Sets a custom TLS verification config.
|
||||
pub fn tls_client_config(mut self, client_config: ClientConfig) -> Self {
|
||||
///
|
||||
/// This is only used with DNS-over-TLS and DNS-over-HTTPS, and requires
|
||||
/// enabling either the ring or aws-lc-rs feature.
|
||||
#[cfg(with_crypto_provider)]
|
||||
pub fn tls_client_config(mut self, client_config: rustls::ClientConfig) -> Self {
|
||||
self.tls_client_config = Some(client_config);
|
||||
self
|
||||
}
|
||||
@@ -517,6 +525,7 @@ impl HickoryResolver {
|
||||
(ResolverConfig::new(), ResolverOpts::default())
|
||||
};
|
||||
|
||||
#[cfg(with_crypto_provider)]
|
||||
if let Some(client_config) = builder.tls_client_config.clone() {
|
||||
options.tls_config = client_config;
|
||||
}
|
||||
|
||||
+14
-11
@@ -355,9 +355,9 @@ impl QuicClient {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "server"))]
|
||||
#[cfg(all(test, feature = "server", with_crypto_provider))]
|
||||
mod tests {
|
||||
use std::net::Ipv4Addr;
|
||||
use std::{net::Ipv4Addr, sync::Arc};
|
||||
|
||||
use n0_error::{Result, StdResultExt};
|
||||
use n0_future::{
|
||||
@@ -393,7 +393,7 @@ mod tests {
|
||||
|
||||
// create the client configuration used for the client endpoint when they
|
||||
// initiate a connection with the server
|
||||
let client_config = crate::client::make_dangerous_client_config();
|
||||
let client_config = crate::tls::make_dangerous_client_config();
|
||||
let quic_client = QuicClient::new(client_endpoint.clone(), client_config);
|
||||
|
||||
let (addr, _latency) = quic_client
|
||||
@@ -425,7 +425,7 @@ mod tests {
|
||||
|
||||
// create the client configuration used for the client endpoint when they
|
||||
// initiate a connection with the server
|
||||
let client_config = crate::client::make_dangerous_client_config();
|
||||
let client_config = crate::tls::make_dangerous_client_config();
|
||||
let quic_client = QuicClient::new(client_endpoint.clone(), client_config);
|
||||
|
||||
// Start a connection attempt with nirvana - this will fail
|
||||
@@ -459,9 +459,8 @@ mod tests {
|
||||
/// In this case we don't simulate it via synthetically high RTT, but by dropping
|
||||
/// all packets on the server-side for 2 seconds.
|
||||
#[tokio::test]
|
||||
// #[traced_test]
|
||||
#[traced_test]
|
||||
async fn test_qad_connect_delayed() -> Result {
|
||||
tracing_subscriber::fmt::try_init().ok();
|
||||
// Create a socket for our QAD server. We need the socket separately because we
|
||||
// need to pop off messages before we attach it to the Noq Endpoint.
|
||||
let socket = tokio::net::UdpSocket::bind(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0))
|
||||
@@ -474,10 +473,14 @@ mod tests {
|
||||
let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()])
|
||||
.std_context("self signed")?;
|
||||
let key = PrivatePkcs8KeyDer::from(cert.signing_key.serialize_der());
|
||||
let mut server_crypto = rustls::ServerConfig::builder()
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(vec![cert.cert.into()], key.into())
|
||||
.std_context("tls")?;
|
||||
let mut server_crypto = rustls::ServerConfig::builder_with_provider(Arc::new(
|
||||
rustls::crypto::ring::default_provider(),
|
||||
))
|
||||
.with_safe_default_protocol_versions()
|
||||
.std_context("crypto provider")?
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(vec![cert.cert.into()], key.into())
|
||||
.std_context("tls")?;
|
||||
server_crypto.key_log = Arc::new(rustls::KeyLogFile::new());
|
||||
server_crypto.alpn_protocols = vec![ALPN_QUIC_ADDR_DISC.to_vec()];
|
||||
let mut server_config = noq::ServerConfig::with_crypto(Arc::new(
|
||||
@@ -525,7 +528,7 @@ mod tests {
|
||||
|
||||
// create the client configuration used for the client endpoint when they
|
||||
// initiate a connection with the server
|
||||
let client_config = crate::client::make_dangerous_client_config();
|
||||
let client_config = crate::tls::make_dangerous_client_config();
|
||||
let quic_client = QuicClient::new(client_endpoint.clone(), client_config);
|
||||
|
||||
// Now we should still connect, but it should take more than 1s.
|
||||
|
||||
@@ -779,7 +779,7 @@ impl hyper::service::Service<Request<Incoming>> for CaptivePortalService {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{net::Ipv4Addr, time::Duration};
|
||||
use std::{net::Ipv4Addr, sync::Arc, time::Duration};
|
||||
|
||||
use http::StatusCode;
|
||||
use iroh_base::{EndpointId, RelayUrl, SecretKey};
|
||||
@@ -800,6 +800,7 @@ mod tests {
|
||||
handshake,
|
||||
relay::{ClientToRelayMsg, Datagrams, RelayToClientMsg},
|
||||
},
|
||||
tls::{CaRootsConfig, default_provider},
|
||||
};
|
||||
|
||||
async fn spawn_local_relay() -> std::result::Result<Server, SpawnError> {
|
||||
@@ -846,6 +847,16 @@ mod tests {
|
||||
DnsResolver::new()
|
||||
}
|
||||
|
||||
fn ring_config() -> rustls::ClientConfig {
|
||||
rustls::ClientConfig::builder_with_provider(Arc::new(
|
||||
rustls::crypto::ring::default_provider(),
|
||||
))
|
||||
.with_safe_default_protocol_versions()
|
||||
.unwrap()
|
||||
.with_root_certificates(rustls::RootCertStore::empty())
|
||||
.with_no_client_auth()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_no_services() {
|
||||
@@ -888,7 +899,10 @@ mod tests {
|
||||
let server = spawn_local_relay().await.unwrap();
|
||||
let url = format!("http://{}", server.http_addr().unwrap());
|
||||
|
||||
let client = reqwest::Client::builder().use_rustls_tls().build().unwrap();
|
||||
let client = reqwest::Client::builder()
|
||||
.use_preconfigured_tls(ring_config())
|
||||
.build()
|
||||
.unwrap();
|
||||
let response = client.get(&url).send().await.unwrap();
|
||||
assert_eq!(response.status(), 200);
|
||||
let body = response.text().await.unwrap();
|
||||
@@ -902,7 +916,10 @@ mod tests {
|
||||
let url = format!("http://{}/generate_204", server.http_addr().unwrap());
|
||||
let challenge = "123az__.";
|
||||
|
||||
let client = reqwest::Client::builder().use_rustls_tls().build().unwrap();
|
||||
let client = reqwest::Client::builder()
|
||||
.use_preconfigured_tls(ring_config())
|
||||
.build()
|
||||
.unwrap();
|
||||
let response = client
|
||||
.get(&url)
|
||||
.header(NO_CONTENT_CHALLENGE_HEADER, challenge)
|
||||
@@ -925,12 +942,17 @@ mod tests {
|
||||
let relay_url = format!("http://{}", server.http_addr().unwrap());
|
||||
let relay_url: RelayUrl = relay_url.parse()?;
|
||||
|
||||
let client_config = CaRootsConfig::default()
|
||||
.client_config(default_provider())
|
||||
.unwrap();
|
||||
|
||||
// set up client a
|
||||
let a_secret_key = SecretKey::generate(&mut rng);
|
||||
let a_key = a_secret_key.public();
|
||||
let resolver = dns_resolver();
|
||||
info!("client a build & connect");
|
||||
let mut client_a = ClientBuilder::new(relay_url.clone(), a_secret_key, resolver.clone())
|
||||
.tls_client_config(client_config.clone())
|
||||
.connect()
|
||||
.await?;
|
||||
|
||||
@@ -939,6 +961,7 @@ mod tests {
|
||||
let b_key = b_secret_key.public();
|
||||
info!("client b build & connect");
|
||||
let mut client_b = ClientBuilder::new(relay_url.clone(), b_secret_key, resolver.clone())
|
||||
.tls_client_config(client_config)
|
||||
.connect()
|
||||
.await?;
|
||||
|
||||
@@ -984,6 +1007,10 @@ mod tests {
|
||||
let current_span = tracing::info_span!("this is a test");
|
||||
let _guard = current_span.enter();
|
||||
|
||||
let client_config = CaRootsConfig::default()
|
||||
.client_config(default_provider())
|
||||
.unwrap();
|
||||
|
||||
let a_secret_key = SecretKey::generate(&mut rng);
|
||||
let a_key = a_secret_key.public();
|
||||
|
||||
@@ -1017,6 +1044,7 @@ mod tests {
|
||||
// set up client a
|
||||
let resolver = dns_resolver();
|
||||
let result = ClientBuilder::new(relay_url.clone(), a_secret_key, resolver)
|
||||
.tls_client_config(client_config.clone())
|
||||
.connect()
|
||||
.await;
|
||||
|
||||
@@ -1032,6 +1060,7 @@ mod tests {
|
||||
|
||||
let resolver = dns_resolver();
|
||||
let mut client_b = ClientBuilder::new(relay_url.clone(), b_secret_key, resolver)
|
||||
.tls_client_config(client_config.clone())
|
||||
.connect()
|
||||
.await?;
|
||||
|
||||
@@ -1041,6 +1070,7 @@ mod tests {
|
||||
|
||||
let resolver = dns_resolver();
|
||||
let mut client_c = ClientBuilder::new(relay_url.clone(), c_secret_key, resolver)
|
||||
.tls_client_config(client_config)
|
||||
.connect()
|
||||
.await?;
|
||||
|
||||
@@ -1070,10 +1100,15 @@ mod tests {
|
||||
let relay_url = format!("http://{}", server.http_addr().unwrap());
|
||||
let relay_url: RelayUrl = relay_url.parse().unwrap();
|
||||
|
||||
let client_config = CaRootsConfig::default()
|
||||
.client_config(default_provider())
|
||||
.unwrap();
|
||||
|
||||
// set up client a
|
||||
let a_secret_key = SecretKey::generate(&mut rng);
|
||||
let resolver = dns_resolver();
|
||||
let mut client_a = ClientBuilder::new(relay_url.clone(), a_secret_key, resolver.clone())
|
||||
.tls_client_config(client_config.clone())
|
||||
.connect()
|
||||
.await?;
|
||||
|
||||
@@ -1081,6 +1116,7 @@ mod tests {
|
||||
let b_secret_key = SecretKey::generate(&mut rng);
|
||||
let b_key = b_secret_key.public();
|
||||
let _client_b = ClientBuilder::new(relay_url.clone(), b_secret_key, resolver.clone())
|
||||
.tls_client_config(client_config)
|
||||
.connect()
|
||||
.await?;
|
||||
|
||||
|
||||
@@ -163,6 +163,10 @@ impl ServerHandle {
|
||||
/// use webpki_types::{CertificateDer, PrivateKeyDer};
|
||||
///
|
||||
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
/// // Set ring as the process-level default crypto provider
|
||||
/// rustls::crypto::ring::default_provider()
|
||||
/// .install_default()
|
||||
/// .ok();
|
||||
/// // Generate a self-signed certificate for testing
|
||||
/// let cert = rcgen::generate_simple_self_signed(vec!["localhost".to_string()])?;
|
||||
/// let cert_der = cert.cert.der().to_vec();
|
||||
@@ -208,6 +212,10 @@ impl TlsConfig {
|
||||
/// use webpki_types::{CertificateDer, PrivateKeyDer};
|
||||
///
|
||||
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
/// // Set ring as the process-level default crypto provider
|
||||
/// rustls::crypto::ring::default_provider()
|
||||
/// .install_default()
|
||||
/// .ok();
|
||||
/// // Generate a self-signed certificate for testing
|
||||
/// let cert = rcgen::generate_simple_self_signed(vec!["localhost".to_string()])?;
|
||||
/// let cert_der = cert.cert.der().to_vec();
|
||||
|
||||
+40
-6
@@ -123,7 +123,6 @@ impl CaRootsConfig {
|
||||
let verifier = rustls_platform_verifier::Verifier::new(crypto_provider);
|
||||
Arc::new(verifier.map_err(io::Error::other)?)
|
||||
}
|
||||
|
||||
Mode::EmbeddedWebPki => {
|
||||
let mut root_store = rustls::RootCertStore {
|
||||
roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
|
||||
@@ -141,7 +140,9 @@ impl CaRootsConfig {
|
||||
.map_err(io::Error::other)?
|
||||
}
|
||||
#[cfg(any(test, feature = "test-utils"))]
|
||||
Mode::InsecureSkipVerify => Arc::new(self::no_cert_verifier::NoCertVerifier),
|
||||
Mode::InsecureSkipVerify => {
|
||||
Arc::new(no_cert_verifier::NoCertVerifier { crypto_provider })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -158,23 +159,56 @@ impl CaRootsConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns iroh's default crypto provider.
|
||||
/// Returns the default crypto provider, if enabled via a feature flag.
|
||||
///
|
||||
/// Currently, this is [`rustls::crypto::ring`].
|
||||
/// Prefers to ring over aws-lc-rs if both are enabled.
|
||||
#[cfg(feature = "tls-ring")]
|
||||
pub fn default_provider() -> Arc<CryptoProvider> {
|
||||
Arc::new(rustls::crypto::ring::default_provider())
|
||||
}
|
||||
|
||||
/// Returns the default crypto provider, if enabled via a feature flag.
|
||||
///
|
||||
/// Prefers to ring over aws-lc-rs if both are enabled.
|
||||
#[cfg(all(feature = "tls-aws-lc-rs", not(feature = "tls-ring")))]
|
||||
pub fn default_provider() -> Arc<CryptoProvider> {
|
||||
Arc::new(rustls::crypto::aws_lc_rs::default_provider())
|
||||
}
|
||||
|
||||
#[cfg(all(any(test, feature = "test-utils"), with_crypto_provider))]
|
||||
/// Creates a client config that trusts any servers without verifying their TLS certificate.
|
||||
///
|
||||
/// Should be used for testing local relay setups only.
|
||||
pub fn make_dangerous_client_config() -> rustls::ClientConfig {
|
||||
tracing::warn!(
|
||||
"Insecure config: SSL certificates from relay servers will be trusted without verification"
|
||||
);
|
||||
let crypto_provider = crate::tls::default_provider();
|
||||
rustls::client::ClientConfig::builder_with_provider(crypto_provider.clone())
|
||||
.with_protocol_versions(&[&rustls::version::TLS13])
|
||||
.expect("protocols supported by ring")
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(Arc::new(no_cert_verifier::NoCertVerifier {
|
||||
crypto_provider,
|
||||
}))
|
||||
.with_no_client_auth()
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-utils"))]
|
||||
mod no_cert_verifier {
|
||||
use std::sync::Arc;
|
||||
|
||||
use rustls::{
|
||||
client::danger::{ServerCertVerified, ServerCertVerifier},
|
||||
crypto::CryptoProvider,
|
||||
pki_types::{CertificateDer, ServerName},
|
||||
};
|
||||
|
||||
/// Used to allow self signed certificates in tests
|
||||
#[derive(Debug)]
|
||||
pub(super) struct NoCertVerifier;
|
||||
pub(super) struct NoCertVerifier {
|
||||
pub(super) crypto_provider: Arc<CryptoProvider>,
|
||||
}
|
||||
|
||||
impl ServerCertVerifier for NoCertVerifier {
|
||||
fn verify_server_cert(
|
||||
@@ -206,7 +240,7 @@ mod no_cert_verifier {
|
||||
}
|
||||
|
||||
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
|
||||
super::default_provider()
|
||||
self.crypto_provider
|
||||
.signature_verification_algorithms
|
||||
.supported_schemes()
|
||||
}
|
||||
|
||||
+15
-12
@@ -22,7 +22,9 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
backon = { version = "1.4" }
|
||||
blake3 = { version = "1.8.3", default-features = false }
|
||||
bytes = "1.11"
|
||||
ctutils = { version = "0.4.0", default-features = false }
|
||||
data-encoding = "2.2"
|
||||
derive_more = { version = "2.0.1", features = ["debug", "display", "from", "try_into", "deref", "from_str", "into_iterator"] }
|
||||
ed25519-dalek = { version = "3.0.0-pre.1", features = ["serde", "rand_core", "zeroize", "pkcs8", "pem"] }
|
||||
@@ -38,16 +40,13 @@ papaya = { version = "0.2.3", default-features = false }
|
||||
pin-project = "1"
|
||||
portable-atomic = "1"
|
||||
pkarr = { version = "5", default-features = false }
|
||||
noq = { version = "0.17.0", default-features = false, features = ["rustls-ring"] }
|
||||
noq-proto = "0.16"
|
||||
noq-udp = "0.9"
|
||||
noq = { version = "0.17.0", default-features = false, features = ["rustls"] }
|
||||
noq-proto = { version = "0.16", default-features = false }
|
||||
noq-udp = { version = "0.9", default-features = false }
|
||||
rand = "0.9.2"
|
||||
reqwest = { version = "0.12", default-features = false, features = [
|
||||
"rustls-tls",
|
||||
"stream",
|
||||
] }
|
||||
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "stream"] }
|
||||
rustc-hash = "2"
|
||||
rustls = { version = "0.23.33", default-features = false, features = ["ring"] }
|
||||
rustls = { version = "0.23.33", default-features = false }
|
||||
serde = { version = "1.0.219", features = ["derive", "rc"] }
|
||||
smallvec = "1.11.1"
|
||||
strum = { version = "0.28", features = ["derive"] }
|
||||
@@ -61,7 +60,7 @@ tokio-stream = { version = "0.1.15", features = ["sync"] }
|
||||
tokio-util = { version = "0.7", features = ["io-util", "io", "rt"] }
|
||||
tracing = "0.1"
|
||||
url = { version = "2.5", features = ["serde"] }
|
||||
webpki = { package = "rustls-webpki", version = "0.103.7", features = ["ring"] }
|
||||
webpki = { package = "rustls-webpki", version = "0.103.7", default-features = false, features = ["std"] }
|
||||
webpki_types = { package = "rustls-pki-types", version = "1.12" }
|
||||
webpki-roots = "1.0.3"
|
||||
pkcs8 = "0.11.0-rc.9"
|
||||
@@ -79,9 +78,9 @@ sync_wrapper = { version = "1.0.2", features = ["futures"] }
|
||||
|
||||
# non-wasm-in-browser dependencies
|
||||
[target.'cfg(not(all(target_family = "wasm", target_os = "unknown")))'.dependencies]
|
||||
hickory-resolver = "0.25.1"
|
||||
hickory-resolver = { version = "0.25.1", default-features = false }
|
||||
portmapper = { version = "0.15", optional = true, default-features = false }
|
||||
noq = { version = "0.17.0", default-features = false, features = ["runtime-tokio", "rustls-ring"] }
|
||||
noq = { version = "0.17.0", default-features = false, features = ["runtime-tokio", "rustls"] }
|
||||
tokio = { version = "1", features = [
|
||||
"io-util",
|
||||
"macros",
|
||||
@@ -143,7 +142,7 @@ wasm-bindgen-test = "0.3.62"
|
||||
cfg_aliases = { version = "0.2.1" }
|
||||
|
||||
[features]
|
||||
default = ["metrics", "fast-apple-datapath", "portmapper"]
|
||||
default = ["metrics", "fast-apple-datapath", "portmapper", "tls-ring"]
|
||||
portmapper = ["dep:portmapper"]
|
||||
metrics = ["iroh-metrics/metrics", "iroh-relay/metrics", "portmapper?/metrics"]
|
||||
test-utils = ["iroh-relay/test-utils", "iroh-relay/server", "dep:axum"]
|
||||
@@ -154,6 +153,10 @@ platform-verifier = ["iroh-relay/platform-verifier"]
|
||||
qlog = ["noq/qlog"]
|
||||
# Use private Apple APIs to send multiple packets in a single syscall.
|
||||
fast-apple-datapath = ["noq/fast-apple-datapath"]
|
||||
# Use ring as the crypto backend.
|
||||
tls-ring = ["noq/ring", "iroh-relay/tls-ring", "webpki/ring"]
|
||||
# Use aws-lc-rs as the crypto backend, unless `ring` is also enabled.
|
||||
tls-aws-lc-rs = ["noq/aws-lc-rs", "iroh-relay/tls-aws-lc-rs", "webpki/aws-lc-rs"]
|
||||
# Unstable: Custom transport API (may change without notice)
|
||||
unstable-custom-transports = []
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ n0-error = "0.1"
|
||||
noq = "0.17.0"
|
||||
rand = "0.9.2"
|
||||
rcgen = "0.14"
|
||||
rustls = { version = "0.23.33", default-features = false, features = ["ring"] }
|
||||
rustls = { version = "0.23.33", default-features = false }
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
tokio = { version = "1", features = ["rt", "sync"] }
|
||||
tracing = "0.1"
|
||||
@@ -28,9 +28,11 @@ tracing-subscriber = { version = "0.3.0", default-features = false, features = [
|
||||
] }
|
||||
|
||||
[features]
|
||||
default = ["metrics", "fast-apple-datapath"]
|
||||
default = ["metrics", "fast-apple-datapath", "tls-ring"]
|
||||
metrics = ["iroh/metrics", "iroh-metrics"]
|
||||
local-relay = ["iroh/test-utils"]
|
||||
# Use private Apple APIs to send multiple packets in a single syscall.
|
||||
fast-apple-datapath = ["iroh/fast-apple-datapath", "noq/fast-apple-datapath"]
|
||||
qlog = ["iroh/qlog", "noq/qlog"]
|
||||
tls-ring = ["rustls/ring", "iroh/tls-ring"]
|
||||
tls-aws-lc-rs = ["rustls/aws-lc-rs", "iroh/tls-aws-lc-rs"]
|
||||
|
||||
@@ -29,8 +29,12 @@ pub fn server_endpoint(
|
||||
.clone()
|
||||
.map_or(RelayMode::Disabled, |url| RelayMode::Custom(url.into()));
|
||||
|
||||
#[cfg(any(feature = "tls-ring", feature = "tls-aws-lc-rs"))]
|
||||
#[allow(unused_mut)]
|
||||
let mut builder = Endpoint::builder(presets::N0);
|
||||
#[cfg(not(any(feature = "tls-ring", feature = "tls-aws-lc-rs")))]
|
||||
#[allow(unused_mut)]
|
||||
let mut builder = Endpoint::builder(presets::Empty); // allow building, but fail at runtime
|
||||
#[cfg(feature = "local-relay")]
|
||||
{
|
||||
if relay_url.is_some() {
|
||||
@@ -90,8 +94,12 @@ pub async fn connect_client(
|
||||
let relay_mode = relay_url
|
||||
.clone()
|
||||
.map_or(RelayMode::Disabled, |url| RelayMode::Custom(url.into()));
|
||||
#[cfg(any(feature = "tls-ring", feature = "tls-aws-lc-rs"))]
|
||||
#[allow(unused_mut)]
|
||||
let mut builder = Endpoint::builder(presets::N0);
|
||||
#[cfg(not(any(feature = "tls-ring", feature = "tls-aws-lc-rs")))]
|
||||
#[allow(unused_mut)]
|
||||
let mut builder = Endpoint::builder(presets::Empty); // allow building, but fail at runtime
|
||||
#[cfg(feature = "local-relay")]
|
||||
{
|
||||
if relay_url.is_some() {
|
||||
|
||||
@@ -5,5 +5,6 @@ fn main() {
|
||||
cfg_aliases! {
|
||||
// Convenience aliases
|
||||
wasm_browser: { all(target_family = "wasm", target_os = "unknown") },
|
||||
with_crypto_provider: { any(feature = "tls-ring", feature = "tls-aws-lc-rs") }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ use std::{sync::Arc, time::Duration};
|
||||
|
||||
use iroh::{
|
||||
Endpoint, Watcher,
|
||||
endpoint::{AfterHandshakeOutcome, ConnectionInfo, EndpointHooks},
|
||||
endpoint::{AfterHandshakeOutcome, ConnectionInfo, EndpointHooks, presets},
|
||||
};
|
||||
use n0_error::{Result, StackResultExt, StdResultExt, ensure_any};
|
||||
use n0_future::task::AbortOnDropHandle;
|
||||
@@ -23,7 +23,7 @@ async fn main() -> Result {
|
||||
.init();
|
||||
|
||||
let monitor = Monitor::new();
|
||||
let server = Endpoint::empty_builder()
|
||||
let server = Endpoint::builder(presets::Minimal)
|
||||
.alpns(vec![ALPN.to_vec()])
|
||||
.hooks(monitor.clone())
|
||||
.bind()
|
||||
@@ -35,7 +35,7 @@ async fn main() -> Result {
|
||||
|
||||
let client_task = tokio::spawn(
|
||||
async move {
|
||||
let client = Endpoint::empty_builder()
|
||||
let client = Endpoint::builder(presets::Minimal)
|
||||
.bind()
|
||||
.instrument(info_span!("client"))
|
||||
.await?;
|
||||
|
||||
@@ -51,7 +51,7 @@ use iroh::{
|
||||
dns::{DnsResolver, N0_DNS_ENDPOINT_ORIGIN_PROD, N0_DNS_ENDPOINT_ORIGIN_STAGING},
|
||||
endpoint::{
|
||||
BindOpts, Connection, ConnectionError, PathId, PathWatcher, RecvStream, SendStream, VarInt,
|
||||
WriteError,
|
||||
WriteError, presets,
|
||||
},
|
||||
};
|
||||
use n0_error::{Result, StackResultExt, StdResultExt, anyerr, ensure_any};
|
||||
@@ -457,7 +457,7 @@ impl EndpointArgs {
|
||||
output: Output,
|
||||
log: Option<&LogSettings>,
|
||||
) -> Result<Endpoint> {
|
||||
let mut builder = Endpoint::empty_builder();
|
||||
let mut builder = Endpoint::builder(presets::Minimal);
|
||||
if self.no_relay {
|
||||
// nothing to do
|
||||
} else if !self.relay_url.is_empty() {
|
||||
|
||||
+30
-20
@@ -69,14 +69,16 @@
|
||||
//! [`PkarrPublisher`] and [`address_lookup::DnsAddressLookup`]:
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # #[cfg(with_crypto_provider)]
|
||||
//! # {
|
||||
//! use iroh::{
|
||||
//! Endpoint, SecretKey,
|
||||
//! address_lookup::{self, AddrFilter, PkarrPublisher},
|
||||
//! endpoint::RelayMode,
|
||||
//! endpoint::{RelayMode, presets},
|
||||
//! };
|
||||
//!
|
||||
//! # async fn wrapper() -> n0_error::Result<()> {
|
||||
//! let ep = Endpoint::empty_builder()
|
||||
//! let ep = Endpoint::builder(presets::Minimal)
|
||||
//! .addr_filter(AddrFilter::relay_only())
|
||||
//! .address_lookup(PkarrPublisher::n0_dns())
|
||||
//! .address_lookup(address_lookup::DnsAddressLookup::n0_dns())
|
||||
@@ -84,6 +86,7 @@
|
||||
//! .await?;
|
||||
//! # Ok(())
|
||||
//! # }
|
||||
//! # }
|
||||
//! ```
|
||||
//!
|
||||
//! To also enable [`address_lookup::MdnsAddressLookup`] it can be added as another service.
|
||||
@@ -93,12 +96,12 @@
|
||||
//! # {
|
||||
//! # use iroh::{
|
||||
//! # address_lookup::{self, AddrFilter, PkarrPublisher},
|
||||
//! # endpoint::RelayMode,
|
||||
//! # endpoint::{presets, RelayMode},
|
||||
//! # Endpoint, SecretKey,
|
||||
//! # };
|
||||
//! #
|
||||
//! # async fn wrapper() -> n0_error::Result<()> {
|
||||
//! let ep = Endpoint::empty_builder()
|
||||
//! let ep = Endpoint::builder(presets::Minimal)
|
||||
//! .relay_mode(RelayMode::Default)
|
||||
//! .addr_filter(AddrFilter::relay_only())
|
||||
//! .address_lookup(PkarrPublisher::n0_dns())
|
||||
@@ -579,7 +582,7 @@ impl AddressLookup for ConcurrentAddressLookup {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, with_crypto_provider))]
|
||||
mod tests {
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
@@ -598,7 +601,7 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
Endpoint,
|
||||
endpoint::{ConnectOptions, IdleTimeout, QuicTransportConfig},
|
||||
endpoint::{ConnectOptions, IdleTimeout, QuicTransportConfig, presets},
|
||||
};
|
||||
|
||||
type InfoStore = HashMap<EndpointId, (EndpointData, u64)>;
|
||||
@@ -922,7 +925,7 @@ mod tests {
|
||||
) -> (Endpoint, AbortOnDropHandle<Result<()>>) {
|
||||
let secret = SecretKey::generate(rng);
|
||||
|
||||
let ep = Endpoint::empty_builder()
|
||||
let ep = Endpoint::builder(presets::Minimal)
|
||||
.secret_key(secret)
|
||||
.alpns(vec![TEST_ALPN.to_vec()])
|
||||
.bind()
|
||||
@@ -965,24 +968,19 @@ mod tests {
|
||||
mod test_dns_pkarr {
|
||||
use iroh_base::{EndpointAddr, SecretKey, TransportAddr};
|
||||
use iroh_relay::{
|
||||
RelayMap,
|
||||
endpoint_info::UserData,
|
||||
tls::{CaRootsConfig, default_provider},
|
||||
};
|
||||
use n0_error::{AnyError, Result, StackResultExt};
|
||||
use n0_error::{Result, StackResultExt};
|
||||
use n0_future::time::Duration;
|
||||
use n0_tracing_test::traced_test;
|
||||
use rand::{CryptoRng, SeedableRng};
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
use rand::SeedableRng;
|
||||
|
||||
use crate::{
|
||||
Endpoint, RelayMode,
|
||||
address_lookup::{EndpointData, PkarrPublisher},
|
||||
dns::DnsResolver,
|
||||
endpoint_info::EndpointInfo,
|
||||
test_utils::{
|
||||
DnsPkarrServer, dns_server::run_dns_server, pkarr_dns_state::State, run_relay_server,
|
||||
},
|
||||
test_utils::{DnsPkarrServer, dns_server::run_dns_server, pkarr_dns_state::State},
|
||||
};
|
||||
|
||||
const PUBLISH_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
@@ -1059,15 +1057,17 @@ mod test_dns_pkarr {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(with_crypto_provider)]
|
||||
const TEST_ALPN: &[u8] = b"TEST";
|
||||
|
||||
#[cfg(with_crypto_provider)]
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn pkarr_publish_dns_address_lookup() -> Result<()> {
|
||||
let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
|
||||
|
||||
let dns_pkarr_server = DnsPkarrServer::run().await.context("DnsPkarrServer run")?;
|
||||
let (relay_map, _relay_url, _relay_guard) = run_relay_server().await?;
|
||||
let (relay_map, _relay_url, _relay_guard) = crate::test_utils::run_relay_server().await?;
|
||||
|
||||
let (ep1, _guard1) =
|
||||
ep_with_address_lookup(&mut rng, &relay_map, &dns_pkarr_server).await?;
|
||||
@@ -1085,13 +1085,21 @@ mod test_dns_pkarr {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn ep_with_address_lookup<R: CryptoRng + ?Sized>(
|
||||
#[cfg(with_crypto_provider)]
|
||||
async fn ep_with_address_lookup<R: rand::CryptoRng + ?Sized>(
|
||||
rng: &mut R,
|
||||
relay_map: &RelayMap,
|
||||
relay_map: &iroh_relay::RelayMap,
|
||||
dns_pkarr_server: &DnsPkarrServer,
|
||||
) -> Result<(Endpoint, AbortOnDropHandle<Result<()>>)> {
|
||||
) -> Result<(
|
||||
crate::Endpoint,
|
||||
n0_future::task::AbortOnDropHandle<Result<()>>,
|
||||
)> {
|
||||
use n0_future::task::AbortOnDropHandle;
|
||||
|
||||
use crate::{Endpoint, RelayMode, endpoint::presets};
|
||||
|
||||
let secret_key = SecretKey::generate(rng);
|
||||
let ep = Endpoint::empty_builder()
|
||||
let ep = Endpoint::builder(presets::Minimal)
|
||||
.relay_mode(RelayMode::Custom(relay_map.clone()))
|
||||
.ca_roots_config(CaRootsConfig::insecure_skip_verify())
|
||||
.secret_key(secret_key.clone())
|
||||
@@ -1104,6 +1112,8 @@ mod test_dns_pkarr {
|
||||
let ep = ep.clone();
|
||||
async move {
|
||||
// we skip accept() errors, they can be caused by retransmits
|
||||
|
||||
use n0_error::AnyError;
|
||||
while let Some(accepting) = ep.accept().await.and_then(|inc| inc.accept().ok()) {
|
||||
let _conn = accepting.await.context("accepting")?;
|
||||
// Just accept incoming connections, but don't do anything with them.
|
||||
|
||||
@@ -14,14 +14,14 @@
|
||||
//! use iroh::{
|
||||
//! RelayMode, SecretKey,
|
||||
//! address_lookup::{DiscoveryEvent, MdnsAddressLookup},
|
||||
//! endpoint::{Endpoint, Source},
|
||||
//! endpoint::{Endpoint, Source, presets},
|
||||
//! };
|
||||
//! use n0_future::StreamExt;
|
||||
//!
|
||||
//! #[tokio::main]
|
||||
//! async fn main() {
|
||||
//! let recent = Duration::from_secs(600); // 10 minutes in seconds
|
||||
//! let endpoint = Endpoint::empty_builder().bind().await.unwrap();
|
||||
//! let endpoint = Endpoint::bind(presets::Minimal).await.unwrap();
|
||||
//!
|
||||
//! // Register the Address Lookupwith the endpoint
|
||||
//! let mdns = MdnsAddressLookup::builder().build(endpoint.id()).unwrap();
|
||||
|
||||
@@ -33,10 +33,11 @@ use super::{AddressLookup, EndpointData, EndpointInfo, Error, Item};
|
||||
///
|
||||
/// This is where the [`MemoryLookup`] is useful: it allows applications to add and
|
||||
/// retract endpoint addressing information that is otherwise out-of-band to iroh.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// ```no_run
|
||||
/// # #[cfg(with_crypto_provider)] // Endpoint::bind needs a crypto provider
|
||||
/// # {
|
||||
/// use iroh::{
|
||||
/// Endpoint, EndpointAddr, TransportAddr, address_lookup::memory::MemoryLookup,
|
||||
/// endpoint::presets,
|
||||
@@ -44,7 +45,7 @@ use super::{AddressLookup, EndpointData, EndpointInfo, Error, Item};
|
||||
/// use iroh_base::SecretKey;
|
||||
///
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() -> n0_error::Result<()> {
|
||||
/// # async fn wrapper() -> n0_error::Result<()> {
|
||||
/// // Create the Address Lookup and endpoint.
|
||||
/// let address_lookup = MemoryLookup::new();
|
||||
///
|
||||
@@ -65,6 +66,7 @@ use super::{AddressLookup, EndpointData, EndpointInfo, Error, Item};
|
||||
///
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// [`EndpointTicket`]: https://docs.rs/iroh-tickets/latest/iroh_tickets/endpoint/struct.EndpointTicket.html
|
||||
@@ -122,7 +124,9 @@ impl MemoryLookup {
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust
|
||||
/// ```no_run
|
||||
/// # #[cfg(with_crypto_provider)] // Endpoint::bind needs a crypto provider
|
||||
/// # {
|
||||
/// use std::{net::SocketAddr, str::FromStr};
|
||||
///
|
||||
/// use iroh::{Endpoint, EndpointAddr, address_lookup::memory::MemoryLookup, endpoint::presets};
|
||||
@@ -131,7 +135,7 @@ impl MemoryLookup {
|
||||
/// # Vec::new()
|
||||
/// # }
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() -> n0_error::Result<()> {
|
||||
/// # async fn wrapper() -> n0_error::Result<()> {
|
||||
/// // get addrs from somewhere
|
||||
/// let addrs = get_addrs();
|
||||
///
|
||||
@@ -144,6 +148,7 @@ impl MemoryLookup {
|
||||
/// .await?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn from_endpoint_info(infos: impl IntoIterator<Item = impl Into<EndpointInfo>>) -> Self {
|
||||
let res = Self::default();
|
||||
@@ -234,19 +239,19 @@ impl AddressLookup for MemoryLookup {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, with_crypto_provider))]
|
||||
mod tests {
|
||||
use iroh_base::{EndpointAddr, SecretKey, TransportAddr};
|
||||
use n0_error::{Result, StackResultExt};
|
||||
|
||||
use super::*;
|
||||
use crate::Endpoint;
|
||||
use crate::{Endpoint, endpoint::presets};
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_basic() -> Result {
|
||||
let address_lookup = MemoryLookup::new();
|
||||
|
||||
let _ep = Endpoint::empty_builder()
|
||||
let _ep = Endpoint::builder(presets::Minimal)
|
||||
.address_lookup(address_lookup.clone())
|
||||
.bind()
|
||||
.await?;
|
||||
|
||||
+111
-70
@@ -16,10 +16,7 @@ use std::{net::SocketAddr, pin::Pin, sync::Arc};
|
||||
#[cfg(not(wasm_browser))]
|
||||
use ipnet::{Ipv4Net, Ipv6Net};
|
||||
use iroh_base::{EndpointAddr, EndpointId, RelayUrl, SecretKey, TransportAddr};
|
||||
use iroh_relay::{
|
||||
RelayConfig, RelayMap,
|
||||
tls::{CaRootsConfig, default_provider},
|
||||
};
|
||||
use iroh_relay::{RelayConfig, RelayMap, tls::CaRootsConfig};
|
||||
#[cfg(not(wasm_browser))]
|
||||
use n0_error::bail;
|
||||
use n0_error::{e, ensure, stack_error};
|
||||
@@ -50,6 +47,7 @@ use crate::address_lookup::PkarrResolver;
|
||||
use crate::dns::DnsResolver;
|
||||
#[cfg(feature = "unstable-custom-transports")]
|
||||
use crate::endpoint::transports::CustomTransport;
|
||||
pub use crate::tls::TlsConfigError;
|
||||
use crate::{
|
||||
NetReport,
|
||||
address_lookup::{
|
||||
@@ -61,7 +59,7 @@ use crate::{
|
||||
socket::{
|
||||
self, EndpointInner, RemoteStateActorStoppedError, StaticConfig, mapped_addrs::MappedAddr,
|
||||
},
|
||||
tls::{self, DEFAULT_MAX_TLS_TICKETS},
|
||||
tls::{self, DEFAULT_MAX_TLS_TICKETS, misc::RustlsTokenKey},
|
||||
};
|
||||
|
||||
#[cfg(not(wasm_browser))]
|
||||
@@ -129,6 +127,7 @@ pub struct Builder {
|
||||
hooks: EndpointHooksList,
|
||||
transport_bias: socket::transports::TransportBiasMap,
|
||||
portmapper_config: PortmapperConfig,
|
||||
crypto_provider: Option<Arc<rustls::crypto::CryptoProvider>>,
|
||||
}
|
||||
|
||||
impl From<RelayMode> for Option<TransportConfig> {
|
||||
@@ -194,6 +193,7 @@ impl Builder {
|
||||
hooks: Default::default(),
|
||||
transport_bias: Default::default(),
|
||||
portmapper_config: Default::default(),
|
||||
crypto_provider: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,18 +201,33 @@ impl Builder {
|
||||
|
||||
/// Binds the endpoint.
|
||||
pub async fn bind(self) -> Result<Endpoint, BindError> {
|
||||
let mut rng = rand::rng();
|
||||
let secret_key = self
|
||||
.secret_key
|
||||
.unwrap_or_else(move || SecretKey::generate(&mut rng));
|
||||
.unwrap_or_else(|| SecretKey::generate(&mut rand::rng()));
|
||||
|
||||
let crypto_provider = self
|
||||
.crypto_provider
|
||||
.ok_or_else(|| e!(BindError::InvalidCryptoProvider))?;
|
||||
|
||||
let token_key = Arc::new(
|
||||
RustlsTokenKey::new(&mut rand::rng(), &crypto_provider)
|
||||
.ok_or_else(|| e!(BindError::InvalidCryptoProvider))?,
|
||||
);
|
||||
|
||||
let span = info_span!("endpoint", id = %secret_key.public().fmt_short());
|
||||
let _guard = span.enter();
|
||||
|
||||
let tls_config = tls::TlsConfig::new(
|
||||
secret_key.clone(),
|
||||
self.max_tls_tickets,
|
||||
crypto_provider.clone(),
|
||||
);
|
||||
let static_config = StaticConfig {
|
||||
server_config: tls_config.make_server_config(self.keylog)?,
|
||||
client_config: tls_config.make_client_config(self.keylog)?,
|
||||
tls_config,
|
||||
transport_config: self.transport_config.clone(),
|
||||
tls_config: tls::TlsConfig::new(secret_key.clone(), self.max_tls_tickets),
|
||||
keylog: self.keylog,
|
||||
token_key,
|
||||
};
|
||||
let server_config = static_config.create_server_config(self.alpn_protocols);
|
||||
|
||||
@@ -224,7 +239,7 @@ impl Builder {
|
||||
let tls_config = self
|
||||
.ca_roots_config
|
||||
.unwrap_or_default()
|
||||
.client_config(default_provider())
|
||||
.client_config(crypto_provider)
|
||||
.map_err(|err| e!(BindError::InvalidCaRootConfig, err))?;
|
||||
|
||||
let sock_opts = socket::Options {
|
||||
@@ -307,6 +322,8 @@ impl Builder {
|
||||
/// # Example
|
||||
///
|
||||
/// ```no_run
|
||||
/// # #[cfg(with_crypto_provider)]
|
||||
/// # {
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() -> n0_error::Result<()> {
|
||||
/// # use iroh::{Endpoint, endpoint::presets};
|
||||
@@ -317,6 +334,7 @@ impl Builder {
|
||||
/// .bind()
|
||||
/// .await?;
|
||||
/// # Ok(()) }
|
||||
/// # }
|
||||
/// ```
|
||||
#[cfg(not(wasm_browser))]
|
||||
pub fn bind_addr<A>(self, addr: A) -> Result<Self, InvalidSocketAddr>
|
||||
@@ -384,6 +402,8 @@ impl Builder {
|
||||
///
|
||||
/// # Example
|
||||
/// ```no_run
|
||||
/// # #[cfg(with_crypto_provider)]
|
||||
/// # {
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() -> n0_error::Result<()> {
|
||||
/// # use iroh::{Endpoint, endpoint::{BindOpts, presets}};
|
||||
@@ -394,6 +414,7 @@ impl Builder {
|
||||
/// .bind()
|
||||
/// .await?;
|
||||
/// # Ok(()) }
|
||||
/// # }
|
||||
/// ```
|
||||
#[cfg(not(wasm_browser))]
|
||||
pub fn bind_addr_with_opts<A>(
|
||||
@@ -680,6 +701,24 @@ impl Builder {
|
||||
self
|
||||
}
|
||||
|
||||
/// Specify the rustls cryptography to use for all TLS operations.
|
||||
///
|
||||
/// This includes
|
||||
/// - TLS for encryption and authentication of iroh connections themselves, but also
|
||||
/// - HTTPS connections to relays
|
||||
/// - Pkarr relay publishing HTTPS connections
|
||||
/// - and any other Address Lookup services that decide to use [`Endpoint::tls_config`].
|
||||
///
|
||||
/// The two most common crypto providers in use today are `ring` as well as `aws-lc-rs`.
|
||||
///
|
||||
/// If either the `ring` or `aws-lc-rs` feature is set in iroh, this function doesn't need to be called.
|
||||
///
|
||||
/// If none of these features are set, then calling this function in the builder is mandatory.
|
||||
pub fn crypto_provider(mut self, crypto_provider: Arc<rustls::crypto::CryptoProvider>) -> Self {
|
||||
self.crypto_provider = Some(crypto_provider);
|
||||
self
|
||||
}
|
||||
|
||||
/// Install hooks onto the endpoint.
|
||||
///
|
||||
/// Endpoint hooks intercept the connection establishment process of an [`Endpoint`].
|
||||
@@ -830,13 +869,6 @@ impl Endpoint {
|
||||
Builder::new(preset)
|
||||
}
|
||||
|
||||
/// Returns the builder for an [`Endpoint`], with an empty configuration.
|
||||
///
|
||||
/// See [`Builder::empty`] for details.
|
||||
pub fn empty_builder() -> Builder {
|
||||
Builder::empty()
|
||||
}
|
||||
|
||||
/// Constructs a default [`Endpoint`] using the provided [`Preset`] and binds it immediately.
|
||||
pub async fn bind(preset: impl Preset) -> Result<Self, BindError> {
|
||||
Self::builder(preset).bind().await
|
||||
@@ -998,18 +1030,12 @@ impl Endpoint {
|
||||
// Start connecting via noq. This will time out after 10 seconds if no reachable
|
||||
// address is available.
|
||||
|
||||
let client_config = {
|
||||
let mut alpn_protocols = vec![alpn.to_vec()];
|
||||
alpn_protocols.extend(options.additional_alpns);
|
||||
let quic_client_config = self
|
||||
.inner
|
||||
.static_config
|
||||
.tls_config
|
||||
.make_client_config(alpn_protocols, self.inner.static_config.keylog);
|
||||
let mut client_config = noq::ClientConfig::new(Arc::new(quic_client_config));
|
||||
client_config.transport_config(transport_config.clone());
|
||||
client_config
|
||||
};
|
||||
let mut alpn_protocols = vec![alpn.to_vec()];
|
||||
alpn_protocols.extend(options.additional_alpns);
|
||||
let client_config = self
|
||||
.inner
|
||||
.static_config
|
||||
.create_client_config(alpn_protocols, transport_config.clone());
|
||||
|
||||
let dest_addr = mapped_addr.private_socket_addr();
|
||||
let server_name = &tls::name::encode(endpoint_id);
|
||||
@@ -1072,6 +1098,8 @@ impl Endpoint {
|
||||
/// The observed [`EndpointAddr`] will have the current [`RelayUrl`] and direct addresses.
|
||||
///
|
||||
/// ```no_run
|
||||
/// # #[cfg(with_crypto_provider)]
|
||||
/// # {
|
||||
/// # async fn wrapper() -> n0_error::Result<()> {
|
||||
/// use iroh::{Endpoint, Watcher, endpoint::presets};
|
||||
///
|
||||
@@ -1083,6 +1111,7 @@ impl Endpoint {
|
||||
/// # let _ = endpoint_addr;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// The [`Endpoint::online`] method can be used as a convenience method to
|
||||
@@ -1106,7 +1135,9 @@ impl Endpoint {
|
||||
/// via [`Watcher::stream`] only terminates once the endpoint is fully dropped. To stop a task
|
||||
/// that loops over a watcher stream once the endpoint stops, combine with [`Self::closed`]:
|
||||
///
|
||||
/// ```
|
||||
/// ```no_run
|
||||
/// # #[cfg(with_crypto_provider)]
|
||||
/// # {
|
||||
/// # use iroh::{Watcher, Endpoint, endpoint::presets};
|
||||
/// # use n0_future::StreamExt;
|
||||
/// # use tracing::info;
|
||||
@@ -1127,6 +1158,7 @@ impl Endpoint {
|
||||
/// endpoint.close().await;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// [`RelayUrl`]: crate::RelayUrl
|
||||
@@ -1243,6 +1275,8 @@ impl Endpoint {
|
||||
///
|
||||
/// To get the first report use [`Watcher::initialized`]:
|
||||
/// ```no_run
|
||||
/// # #[cfg(with_crypto_provider)]
|
||||
/// # {
|
||||
/// use iroh::{Endpoint, Watcher as _, endpoint::presets};
|
||||
///
|
||||
/// # let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
|
||||
@@ -1250,6 +1284,7 @@ impl Endpoint {
|
||||
/// let ep = Endpoint::bind(presets::N0).await.unwrap();
|
||||
/// let _report = ep.net_report().initialized().await;
|
||||
/// # });
|
||||
/// # }
|
||||
/// ```
|
||||
#[doc(hidden)]
|
||||
pub fn net_report(&self) -> impl Watcher<Value = Option<NetReport>> + use<> {
|
||||
@@ -1552,7 +1587,9 @@ impl Endpoint {
|
||||
///
|
||||
/// To run a task and stop it once the endpoint closes, you can use
|
||||
/// [`EndpointClosed::run_until`]:
|
||||
/// ```
|
||||
/// ```no_run
|
||||
/// # #[cfg(with_crypto_provider)]
|
||||
/// # {
|
||||
/// # use iroh::endpoint::{Endpoint, presets};
|
||||
/// # async fn wrapper() -> n0_error::Result<()> {
|
||||
/// let endpoint = Endpoint::bind(presets::N0).await?;
|
||||
@@ -1561,6 +1598,7 @@ impl Endpoint {
|
||||
/// }));
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn closed(&self) -> EndpointClosed {
|
||||
EndpointClosed {
|
||||
@@ -1585,7 +1623,7 @@ impl Endpoint {
|
||||
self.inner.to_transport_addr(addr)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, with_crypto_provider))]
|
||||
pub(crate) fn inner(&self) -> Result<Arc<EndpointInner>, EndpointError> {
|
||||
if self.is_closed() {
|
||||
return Err(e!(EndpointError::Closed));
|
||||
@@ -1790,7 +1828,7 @@ fn is_cgi() -> bool {
|
||||
std::env::var_os("REQUEST_METHOD").is_some()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, with_crypto_provider))]
|
||||
mod tests {
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
@@ -1830,7 +1868,7 @@ mod tests {
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_connect_self() -> Result {
|
||||
let ep = Endpoint::empty_builder()
|
||||
let ep = Endpoint::builder(presets::Minimal)
|
||||
.alpns(vec![TEST_ALPN.to_vec()])
|
||||
.bind()
|
||||
.await
|
||||
@@ -1855,7 +1893,7 @@ mod tests {
|
||||
let qlog = QlogFileGroup::from_env("endpoint_connect_close");
|
||||
|
||||
// Wait for the endpoint to be started to make sure it's up before clients try to connect
|
||||
let ep = Endpoint::empty_builder()
|
||||
let ep = Endpoint::builder(presets::Minimal)
|
||||
.relay_mode(RelayMode::Custom(relay_map.clone()))
|
||||
.secret_key(server_secret_key)
|
||||
.transport_config(qlog.create("server")?)
|
||||
@@ -1898,7 +1936,7 @@ mod tests {
|
||||
|
||||
let client = tokio::spawn(
|
||||
async move {
|
||||
let ep = Endpoint::empty_builder()
|
||||
let ep = Endpoint::builder(presets::Minimal)
|
||||
.relay_mode(RelayMode::Custom(relay_map))
|
||||
.alpns(vec![TEST_ALPN.to_vec()])
|
||||
.ca_roots_config(CaRootsConfig::insecure_skip_verify())
|
||||
@@ -1960,7 +1998,7 @@ mod tests {
|
||||
let server_endpoint_id = server_secret_key.public();
|
||||
|
||||
// Make sure the server is bound before having clients connect to it:
|
||||
let ep = Endpoint::empty_builder()
|
||||
let ep = Endpoint::builder(presets::Minimal)
|
||||
.relay_mode(RelayMode::Custom(relay_map.clone()))
|
||||
.ca_roots_config(CaRootsConfig::insecure_skip_verify())
|
||||
.secret_key(server_secret_key)
|
||||
@@ -2025,7 +2063,7 @@ mod tests {
|
||||
let round_start = Instant::now();
|
||||
info!("[client] round {i}");
|
||||
let client_secret_key = SecretKey::generate(&mut rng);
|
||||
let ep = Endpoint::empty_builder()
|
||||
let ep = Endpoint::builder(presets::Minimal)
|
||||
.relay_mode(RelayMode::Custom(relay_map.clone()))
|
||||
.alpns(vec![TEST_ALPN.to_vec()])
|
||||
.ca_roots_config(CaRootsConfig::insecure_skip_verify())
|
||||
@@ -2079,12 +2117,12 @@ mod tests {
|
||||
#[traced_test]
|
||||
async fn endpoint_send_relay() -> Result {
|
||||
let (relay_map, _relay_url, _guard) = run_relay_server().await?;
|
||||
let client = Endpoint::empty_builder()
|
||||
let client = Endpoint::builder(presets::Minimal)
|
||||
.relay_mode(RelayMode::Custom(relay_map.clone()))
|
||||
.ca_roots_config(CaRootsConfig::insecure_skip_verify())
|
||||
.bind()
|
||||
.await?;
|
||||
let server = Endpoint::empty_builder()
|
||||
let server = Endpoint::builder(presets::Minimal)
|
||||
.relay_mode(RelayMode::Custom(relay_map))
|
||||
.ca_roots_config(CaRootsConfig::insecure_skip_verify())
|
||||
.alpns(vec![TEST_ALPN.to_vec()])
|
||||
@@ -2513,12 +2551,12 @@ mod tests {
|
||||
#[traced_test]
|
||||
async fn endpoint_relay_map_change() -> Result {
|
||||
let (relay_map, relay_url, _guard1) = run_relay_server().await?;
|
||||
let client = Endpoint::empty_builder()
|
||||
let client = Endpoint::builder(presets::Minimal)
|
||||
.relay_mode(RelayMode::Custom(relay_map.clone()))
|
||||
.ca_roots_config(CaRootsConfig::insecure_skip_verify())
|
||||
.bind()
|
||||
.await?;
|
||||
let server = Endpoint::empty_builder()
|
||||
let server = Endpoint::builder(presets::Minimal)
|
||||
.relay_mode(RelayMode::Custom(relay_map))
|
||||
.ca_roots_config(CaRootsConfig::insecure_skip_verify())
|
||||
.alpns(vec![TEST_ALPN.to_vec()])
|
||||
@@ -2624,13 +2662,13 @@ mod tests {
|
||||
#[traced_test]
|
||||
async fn endpoint_bidi_send_recv() -> Result {
|
||||
let disco = MemoryLookup::new();
|
||||
let ep1 = Endpoint::empty_builder()
|
||||
let ep1 = Endpoint::builder(presets::Minimal)
|
||||
.address_lookup(disco.clone())
|
||||
.alpns(vec![TEST_ALPN.to_vec()])
|
||||
.bind()
|
||||
.await?;
|
||||
|
||||
let ep2 = Endpoint::empty_builder()
|
||||
let ep2 = Endpoint::builder(presets::Minimal)
|
||||
.address_lookup(disco.clone())
|
||||
.alpns(vec![TEST_ALPN.to_vec()])
|
||||
.bind()
|
||||
@@ -2723,7 +2761,7 @@ mod tests {
|
||||
async fn test_direct_addresses_no_qad_relay() -> Result {
|
||||
let (relay_map, _, _guard) = run_relay_server_with(false).await.unwrap();
|
||||
|
||||
let ep = Endpoint::empty_builder()
|
||||
let ep = Endpoint::builder(presets::Minimal)
|
||||
.relay_mode(RelayMode::Custom(relay_map))
|
||||
.alpns(vec![TEST_ALPN.to_vec()])
|
||||
.ca_roots_config(CaRootsConfig::insecure_skip_verify())
|
||||
@@ -2739,8 +2777,8 @@ mod tests {
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn graceful_close() -> Result {
|
||||
let client = Endpoint::empty_builder().bind().await?;
|
||||
let server = Endpoint::empty_builder()
|
||||
let client = Endpoint::bind(presets::Minimal).await?;
|
||||
let server = Endpoint::builder(presets::Minimal)
|
||||
.alpns(vec![TEST_ALPN.to_vec()])
|
||||
.bind()
|
||||
.await?;
|
||||
@@ -2782,12 +2820,12 @@ mod tests {
|
||||
use iroh_metrics::Registry;
|
||||
|
||||
let secret_key = SecretKey::from_bytes(&[0u8; 32]);
|
||||
let client = Endpoint::empty_builder()
|
||||
let client = Endpoint::builder(presets::Minimal)
|
||||
.secret_key(secret_key)
|
||||
.bind()
|
||||
.await?;
|
||||
let secret_key = SecretKey::from_bytes(&[1u8; 32]);
|
||||
let server = Endpoint::empty_builder()
|
||||
let server = Endpoint::builder(presets::Minimal)
|
||||
.secret_key(secret_key)
|
||||
.alpns(vec![TEST_ALPN.to_vec()])
|
||||
.bind()
|
||||
@@ -2844,8 +2882,11 @@ mod tests {
|
||||
primary_connect_alpn: &[u8],
|
||||
secondary_connect_alpns: Vec<Vec<u8>>,
|
||||
) -> Result<Vec<u8>> {
|
||||
let client = Endpoint::empty_builder().bind().await?;
|
||||
let server = Endpoint::empty_builder().alpns(accept_alpns).bind().await?;
|
||||
let client = Endpoint::bind(presets::Minimal).await?;
|
||||
let server = Endpoint::builder(presets::Minimal)
|
||||
.alpns(accept_alpns)
|
||||
.bind()
|
||||
.await?;
|
||||
let server_addr = server.addr();
|
||||
let server_task = tokio::spawn({
|
||||
let server = server.clone();
|
||||
@@ -2931,7 +2972,7 @@ mod tests {
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn watch_net_report() -> Result {
|
||||
let endpoint = Endpoint::empty_builder()
|
||||
let endpoint = Endpoint::builder(presets::Minimal)
|
||||
.relay_mode(RelayMode::Staging)
|
||||
.bind()
|
||||
.await?;
|
||||
@@ -2965,7 +3006,7 @@ mod tests {
|
||||
}
|
||||
|
||||
async fn noop_server() -> Result<(Router, EndpointAddr)> {
|
||||
let endpoint = Endpoint::empty_builder().bind().await.anyerr()?;
|
||||
let endpoint = Endpoint::bind(presets::Minimal).await.anyerr()?;
|
||||
let addr = endpoint.addr();
|
||||
let router = Router::builder(endpoint).accept(NOOP_ALPN, Noop).spawn();
|
||||
Ok((router, addr))
|
||||
@@ -2986,7 +3027,7 @@ mod tests {
|
||||
.collect::<Vec<_>>();
|
||||
let ids = addrs.iter().map(|addr| addr.id).collect::<Vec<_>>();
|
||||
let address_lookup = MemoryLookup::from_endpoint_info(addrs);
|
||||
let endpoint = Endpoint::empty_builder()
|
||||
let endpoint = Endpoint::builder(presets::Minimal)
|
||||
.address_lookup(address_lookup)
|
||||
.bind()
|
||||
.await
|
||||
@@ -3014,7 +3055,7 @@ mod tests {
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_custom_relay() -> Result {
|
||||
let _ep = Endpoint::empty_builder()
|
||||
let _ep = Endpoint::builder(presets::Minimal)
|
||||
.relay_mode(RelayMode::custom([RelayUrl::from_str(
|
||||
"https://use1-1.relay.n0.iroh-canary.iroh.link.",
|
||||
)?]))
|
||||
@@ -3025,7 +3066,7 @@ mod tests {
|
||||
"https://use1-1.relay.n0.iroh.iroh.link/",
|
||||
"https://euc1-1.relay.n0.iroh.iroh.link/",
|
||||
])?;
|
||||
let _ep = Endpoint::empty_builder()
|
||||
let _ep = Endpoint::builder(presets::Minimal)
|
||||
.relay_mode(RelayMode::Custom(relays))
|
||||
.bind()
|
||||
.await?;
|
||||
@@ -3037,7 +3078,7 @@ mod tests {
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_bind_addr_clear() -> Result {
|
||||
let ep = Endpoint::empty_builder()
|
||||
let ep = Endpoint::builder(presets::Minimal)
|
||||
.clear_ip_transports()
|
||||
.bind_addr((Ipv4Addr::LOCALHOST, 0))?
|
||||
.bind()
|
||||
@@ -3056,7 +3097,7 @@ mod tests {
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_bind_addr_no_clear() -> Result {
|
||||
let ep = Endpoint::empty_builder()
|
||||
let ep = Endpoint::builder(presets::Minimal)
|
||||
.bind_addr((Ipv4Addr::LOCALHOST, 0))?
|
||||
.bind()
|
||||
.await?;
|
||||
@@ -3081,7 +3122,7 @@ mod tests {
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_bind_addr_default() -> Result {
|
||||
let ep = Endpoint::empty_builder()
|
||||
let ep = Endpoint::builder(presets::Minimal)
|
||||
.bind_addr_with_opts(
|
||||
(Ipv4Addr::LOCALHOST, 0),
|
||||
BindOpts::default().set_is_default_route(true),
|
||||
@@ -3110,7 +3151,7 @@ mod tests {
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_bind_addr_nonzero_prefix() -> Result {
|
||||
let ep = Endpoint::empty_builder()
|
||||
let ep = Endpoint::builder(presets::Minimal)
|
||||
.bind_addr_with_opts(
|
||||
(Ipv4Addr::LOCALHOST, 0),
|
||||
BindOpts::default().set_prefix_len(32),
|
||||
@@ -3146,7 +3187,7 @@ mod tests {
|
||||
let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?;
|
||||
let port = socket.local_addr()?.port();
|
||||
|
||||
let res = Endpoint::empty_builder()
|
||||
let res = Endpoint::builder(presets::Minimal)
|
||||
.clear_ip_transports()
|
||||
.bind_addr((Ipv4Addr::LOCALHOST, port))?
|
||||
.bind()
|
||||
@@ -3172,7 +3213,7 @@ mod tests {
|
||||
let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?;
|
||||
let port = socket.local_addr()?.port();
|
||||
|
||||
let ep = Endpoint::empty_builder()
|
||||
let ep = Endpoint::builder(presets::Minimal)
|
||||
.bind_addr_with_opts(
|
||||
(Ipv4Addr::LOCALHOST, port),
|
||||
BindOpts::default()
|
||||
@@ -3202,7 +3243,7 @@ mod tests {
|
||||
let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?;
|
||||
let port = socket.local_addr()?.port();
|
||||
|
||||
let ep = Endpoint::empty_builder()
|
||||
let ep = Endpoint::builder(presets::Minimal)
|
||||
.bind_addr_with_opts(
|
||||
(Ipv4Addr::LOCALHOST, port),
|
||||
BindOpts::default().set_is_required(false),
|
||||
@@ -3226,7 +3267,7 @@ mod tests {
|
||||
let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?;
|
||||
let port = socket.local_addr()?.port();
|
||||
|
||||
let res = Endpoint::empty_builder()
|
||||
let res = Endpoint::builder(presets::Minimal)
|
||||
.clear_ip_transports()
|
||||
.bind_addr_with_opts(
|
||||
(Ipv4Addr::LOCALHOST, port),
|
||||
@@ -3250,7 +3291,7 @@ mod tests {
|
||||
#[tokio::test]
|
||||
#[traced_test]
|
||||
async fn test_bind_addr_prefix_len_0_not_default() -> Result {
|
||||
let ep = Endpoint::empty_builder()
|
||||
let ep = Endpoint::builder(presets::Minimal)
|
||||
.bind_addr_with_opts(
|
||||
(Ipv4Addr::LOCALHOST, 0),
|
||||
BindOpts::default().set_is_default_route(false),
|
||||
@@ -3302,13 +3343,13 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
let client = Endpoint::empty_builder()
|
||||
let client = Endpoint::builder(presets::Minimal)
|
||||
.relay_mode(RelayMode::Custom(relay_map.clone()))
|
||||
.ca_roots_config(CaRootsConfig::insecure_skip_verify())
|
||||
.transport_config(qlog.create("client")?)
|
||||
.bind()
|
||||
.await?;
|
||||
let server = Endpoint::empty_builder()
|
||||
let server = Endpoint::builder(presets::Minimal)
|
||||
.relay_mode(RelayMode::Custom(relay_map))
|
||||
.ca_roots_config(CaRootsConfig::insecure_skip_verify())
|
||||
.transport_config(qlog.create("server")?)
|
||||
@@ -3386,7 +3427,7 @@ mod tests {
|
||||
let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64);
|
||||
let secret_key = SecretKey::generate(&mut rng);
|
||||
|
||||
let client = Endpoint::empty_builder()
|
||||
let client = Endpoint::builder(presets::Minimal)
|
||||
.relay_mode(RelayMode::Custom(relay_map.clone()))
|
||||
.ca_roots_config(CaRootsConfig::insecure_skip_verify())
|
||||
.bind()
|
||||
@@ -3396,7 +3437,7 @@ mod tests {
|
||||
info!("client {}", client.id());
|
||||
|
||||
// bind ep1 and wait until connected to relay.
|
||||
let ep1 = Endpoint::empty_builder()
|
||||
let ep1 = Endpoint::builder(presets::Minimal)
|
||||
.relay_mode(RelayMode::Custom(relay_map.clone()))
|
||||
.secret_key(secret_key.clone())
|
||||
.ca_roots_config(CaRootsConfig::insecure_skip_verify())
|
||||
@@ -3426,7 +3467,7 @@ mod tests {
|
||||
info!("client connected to ep1");
|
||||
|
||||
// now start second endpoint with same secret key
|
||||
let ep2 = Endpoint::empty_builder()
|
||||
let ep2 = Endpoint::builder(presets::Minimal)
|
||||
.relay_mode(RelayMode::Custom(relay_map))
|
||||
.secret_key(secret_key.clone())
|
||||
.ca_roots_config(CaRootsConfig::insecure_skip_verify())
|
||||
|
||||
@@ -1263,7 +1263,7 @@ impl ConnectionInfo {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, with_crypto_provider))]
|
||||
mod tests {
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -1279,14 +1279,14 @@ mod tests {
|
||||
use super::Endpoint;
|
||||
use crate::{
|
||||
RelayMode,
|
||||
endpoint::{ConnectOptions, Incoming, PathInfo, PathInfoList, ZeroRttStatus},
|
||||
endpoint::{ConnectOptions, Incoming, PathInfo, PathInfoList, ZeroRttStatus, presets},
|
||||
test_utils::run_relay_server,
|
||||
};
|
||||
|
||||
const TEST_ALPN: &[u8] = b"n0/iroh/test";
|
||||
|
||||
async fn spawn_0rtt_server(secret_key: SecretKey, log_span: tracing::Span) -> Result<Endpoint> {
|
||||
let server = Endpoint::empty_builder()
|
||||
let server = Endpoint::builder(presets::Minimal)
|
||||
.secret_key(secret_key)
|
||||
.alpns(vec![TEST_ALPN.to_vec()])
|
||||
.bind()
|
||||
@@ -1413,7 +1413,7 @@ mod tests {
|
||||
#[traced_test]
|
||||
async fn test_0rtt() -> Result {
|
||||
let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42);
|
||||
let client = Endpoint::empty_builder().bind().await?;
|
||||
let client = Endpoint::bind(presets::Minimal).await?;
|
||||
let server = spawn_0rtt_server(SecretKey::generate(&mut rng), info_span!("server")).await?;
|
||||
|
||||
connect_client_0rtt_expect_err(&client, server.addr()).await?;
|
||||
@@ -1433,7 +1433,7 @@ mod tests {
|
||||
#[traced_test]
|
||||
async fn test_0rtt_non_consecutive() -> Result {
|
||||
let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42);
|
||||
let client = Endpoint::empty_builder().bind().await?;
|
||||
let client = Endpoint::bind(presets::Minimal).await?;
|
||||
let server = spawn_0rtt_server(SecretKey::generate(&mut rng), info_span!("server")).await?;
|
||||
|
||||
connect_client_0rtt_expect_err(&client, server.addr()).await?;
|
||||
@@ -1458,7 +1458,7 @@ mod tests {
|
||||
#[traced_test]
|
||||
async fn test_0rtt_after_server_restart() -> Result {
|
||||
let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42);
|
||||
let client = Endpoint::empty_builder()
|
||||
let client = Endpoint::builder(presets::Minimal)
|
||||
.bind()
|
||||
.instrument(info_span!("client"))
|
||||
.await?;
|
||||
@@ -1497,7 +1497,7 @@ mod tests {
|
||||
const ALPN: &[u8] = b"test";
|
||||
let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
|
||||
let (relay_map, _relay_map, _guard) = run_relay_server().await?;
|
||||
let server = Endpoint::empty_builder()
|
||||
let server = Endpoint::builder(presets::Minimal)
|
||||
.relay_mode(RelayMode::Custom(relay_map.clone()))
|
||||
.secret_key(SecretKey::generate(&mut rng))
|
||||
.ca_roots_config(CaRootsConfig::insecure_skip_verify())
|
||||
@@ -1505,7 +1505,7 @@ mod tests {
|
||||
.bind()
|
||||
.await?;
|
||||
|
||||
let client = Endpoint::empty_builder()
|
||||
let client = Endpoint::builder(presets::Minimal)
|
||||
.relay_mode(RelayMode::Custom(relay_map.clone()))
|
||||
.secret_key(SecretKey::generate(&mut rng))
|
||||
.ca_roots_config(CaRootsConfig::insecure_skip_verify())
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
//! # Example
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # #[cfg(with_crypto_provider)]
|
||||
//! # {
|
||||
//! # async fn wrapper() -> n0_error::Result {
|
||||
//! use iroh::{Endpoint, RelayMode, Watcher, endpoint::presets};
|
||||
//!
|
||||
@@ -10,13 +12,10 @@
|
||||
//! # let _ = endpoint;
|
||||
//! # Ok(())
|
||||
//! # }
|
||||
//! # }
|
||||
//! ```
|
||||
|
||||
use crate::{
|
||||
RelayMode,
|
||||
address_lookup::PkarrPublisher,
|
||||
endpoint::{Builder, default_relay_mode},
|
||||
};
|
||||
use crate::endpoint::Builder;
|
||||
|
||||
/// Defines a preset
|
||||
pub trait Preset {
|
||||
@@ -24,11 +23,74 @@ pub trait Preset {
|
||||
fn apply(self, builder: Builder) -> Builder;
|
||||
}
|
||||
|
||||
/// An empty preset that doesn't set anything on the builder.
|
||||
///
|
||||
/// This doesn't set mandatory builder options, so using this in
|
||||
/// `Endpoint::bind(presets::Empty)` will always fail.
|
||||
///
|
||||
/// However, it can be useful, if you want control over all mandatory options
|
||||
/// yourself, by using `Endpoint::builder(presets::Empty)`.
|
||||
///
|
||||
/// If you prefer a minimal version that is guaranteed to work, see the
|
||||
/// [`Minimal`] preset.
|
||||
#[derive(Debug, Copy, Clone, Default)]
|
||||
pub struct Empty;
|
||||
|
||||
impl Preset for Empty {
|
||||
fn apply(self, builder: Builder) -> Builder {
|
||||
builder
|
||||
}
|
||||
}
|
||||
|
||||
/// A preset that is almost empty, besides setting mandatory options.
|
||||
///
|
||||
/// At the moment the only mandatory option to set on the endpoint builder is
|
||||
/// [`Builder::crypto_provider`]. This preset makes a choice for that based on
|
||||
/// the current set of enabled features in iroh, which is why it's only available
|
||||
/// with the "ring" or "aws-lc-rs" feature flag.
|
||||
///
|
||||
/// It uses either [ring] or [aws-lc-rs], depending on which feature is enabled
|
||||
/// on iroh (preferring ring if both are enabled).
|
||||
///
|
||||
/// [ring]: rustls::crypto::ring::default_provider
|
||||
/// [aws-lc-rs]: rustls::crypto::aws_lc_rs::default_provider
|
||||
#[cfg(with_crypto_provider)]
|
||||
#[derive(Debug, Copy, Clone, Default)]
|
||||
pub struct Minimal;
|
||||
|
||||
#[cfg(with_crypto_provider)]
|
||||
impl Preset for Minimal {
|
||||
fn apply(self, mut builder: Builder) -> Builder {
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(feature = "tls-ring")]
|
||||
{
|
||||
builder = builder.crypto_provider(Arc::new(rustls::crypto::ring::default_provider()));
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "tls-aws-lc-rs", not(feature = "tls-ring")))]
|
||||
{
|
||||
builder =
|
||||
builder.crypto_provider(Arc::new(rustls::crypto::aws_lc_rs::default_provider()));
|
||||
}
|
||||
|
||||
builder
|
||||
}
|
||||
}
|
||||
|
||||
/// Configures the endpoint to use the n0 defaults
|
||||
///
|
||||
/// Currently this consists of
|
||||
/// - the DNS Address Lookup service.
|
||||
/// - the default relay servers provided by Number 0.
|
||||
/// - setting the [`rustls::crypto::CryptoProvider`] to [ring] or [aws-lc-rs], depending
|
||||
/// on which feature is enabled in iroh (preferring ring if both are enabled).
|
||||
///
|
||||
/// Due to the last point, this preset is only available with the `ring` or
|
||||
/// `aws-lc-rs` preset installed.
|
||||
/// If you want to set your own crypto provider, we recommend copying the
|
||||
/// implementation of this preset into your own and setting the appropriate crypto
|
||||
/// provider there.
|
||||
///
|
||||
/// The default address lookup service publishes to and resolves from the
|
||||
/// n0.computer dns server `iroh.link`.
|
||||
@@ -41,13 +103,21 @@ pub trait Preset {
|
||||
/// When in tests, or when the `test-utils` feature is enabled, this will use the
|
||||
/// [`N0_DNS_PKARR_RELAY_STAGING`].
|
||||
///
|
||||
/// [ring]: rustls::crypto::ring::default_provider
|
||||
/// [aws-lc-rs]: rustls::crypto::aws_lc_rs::default_provider
|
||||
/// [`N0_DNS_PKARR_RELAY_PROD`]: crate::address_lookup::N0_DNS_PKARR_RELAY_PROD
|
||||
/// [`N0_DNS_PKARR_RELAY_STAGING`]: crate::address_lookup::N0_DNS_PKARR_RELAY_STAGING
|
||||
#[cfg(with_crypto_provider)]
|
||||
#[derive(Debug, Copy, Clone, Default)]
|
||||
pub struct N0;
|
||||
|
||||
#[cfg(with_crypto_provider)]
|
||||
impl Preset for N0 {
|
||||
fn apply(self, mut builder: Builder) -> Builder {
|
||||
use crate::{address_lookup::PkarrPublisher, endpoint::default_relay_mode};
|
||||
|
||||
builder = Minimal.apply(builder);
|
||||
|
||||
builder = builder.address_lookup(PkarrPublisher::n0_dns());
|
||||
|
||||
// Resolve using HTTPS requests to our DNS server's /pkarr path in browsers
|
||||
@@ -75,6 +145,14 @@ impl Preset for N0 {
|
||||
/// - setting `RelayMode::Disabled`
|
||||
/// - the DNS Address Lookup service, that publishes IP addresses rather than
|
||||
/// relay urls.
|
||||
/// - setting the [`rustls::crypto::CryptoProvider`] to [ring] or [aws-lc-rs], depending
|
||||
/// on which feature is enabled in iroh (preferring ring if both are enabled).
|
||||
///
|
||||
/// Due to the last point, this preset is only available with the `ring` or
|
||||
/// `aws-lc-rs` preset installed.
|
||||
/// If you want to set your own crypto provider, we recommend copying the
|
||||
/// implementation of this preset into your own and setting the appropriate crypto
|
||||
/// provider there.
|
||||
///
|
||||
/// The default address lookup service publishes to and resolves from the
|
||||
/// n0.computer dns server `iroh.link`.
|
||||
@@ -87,29 +165,19 @@ impl Preset for N0 {
|
||||
/// When in tests, or when the `test-utils` feature is enabled, this will use the
|
||||
/// [`N0_DNS_PKARR_RELAY_STAGING`].
|
||||
///
|
||||
/// [ring]: rustls::crypto::ring::default_provider
|
||||
/// [aws-lc-rs]: rustls::crypto::aws_lc_rs::default_provider
|
||||
/// [`N0_DNS_PKARR_RELAY_PROD`]: crate::address_lookup::N0_DNS_PKARR_RELAY_PROD
|
||||
/// [`N0_DNS_PKARR_RELAY_STAGING`]: crate::address_lookup::N0_DNS_PKARR_RELAY_STAGING
|
||||
#[cfg(with_crypto_provider)]
|
||||
#[derive(Debug, Copy, Clone, Default)]
|
||||
pub struct N0DisableRelay;
|
||||
|
||||
#[cfg(with_crypto_provider)]
|
||||
impl Preset for N0DisableRelay {
|
||||
fn apply(self, mut builder: Builder) -> Builder {
|
||||
builder = builder.address_lookup(PkarrPublisher::n0_dns());
|
||||
// Resolve using HTTPS requests to our DNS server's /pkarr path in browsers
|
||||
#[cfg(wasm_browser)]
|
||||
{
|
||||
use crate::address_lookup::PkarrResolver;
|
||||
fn apply(self, builder: Builder) -> Builder {
|
||||
use crate::RelayMode;
|
||||
|
||||
builder = builder.address_lookup(PkarrResolver::n0_dns());
|
||||
}
|
||||
// Resolve using DNS queries outside browsers.
|
||||
#[cfg(not(wasm_browser))]
|
||||
{
|
||||
builder = builder.address_lookup(crate::address_lookup::DnsAddressLookup::n0_dns());
|
||||
}
|
||||
|
||||
builder = builder.relay_mode(RelayMode::Disabled);
|
||||
|
||||
builder
|
||||
N0.apply(builder).relay_mode(RelayMode::Disabled)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@
|
||||
//! another endpoint:
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # #[cfg(with_crypto_provider)]
|
||||
//! # {
|
||||
//! # use iroh::{Endpoint, EndpointAddr, endpoint::presets};
|
||||
//! # use n0_error::{StackResultExt, StdResultExt};
|
||||
//! # async fn wrapper() -> n0_error::Result<()> {
|
||||
@@ -21,11 +23,14 @@
|
||||
//! .std_context("unable to write all")?;
|
||||
//! # Ok(())
|
||||
//! # }
|
||||
//! # }
|
||||
//! ```
|
||||
//!
|
||||
//! The other endpoint can accept incoming connections using the [`Endpoint`] as well:
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # #[cfg(with_crypto_provider)]
|
||||
//! # {
|
||||
//! # use iroh::{Endpoint, EndpointAddr, endpoint::presets};
|
||||
//! # use n0_error::{StackResultExt, StdResultExt};
|
||||
//! # async fn wrapper() -> n0_error::Result<()> {
|
||||
@@ -47,6 +52,7 @@
|
||||
//! .std_context("unable to read")?;
|
||||
//! # Ok(())
|
||||
//! # }
|
||||
//! # }
|
||||
//! ```
|
||||
//!
|
||||
//! Of course you can also use [bi-directional streams] or any other features from QUIC.
|
||||
@@ -170,6 +176,8 @@
|
||||
//! The central struct is the [`Endpoint`], which allows you to connect to other endpoints:
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # #[cfg(with_crypto_provider)]
|
||||
//! # {
|
||||
//! use iroh::{Endpoint, EndpointAddr, endpoint::presets};
|
||||
//! use n0_error::{Result, StackResultExt, StdResultExt};
|
||||
//!
|
||||
@@ -190,11 +198,14 @@
|
||||
//! println!("Client closed");
|
||||
//! Ok(())
|
||||
//! }
|
||||
//! # }
|
||||
//! ```
|
||||
//!
|
||||
//! Every [`Endpoint`] can also accept connections:
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # #[cfg(with_crypto_provider)]
|
||||
//! # {
|
||||
//! use iroh::{Endpoint, EndpointAddr, endpoint::presets};
|
||||
//! use n0_error::{Result, StackResultExt, StdResultExt};
|
||||
//! use n0_future::StreamExt;
|
||||
@@ -224,6 +235,7 @@
|
||||
//! ep.close().await;
|
||||
//! Ok(())
|
||||
//! }
|
||||
//! # }
|
||||
//! ```
|
||||
//!
|
||||
//! Please see the examples directory for more nuanced examples.
|
||||
|
||||
@@ -958,7 +958,7 @@ mod test_utils {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, with_crypto_provider))]
|
||||
mod tests {
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
|
||||
@@ -978,7 +978,7 @@ mod tests {
|
||||
#[traced_test]
|
||||
async fn test_basic() -> Result<()> {
|
||||
let (server, relay) = test_utils::relay().await;
|
||||
let client_config = iroh_relay::client::make_dangerous_client_config();
|
||||
let client_config = iroh_relay::tls::make_dangerous_client_config();
|
||||
let ep = noq::Endpoint::client(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0)).anyerr()?;
|
||||
let quic_addr_disc = QuicConfig {
|
||||
ep: ep.clone(),
|
||||
|
||||
@@ -878,7 +878,7 @@ async fn run_https_probe(
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, with_crypto_provider))]
|
||||
mod tests {
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
@@ -915,7 +915,7 @@ mod tests {
|
||||
async fn test_qad_probe_v4() -> Result {
|
||||
let (server, relay) = test_utils::relay().await;
|
||||
let relay = Arc::new(relay);
|
||||
let client_config = iroh_relay::client::make_dangerous_client_config();
|
||||
let client_config = iroh_relay::tls::make_dangerous_client_config();
|
||||
let ep = noq::Endpoint::client(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0)).anyerr()?;
|
||||
let client_addr = ep.local_addr().anyerr()?;
|
||||
|
||||
|
||||
+23
-12
@@ -3,13 +3,18 @@
|
||||
//! ## Example
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # #[cfg(with_crypto_provider)]
|
||||
//! # use iroh::{
|
||||
//! # endpoint::{Connection, BindError, presets},
|
||||
//! # protocol::{AcceptError, ProtocolHandler, Router},
|
||||
//! # endpoint::{BindError, presets},
|
||||
//! # protocol::Router,
|
||||
//! # Endpoint,
|
||||
//! # EndpointAddr
|
||||
//! # };
|
||||
//! # use iroh::{
|
||||
//! # endpoint::Connection,
|
||||
//! # protocol::{AcceptError, ProtocolHandler},
|
||||
//! # };
|
||||
//! #
|
||||
//! # #[cfg(with_crypto_provider)]
|
||||
//! # async fn test_compile() -> Result<(), BindError> {
|
||||
//! let endpoint = Endpoint::bind(presets::N0).await?;
|
||||
//!
|
||||
@@ -69,6 +74,8 @@ use crate::{
|
||||
/// wait for [`tokio::signal::ctrl_c()`]:
|
||||
///
|
||||
/// ```no_run
|
||||
/// # #[cfg(with_crypto_provider)]
|
||||
/// # {
|
||||
/// # use std::sync::Arc;
|
||||
/// # use n0_error::StdResultExt;
|
||||
/// # use iroh::{endpoint::{Connecting, presets}, protocol::{ProtocolHandler, Router}, Endpoint, EndpointAddr};
|
||||
@@ -85,6 +92,7 @@ use crate::{
|
||||
/// router.shutdown().await.std_context("shutdown")?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// # }
|
||||
/// ```
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Router {
|
||||
@@ -602,7 +610,7 @@ impl<P: ProtocolHandler + Clone> ProtocolHandler for AccessLimit<P> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, with_crypto_provider))]
|
||||
mod tests {
|
||||
use std::{sync::Mutex, time::Duration};
|
||||
|
||||
@@ -611,12 +619,12 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::endpoint::{
|
||||
ApplicationClose, BeforeConnectOutcome, ConnectError, ConnectWithOptsError,
|
||||
ConnectionError, EndpointHooks,
|
||||
ConnectionError, EndpointHooks, presets,
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_shutdown() -> Result {
|
||||
let endpoint = Endpoint::empty_builder().bind().await?;
|
||||
let endpoint = Endpoint::bind(presets::Minimal).await?;
|
||||
let router = Router::builder(endpoint.clone()).spawn();
|
||||
|
||||
assert!(!router.is_shutdown());
|
||||
@@ -654,14 +662,14 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn test_limiter_router() -> Result {
|
||||
// tracing_subscriber::fmt::try_init().ok();
|
||||
let e1 = Endpoint::empty_builder().bind().await?;
|
||||
let e1 = Endpoint::bind(presets::Minimal).await?;
|
||||
// deny all access
|
||||
let proto = AccessLimit::new(Echo, |_endpoint_id| false);
|
||||
let r1 = Router::builder(e1.clone()).accept(ECHO_ALPN, proto).spawn();
|
||||
|
||||
let addr1 = r1.endpoint().addr();
|
||||
dbg!(&addr1);
|
||||
let e2 = Endpoint::empty_builder().bind().await?;
|
||||
let e2 = Endpoint::bind(presets::Minimal).await?;
|
||||
|
||||
println!("connecting");
|
||||
let conn = e2.connect(addr1, ECHO_ALPN).await?;
|
||||
@@ -694,13 +702,16 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
let e1 = Endpoint::empty_builder().bind().await?;
|
||||
let e1 = Endpoint::bind(presets::Minimal).await?;
|
||||
|
||||
let r1 = Router::builder(e1.clone()).accept(ECHO_ALPN, Echo).spawn();
|
||||
|
||||
let addr1 = r1.endpoint().addr();
|
||||
dbg!(&addr1);
|
||||
let e2 = Endpoint::empty_builder().hooks(LimitHook).bind().await?;
|
||||
let e2 = Endpoint::builder(presets::Minimal)
|
||||
.hooks(LimitHook)
|
||||
.bind()
|
||||
.await?;
|
||||
|
||||
println!("connecting");
|
||||
let conn_err = e2.connect(addr1, ECHO_ALPN).await.unwrap_err();
|
||||
@@ -744,7 +755,7 @@ mod tests {
|
||||
}
|
||||
|
||||
eprintln!("creating ep1");
|
||||
let endpoint = Endpoint::empty_builder().bind().await?;
|
||||
let endpoint = Endpoint::bind(presets::Minimal).await?;
|
||||
let router = Router::builder(endpoint)
|
||||
.accept(TEST_ALPN, TestProtocol::default())
|
||||
.spawn();
|
||||
@@ -752,7 +763,7 @@ mod tests {
|
||||
let addr = router.endpoint().addr();
|
||||
|
||||
eprintln!("creating ep2");
|
||||
let endpoint2 = Endpoint::empty_builder().bind().await?;
|
||||
let endpoint2 = Endpoint::bind(presets::Minimal).await?;
|
||||
eprintln!("connecting to {addr:?}");
|
||||
let conn = endpoint2.connect(addr, TEST_ALPN).await?;
|
||||
|
||||
|
||||
+80
-28
@@ -37,7 +37,10 @@ use n0_watcher::{self, Watchable, Watcher};
|
||||
#[cfg(not(wasm_browser))]
|
||||
use netwatch::ip::LocalAddresses;
|
||||
use netwatch::netmon;
|
||||
use noq::WeakConnectionHandle;
|
||||
use noq::{
|
||||
WeakConnectionHandle,
|
||||
crypto::rustls::{QuicClientConfig, QuicServerConfig},
|
||||
};
|
||||
use rand::Rng;
|
||||
use tokio::sync::{
|
||||
Mutex as AsyncMutex,
|
||||
@@ -70,7 +73,10 @@ use crate::{
|
||||
remote_map::{MappedAddrs, PathWatchable, RemoteInfo},
|
||||
transports::TransportBiasMap,
|
||||
},
|
||||
tls,
|
||||
tls::{
|
||||
self,
|
||||
misc::{Blake3HmacKey, RustlsTokenKey},
|
||||
},
|
||||
};
|
||||
|
||||
mod metrics;
|
||||
@@ -187,11 +193,16 @@ impl Drop for EndpointInner {
|
||||
}
|
||||
|
||||
/// Configuration for a [`noq::Endpoint`] that cannot be changed at runtime.
|
||||
#[derive(Debug)]
|
||||
#[derive(derive_more::Debug)]
|
||||
pub(crate) struct StaticConfig {
|
||||
pub(crate) tls_config: tls::TlsConfig,
|
||||
#[debug("QuicServerConifg")]
|
||||
pub(crate) server_config: QuicServerConfig,
|
||||
#[debug("QuicClientConfig")]
|
||||
pub(crate) client_config: QuicClientConfig,
|
||||
#[debug("Arc<RustlsTokenKey>")]
|
||||
pub(crate) token_key: Arc<RustlsTokenKey>,
|
||||
pub(crate) transport_config: QuicTransportConfig,
|
||||
pub(crate) keylog: bool,
|
||||
}
|
||||
|
||||
impl StaticConfig {
|
||||
@@ -200,13 +211,26 @@ impl StaticConfig {
|
||||
&self,
|
||||
alpn_protocols: Vec<Vec<u8>>,
|
||||
) -> noq_proto::ServerConfig {
|
||||
let quic_server_config = self
|
||||
.tls_config
|
||||
.make_server_config(alpn_protocols, self.keylog);
|
||||
let mut inner = noq::ServerConfig::with_crypto(Arc::new(quic_server_config));
|
||||
let mut quic_server_config = self.server_config.clone();
|
||||
quic_server_config.set_alpn_protocols(alpn_protocols);
|
||||
let mut inner =
|
||||
noq::ServerConfig::new(Arc::new(quic_server_config), self.token_key.clone());
|
||||
inner.transport_config(self.transport_config.to_inner_arc());
|
||||
inner
|
||||
}
|
||||
|
||||
/// Create a [`noq_proto::ClientConfig`] with the specified ALPN protocols.
|
||||
pub(crate) fn create_client_config(
|
||||
&self,
|
||||
alpn_protocols: Vec<Vec<u8>>,
|
||||
transport_config: Arc<noq::TransportConfig>,
|
||||
) -> noq_proto::ClientConfig {
|
||||
let mut quic_client_config = self.client_config.clone();
|
||||
quic_client_config.set_alpn_protocols(alpn_protocols);
|
||||
let mut inner = noq::ClientConfig::new(Arc::new(quic_client_config));
|
||||
inner.transport_config(transport_config);
|
||||
inner
|
||||
}
|
||||
}
|
||||
|
||||
/// This coordinates the shutdown of the [`Socket`] and all its tasks.
|
||||
@@ -755,6 +779,13 @@ pub enum BindError {
|
||||
#[error(from)]
|
||||
source: crate::address_lookup::AddressLookupBuilderError,
|
||||
},
|
||||
#[error("Missing or incompatible rustls crypto provider configured")]
|
||||
InvalidCryptoProvider,
|
||||
#[error("Error constructing TLS configuration")]
|
||||
TlsConfigError {
|
||||
#[error(from)]
|
||||
source: tls::TlsConfigError,
|
||||
},
|
||||
}
|
||||
|
||||
impl EndpointInner {
|
||||
@@ -893,7 +924,8 @@ impl EndpointInner {
|
||||
span: span.clone(),
|
||||
});
|
||||
|
||||
let mut endpoint_config = noq::EndpointConfig::default();
|
||||
let mut endpoint_config =
|
||||
noq::EndpointConfig::new(Arc::new(Blake3HmacKey::new(&mut rand::rng())));
|
||||
// Setting this to false means that noq will ignore packets that have the QUIC fixed bit
|
||||
// set to 0. The fixed bit is the 3rd bit of the first byte of a packet.
|
||||
// For performance reasons and to not rewrite buffers we pass non-QUIC UDP packets straight
|
||||
@@ -1141,7 +1173,7 @@ impl EndpointInner {
|
||||
.ok();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, with_crypto_provider))]
|
||||
async fn force_network_change(&self, is_major: bool) {
|
||||
self.actor_sender
|
||||
.send(ActorMessage::ForceNetworkChange(is_major))
|
||||
@@ -1236,7 +1268,7 @@ enum ActorMessage {
|
||||
),
|
||||
#[debug("RemoteInfo(..)")]
|
||||
RemoteInfo(EndpointId, oneshot::Sender<RemoteInfo>),
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, with_crypto_provider))]
|
||||
ForceNetworkChange(bool),
|
||||
}
|
||||
|
||||
@@ -1449,7 +1481,7 @@ impl Actor {
|
||||
tx.send(watcher).ok();
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, with_crypto_provider))]
|
||||
ActorMessage::ForceNetworkChange(is_major) => {
|
||||
self.handle_network_change(is_major).await;
|
||||
}
|
||||
@@ -1724,7 +1756,7 @@ impl Display for DirectAddrType {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, with_crypto_provider))]
|
||||
mod tests {
|
||||
use std::{net::SocketAddrV4, sync::Arc, time::Duration};
|
||||
|
||||
@@ -1744,22 +1776,30 @@ mod tests {
|
||||
Endpoint, SecretKey,
|
||||
address_lookup::memory::MemoryLookup,
|
||||
dns::DnsResolver,
|
||||
endpoint::QuicTransportConfig,
|
||||
endpoint::{QuicTransportConfig, presets},
|
||||
socket::{
|
||||
EndpointInner, StaticConfig, TransportConfig,
|
||||
mapped_addrs::{EndpointIdMappedAddr, MappedAddr},
|
||||
},
|
||||
tls::{self, DEFAULT_MAX_TLS_TICKETS},
|
||||
tls::{self, DEFAULT_MAX_TLS_TICKETS, misc::RustlsTokenKey},
|
||||
};
|
||||
|
||||
const ALPN: &[u8] = b"n0/test/1";
|
||||
|
||||
fn default_options<R: CryptoRng + ?Sized>(rng: &mut R) -> Options {
|
||||
fn default_options(rng: &mut impl CryptoRng) -> Options {
|
||||
let crypto_provider = default_provider();
|
||||
let secret_key = SecretKey::generate(rng);
|
||||
let tls_config = tls::TlsConfig::new(
|
||||
secret_key.clone(),
|
||||
DEFAULT_MAX_TLS_TICKETS,
|
||||
crypto_provider.clone(),
|
||||
);
|
||||
let static_config = StaticConfig {
|
||||
tls_config: tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS),
|
||||
server_config: tls_config.make_server_config(false).unwrap(),
|
||||
client_config: tls_config.make_client_config(false).unwrap(),
|
||||
tls_config,
|
||||
token_key: Arc::new(RustlsTokenKey::new(rng, &crypto_provider).unwrap()),
|
||||
transport_config: QuicTransportConfig::default(),
|
||||
keylog: false,
|
||||
};
|
||||
let server_config = static_config.create_server_config(vec![]);
|
||||
Options {
|
||||
@@ -1772,7 +1812,7 @@ mod tests {
|
||||
dns_resolver: DnsResolver::new(),
|
||||
server_config,
|
||||
tls_config: CaRootsConfig::default()
|
||||
.client_config(default_provider())
|
||||
.client_config(crypto_provider.clone())
|
||||
.unwrap(),
|
||||
#[cfg(any(test, feature = "test-utils"))]
|
||||
address_lookup_user_data: None,
|
||||
@@ -1940,13 +1980,13 @@ mod tests {
|
||||
/// the endpoints rebind.
|
||||
async fn endpoint_pair() -> (AbortOnDropHandle<()>, Endpoint, Endpoint) {
|
||||
let address_lookup = MemoryLookup::new();
|
||||
let ep1 = Endpoint::empty_builder()
|
||||
let ep1 = Endpoint::builder(presets::Minimal)
|
||||
.alpns(vec![ALPN.to_vec()])
|
||||
.address_lookup(address_lookup.clone())
|
||||
.bind()
|
||||
.await
|
||||
.unwrap();
|
||||
let ep2 = Endpoint::empty_builder()
|
||||
let ep2 = Endpoint::builder(presets::Minimal)
|
||||
.alpns(vec![ALPN.to_vec()])
|
||||
.address_lookup(address_lookup.clone())
|
||||
.bind()
|
||||
@@ -2154,10 +2194,19 @@ mod tests {
|
||||
/// Use [`socket_connect`] to establish connections.
|
||||
#[instrument(name = "ep", skip_all, fields(me = %secret_key.public().fmt_short()))]
|
||||
async fn socket_ep(secret_key: SecretKey) -> Result<EndpointInner> {
|
||||
let crypto_provider = default_provider();
|
||||
let tls_config = tls::TlsConfig::new(
|
||||
secret_key.clone(),
|
||||
DEFAULT_MAX_TLS_TICKETS,
|
||||
crypto_provider.clone(),
|
||||
);
|
||||
let keylog = true;
|
||||
let static_config = StaticConfig {
|
||||
tls_config: tls::TlsConfig::new(secret_key.clone(), DEFAULT_MAX_TLS_TICKETS),
|
||||
server_config: tls_config.make_server_config(keylog).unwrap(),
|
||||
client_config: tls_config.make_client_config(keylog).unwrap(),
|
||||
tls_config,
|
||||
token_key: Arc::new(RustlsTokenKey::new(&mut rand::rng(), &crypto_provider).unwrap()),
|
||||
transport_config: QuicTransportConfig::default(),
|
||||
keylog: true,
|
||||
};
|
||||
let server_config = static_config.create_server_config(vec![ALPN.to_vec()]);
|
||||
|
||||
@@ -2173,7 +2222,7 @@ mod tests {
|
||||
proxy_url: None,
|
||||
server_config,
|
||||
tls_config: CaRootsConfig::default()
|
||||
.client_config(default_provider())
|
||||
.client_config(crypto_provider.clone())
|
||||
.unwrap(),
|
||||
metrics: Default::default(),
|
||||
hooks: Default::default(),
|
||||
@@ -2222,10 +2271,13 @@ mod tests {
|
||||
endpoint_id: EndpointId,
|
||||
transport_config: Arc<noq::TransportConfig>,
|
||||
) -> Result<noq::Connection> {
|
||||
let alpns = vec![ALPN.to_vec()];
|
||||
let quic_client_config =
|
||||
tls::TlsConfig::new(ep_secret_key.clone(), DEFAULT_MAX_TLS_TICKETS)
|
||||
.make_client_config(alpns, true);
|
||||
let mut quic_client_config = tls::TlsConfig::new(
|
||||
ep_secret_key.clone(),
|
||||
DEFAULT_MAX_TLS_TICKETS,
|
||||
default_provider(),
|
||||
)
|
||||
.make_client_config(true)?;
|
||||
quic_client_config.set_alpn_protocols(vec![ALPN.to_vec()]);
|
||||
let mut client_config = noq::ClientConfig::new(Arc::new(quic_client_config));
|
||||
client_config.transport_config(transport_config);
|
||||
let connect = ep
|
||||
|
||||
@@ -34,6 +34,8 @@ impl RemoteInfo {
|
||||
/// You can use this to construct an [`EndpointAddr`] for this remote:
|
||||
///
|
||||
/// ```no_run
|
||||
/// # #[cfg(with_crypto_provider)]
|
||||
/// # {
|
||||
/// # use iroh::{Endpoint, EndpointId, EndpointAddr, endpoint::presets};
|
||||
/// # #[tokio::main]
|
||||
/// # async fn main() {
|
||||
@@ -42,6 +44,7 @@ impl RemoteInfo {
|
||||
/// let info = endpoint.remote_info(remote_id).await.unwrap();
|
||||
/// let addr = EndpointAddr::from_parts(info.id(), info.into_addrs().map(|addr| addr.into_addr()));
|
||||
/// # }
|
||||
/// # }
|
||||
/// ```
|
||||
///
|
||||
/// [`EndpointAddr`]: crate::EndpointAddr
|
||||
|
||||
+41
-24
@@ -13,11 +13,14 @@ use tracing::warn;
|
||||
|
||||
use self::resolver::ResolveRawPublicKeyCert;
|
||||
|
||||
pub(crate) mod misc;
|
||||
pub(crate) mod name;
|
||||
mod resolver;
|
||||
mod verifier;
|
||||
|
||||
pub use iroh_relay::tls::{CaRootsConfig, default_provider};
|
||||
pub use iroh_relay::tls::CaRootsConfig;
|
||||
#[cfg(with_crypto_provider)]
|
||||
pub use iroh_relay::tls::default_provider;
|
||||
|
||||
/// Maximum amount of TLS tickets we will cache (by default) for 0-RTT connection
|
||||
/// establishment.
|
||||
@@ -43,10 +46,15 @@ pub(crate) struct TlsConfig {
|
||||
server_verifier: Arc<verifier::ServerCertificateVerifier>,
|
||||
client_verifier: Arc<verifier::ClientCertificateVerifier>,
|
||||
session_store: Arc<dyn rustls::client::ClientSessionStore>,
|
||||
crypto_provider: Arc<rustls::crypto::CryptoProvider>,
|
||||
}
|
||||
|
||||
impl TlsConfig {
|
||||
pub(crate) fn new(secret_key: SecretKey, max_tls_tickets: usize) -> Self {
|
||||
pub(crate) fn new(
|
||||
secret_key: SecretKey,
|
||||
max_tls_tickets: usize,
|
||||
crypto_provider: Arc<rustls::crypto::CryptoProvider>,
|
||||
) -> Self {
|
||||
Self {
|
||||
cert_resolver: Arc::new(ResolveRawPublicKeyCert::new(&secret_key)),
|
||||
server_verifier: Arc::new(verifier::ServerCertificateVerifier),
|
||||
@@ -54,6 +62,7 @@ impl TlsConfig {
|
||||
session_store: Arc::new(rustls::client::ClientSessionMemoryCache::new(
|
||||
max_tls_tickets,
|
||||
)),
|
||||
crypto_provider,
|
||||
secret_key,
|
||||
}
|
||||
}
|
||||
@@ -65,16 +74,13 @@ impl TlsConfig {
|
||||
/// debugging purposes.
|
||||
pub(crate) fn make_client_config(
|
||||
&self,
|
||||
alpn_protocols: Vec<Vec<u8>>,
|
||||
keylog: bool,
|
||||
) -> QuicClientConfig {
|
||||
let mut crypto = rustls::ClientConfig::builder_with_provider(default_provider())
|
||||
.with_protocol_versions(verifier::PROTOCOL_VERSIONS)
|
||||
.expect("version supported by ring")
|
||||
) -> Result<QuicClientConfig, TlsConfigError> {
|
||||
let mut crypto = rustls::ClientConfig::builder_with_provider(self.crypto_provider.clone())
|
||||
.with_protocol_versions(verifier::PROTOCOL_VERSIONS)?
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(self.server_verifier.clone())
|
||||
.with_client_cert_resolver(self.cert_resolver.clone());
|
||||
crypto.alpn_protocols = alpn_protocols;
|
||||
|
||||
// TODO: enable/disable 0-RTT/storing tickets
|
||||
crypto.resumption = rustls::client::Resumption::store(self.session_store.clone());
|
||||
@@ -85,9 +91,8 @@ impl TlsConfig {
|
||||
crypto.key_log = Arc::new(rustls::KeyLogFile::new());
|
||||
}
|
||||
|
||||
crypto
|
||||
.try_into()
|
||||
.expect("expected to have a TLS1.3-compatible crypto provider set (hardcoded)")
|
||||
let quic = QuicClientConfig::try_from(crypto)?;
|
||||
Ok(quic)
|
||||
}
|
||||
|
||||
/// Create a TLS server configuration.
|
||||
@@ -97,17 +102,12 @@ impl TlsConfig {
|
||||
/// debugging purposes.
|
||||
pub(crate) fn make_server_config(
|
||||
&self,
|
||||
alpn_protocols: Vec<Vec<u8>>,
|
||||
keylog: bool,
|
||||
) -> QuicServerConfig {
|
||||
let mut crypto = rustls::ServerConfig::builder_with_provider(Arc::new(
|
||||
rustls::crypto::ring::default_provider(),
|
||||
))
|
||||
.with_protocol_versions(verifier::PROTOCOL_VERSIONS)
|
||||
.expect("fixed config")
|
||||
.with_client_cert_verifier(self.client_verifier.clone())
|
||||
.with_cert_resolver(self.cert_resolver.clone());
|
||||
crypto.alpn_protocols = alpn_protocols;
|
||||
) -> Result<QuicServerConfig, TlsConfigError> {
|
||||
let mut crypto = rustls::ServerConfig::builder_with_provider(self.crypto_provider.clone())
|
||||
.with_protocol_versions(verifier::PROTOCOL_VERSIONS)?
|
||||
.with_client_cert_verifier(self.client_verifier.clone())
|
||||
.with_cert_resolver(self.cert_resolver.clone());
|
||||
if keylog {
|
||||
warn!("enabling SSLKEYLOGFILE for TLS pre-master keys");
|
||||
crypto.key_log = Arc::new(rustls::KeyLogFile::new());
|
||||
@@ -116,8 +116,25 @@ impl TlsConfig {
|
||||
// must be u32::MAX or 0 (the default). Any other value panics with QUIC
|
||||
// This is specified in RFC 9001: https://www.rfc-editor.org/rfc/rfc9001#section-4.6.1
|
||||
crypto.max_early_data_size = u32::MAX;
|
||||
crypto
|
||||
.try_into()
|
||||
.expect("expected to have a TLS1.3-compatible crypto provider set (hardcoded)")
|
||||
let quic = QuicServerConfig::try_from(crypto)?;
|
||||
Ok(quic)
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(missing_docs)]
|
||||
#[n0_error::stack_error(derive, add_meta, from_sources)]
|
||||
#[non_exhaustive]
|
||||
pub enum TlsConfigError {
|
||||
#[error(
|
||||
"The configured crypto provider is missing support for TLS13_AES_128_GCM_SHA256, which is required for QUIC initial packets."
|
||||
)]
|
||||
CryptoProviderNoInitialCipherSuite {
|
||||
#[error(std_err)]
|
||||
source: noq::crypto::rustls::NoInitialCipherSuite,
|
||||
},
|
||||
#[error("The configured crypto provider is incompatible with iroh and QUIC encryption")]
|
||||
CryptoProviderIncompatible {
|
||||
#[error(std_err)]
|
||||
source: rustls::Error,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
use ctutils::CtEq;
|
||||
use noq_proto::crypto;
|
||||
use rand::Rng;
|
||||
use rustls::crypto::cipher::{
|
||||
AeadKey, InboundOpaqueMessage, Iv, NONCE_LEN, OutboundPlainMessage, Tls13AeadAlgorithm,
|
||||
};
|
||||
|
||||
/// Implements [`crypto::HandshakeTokenKey`] using a [`Tls13AeadAlgorithm`].
|
||||
///
|
||||
/// This can be obtained from looking through available ciphers from a
|
||||
/// [`rustls::crypto::CryptoProvider`].
|
||||
pub struct RustlsTokenKey {
|
||||
key: [u8; 32],
|
||||
aead: &'static dyn Tls13AeadAlgorithm,
|
||||
}
|
||||
|
||||
impl RustlsTokenKey {
|
||||
/// Constructs [`crypto::HandshakeTokenKey`] from a [`rustls::crypto::CryptoProvider`].
|
||||
///
|
||||
/// Tries to find a suitable TLS 1.3 cipher suite from the provided crypto provider,
|
||||
/// then uses it to extract an AEAD to use as the token key encryption method.
|
||||
///
|
||||
/// Then generates a random master key to use.
|
||||
///
|
||||
/// Returns `None` when this can't find a suitable TLS cipher suite in the given crypto
|
||||
/// provider.
|
||||
pub fn new(
|
||||
rng: &mut impl rand::CryptoRng,
|
||||
crypto_provider: &rustls::crypto::CryptoProvider,
|
||||
) -> Option<Self> {
|
||||
let suite = crypto_provider
|
||||
.cipher_suites
|
||||
.iter()
|
||||
.filter_map(|suite| suite.tls13())
|
||||
.next()?;
|
||||
let aead = suite.aead_alg;
|
||||
Some(Self {
|
||||
key: rng.random(),
|
||||
aead,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl crypto::HandshakeTokenKey for RustlsTokenKey {
|
||||
fn seal(&self, token_nonce: u128, data: &mut Vec<u8>) -> Result<(), crypto::CryptoError> {
|
||||
let key = AeadKey::from(self.key);
|
||||
let nonce: [u8; NONCE_LEN] = *token_nonce
|
||||
.to_le_bytes()
|
||||
.first_chunk()
|
||||
.expect("expected u128 > 96 bit");
|
||||
let iv = Iv::from(nonce);
|
||||
let msg = OutboundPlainMessage {
|
||||
typ: rustls::ContentType::ApplicationData,
|
||||
version: rustls::ProtocolVersion::TLSv1_3,
|
||||
payload: rustls::crypto::cipher::OutboundChunks::Single(&*data),
|
||||
};
|
||||
let out = self
|
||||
.aead
|
||||
.encrypter(key, iv)
|
||||
.encrypt(msg, 0)
|
||||
.map_err(|_| crypto::CryptoError)?;
|
||||
|
||||
data.clear();
|
||||
data.extend(out.payload.as_ref());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn open<'a>(
|
||||
&self,
|
||||
token_nonce: u128,
|
||||
data: &'a mut [u8],
|
||||
) -> Result<&'a [u8], crypto::CryptoError> {
|
||||
let key = AeadKey::from(self.key);
|
||||
let nonce: [u8; NONCE_LEN] = *token_nonce
|
||||
.to_le_bytes()
|
||||
.first_chunk()
|
||||
.expect("expected u128 > 96 bit");
|
||||
let iv = Iv::from(nonce);
|
||||
|
||||
let msg = InboundOpaqueMessage::new(
|
||||
rustls::ContentType::ApplicationData,
|
||||
rustls::ProtocolVersion::TLSv1_3,
|
||||
data,
|
||||
);
|
||||
let plain = self
|
||||
.aead
|
||||
.decrypter(key, iv)
|
||||
.decrypt(msg, 0)
|
||||
.map_err(|_| crypto::CryptoError)?;
|
||||
|
||||
Ok(plain.payload)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Blake3HmacKey([u8; 32]);
|
||||
|
||||
impl Blake3HmacKey {
|
||||
pub fn new(rng: &mut impl rand::CryptoRng) -> Self {
|
||||
let mut key = [0u8; 32];
|
||||
rng.fill_bytes(&mut key);
|
||||
Self(key)
|
||||
}
|
||||
}
|
||||
|
||||
impl crypto::HmacKey for Blake3HmacKey {
|
||||
fn sign(&self, data: &[u8], signature_out: &mut [u8]) {
|
||||
signature_out.copy_from_slice(blake3::keyed_hash(&self.0, data).as_slice());
|
||||
}
|
||||
|
||||
fn signature_len(&self) -> usize {
|
||||
blake3::OUT_LEN // 32 bytes
|
||||
}
|
||||
|
||||
fn verify(&self, data: &[u8], signature: &[u8]) -> Result<(), crypto::CryptoError> {
|
||||
let reference = blake3::keyed_hash(&self.0, data);
|
||||
// to_bool is fine here, because it's the last thing we do to
|
||||
// distinguish success or failure (see to_bool documentation)
|
||||
if signature.ct_eq(reference.as_slice()).to_bool() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(crypto::CryptoError)
|
||||
}
|
||||
}
|
||||
}
|
||||
+46
-39
@@ -3,8 +3,7 @@
|
||||
//! This module handles a verification of a client/server certificate chain
|
||||
//! and signatures allegedly by the given certificates, or using raw public keys.
|
||||
|
||||
use ed25519_dalek::pkcs8::EncodePublicKey;
|
||||
use iroh_base::PublicKey;
|
||||
use iroh_base::{PublicKey, Signature};
|
||||
use rustls::{
|
||||
CertificateError, DigitallySignedStruct, DistinguishedName, SignatureScheme,
|
||||
SupportedProtocolVersion,
|
||||
@@ -13,38 +12,15 @@ use rustls::{
|
||||
pki_types::CertificateDer as Certificate,
|
||||
server::danger::{ClientCertVerified, ClientCertVerifier},
|
||||
};
|
||||
use webpki::ring as webpki_algs;
|
||||
use webpki_types::SubjectPublicKeyInfoDer;
|
||||
|
||||
/// The only TLS version we support is 1.3
|
||||
pub(super) static PROTOCOL_VERSIONS: &[&SupportedProtocolVersion] = &[&rustls::version::TLS13];
|
||||
pub(super) const PROTOCOL_VERSIONS: &[&SupportedProtocolVersion] = &[&rustls::version::TLS13];
|
||||
|
||||
static SUPPORTED_SIG_ALGS: WebPkiSupportedAlgorithms = WebPkiSupportedAlgorithms {
|
||||
all: &[
|
||||
webpki_algs::ECDSA_P256_SHA256,
|
||||
webpki_algs::ECDSA_P256_SHA384,
|
||||
webpki_algs::ECDSA_P384_SHA256,
|
||||
webpki_algs::ECDSA_P384_SHA384,
|
||||
webpki_algs::ED25519,
|
||||
],
|
||||
mapping: &[
|
||||
// Note: for TLS1.2 the curve is not fixed by SignatureScheme. For TLS1.3 it is.
|
||||
(
|
||||
SignatureScheme::ECDSA_NISTP384_SHA384,
|
||||
&[
|
||||
webpki_algs::ECDSA_P384_SHA384,
|
||||
webpki_algs::ECDSA_P256_SHA384,
|
||||
],
|
||||
),
|
||||
(
|
||||
SignatureScheme::ECDSA_NISTP256_SHA256,
|
||||
&[
|
||||
webpki_algs::ECDSA_P256_SHA256,
|
||||
webpki_algs::ECDSA_P384_SHA256,
|
||||
],
|
||||
),
|
||||
(SignatureScheme::ED25519, &[webpki_algs::ED25519]),
|
||||
],
|
||||
const ED25519_DALEK: Ed25519Dalek = Ed25519Dalek;
|
||||
const SUPPORTED_SIG_ALGS: WebPkiSupportedAlgorithms = WebPkiSupportedAlgorithms {
|
||||
all: &[&ED25519_DALEK],
|
||||
mapping: &[(SignatureScheme::ED25519, &[&ED25519_DALEK])],
|
||||
};
|
||||
|
||||
/// Implementation of the `rustls` certificate verification traits
|
||||
@@ -53,14 +29,6 @@ static SUPPORTED_SIG_ALGS: WebPkiSupportedAlgorithms = WebPkiSupportedAlgorithms
|
||||
#[derive(Default, Debug)]
|
||||
pub(super) struct ServerCertificateVerifier;
|
||||
|
||||
fn public_key_to_spki(remote_peer_id: &PublicKey) -> SubjectPublicKeyInfoDer<'static> {
|
||||
let der_key = remote_peer_id
|
||||
.as_verifying_key()
|
||||
.to_public_key_der()
|
||||
.expect("valid key");
|
||||
SubjectPublicKeyInfoDer::from(der_key.into_vec())
|
||||
}
|
||||
|
||||
impl ServerCertVerifier for ServerCertificateVerifier {
|
||||
fn verify_server_cert(
|
||||
&self,
|
||||
@@ -86,6 +54,10 @@ impl ServerCertVerifier for ServerCertificateVerifier {
|
||||
}
|
||||
|
||||
let end_entity_as_spki = SubjectPublicKeyInfoDer::from(end_entity.as_ref());
|
||||
let remote_public_spki = rustls::sign::public_key_to_spki(
|
||||
&webpki_types::alg_id::ED25519,
|
||||
remote_peer_id.as_bytes(),
|
||||
);
|
||||
|
||||
// This effectively checks that the `end_entity_as_spki` bytes have the expected
|
||||
// (constant) 12 byte prefix (consisting of the Ed25519 public key ASN.1 object
|
||||
@@ -93,7 +65,7 @@ impl ServerCertVerifier for ServerCertificateVerifier {
|
||||
// consists of the object identifier and a bit sequence, a zero byte indicating
|
||||
// that the bit sequence is padded with 0 additional bits) matches, as well as
|
||||
// the public key bytes match the `remote_peer_id` public key bytes.
|
||||
if public_key_to_spki(&remote_peer_id) != end_entity_as_spki {
|
||||
if remote_public_spki != end_entity_as_spki {
|
||||
return Err(rustls::Error::InvalidCertificate(
|
||||
CertificateError::UnknownIssuer,
|
||||
));
|
||||
@@ -162,6 +134,9 @@ impl ClientCertVerifier for ClientCertificateVerifier {
|
||||
));
|
||||
}
|
||||
|
||||
// Beyond checking for no intermediates, we don't check the client certificate.
|
||||
// The actual signatures are already verified - this ensures authentication.
|
||||
|
||||
Ok(ClientCertVerified::assertion())
|
||||
}
|
||||
|
||||
@@ -202,3 +177,35 @@ impl ClientCertVerifier for ClientCertificateVerifier {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Ed25519Dalek;
|
||||
|
||||
impl webpki_types::SignatureVerificationAlgorithm for Ed25519Dalek {
|
||||
fn verify_signature(
|
||||
&self,
|
||||
public_key: &[u8],
|
||||
message: &[u8],
|
||||
signature: &[u8],
|
||||
) -> Result<(), webpki_types::InvalidSignature> {
|
||||
let public_key =
|
||||
PublicKey::try_from(public_key).map_err(|_| webpki_types::InvalidSignature)?;
|
||||
let signature =
|
||||
Signature::try_from(signature).map_err(|_| webpki_types::InvalidSignature)?;
|
||||
public_key
|
||||
.verify(message, &signature)
|
||||
.map_err(|_| webpki_types::InvalidSignature)
|
||||
}
|
||||
|
||||
fn public_key_alg_id(&self) -> webpki_types::AlgorithmIdentifier {
|
||||
webpki_types::alg_id::ED25519
|
||||
}
|
||||
|
||||
fn signature_alg_id(&self) -> webpki_types::AlgorithmIdentifier {
|
||||
webpki_types::alg_id::ED25519
|
||||
}
|
||||
|
||||
fn fips(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user