diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3a0f587..f1d1358 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,6 +51,36 @@ jobs: test -n "$endpoint" VXVHAL_TEST_DATABROKER="$endpoint" cargo test --locked --test databroker + container: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@1.99.1 + with: + targets: x86_64-unknown-linux-musl + - name: Install protoc and the musl C compiler + run: sudo apt-get update && sudo apt-get install -y protobuf-compiler musl-tools + - uses: Swatinem/rust-cache@v2 + - name: Build static payload + env: + CC_x86_64_unknown_linux_musl: musl-gcc + run: cargo build --locked --release --target x86_64-unknown-linux-musl + - name: Build and smoke-test the OCI image + run: | + podman build --tag vxvhal-ci --file Containerfile . + container=$(podman run --detach --network none vxvhal-ci) + trap 'podman logs "$container"; podman rm --force "$container" >/dev/null' EXIT + for attempt in {1..20}; do + test "$(podman inspect --format '{{.State.Running}}' "$container")" = true + if podman logs "$container" 2>&1 | grep -F 'vxvhal serving' >/dev/null; then + podman stop --time 5 "$container" + test "$(podman inspect --format '{{.State.ExitCode}}' "$container")" = 0 + exit 0 + fi + sleep 0.5 + done + exit 1 + deny: runs-on: ubuntu-latest steps: diff --git a/Cargo.lock b/Cargo.lock index 2699a0e..df2c1e2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -47,7 +47,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -58,7 +58,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -145,6 +145,16 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "cc" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" +dependencies = [ + "find-msvc-tools", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -216,7 +226,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -225,6 +235,12 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + [[package]] name = "fixedbitset" version = "0.5.7" @@ -282,6 +298,17 @@ dependencies = [ "slab", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.4.3" @@ -524,7 +551,7 @@ checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "wasi", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -539,7 +566,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -733,6 +760,20 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rustix" version = "1.1.6" @@ -743,7 +784,42 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", ] [[package]] @@ -804,6 +880,12 @@ dependencies = [ "lazy_static", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + [[package]] name = "signal-hook-registry" version = "1.4.8" @@ -833,7 +915,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -842,6 +924,12 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "2.0.119" @@ -877,10 +965,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom", + "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -925,7 +1013,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -939,6 +1027,16 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + [[package]] name = "tokio-stream" version = "0.1.19" @@ -987,12 +1085,14 @@ dependencies = [ "socket2", "sync_wrapper", "tokio", + "tokio-rustls", "tokio-stream", "tokio-util", "tower", "tower-layer", "tower-service", "tracing", + "webpki-roots", ] [[package]] @@ -1150,6 +1250,12 @@ version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "utf8parse" version = "0.2.2" @@ -1196,12 +1302,30 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "webpki-roots" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5f280bbb2b287bc8e7de7e3852945a0ff50d1bbcb5ed42b6c7a568c546df171" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -1211,3 +1335,72 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" diff --git a/Cargo.toml b/Cargo.toml index 8967bd2..011087d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,11 +9,11 @@ description = "A server for Android Automotive's gRPC Vehicle HAL, backed by VSS publish = false [dependencies] -tonic = "0.14" +tonic = { version = "0.14", features = ["tls-ring", "tls-webpki-roots"] } tonic-prost = "0.14" prost = "0.14" prost-types = "0.14" -tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "time", "sync", "signal"] } +tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "time", "sync", "signal", "fs"] } tokio-stream = { version = "0.1", features = ["sync"] } clap = { version = "4", features = ["derive", "env"] } serde = { version = "1", features = ["derive"] } diff --git a/Containerfile b/Containerfile index 92757ab..f5cceb2 100644 --- a/Containerfile +++ b/Containerfile @@ -1,5 +1,5 @@ # vxvhal as a container payload: the static musl build on an empty base, with the default mapping. -# Built from a checkout: +# Built from a checkout with protoc and an x86-64 musl C compiler: # cargo build --release --target x86_64-unknown-linux-musl # podman build -t vxvhal -f Containerfile . # The databroker defaults to the same node (127.0.0.1:55555): place the vehicle's signal plane on the diff --git a/README.md b/README.md index c780131..eed42fb 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,6 @@ The default mapping (`mappings/default.yaml`) carries four properties: `PERF_VEH ## Limits -- No TLS, and no token for the databroker: it works only with a databroker that runs without authorization. - Its own gRPC port has no TLS or authentication, and listens on `0.0.0.0:9300` by default. Keep it on an isolated network, or set `--listen`. - Missing VSS paths are logged and omitted from the subscription. Reads of those properties @@ -67,6 +66,25 @@ In the AAOS guest, the Vehicle HAL must be the gRPC one, pointed at this address already is: `scripts/cuttlefish-vhal-proxy.sh` replaces Cuttlefish's host `vhal_proxy_server` with vxvhal (`docs/aaos-cuttlefish.md`). +### Connect to a TLS-enabled Databroker + +Use an HTTPS URL whose hostname or IP matches the broker certificate. For a private +CA, pass its PEM certificate. For a publicly trusted broker, the client uses the +bundled WebPKI roots when no CA file is supplied. + +```bash +cargo run --locked --release -- \ + --databroker https://broker.example.com:55555 \ + --databroker-ca /path/to/ca.pem \ + --databroker-token-file /path/to/read.token +``` + +Give the JWT read access to the mapped VSS signals. Use a file readable by the +vxvhal process and rotate it by atomically replacing it. Each new Databroker RPC +reads the current file. A running subscription uses the credentials from when it +opened and picks up the new token when it reconnects. TLS and the token apply to +the Databroker connection. See [Limits](#limits) for the AAOS-facing listener. + ## Test ``` @@ -79,6 +97,16 @@ scripts/databroker.sh stop The integration test publishes `Vehicle.Speed` to the databroker. It checks that 72 km/h reads back through `GetValues` as 20 m/s, and that a later 36 km/h arrives on the property stream as 10 m/s. +To test TLS and JWT against a native Databroker 0.7.2 release binary and its +release-matched VSS file, run the following with OpenSSL and Python 3 available: + +```bash +scripts/test-databroker-auth.sh /path/to/databroker /path/to/vss_release_6.0.json +``` + +The script generates disposable credentials, starts the broker on a temporary +loopback port, and cleans up the broker and credentials after the test. + ## Interfaces Both APIs are vendored, pinned and unmodified (`proto/PROVENANCE.md`): AOSP's `VehicleServer.proto` and Vehicle diff --git a/scripts/test-databroker-auth.sh b/scripts/test-databroker-auth.sh new file mode 100755 index 0000000..03564fb --- /dev/null +++ b/scripts/test-databroker-auth.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +set -euo pipefail +if [[ $# != 2 ]]; then + echo "Usage: $0 /path/to/databroker /path/to/vss.json" >&2 + exit 2 +fi +broker=$(realpath "$1") +vss=$(realpath "$2") +cd "$(dirname "$0")/.." +fixture=$(mktemp -d /tmp/vxvhal-auth.XXXXXX) +chmod 700 "$fixture" +pid= +cleanup() { + if [[ -n "$pid" ]]; then + kill "$pid" 2>/dev/null || true + wait "$pid" 2>/dev/null || true + fi + rm -rf -- "$fixture" +} +trap cleanup EXIT +umask 077 +openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj /CN=vxvhal-test-ca -keyout "$fixture/ca.key" -out "$fixture/ca.pem" 2>/dev/null +openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj /CN=vxvhal-other-ca -keyout "$fixture/other-ca.key" -out "$fixture/other-ca.pem" 2>/dev/null +openssl req -new -newkey rsa:2048 -nodes -subj /CN=localhost -keyout "$fixture/server.key" -out "$fixture/server.csr" 2>/dev/null +printf 'subjectAltName=IP:127.0.0.1\nextendedKeyUsage=serverAuth\n' > "$fixture/server.ext" +openssl x509 -req -in "$fixture/server.csr" -CA "$fixture/ca.pem" -CAkey "$fixture/ca.key" -CAcreateserial -days 1 -extfile "$fixture/server.ext" -out "$fixture/server.pem" 2>/dev/null +openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out "$fixture/jwt.key" 2>/dev/null +openssl pkey -in "$fixture/jwt.key" -pubout -out "$fixture/jwt.pub" +python3 - "$fixture" <<'PY' +import base64, json, subprocess, sys, time +from pathlib import Path +p=Path(sys.argv[1]) +def b64(data): + return base64.urlsafe_b64encode(data).rstrip(b"=") +for name, scope in (("read", "read"), ("provide", "provide")): + now=int(time.time()) + claims=dict(iss="vxvhal-test", aud=["kuksa.val"], sub=name, iat=now, nbf=now-5, exp=now+3600, scope=scope) + data=b".".join(b64(json.dumps(x).encode()) for x in ({"alg":"RS256","typ":"JWT"}, claims)) + sig=subprocess.check_output(["openssl","dgst","-sha256","-sign",str(p/"jwt.key")],input=data) + (p/(name+".token")).write_bytes(data+b"."+b64(sig)) +PY +port=$(python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1",0)); print(s.getsockname()[1])') +"$broker" --address 127.0.0.1 --port "$port" --tls-cert "$fixture/server.pem" --tls-private-key "$fixture/server.key" --jwt-public-key "$fixture/jwt.pub" --vss "$vss" > "$fixture/broker.log" 2>&1 & +pid=$! +for attempt in {1..50}; do + if (exec 3<>"/dev/tcp/127.0.0.1/$port") 2>/dev/null; then break; fi + if ! kill -0 "$pid"; then cat "$fixture/broker.log"; exit 1; fi + sleep 0.1 +done +VXVHAL_TEST_SECURE_DATABROKER="https://127.0.0.1:$port" VXVHAL_TEST_AUTH_FIXTURE="$fixture" timeout 60s cargo test --locked --test databroker_auth -- --nocapture diff --git a/src/main.rs b/src/main.rs index 9adb608..02d7b08 100644 --- a/src/main.rs +++ b/src/main.rs @@ -26,6 +26,12 @@ struct Args { default_value = "http://127.0.0.1:55555" )] databroker: String, + /// PEM CA certificate for the Databroker HTTPS endpoint. + #[arg(long, env = "VXVHAL_DATABROKER_CA")] + databroker_ca: Option, + /// File containing the Databroker JWT bearer token. + #[arg(long, env = "VXVHAL_DATABROKER_TOKEN_FILE")] + databroker_token_file: Option, /// The VSS-to-AAOS mapping table. #[arg(long, env = "VXVHAL_MAPPING", default_value = "mappings/default.yaml")] mapping: PathBuf, @@ -40,7 +46,18 @@ async fn main() -> Result<(), Box> { .init(); let args = Args::parse(); let mapping = Mapping::load(&args.mapping)?; - let signals = Signals::new(&args.databroker, &mapping.properties)?; + let ca = args + .databroker_ca + .as_ref() + .map(std::fs::read) + .transpose() + .map_err(|error| format!("cannot read Databroker CA certificate: {error}"))?; + let signals = Signals::with_credentials( + &args.databroker, + &mapping.properties, + ca, + args.databroker_token_file, + )?; tokio::spawn(signals.clone().run()); tracing::info!( listen = %args.listen, diff --git a/src/signals.rs b/src/signals.rs index 21132b9..05c6e55 100644 --- a/src/signals.rs +++ b/src/signals.rs @@ -1,11 +1,13 @@ //! The Kuksa side: current values on demand, and a stream of AAOS property updates. use std::collections::{HashMap, HashSet}; +use std::path::PathBuf; use std::sync::{Arc, Mutex}; use std::time::Duration; use tokio::sync::broadcast; -use tonic::transport::{Channel, Endpoint}; +use tonic::Request; +use tonic::transport::{Certificate, Channel, ClientTlsConfig, Endpoint}; use crate::mapping::Property; use crate::pb::kuksa::{self, val_client::ValClient}; @@ -18,6 +20,7 @@ const RESUBSCRIBE_AFTER: Duration = Duration::from_secs(1); #[derive(Clone)] pub struct Signals { client: ValClient, + token_file: Option, by_path: Arc>>, updates: broadcast::Sender, /// The last timestamp sent per (prop, area). Android's proxy drops a value whose timestamp @@ -30,6 +33,10 @@ pub struct Signals { pub enum SignalError { #[error("invalid databroker address {0}")] Address(String), + #[error("Databroker CA and token options require an https:// endpoint")] + InsecureCredentials, + #[error("cannot configure Databroker TLS: {0}")] + Tls(#[from] tonic::transport::Error), #[error("databroker call failed: {0}")] Call(#[from] tonic::Status), } @@ -38,10 +45,34 @@ impl Signals { /// Connects lazily: vxvhal serves (reporting values not available) while the databroker is /// still starting, and picks it up when it answers. pub fn new(databroker: &str, properties: &[Property]) -> Result { - let channel = Endpoint::from_shared(databroker.to_string()) + Self::with_credentials(databroker, properties, None, None) + } + + /// Configure upstream TLS and a rotating bearer token file. + pub fn with_credentials( + databroker: &str, + properties: &[Property], + ca_pem: Option>, + token_file: Option, + ) -> Result { + let mut endpoint = Endpoint::from_shared(databroker.to_string()) .map_err(|_| SignalError::Address(databroker.to_string()))? - .connect_timeout(Duration::from_secs(2)) - .connect_lazy(); + .connect_timeout(Duration::from_secs(2)); + match endpoint.uri().scheme_str() { + Some("https") => { + let tls = match ca_pem { + Some(pem) => ClientTlsConfig::new().ca_certificate(Certificate::from_pem(pem)), + None => ClientTlsConfig::new().with_webpki_roots(), + }; + endpoint = endpoint.tls_config(tls)?; + } + Some("http") if ca_pem.is_some() || token_file.is_some() => { + return Err(SignalError::InsecureCredentials); + } + Some("http") => {} + _ => return Err(SignalError::Address(databroker.to_string())), + } + let channel = endpoint.connect_lazy(); let mut by_path: HashMap> = HashMap::new(); for p in properties { by_path.entry(p.vss.clone()).or_default().push(p.clone()); @@ -49,12 +80,36 @@ impl Signals { let (updates, _) = broadcast::channel(1024); Ok(Self { client: ValClient::new(channel), + token_file, by_path: Arc::new(by_path), updates, last_ts: Arc::new(Mutex::new(HashMap::new())), }) } + async fn request(&self, message: T) -> Result, tonic::Status> { + let mut request = Request::new(message); + if let Some(path) = &self.token_file { + let token = tokio::fs::read_to_string(path).await.map_err(|error| { + tonic::Status::unauthenticated(format!( + "cannot read Databroker token file: {error}" + )) + })?; + let token = token.trim(); + if token.is_empty() || token.bytes().any(|byte| byte.is_ascii_whitespace()) { + return Err(tonic::Status::unauthenticated( + "invalid Databroker token file", + )); + } + let mut value: tonic::metadata::MetadataValue<_> = format!("Bearer {token}") + .parse() + .map_err(|_| tonic::Status::unauthenticated("invalid Databroker token file"))?; + value.set_sensitive(true); + request.metadata_mut().insert("authorization", value); + } + Ok(request) + } + /// Updates for every mapped property, as they arrive from the databroker. pub fn subscribe(&self) -> broadcast::Receiver { self.updates.subscribe() @@ -71,7 +126,12 @@ impl Signals { signal: Some(kuksa::signal_id::Signal::Path(property.vss.clone())), }], }; - let response = match self.client.clone().get_values(request).await { + let response = match self + .client + .clone() + .get_values(self.request(request).await?) + .await + { Ok(response) => response.into_inner(), Err(status) if status.code() == tonic::Code::NotFound => return Ok(None), Err(status) => return Err(status.into()), @@ -84,11 +144,10 @@ impl Signals { /// Whether the databroker answers. pub async fn healthy(&self) -> bool { - self.client - .clone() - .get_server_info(kuksa::GetServerInfoRequest {}) - .await - .is_ok() + let Ok(request) = self.request(kuksa::GetServerInfoRequest {}).await else { + return false; + }; + self.client.clone().get_server_info(request).await.is_ok() } /// Follows the databroker until the process ends, resubscribing after any failure. @@ -112,7 +171,13 @@ impl Signals { buffer_size: 0, filter: None, }; - match self.client.clone().subscribe(request).await { + let subscription = async { + self.client + .clone() + .subscribe(self.request(request).await?) + .await + }; + match subscription.await { Ok(response) => { tracing::info!(signals = paths.len(), "subscribed to the databroker"); let mut stream = response.into_inner(); @@ -146,10 +211,13 @@ impl Signals { let mut paths = Vec::new(); for path in self.by_path.keys() { let response = client - .list_metadata(kuksa::ListMetadataRequest { - root: path.clone(), - filter: String::new(), - }) + .list_metadata( + self.request(kuksa::ListMetadataRequest { + root: path.clone(), + filter: String::new(), + }) + .await?, + ) .await; let exists = match response { Ok(response) => response diff --git a/tests/databroker_auth.rs b/tests/databroker_auth.rs new file mode 100644 index 0000000..259d9ff --- /dev/null +++ b/tests/databroker_auth.rs @@ -0,0 +1,123 @@ +//! Live read and subscription checks against a TLS- and JWT-enabled Databroker. + +use std::path::PathBuf; +use std::time::Duration; + +use tonic::transport::{Certificate, ClientTlsConfig, Endpoint}; +use vxvhal::mapping::Mapping; +use vxvhal::pb::kuksa::{self, val_client::ValClient}; +use vxvhal::signals::{SignalError, Signals}; + +#[tokio::test] +async fn authenticated_reads_and_streams_use_the_current_token() { + let Ok(addr) = std::env::var("VXVHAL_TEST_SECURE_DATABROKER") else { + eprintln!("skipped: set VXVHAL_TEST_SECURE_DATABROKER"); + return; + }; + let fixture = PathBuf::from(std::env::var_os("VXVHAL_TEST_AUTH_FIXTURE").unwrap()); + let ca = std::fs::read(fixture.join("ca.pem")).unwrap(); + let mapping = Mapping::parse(include_str!("../mappings/default.yaml")).unwrap(); + let speed = mapping + .properties + .iter() + .find(|p| p.vss == "Vehicle.Speed") + .unwrap(); + let token_file = fixture.join("active-test.token"); + let valid = std::fs::read_to_string(fixture.join("read.token")).unwrap(); + + let anonymous = + Signals::with_credentials(&addr, &mapping.properties, Some(ca.clone()), None).unwrap(); + assert!(matches!( + anonymous.get(speed).await, + Err(SignalError::Call(status)) if status.code() == tonic::Code::Unauthenticated + )); + + let untrusted = Signals::with_credentials( + &addr, + &mapping.properties, + Some(std::fs::read(fixture.join("other-ca.pem")).unwrap()), + None, + ) + .unwrap(); + assert!(matches!( + untrusted.get(speed).await, + Err(SignalError::Call(status)) if status.code() == tonic::Code::Unavailable + )); + + std::fs::write(&token_file, "invalid-token").unwrap(); + let signals = Signals::with_credentials( + &addr, + &mapping.properties, + Some(ca.clone()), + Some(token_file.clone()), + ) + .unwrap(); + assert!(matches!( + signals.get(speed).await, + Err(SignalError::Call(status)) if status.code() == tonic::Code::Unauthenticated + )); + std::fs::write(&token_file, &valid).unwrap(); + signals + .get(speed) + .await + .expect("read with the replacement token"); + assert!(signals.healthy().await); + let mut updates = signals.subscribe(); + let subscriber = tokio::spawn(signals.clone().run()); + + let channel = Endpoint::from_shared(addr) + .unwrap() + .tls_config(ClientTlsConfig::new().ca_certificate(Certificate::from_pem(ca))) + .unwrap() + .connect() + .await + .unwrap(); + let producer = std::fs::read_to_string(fixture.join("provide.token")).unwrap(); + let mut producer_client = ValClient::new(channel); + let deadline = tokio::time::Instant::now() + Duration::from_secs(5); + loop { + assert!( + tokio::time::Instant::now() < deadline, + "no authenticated stream update" + ); + let mut request = tonic::Request::new(kuksa::PublishValueRequest { + signal_id: Some(kuksa::SignalId { + signal: Some(kuksa::signal_id::Signal::Path("Vehicle.Speed".into())), + }), + data_point: Some(kuksa::Datapoint { + timestamp: None, + value: Some(kuksa::Value { + typed_value: Some(kuksa::value::TypedValue::Float(72.0)), + }), + }), + }); + request.metadata_mut().insert( + "authorization", + format!("Bearer {}", producer.trim()).parse().unwrap(), + ); + producer_client.publish_value(request).await.unwrap(); + if let Ok(Ok(batch)) = + tokio::time::timeout(Duration::from_millis(200), updates.recv()).await + { + assert!( + batch + .values + .iter() + .any(|value| value.float_values == [20.0]) + ); + break; + } + } + + let current = signals.get(speed).await.unwrap().unwrap(); + assert!((current.float_values[0] - 20.0).abs() < 1e-3); + std::fs::write(&token_file, "invalid-token").unwrap(); + assert!(matches!( + signals.get(speed).await, + Err(SignalError::Call(status)) if status.code() == tonic::Code::Unauthenticated + )); + std::fs::write(&token_file, valid).unwrap(); + assert!(signals.get(speed).await.unwrap().is_some()); + subscriber.abort(); + std::fs::remove_file(token_file).unwrap(); +}