diff --git a/kt/README.md b/kt/README.md index 5b0d6eac..693efd0f 100644 --- a/kt/README.md +++ b/kt/README.md @@ -16,6 +16,22 @@ dependencies { } ``` +## Certificate verification + +Without `serverCertificateHashes` or `noCertVerification`, clients verify servers with +the operating system's trust store through +[rustls-platform-verifier](https://github.com/rustls/rustls-platform-verifier), +including user-installed and enterprise roots where the OS allows them. + +On Android the verifier needs the application `Context`. The AAR handles this with no +app code: a manifest-merged `ContentProvider` loads the native library with +`System.loadLibrary` during app startup, and the library's `JNI_OnLoad` initializes +the verifier from the Application. The AAR also bundles the verifier's Kotlin +component and ships its R8/ProGuard keep rule. If initialization has not succeeded, +for example because the provider was removed from the merged manifest and the +library was first loaded by JNA, each new client retries it; a client built before +it succeeds trusts the bundled Mozilla roots from webpki-roots instead and keeps them. + ## Session lifetime Keep the Session object alive while using its streams. Streams do not retain the Session: releasing the final Session reference closes the connection, even if stream objects remain. A helper that returns streams must also return or retain their Session. An explicit close already underway keeps its bounded graceful close after the Session is released; awaiting closure lets it finish, but timeout or cancellation can prevent capsule delivery. @@ -77,11 +93,13 @@ kt/ gradle.properties Defaults: version, android.useAndroidX, etc. web-transport/ build.gradle.kts KMP plugin, jvm() always, androidTarget() conditional + consumer-rules.pro Android keep rule for the bundled verifier component src/ commonMain/ Public Kotlin facade (reserved for future K/N) jvmAndAndroidMain/ UniFFI-generated kotlin (populated, gitignored) jvmMain/resources/ Native libs at JNA paths (populated, gitignored) - androidMain/jniLibs/ JNI .so per ABI (populated, gitignored) + androidMain/ Startup provider that loads the library via System.loadLibrary + jniLibs/ JNI .so per ABI (populated, gitignored) jvmArtifactTest/ Opt-in packaged-artifact lifecycle smoke scripts/ check.sh, package.sh ``` diff --git a/kt/gradle.properties b/kt/gradle.properties index 205acf65..f35289b0 100644 --- a/kt/gradle.properties +++ b/kt/gradle.properties @@ -20,3 +20,8 @@ publishing.enabled=false # still builds the JVM variant. android.useAndroidX=true android.nonTransitiveRClass=true + +# Android component of rustls-platform-verifier, bundled into the AAR. The version +# must equal the rustls-platform-verifier-android pin in rs/web-transport-ffi/Cargo.toml. +rustlsPlatformVerifier.version=0.2.0 +rustlsPlatformVerifier.sha256=aa021794230fbc2f0be355999e2cf67398dd563de066a2e17001ffbd0b69101b diff --git a/kt/settings.gradle.kts b/kt/settings.gradle.kts index a57235e6..f0588467 100644 --- a/kt/settings.gradle.kts +++ b/kt/settings.gradle.kts @@ -23,6 +23,14 @@ dependencyResolutionManagement { repositories { google() mavenCentral() + // rustls-platform-verifier publishes its Android component only here; + // web-transport/build.gradle.kts bundles it into the AAR. + exclusiveContent { + forRepository { + maven("https://github.com/rustls/rustls-platform-verifier/raw/maven-archive/android-release-support/maven/") + } + filter { includeGroup("org.rustls") } + } } } diff --git a/kt/web-transport/build.gradle.kts b/kt/web-transport/build.gradle.kts index 076c765c..345838e3 100644 --- a/kt/web-transport/build.gradle.kts +++ b/kt/web-transport/build.gradle.kts @@ -7,7 +7,8 @@ // commonMain (empty today; reserved for future K/N targets) // └─ jvmAndAndroidMain Wrappers + UniFFI-generated kotlin (uses JNA) // ├─ jvmMain JVM-specific: native libs as JAR resources -// └─ androidMain Android-specific: native libs in jniLibs +// └─ androidMain Android-specific: native libs in jniLibs, and a +// startup provider that loads them via System.loadLibrary // // Native libraries are populated by `kt/scripts/package.sh`: // src/jvmMain/resources/-/ (JNA classpath layout) @@ -36,6 +37,7 @@ // the signing key) don't trip on "no configured signatory". import com.vanniktech.maven.publish.SonatypeHost +import java.security.MessageDigest import java.time.Duration import org.gradle.api.tasks.testing.logging.TestExceptionFormat import org.jetbrains.kotlin.gradle.dsl.JvmTarget @@ -61,6 +63,36 @@ if (androidEnabled) { apply(plugin = "com.android.library") } +// rustls-platform-verifier verifies on Android through a small Kotlin component +// that is not on Maven Central. Bundle its classes into the AAR so consumers need +// no extra repository. Only the classes are taken: its manifest would impose an +// app-wide network security config, which only aids best-effort revocation fetches. +val rustlsPlatformVerifierJar: FileCollection? = if (androidEnabled) { + val aar = configurations.create("rustlsPlatformVerifier") { + isCanBeConsumed = false + isTransitive = false + } + val version = providers.gradleProperty("rustlsPlatformVerifier.version").get() + dependencies.add(aar.name, "org.rustls:rustls-platform-verifier:$version@aar") + val expectedSha256 = providers.gradleProperty("rustlsPlatformVerifier.sha256").get() + val extract = tasks.register("extractRustlsPlatformVerifier") { + val aarFiles: FileCollection = aar + inputs.property("sha256", expectedSha256) + from({ zipTree(aarFiles.singleFile) }) { include("classes.jar") } + into(layout.buildDirectory.dir("rustls-platform-verifier")) + doFirst { + val digest = MessageDigest.getInstance("SHA-256").digest(aarFiles.singleFile.readBytes()) + val actual = digest.joinToString("") { "%02x".format(it) } + check(actual == expectedSha256) { + "rustls-platform-verifier AAR SHA-256 is $actual, expected $expectedSha256" + } + } + } + files(layout.buildDirectory.file("rustls-platform-verifier/classes.jar")).builtBy(extract) +} else { + null +} + kotlin { jvm() @@ -114,6 +146,7 @@ kotlin { dependsOn(jvmAndAndroidMain) dependencies { implementation("net.java.dev.jna:jna:5.15.0@aar") + implementation(rustlsPlatformVerifierJar!!) } } val androidUnitTest by getting { @@ -132,6 +165,7 @@ if (androidEnabled) { ndk { abiFilters += listOf("arm64-v8a", "armeabi-v7a", "x86_64") } + consumerProguardFiles("consumer-rules.pro") } compileOptions { sourceCompatibility = JavaVersion.VERSION_17 diff --git a/kt/web-transport/consumer-rules.pro b/kt/web-transport/consumer-rules.pro new file mode 100644 index 00000000..5abedca6 --- /dev/null +++ b/kt/web-transport/consumer-rules.pro @@ -0,0 +1,3 @@ +# rustls-platform-verifier calls its bundled Kotlin component through JNI, +# which shrinkers cannot see. +-keep, includedescriptorclasses class org.rustls.platformverifier.** { *; } diff --git a/kt/web-transport/src/androidMain/AndroidManifest.xml b/kt/web-transport/src/androidMain/AndroidManifest.xml new file mode 100644 index 00000000..9575f0b0 --- /dev/null +++ b/kt/web-transport/src/androidMain/AndroidManifest.xml @@ -0,0 +1,10 @@ + + + + + + + diff --git a/kt/web-transport/src/androidMain/kotlin/dev/moq/webtransport/NativeLibraryInitializer.kt b/kt/web-transport/src/androidMain/kotlin/dev/moq/webtransport/NativeLibraryInitializer.kt new file mode 100644 index 00000000..fc519cb9 --- /dev/null +++ b/kt/web-transport/src/androidMain/kotlin/dev/moq/webtransport/NativeLibraryInitializer.kt @@ -0,0 +1,47 @@ +package dev.moq.webtransport + +import android.content.ContentProvider +import android.content.ContentValues +import android.database.Cursor +import android.net.Uri +import android.util.Log + +/** + * Loads the native library while the app starts, after its Application exists. + * + * `System.loadLibrary` runs the library's `JNI_OnLoad`, which initializes the + * OS platform certificate verifier from the application Context. JNA, which the + * generated bindings use, loads the library without running `JNI_OnLoad`. + */ +internal class NativeLibraryInitializer : ContentProvider() { + override fun onCreate(): Boolean { + try { + System.loadLibrary("web_transport_ffi") + } catch (e: UnsatisfiedLinkError) { + // Not fatal at startup: JNA reports the load failure when the bindings are first used. + Log.w("WebTransport", "failed to load web_transport_ffi", e) + } + return true + } + + override fun query( + uri: Uri, + projection: Array?, + selection: String?, + selectionArgs: Array?, + sortOrder: String?, + ): Cursor? = null + + override fun getType(uri: Uri): String? = null + + override fun insert(uri: Uri, values: ContentValues?): Uri? = null + + override fun delete(uri: Uri, selection: String?, selectionArgs: Array?): Int = 0 + + override fun update( + uri: Uri, + values: ContentValues?, + selection: String?, + selectionArgs: Array?, + ): Int = 0 +} diff --git a/py/web-transport/README.md b/py/web-transport/README.md index 1e5e0801..e77edd14 100644 --- a/py/web-transport/README.md +++ b/py/web-transport/README.md @@ -75,6 +75,14 @@ async def main(): asyncio.run(main()) ``` +## Certificate verification + +Without `server_certificate_hashes` or `no_cert_verification`, `Client()` verifies +servers with the operating system's trust store through +[rustls-platform-verifier](https://github.com/rustls/rustls-platform-verifier): +the Security framework on macOS, CryptoAPI on Windows, and the system CA bundle on +Linux. Construction fails on Linux when no system CA certificate can be loaded. + ## Session lifetime Keep the Session object alive while using its streams. Streams do not retain the Session: releasing the final Session reference closes the connection, even if stream objects remain. A helper that returns streams must also return or retain their Session. An explicit close already underway keeps its bounded graceful close after the Session is released; awaiting closure lets it finish, but timeout or cancellation can prevent capsule delivery. diff --git a/quest/a1/README.md b/quest/a1/README.md index bfc552db..e65c688d 100644 --- a/quest/a1/README.md +++ b/quest/a1/README.md @@ -13,4 +13,3 @@ The Required list is ordered by priority. Independent children may proceed concu - [Rust crates on rind](/quest/a1/rind/README.md) - no C crypto outside Quiche - [Binding runtime coverage](/quest/a1/bindings/README.md) - independent language jobs - [Rust platform verifier](/quest/a1/platform-verifier.md) - `with_system_roots()` verifies with the OS trust store -- [FFI platform verifier](/quest/a1/ffi-platform-verifier.md) - bindings verify on iOS and Android diff --git a/quest/a1/ffi-platform-verifier.md b/quest/a1/ffi-platform-verifier.md deleted file mode 100644 index f0092742..00000000 --- a/quest/a1/ffi-platform-verifier.md +++ /dev/null @@ -1,25 +0,0 @@ -# [M] Verify FFI clients with the OS platform verifier - -## Goal - -Python, Kotlin and Swift clients that use default verification (neither certificate hashes nor disabled verification) verify servers with the OS trust store on every platform, including iOS and Android. Today `rs/web-transport-ffi/src/client.rs` loads `rustls-native-certs`, which finds no roots on iOS and likely none on Android, so those clients cannot verify any server. - -## Plan - -Follow moq-dev/moq#1968. The FFI client verifies with rustls-platform-verifier on its existing provider, and `rustls-native-certs` is dropped. On Android, add a `JNI_OnLoad` that initializes the platform verifier from the application Context (moq uses `android.app.ActivityThread.currentApplication()`), clearing any pending JNI exception so loading the library never fails. Until initialization succeeds, Android falls back to bundled webpki-roots and logs a warning. The fallback is Android-only. - -`JNI_OnLoad` alone is not enough on Android: - -- JNA can load the library without running `JNI_OnLoad`. The Kotlin Android code must guarantee initialization before the first client, for example by loading the library through `System.loadLibrary`. -- `currentApplication()` returns null if the library loads before the Application exists. Retry initialization when each client is built. A client built during the fallback keeps webpki-roots. -- rustls-platform-verifier needs its Android Kotlin component at runtime. Ship it in the Android artifact with its shrinker keep rules, and document the same setup for Rust users on Android. - -Update the Kotlin and Swift READMEs where they describe verification. Python, Kotlin and Swift share the `web-transport-ffi-v*` release. - -## Closes - -- [#506](https://github.com/moq-dev/web-transport/issues/506) - support for the platform verifier - -## Related - -- [Rust platform verifier](/quest/a1/platform-verifier.md) - the same switch in the Rust builders diff --git a/quest/a1/platform-verifier.md b/quest/a1/platform-verifier.md index d24af6f7..207f446b 100644 --- a/quest/a1/platform-verifier.md +++ b/quest/a1/platform-verifier.md @@ -8,11 +8,10 @@ Follow moq-dev/moq#1968, which made the same switch in moq-native. Replace the `rustls_native_certs` root loading in both builders with the platform verifier on the crate's existing provider (`crypto::default_provider()`), so rind stays the default provider. Drop the `rustls-native-certs` dependency from both crates. Also drop quinn's and noq's `platform-verifier` feature, which nothing uses: it only enables `ClientConfig::try_with_platform_verifier`, which bypasses this crate's provider-neutral crypto adapter. -The FFI client does not use these builders and is handled in [FFI platform verifier](/quest/a1/ffi-platform-verifier.md). Android needs JNI initialization that only that quest provides. Here, document in the builders that on Android the platform verifier requires app initialization. +The FFI client does not use these builders; it already verifies with the platform verifier and initializes it on Android from its own `JNI_OnLoad` (see `rs/web-transport-ffi/README.md`). Here, document in the builders that on Android the platform verifier requires app initialization. Coordinate with [Noq on rind](/quest/a1/rind/noq.md), which rewrites the noq client builder; whichever lands second resolves the conflict. Update the crate READMEs and doc comments that describe `with_system_roots()`. ## Related -- [Issue #506](https://github.com/moq-dev/web-transport/issues/506) - platform verifier support; closed by the FFI quest -- [FFI platform verifier](/quest/a1/ffi-platform-verifier.md) - same switch for the language bindings +- [Issue #506](https://github.com/moq-dev/web-transport/issues/506) - platform verifier support; closed by the FFI platform verifier PR diff --git a/rs/web-transport-ffi/Cargo.toml b/rs/web-transport-ffi/Cargo.toml index 0c54f870..f041ef8a 100644 --- a/rs/web-transport-ffi/Cargo.toml +++ b/rs/web-transport-ffi/Cargo.toml @@ -10,6 +10,10 @@ edition = "2021" keywords = ["webtransport", "quic", "http3", "uniffi"] categories = ["network-programming", "web-programming"] +[package.metadata.cargo-shear] +# A version pin only; see the Android dependencies below. +ignored = ["rustls-platform-verifier-android"] + [lib] name = "web_transport_ffi" crate-type = ["staticlib", "cdylib"] @@ -23,7 +27,7 @@ bytes = "1" http = "1" quinn = { version = "0.11", default-features = false, features = ["runtime-tokio"] } rustls = { version = "0.23", default-features = false, features = ["std"] } -rustls-native-certs = "0.8" +rustls-platform-verifier = "0.7" thiserror = "2" tokio = { version = "1", features = ["rt-multi-thread", "sync", "time", "macros"] } tokio-util = "0.7" @@ -31,6 +35,16 @@ uniffi = { version = "0.32", features = ["cli"] } url = "2" web-transport-quinn = { workspace = true } +[target.'cfg(target_os = "android")'.dependencies] +# The platform verifier reaches Android's trust store through JNI (see `android.rs`). +jni = "0.22" +# Pins the Kotlin component that kt/ bundles (`rustlsPlatformVerifier.version` in +# kt/gradle.properties); both must change together. +rustls-platform-verifier-android = "=0.2.0" +tracing = "0.1" +# Trusted until the platform verifier is initialized. +webpki-roots = "1" + [build-dependencies] uniffi = { version = "0.32", features = ["build"] } diff --git a/rs/web-transport-ffi/README.md b/rs/web-transport-ffi/README.md index 822b913c..663aa6c1 100644 --- a/rs/web-transport-ffi/README.md +++ b/rs/web-transport-ffi/README.md @@ -12,6 +12,30 @@ Socket setup errors are returned by `connect`. `close` and final client drop close both sockets, including pending connections. Call `close` before awaiting `wait_closed` to prevent new connections while both sockets drain. +## Certificate verification + +With neither `server_certificate_hashes` nor `no_cert_verification`, clients verify +with [rustls-platform-verifier](https://github.com/rustls/rustls-platform-verifier) +on the crate's crypto provider, so the operating system's trust store decides on +every platform. On Linux, building such a client fails when no system CA +certificate can be loaded. + +Android needs the application `Context`. The library exports `JNI_OnLoad`, which +initializes the verifier from `ActivityThread.currentApplication()` when the JVM +loads it with `System.loadLibrary`; a failure is logged and never fails the load. +Each new client retries until initialization succeeds, and a client built before +then trusts the bundled webpki-roots and keeps them. The Kotlin AAR in `kt/` +handles this. If you package the Android library yourself: + +- Load it with `System.loadLibrary("web_transport_ffi")` after the `Application` + exists and before building the first client. JNA alone does not run `JNI_OnLoad`. +- Add rustls-platform-verifier's Kotlin component, + `org.rustls:rustls-platform-verifier`, at the version of the + `rustls-platform-verifier-android` crate pinned in `Cargo.toml`, as described in + [its Android setup](https://github.com/rustls/rustls-platform-verifier#android). +- Keep it from shrinking with + `-keep, includedescriptorclasses class org.rustls.platformverifier.** { *; }`. + ## Session lifetime Keep the Session object alive while using its streams. Streams do not retain the Session: releasing the final Session reference closes the connection, even if stream objects remain. A helper that returns streams must also return or retain their Session. An explicit close already underway keeps its bounded graceful close after the Session is released; awaiting closure lets it finish, but timeout or cancellation can prevent capsule delivery. diff --git a/rs/web-transport-ffi/src/android.rs b/rs/web-transport-ffi/src/android.rs new file mode 100644 index 00000000..6d1eda35 --- /dev/null +++ b/rs/web-transport-ffi/src/android.rs @@ -0,0 +1,88 @@ +//! Android initialization of the platform certificate verifier. +//! +//! Android's trust store is reachable only through the JVM, so +//! rustls-platform-verifier needs the application `Context` before it can +//! verify. `JNI_OnLoad` initializes it when the JVM loads this library, and each +//! default-verification client retries until it succeeds. Until then, clients +//! trust the bundled Mozilla roots from webpki-roots. + +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + +use jni::sys::{self, jint, JNI_VERSION_1_6}; +use jni::{jni_sig, jni_str, Env, JavaVM}; +use rustls::client::danger::ServerCertVerifier; + +static INITIALIZED: AtomicBool = AtomicBool::new(false); + +/// Called by `System.loadLibrary`; JNA loads skip it, so the per-client retry +/// also needs the `JavaVM` registered here. +#[no_mangle] +#[allow(non_snake_case)] +pub extern "system" fn JNI_OnLoad(vm: *mut sys::JavaVM, _reserved: *mut c_void) -> jint { + // SAFETY: the JVM passes `JNI_OnLoad` a valid `JavaVM` pointer. + let vm = unsafe { JavaVM::from_raw(vm) }; + init(&vm); + JNI_VERSION_1_6 +} + +/// The verifier for default verification on Android. +pub(crate) fn verifier( + provider: Arc, +) -> Result, rustls::Error> { + let ready = + INITIALIZED.load(Ordering::Acquire) || JavaVM::singleton().is_ok_and(|vm| init(&vm)); + if ready { + return Ok(Arc::new(rustls_platform_verifier::Verifier::new(provider)?)); + } + + tracing::warn!("Android platform verifier is not initialized; trusting bundled webpki roots"); + let roots = rustls::RootCertStore { + roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(), + }; + let verifier = + rustls::client::WebPkiServerVerifier::builder_with_provider(Arc::new(roots), provider) + .build() + .map_err(|e| rustls::Error::General(e.to_string()))?; + Ok(verifier) +} + +/// Initialize the platform verifier, returning whether it is ready. +/// +/// A failure leaves no pending Java exception: `attach_current_thread` catches +/// and clears any thrown by the callback, so loading the library never fails. +fn init(vm: &JavaVM) -> bool { + if INITIALIZED.load(Ordering::Acquire) { + return true; + } + match vm.attach_current_thread(init_with_application) { + Ok(()) => { + INITIALIZED.store(true, Ordering::Release); + true + } + Err(err) => { + tracing::warn!(%err, "failed to initialize the Android platform verifier"); + false + } + } +} + +fn init_with_application(env: &mut Env) -> Result<(), jni::errors::Error> { + // Native code isn't handed the Context, so use the long-stable + // ActivityThread.currentApplication(), which is null until the Application exists. + let app = env + .call_static_method( + jni_str!("android/app/ActivityThread"), + jni_str!("currentApplication"), + jni_sig!("()Landroid/app/Application;"), + &[], + )? + .l()?; + if app.is_null() { + return Err(jni::errors::Error::NullPtr( + "ActivityThread.currentApplication()", + )); + } + rustls_platform_verifier::android::init_with_env(env, app) +} diff --git a/rs/web-transport-ffi/src/client.rs b/rs/web-transport-ffi/src/client.rs index 3e046d48..b4ae8f07 100644 --- a/rs/web-transport-ffi/src/client.rs +++ b/rs/web-transport-ffi/src/client.rs @@ -86,15 +86,11 @@ impl Client { .with_custom_certificate_verifier(fingerprints) .with_no_client_auth() } else { - let mut roots = rustls::RootCertStore::empty(); - let native = rustls_native_certs::load_native_certs(); - // Errors loading individual certs are non-fatal; we still want - // whatever the platform yielded. - for cert in native.certs { - let _ = roots.add(cert); - } + let verifier = platform_verifier(provider.clone()) + .map_err(|e| WebTransportError::invalid(format!("platform verifier: {e}")))?; tls_builder - .with_root_certificates(roots) + .dangerous() + .with_custom_certificate_verifier(verifier) .with_no_client_auth() }; @@ -196,6 +192,17 @@ fn default_crypto_provider() -> Result, WebT .map_err(|e| WebTransportError::invalid(e.to_string())) } +/// Verify with the OS trust store; Android falls back to webpki roots until initialized. +#[cfg(not(target_os = "android"))] +fn platform_verifier( + provider: Arc, +) -> Result, rustls::Error> { + Ok(Arc::new(rustls_platform_verifier::Verifier::new(provider)?)) +} + +#[cfg(target_os = "android")] +use crate::android::verifier as platform_verifier; + // --------------------------------------------------------------------------- // Certificate verifiers — preserved from web-transport-python. // --------------------------------------------------------------------------- diff --git a/rs/web-transport-ffi/src/lib.rs b/rs/web-transport-ffi/src/lib.rs index 9aac44f8..52cf48d2 100644 --- a/rs/web-transport-ffi/src/lib.rs +++ b/rs/web-transport-ffi/src/lib.rs @@ -5,6 +5,8 @@ //! take-out patterns for `finish()`/`reset()` and a single shared tokio //! runtime ([`ffi::RUNTIME`]). +#[cfg(target_os = "android")] +mod android; pub mod client; pub mod error; mod ffi; diff --git a/rs/web-transport-ffi/src/test.rs b/rs/web-transport-ffi/src/test.rs index 9fa8e9c7..3bc8771c 100644 --- a/rs/web-transport-ffi/src/test.rs +++ b/rs/web-transport-ffi/src/test.rs @@ -93,6 +93,47 @@ fn client_rejects_incompatible_args() { assert!(matches!(err, WebTransportError::InvalidArgument(_))); } +#[tokio::test] +async fn default_verification_rejects_untrusted_server() { + let cert = rcgen::generate_simple_self_signed(["127.0.0.1".to_string()]) + .expect("generate self-signed cert"); + let server = Server::new(ServerConfig { + certificate_chain: vec![cert.cert.der().to_vec()], + private_key: cert.signing_key.serialize_der(), + bind: "127.0.0.1:0".to_string(), + congestion_control: CongestionControl::Default, + max_idle_timeout_secs: Some(10.0), + keep_alive_interval_secs: None, + }) + .expect("server"); + let addr = server.local_addr(); + let server_task = tokio::spawn({ + let server = server.clone(); + async move { + let _ = server.accept().await; + } + }); + + let client = Client::new(ClientConfig::default()).expect("client"); + let err = match tokio::time::timeout( + TIMEOUT, + client.connect(format!("https://{}:{}", addr.host, addr.port)), + ) + .await + .expect("connect timeout") + { + Ok(_) => panic!("connected to a server the OS does not trust"), + Err(e) => e, + }; + assert!( + matches!(&err, WebTransportError::Connect(msg) if msg.contains("certificate")), + "{err:?}" + ); + + server.close(0, String::new()).expect("close server"); + server_task.abort(); +} + fn sha256(cert_der: &[u8]) -> Vec { use sha2::{Digest, Sha256}; let mut hasher = Sha256::new(); diff --git a/swift/README.md b/swift/README.md index d51a9673..325201e0 100644 --- a/swift/README.md +++ b/swift/README.md @@ -14,6 +14,12 @@ For now, consume the package locally by downloading the `web-transport-ffi-${VER .package(path: "/path/to/web-transport-ffi-${VERSION}-swift"), ``` +## Certificate verification + +Without `serverCertificateHashes` or `noCertVerification`, clients verify servers with +the operating system's trust store, on iOS and macOS through the Security framework, +using [rustls-platform-verifier](https://github.com/rustls/rustls-platform-verifier). + ## Session lifetime Keep the Session object alive while using its streams. Streams do not retain the Session: releasing the final Session reference closes the connection, even if stream objects remain. A helper that returns streams must also return or retain their Session. An explicit close already underway keeps its bounded graceful close after the Session is released; awaiting closure lets it finish, but timeout or cancellation can prevent capsule delivery.