diff --git a/.github/ci/esp-lte-mtls.toml b/.github/ci/esp-lte-mtls.toml index aaeef9c..7b6fbb8 100644 --- a/.github/ci/esp-lte-mtls.toml +++ b/.github/ci/esp-lte-mtls.toml @@ -1,5 +1,6 @@ -# CI only: an ESP32-S3 on LTE with MQTT over mTLS, so the TLS code (the `mqtt-tls` -# feature, off in the example config) is linted and built on Xtensa. ci.yml makes +# CI only: an ESP32-S3 on WiFi and LTE (relay with LTE fallback, LAN direct on WiFi) +# with MQTT over mTLS, so the TLS code (the `mqtt-tls` feature, off in the example +# config) and the dual uplink are linted and built on Xtensa. ci.yml makes # throwaway certificates in /tmp/mqtt-certs first. # ============================================== # OPEN CAR INTERFACE - BUILD CONFIGURATION @@ -83,12 +84,14 @@ interface = "vcan0" # =========================== [network.wifi] -enabled = false +enabled = true ssid = "YourSSID" password = "YourPassword" -# LTE uplink instead of WiFi (one uplink per build: set [network.wifi].enabled = false). -# Needs a board with a modem, e.g. hardware_profile = "lilygo-t-sim7670g-s3". See docs/lte.md. +[network.lan] +enabled = true + +# LTE together with WiFi: the relay prefers WiFi and falls back to LTE. See docs/lte.md. [network.lte] enabled = true apn = "your.carrier.apn" @@ -106,7 +109,6 @@ port = 23 # Use mqtt:// for basic auth (plain TCP). Use mqtts:// for mTLS. broker_url = "mqtts://broker.example.com" # Names this device's MQTT topics, and the app learns it over BLE: give each device its own. -client_id = "dev-car" # Specify the type of authentication to the broker. # - `basic` is for username/password combo (no certs needed) diff --git a/README.md b/README.md index a266742..01b8d29 100644 --- a/README.md +++ b/README.md @@ -54,11 +54,11 @@ ssid = "YourSSID" password = "YourPassword" [network.mqtt] -broker_url = "mqtts://broker.example.com" # mqtt:// is plain TCP: only on a network you trust -auth_mode = "mtls" # or "basic" (username/password) +broker_url = "mqtt://192.168.0.100:1883" # or mqtts:// for TLS +auth_mode = "basic" # "none", "basic" (username/password) or "mtls" ``` -A broker on the internet (any LTE setup) should use `mqtts://` with `auth_mode = "mtls"`: see [MQTT over TLS](docs/mqtt-tls.md) for the certificates and the broker's settings. +Any MQTT broker works as a relay for remote access: the app and the device talk through it with the end-to-end encrypted secure channel, so the broker never sees the state or the commands, and TLS and broker credentials are optional hardening. See [MQTT relay](docs/mqtt-relay.md). To reach the broker over a cellular modem instead of WiFi, disable `[network.wifi]` and set the SIM's APN in `[network.lte]` (see [LTE](docs/lte.md)). Per-board settings live under `[hardware.esp]` / `[hardware.pc]`, including CAN buses (`[[hardware..can_buses]]`, where order determines `bus_id`) and BLE options. The `board` and `platform` values can be overridden with `--board` and `--platform`. To reverse engineer a car, `[network.can_logger] enabled = true` streams the CAN buses to SavvyCAN over WiFi (see [CAN bus](docs/can.md#savvycan-logging)). Hardware profiles in `hardware-profiles/` are ready-made pin/CAN setups for specific devices; anything set in `config.toml`, including `board`, wins over the profile. @@ -96,7 +96,7 @@ The firmware is a Cargo workspace of independently compiled crates that cooperat ┌───────▼──────────────────▼──────────────┐ │ core-interface │ │ static Channels · Embassy tasks │ -│ platform_id gating · BLE/MQTT routing │ +│ platform_id gating · routing · Noise │ └─────────────────────────────────────────┘ ``` @@ -107,7 +107,7 @@ The firmware is a Cargo workspace of independently compiled crates that cooperat | `cars/*` | Vehicle logic: CAN decoding, command handling, state encoding | | `xtask` | Build orchestrator: reads `config.toml`, generates `.app_build/`, invokes cargo | -Details: [Architecture](docs/architecture.md) · [BLE](docs/ble.md) · [CAN bus](docs/can.md) · [LAN direct](docs/lan.md) · [LTE](docs/lte.md) · [MQTT over TLS](docs/mqtt-tls.md) · [Vehicle commands](docs/commands.md) +Details: [Architecture](docs/architecture.md) · [BLE](docs/ble.md) · [CAN bus](docs/can.md) · [LAN direct](docs/lan.md) · [LTE](docs/lte.md) · [MQTT relay](docs/mqtt-relay.md) · [Vehicle commands](docs/commands.md) ## 📂 Project Structure diff --git a/boards/esp/src/lib.rs b/boards/esp/src/lib.rs index 11e1ec6..c6f3ac2 100644 --- a/boards/esp/src/lib.rs +++ b/boards/esp/src/lib.rs @@ -1,7 +1,7 @@ //! Board support crate for the ESP32 family. //! //! Wires the `core-interface` task set to ESP32-specific hardware drivers: BLE -//! (trouble-host), WiFi or LTE (esp-radio or a PPP modem, + embassy-net) with MQTT and, on WiFi, LAN direct, and CAN buses (TWAI and/or +//! (trouble-host), WiFi and/or LTE (esp-radio or a PPP modem, + embassy-net) with MQTT and, on WiFi, LAN direct, and CAN buses (TWAI and/or //! MCP2515). The public API is kept minimal: [`start`] spawns the core protocol //! tasks, and hardware-init functions are re-exported for use by the generated //! `main.rs` entry point produced by `xtask`. @@ -59,7 +59,6 @@ mod hardware { pub fn start(spawner: &embassy_executor::Spawner) { status_leds::set_flag(status_leds::FLAG_POWER, true); spawner.spawn(core_interface::process_ble_commands_task().unwrap()); - spawner.spawn(core_interface::process_mqtt_commands_task().unwrap()); spawner.spawn(core_interface::route_responses_task().unwrap()); spawner.spawn(core_interface::publish_state_task().unwrap()); spawner.spawn(core_interface::publish_can_access_task().unwrap()); diff --git a/boards/esp/src/network.rs b/boards/esp/src/network.rs index 1b8cc87..cadb117 100644 --- a/boards/esp/src/network.rs +++ b/boards/esp/src/network.rs @@ -5,26 +5,23 @@ //! LTE uplink (`modem::init_lte`) creates the same kind of stack over PPP instead. LAN //! direct (`lan.rs`) runs on the WiFi stack. //! -//! `mqtt_driver_task` connects to the MQTT broker over TCP on whichever stack it is -//! given (with TLS through MbedTLS for `mqtts://`, see `docs/mqtt-tls.md`), subscribes -//! to the command topic, and bridges the `MQTT_RX_CHANNEL` / `MQTT_TX_CHANNEL` channel -//! pair. It reconnects from scratch on any session failure. +//! `mqtt_driver_task` connects to the MQTT broker over TCP (with TLS through MbedTLS for +//! `mqtts://`, see `docs/mqtt-relay.md`), on WiFi when a build has both uplinks and WiFi +//! is up, on LTE otherwise. It subscribes to the device's relay topics and moves secure +//! channel frames between the broker and `core_interface`'s relay, and reconnects from +//! scratch on any session failure. #[cfg(feature = "hardware")] mod hardware { use alloc::string::String; - use alloc::vec::Vec; - use core_interface::{ - MQTT_RX_CHANNEL, MQTT_STATE_TX, MQTT_TX_CHANNEL, MqttTls, Transport, proto, - }; + use core_interface::MqttTls; use embassy_net::{Runner, Stack, StackResources, dns::DnsQueryType, tcp::TcpSocket}; use esp_radio::wifi::sta::StationConfig; use esp_radio::wifi::{ Config as WifiModeConfig, ControllerConfig as WifiControllerConfig, Interface as WifiInterface, WifiController, }; - use prost::Message as _; use rust_mqtt::{ Bytes, buffer::AllocBuffer, @@ -217,21 +214,33 @@ mod hardware { } } - /// Inner MQTT session logic. Authenticates, subscribes, then loops until an - /// error occurs. Returns `Err(())` on any protocol or IO fault so the caller - /// can reconnect. + /// One session with the broker for the relay (docs/mqtt-relay.md in the contracts): + /// connects with the device's client ID, subscribes to its device topics, then moves + /// secure channel frames both ways until an error, at which point it returns + /// `Err(())` so the caller reconnects. Nothing but frames is sent or accepted. + /// + /// The session also ends when `current` (the stack it runs on) loses its + /// configuration, and, on the fallback uplink, once `preferred` has been up for + /// [`PREFERRED_SETTLE`]: the driver then reconnects on the preferred one. async fn run_mqtt_session( network: N, - client_id: &'static str, - cmd_topic: &'static str, - data_topic: &'static str, username: &'static str, password: &'static str, + current: &'static NetStack, + preferred: Option<&'static NetStack>, ) -> Result<(), ()> { use embassy_time::{Duration, Instant}; + let (Some(client_id), Some(filter)) = ( + core_interface::relay_client_id(), + core_interface::relay_subscribe_filter(), + ) else { + log::warn!("MQTT: no device identity yet"); + return Err(()); + }; + let mut buffer = AllocBuffer; - let mut client = Client::<_, _, 1, 1, 1, 0>::new(&mut buffer); + let mut client = Client::<_, _, 1, 4, 4, 0>::new(&mut buffer); let mut connect_opts = ConnectOptions::new().clean_start(); if !username.is_empty() { @@ -244,106 +253,192 @@ mod hardware { .connect( network, &connect_opts, - Some(MqttString::from_str_unchecked(client_id)), + Some(MqttString::from_str_unchecked(&client_id)), ) .await .map_err(|e| { log::warn!("MQTT: connect failed: {:?}", e); })?; - log::info!("MQTT: connected, subscribing to '{}'", cmd_topic); + log::info!( + "MQTT: connected as '{}', subscribing to '{}'", + client_id, + filter + ); - let filter = TopicFilter::new_unchecked(MqttString::from_str_unchecked(cmd_topic)); + let topic_filter = TopicFilter::new_unchecked(MqttString::from_str_unchecked(&filter)); client - .subscribe(filter, SubscriptionOptions::new()) + .subscribe(topic_filter, SubscriptionOptions::new().at_least_once()) .await .map_err(|e| { log::warn!("MQTT: subscribe failed: {:?}", e); })?; - log::info!("MQTT: ready"); - core_interface::set_link_up(Transport::Mqtt, true); - - let keepalive = Duration::from_secs(55); - let mut last_ping = Instant::now(); - let data_topic_name = TopicName::new_unchecked(MqttString::from_str_unchecked(data_topic)); - - loop { - // Responses and system state first, then the newest vehicle state. - while let Some(msg) = MQTT_TX_CHANNEL - .try_receive() - .ok() - .or_else(|| MQTT_STATE_TX.try_take()) - { - let mut buf = Vec::::new(); - if msg.encode(&mut buf).is_ok() { - let t = data_topic_name.as_borrowed(); - let pub_opts = PublicationOptions::new(TopicReference::Name(t)); - client - .publish(&pub_opts, Bytes::Borrowed(buf.as_slice())) + let Some(relay) = core_interface::relay_connect() else { + return Err(()); + }; + log::info!("MQTT: relay ready"); + + let result = async { + let keepalive = Duration::from_secs(55); + let mut last_ping = Instant::now(); + // A frame the client couldn't take yet (too many publications waiting for + // their PUBACK): sent once the broker acknowledges one. + let mut pending: Option = None; + let mut preferred_up_since: Option = None; + loop { + if !current.is_config_up() { + log::info!("MQTT: the uplink went down"); + return Err(()); + } + if let Some(preferred) = preferred { + if preferred.is_config_up() { + let since = *preferred_up_since.get_or_insert_with(Instant::now); + if since.elapsed() >= PREFERRED_SETTLE { + log::info!("MQTT: WiFi is back, moving the relay to it"); + return Ok(()); + } + } else { + preferred_up_since = None; + } + } + // Publish what is ready before polling inbound: responses and system + // state first, then the vehicle state, as the relay decides. + loop { + let Some(frame) = pending.take().or_else(|| { + core_interface::relay_try_next_frame(relay, Instant::now().as_millis()) + }) else { + break; + }; + let topic = + TopicName::new_unchecked(MqttString::from_str_unchecked(&frame.topic)); + let pub_opts = + PublicationOptions::new(TopicReference::Name(topic)).at_least_once(); + match client + .publish(&pub_opts, Bytes::Borrowed(frame.frame.as_slice())) .await - .map_err(|e| { + { + Ok(_) => {} + Err(MqttError::SendQuotaExceeded | MqttError::SessionBuffer) => { + pending = Some(frame); + break; + } + Err(e) => { log::warn!("MQTT: publish failed: {:?}", e); - })?; + return Err(()); + } + } } - } - if last_ping.elapsed() >= keepalive { - client.ping().await.map_err(|e| { - log::warn!("MQTT: ping failed: {:?}", e); - })?; - last_ping = Instant::now(); - } + if last_ping.elapsed() >= keepalive { + client.ping().await.map_err(|e| { + log::warn!("MQTT: ping failed: {:?}", e); + })?; + last_ping = Instant::now(); + } - let poll_result = - embassy_time::with_timeout(Duration::from_millis(100), client.poll()).await; - - match poll_result { - Err(_timeout) => continue, - Ok(Err(e)) => { - log::warn!("MQTT: poll error: {:?}", e); - // abort() panics if the broker sent a clean DISCONNECT - // (e.g. SessionTakenOver) because the network is still in - // Ok state. Only call it for IO/protocol errors. - if !matches!(e, MqttError::Disconnect { .. }) { - client.abort().await; + let poll_result = + embassy_time::with_timeout(Duration::from_millis(100), client.poll()).await; + + match poll_result { + Err(_timeout) => continue, + Ok(Err(e)) => { + log::warn!("MQTT: poll error: {:?}", e); + // abort() panics if the broker sent a clean DISCONNECT + // (e.g. SessionTakenOver) because the network is still in + // Ok state. Only call it for IO/protocol errors. + if !matches!(e, MqttError::Disconnect { .. }) { + client.abort().await; + } + return Err(()); } - return Err(()); - } - Ok(Ok(Event::Publish(p))) => { - if p.topic.as_ref().as_str() == cmd_topic { - let payload = p.message.as_bytes(); - if let Ok(msg) = proto::AppToDevice::decode(payload) { - // Use try_send to avoid blocking here. If we blocked on - // MQTT_RX_CHANNEL.send().await while downstream tasks are - // simultaneously blocked on BASIC_CMD_CHANNEL and - // CMD_RESP_CHANNEL, route_responses_task would be stuck - // trying to send to MQTT_TX_CHANNEL — which we can't drain - // because we're blocked. That forms a deadlock cycle. - // Dropping one inbound command under back-pressure is safe; - // the app can retry. What we must never do is stall the - // outbound drain loop. - if MQTT_RX_CHANNEL.try_send(msg).is_err() { - log::warn!("MQTT: RX channel full, dropping inbound command"); + Ok(Ok(Event::Publish(p))) => { + // Never blocks on a downstream queue: the dispatcher answers + // through the session's queue with try_send (see + // docs/architecture.md). + let topic = String::from(p.topic.as_ref().as_str()); + let payload = p.message.as_bytes().to_vec(); + drop(p); + let reply = + core_interface::relay_receive_frame(relay, &topic, &payload).await; + if let Some(reply) = reply { + let name = TopicName::new_unchecked(MqttString::from_str_unchecked( + &reply.topic, + )); + let pub_opts = + PublicationOptions::new(TopicReference::Name(name)).at_least_once(); + match client + .publish(&pub_opts, Bytes::Borrowed(reply.frame.as_slice())) + .await + { + Ok(_) => {} + // The client handshakes again after its timeout. + Err(MqttError::SendQuotaExceeded | MqttError::SessionBuffer) => { + log::warn!( + "MQTT: too many publications in flight, reply dropped" + ); + } + Err(e) => { + log::warn!("MQTT: publish failed: {:?}", e); + return Err(()); + } } } } + Ok(Ok(_)) => {} + } + } + } + .await; + core_interface::relay_disconnect(relay); + result + } + + /// How long WiFi must stay up before the relay leaves LTE for it, so a flaky WiFi at + /// the edge of its range doesn't make the relay bounce between the two. + const PREFERRED_SETTLE: embassy_time::Duration = embassy_time::Duration::from_secs(20); + + /// The stack to connect on: `stack` when it is up, else `fallback` when it is up, + /// waiting for either. Also whether it is the fallback. + async fn pick_uplink( + stack: &'static NetStack, + fallback: Option<&'static NetStack>, + ) -> (&'static NetStack, bool) { + loop { + if stack.is_config_up() { + return (stack, false); + } + if let Some(fallback) = fallback + && fallback.is_config_up() + { + return (fallback, true); + } + log::debug!("MQTT: waiting for network..."); + match fallback { + None => stack.wait_config_up().await, + Some(fallback) => { + embassy_futures::select::select( + stack.wait_config_up(), + fallback.wait_config_up(), + ) + .await; } - Ok(Ok(_)) => {} } } } /// Public MQTT driver task. Waits for the network, resolves the broker, opens a TCP connection to the /// broker, runs the session, and reconnects on any failure. + /// + /// `stack` is the preferred uplink (WiFi, or the build's only one). A build with WiFi + /// and LTE passes the LTE stack as `fallback`: the relay runs on WiFi while it is up, + /// on LTE otherwise, and moves back to WiFi once WiFi has been up for a while. #[embassy_executor::task] pub async fn mqtt_driver_task( stack: &'static NetStack, + fallback: Option<&'static NetStack>, broker_host: &'static str, broker_port: u16, - client_id: &'static str, - cmd_topic: &'static str, - data_topic: &'static str, username: &'static str, password: &'static str, tls: Option, @@ -373,16 +468,17 @@ mod hardware { let mut tx_buffer = [0u8; TCP_TX]; loop { - if !stack.is_config_up() { - log::debug!("MQTT: waiting for network..."); - stack.wait_config_up().await; + let (uplink, on_fallback) = pick_uplink(stack, fallback).await; + let preferred = on_fallback.then_some(stack); + if fallback.is_some() { + log::info!("MQTT: using {}", if on_fallback { "LTE" } else { "WiFi" }); } - let mut socket = TcpSocket::new(*stack, &mut rx_buffer, &mut tx_buffer); + let mut socket = TcpSocket::new(*uplink, &mut rx_buffer, &mut tx_buffer); socket.set_timeout(Some(embassy_time::Duration::from_secs(30))); // Numeric addresses are returned as they are, without a query. - let addr = match stack.dns_query(broker_host, DnsQueryType::A).await { + let addr = match uplink.dns_query(broker_host, DnsQueryType::A).await { Ok(addrs) if !addrs.is_empty() => addrs[0], Ok(_) | Err(_) => { log::warn!("MQTT: can't resolve '{}', retrying in 10s", broker_host); @@ -400,15 +496,10 @@ mod hardware { } #[cfg(not(feature = "mqtt-tls"))] - let result = - run_mqtt_session(socket, client_id, cmd_topic, data_topic, username, password) - .await; + let result = run_mqtt_session(socket, username, password, uplink, preferred).await; #[cfg(feature = "mqtt-tls")] let result = match &tls { - None => { - run_mqtt_session(socket, client_id, cmd_topic, data_topic, username, password) - .await - } + None => run_mqtt_session(socket, username, password, uplink, preferred).await, Some(setup) => { match mbedtls_rs::Session::new( setup.tls.reference(), @@ -433,21 +524,18 @@ mod hardware { "MQTT: TLS established, {} B heap free", esp_alloc::HEAP.free() ); - run_mqtt_session( - session, client_id, cmd_topic, data_topic, username, password, - ) - .await + run_mqtt_session(session, username, password, uplink, preferred) + .await } }, } } }; + // Ok means the session left LTE for WiFi: reconnect at once. if result.is_err() { log::info!("MQTT: session ended, reconnecting in 5s"); + Timer::after(Duration::from_secs(5)).await; } - // Drops what was queued for this session instead of sending it on the next. - core_interface::set_link_up(Transport::Mqtt, false); - Timer::after(Duration::from_secs(5)).await; } } diff --git a/boards/esp/xtask_builder.rs b/boards/esp/xtask_builder.rs index f416d15..a47ddf5 100644 --- a/boards/esp/xtask_builder.rs +++ b/boards/esp/xtask_builder.rs @@ -1,6 +1,6 @@ use crate::{ Config, LAUNCH_NAME_PREFIX, RustAnalyzerConfig, TargetBuilder, escape_rust_string, - firmware_dir, load_transport_contract, parse_broker_url, render_topic_from_template, + firmware_dir, load_transport_contract, parse_broker_url, validate_ble_transport_contract, }; use serde::Deserialize; @@ -152,12 +152,24 @@ fn parse_level(field: &str, level: &str) -> Result { } } -/// The network the MQTT driver runs on. One per build for now (see docs/lte.md). +/// The networks a build joins (see docs/lte.md). With both, the relay prefers WiFi and +/// falls back to LTE, and LAN direct and the CAN logger run on WiFi. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Uplink { None, Wifi, Lte, + Both, +} + +impl Uplink { + fn has_wifi(self) -> bool { + matches!(self, Uplink::Wifi | Uplink::Both) + } + + fn has_lte(self) -> bool { + matches!(self, Uplink::Lte | Uplink::Both) + } } fn select_uplink( @@ -167,21 +179,17 @@ fn select_uplink( can_logger_enabled: bool, ) -> Result { let uplink = match (wifi_enabled, lte_enabled) { - (true, true) => { - return Err("[network.wifi] and [network.lte] are both enabled; a build has one \ - uplink for now. Set [network.wifi].enabled = false to use LTE." - .into()); - } + (true, true) => Uplink::Both, (true, false) => Uplink::Wifi, (false, true) => Uplink::Lte, (false, false) => Uplink::None, }; - if uplink == Uplink::Lte && !has_modem { + if uplink.has_lte() && !has_modem { return Err("[network.lte].enabled = true needs a modem: this board has no \ [hardware.esp.modem] (use a hardware profile with one, or add it)." .into()); } - if can_logger_enabled && uplink != Uplink::Wifi { + if can_logger_enabled && !uplink.has_wifi() { return Err("[network.can_logger].enabled = true needs [network.wifi].enabled = true: \ SavvyCAN connects to the device, which a carrier network doesn't allow." .into()); @@ -189,9 +197,27 @@ fn select_uplink( Ok(uplink) } -/// Whether LAN direct is built in: asked for, on a WiFi uplink. -fn lan_on_uplink(lan_enabled: bool, wifi_uplink: bool) -> bool { - lan_enabled && wifi_uplink +/// Whether LAN direct is built in: asked for, on a build that joins WiFi. +fn lan_on_uplink(lan_enabled: bool, wifi_enabled: bool) -> bool { + lan_enabled && wifi_enabled +} + +/// The generated `main.rs` code that spawns the MQTT relay driver: on `net_stack`, with +/// `lte_stack` as the fallback when the build joins both networks. +fn mqtt_driver_spawn_code(uplink: Uplink) -> String { + let fallback = if uplink == Uplink::Both { "Some(lte_stack)" } else { "None" }; + format!( + " spawner\n\ + \x20 .spawn(board_esp::mqtt_driver_task(\n\ + \x20 net_stack,\n\ + \x20 {fallback},\n\ + \x20 MQTT_BROKER_HOST,\n\ + \x20 MQTT_BROKER_PORT,\n\ + \x20 MQTT_USERNAME,\n\ + \x20 MQTT_PASSWORD,\n\ + \x20 MQTT_TLS,\n\ + \x20 ).unwrap());\n" + ) } /// Checks `[network.lte]` with the rules the firmware applies to what it sends the modem. @@ -212,8 +238,8 @@ fn check_lte_settings(lte: &crate::LteConfig) -> Result<(), String> { } /// The generated `main.rs` code that opens the modem's UART and starts the LTE stack -/// as `net_stack`. -fn lte_init_code(modem: &EspModemConfig) -> Result { +/// as the variable `stack_var`. +fn lte_init_code(modem: &EspModemConfig, stack_var: &str) -> Result { let kind = modem_kind_ident(&modem.kind)?; let pin = |field: &str, pin: Option, active_high: bool| match pin { Some(p) => format!( @@ -222,7 +248,7 @@ fn lte_init_code(modem: &EspModemConfig) -> Result { None => format!(" {field}: None,\n"), }; let mut code = String::new(); - code.push_str(" let net_stack = board_esp::init_lte(\n &spawner,\n"); + code.push_str(&format!(" let {stack_var} = board_esp::init_lte(\n &spawner,\n")); code.push_str(&format!( " board_esp::new_modem_uart(peripherals.UART1, peripherals.GPIO{}, peripherals.GPIO{}, {}),\n", modem.uart_tx_pin, modem.uart_rx_pin, modem.baudrate @@ -542,11 +568,8 @@ impl TargetBuilder for Builder { cargo_toml.push_str("[dependencies]\n"); cargo_toml.push_str("core-interface = { path = \"../core-interface\" }\n"); let mqtt_security = crate::checked_mqtt_security(config); - // LAN direct needs the WiFi stack: `select_uplink` below rejects WiFi with LTE. - let lan_enabled = lan_on_uplink( - config.network.lan.enabled, - config.network.wifi.enabled && !config.network.lte.enabled, - ); + // LAN direct runs on the WiFi stack, also in a build that joins LTE too. + let lan_enabled = lan_on_uplink(config.network.lan.enabled, config.network.wifi.enabled); let mut board_features = vec!["\"hardware\""]; if matches!(mqtt_security, crate::MqttSecurity::Tls { .. }) { board_features.push("\"mqtt-tls\""); @@ -597,17 +620,6 @@ impl TargetBuilder for Builder { // Generate network constants and WiFi/MQTT driver spawn let (broker_host, broker_port) = parse_broker_url(&config.network.mqtt.broker_url); - let client_id = &config.network.mqtt.client_id; - let mqtt_cmd_topic = escape_rust_string(&render_topic_from_template( - &transport.mqtt.command_topic_template, - client_id, - "mqtt.command_topic_template", - )); - let mqtt_data_topic = escape_rust_string(&render_topic_from_template( - &transport.mqtt.data_topic_template, - client_id, - "mqtt.data_topic_template", - )); let ble_device_name = esp_hw .ble @@ -627,12 +639,12 @@ impl TargetBuilder for Builder { eprintln!("\u{274c} {e}"); exit(1); }); - let wifi_enabled = uplink == Uplink::Wifi; + let wifi_enabled = uplink.has_wifi(); if config.network.lan.enabled && !lan_enabled { println!( "\u{26a0}\u{fe0f} [network.lan].enabled is ignored: LAN direct needs \ - [network.wifi].enabled = true (a build has one uplink, and a carrier network \ - doesn't let the phone reach the device)." + [network.wifi].enabled = true (a carrier network doesn't let the phone reach \ + the device)." ); } let wifi_ssid = if wifi_enabled { @@ -646,7 +658,6 @@ impl TargetBuilder for Builder { let wifi_ssid = escape_rust_string(wifi_ssid); let wifi_password = escape_rust_string(config.network.wifi.password.as_deref().unwrap_or("")); let broker_host = escape_rust_string(&broker_host); - let client_id = escape_rust_string(client_id); let ble_constants = format!( "const BLE_DEVICE_NAME_BASE: &str = \"{ble_name}\";\n\ @@ -678,47 +689,41 @@ impl TargetBuilder for Builder { }, ); - let uplink_constants = match uplink { - Uplink::Wifi => format!( + let mut uplink_constants = String::new(); + if uplink.has_wifi() { + uplink_constants.push_str(&format!( "const WIFI_SSID: &str = \"{}\";\nconst WIFI_PASSWORD: &str = \"{}\";\n", wifi_ssid, wifi_password - ), - Uplink::Lte => { - check_lte_settings(lte).unwrap_or_else(|e| { - eprintln!("\u{274c} {e}"); - exit(1); - }); - format!( - "const LTE_APN: &str = \"{}\";\n\ - const LTE_USERNAME: &str = \"{}\";\n\ - const LTE_PASSWORD: &str = \"{}\";\n\ - const LTE_SIM_PIN: &str = \"{}\";\n", - escape_rust_string(lte.apn.as_deref().unwrap_or("")), - escape_rust_string(<e.username), - escape_rust_string(<e.password), - escape_rust_string(<e.sim_pin), - ) - } - Uplink::None => String::new(), - }; + )); + } + if uplink.has_lte() { + check_lte_settings(lte).unwrap_or_else(|e| { + eprintln!("\u{274c} {e}"); + exit(1); + }); + uplink_constants.push_str(&format!( + "const LTE_APN: &str = \"{}\";\n\ + const LTE_USERNAME: &str = \"{}\";\n\ + const LTE_PASSWORD: &str = \"{}\";\n\ + const LTE_SIM_PIN: &str = \"{}\";\n", + escape_rust_string(lte.apn.as_deref().unwrap_or("")), + escape_rust_string(<e.username), + escape_rust_string(<e.password), + escape_rust_string(<e.sim_pin), + )); + } let network_constants = if uplink != Uplink::None { format!( "{uplink}\ const MQTT_BROKER_HOST: &str = \"{host}\";\n\ const MQTT_BROKER_PORT: u16 = {port};\n\ - const MQTT_CLIENT_ID: &str = \"{cid}\";\n\ - const MQTT_CMD_TOPIC: &str = \"{cmd_topic}\";\n\ - const MQTT_DATA_TOPIC: &str = \"{data_topic}\";\n\ const MQTT_USERNAME: &str = \"{user}\";\n\ const MQTT_PASSWORD: &str = \"{pass}\";\n\ {ble}", uplink = uplink_constants, host = broker_host, port = broker_port, - cid = client_id, - cmd_topic = mqtt_cmd_topic, - data_topic = mqtt_data_topic, user = mqtt_username, pass = mqtt_password, ble = ble_constants, @@ -727,24 +732,27 @@ impl TargetBuilder for Builder { ble_constants }; - let network_hardware_init = match uplink { - Uplink::Wifi => concat!( + // `net_stack` is the preferred uplink: WiFi when the build joins it (LAN direct + // and the CAN logger run there), else LTE. With both, LTE is `lte_stack`. + let mut network_hardware_init = String::new(); + if uplink.has_wifi() { + network_hardware_init.push_str(concat!( " let net_stack = board_esp::init_wifi(\n", " &spawner,\n", " peripherals.WIFI,\n", " WIFI_SSID,\n", " WIFI_PASSWORD,\n", " );\n", - ).to_string(), - Uplink::Lte => { - let modem = esp_hw.modem.as_ref().expect("select_uplink checked the modem"); - lte_init_code(modem).unwrap_or_else(|e| { - eprintln!("\u{274c} {e}"); - exit(1); - }) - } - Uplink::None => String::new(), - }; + )); + } + if uplink.has_lte() { + let modem = esp_hw.modem.as_ref().expect("select_uplink checked the modem"); + let stack_var = if uplink == Uplink::Both { "lte_stack" } else { "net_stack" }; + network_hardware_init.push_str(<e_init_code(modem, stack_var).unwrap_or_else(|e| { + eprintln!("\u{274c} {e}"); + exit(1); + })); + } let ble_driver_spawn = concat!( " spawner\n", @@ -757,27 +765,13 @@ impl TargetBuilder for Builder { ).to_string(); let mqtt_driver_spawn = if uplink != Uplink::None { - concat!( - " core_interface::set_mqtt_client_id(MQTT_CLIENT_ID);\n", - " spawner\n", - " .spawn(board_esp::mqtt_driver_task(\n", - " net_stack,\n", - " MQTT_BROKER_HOST,\n", - " MQTT_BROKER_PORT,\n", - " MQTT_CLIENT_ID,\n", - " MQTT_CMD_TOPIC,\n", - " MQTT_DATA_TOPIC,\n", - " MQTT_USERNAME,\n", - " MQTT_PASSWORD,\n", - " MQTT_TLS,\n", - " ).unwrap());\n", - ).to_string() + mqtt_driver_spawn_code(uplink) } else { " // No uplink (WiFi and LTE disabled): MQTT driver not spawned.\n".to_string() }; let can_logger = &config.network.can_logger; - // `select_uplink` only allows the logger on WiFi. + // `select_uplink` only allows the logger with WiFi, which is `net_stack`. let can_logger_spawn = if can_logger.enabled { format!( " spawner\n\ @@ -801,7 +795,13 @@ impl TargetBuilder for Builder { }; let is_dual_core = esp_hw.mcu == "esp32" || esp_hw.mcu == "esp32s3"; - let heap_size = if is_dual_core { "160 * 1024" } else { "83 * 1024" }; + // A build that joins WiFi and LTE has both network stacks in static RAM, which + // takes ~48 KB from the shared stack/heap SRAM on the dual-core chips. + let heap_size = match (is_dual_core, uplink == Uplink::Both) { + (true, false) => "160 * 1024", + (true, true) => "104 * 1024", + (false, _) => "83 * 1024", + }; // RAM used by the 2nd-stage bootloader is free once the app runs. On the RISC-V // chips it is a separate ~64 KB region, so use it as extra heap for the WiFi/BLE // stacks instead of taking more from the shared stack/heap SRAM. @@ -1140,11 +1140,21 @@ mod lte_tests { } #[test] - fn one_uplink_per_build() { + fn uplinks_from_the_config() { assert_eq!(select_uplink(true, false, false, false), Ok(Uplink::Wifi)); assert_eq!(select_uplink(false, true, true, false), Ok(Uplink::Lte)); assert_eq!(select_uplink(false, false, true, false), Ok(Uplink::None)); - assert!(select_uplink(true, true, true, false).is_err()); + assert_eq!(select_uplink(true, true, true, false), Ok(Uplink::Both)); + assert!(select_uplink(true, true, false, false).is_err()); + } + + #[test] + fn relay_prefers_wifi_and_falls_back_to_lte() { + let both = mqtt_driver_spawn_code(Uplink::Both); + assert!(both.contains(" net_stack,\n Some(lte_stack),\n")); + for single in [Uplink::Wifi, Uplink::Lte] { + assert!(mqtt_driver_spawn_code(single).contains(" net_stack,\n None,\n")); + } } #[test] @@ -1162,6 +1172,7 @@ mod lte_tests { #[test] fn can_logger_needs_wifi() { assert_eq!(select_uplink(true, false, false, true), Ok(Uplink::Wifi)); + assert_eq!(select_uplink(true, true, true, true), Ok(Uplink::Both)); assert!(select_uplink(false, true, true, true).is_err()); assert!(select_uplink(false, false, false, true).is_err()); } @@ -1200,8 +1211,9 @@ mod lte_tests { let code = lte_init_code(&modem( "kind = \"sim7670g\"\nuart_tx_pin = 11\nuart_rx_pin = 10\n\ pwrkey_pin = 18\nreset_pin = 17\ndtr_pin = 9", - )) + ), "lte_stack") .unwrap(); + assert!(code.starts_with(" let lte_stack = board_esp::init_lte(")); assert!(code.contains("new_modem_uart(peripherals.UART1, peripherals.GPIO11, peripherals.GPIO10, 115200)")); assert!(code.contains("power_enable: None,")); assert!(code.contains("pwrkey: Some(board_esp::ControlPin::new(peripherals.GPIO18, true)),")); @@ -1212,10 +1224,10 @@ mod lte_tests { #[test] fn unknown_modem_and_bad_levels_are_rejected() { - assert!(lte_init_code(&modem("kind = \"bg96\"\nuart_tx_pin = 1\nuart_rx_pin = 2")).is_err()); + assert!(lte_init_code(&modem("kind = \"bg96\"\nuart_tx_pin = 1\nuart_rx_pin = 2"), "net_stack").is_err()); assert!(lte_init_code(&modem( "kind = \"sim7670g\"\nuart_tx_pin = 1\nuart_rx_pin = 2\npwrkey_pin = 3\npwrkey_level = \"up\"" - )) + ), "net_stack") .is_err()); } @@ -1231,6 +1243,6 @@ mod lte_tests { .unwrap(); let esp: EspConfig = profile["hardware"]["esp"].clone().try_into().unwrap(); assert_eq!(esp.mcu, "esp32s3"); - assert!(lte_init_code(esp.modem.as_ref().unwrap()).is_ok()); + assert!(lte_init_code(esp.modem.as_ref().unwrap(), "net_stack").is_ok()); } } diff --git a/boards/pc/src/lib.rs b/boards/pc/src/lib.rs index b7bcc88..976c18b 100644 --- a/boards/pc/src/lib.rs +++ b/boards/pc/src/lib.rs @@ -21,7 +21,6 @@ pub use secure_keys::{client_keys_store_task, restore_secure_keys}; pub fn start(spawner: &embassy_executor::Spawner) { spawner.spawn(core_interface::process_ble_commands_task().unwrap()); - spawner.spawn(core_interface::process_mqtt_commands_task().unwrap()); spawner.spawn(core_interface::route_responses_task().unwrap()); spawner.spawn(core_interface::publish_state_task().unwrap()); spawner.spawn(core_interface::publish_can_access_task().unwrap()); diff --git a/boards/pc/src/network.rs b/boards/pc/src/network.rs index 62a7b4d..04cc24d 100644 --- a/boards/pc/src/network.rs +++ b/boards/pc/src/network.rs @@ -1,7 +1,6 @@ use std::sync::Arc; -use core_interface::{MQTT_RX_CHANNEL, MQTT_STATE_TX, MQTT_TX_CHANNEL, MqttTls, Transport, proto}; -use prost::Message as _; +use core_interface::MqttTls; use rust_mqtt::{ Bytes, buffer::AllocBuffer, @@ -61,21 +60,30 @@ impl embedded_io_async::Write for NonBlocking } } -/// Shared MQTT session logic. Authenticates (if credentials provided), -/// subscribes, then drives inbound/outbound message exchange until an error -/// occurs, at which point it returns `Err(())` so the caller reconnects. +/// How long the driver waits for an inbound packet before it checks for frames to send. +const POLL_MS: u64 = 100; + +/// One session with the broker for the relay (docs/mqtt-relay.md in the contracts): +/// connects with the device's client ID, subscribes to its device topics, then moves +/// secure channel frames both ways until an error, at which point it returns `Err(())` +/// so the caller reconnects. Nothing but frames is sent or accepted. async fn run_mqtt_session( transport: NonBlockingTcpStream, - client_id: &'static str, - cmd_topic: &'static str, - data_topic: &'static str, username: &'static str, password: &'static str, ) -> Result<(), ()> { use embassy_time::{Duration, Instant}; + let (Some(client_id), Some(filter)) = ( + core_interface::relay_client_id(), + core_interface::relay_subscribe_filter(), + ) else { + log::warn!("MQTT: no device identity yet"); + return Err(()); + }; + let mut buffer = AllocBuffer; - let mut client = Client::<_, _, 1, 1, 1, 0>::new(&mut buffer); + let mut client = Client::<_, _, 1, 4, 4, 0>::new(&mut buffer); let mut connect_opts = ConnectOptions::new().clean_start(); if !username.is_empty() { @@ -88,97 +96,118 @@ async fn run_mqtt_session( .connect( transport, &connect_opts, - Some(MqttString::from_str_unchecked(client_id)), + Some(MqttString::from_str_unchecked(&client_id)), ) .await .map_err(|e| { log::warn!("MQTT: connect failed: {:?}", e); })?; - log::info!("MQTT: connected, subscribing to '{}'", cmd_topic); + log::info!("MQTT: connected as '{client_id}', subscribing to '{filter}'"); - let filter = TopicFilter::new_unchecked(MqttString::from_str_unchecked(cmd_topic)); + let topic_filter = TopicFilter::new_unchecked(MqttString::from_str_unchecked(&filter)); client - .subscribe(filter, SubscriptionOptions::new()) + .subscribe(topic_filter, SubscriptionOptions::new().at_least_once()) .await .map_err(|e| { log::warn!("MQTT: subscribe failed: {:?}", e); })?; - log::info!("MQTT: ready"); - core_interface::set_link_up(Transport::Mqtt, true); - - let keepalive = Duration::from_secs(55); - let mut last_ping = Instant::now(); - let data_topic_name = TopicName::new_unchecked(MqttString::from_str_unchecked(data_topic)); + let Some(relay) = core_interface::relay_connect() else { + return Err(()); + }; + log::info!("MQTT: relay ready"); - loop { - // Drain outbound before polling inbound: responses and system state - // first, then the newest vehicle state. - while let Some(msg) = MQTT_TX_CHANNEL - .try_receive() - .ok() - .or_else(|| MQTT_STATE_TX.try_take()) - { - let mut buf = Vec::new(); - if msg.encode(&mut buf).is_ok() { - let t = data_topic_name.as_borrowed(); - let pub_opts = PublicationOptions::new(TopicReference::Name(t)); - client - .publish(&pub_opts, Bytes::Borrowed(buf.as_slice())) + let result = async { + let keepalive = Duration::from_secs(55); + let mut last_ping = Instant::now(); + // A frame the client couldn't take yet (too many publications waiting for their + // PUBACK): sent once the broker acknowledges one. + let mut pending: Option = None; + loop { + // Publish what is ready before polling inbound: responses and system state + // first, then the vehicle state, as the relay decides. + loop { + let Some(frame) = pending.take().or_else(|| { + core_interface::relay_try_next_frame(relay, Instant::now().as_millis()) + }) else { + break; + }; + let topic = TopicName::new_unchecked(MqttString::from_str_unchecked(&frame.topic)); + let pub_opts = PublicationOptions::new(TopicReference::Name(topic)).at_least_once(); + match client + .publish(&pub_opts, Bytes::Borrowed(frame.frame.as_slice())) .await - .map_err(|e| { + { + Ok(_) => {} + Err(MqttError::SendQuotaExceeded | MqttError::SessionBuffer) => { + pending = Some(frame); + break; + } + Err(e) => { log::warn!("MQTT: publish failed: {:?}", e); - })?; + return Err(()); + } + } } - } - // Keepalive ping - if last_ping.elapsed() >= keepalive { - client.ping().await.map_err(|e| { - log::warn!("MQTT: ping failed: {:?}", e); - })?; - last_ping = Instant::now(); - } + if last_ping.elapsed() >= keepalive { + client.ping().await.map_err(|e| { + log::warn!("MQTT: ping failed: {:?}", e); + })?; + last_ping = Instant::now(); + } - // Poll for inbound with 100 ms timeout - let poll_result = - embassy_time::with_timeout(Duration::from_millis(100), client.poll()).await; + let poll_result = + embassy_time::with_timeout(Duration::from_millis(POLL_MS), client.poll()).await; - match poll_result { - Err(_timeout) => continue, - Ok(Err(e)) => { - log::warn!("MQTT: poll error: {:?}", e); - // abort() panics if the broker sent a clean DISCONNECT - // (e.g. SessionTakenOver) because the network is still in - // Ok state. Only call it for IO/protocol errors. - if !matches!(e, MqttError::Disconnect { .. }) { - client.abort().await; + match poll_result { + Err(_timeout) => continue, + Ok(Err(e)) => { + log::warn!("MQTT: poll error: {:?}", e); + // abort() panics if the broker sent a clean DISCONNECT + // (e.g. SessionTakenOver) because the network is still in + // Ok state. Only call it for IO/protocol errors. + if !matches!(e, MqttError::Disconnect { .. }) { + client.abort().await; + } + return Err(()); } - return Err(()); - } - Ok(Ok(Event::Publish(p))) => { - if p.topic.as_ref().as_str() == cmd_topic { - let payload = p.message.as_bytes(); - if let Ok(msg) = proto::AppToDevice::decode(payload) { - // Use try_send to avoid blocking here. If we blocked on - // MQTT_RX_CHANNEL.send().await while downstream tasks are - // simultaneously blocked on BASIC_CMD_CHANNEL and - // CMD_RESP_CHANNEL, route_responses_task would be stuck - // trying to send to MQTT_TX_CHANNEL — which we can't drain - // because we're blocked. That forms a deadlock cycle. - // Dropping one inbound command under back-pressure is safe; - // the app can retry. What we must never do is stall the - // outbound drain loop. - if MQTT_RX_CHANNEL.try_send(msg).is_err() { - log::warn!("MQTT: RX channel full, dropping inbound command"); + Ok(Ok(Event::Publish(p))) => { + // Never blocks on a downstream queue: the dispatcher answers through + // the session's queue with try_send (see docs/architecture.md). + let topic = String::from(p.topic.as_ref().as_str()); + let payload = p.message.as_bytes().to_vec(); + drop(p); + let reply = core_interface::relay_receive_frame(relay, &topic, &payload).await; + if let Some(reply) = reply { + let name = + TopicName::new_unchecked(MqttString::from_str_unchecked(&reply.topic)); + let pub_opts = + PublicationOptions::new(TopicReference::Name(name)).at_least_once(); + match client + .publish(&pub_opts, Bytes::Borrowed(reply.frame.as_slice())) + .await + { + Ok(_) => {} + // The client handshakes again after its timeout. + Err(MqttError::SendQuotaExceeded | MqttError::SessionBuffer) => { + log::warn!("MQTT: too many publications in flight, reply dropped"); + } + Err(e) => { + log::warn!("MQTT: publish failed: {:?}", e); + return Err(()); + } } } } + Ok(Ok(_)) => {} } - Ok(Ok(_)) => {} } } + .await; + core_interface::relay_disconnect(relay); + result } /// The rustls client configuration for `tls`: the broker must chain to `ca_pem`; @@ -252,9 +281,6 @@ async fn tls_handshake( pub async fn mqtt_driver_task( broker_host: &'static str, broker_port: u16, - client_id: &'static str, - cmd_topic: &'static str, - data_topic: &'static str, username: &'static str, password: &'static str, tls: Option, @@ -288,29 +314,11 @@ pub async fn mqtt_driver_task( .expect("set_nonblocking failed"); let result = match &tls_config { - None => { - run_mqtt_session( - NonBlockingTcpStream(stream), - client_id, - cmd_topic, - data_topic, - username, - password, - ) - .await - } + None => run_mqtt_session(NonBlockingTcpStream(stream), username, password).await, Some(config) => match tls_handshake(config, broker_host, stream).await { Ok(tls_stream) => { log::info!("MQTT: TLS established"); - run_mqtt_session( - NonBlockingTcpStream(tls_stream), - client_id, - cmd_topic, - data_topic, - username, - password, - ) - .await + run_mqtt_session(NonBlockingTcpStream(tls_stream), username, password).await } Err(e) => { log::warn!("MQTT: TLS handshake failed: {e}"); @@ -321,8 +329,6 @@ pub async fn mqtt_driver_task( if result.is_err() { log::info!("MQTT: session ended, reconnecting in 5s"); } - // Drops what was queued for this session instead of sending it on the next. - core_interface::set_link_up(Transport::Mqtt, false); Timer::after(Duration::from_secs(5)).await; } } diff --git a/boards/pc/xtask_builder.rs b/boards/pc/xtask_builder.rs index 2273405..2fe7a43 100644 --- a/boards/pc/xtask_builder.rs +++ b/boards/pc/xtask_builder.rs @@ -1,6 +1,6 @@ use crate::{ Config, LAUNCH_NAME_PREFIX, RustAnalyzerConfig, TargetBuilder, escape_rust_string, - firmware_dir, load_transport_contract, parse_broker_url, render_topic_from_template, + firmware_dir, load_transport_contract, parse_broker_url, validate_ble_transport_contract, }; use serde::Deserialize; @@ -226,17 +226,6 @@ impl TargetBuilder for Builder { // Generate network constants and MQTT driver spawn let (broker_host, broker_port) = parse_broker_url(&config.network.mqtt.broker_url); - let client_id = &config.network.mqtt.client_id; - let mqtt_cmd_topic = escape_rust_string(&render_topic_from_template( - &transport.mqtt.command_topic_template, - client_id, - "mqtt.command_topic_template", - )); - let mqtt_data_topic = escape_rust_string(&render_topic_from_template( - &transport.mqtt.data_topic_template, - client_id, - "mqtt.data_topic_template", - )); let ble_device_name = pc_hw .ble .device_name @@ -244,7 +233,6 @@ impl TargetBuilder for Builder { .unwrap_or(transport.ble.service.name.as_str()); let ble_device_name = escape_rust_string(ble_device_name); let broker_host = escape_rust_string(&broker_host); - let client_id = escape_rust_string(client_id); let paired_phones_file = escape_rust_string(&pc_hw.ble.paired_phones_file); if pc_hw.ble.max_bonded_phones == 0 || pc_hw.ble.http_port == 0 { @@ -273,9 +261,6 @@ impl TargetBuilder for Builder { const PHONE_VALIDATIONS_FILE: &str = \"{validations_path}\";\n\ const DEVICE_IDENTITY_FILE: &str = \"{identity_path}\";\n\ const CLIENT_KEYS_FILE: &str = \"{client_keys_path}\";\n\ - const MQTT_CLIENT_ID: &str = \"{cid}\";\n\ - const MQTT_CMD_TOPIC: &str = \"{cmd_topic}\";\n\ - const MQTT_DATA_TOPIC: &str = \"{data_topic}\";\n\ const MQTT_USERNAME: &str = \"{user}\";\n\ const MQTT_PASSWORD: &str = \"{pass}\";", host = broker_host, @@ -290,9 +275,6 @@ impl TargetBuilder for Builder { validations_path = escape_rust_string(&pc_hw.phone_validations_file), identity_path = escape_rust_string(&pc_hw.device_identity_file), client_keys_path = escape_rust_string(&pc_hw.client_keys_file), - cid = client_id, - cmd_topic = mqtt_cmd_topic, - data_topic = mqtt_data_topic, user = mqtt_username, pass = mqtt_password, ); @@ -301,14 +283,10 @@ impl TargetBuilder for Builder { .spawn(board_pc::ble_http_task(BLE_HTTP_BIND, BLE_HTTP_PORT, BLE_DEVICE_NAME_BASE, BLE_PAIRING_WINDOW_S).unwrap());\n" .to_string(); - let mqtt_driver_spawn = " core_interface::set_mqtt_client_id(MQTT_CLIENT_ID);\n\ - \x20 spawner\n\ + let mqtt_driver_spawn = " spawner\n\ .spawn(board_pc::mqtt_driver_task(\n\ MQTT_BROKER_HOST,\n\ MQTT_BROKER_PORT,\n\ - MQTT_CLIENT_ID,\n\ - MQTT_CMD_TOPIC,\n\ - MQTT_DATA_TOPIC,\n\ MQTT_USERNAME,\n\ MQTT_PASSWORD,\n\ MQTT_TLS,\n\ diff --git a/cars/egmp/src/lib.rs b/cars/egmp/src/lib.rs index 7e31209..d2ab50f 100644 --- a/cars/egmp/src/lib.rs +++ b/cars/egmp/src/lib.rs @@ -232,7 +232,7 @@ pub(crate) static CAR_STATE: Mutex = /// these so a busy bus produces at most one publish per `STATE_MIN_PUBLISH_INTERVAL`. pub(crate) static STATE_CHANGED: Signal = Signal::new(); -/// Upper bound on how often state is pushed to BLE/MQTT while CAN data is changing. +/// Upper bound on how often state is pushed to BLE and the secure channel while CAN data is changing. const STATE_MIN_PUBLISH_INTERVAL: Duration = Duration::from_millis(250); /// State is re-published at this interval even when nothing changed. const STATE_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5); @@ -346,7 +346,7 @@ pub async fn handle_advanced_commands_task() { /// Decodes an advanced command, checks its requirements /// (`commands::advanced_requirements`) and only then runs it. `authorization` is the one the -/// command came with: `None` (MQTT) can't send the command's frames, so the command fails. +/// command came with: `None` (no validated phone) can't send the command's frames, so the command fails. pub async fn process_advanced_command( bytes: &[u8], authorization: Option, diff --git a/cars/egmp/src/preconditioning.rs b/cars/egmp/src/preconditioning.rs index 2986aeb..e93cc33 100644 --- a/cars/egmp/src/preconditioning.rs +++ b/cars/egmp/src/preconditioning.rs @@ -725,7 +725,7 @@ mod tests { } #[test] - fn mqtt_cannot_start_it() { + fn a_command_without_authorization_cannot_start_it() { open_the_gate(); assert_eq!( command(true, None), diff --git a/cars/virtual-car/src/lib.rs b/cars/virtual-car/src/lib.rs index d587ce7..3734d6e 100644 --- a/cars/virtual-car/src/lib.rs +++ b/cars/virtual-car/src/lib.rs @@ -311,7 +311,7 @@ async fn send_can_request(id: StandardId, data: &[u8]) { } /// state update to `VEHICLE_STATE_CHANNEL`, and sends a `CommandResponse` to -/// `CMD_RESP_CHANNEL`. Both BLE and MQTT may send basic commands. +/// `CMD_RESP_CHANNEL`. Both BLE and the secure channel may send basic commands. #[embassy_executor::task] pub async fn handle_basic_commands_task() { loop { @@ -322,7 +322,7 @@ pub async fn handle_basic_commands_task() { } } -/// `authorization` is the one the command came with: `None` (MQTT) can't send the command's +/// `authorization` is the one the command came with: `None` (no validated phone) can't send the command's /// frame, so the command fails. pub async fn process_basic_command( bytes: &[u8], diff --git a/config.toml.example b/config.toml.example index 5de84c9..5895780 100644 --- a/config.toml.example +++ b/config.toml.example @@ -86,8 +86,9 @@ enabled = true ssid = "YourSSID" password = "YourPassword" -# LTE uplink instead of WiFi (one uplink per build: set [network.wifi].enabled = false). -# Needs a board with a modem, e.g. hardware_profile = "lilygo-t-sim7670g-s3". See docs/lte.md. +# LTE uplink, alone ([network.wifi].enabled = false) or with WiFi: the relay then prefers +# WiFi and falls back to LTE. Needs a board with a modem, e.g. +# hardware_profile = "lilygo-t-sim7670g-s3". See docs/lte.md. # [network.lte] # enabled = true # apn = "your.carrier.apn" @@ -114,15 +115,17 @@ enabled = false mdns = true [network.mqtt] +# The MQTT relay: any broker carries the app's end-to-end encrypted secure channel to the +# device, so the broker never sees the state or the commands (docs/mqtt-relay.md). The +# device's client ID and topics come from its device key ID: nothing to set per device. # mqtts:// is MQTT over TLS (port 8883 by default): the broker's certificate is checked -# against ca_cert_file and its name. mqtt:// is plain TCP (port 1883): state and the -# password travel unencrypted, so only use it on a network you trust. A broker on the -# internet (LTE) should use mqtts:// with auth_mode = "mtls". See docs/mqtt-tls.md. +# against ca_cert_file and its name. mqtt:// is plain TCP (port 1883): the password and +# who talks to the device are visible on the network. TLS and broker authentication are +# optional hardening. broker_url = "mqtt://192.168.0.100:1883" -# Names this device's MQTT topics, and the app learns it over BLE: give each device its own. -client_id = "dev-car" # How the device authenticates to the broker: +# - `none`: no credentials # - `basic`: username and password (inside TLS with mqtts://) # - `mtls`: the client certificate and key below; needs mqtts://. No password is sent. auth_mode = "basic" diff --git a/contracts b/contracts index 3998261..15a063e 160000 --- a/contracts +++ b/contracts @@ -1 +1 @@ -Subproject commit 39982611fec37f98f5221341ef3b77b313445c2a +Subproject commit 15a063ef1a5f0718f51bd014674a5ee2c5f6f240 diff --git a/core-interface/build.rs b/core-interface/build.rs index 7f43659..dbc870b 100644 --- a/core-interface/build.rs +++ b/core-interface/build.rs @@ -15,6 +15,7 @@ fn main() -> Result<()> { generate_phone_validation_constants()?; generate_secure_channel_constants()?; generate_lan_constants()?; + generate_relay_constants()?; Ok(()) } @@ -404,3 +405,86 @@ fn generate_lan_constants() -> Result<()> { ), ) } + +/// The MQTT relay's constants (`[mqtt]`, docs/mqtt-relay.md in the contracts), for +/// `relay.rs`. +fn generate_relay_constants() -> Result<()> { + let toml_str = std::fs::read_to_string("../contracts/opencar/core/v1/transport.toml") + .expect("Failed to read contracts/opencar/core/v1/transport.toml"); + let transport: toml::Value = toml::from_str(&toml_str).expect("Failed to parse transport.toml"); + let mqtt = transport + .get("mqtt") + .expect("transport.toml is missing [mqtt]"); + let int = |key: &str| { + mqtt.get(key) + .and_then(|v| v.as_integer()) + .unwrap_or_else(|| panic!("transport.toml is missing integer mqtt.{key}")) + }; + let string = |key: &str| { + mqtt.get(key) + .and_then(|v| v.as_str()) + .unwrap_or_else(|| { + panic!( + "transport.toml is missing string mqtt.{key}; update the contracts submodule" + ) + }) + .to_string() + }; + let device_topic = string("device_topic_template"); + let device_filter = string("device_topic_filter"); + let client_topic = string("client_topic_template"); + let client_id = string("device_client_id_template"); + // The relay parses the client key ID from the end of the device topic, and fills the + // templates by replacing their placeholders: a change of shape has to change the code. + assert!( + device_topic.ends_with("/{client_key_id}") + && device_topic.matches('{').count() == 2 + && device_topic.replace("{client_key_id}", "+") == device_filter + && client_topic.contains("{device_key_id}") + && client_topic.ends_with("/{client_key_id}") + && client_id.matches('{').count() == 1 + && client_id.contains("{device_key_id}"), + "transport.toml mqtt topic layout changed; update core_interface::relay" + ); + assert!( + int("qos") == 1 && mqtt.get("retain").and_then(|v| v.as_bool()) == Some(false), + "transport.toml mqtt.qos or mqtt.retain changed; update the boards' MQTT drivers" + ); + let heartbeat = int("heartbeat_seconds"); + let activity = int("activity_window_seconds"); + let min_state = int("min_state_interval_ms"); + let idle_state = int("idle_state_interval_seconds"); + let system_repeat = int("system_state_repeat_ms"); + assert!( + heartbeat > 0 + && activity > heartbeat + && min_state >= 0 + && idle_state > 0 + && system_repeat > 0, + "transport.toml mqtt relay timing out of range" + ); + + let out_dir = std::env::var("OUT_DIR").unwrap(); + std::fs::write( + std::path::Path::new(&out_dir).join("relay.rs"), + format!( + "// @generated — do not edit. Source: contracts/opencar/core/v1/transport.toml\n\ + /// Client -> device topic template (`{{device_key_id}}`, `{{client_key_id}}`).\n\ + pub const RELAY_DEVICE_TOPIC_TEMPLATE: &str = {device_topic:?};\n\ + /// The filter the device subscribes to (`{{device_key_id}}`).\n\ + pub const RELAY_DEVICE_TOPIC_FILTER: &str = {device_filter:?};\n\ + /// Device -> client topic template (`{{device_key_id}}`, `{{client_key_id}}`).\n\ + pub const RELAY_CLIENT_TOPIC_TEMPLATE: &str = {client_topic:?};\n\ + /// The device's MQTT client ID template (`{{device_key_id}}`).\n\ + pub const RELAY_DEVICE_CLIENT_ID_TEMPLATE: &str = {client_id:?};\n\ + /// A session with an inbound frame this recently is active.\n\ + pub const RELAY_ACTIVITY_WINDOW_MS: u64 = {activity} * 1_000;\n\ + /// An active session gets a basic state at most this often.\n\ + pub const RELAY_MIN_STATE_INTERVAL_MS: u64 = {min_state};\n\ + /// An idle session gets the newest basic state this often.\n\ + pub const RELAY_IDLE_STATE_INTERVAL_MS: u64 = {idle_state} * 1_000;\n\ + /// A relay session gets a system state at least this often (ms), even unchanged.\n\ + pub const RELAY_SYSTEM_STATE_REPEAT_MS: u64 = {system_repeat};\n" + ), + ) +} diff --git a/core-interface/src/availability.rs b/core-interface/src/availability.rs index e118c42..04e1b5b 100644 --- a/core-interface/src/availability.rs +++ b/core-interface/src/availability.rs @@ -15,10 +15,9 @@ //! - over BLE, every command is unavailable while the connected phone isn't validated for //! this car (`phone_trust.rs`), since the device rejects its vehicle commands. //! -//! MQTT apps are told too, for the basic commands only (advanced commands are BLE only), at -//! the same rate as the MQTT state: every [`COMMAND_AVAILABILITY_REPEAT_MS`] while a client is -//! active, once per MQTT idle period otherwise. MQTT commands are not authenticated yet, so the -//! device rejects every one; until that changes they are all reported unavailable over MQTT. +//! Secure channel sessions (LAN, relay) are told too, about their own client, with the +//! advanced commands always unavailable ([`client_command_availability_at`]): `lan.rs` and +//! `relay.rs` send it when it changes and repeat it at their own rate. //! //! Commands are identified by their field number in the vehicle's command oneof, so this //! module stays vehicle-agnostic. @@ -121,12 +120,6 @@ static LAST_PUBLISHED: Mutex< RefCell>, > = Mutex::new(RefCell::new(None)); -/// The last state queued for MQTT and when, see [`LAST_PUBLISHED`]. -static LAST_MQTT_PUBLISHED: Mutex< - CriticalSectionRawMutex, - RefCell>, -> = Mutex::new(RefCell::new(None)); - /// Reports the availability of every command of `kind`, replacing the previous report for /// that kind. `now_ms` is the report time (`Instant::now().as_millis()`). pub fn report_command_availability_at(kind: CommandKind, entries: &[(u32, State)], now_ms: u64) { @@ -224,64 +217,9 @@ pub fn publish_command_availability(timestamp_ms: u64) -> bool { true } -/// What an MQTT app is told, given what a BLE app is told: the basic commands only, and none -/// of them available while MQTT commands are rejected as unauthenticated. -fn mqtt_view(ble: &proto::CommandAvailability) -> proto::CommandAvailability { - let mut basic = ble.basic.clone(); - if !crate::dispatch::MQTT_COMMANDS_AUTHENTICATED { - for state in basic.values_mut() { - if *state != State::Unsupported as i32 { - *state = State::Unavailable as i32; - } - } - } - proto::CommandAvailability { - basic, - advanced: BTreeMap::new(), - } -} - -/// What an MQTT app is told at `now_ms`, or `None` while the vehicle has not reported. -pub fn mqtt_command_availability_at(now_ms: u64) -> Option { - command_availability_at(now_ms).map(|ble| mqtt_view(&ble)) -} - -/// Queues the availability on MQTT like [`publish_command_availability`] does on BLE, at the -/// MQTT state's rate: while a client is active when it changed or [`COMMAND_AVAILABILITY_REPEAT_MS`] -/// passed, otherwise once per MQTT idle period. `try_send`: never blocks the MQTT driver's -/// queue; a full queue or an MQTT session that is down leaves it unsent, to retry on the -/// next call. -pub fn publish_command_availability_mqtt(timestamp_ms: u64) -> bool { - let Some(availability) = mqtt_command_availability_at(timestamp_ms) else { - return false; - }; - let active = crate::routing::is_mqtt_active((timestamp_ms / 1000) as u32); - let due = LAST_MQTT_PUBLISHED.lock(|last| match last.borrow().as_ref() { - None => true, - Some((sent, sent_at)) => { - let elapsed = timestamp_ms.saturating_sub(*sent_at); - if active { - *sent != availability || elapsed >= COMMAND_AVAILABILITY_REPEAT_MS - } else { - elapsed >= u64::from(crate::routing::MQTT_IDLE_RATE_S) * 1_000 - } - } - }); - if !due { - return false; - } - let msg = command_availability_state_update(timestamp_ms, availability.clone()); - if !crate::routing::try_send_to(crate::types::Transport::Mqtt, msg) { - return false; - } - LAST_MQTT_PUBLISHED.lock(|last| *last.borrow_mut() = Some((availability, timestamp_ms))); - true -} - /// Sends the availability again even if unchanged, e.g. when the app subscribes. pub fn resend_command_availability() { LAST_PUBLISHED.lock(|last| *last.borrow_mut() = None); - LAST_MQTT_PUBLISHED.lock(|last| *last.borrow_mut() = None); CHANGED.signal(()); } @@ -289,11 +227,10 @@ pub fn resend_command_availability() { pub fn reset_command_availability_for_tests() { REPORT.lock(|report| *report.borrow_mut() = Report::default()); LAST_PUBLISHED.lock(|last| *last.borrow_mut() = None); - LAST_MQTT_PUBLISHED.lock(|last| *last.borrow_mut() = None); CHANGED.reset(); } -/// Publishes the availability over BLE and MQTT whenever it changes, and every +/// Publishes the availability over BLE, and tells the secure channel's sessions, whenever it changes, and every /// [`COMMAND_AVAILABILITY_REPEAT_MS`] while it doesn't. Also checks once a second, which /// retries a send that found the queue full and picks up a read-only flip or an expired /// report. @@ -302,9 +239,9 @@ pub async fn publish_command_availability_task() { loop { let now_ms = Instant::now().as_millis(); publish_command_availability(now_ms); - publish_command_availability_mqtt(now_ms); - // LAN sessions compare with what they were last sent when they next send. + // Sessions compare with what they were last sent when they next send. crate::lan::notify_availability(); + crate::relay::notify_availability(); let _ = embassy_futures::select::select(CHANGED.wait(), Timer::after(Duration::from_secs(1))) .await; diff --git a/core-interface/src/can_access.rs b/core-interface/src/can_access.rs index af8a976..c1a6377 100644 --- a/core-interface/src/can_access.rs +++ b/core-interface/src/can_access.rs @@ -289,7 +289,7 @@ pub fn can_access_state() -> proto::CanAccessState { } /// A BLE state update carrying only the system state with [`can_access_state`], the -/// connected phone's [`crate::phone_access_state`], the device's MQTT client ID, its +/// connected phone's [`crate::phone_access_state`], the device's /// identity for the secure channel (`identity.rs`) and its LAN address (`lan.rs`). pub fn can_access_state_update(timestamp_ms: u64) -> proto::DeviceToApp { proto::DeviceToApp { @@ -300,7 +300,6 @@ pub fn can_access_state_update(timestamp_ms: u64) -> proto::DeviceToApp { system_state: Some(proto::SystemState { can_access: Some(can_access_state()), phone_access: crate::phone_trust::phone_access_state(timestamp_ms), - mqtt_client_id: crate::mqtt_client_id().map(Into::into), device_identity: crate::identity::device_identity(), lan_address: crate::lan::lan_address(), ..Default::default() diff --git a/core-interface/src/can_log.rs b/core-interface/src/can_log.rs index e3913ab..38fa143 100644 --- a/core-interface/src/can_log.rs +++ b/core-interface/src/can_log.rs @@ -5,7 +5,7 @@ //! //! * the GVRET parser and frame encoder, //! * a dedicated frame channel ([`CAN_LOG_CHANNEL`]), kept apart from the vehicle and -//! BLE/MQTT queues so a slow SavvyCAN client can never stall them, +//! BLE queues so a slow SavvyCAN client can never stall them, //! * the session state: while a client is connected, the buses are forced read-only and //! the board drivers stop feeding the vehicle (see [`is_can_logging`]). //! diff --git a/core-interface/src/channels.rs b/core-interface/src/channels.rs index 8ecda6a..ec73c3a 100644 --- a/core-interface/src/channels.rs +++ b/core-interface/src/channels.rs @@ -13,21 +13,10 @@ use embassy_sync::signal::Signal; pub static BLE_TX_CHANNEL: Channel = Channel::new(); /// Inbound commands arriving from the BLE driver task. pub static BLE_RX_CHANNEL: Channel = Channel::new(); -/// Outbound command responses and system-state messages toward the MQTT driver task. -/// Only filled while the MQTT session is up, and cleared when it ends (see -/// `set_link_up`). Vehicle state goes through [`MQTT_STATE_TX`] instead. -pub static MQTT_TX_CHANNEL: Channel = - Channel::new(); -/// Inbound commands arriving from the MQTT driver task. -pub static MQTT_RX_CHANNEL: Channel = - Channel::new(); /// The newest vehicle state update for the BLE driver task, not yet sent. Each update /// overwrites the previous one, so state never queues up behind (or pushes out) a /// response. Drivers send `BLE_TX_CHANNEL` first. pub static BLE_STATE_TX: Signal = Signal::new(); -/// The newest vehicle state update for the MQTT driver task, not yet sent (basic state -/// only, already throttled). Like [`BLE_STATE_TX`]. -pub static MQTT_STATE_TX: Signal = Signal::new(); /// Decoded system commands (restart, etc.) for the board to act on. pub static SYSTEM_COMMAND_CHANNEL: Channel = Channel::new(); @@ -35,7 +24,7 @@ pub static SYSTEM_COMMAND_CHANNEL: Channel = Channel::new(); /// Advanced vehicle commands routed to the vehicle task. BLE only. pub static ADVANCED_CMD_CHANNEL: Channel = diff --git a/core-interface/src/dedupe.rs b/core-interface/src/dedupe.rs index 990c5c7..0ad7eed 100644 --- a/core-interface/src/dedupe.rs +++ b/core-interface/src/dedupe.rs @@ -9,9 +9,7 @@ //! //! The source is the transport-verified one, never the app's: the BLE address, or the //! secure channel client's ID, which for a phone is the same `ble:` ID. So a command -//! resent from BLE to the secure channel (or back) is caught. Plain MQTT has no verified -//! source, so its commands are keyed with an empty source and only match other MQTT -//! commands (plain MQTT commands are refused anyway, see `dispatch.rs`). +//! resent from BLE to the secure channel (or back) is caught. use alloc::collections::VecDeque; use alloc::vec::Vec; diff --git a/core-interface/src/dispatch.rs b/core-interface/src/dispatch.rs index 9d50ad0..c2ff37f 100644 --- a/core-interface/src/dispatch.rs +++ b/core-interface/src/dispatch.rs @@ -3,8 +3,7 @@ use alloc::vec::Vec; use portable_atomic::Ordering; use crate::channels::{ - ADVANCED_CMD_CHANNEL, BASIC_CMD_CHANNEL, BLE_RX_CHANNEL, MQTT_RX_CHANNEL, - SYSTEM_COMMAND_CHANNEL, + ADVANCED_CMD_CHANNEL, BASIC_CMD_CHANNEL, BLE_RX_CHANNEL, SYSTEM_COMMAND_CHANNEL, }; use crate::dedupe::is_duplicate_command; use crate::proto; @@ -579,7 +578,7 @@ pub async fn handle_ble_message(msg: proto::AppToDevice) { ) .await; } - // Heartbeat is an MQTT-only concept — silently ignored on BLE. + // Heartbeats are for the relay's throttle: nothing to do over BLE. Some(proto::app_to_device::Payload::Heartbeat(_)) => {} None => {} } @@ -593,90 +592,6 @@ pub async fn process_ble_commands_task() { } } -// ── MQTT Dispatcher ─────────────────────────────────────────────────────────── - -/// Whether commands arriving over MQTT are authenticated. They are not: anyone -/// with the broker credentials (which ship in the app) could publish one, or -/// replay a captured one. Until they are (contracts#8, firmware#16), basic -/// commands from MQTT are rejected. Remove the gate together with this flag. -pub(crate) const MQTT_COMMANDS_AUTHENTICATED: bool = false; - -/// Answers a rejected MQTT command. `try_send`: the MQTT driver must never be -/// stalled by a full queue, and the app can retry or notice the missing reply. -fn send_mqtt_unauthenticated_response(message_id: u64) { - try_send_to( - Transport::Mqtt, - proto::DeviceToApp { - timestamp_ms: embassy_time::Instant::now().as_millis(), - platform_id: crate::PLATFORM_ID.load(Ordering::Relaxed), - payload: Some(proto::device_to_app::Payload::CommandResponse( - proto::CommandResponse { - message_id, - success: false, - error_message: String::from( - "command rejected: commands over MQTT are not authenticated yet, use BLE", - ), - response_data: None, - status_code: proto::CommandStatusCode::Failed as i32, - }, - )), - }, - ); -} - -/// Processes a single `AppToDevice` message arriving from the MQTT driver. -/// Validates `platform_id` and routes `basic_command_bytes` → -/// `BASIC_CMD_CHANNEL` (Transport::Mqtt) once MQTT commands are authenticated; -/// until then they are answered with a failed `CommandResponse` instead. -/// `SystemCommand` and `advanced_command_bytes` are silently dropped — both -/// are restricted to BLE only. That includes the CAN read-write approval and the dev -/// lock: MQTT can never approve or unlock read-write mode. -/// `heartbeat` carries no payload and is not routed; its presence alone resets -/// the MQTT activity window so state updates continue at full rate. -/// A basic command whose `message_id` was seen recently from MQTT (a QoS 1 -/// redelivery) is dropped without an answer; see `dedupe.rs`. -pub async fn handle_mqtt_message(msg: proto::AppToDevice) { - if msg.platform_id != crate::PLATFORM_ID.load(Ordering::Relaxed) { - return; - } - // Any valid inbound MQTT message (command or app heartbeat) keeps the - // activity window alive so state updates flow at full rate. - crate::routing::record_mqtt_activity((embassy_time::Instant::now().as_millis() / 1000) as u32); - if let Some(proto::app_to_device::Payload::BasicCommandBytes(bytes)) = msg.payload { - // No verified source over MQTT yet, so the key is the message ID alone. - if is_duplicate_command(&[], msg.message_id) { - return; - } - if !MQTT_COMMANDS_AUTHENTICATED { - send_mqtt_unauthenticated_response(msg.message_id); - return; - } - if let Some(rejection) = read_only_rejection(msg.message_id) { - try_send_to(Transport::Mqtt, rejection); - return; - } - BASIC_CMD_CHANNEL - .sender() - .send(InboundCommand { - message_id: msg.message_id, - transport: Transport::Mqtt, - source_device_id: Vec::new(), - bytes, - // MQTT has no phone identity, so it can never send a command's frames. - authorization: None, - }) - .await; - } -} - -#[embassy_executor::task] -pub async fn process_mqtt_commands_task() { - let receiver = MQTT_RX_CHANNEL.receiver(); - loop { - handle_mqtt_message(receiver.receive().await).await; - } -} - // ── Secure channel dispatcher ───────────────────────────────────────────────── /// Processes a single `AppToDevice` that a secure channel session carried diff --git a/core-interface/src/lan.rs b/core-interface/src/lan.rs index a027bd3..ccdcd91 100644 --- a/core-interface/src/lan.rs +++ b/core-interface/src/lan.rs @@ -8,7 +8,7 @@ //! so or the peer leaves ([`lan_close`]). All the crypto, and what each session is sent, //! is here: //! - command responses for a session, queued per connection (never waited on); -//! - the basic vehicle state only, like MQTT (the newest one, overwritten while unsent): the +//! - the basic vehicle state only, like the relay (the newest one, overwritten while unsent): the //! LAN is the remote tier, being on the network is no proof of being at the car; //! - a system state with the session's client's command availability and the device's //! LAN address, when the session starts, when either changes, and every @@ -244,6 +244,7 @@ pub fn set_lan_address(address: Option<&str>) { if changed { crate::can_access::resend_can_access_state(); for_each_open(|slot| slot.system_due = true); + crate::relay::notify_system(); } } @@ -265,7 +266,7 @@ fn system_state_for(client_id: &[u8], now_ms: u64) -> Option (state.command_availability.is_some() || state.lan_address.is_some()).then_some(state) } -/// `msg` without its advanced state: the LAN gets the basic state only, like MQTT. +/// `msg` without its advanced state: the LAN gets the basic state only, like the relay. fn basic_only(mut msg: proto::DeviceToApp) -> proto::DeviceToApp { if let Some(proto::device_to_app::Payload::StateUpdate(update)) = &mut msg.payload && let Some(vehicle) = &mut update.vehicle_state diff --git a/core-interface/src/lib.rs b/core-interface/src/lib.rs index a6c0ceb..abf2904 100644 --- a/core-interface/src/lib.rs +++ b/core-interface/src/lib.rs @@ -25,6 +25,7 @@ mod mqtt_tls; mod noise; mod pairing; mod phone_trust; +mod relay; mod requirements; mod routing; mod secure_channel; @@ -35,10 +36,6 @@ mod validation; pub mod ble; -use core::cell::Cell; - -use embassy_sync::blocking_mutex::Mutex; -use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; use portable_atomic::{AtomicU32, Ordering}; // ── Platform ID ─────────────────────────────────────────────────────────────── @@ -58,23 +55,6 @@ pub fn platform_id() -> u32 { PLATFORM_ID.load(Ordering::Relaxed) } -// ── MQTT client ID ──────────────────────────────────────────────────────────── - -static MQTT_CLIENT_ID: Mutex>> = - Mutex::new(Cell::new(None)); - -/// Called once at boot by the generated `main.rs` of a build with MQTT, with the -/// `network.mqtt.client_id` its topics are built from. The app learns it over BLE -/// to use the same topics. -pub fn set_mqtt_client_id(client_id: &'static str) { - MQTT_CLIENT_ID.lock(|id| id.set(Some(client_id))); -} - -/// The device's MQTT client ID, or `None` when it has no MQTT. -pub(crate) fn mqtt_client_id() -> Option<&'static str> { - MQTT_CLIENT_ID.lock(Cell::get) -} - // ── Public re-exports ───────────────────────────────────────────────────────── // Types @@ -84,9 +64,8 @@ pub use types::{CanFilter, CanFrame, InboundCommand, Transport, VehicleStatePayl // Channels pub use channels::{ ADVANCED_CMD_CHANNEL, BASIC_CMD_CHANNEL, BLE_RX_CHANNEL, BLE_STATE_TX, BLE_TX_CHANNEL, - CAN_RX_CHANNEL, CAN_TX_CHANNELS, CMD_RESP_CHANNEL, MAX_CAN_BUSES, MQTT_RX_CHANNEL, - MQTT_STATE_TX, MQTT_TX_CHANNEL, RESTART_RESPONSE_GRACE, SYSTEM_COMMAND_CHANNEL, - VEHICLE_STATE_CHANNEL, can_tx_channel, send_can_frame, + CAN_RX_CHANNEL, CAN_TX_CHANNELS, CMD_RESP_CHANNEL, MAX_CAN_BUSES, RESTART_RESPONSE_GRACE, + SYSTEM_COMMAND_CHANNEL, VEHICLE_STATE_CHANNEL, can_tx_channel, send_can_frame, }; // CAN TX classes (platform frames, command frames) @@ -138,10 +117,9 @@ pub use can_log::{ pub use availability::{ COMMAND_AVAILABILITY_REPEAT_MS, CommandKind, REPORT_MAX_AGE_MS, ble_command_availability_at, client_command_availability_at, command_availability, command_availability_at, - command_availability_state_update, mqtt_command_availability_at, publish_command_availability, - publish_command_availability_mqtt, publish_command_availability_task, - report_command_availability, report_command_availability_at, resend_command_availability, - reset_command_availability_for_tests, + command_availability_state_update, publish_command_availability, + publish_command_availability_task, report_command_availability, report_command_availability_at, + resend_command_availability, reset_command_availability_for_tests, }; // Command requirements @@ -174,8 +152,19 @@ pub use secure_channel::{ MAX_SESSION_MS, MAX_SESSIONS, MAX_SESSIONS_PER_CLIENT, PROLOGUE_LABEL, REPLAY_WINDOW, SECURE_TX_CHANNEL, SESSION_BYTES, SESSION_IDLE_TIMEOUT_MS, SessionHandle, TRANSPORT_HEADER_BYTES, close_link, expire_secure_sessions, has_open_session, is_session_open, - newest_session, on_frame, process_secure_frame, reset_secure_channel_for_tests, seal, - secure_session_count, + newest_session, on_frame, on_frame_from, process_secure_frame, process_secure_frame_from, + reset_secure_channel_for_tests, seal, secure_session_count, session_by_id, session_client_id, + session_client_key_id, session_last_received_ms, +}; + +// MQTT relay (the secure channel over any MQTT broker) +pub use relay::{ + RELAY_ACTIVITY_WINDOW_MS, RELAY_CLIENT_TOPIC_TEMPLATE, RELAY_DEVICE_CLIENT_ID_TEMPLATE, + RELAY_DEVICE_TOPIC_FILTER, RELAY_DEVICE_TOPIC_TEMPLATE, RELAY_IDLE_STATE_INTERVAL_MS, + RELAY_MIN_STATE_INTERVAL_MS, RELAY_SYSTEM_STATE_REPEAT_MS, RelayConnection, RelayFrame, + relay_client_id, relay_client_key_id_from_topic, relay_connect, relay_disconnect, + relay_is_connected, relay_receive_frame, relay_session_count, relay_subscribe_filter, + relay_try_next_frame, relay_wait, reset_relay_for_tests, }; // LAN direct (the secure channel over TCP on the local network, UDP discovery) @@ -224,16 +213,15 @@ pub use dedupe::{ // Dispatch tasks pub use dispatch::{ - handle_ble_message, handle_mqtt_message, handle_secure_message, process_ble_commands_task, - process_mqtt_commands_task, reset_ble_controller_lease_for_tests, - set_ble_controller_lease_ttl_s, + handle_ble_message, handle_secure_message, process_ble_commands_task, + reset_ble_controller_lease_for_tests, set_ble_controller_lease_ttl_s, }; // Routing tasks pub use routing::{ ble_state_update, is_link_up, latest_ble_state, publish_single_state, publish_state_task, - record_mqtt_activity, reset_latest_ble_state_for_tests, reset_links_for_tests, - reset_mqtt_throttle_for_tests, route_responses_task, route_single_response, set_link_up, + reset_latest_ble_state_for_tests, reset_links_for_tests, route_responses_task, + route_single_response, set_link_up, }; // Simulation diff --git a/core-interface/src/mqtt_tls.rs b/core-interface/src/mqtt_tls.rs index 99326a6..90ee73c 100644 --- a/core-interface/src/mqtt_tls.rs +++ b/core-interface/src/mqtt_tls.rs @@ -1,7 +1,7 @@ //! The TLS settings of the MQTT connection, shared by the boards' MQTT drivers. //! //! Today xtask compiles them into the image from `[network.mqtt]` (see -//! `docs/mqtt-tls.md`). The setup wizard will later write them to the device over +//! `docs/mqtt-relay.md`). The setup wizard will later write them to the device over //! BLE; the drivers only see this type, so where the bytes come from can change //! without touching them. diff --git a/core-interface/src/relay.rs b/core-interface/src/relay.rs new file mode 100644 index 0000000..14dcde3 --- /dev/null +++ b/core-interface/src/relay.rs @@ -0,0 +1,403 @@ +//! The MQTT relay (docs/mqtt-relay.md in the contracts): any MQTT broker carries secure +//! channel frames between the app and the device, one frame per MQTT message. The broker +//! is an untrusted pipe: nothing but secure channel frames is accepted from it. +//! +//! The board's MQTT driver stays dumb, like the LAN server: on each broker session it +//! calls [`relay_connect`], subscribes to [`relay_subscribe_filter`] with +//! [`relay_client_id`], hands every message to [`relay_receive_frame`] with its topic, and +//! publishes what that returns and what [`relay_try_next_frame`] gives it. When the broker +//! session ends it calls [`relay_disconnect`], which ends the relay's sessions: clients get +//! an unknown session frame and handshake again. All the crypto, and what each session is +//! sent, is here: +//! - command responses, from [`crate::SECURE_TX_CHANNEL`]; +//! - the system state (command availability, LAN address) when a session starts, when it +//! changes, and every [`RELAY_SYSTEM_STATE_REPEAT_MS`]; +//! - the basic vehicle state, throttled for mobile data: at most every +//! [`RELAY_MIN_STATE_INTERVAL_MS`] while the session is active (an inbound frame, such as +//! the app's heartbeat, within [`RELAY_ACTIVITY_WINDOW_MS`]), every +//! [`RELAY_IDLE_STATE_INTERVAL_MS`] otherwise. +//! +//! Each client has its own pair of topics, named by its key ID: the device answers on the +//! client topic of the topic a frame came in on, and the secure channel drops a handshake +//! whose key doesn't match it. State goes to each client's newest session only. + +use alloc::string::String; +use alloc::vec::Vec; +use core::cell::RefCell; + +use embassy_sync::blocking_mutex::Mutex; +use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; +use embassy_sync::signal::Signal; +use portable_atomic::{AtomicU32, Ordering}; + +use crate::proto; +use crate::secure_channel::{ + ChannelLink, FRAME_HANDSHAKE_RESPONSE, FRAME_HEADER_BYTES, SECURE_TX_CHANNEL, SessionHandle, +}; + +include!(concat!(env!("OUT_DIR"), "/relay.rs")); + +/// The device's session with the broker, given by [`relay_connect`]. Stale once the +/// session ended or another one started. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RelayConnection { + generation: u32, +} + +impl RelayConnection { + /// The secure channel link of this broker session. + pub fn link(self) -> ChannelLink { + ChannelLink::relay(self.generation) + } +} + +/// A frame to publish: its topic and payload. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RelayFrame { + pub topic: String, + pub frame: Vec, +} + +/// The newest session of one client on the relay, and what it was sent. +struct RelaySession { + session: SessionHandle, + client_key_id: String, + client_id: Vec, + /// A vehicle state newer than the last one sent is waiting. + state_due: bool, + last_state_ms: Option, + /// The system state has to be sent even if unchanged. + system_due: bool, + /// The availability may have changed: compare it with the last one sent. + availability_check: bool, + last_system: Option<(proto::SystemState, u64)>, +} + +struct Relay { + /// 0 while there is no broker session. + generation: u32, + sessions: Vec, +} + +static RELAY: Mutex> = Mutex::new(RefCell::new(Relay { + generation: 0, + sessions: Vec::new(), +})); + +static NEXT_GENERATION: AtomicU32 = AtomicU32::new(1); + +/// Something may be ready to publish. +static RELAY_WAKE: Signal = Signal::new(); + +pub(crate) fn wake() { + RELAY_WAKE.signal(()); +} + +/// Waits until something may be ready to publish (a response, a state), for a driver that +/// would rather not poll [`relay_try_next_frame`]. Spurious wake-ups are possible. +pub async fn relay_wait() { + RELAY_WAKE.wait().await; +} + +fn device_key_id() -> Option { + crate::identity::device_identity().map(|identity| identity.key_id) +} + +/// The MQTT client ID the device connects with, `None` while it has no identity (the +/// relay can't run without one). +pub fn relay_client_id() -> Option { + Some(RELAY_DEVICE_CLIENT_ID_TEMPLATE.replace("{device_key_id}", &device_key_id()?)) +} + +/// The topic filter the device subscribes to: every client's device topic. +pub fn relay_subscribe_filter() -> Option { + Some(RELAY_DEVICE_TOPIC_FILTER.replace("{device_key_id}", &device_key_id()?)) +} + +fn client_topic(device_key_id: &str, client_key_id: &str) -> String { + RELAY_CLIENT_TOPIC_TEMPLATE + .replace("{device_key_id}", device_key_id) + .replace("{client_key_id}", client_key_id) +} + +/// The client key ID a device topic names, if `topic` is one of this device's: the +/// template's last level, `key_id_bytes` bytes in lowercase hex. +pub fn relay_client_key_id_from_topic(topic: &str) -> Option<&str> { + let device = device_key_id()?; + let prefix = RELAY_DEVICE_TOPIC_TEMPLATE + .replace("{device_key_id}", &device) + .replace("{client_key_id}", ""); + let id = topic.strip_prefix(prefix.as_str())?; + let valid = id.len() == crate::secure_channel::DEVICE_KEY_ID_BYTES * 2 + && id.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')); + valid.then_some(id) +} + +fn is_current(conn: RelayConnection) -> bool { + conn.generation != 0 && RELAY.lock(|relay| relay.borrow().generation == conn.generation) +} + +/// Ends the current broker session's channel sessions, and forgets them. +fn end_current() { + let previous = RELAY.lock(|relay| { + let mut relay = relay.borrow_mut(); + relay.sessions.clear(); + core::mem::take(&mut relay.generation) + }); + if previous != 0 { + crate::secure_channel::close_link(ChannelLink::relay(previous)); + } + while SECURE_TX_CHANNEL.try_receive().is_ok() {} +} + +/// A broker session started (connected and subscribed): returns its handle, `None` while +/// the device has no identity. Ends what the previous broker session carried. +pub fn relay_connect() -> Option { + device_key_id()?; + end_current(); + let generation = NEXT_GENERATION.fetch_add(1, Ordering::Relaxed).max(1); + RELAY.lock(|relay| relay.borrow_mut().generation = generation); + Some(RelayConnection { generation }) +} + +/// The broker session ended: its channel sessions end with it. Nothing happens if `conn` +/// is already stale. +pub fn relay_disconnect(conn: RelayConnection) { + if is_current(conn) { + end_current(); + } +} + +/// Whether `conn` is the current broker session. +pub fn relay_is_connected(conn: RelayConnection) -> bool { + is_current(conn) +} + +/// Hands one message received on `topic` to the secure channel and the dispatcher. +/// Returns the frame to publish back, if any. A message on a topic that isn't a device +/// topic of this device is ignored. +pub async fn relay_receive_frame( + conn: RelayConnection, + topic: &str, + frame: &[u8], +) -> Option { + if !is_current(conn) { + return None; + } + let client_key_id = relay_client_key_id_from_topic(topic)?; + let device = device_key_id()?; + let reply = + crate::secure_channel::process_secure_frame_from(conn.link(), frame, Some(client_key_id)) + .await?; + if reply.first() == Some(&FRAME_HANDSHAKE_RESPONSE) && reply.len() >= FRAME_HEADER_BYTES { + let session_id: [u8; 4] = reply[1..FRAME_HEADER_BYTES].try_into().ok()?; + if let Some(session) = crate::secure_channel::session_by_id(conn.link(), &session_id) + && let Some(client_id) = crate::secure_channel::session_client_id(session) + { + start_session(conn, session, client_key_id, client_id); + } + } + Some(RelayFrame { + topic: client_topic(&device, client_key_id), + frame: reply, + }) +} + +/// A session started: it replaces that client's previous one for what isn't an answer. +fn start_session( + conn: RelayConnection, + session: SessionHandle, + client_key_id: &str, + client_id: Vec, +) { + RELAY.lock(|relay| { + let mut relay = relay.borrow_mut(); + if relay.generation != conn.generation { + return; + } + relay.sessions.retain(|s| s.client_key_id != client_key_id); + relay.sessions.push(RelaySession { + session, + client_key_id: String::from(client_key_id), + client_id, + state_due: true, + last_state_ms: None, + system_due: true, + availability_check: false, + last_system: None, + }); + }); + wake(); +} + +/// Marks every session, and wakes the driver. +fn for_each_session(mut mark: impl FnMut(&mut RelaySession)) { + let any = RELAY.lock(|relay| { + let mut relay = relay.borrow_mut(); + relay.sessions.iter_mut().for_each(&mut mark); + !relay.sessions.is_empty() + }); + if any { + wake(); + } +} + +/// A new vehicle state was published (`routing.rs`). +pub(crate) fn notify_state() { + for_each_session(|s| s.state_due = true); +} + +/// The command availability may have changed, or is due again (`availability.rs`). +pub(crate) fn notify_availability() { + for_each_session(|s| s.availability_check = true); +} + +/// The system state changed (the LAN address). +pub(crate) fn notify_system() { + for_each_session(|s| s.system_due = true); +} + +/// What to send a session next, decided under the lock. +enum Next { + System(SessionHandle, String, proto::SystemState), + State(SessionHandle, String), +} + +/// The system state for a session of `client_id` at `now_ms`, `None` while there is +/// nothing to say. +fn system_state_for(client_id: &[u8], now_ms: u64) -> Option { + let state = proto::SystemState { + command_availability: crate::availability::client_command_availability_at( + client_id, now_ms, + ), + lan_address: crate::lan::lan_address(), + ..Default::default() + }; + (state.command_availability.is_some() || state.lan_address.is_some()).then_some(state) +} + +/// Picks what is due for the sessions at `now_ms`: a system state first, then a vehicle +/// state, one session after the other. Drops the sessions that ended. +fn next_due(conn: RelayConnection, now_ms: u64, has_state: bool) -> Option { + RELAY.lock(|relay| { + let mut relay = relay.borrow_mut(); + if relay.generation != conn.generation { + return None; + } + relay + .sessions + .retain(|s| crate::secure_channel::is_session_open(s.session)); + for s in relay.sessions.iter_mut() { + let (forced, check) = (s.system_due, s.availability_check); + let repeat = s.last_system.as_ref().is_none_or(|(_, sent_at)| { + now_ms.saturating_sub(*sent_at) >= RELAY_SYSTEM_STATE_REPEAT_MS + }); + if forced || check || repeat { + s.system_due = false; + s.availability_check = false; + if let Some(state) = system_state_for(&s.client_id, now_ms) { + let unchanged = s.last_system.as_ref().map(|(sent, _)| sent) == Some(&state); + if forced || repeat || !unchanged { + s.last_system = Some((state.clone(), now_ms)); + return Some(Next::System(s.session, s.client_key_id.clone(), state)); + } + } + } + } + if !has_state { + return None; + } + for s in relay.sessions.iter_mut() { + if !s.state_due { + continue; + } + let active = crate::secure_channel::session_last_received_ms(s.session) + .is_some_and(|at| now_ms.saturating_sub(at) <= RELAY_ACTIVITY_WINDOW_MS); + let interval = if active { + RELAY_MIN_STATE_INTERVAL_MS + } else { + RELAY_IDLE_STATE_INTERVAL_MS + }; + if s.last_state_ms + .is_none_or(|at| now_ms.saturating_sub(at) >= interval) + { + s.state_due = false; + s.last_state_ms = Some(now_ms); + return Some(Next::State(s.session, s.client_key_id.clone())); + } + } + None + }) +} + +/// `msg` without its advanced state: the relay gets the basic state only. +fn basic_only(mut msg: proto::DeviceToApp) -> proto::DeviceToApp { + if let Some(proto::device_to_app::Payload::StateUpdate(update)) = &mut msg.payload + && let Some(vehicle) = &mut update.vehicle_state + { + vehicle.advanced_state_bytes.clear(); + } + msg +} + +fn system_update(timestamp_ms: u64, state: proto::SystemState) -> proto::DeviceToApp { + proto::DeviceToApp { + timestamp_ms, + platform_id: crate::platform_id(), + payload: Some(proto::device_to_app::Payload::StateUpdate( + proto::StateUpdate { + system_state: Some(state), + vehicle_state: None, + }, + )), + } +} + +/// The next frame to publish on `conn` at `now_ms`, without waiting: a command response +/// first, then a system state when due, then a vehicle state when due and allowed by the +/// throttle. `None` when there is nothing to send (or `conn` is stale). +pub fn relay_try_next_frame(conn: RelayConnection, now_ms: u64) -> Option { + if !is_current(conn) { + return None; + } + let device = device_key_id()?; + while let Ok((session, msg)) = SECURE_TX_CHANNEL.try_receive() { + let Some(client_key_id) = crate::secure_channel::session_client_key_id(session) else { + continue; + }; + if let Some((link, frame)) = crate::secure_channel::seal(session, &msg, now_ms) + && link == conn.link() + { + return Some(RelayFrame { + topic: client_topic(&device, &client_key_id), + frame, + }); + } + } + let latest = crate::routing::latest_ble_state(); + loop { + let (session, client_key_id, msg) = match next_due(conn, now_ms, latest.is_some())? { + Next::System(session, key, state) => (session, key, system_update(now_ms, state)), + Next::State(session, key) => (session, key, basic_only(latest.clone()?)), + }; + // A session that ended since: try the next one. + if let Some((_, frame)) = crate::secure_channel::seal(session, &msg, now_ms) { + return Some(RelayFrame { + topic: client_topic(&device, &client_key_id), + frame, + }); + } + } +} + +/// The number of sessions the relay sends state to (each client's newest). For tests and +/// logs. +pub fn relay_session_count() -> usize { + RELAY.lock(|relay| relay.borrow().sessions.len()) +} + +/// Ends the broker session and forgets everything. For tests only. +pub fn reset_relay_for_tests() { + end_current(); + RELAY_WAKE.reset(); +} diff --git a/core-interface/src/requirements.rs b/core-interface/src/requirements.rs index 5492725..67ab58e 100644 --- a/core-interface/src/requirements.rs +++ b/core-interface/src/requirements.rs @@ -7,7 +7,7 @@ //! [`rejection_response`] turns into a failed `CommandResponse` and [`try_send_response`] //! queues without ever blocking. //! -//! The BLE/MQTT dispatcher already refuses commands while the device is read-only (the CAN +//! The BLE and secure channel dispatchers already refuses commands while the device is read-only (the CAN //! read-write policy, `can_access.rs`). The check here repeats that against the live flag, //! because a command can wait in the queue while the policy changes, and adds what only the //! vehicle knows: how fresh its state is and what the car must be doing. @@ -324,7 +324,7 @@ pub fn rejection_response(message_id: u64, rejection: &Rejection) -> proto::Comm /// full and the response was dropped. /// /// Use this for responses to commands that did nothing (rejections): blocking on a full -/// channel would stall the command handler behind the router and the BLE/MQTT drivers, which +/// channel would stall the command handler behind the router and the BLE driver, which /// backs up `BASIC_CMD_CHANNEL` and from there the BLE dispatcher. A dropped rejection costs /// the app a retry; nothing was sent to the car. pub fn try_send_response(transport: Transport, response: proto::CommandResponse) -> bool { diff --git a/core-interface/src/routing.rs b/core-interface/src/routing.rs index b2549b1..f790fc5 100644 --- a/core-interface/src/routing.rs +++ b/core-interface/src/routing.rs @@ -1,4 +1,3 @@ -use alloc::vec; use core::cell::RefCell; use embassy_sync::blocking_mutex::Mutex; use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; @@ -8,48 +7,14 @@ use portable_atomic::{AtomicBool, AtomicU32, Ordering}; use core::task::Poll; use embassy_time::Instant; -use crate::channels::{ - BLE_STATE_TX, BLE_TX_CHANNEL, CMD_RESP_CHANNEL, MQTT_STATE_TX, MQTT_TX_CHANNEL, - VEHICLE_STATE_CHANNEL, -}; +use crate::channels::{BLE_STATE_TX, BLE_TX_CHANNEL, CMD_RESP_CHANNEL, VEHICLE_STATE_CHANNEL}; use crate::proto; use crate::types::{Transport, VehicleStatePayload}; -// ── MQTT Throttle ───────────────────────────────────────────────────────────── - -/// Seconds of silence from any MQTT client before entering idle rate. -const MQTT_ACTIVITY_WINDOW_S: u32 = 35; -/// Minimum gap between MQTT state sends while no client is active. -pub(crate) const MQTT_IDLE_RATE_S: u32 = 30; - -/// Uptime seconds of the most recent inbound MQTT message (command or heartbeat). -static LAST_MQTT_RX_SECS: AtomicU32 = AtomicU32::new(0); -/// Uptime seconds of the most recent MQTT state message actually sent. -static LAST_MQTT_STATE_SECS: AtomicU32 = AtomicU32::new(0); - -/// Called by `handle_mqtt_message` whenever any valid MQTT message arrives -/// (command, heartbeat, or any other payload). Keeps the activity window alive -/// so state updates continue to flow at full rate. -pub fn record_mqtt_activity(secs: u32) { - LAST_MQTT_RX_SECS.store(secs, Ordering::Relaxed); -} - -/// Whether an MQTT client has been active within the last [`MQTT_ACTIVITY_WINDOW_S`] seconds, -/// i.e. whether MQTT messages go out at the full rate or the idle rate. -pub(crate) fn is_mqtt_active(now_secs: u32) -> bool { - now_secs.saturating_sub(LAST_MQTT_RX_SECS.load(Ordering::Relaxed)) <= MQTT_ACTIVITY_WINDOW_S -} - -/// Resets MQTT throttle state to boot defaults. For use in tests only. -pub fn reset_mqtt_throttle_for_tests() { - LAST_MQTT_RX_SECS.store(0, Ordering::Relaxed); - LAST_MQTT_STATE_SECS.store(0, Ordering::Relaxed); -} - // ── Transport links ─────────────────────────────────────────────────────────── /// Whether a transport can deliver messages right now: a phone is connected over -/// BLE, or the MQTT session with the broker is up. Boards report it with +/// BLE. Boards report it with /// [`set_link_up`]. A message for a transport whose link is down is dropped, and /// whatever is queued when a link goes down is cleared: it was meant for the peer /// that left, never the next one. @@ -64,17 +29,11 @@ static BLE_LINK: Link = Link { up: AtomicBool::new(false), generation: AtomicU32::new(0), }; -static MQTT_LINK: Link = Link { - up: AtomicBool::new(false), - generation: AtomicU32::new(0), -}; - -/// The link of BLE or MQTT. A secure channel session has no link of its own: it is open +/// The link of BLE. A secure channel session has no link of its own: it is open /// while the session is (see `secure_channel.rs`). fn link(transport: Transport) -> Option<&'static Link> { match transport { Transport::Ble => Some(&BLE_LINK), - Transport::Mqtt => Some(&MQTT_LINK), Transport::Secure(_) => None, } } @@ -84,13 +43,12 @@ fn tx_channel( ) -> Option<&'static Channel> { match transport { Transport::Ble => Some(&BLE_TX_CHANNEL), - Transport::Mqtt => Some(&MQTT_TX_CHANNEL), Transport::Secure(_) => None, } } /// Called by the board's transport driver when its link comes up (a phone -/// connected, the MQTT session is ready) and when it goes down. Going down clears +/// connected) and when it goes down. Going down clears /// that transport's TX queue. Ignored for a secure channel session, which opens and ends /// with the channel. pub fn set_link_up(transport: Transport, up: bool) { @@ -163,15 +121,15 @@ pub(crate) async fn send_to(transport: Transport, msg: proto::DeviceToApp) -> bo .await } -/// Resets both links to their boot state (down). For use in tests only. +/// Resets the BLE link to its boot state (down). For use in tests only. pub fn reset_links_for_tests() { set_link_up(Transport::Ble, false); - set_link_up(Transport::Mqtt, false); } // ── Response Router ─────────────────────────────────────────────────────────── -/// Routes a single command response to BLE or MQTT based on the transport tag. +/// Routes a single command response to BLE or a secure channel session based on the +/// transport tag. /// The response goes back on the transport the command came in on; if that link is /// down, or goes down while the response waits for room, it is dropped (the app /// re-reads the state). `timestamp_ms` is passed explicitly so callers (and tests) @@ -190,7 +148,8 @@ pub async fn route_single_response( } /// Reads command responses from `CMD_RESP_CHANNEL` and routes each as a -/// `DeviceToApp(command_response)` to BLE or MQTT based on the transport tag. +/// `DeviceToApp(command_response)` to BLE or a secure channel session based on the +/// transport tag. /// /// `timestamp_ms` reflects device uptime. SNTP wall-clock sync is future work. #[embassy_executor::task] @@ -246,12 +205,14 @@ pub fn reset_latest_ble_state_for_tests() { /// Publishes a single vehicle state update. /// - BLE receives the full state (basic + advanced). -/// - MQTT receives basic only (`advanced_state_bytes` is always empty). +/// - The secure channel's sessions (LAN, relay) are told a new state is there, and send +/// the basic state only, when each is due (`lan.rs`, `relay.rs`). /// /// `timestamp_ms` is passed explicitly so callers (and tests) control the clock. /// /// State updates don't go through the TX queues: each transport has a single-value -/// slot (`BLE_STATE_TX`, `MQTT_STATE_TX`) that the newest update overwrites, since +/// slot (`BLE_STATE_TX`, and the latest state the sessions read) that the newest update +/// overwrites, since /// the latest reading always supersedes older ones. This never blocks, so /// `publish_state_task` can't stall `VEHICLE_STATE_CHANNEL` and every producer task /// behind it (`state_update_task`, command handlers), and a state update can never @@ -260,47 +221,16 @@ pub async fn publish_single_state(payload: VehicleStatePayload, timestamp_ms: u6 let pid = crate::PLATFORM_ID.load(Ordering::Relaxed); // BLE: full state (basic + advanced) - let basic = payload.basic.clone(); let ble_msg = ble_state_update(timestamp_ms, pid, payload); LATEST_BLE_STATE.lock(|latest| *latest.borrow_mut() = Some(ble_msg.clone())); BLE_STATE_TX.signal(ble_msg); - // LAN: the same full state, sealed for each connection's session (`lan.rs`). + // The secure channel's sessions: the basic state, sealed for each one when it is due. crate::lan::notify_state(); - - // MQTT: basic only (advanced is BLE-exclusive), throttled when no client is active. - let now_secs = (timestamp_ms / 1000) as u32; - let last_rx = LAST_MQTT_RX_SECS.load(Ordering::Relaxed); - let mqtt_active = now_secs.saturating_sub(last_rx) <= MQTT_ACTIVITY_WINDOW_S; - let should_send_mqtt = if mqtt_active { - true - } else { - let last_state = LAST_MQTT_STATE_SECS.load(Ordering::Relaxed); - now_secs.saturating_sub(last_state) >= MQTT_IDLE_RATE_S - }; - - if should_send_mqtt { - let mqtt_msg = proto::DeviceToApp { - timestamp_ms, - platform_id: pid, - payload: Some(proto::device_to_app::Payload::StateUpdate( - proto::StateUpdate { - system_state: None, - vehicle_state: Some(proto::VehicleState { - basic_state_bytes: basic, - advanced_state_bytes: vec![], - }), - }, - )), - }; - MQTT_STATE_TX.signal(mqtt_msg); - LAST_MQTT_STATE_SECS.store(now_secs, Ordering::Relaxed); - } + crate::relay::notify_state(); } -/// Reads `VehicleStatePayload` from `VEHICLE_STATE_CHANNEL` and publishes two -/// outbound `DeviceToApp(state_update)` messages per update: -/// - BLE: full `VehicleState` (basic + advanced bytes) -/// - MQTT: basic only (`advanced_state_bytes` omitted — BLE-exclusive) +/// Reads `VehicleStatePayload` from `VEHICLE_STATE_CHANNEL` and publishes +/// each update with [`publish_single_state`]. /// /// `timestamp_ms` reflects device uptime. SNTP wall-clock sync is future work. #[embassy_executor::task] diff --git a/core-interface/src/secure_channel.rs b/core-interface/src/secure_channel.rs index f933505..7239959 100644 --- a/core-interface/src/secure_channel.rs +++ b/core-interface/src/secure_channel.rs @@ -280,14 +280,30 @@ fn unknown_session_frame(session_id: &[u8; 4]) -> Vec { /// Handles one frame received on `link` at `now_ms`. pub fn on_frame(link: ChannelLink, frame: &[u8], now_ms: u64) -> FrameOutcome { + on_frame_from(link, frame, now_ms, None) +} + +/// Handles one frame received on `link` at `now_ms`, from a transport that names its +/// sender: the MQTT relay, whose topic carries the client's key ID. A handshake init whose +/// client key doesn't have `client_key_id` is dropped, like one for an unknown key. +pub fn on_frame_from( + link: ChannelLink, + frame: &[u8], + now_ms: u64, + client_key_id: Option<&str>, +) -> FrameOutcome { if frame.len() < FRAME_HEADER_BYTES || frame.len() > MAX_FRAME_BYTES { return FrameOutcome::Drop; } let session_id: [u8; 4] = frame[1..FRAME_HEADER_BYTES].try_into().unwrap_or_default(); match frame[0] { - FRAME_HANDSHAKE_INIT => { - on_handshake_init(link, session_id, &frame[FRAME_HEADER_BYTES..], now_ms) - } + FRAME_HANDSHAKE_INIT => on_handshake_init( + link, + session_id, + &frame[FRAME_HEADER_BYTES..], + now_ms, + client_key_id, + ), FRAME_TRANSPORT => on_transport(link, session_id, frame, now_ms), _ => FrameOutcome::Drop, } @@ -298,6 +314,7 @@ fn on_handshake_init( session_id: [u8; 4], message1: &[u8], now_ms: u64, + client_key_id: Option<&str>, ) -> FrameOutcome { // Before any X25519 work: anyone who can reach a transport can send inits. if !take_handshake_budget(now_ms) { @@ -306,7 +323,7 @@ fn on_handshake_init( let Some(ephemeral) = fresh_ephemeral() else { return FrameOutcome::Drop; }; - on_handshake_init_with(link, session_id, message1, now_ms, ephemeral) + on_handshake_init_with(link, session_id, message1, now_ms, ephemeral, client_key_id) } /// Counts a handshake init against [`MAX_HANDSHAKE_INITS_PER_SECOND`]: whether it may be @@ -343,6 +360,7 @@ fn on_handshake_init_with( message1: &[u8], now_ms: u64, device_ephemeral: StaticSecret, + client_key_id: Option<&str>, ) -> FrameOutcome { let (Some(device_static), Some(identity)) = ( crate::identity::device_static_secret(), @@ -357,6 +375,10 @@ fn on_handshake_init_with( &device_ephemeral, message1, |client_static| { + // The relay's topic named a client: it must be this key's. + if client_key_id.is_some_and(|id| crate::identity::device_key_id(client_static) != id) { + return false; + } client = crate::client_keys::client_for_key(client_static); // Only phones for now; hubs can't enroll yet. client @@ -537,6 +559,43 @@ pub fn newest_session(link: ChannelLink, now_ms: u64) -> Option<(SessionHandle, }) } +/// The session with `session_id` on `link`, while it is open. +pub fn session_by_id(link: ChannelLink, session_id: &[u8; 4]) -> Option { + let now_ms = embassy_time::Instant::now().as_millis(); + SESSIONS.lock(|sessions| { + let sessions = sessions.borrow(); + let slot = sessions.find(link, session_id)?; + let s = sessions.slots[slot].as_ref()?; + (!s.expired(now_ms) && s.key_still_enrolled()).then_some(SessionHandle { + slot: slot as u8, + generation: s.generation, + }) + }) +} + +/// When `session` last received a valid transport frame (or was made), while it is open. +pub fn session_last_received_ms(session: SessionHandle) -> Option { + SESSIONS.lock(|sessions| sessions.borrow_mut().get(session).map(|s| s.last_active_ms)) +} + +/// The ID of `session`'s client (a phone's `ble:` ID), while it is open. +pub fn session_client_id(session: SessionHandle) -> Option> { + SESSIONS.lock(|sessions| { + sessions + .borrow_mut() + .get(session) + .map(|s| s.client_id.clone()) + }) +} + +/// The key ID of `session`'s client (see [`crate::device_key_id`]), while it is open: it +/// names the client's topic on the relay. +pub fn session_client_key_id(session: SessionHandle) -> Option { + let client_static = + SESSIONS.lock(|sessions| sessions.borrow_mut().get(session).map(|s| s.client_static))?; + Some(crate::identity::device_key_id(&client_static)) +} + /// The link carrying `session`, while it is open. fn session_link(session: SessionHandle) -> Option { SESSIONS.lock(|sessions| sessions.borrow_mut().get(session).map(|s| s.link)) @@ -561,8 +620,18 @@ pub fn secure_session_count() -> usize { /// Hands one received frame to the channel and the dispatcher: returns the bytes to send /// back on `link`, if any. The entry point for transports. pub async fn process_secure_frame(link: ChannelLink, frame: &[u8]) -> Option> { + process_secure_frame_from(link, frame, None).await +} + +/// [`process_secure_frame`] for a transport that names the frame's sender (see +/// [`on_frame_from`]). +pub async fn process_secure_frame_from( + link: ChannelLink, + frame: &[u8], + client_key_id: Option<&str>, +) -> Option> { let now_ms = embassy_time::Instant::now().as_millis(); - match on_frame(link, frame, now_ms) { + match on_frame_from(link, frame, now_ms, client_key_id) { FrameOutcome::Drop => None, FrameOutcome::Reply(reply) => Some(reply), FrameOutcome::Message(session, message) => { @@ -583,7 +652,13 @@ pub(crate) fn try_queue(session: SessionHandle, msg: proto::DeviceToApp) -> bool kind: LinkKind::Lan, connection, }) => crate::lan::try_queue(connection as usize, session, msg), - Some(_) => SECURE_TX_CHANNEL.try_send((session, msg)).is_ok(), + Some(_) => { + let queued = SECURE_TX_CHANNEL.try_send((session, msg)).is_ok(); + if queued { + crate::relay::wake(); + } + queued + } None => false, } } @@ -607,6 +682,7 @@ pub fn on_handshake_init_for_tests( &frame[FRAME_HEADER_BYTES..], now_ms, StaticSecret::from(device_ephemeral), + None, ) } diff --git a/core-interface/src/types.rs b/core-interface/src/types.rs index 286e565..b4f72b3 100644 --- a/core-interface/src/types.rs +++ b/core-interface/src/types.rs @@ -7,7 +7,6 @@ use alloc::vec::Vec; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Transport { Ble, - Mqtt, /// A session of the secure channel, whichever transport carries its frames (see /// `secure_channel.rs`). Its messages go to its LAN connection's queue (`lan.rs`), or to /// `SECURE_TX_CHANNEL` for the relay. @@ -21,13 +20,12 @@ pub struct InboundCommand { /// Which transport delivered this command. pub transport: Transport, /// The transport-verified sender: the BLE source device, or the secure channel - /// client's ID (a phone's `ble:` ID). Empty over MQTT. + /// client's ID (a phone's `ble:` ID). pub source_device_id: Vec, /// Raw encoded bytes of the vehicle-specific command proto message. pub bytes: Vec, /// Set by the dispatcher for a command from a phone validated for this car: what the /// vehicle needs to send the command's frames ([`crate::CanTxFrame::command`]). - /// `None` over MQTT, which has no phone identity. pub authorization: Option, } @@ -62,7 +60,7 @@ pub struct CanFilter { /// Encoded vehicle state produced by the vehicle crate and consumed by /// `publish_state_task` to build outbound `DeviceToApp` messages. pub struct VehicleStatePayload { - /// Encoded `BasicState` bytes — sent over both BLE and MQTT. + /// Encoded `BasicState` bytes — sent over BLE and the secure channel. pub basic: Vec, /// Encoded `AdvancedState` bytes — sent over BLE only. pub advanced: Vec, diff --git a/core-interface/tests/availability.rs b/core-interface/tests/availability.rs index bd06bd4..33c1d57 100644 --- a/core-interface/tests/availability.rs +++ b/core-interface/tests/availability.rs @@ -1,11 +1,9 @@ use core_interface::{ - BLE_TX_CHANNEL, COMMAND_AVAILABILITY_REPEAT_MS, CommandKind, MQTT_TX_CHANNEL, - REPORT_MAX_AGE_MS, approve_can_read_write, command_availability_at, confirm_car_fingerprint, - confirm_car_identity, init, proto, publish_command_availability, - publish_command_availability_mqtt, record_mqtt_activity, report_command_availability_at, + BLE_TX_CHANNEL, COMMAND_AVAILABILITY_REPEAT_MS, CommandKind, REPORT_MAX_AGE_MS, + approve_can_read_write, command_availability_at, confirm_car_fingerprint, confirm_car_identity, + init, proto, publish_command_availability, report_command_availability_at, resend_command_availability, reset_can_access_for_tests, reset_command_availability_for_tests, - reset_mqtt_throttle_for_tests, revoke_car_identity, set_can_dev_write_unlocked, - set_can_read_only, + revoke_car_identity, set_can_dev_write_unlocked, set_can_read_only, }; use proto::CommandAvailabilityState as State; @@ -13,7 +11,6 @@ const PLATFORM_ID: u32 = 0xDEAD_BEEF; fn drain_tx() { while BLE_TX_CHANNEL.try_receive().is_ok() {} - while MQTT_TX_CHANNEL.try_receive().is_ok() {} } /// Boot state: read-only, nothing reported. @@ -25,9 +22,7 @@ fn boot() { embassy_futures::block_on(core_interface::clear_paired_phones()); core_interface::reset_phone_trust_for_tests(); set_can_read_only(true); - reset_mqtt_throttle_for_tests(); core_interface::set_link_up(core_interface::Transport::Ble, true); - core_interface::set_link_up(core_interface::Transport::Mqtt, true); drain_tx(); } @@ -195,112 +190,3 @@ fn a_new_report_replaces_the_previous_one_for_that_kind() { let shown = command_availability_at(1_100).unwrap(); assert_eq!(shown.basic.len(), 1); } - -// ── MQTT ────────────────────────────────────────────────────────────────────── - -fn sent_mqtt_availability() -> Option { - match MQTT_TX_CHANNEL.try_receive().ok()?.payload { - Some(proto::device_to_app::Payload::StateUpdate(update)) => { - assert!(update.vehicle_state.is_none()); - update.system_state?.command_availability - } - other => panic!("unexpected message {other:?}"), - } -} - -/// An MQTT client is active now: state goes out at the full rate. -fn mqtt_client_active(now_secs: u32) { - record_mqtt_activity(now_secs); -} - -#[test] -fn mqtt_is_told_nothing_before_the_vehicle_reports() { - read_write(); - assert!(!publish_command_availability_mqtt(1_000)); - assert!(MQTT_TX_CHANNEL.try_receive().is_err()); -} - -#[test] -fn mqtt_gets_the_basic_commands_only_and_all_unavailable_while_mqtt_commands_are_rejected() { - read_write(); - report_command_availability_at( - CommandKind::Basic, - &[(1, State::Available), (2, State::Unsupported)], - 1_000, - ); - report_command_availability_at(CommandKind::Advanced, &[(1, State::Available)], 1_000); - mqtt_client_active(1); - assert!(publish_command_availability_mqtt(1_000)); - let sent = sent_mqtt_availability().expect("availability"); - // BLE would say available: the device rejects every command over MQTT for now. - assert_eq!(state(sent.basic[&1]), State::Unavailable); - assert_eq!(state(sent.basic[&2]), State::Unsupported); - assert!(sent.advanced.is_empty(), "advanced commands are BLE only"); - // BLE is unaffected. - assert!(publish_command_availability(1_000)); - let ble = sent_availability().unwrap(); - assert_eq!(state(ble.basic[&1]), State::Available); - assert_eq!(state(ble.advanced[&1]), State::Available); -} - -#[test] -fn mqtt_repeats_while_active_and_sends_a_change_at_once() { - read_write(); - report_command_availability_at(CommandKind::Basic, &[(1, State::Available)], 1_000); - mqtt_client_active(1); - assert!(publish_command_availability_mqtt(1_000)); - drain_tx(); - - // Unchanged: nothing until the repeat interval has passed. - assert!(!publish_command_availability_mqtt(2_000)); - report_command_availability_at( - CommandKind::Basic, - &[(1, State::Available)], - 1_000 + COMMAND_AVAILABILITY_REPEAT_MS, - ); - mqtt_client_active(6); - assert!(publish_command_availability_mqtt( - 1_000 + COMMAND_AVAILABILITY_REPEAT_MS - )); - assert!(sent_mqtt_availability().is_some()); -} - -#[test] -fn mqtt_is_sent_at_the_idle_rate_when_no_client_is_active() { - read_write(); - // No MQTT activity recorded: the first message goes out, then one per idle period. - report_command_availability_at(CommandKind::Basic, &[(1, State::Available)], 100_000); - assert!(publish_command_availability_mqtt(100_000)); - drain_tx(); - report_command_availability_at(CommandKind::Basic, &[(1, State::Available)], 110_000); - assert!(!publish_command_availability_mqtt(110_000)); - report_command_availability_at(CommandKind::Basic, &[(1, State::Available)], 130_000); - assert!(publish_command_availability_mqtt(130_000)); -} - -#[test] -fn mqtt_resend_publishes_again() { - read_write(); - report_command_availability_at(CommandKind::Basic, &[(1, State::Available)], 1_000); - mqtt_client_active(1); - assert!(publish_command_availability_mqtt(1_000)); - drain_tx(); - assert!(!publish_command_availability_mqtt(1_100)); - resend_command_availability(); - assert!(publish_command_availability_mqtt(1_100)); -} - -#[test] -fn a_full_mqtt_queue_never_blocks_and_is_retried() { - read_write(); - report_command_availability_at(CommandKind::Basic, &[(1, State::Available)], 1_000); - mqtt_client_active(1); - for _ in 0..4 { - MQTT_TX_CHANNEL - .try_send(proto::DeviceToApp::default()) - .unwrap(); - } - assert!(!publish_command_availability_mqtt(1_000)); - drain_tx(); - assert!(publish_command_availability_mqtt(1_100)); -} diff --git a/core-interface/tests/can_access.rs b/core-interface/tests/can_access.rs index 2ec7fb1..0a5482c 100644 --- a/core-interface/tests/can_access.rs +++ b/core-interface/tests/can_access.rs @@ -4,14 +4,13 @@ //! in `can_access_production.rs`, a separate process, since that is set once per boot. use core_interface::{ - BLE_TX_CHANNEL, CanLogSession, MQTT_TX_CHANNEL, add_paired_phone, approve_can_read_write, - can_access_state, can_read_write_approval, clear_paired_phones, confirm_car_fingerprint, - confirm_car_identity, handle_ble_message, handle_mqtt_message, has_can_dev_write_lock, init, - is_can_bus_read_only, is_can_dev_write_unlocked, is_can_read_only, - is_car_fingerprint_confirmed, proto, publish_can_access_state, remove_paired_phone, - reset_can_access_for_tests, restore_can_read_write_approval, revoke_can_read_write_approval, - revoke_car_identity, set_can_dev_write_unlocked, set_can_read_only, - try_take_can_read_write_approval_to_store, + BLE_TX_CHANNEL, CanLogSession, add_paired_phone, approve_can_read_write, can_access_state, + can_read_write_approval, clear_paired_phones, confirm_car_fingerprint, confirm_car_identity, + handle_ble_message, has_can_dev_write_lock, init, is_can_bus_read_only, + is_can_dev_write_unlocked, is_can_read_only, is_car_fingerprint_confirmed, proto, + publish_can_access_state, remove_paired_phone, reset_can_access_for_tests, + restore_can_read_write_approval, revoke_can_read_write_approval, revoke_car_identity, + set_can_dev_write_unlocked, set_can_read_only, try_take_can_read_write_approval_to_store, }; use proto::CanReadWriteApproval as Approval; use proto::app_to_device::Payload; @@ -25,7 +24,6 @@ const STRANGER: &[u8] = b"ble:\x0A\x0B\x0C\x0D\x0E\x0F"; fn drain_tx() { while BLE_TX_CHANNEL.try_receive().is_ok() {} - while MQTT_TX_CHANNEL.try_receive().is_ok() {} } /// Boot state: nothing identified, approved or unlocked, no phones, bus locked. @@ -37,7 +35,6 @@ fn boot() { core_interface::reset_phone_trust_for_tests(); set_can_read_only(true); core_interface::set_link_up(core_interface::Transport::Ble, true); - core_interface::set_link_up(core_interface::Transport::Mqtt, true); core_interface::reset_recent_commands_for_tests(); drain_tx(); } @@ -376,28 +373,6 @@ fn a_phone_that_is_not_bonded_cannot_approve_or_unlock() { assert!(!is_can_dev_write_unlocked()); } -#[test] -fn mqtt_can_never_approve_unlock_or_revoke() { - boot(); - embassy_futures::block_on(add_paired_phone(PHONE)); - identify(CAR_A); - // Even with a bonded phone's id: MQTT drops every system command. - embassy_futures::block_on(handle_mqtt_message(approve_cmd(PHONE, true))); - embassy_futures::block_on(handle_mqtt_message(unlock_cmd(PHONE, true))); - assert_eq!(can_read_write_approval(), Approval::NotApproved); - assert!(!is_can_dev_write_unlocked()); - assert!(BLE_TX_CHANNEL.try_receive().is_err()); - assert!(MQTT_TX_CHANNEL.try_receive().is_err()); - - // Nor take an approval away. - read_write_for(CAR_A); - embassy_futures::block_on(add_paired_phone(PHONE)); - embassy_futures::block_on(handle_mqtt_message(approve_cmd(PHONE, false))); - embassy_futures::block_on(handle_mqtt_message(unlock_cmd(PHONE, false))); - assert_eq!(can_read_write_approval(), Approval::Approved); - assert!(!is_can_read_only()); -} - // ── What the app sees ───────────────────────────────────────────────────────── #[test] @@ -437,7 +412,6 @@ fn access_state_is_published_on_change_and_only_over_ble() { identify(CAR_A); assert!(publish_can_access_state(3)); - assert!(MQTT_TX_CHANNEL.try_receive().is_err()); drain_tx(); } diff --git a/core-interface/tests/client_keys.rs b/core-interface/tests/client_keys.rs index 6932edf..ba5f5e5 100644 --- a/core-interface/tests/client_keys.rs +++ b/core-interface/tests/client_keys.rs @@ -3,15 +3,14 @@ //! only, and the key goes away with the phone's bond but not with its validation. use core_interface::{ - BLE_TX_CHANNEL, MQTT_TX_CHANNEL, add_paired_phone, approve_can_read_write, clear_paired_phones, - client_for_key, client_key_label, confirm_car_fingerprint, confirm_car_identity, - device_identity, device_key_id, encode_client_keys, encode_device_identity, - forget_phone_validation, handle_ble_message, handle_mqtt_message, init, is_client_key_enrolled, - proto, prune_phone_validations, remove_paired_phone, reset_can_access_for_tests, - reset_client_keys_for_tests, reset_device_identity_for_tests, reset_phone_trust_for_tests, - reset_phone_validation_for_tests, restore_client_keys, restore_device_identity, - revoke_car_identity, set_random_source, try_take_client_keys_to_store, - validate_phone_for_tests, + BLE_TX_CHANNEL, add_paired_phone, approve_can_read_write, clear_paired_phones, client_for_key, + client_key_label, confirm_car_fingerprint, confirm_car_identity, device_identity, + device_key_id, encode_client_keys, encode_device_identity, forget_phone_validation, + handle_ble_message, init, is_client_key_enrolled, proto, prune_phone_validations, + remove_paired_phone, reset_can_access_for_tests, reset_client_keys_for_tests, + reset_device_identity_for_tests, reset_phone_trust_for_tests, reset_phone_validation_for_tests, + restore_client_keys, restore_device_identity, revoke_car_identity, set_random_source, + try_take_client_keys_to_store, validate_phone_for_tests, }; use proto::app_to_device::Payload; use proto::system_command::Action; @@ -61,10 +60,8 @@ fn boot() { set_random_source(counting_random); assert!(restore_device_identity(&[]).is_some()); core_interface::set_link_up(core_interface::Transport::Ble, true); - core_interface::set_link_up(core_interface::Transport::Mqtt, true); core_interface::reset_recent_commands_for_tests(); while BLE_TX_CHANNEL.try_receive().is_ok() {} - while MQTT_TX_CHANNEL.try_receive().is_ok() {} for phone in [OWNER, SECOND] { embassy_futures::block_on(add_paired_phone(phone)); } @@ -242,20 +239,6 @@ fn a_bonded_but_not_validated_phone_cannot_enroll() { assert_eq!(client_for_key(&SECOND_KEY), None); } -#[test] -fn enrollment_over_mqtt_is_ignored() { - boot(); - embassy_futures::block_on(handle_mqtt_message(system_message( - OWNER, - enroll_cmd(&OWNER_KEY, proto::ClientKind::Phone, "Pixel"), - ))); - assert!(!is_client_key_enrolled(OWNER)); - assert!( - MQTT_TX_CHANNEL.try_receive().is_err(), - "no answer over MQTT" - ); -} - #[test] fn enrolling_again_replaces_the_key() { boot(); diff --git a/core-interface/tests/dedupe.rs b/core-interface/tests/dedupe.rs index 577e8e9..45dd8ed 100644 --- a/core-interface/tests/dedupe.rs +++ b/core-interface/tests/dedupe.rs @@ -18,7 +18,7 @@ fn the_same_id_from_another_source_is_not() { assert!(!recent.is_duplicate(PHONE_B, 7, 1_000)); assert!( !recent.is_duplicate(&[], 7, 1_000), - "MQTT has its own source" + "an empty source is a source of its own" ); } diff --git a/core-interface/tests/dispatch.rs b/core-interface/tests/dispatch.rs index b6081c3..9f72a9f 100644 --- a/core-interface/tests/dispatch.rs +++ b/core-interface/tests/dispatch.rs @@ -1,6 +1,6 @@ use core_interface::{ - ADVANCED_CMD_CHANNEL, BASIC_CMD_CHANNEL, BLE_TX_CHANNEL, MQTT_TX_CHANNEL, - SYSTEM_COMMAND_CHANNEL, Transport, handle_ble_message, handle_mqtt_message, init, + ADVANCED_CMD_CHANNEL, BASIC_CMD_CHANNEL, BLE_TX_CHANNEL, SYSTEM_COMMAND_CHANNEL, Transport, + handle_ble_message, init, proto::{ self, CanDebugFilter as ProtoCanDebugFilter, ClearPairedPhonesCommand, ListPairedPhonesCommand, RemovePairedPhoneCommand, RestartCommand, SetCanDebugEnabled, @@ -14,14 +14,13 @@ const PLATFORM_ID: u32 = 0xDEAD_BEEF; const WRONG_ID: u32 = 0x0000_0001; const MSG_ID: u64 = 42; -/// Fresh dispatcher state: no commands seen yet (tests reuse `MSG_ID`), both links up. +/// Fresh dispatcher state: no commands seen yet (tests reuse `MSG_ID`), the BLE link up. fn setup() { init(PLATFORM_ID); reset_recent_commands_for_tests(); embassy_futures::block_on(core_interface::clear_paired_phones()); core_interface::reset_phone_trust_for_tests(); set_link_up(Transport::Ble, true); - set_link_up(Transport::Mqtt, true); while BLE_TX_CHANNEL.try_receive().is_ok() {} while SYSTEM_COMMAND_CHANNEL.try_receive().is_ok() {} } @@ -112,15 +111,6 @@ fn ble_wrong_platform_id_drops_message() { assert!(BASIC_CMD_CHANNEL.try_receive().is_err()); } -#[test] -fn mqtt_wrong_platform_id_drops_message() { - setup(); - let bytes = vec![1u8, 2, 3]; - let msg = ble_msg(WRONG_ID, Some(Payload::BasicCommandBytes(bytes))); - embassy_futures::block_on(handle_mqtt_message(msg)); - assert!(BASIC_CMD_CHANNEL.try_receive().is_err()); -} - // ── BLE routing ─────────────────────────────────────────────────────────────── #[test] @@ -265,55 +255,6 @@ fn ble_basic_command_with_empty_source_device_id_is_rejected() { ); } -// ── MQTT routing (restrictions) ─────────────────────────────────────────────── - -#[test] -fn mqtt_basic_command_is_rejected_until_mqtt_is_authenticated() { - setup(); - while MQTT_TX_CHANNEL.try_receive().is_ok() {} - let mut msg = ble_msg( - PLATFORM_ID, - Some(Payload::BasicCommandBytes(vec![0x11, 0x22])), - ); - msg.message_id = 77; - embassy_futures::block_on(handle_mqtt_message(msg)); - assert!( - BASIC_CMD_CHANNEL.try_receive().is_err(), - "MQTT command must not reach the vehicle" - ); - let reply = MQTT_TX_CHANNEL - .try_receive() - .expect("rejected MQTT command not answered"); - match reply.payload { - Some(proto::device_to_app::Payload::CommandResponse(resp)) => { - assert_eq!(resp.message_id, 77); - assert!(!resp.success); - assert_eq!(resp.status_code, proto::CommandStatusCode::Failed as i32); - assert!(resp.error_message.contains("MQTT")); - } - other => panic!("expected CommandResponse, got {other:?}"), - } -} - -#[test] -fn mqtt_system_command_silently_dropped() { - setup(); - let msg = ble_msg(PLATFORM_ID, Some(Payload::SystemCommand(make_system_cmd()))); - embassy_futures::block_on(handle_mqtt_message(msg)); - assert!(SYSTEM_COMMAND_CHANNEL.try_receive().is_err()); - assert!(BASIC_CMD_CHANNEL.try_receive().is_err()); -} - -#[test] -fn mqtt_advanced_command_bytes_silently_dropped() { - setup(); - let bytes = vec![0xFF]; - let msg = ble_msg(PLATFORM_ID, Some(Payload::AdvancedCommandBytes(bytes))); - embassy_futures::block_on(handle_mqtt_message(msg)); - assert!(ADVANCED_CMD_CHANNEL.try_receive().is_err()); - assert!(BASIC_CMD_CHANNEL.try_receive().is_err()); -} - // ── Deprecated CAN debug commands ───────────────────────────────────────────── /// The BLE CAN debug stream was removed (contracts still carry the messages, deprecated). @@ -554,18 +495,3 @@ fn ble_repeated_system_command_runs_once() { assert!(SYSTEM_COMMAND_CHANNEL.try_receive().is_ok()); assert!(SYSTEM_COMMAND_CHANNEL.try_receive().is_err()); } - -#[test] -fn mqtt_redelivered_command_is_answered_once() { - setup(); - while MQTT_TX_CHANNEL.try_receive().is_ok() {} - for _ in 0..2 { - let msg = ble_msg(PLATFORM_ID, Some(Payload::BasicCommandBytes(vec![1]))); - embassy_futures::block_on(handle_mqtt_message(msg)); - } - assert!(MQTT_TX_CHANNEL.try_receive().is_ok()); - assert!( - MQTT_TX_CHANNEL.try_receive().is_err(), - "a QoS 1 redelivery must not be handled again" - ); -} diff --git a/core-interface/tests/mqtt_client_id.rs b/core-interface/tests/mqtt_client_id.rs deleted file mode 100644 index 419a534..0000000 --- a/core-interface/tests/mqtt_client_id.rs +++ /dev/null @@ -1,22 +0,0 @@ -//! The device tells the app its MQTT client ID over BLE. Its own test binary, since -//! `set_mqtt_client_id()` holds for the rest of the process. - -use core_interface::{can_access_state_update, init, proto, set_mqtt_client_id}; - -fn reported_client_id() -> Option { - match can_access_state_update(0).payload { - Some(proto::device_to_app::Payload::StateUpdate(update)) => { - update.system_state.unwrap().mqtt_client_id - } - other => panic!("expected a state update, got {other:?}"), - } -} - -#[test] -fn the_access_state_reports_the_mqtt_client_id_only_when_there_is_one() { - init(0xDEAD_BEEF); - assert_eq!(reported_client_id(), None, "no MQTT in this build"); - - set_mqtt_client_id("dev-car"); - assert_eq!(reported_client_id().as_deref(), Some("dev-car")); -} diff --git a/core-interface/tests/relay.rs b/core-interface/tests/relay.rs new file mode 100644 index 0000000..b997862 --- /dev/null +++ b/core-interface/tests/relay.rs @@ -0,0 +1,566 @@ +//! The MQTT relay (docs/mqtt-relay.md): per-client topics, the handshake's topic check, +//! what a relay session is sent and how often, and what a broker reconnect does. + +use core_interface::{ + BLE_TX_CHANNEL, CommandKind, Initiator, InitiatorSession, RELAY_ACTIVITY_WINDOW_MS, + RELAY_IDLE_STATE_INTERVAL_MS, RELAY_MIN_STATE_INTERVAL_MS, RELAY_SYSTEM_STATE_REPEAT_MS, + RelayConnection, Transport, VehicleStatePayload, add_paired_phone, approve_can_read_write, + clear_paired_phones, confirm_car_fingerprint, confirm_car_identity, device_identity, + device_key_id, handle_ble_message, init, proto, publish_single_state, relay_client_id, + relay_client_key_id_from_topic, relay_connect, relay_disconnect, relay_receive_frame, + relay_session_count, relay_subscribe_filter, relay_try_next_frame, + report_command_availability_at, reset_can_access_for_tests, reset_client_keys_for_tests, + reset_command_availability_for_tests, reset_device_identity_for_tests, reset_lan_for_tests, + reset_latest_ble_state_for_tests, reset_phone_trust_for_tests, + reset_phone_validation_for_tests, reset_relay_for_tests, reset_secure_channel_for_tests, + restore_device_identity, revoke_car_identity, route_single_response, + set_can_dev_write_unlocked, set_can_read_only, set_random_source, validate_phone_for_tests, +}; +use embassy_time::Instant; +use prost::Message as _; +use proto::CommandAvailabilityState as State; +use proto::app_to_device::Payload; +use proto::device_to_app::Payload as Out; + +const PLATFORM_ID: u32 = 0xDEAD_BEEF; +const CAR: &[u8] = b"KNAC381AAP5000001"; +const OTHER_CAR: &[u8] = b"KNAC381AAP5000002"; +const OWNER: &[u8] = b"ble:\x01\x02\x03\x04\x05\x06"; +const SECOND: &[u8] = b"ble:\x0A\x0B\x0C\x0D\x0E\x0F"; +const OWNER_STATIC: [u8; 32] = [0x41; 32]; +const SECOND_STATIC: [u8; 32] = [0x42; 32]; + +fn counting_random(buf: &mut [u8]) { + static NEXT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(1); + for b in buf { + *b = NEXT.fetch_add(7, std::sync::atomic::Ordering::Relaxed); + } +} + +fn next_id() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) +} + +fn now() -> u64 { + Instant::now().as_millis() +} + +fn public(secret: [u8; 32]) -> [u8; 32] { + x25519_dalek::PublicKey::from(&x25519_dalek::StaticSecret::from(secret)).to_bytes() +} + +fn ephemeral() -> [u8; 32] { + let mut e = [0u8; 32]; + e[1..9].copy_from_slice(&next_id().to_le_bytes()); + e[31] = 0x66; + e +} + +fn enroll(phone: &[u8], client_static: [u8; 32]) { + let msg = proto::AppToDevice { + message_id: next_id(), + platform_id: PLATFORM_ID, + source_device_id: phone.to_vec(), + payload: Some(Payload::SystemCommand(proto::SystemCommand { + action: Some(proto::system_command::Action::EnrollClientKey( + proto::EnrollClientKeyCommand { + public_key: public(client_static).to_vec(), + kind: proto::ClientKind::Phone as i32, + label: "test".into(), + }, + )), + })), + }; + embassy_futures::block_on(handle_ble_message(msg)); + while BLE_TX_CHANNEL.try_receive().is_ok() {} +} + +/// The car identified and read-write, both phones bonded and enrolled, only the owner +/// validated, a broker session up. +fn boot() -> RelayConnection { + init(PLATFORM_ID); + revoke_car_identity(); + reset_can_access_for_tests(); + embassy_futures::block_on(clear_paired_phones()); + reset_phone_trust_for_tests(); + reset_phone_validation_for_tests(); + reset_client_keys_for_tests(); + reset_device_identity_for_tests(); + reset_secure_channel_for_tests(); + reset_command_availability_for_tests(); + reset_latest_ble_state_for_tests(); + reset_lan_for_tests(); + reset_relay_for_tests(); + set_random_source(counting_random); + assert!(restore_device_identity(&[]).is_some()); + core_interface::set_link_up(Transport::Ble, true); + core_interface::reset_recent_commands_for_tests(); + embassy_futures::block_on(core_interface::reset_ble_controller_lease_for_tests()); + while core_interface::BASIC_CMD_CHANNEL.try_receive().is_ok() {} + for phone in [OWNER, SECOND] { + embassy_futures::block_on(add_paired_phone(phone)); + } + confirm_car_identity(); + assert!(confirm_car_fingerprint(CAR)); + approve_can_read_write().unwrap(); + set_can_dev_write_unlocked(true).unwrap(); + assert!(!set_can_read_only(false)); + assert!(validate_phone_for_tests(OWNER)); + assert!(validate_phone_for_tests(SECOND)); + enroll(OWNER, OWNER_STATIC); + enroll(SECOND, SECOND_STATIC); + // Back in this car after another one: only the owner validates again. + assert!(confirm_car_fingerprint(OTHER_CAR)); + approve_can_read_write().unwrap(); + assert!(confirm_car_fingerprint(CAR)); + approve_can_read_write().unwrap(); + assert!(!set_can_read_only(false)); + assert!(validate_phone_for_tests(OWNER)); + while BLE_TX_CHANNEL.try_receive().is_ok() {} + relay_connect().expect("no identity") +} + +fn device_id() -> String { + device_identity().unwrap().key_id +} + +fn client_key_id(client_static: [u8; 32]) -> String { + device_key_id(&public(client_static)) +} + +fn device_topic(client: &str) -> String { + format!("opencar/{}/d/{client}", device_id()) +} + +fn client_topic(client: &str) -> String { + format!("opencar/{}/c/{client}", device_id()) +} + +fn prologue() -> Vec { + let mut p = b"opencar/secure/1\0".to_vec(); + p.extend_from_slice(device_id().as_bytes()); + p +} + +struct Client { + relay: RelayConnection, + key_id: String, + session: InitiatorSession, + session_id: [u8; 4], + counter: u64, +} + +fn init_frame(client_static: [u8; 32]) -> (Initiator, [u8; 4], Vec) { + let device_key: [u8; 32] = device_identity().unwrap().public_key.try_into().unwrap(); + let (initiator, message1) = + Initiator::start(&prologue(), client_static, ephemeral(), device_key).unwrap(); + let session_id = (next_id() as u32).to_be_bytes(); + let mut frame = vec![1]; + frame.extend_from_slice(&session_id); + frame.extend_from_slice(&message1); + (initiator, session_id, frame) +} + +/// Handshakes on the client's own device topic. +fn connect(relay: RelayConnection, client_static: [u8; 32]) -> Client { + let key_id = client_key_id(client_static); + let (initiator, session_id, frame) = init_frame(client_static); + let reply = + embassy_futures::block_on(relay_receive_frame(relay, &device_topic(&key_id), &frame)) + .expect("no handshake reply"); + assert_eq!(reply.topic, client_topic(&key_id)); + assert_eq!(reply.frame[0], 2); + Client { + relay, + session: initiator.finish(&reply.frame[5..]).unwrap(), + key_id, + session_id, + counter: 0, + } +} + +impl Client { + fn frame(&mut self, plaintext: &[u8]) -> Vec { + let mut frame = vec![3]; + frame.extend_from_slice(&self.session_id); + frame.extend_from_slice(&self.counter.to_be_bytes()); + frame.extend_from_slice(&self.session.encrypt(self.counter, plaintext)); + self.counter += 1; + frame + } + + fn send(&mut self, msg: &proto::AppToDevice) -> Option { + let frame = self.frame(&msg.encode_to_vec()); + embassy_futures::block_on(relay_receive_frame( + self.relay, + &device_topic(&self.key_id), + &frame, + )) + } + + fn open(&self, frame: &[u8]) -> proto::DeviceToApp { + assert_eq!(frame[0], 3); + assert_eq!(frame[1..5], self.session_id); + let counter = u64::from_be_bytes(frame[5..13].try_into().unwrap()); + let plaintext = self.session.decrypt(counter, &frame[13..]).unwrap(); + proto::DeviceToApp::decode(plaintext.as_slice()).unwrap() + } +} + +/// Everything the relay has ready at `at`, by topic. +fn publish_all(relay: RelayConnection, at: u64) -> Vec { + core::iter::from_fn(|| relay_try_next_frame(relay, at)).collect() +} + +fn opened(client: &Client, frames: &[core_interface::RelayFrame]) -> Vec { + frames + .iter() + .filter(|f| f.topic == client_topic(&client.key_id)) + .map(|f| client.open(&f.frame)) + .collect() +} + +fn system_states(msgs: &[proto::DeviceToApp]) -> Vec { + msgs.iter() + .filter_map(|m| match &m.payload { + Some(Out::StateUpdate(u)) => u.system_state.clone(), + _ => None, + }) + .collect() +} + +fn vehicle_states(msgs: &[proto::DeviceToApp]) -> Vec { + msgs.iter() + .filter_map(|m| match &m.payload { + Some(Out::StateUpdate(u)) => u.vehicle_state.clone(), + _ => None, + }) + .collect() +} + +fn report_available(at: u64) { + report_command_availability_at(CommandKind::Basic, &[(1, State::Available)], at); + report_command_availability_at(CommandKind::Advanced, &[(2, State::Available)], at); +} + +fn publish_state(basic: u8, at: u64) { + embassy_futures::block_on(publish_single_state( + VehicleStatePayload { + basic: vec![0x08, basic], + advanced: vec![0x10, 0x02], + }, + at, + )); +} + +fn basic_command(message_id: u64) -> proto::AppToDevice { + proto::AppToDevice { + message_id, + platform_id: PLATFORM_ID, + // Whatever the app puts here, the session's client ID replaces it. + source_device_id: b"forged".to_vec(), + payload: Some(Payload::BasicCommandBytes(vec![0x0A, 0x00])), + } +} + +// ── Topics ──────────────────────────────────────────────────────────────────── + +#[test] +fn the_device_connects_with_its_key_id_and_subscribes_to_every_client_topic() { + let _relay = boot(); + let id = device_id(); + assert_eq!(relay_client_id().as_deref(), Some(id.as_str())); + assert_eq!(relay_subscribe_filter(), Some(format!("opencar/{id}/d/+"))); + let owner = client_key_id(OWNER_STATIC); + assert_eq!( + relay_client_key_id_from_topic(&device_topic(&owner)), + Some(owner.as_str()) + ); + // Another device's topic, a client topic, or a malformed key ID: not for the relay. + assert_eq!( + relay_client_key_id_from_topic(&format!("opencar/00000000000000000000/d/{owner}")), + None + ); + assert_eq!(relay_client_key_id_from_topic(&client_topic(&owner)), None); + assert_eq!(relay_client_key_id_from_topic(&device_topic("abc")), None); + assert_eq!( + relay_client_key_id_from_topic(&device_topic(&owner.to_uppercase())), + None + ); +} + +#[test] +fn a_handshake_on_another_clients_topic_is_dropped() { + let relay = boot(); + let (_, _, frame) = init_frame(OWNER_STATIC); + let reply = embassy_futures::block_on(relay_receive_frame( + relay, + &device_topic(&client_key_id(SECOND_STATIC)), + &frame, + )); + assert_eq!(reply, None, "the topic must name the handshake's key"); + assert_eq!(relay_session_count(), 0); +} + +#[test] +fn nothing_is_published_without_a_session() { + let relay = boot(); + report_available(now()); + publish_state(1, now()); + assert!(publish_all(relay, now()).is_empty()); +} + +// ── What a session is sent ──────────────────────────────────────────────────── + +#[test] +fn a_new_session_gets_the_system_state_then_the_basic_state_on_its_topic() { + let relay = boot(); + let at = now(); + report_available(at); + publish_state(1, at); + let owner = connect(relay, OWNER_STATIC); + let frames = publish_all(relay, at); + assert!( + frames + .iter() + .all(|f| f.topic == client_topic(&owner.key_id)), + "{frames:?}" + ); + let msgs = opened(&owner, &frames); + let systems = system_states(&msgs); + assert_eq!(systems.len(), 1); + let availability = systems[0].command_availability.as_ref().unwrap(); + assert_eq!(availability.basic[&1], State::Available as i32); + assert_eq!( + availability.advanced[&2], + State::Unavailable as i32, + "the relay is the remote tier" + ); + let vehicle = vehicle_states(&msgs); + assert_eq!(vehicle.len(), 1); + assert_eq!(vehicle[0].basic_state_bytes, vec![0x08, 0x01]); + assert!(vehicle[0].advanced_state_bytes.is_empty()); +} + +#[test] +fn each_client_gets_its_own_frames_on_its_own_topic() { + let relay = boot(); + let at = now(); + report_available(at); + let owner = connect(relay, OWNER_STATIC); + let second = connect(relay, SECOND_STATIC); + let frames = publish_all(relay, at); + let owner_systems = system_states(&opened(&owner, &frames)); + let second_systems = system_states(&opened(&second, &frames)); + assert_eq!(owner_systems.len(), 1); + assert_eq!(second_systems.len(), 1); + // The second phone isn't validated for this car. + let second_basic = second_systems[0] + .command_availability + .as_ref() + .unwrap() + .basic[&1]; + assert_eq!(second_basic, State::Unavailable as i32); +} + +#[test] +fn the_system_state_repeats_at_the_relay_rate() { + let relay = boot(); + let at = now(); + report_available(at); + let owner = connect(relay, OWNER_STATIC); + assert_eq!( + system_states(&opened(&owner, &publish_all(relay, at))).len(), + 1 + ); + let before = at + RELAY_SYSTEM_STATE_REPEAT_MS - 1; + report_available(before); + assert!(system_states(&opened(&owner, &publish_all(relay, before))).is_empty()); + let due = at + RELAY_SYSTEM_STATE_REPEAT_MS; + report_available(due); + assert_eq!( + system_states(&opened(&owner, &publish_all(relay, due))).len(), + 1 + ); +} + +#[test] +fn an_active_session_gets_state_at_most_once_per_interval() { + let relay = boot(); + let at = now(); + let mut owner = connect(relay, OWNER_STATIC); + // A heartbeat keeps the session active. + assert_eq!( + owner.send(&proto::AppToDevice { + message_id: next_id(), + platform_id: PLATFORM_ID, + source_device_id: Vec::new(), + payload: Some(Payload::Heartbeat(true)), + }), + None + ); + publish_state(1, at); + assert_eq!( + vehicle_states(&opened(&owner, &publish_all(relay, at))).len(), + 1 + ); + publish_state(2, at); + publish_state(3, at); + assert!( + vehicle_states(&opened(&owner, &publish_all(relay, at))).is_empty(), + "within the interval" + ); + let later = at + RELAY_MIN_STATE_INTERVAL_MS; + let vehicle = vehicle_states(&opened(&owner, &publish_all(relay, later))); + assert_eq!(vehicle.len(), 1, "the newest one"); + assert_eq!(vehicle[0].basic_state_bytes, vec![0x08, 0x03]); +} + +#[test] +fn an_idle_session_gets_state_at_the_idle_rate() { + let relay = boot(); + let owner = connect(relay, OWNER_STATIC); + // Nothing received from the client for longer than the activity window. + let idle = now() + RELAY_ACTIVITY_WINDOW_MS + 1_000; + publish_state(1, idle); + assert_eq!( + vehicle_states(&opened(&owner, &publish_all(relay, idle))).len(), + 1 + ); + publish_state(2, idle); + let soon = idle + RELAY_MIN_STATE_INTERVAL_MS; + assert!(vehicle_states(&opened(&owner, &publish_all(relay, soon))).is_empty()); + let due = idle + RELAY_IDLE_STATE_INTERVAL_MS; + assert_eq!( + vehicle_states(&opened(&owner, &publish_all(relay, due))).len(), + 1 + ); +} + +#[test] +fn a_new_handshake_moves_the_state_to_the_clients_new_session() { + let relay = boot(); + let at = now(); + let _old = connect(relay, OWNER_STATIC); + let _ = publish_all(relay, at); + let new = connect(relay, OWNER_STATIC); + assert_eq!(relay_session_count(), 1); + publish_state(1, at); + let frames = publish_all(relay, at); + assert!(!frames.is_empty()); + // Every frame opens with the new session's keys. + assert_eq!(vehicle_states(&opened(&new, &frames)).len(), 1); +} + +// ── Commands ────────────────────────────────────────────────────────────────── + +#[test] +fn a_validated_phones_basic_command_reaches_the_vehicle_and_is_answered_on_its_topic() { + let relay = boot(); + let mut owner = connect(relay, OWNER_STATIC); + let _ = publish_all(relay, now()); + let id = next_id(); + assert_eq!(owner.send(&basic_command(id)), None); + let cmd = core_interface::BASIC_CMD_CHANNEL + .try_receive() + .expect("the command reaches the vehicle"); + assert_eq!(cmd.source_device_id, OWNER); + assert!(cmd.authorization.is_some()); + embassy_futures::block_on(route_single_response( + cmd.transport, + proto::CommandResponse { + message_id: id, + success: true, + status_code: proto::CommandStatusCode::Ok as i32, + ..Default::default() + }, + now(), + )); + let frames = publish_all(relay, now()); + let responses: Vec<_> = opened(&owner, &frames) + .into_iter() + .filter_map(|m| match m.payload { + Some(Out::CommandResponse(r)) => Some(r), + _ => None, + }) + .collect(); + assert_eq!(responses.len(), 1); + assert_eq!(responses[0].message_id, id); +} + +#[test] +fn advanced_commands_are_refused_over_the_relay() { + let relay = boot(); + let mut owner = connect(relay, OWNER_STATIC); + let _ = publish_all(relay, now()); + let mut msg = basic_command(next_id()); + msg.payload = Some(Payload::AdvancedCommandBytes(vec![0x0A, 0x00])); + owner.send(&msg); + assert!(core_interface::ADVANCED_CMD_CHANNEL.try_receive().is_err()); + let response = opened(&owner, &publish_all(relay, now())) + .into_iter() + .find_map(|m| match m.payload { + Some(Out::CommandResponse(r)) => Some(r), + _ => None, + }) + .expect("refused with an answer"); + assert_eq!( + response.status_code, + proto::CommandStatusCode::RejectedUnavailable as i32 + ); +} + +#[test] +fn plaintext_is_never_accepted_from_the_broker() { + let relay = boot(); + let owner = client_key_id(OWNER_STATIC); + let reply = embassy_futures::block_on(relay_receive_frame( + relay, + &device_topic(&owner), + &basic_command(next_id()).encode_to_vec(), + )); + assert!(core_interface::BASIC_CMD_CHANNEL.try_receive().is_err()); + // At most an unknown session hint, never anything decrypted. + if let Some(reply) = reply { + assert_eq!(reply.frame[0], 5); + } +} + +// ── Broker sessions ─────────────────────────────────────────────────────────── + +#[test] +fn a_broker_reconnect_ends_the_sessions_and_the_client_is_told_on_its_topic() { + let relay = boot(); + let mut owner = connect(relay, OWNER_STATIC); + relay_disconnect(relay); + assert_eq!(relay_session_count(), 0); + let relay = relay_connect().unwrap(); + owner.relay = relay; + let frame = owner.frame(&basic_command(next_id()).encode_to_vec()); + let reply = embassy_futures::block_on(relay_receive_frame( + relay, + &device_topic(&owner.key_id), + &frame, + )) + .expect("an unknown session frame"); + assert_eq!(reply.topic, client_topic(&owner.key_id)); + assert_eq!(reply.frame, [&[5u8][..], &owner.session_id[..]].concat()); + assert!(core_interface::BASIC_CMD_CHANNEL.try_receive().is_err()); +} + +#[test] +fn a_stale_broker_session_is_ignored() { + let old = boot(); + let _new = relay_connect().unwrap(); + let (_, _, frame) = init_frame(OWNER_STATIC); + assert_eq!( + embassy_futures::block_on(relay_receive_frame( + old, + &device_topic(&client_key_id(OWNER_STATIC)), + &frame, + )), + None + ); + assert_eq!(relay_try_next_frame(old, now()), None); +} diff --git a/core-interface/tests/routing.rs b/core-interface/tests/routing.rs index 0b56b47..8b00b61 100644 --- a/core-interface/tests/routing.rs +++ b/core-interface/tests/routing.rs @@ -1,24 +1,18 @@ use core_interface::{ - BLE_STATE_TX, BLE_TX_CHANNEL, MQTT_STATE_TX, MQTT_TX_CHANNEL, Transport, VehicleStatePayload, - init, latest_ble_state, proto, publish_single_state, record_mqtt_activity, - reset_latest_ble_state_for_tests, reset_mqtt_throttle_for_tests, route_single_response, - set_link_up, + BLE_STATE_TX, BLE_TX_CHANNEL, Transport, VehicleStatePayload, init, latest_ble_state, proto, + publish_single_state, reset_latest_ble_state_for_tests, route_single_response, set_link_up, }; const PLATFORM_ID: u32 = 0xCAFE_BABE; const TS: u64 = 12345; -/// Drain both outbound channels and state slots, bring both links up and reset -/// throttle state so earlier tests don't pollute later ones when running under -/// `cargo test` (single process, shared statics). +/// Drain the outbound channel and state slot and bring the link up so earlier tests +/// don't pollute later ones when running under `cargo test` (single process, shared +/// statics). fn drain_tx_channels() { - while MQTT_TX_CHANNEL.try_receive().is_ok() {} while BLE_TX_CHANNEL.try_receive().is_ok() {} BLE_STATE_TX.reset(); - MQTT_STATE_TX.reset(); set_link_up(Transport::Ble, true); - set_link_up(Transport::Mqtt, true); - reset_mqtt_throttle_for_tests(); } fn response_id(msg: proto::DeviceToApp) -> u64 { @@ -52,24 +46,6 @@ fn ble_response_goes_to_ble_tx_only() { msg.payload, Some(proto::device_to_app::Payload::CommandResponse(_)) )); - assert!(MQTT_TX_CHANNEL.try_receive().is_err()); -} - -#[test] -fn mqtt_response_goes_to_mqtt_tx_only() { - drain_tx_channels(); - init(PLATFORM_ID); - let resp = make_response(2); - embassy_futures::block_on(route_single_response(Transport::Mqtt, resp, TS)); - let msg = MQTT_TX_CHANNEL - .try_receive() - .expect("MQTT_TX has no message"); - assert_eq!(msg.timestamp_ms, TS); - assert!(matches!( - msg.payload, - Some(proto::device_to_app::Payload::CommandResponse(_)) - )); - assert!(BLE_TX_CHANNEL.try_receive().is_err()); } #[test] @@ -86,28 +62,8 @@ fn responses_are_dropped_while_the_link_is_down() { drain_tx_channels(); init(PLATFORM_ID); set_link_up(Transport::Ble, false); - set_link_up(Transport::Mqtt, false); embassy_futures::block_on(route_single_response(Transport::Ble, make_response(5), TS)); - embassy_futures::block_on(route_single_response(Transport::Mqtt, make_response(6), TS)); assert!(BLE_TX_CHANNEL.try_receive().is_err()); - assert!(MQTT_TX_CHANNEL.try_receive().is_err()); -} - -#[test] -fn mqtt_responses_are_not_stuck_behind_ble_with_no_phone_connected() { - drain_tx_channels(); - init(PLATFORM_ID); - set_link_up(Transport::Ble, false); - // Many BLE responses with nobody to take them: each returns at once. - for id in 10..20 { - embassy_futures::block_on(route_single_response(Transport::Ble, make_response(id), TS)); - } - embassy_futures::block_on(route_single_response( - Transport::Mqtt, - make_response(20), - TS, - )); - assert_eq!(response_id(MQTT_TX_CHANNEL.try_receive().unwrap()), 20); } #[test] @@ -167,14 +123,8 @@ fn a_response_waiting_for_room_is_sent_once_there_is_room() { fn state_updates_never_push_out_responses() { drain_tx_channels(); init(PLATFORM_ID); - record_mqtt_activity((TS / 1000) as u32); for id in 60..64 { embassy_futures::block_on(route_single_response(Transport::Ble, make_response(id), TS)); - embassy_futures::block_on(route_single_response( - Transport::Mqtt, - make_response(id), - TS, - )); } for basic in 0..10u8 { let payload = VehicleStatePayload { @@ -183,22 +133,18 @@ fn state_updates_never_push_out_responses() { }; embassy_futures::block_on(publish_single_state(payload, TS)); } - for channel in [&BLE_TX_CHANNEL, &MQTT_TX_CHANNEL] { - let ids: Vec = core::iter::from_fn(|| channel.try_receive().ok()) - .map(response_id) - .collect(); - assert_eq!(ids, vec![60, 61, 62, 63]); - } - // Only the newest state waits in each slot. - for slot in [&BLE_STATE_TX, &MQTT_STATE_TX] { - match slot.try_take().expect("no state").payload { - Some(proto::device_to_app::Payload::StateUpdate(update)) => { - assert_eq!(update.vehicle_state.unwrap().basic_state_bytes, vec![9]); - } - other => panic!("unexpected payload: {:?}", other), + let ids: Vec = core::iter::from_fn(|| BLE_TX_CHANNEL.try_receive().ok()) + .map(response_id) + .collect(); + assert_eq!(ids, vec![60, 61, 62, 63]); + // Only the newest state waits in the slot. + match BLE_STATE_TX.try_take().expect("no state").payload { + Some(proto::device_to_app::Payload::StateUpdate(update)) => { + assert_eq!(update.vehicle_state.unwrap().basic_state_bytes, vec![9]); } - assert!(slot.try_take().is_none()); + other => panic!("unexpected payload: {:?}", other), } + assert!(BLE_STATE_TX.try_take().is_none()); } // ── publish_single_state ────────────────────────────────────────────────────── @@ -228,48 +174,17 @@ fn ble_receives_full_state_basic_and_advanced() { } } -#[test] -fn mqtt_receives_basic_only_advanced_is_empty() { - drain_tx_channels(); - init(PLATFORM_ID); - let payload = VehicleStatePayload { - basic: vec![0xAA], - advanced: vec![0xBB, 0xCC], - }; - embassy_futures::block_on(publish_single_state(payload, TS)); - - let msg = MQTT_STATE_TX - .try_take() - .expect("MQTT_TX has no state message"); - match msg.payload { - Some(proto::device_to_app::Payload::StateUpdate(update)) => { - let vs = update - .vehicle_state - .expect("no vehicle_state in MQTT update"); - assert_eq!(vs.basic_state_bytes, vec![0xAA]); - assert!( - vs.advanced_state_bytes.is_empty(), - "MQTT must not include advanced bytes" - ); - } - other => panic!("unexpected MQTT payload: {:?}", other), - } -} - #[test] fn state_publish_carries_correct_timestamp() { drain_tx_channels(); init(PLATFORM_ID); - // timestamp = 9999 ms = 9 s; LAST_MQTT_RX_SECS = 0 → elapsed = 9 s < 35 s → active let payload = VehicleStatePayload { basic: vec![], advanced: vec![], }; embassy_futures::block_on(publish_single_state(payload, 9999)); let ble_msg = BLE_STATE_TX.try_take().unwrap(); - let mqtt_msg = MQTT_STATE_TX.try_take().unwrap(); assert_eq!(ble_msg.timestamp_ms, 9999); - assert_eq!(mqtt_msg.timestamp_ms, 9999); } // ── latest_ble_state ────────────────────────────────────────────────────────── @@ -327,127 +242,3 @@ fn command_responses_do_not_replace_latest_ble_state() { Some(proto::device_to_app::Payload::StateUpdate(_)) )); } - -// ── MQTT throttle ───────────────────────────────────────────────────────────── - -#[test] -fn mqtt_suppressed_in_idle_when_within_30s() { - drain_tx_channels(); - init(PLATFORM_ID); - // LAST_MQTT_RX_SECS = 0. Publish at t = 40 s → elapsed since RX = 40 > 35 → idle. - // LAST_MQTT_STATE_SECS = 0 → elapsed since last state = 40 s > 30 s → allowed. - // Send at t = 40 s first to set LAST_MQTT_STATE_SECS = 40. - let payload = VehicleStatePayload { - basic: vec![0x01], - advanced: vec![], - }; - embassy_futures::block_on(publish_single_state(payload, 40_000)); - let _ = BLE_STATE_TX.try_take().unwrap(); - MQTT_STATE_TX.try_take().unwrap(); // first idle send allowed - - // Now publish at t = 60 s → elapsed since last state = 20 s < 30 s → suppressed. - let payload2 = VehicleStatePayload { - basic: vec![0x01], - advanced: vec![], - }; - embassy_futures::block_on(publish_single_state(payload2, 60_000)); - let _ = BLE_STATE_TX.try_take().unwrap(); - assert!( - MQTT_STATE_TX.try_take().is_none(), - "MQTT must be suppressed in idle within 30 s window" - ); -} - -#[test] -fn mqtt_allowed_in_idle_after_30s() { - drain_tx_channels(); - init(PLATFORM_ID); - // LAST_MQTT_RX_SECS = 0. Publish at t = 100 s → idle. - // LAST_MQTT_STATE_SECS = 0 → elapsed = 100 s >= 30 s → allowed. - let payload = VehicleStatePayload { - basic: vec![0x01], - advanced: vec![], - }; - embassy_futures::block_on(publish_single_state(payload, 100_000)); - let _ = BLE_STATE_TX.try_take().unwrap(); - assert!( - MQTT_STATE_TX.try_take().is_some(), - "MQTT must be allowed in idle after 30 s" - ); -} - -#[test] -fn mqtt_idle_rate_resets_after_send() { - drain_tx_channels(); - init(PLATFORM_ID); - // First idle send at t = 100 s — sets LAST_MQTT_STATE_SECS = 100. - let p = || VehicleStatePayload { - basic: vec![0x01], - advanced: vec![], - }; - embassy_futures::block_on(publish_single_state(p(), 100_000)); - let _ = BLE_STATE_TX.try_take().unwrap(); - MQTT_STATE_TX.try_take().unwrap(); // first send allowed - - // Second send at t = 129 s → elapsed since last state = 29 s < 30 s → suppressed. - embassy_futures::block_on(publish_single_state(p(), 129_000)); - let _ = BLE_STATE_TX.try_take().unwrap(); - assert!( - MQTT_STATE_TX.try_take().is_none(), - "MQTT must be suppressed within 30 s of last idle send" - ); - - // Third send at t = 131 s → elapsed = 31 s >= 30 s → allowed. - embassy_futures::block_on(publish_single_state(p(), 131_000)); - let _ = BLE_STATE_TX.try_take().unwrap(); - assert!( - MQTT_STATE_TX.try_take().is_some(), - "MQTT must be allowed after 30 s idle gap" - ); -} - -#[test] -fn mqtt_not_throttled_when_client_active() { - drain_tx_channels(); - init(PLATFORM_ID); - // Simulate heartbeat at t = 50 s; publish state at t = 60 s. - // elapsed since RX = 10 s < 35 s → active → all sends go through. - record_mqtt_activity(50); - let p = || VehicleStatePayload { - basic: vec![0x01], - advanced: vec![], - }; - embassy_futures::block_on(publish_single_state(p(), 60_000)); - let _ = BLE_STATE_TX.try_take().unwrap(); - assert!( - MQTT_STATE_TX.try_take().is_some(), - "MQTT must not be throttled while a client is active" - ); - - // Still active — second send at t = 70 s (elapsed = 20 s < 35 s). - embassy_futures::block_on(publish_single_state(p(), 70_000)); - let _ = BLE_STATE_TX.try_take().unwrap(); - assert!( - MQTT_STATE_TX.try_take().is_some(), - "MQTT must continue sending while within activity window" - ); -} - -#[test] -fn ble_never_throttled_regardless_of_mqtt_activity() { - drain_tx_channels(); - init(PLATFORM_ID); - // No recent MQTT activity; publish many states — BLE always receives all of them. - let p = || VehicleStatePayload { - basic: vec![0x01], - advanced: vec![], - }; - for i in 0u64..5 { - embassy_futures::block_on(publish_single_state(p(), 40_000 + i * 1_000)); - assert!( - BLE_STATE_TX.try_take().is_some(), - "BLE must always receive state updates" - ); - let _ = MQTT_STATE_TX.try_take(); // may or may not be present — don't care - } -} diff --git a/docs/architecture.md b/docs/architecture.md index ec63ef4..31f9946 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -2,24 +2,24 @@ Open Car Firmware is an embedded Rust monorepo for the hardware controller (ESP32 / Raspberry Pi). It handles CAN bus reading/writing, BLE/WiFi/LTE connections, and OTA updates. -Related docs: [BLE](ble.md) · [CAN bus](can.md) · [LTE](lte.md) · [Vehicle commands](commands.md) · [Testing](testing.md) · [Releases & OTA](releases.md) · [Hardware setup](hardware-setup.md) +Related docs: [BLE](ble.md) · [CAN bus](can.md) · [LAN direct](lan.md) · [MQTT relay](mqtt-relay.md) · [LTE](lte.md) · [Vehicle commands](commands.md) · [Testing](testing.md) · [Releases & OTA](releases.md) · [Hardware setup](hardware-setup.md) ## Cargo workspace & xtask ### `core-interface` -The intermediary between transport layers (BLE/MQTT) and vehicle logic. Knows nothing about specific cars or boards. Uses Embassy throughout (`embassy_time`, `embassy_sync`, `embassy_executor`). +The intermediary between transport layers (BLE, and the secure channel over the LAN and the MQTT relay) and vehicle logic. Knows nothing about specific cars or boards. Uses Embassy throughout (`embassy_time`, `embassy_sync`, `embassy_executor`). -* Defines 12 static `Channel`s as the inter-crate contract (see [Channels](#channels)). +* Defines static `Channel`s as the inter-crate contract (see [Channels](#channels)). * Defines shared types: `Transport`, `InboundCommand`, `VehicleStatePayload`, `CanLogFrame`. -* Defines pure-logic `#[embassy_executor::task]` functions: `process_ble_commands_task`, `process_mqtt_commands_task`, `route_responses_task`, `publish_state_task`, `publish_can_access_task`, `publish_command_availability_task`, `publish_can_bus_health_task`. +* Defines pure-logic `#[embassy_executor::task]` functions: `process_ble_commands_task`, `route_responses_task`, `publish_state_task`, `publish_can_access_task`, `publish_command_availability_task`, `publish_can_bus_health_task`. * Exposes `pub fn passes_filter()`, `pub fn is_can_read_only()`, `pub fn set_can_read_only(bool)`, the CAN read-write policy (car identity, owner approval, dev lock; see [CAN](can.md#read-write-policy)), the CAN TX classes (`CanTxFrame`, `CommandAuthorization`; see [CAN](can.md#tx-classes)), phone trust and validation sessions (see [BLE](ble.md#phone-trust)), the secure channel's keys (the device identity and the client key registry, see [BLE](ble.md#device-identity)), and the SavvyCAN logging API (`is_can_logging`, `log_can_frame`, `run_can_log_session`). -* Has 4 inner async helpers (`handle_ble_message`, `handle_mqtt_message`, `route_single_response`, `publish_single_state`) extracted from the task loops so they can be unit-tested without running an executor. -* **`publish_single_state` is intentionally non-blocking:** state updates don't go through the TX queues. Each transport has a single-value slot (`BLE_STATE_TX`, `MQTT_STATE_TX`, embassy `Signal`s) that the newest update overwrites. This guarantees `publish_state_task` never stalls, keeping `VEHICLE_STATE_CHANNEL` always drainable and preventing a deadlock cascade through `state_update_task` and command-handler tasks, and a state update can never push a command response out of a queue. +* Has inner async helpers (`handle_ble_message`, `handle_secure_message`, `route_single_response`, `publish_single_state`) extracted from the task loops so they can be unit-tested without running an executor. +* **`publish_single_state` is intentionally non-blocking:** state updates don't go through the TX queues. BLE has a single-value slot (`BLE_STATE_TX`, an embassy `Signal`) that the newest update overwrites, and the secure channel's sessions (LAN, relay) are only told a new state is there: each reads the latest one when it is due. This guarantees `publish_state_task` never stalls, keeping `VEHICLE_STATE_CHANNEL` always drainable and preventing a deadlock cascade through `state_update_task` and command-handler tasks, and a state update can never push a command response out of a queue. * Uses `#![cfg_attr(not(test), no_std)]` so host tests compile without a `no_std` target. * Internally organised into modules (`types`, `channels`, `can`, `can_log`, `dispatch`, `routing`, …); all public symbols are re-exported from `lib.rs`. ### Board crates (`board-esp`, `board-pc`) -Compiled as `rlib`. Each exports a single `pub fn start(spawner: &Spawner)` that spawns the `core-interface` tasks. Board crates have no knowledge of vehicle logic or protos — they only drive hardware peripherals (radio, CAN, LTE) by reading/writing the edge channels (`BLE_RX_CHANNEL`, `BLE_TX_CHANNEL`, `MQTT_RX_CHANNEL`, `MQTT_TX_CHANNEL`, and the `BLE_STATE_TX` / `MQTT_STATE_TX` state slots), and report each transport's link with `set_link_up` (see [Transport links](#transport-links-and-responses)). +Compiled as `rlib`. Each exports a single `pub fn start(spawner: &Spawner)` that spawns the `core-interface` tasks. Board crates have no knowledge of vehicle logic or protos — they only drive hardware peripherals (radio, CAN, LTE) by reading/writing the edge channels (`BLE_RX_CHANNEL`, `BLE_TX_CHANNEL` and the `BLE_STATE_TX` state slot) and moving the secure channel's frames through `core-interface` (`lan_*`, `relay_*`), and report the BLE link with `set_link_up` (see [Transport links](#transport-links-and-responses)). ### Vehicle crates (`cars/*`) Compiled as `rlib`. Each exports 3 `#[embassy_executor::task]` functions: `handle_basic_commands_task`, `handle_advanced_commands_task`, and `state_update_task`. They read from `BASIC_CMD_CHANNEL` / `ADVANCED_CMD_CHANNEL`, write results to `CMD_RESP_CHANNEL`, and push state updates to `VEHICLE_STATE_CHANNEL`. They depend on `core-interface` for the channel statics and shared types, but never touch board code. @@ -61,15 +61,12 @@ The actual binary entry point. Generated fresh by `xtask` before every build fro | `BLE_RX_CHANNEL` | board → core | `AppToDevice` | Raw inbound proto from BLE driver | | `BLE_TX_CHANNEL` | core → board | `DeviceToApp` | Responses and system state to the BLE driver; only filled while the link is up | | `BLE_STATE_TX` | core → board | `DeviceToApp` | Newest vehicle state for BLE (a `Signal`: one value, overwritten); sent after `BLE_TX_CHANNEL` | -| `MQTT_RX_CHANNEL` | board → core | `AppToDevice` | Raw inbound proto from MQTT driver | -| `MQTT_TX_CHANNEL` | core → board | `DeviceToApp` | Responses and system state to the MQTT driver; only filled while the session is up | -| `MQTT_STATE_TX` | core → board | `DeviceToApp` | Newest vehicle state for MQTT, basic only and throttled (a `Signal`); sent after `MQTT_TX_CHANNEL` | | `SYSTEM_COMMAND_CHANNEL` | core → board | `SystemCommand` | BLE only; board handles restart (already answered by core, see [BLE](ble.md#restart)) and phone removal (the CAN read-write commands, `ListPairedPhones` and phone validation are handled in core) | -| `BASIC_CMD_CHANNEL` | core → vehicle | `InboundCommand` | From BLE and the secure channel (plain MQTT is rejected) | +| `BASIC_CMD_CHANNEL` | core → vehicle | `InboundCommand` | From BLE and the secure channel | | `ADVANCED_CMD_CHANNEL` | core → vehicle | `InboundCommand` | From BLE and the secure channel | | `CMD_RESP_CHANNEL` | vehicle → core | `(Transport, CommandResponse)` | Transport tag routes response back | -| `SECURE_TX_CHANNEL` | core → transport | `(SessionHandle, DeviceToApp)` | Responses for a [secure channel](#secure-channel) session on the relay, for it to `seal`; never waited on. LAN sessions use a queue per connection inside core ([LAN direct](lan.md)) | -| `VEHICLE_STATE_CHANNEL` | vehicle → core | `VehicleStatePayload` | BLE gets full; MQTT and the secure channel (LAN) get basic only | +| `SECURE_TX_CHANNEL` | core → transport | `(SessionHandle, DeviceToApp)` | Responses for a [secure channel](#secure-channel) session on the relay, sealed by `relay_try_next_frame`; never waited on. LAN sessions use a queue per connection inside core ([LAN direct](lan.md)) | +| `VEHICLE_STATE_CHANNEL` | vehicle → core | `VehicleStatePayload` | BLE gets full; the secure channel (LAN, relay) gets basic only | | `CAN_RX_CHANNEL` | board → vehicle | `CanFrame` | Hardware-received CAN frame | | `CAN_TX_CHANNELS[bus_id]` | vehicle → board | `CanTxFrame` | Frame to transmit on that CAN bus, with its TX class (one queue per bus; see [CAN bus](can.md#tx-classes)) | | `CAN_LOG_CHANNEL` | board → logger session | `CanLogFrame` | Raw (pre-filter) frames for the SavvyCAN logger, only filled while a client is connected; see [CAN bus](can.md#savvycan-logging) | @@ -79,32 +76,32 @@ The actual binary entry point. Generated fresh by `xtask` before every build fro ### Transport links and responses A response goes back on the transport its command came in on. If that transport is gone, the response is dropped: the app re-reads the state, which stays the source of truth (contracts#7). -* Each board driver calls `set_link_up(Transport, bool)`: the ESP BLE transport when a phone connects and when the connection closes, both MQTT drivers when the session is ready and when it ends. The PC BLE mock (HTTP, no connections) reports BLE up once at start. Links are down at boot. -* Everything core queues on `BLE_TX_CHANNEL` / `MQTT_TX_CHANNEL` (responses, CAN access state, command availability) goes through `routing::send_to` / `try_send_to`, which drop the message while the link is down. Going down clears that transport's queue, so a message queued for one phone is never delivered to the next. -* `send_to` (responses) waits for room while the link stays up, but gives up once the link goes down, even if another peer connected since (a per-link generation counter). Clearing the queue wakes it. So with no phone connected, `route_responses_task` never waits on BLE, and MQTT responses never queue up behind it. -* While a phone is connected but not reading, a BLE response still waits for room, which holds MQTT responses behind it until the link drops. +* Each board driver calls `set_link_up(Transport, bool)`: the ESP BLE transport when a phone connects and when the connection closes. The PC BLE mock (HTTP, no connections) reports BLE up once at start. Links are down at boot. +* Everything core queues on `BLE_TX_CHANNEL` (responses, CAN access state, command availability) goes through `routing::send_to` / `try_send_to`, which drop the message while the link is down. Going down clears that transport's queue, so a message queued for one phone is never delivered to the next. +* `send_to` (responses) waits for room while the link stays up, but gives up once the link goes down, even if another peer connected since (a per-link generation counter). Clearing the queue wakes it. So with no phone connected, `route_responses_task` never waits on BLE, and secure channel responses never queue up behind it. +* While a phone is connected but not reading, a BLE response still waits for room, which holds other responses behind it until the link drops. A secure channel session's responses never wait (`try_send` to its queue). * A response the vehicle is still working on when its phone leaves isn't tied to that connection: if another phone connects before it is sent, that phone gets it. `CMD_RESP_CHANNEL` only carries the `Transport`. ### Duplicate commands -The app may resend a command with the same `message_id` after switching transport or reconnecting, and the broker redelivers an MQTT QoS 1 message it didn't see acknowledged. Both dispatchers drop a command whose (source, `message_id`) pair they saw in the last `DEDUPE_WINDOW_MS` (5 min, at most `DEDUPE_CAPACITY` = 16 entries, oldest forgotten first), without answering it (`dedupe.rs`). Heartbeats aren't commands and aren't remembered; `message_id` 0 (the proto default) never counts as a duplicate. The source is the transport-verified one: the BLE address, or a secure channel session's client ID, which for a phone is the same `ble:` ID, so a resend from BLE to the secure channel (or back) is caught. Plain MQTT has none, so its commands are keyed by `message_id` alone and only match each other. +The app may resend a command with the same `message_id` after switching transport or reconnecting, and the broker redelivers an MQTT QoS 1 message it didn't see acknowledged. Both dispatchers drop a command whose (source, `message_id`) pair they saw in the last `DEDUPE_WINDOW_MS` (5 min, at most `DEDUPE_CAPACITY` = 16 entries, oldest forgotten first), without answering it (`dedupe.rs`). Heartbeats aren't commands and aren't remembered; `message_id` 0 (the proto default) never counts as a duplicate. The source is the transport-verified one: the BLE address, or a secure channel session's client ID, which for a phone is the same `ble:` ID, so a resend from BLE to the secure channel (or back) is caught. **`platform_id`** is a CRC32 of the proto package name (e.g. `0xF7544D7E` for `opencar.cars.virtual_car.v1`), pre-computed and stored in `contracts/.../meta.toml`. xtask injects it as a compile-time constant into `.app_build/src/main.rs`. `core_interface::init(platform_id)` stores it in an `AtomicU32`; the dispatcher tasks validate every inbound message against it and silently drop mismatches. -**Read-only devices:** while the device is CAN read-only, both dispatchers answer `BasicCommandBytes` and `AdvancedCommandBytes` with a failed `CommandResponse` giving the reason instead of routing them (see [CAN](can.md#read-write-policy)). Over BLE they are then refused from a phone that isn't validated in the car (`REJECTED_NOT_VALIDATED`, see [BLE](ble.md#phone-trust)). +**Read-only devices:** while the device is CAN read-only, both dispatchers (BLE, secure channel) answer `BasicCommandBytes` and `AdvancedCommandBytes` with a failed `CommandResponse` giving the reason instead of routing them (see [CAN](can.md#read-write-policy)). Over BLE they are then refused from a phone that isn't validated in the car (`REJECTED_NOT_VALIDATED`, see [BLE](ble.md#phone-trust)). **Secure channel:** see [Secure channel](#secure-channel): vehicle commands get the same checks as over BLE for the session's client, and system commands are dropped. -**MQTT restrictions:** `SystemCommand` and `AdvancedCommandBytes` are restricted to BLE and silently dropped from MQTT. `BasicCommandBytes` are **rejected for now** as well: MQTT commands aren't authenticated (anyone the broker lets publish to the command topic, with credentials or a certificate that ship in the app, could send or replay one; TLS protects the link, not the commands), so `handle_mqtt_message` answers them with a failed `CommandResponse` saying so and never queues them to `BASIC_CMD_CHANNEL`. The gate is the `MQTT_COMMANDS_AUTHENTICATED` constant in `dispatch.rs`; remove it once MQTT commands are authenticated (contracts#8, firmware#16). State updates and heartbeats over MQTT are unaffected. +**No plaintext MQTT:** the broker is only a relay for secure channel frames (see [MQTT relay](mqtt-relay.md)); nothing else is accepted from it. ### Secure channel The device side of the end-to-end encrypted channel ([contracts `docs/secure-channel.md`](https://github.com/OpenCarControls/contracts/blob/main/docs/secure-channel.md)): `Noise_IK_25519_ChaChaPoly_BLAKE2s` between an enrolled client and the device, the same on every transport that carries its frames. `noise.rs` implements the handshake (the device is the responder) and the cipher states from the Noise specification on `x25519-dalek`, `chacha20poly1305` and `blake2`, and its tests pass the contracts' `secure-channel-vectors.json` byte for byte. (`clatter`, a `no_std` Noise crate, was considered; the IK pattern alone is short, and doing it directly gives the explicit nonces and the fixed ephemeral keys the vectors need without its generic layers.) Its constants come from `[secure_channel]` in `transport.toml`, generated by the build script. -* **Transports stay dumb.** A transport hands each received frame to `process_secure_frame(link, bytes)` with the `ChannelLink` it came on (its kind, `Lan` or `Relay`, and a connection number), sends back the reply it returns on that link, and reports a closed connection with `close_link`. All the crypto is in `core-interface`. The LAN goes through `lan.rs`, which wraps these per connection and also decides what each session is sent (see [LAN direct](lan.md)); the relay (firmware#122) will drain `SECURE_TX_CHANNEL`, sealing each message with `seal(session, msg)` (which also gives the link). +* **Transports stay dumb.** A transport hands each received frame to `process_secure_frame(link, bytes)` with the `ChannelLink` it came on (its kind, `Lan` or `Relay`, and a connection number), sends back the reply it returns on that link, and reports a closed connection with `close_link`. All the crypto is in `core-interface`. The LAN goes through `lan.rs`, which wraps these per connection and also decides what each session is sent (see [LAN direct](lan.md)); the relay goes through `relay.rs`, which names each client's topic and decides what each session is sent (see [MQTT relay](mqtt-relay.md)). A transport that names the sender (the relay's topic carries the client's key ID) uses `process_secure_frame_from`, and the handshake is dropped unless the key matches. * **Handshake rate.** At most `MAX_HANDSHAKE_INITS_PER_SECOND` (8) inits are processed per second, all transports together, checked before any X25519 work; the rest are dropped unanswered. * **Handshake.** A valid handshake init from a key in the registry (`client_for_key`, [BLE](ble.md#client-keys)) creates a session and is answered with the handshake response. An unknown key, or a failed handshake, gets no answer, and an init whose ephemeral key was seen recently is refused (a replay). The ephemeral key comes from the board's random source; without it, or without a device identity, the channel is off. * **Sessions** (`secure_channel.rs`) are RAM-only, keyed by session ID and link, at most `MAX_SESSIONS` (4) and `MAX_SESSIONS_PER_CLIENT` (2); a new one replaces the client's idlest session at its limit, else the idlest one. A session ends after `SESSION_IDLE_TIMEOUT_MS` without a valid frame, `MAX_SESSION_MS` after its handshake, after `MAX_SESSION_MESSAGES` frames one way, when its link closes, and when its client's key leaves the registry (checked on every frame and seal). A transport frame for a session the device doesn't have on that link is answered with an unknown session frame. * **Frames.** Transport frames carry an explicit counter (the nonce); a 64-wide replay window drops duplicates and counters too far behind, and is only updated once a frame decrypts. An empty plaintext is a keepalive. -* **Identity and authorization.** Each `AppToDevice` a session carries is stamped with its client's ID (a phone's `ble:` ID) as `source_device_id`, whatever the client put there, and goes to `handle_secure_message`: every channel transport is the remote tier, so basic vehicle commands get the same checks as that phone over BLE (read-only, validated for this car, controller lease) and a `CommandAuthorization`, and advanced commands are refused with `REJECTED_UNAVAILABLE` (they need Bluetooth). Responses come back through the session (`Transport::Secure(SessionHandle)`, routed to its LAN connection's queue, or to `SECURE_TX_CHANNEL` for the relay). System commands are dropped: they stay BLE-only. The `MQTT_COMMANDS_AUTHENTICATED` gate only applies to plain MQTT, until MQTT carries only channel frames (firmware#122). +* **Identity and authorization.** Each `AppToDevice` a session carries is stamped with its client's ID (a phone's `ble:` ID) as `source_device_id`, whatever the client put there, and goes to `handle_secure_message`: every channel transport is the remote tier, so basic vehicle commands get the same checks as that phone over BLE (read-only, validated for this car, controller lease) and a `CommandAuthorization`, and advanced commands are refused with `REJECTED_UNAVAILABLE` (they need Bluetooth). Responses come back through the session (`Transport::Secure(SessionHandle)`, routed to its LAN connection's queue, or to `SECURE_TX_CHANNEL` for the relay). System commands are dropped: they stay BLE-only. * **Memory.** A session's table entry is about 200 bytes (`SESSION_BYTES`, in a static, not the heap). A handshake only allocates a few small buffers. `seal` builds a frame in one buffer, encrypted in place, and an inbound frame is decrypted into one buffer, so a message costs about its own size on the heap (up to 4 KB for the largest). ### Channel flow @@ -116,19 +113,18 @@ BLE driver ──BLE_RX──▶ core-interface ──BASIC_CMD──── ──ADVANCED_CMD──▶ ──SYSTEM_CMD───▶ board -MQTT driver ──MQTT_RX─▶ core-interface ──BASIC_CMD────▶ vehicle - ◀─MQTT_TX─ ◀─CMD_RESP───── - ◀─MQTT_STATE_TX─ +LAN server ──frames──▶ core-interface ──BASIC_CMD────▶ vehicle +MQTT driver ◀─frames─── (secure channel) ◀─CMD_RESP───── CAN driver ──CAN_RX──▶ vehicle ◀─CAN_TX── ``` ### MQTT driver resilience -Both board MQTT driver tasks (`board-pc` and `board-esp`) apply two rules to stay live under all broker conditions: +Both board MQTT driver tasks (`board-pc` and `board-esp`) apply these rules to stay live under all broker conditions: -1. **Inbound `try_send`:** When a PUBLISH arrives, the payload is forwarded to `MQTT_RX_CHANNEL` via `try_send` (not `.send().await`). Blocking here would deadlock if downstream tasks (`process_mqtt_commands_task` → `BASIC_CMD_CHANNEL` → vehicle → `CMD_RESP_CHANNEL` → `route_responses_task` → `MQTT_TX_CHANNEL`) are all simultaneously full, preventing the driver from draining its own outbound channel. A full `MQTT_RX_CHANNEL` logs a warning and drops the inbound command; the app can retry. -2. **`abort()` skipped for broker `DISCONNECT`:** When the broker sends a `DISCONNECT` packet (e.g. `SessionTakenOver` from a duplicate `client_id`), `poll()` returns `Err(MqttError::Disconnect { .. })` while the TCP stream is still healthy. Calling `abort()` in this case panics inside rust-mqtt. The driver only calls `abort()` for IO/protocol errors, never for `MqttError::Disconnect`. Either way the session ends and the reconnect loop retries after 5 s. +1. **Never wait on a downstream queue it drains itself.** An inbound frame goes to `relay_receive_frame`, which dispatches it; the vehicle's response comes back through `route_responses_task` to the session's queue with `try_send`, so it can never wait on the driver. A publication the MQTT client can't take yet (too many waiting for their PUBACK) is kept and retried after the next poll, never waited on. +2. **`abort()` skipped for broker `DISCONNECT`:** When the broker sends a `DISCONNECT` packet (e.g. `SessionTakenOver`, another connection with the same client ID), `poll()` returns `Err(MqttError::Disconnect { .. })` while the TCP stream is still healthy. Calling `abort()` in this case panics inside rust-mqtt. The driver only calls `abort()` for IO/protocol errors, never for `MqttError::Disconnect`. Either way the session ends (`relay_disconnect`) and the reconnect loop retries after 5 s. ## Board / core-interface contract @@ -136,13 +132,13 @@ Embassy is used freely inside `core-interface`. Boards adapt to it — not the o **Task pattern:** `#[embassy_executor::task]` cannot take generic (`impl Trait`) parameters. The split is: * `core-interface` defines all `static Channel`s and `#[embassy_executor::task]` functions containing all protocol logic. -* Board crates define thin **driver tasks** with concrete hardware types that read/write only the four edge channels (`BLE_RX/TX`, `MQTT_RX/TX`). These are the only hardware-specific tasks. +* Board crates define thin **driver tasks** with concrete hardware types that read/write only the BLE edge channels and hand the secure channel's frames to `core-interface` (`lan_*`, `relay_*`). These are the only hardware-specific tasks. * Vehicle crates define their own Embassy tasks that read/write only the four inner channels (`BASIC_CMD`, `ADVANCED_CMD`, `CMD_RESP`, `VEHICLE_STATE`). * `.app_build` spawns all tasks from all three layers in `main`. **Per-subsystem approach:** * **CAN:** Vehicle crates define their filter list (`&'static [CanFilter]`). Board crates own all hardware; `CAN_RX_CHANNEL` and the per-bus `CAN_TX_CHANNELS` are the shared contract. Each board provides driver functions (`init_*` / `run_*_loop`) and async loop tasks that software-filter received frames against the vehicle's filter list. See [CAN bus](can.md). -* **MQTT / networking:** `core-interface` logic uses `embassy-net::TcpSocket`. Each board provides an `embassy-net::driver::Driver` implementation (on ESP, `esp-radio` WiFi or PPP over an LTE modem with `embassy-net-ppp`, see [LTE](lte.md); tuntap shim on PC). The ESP MQTT driver takes whichever stack the build has and resolves the broker's hostname with the stack's DNS. +* **MQTT / networking:** the board drivers use `embassy-net::TcpSocket` (std sockets on PC). Each board provides an `embassy-net::driver::Driver` implementation (on ESP, `esp-radio` WiFi or PPP over an LTE modem with `embassy-net-ppp`, see [LTE](lte.md); tuntap shim on PC). The ESP MQTT driver takes whichever stack the build has and resolves the broker's hostname with the stack's DNS. * **BLE:** No single cross-platform embassy BLE abstraction exists. `core-interface` defines its own traits (e.g. `trait BleGatt`). ESP implements them with `esp-radio` + `trouble-host`; PC implements them as mocks. See [BLE](ble.md). ## Board-specific requirements @@ -157,9 +153,9 @@ Embassy is used freely inside `core-interface`. Boards adapt to it — not the o * `board-esp` enables esp-radio's `coex` feature: every ESP has a single 2.4 GHz RF front end, and without `coex` WiFi and BLE are not time-sliced and interfere with each other. * BLE: `ble::controller::BleConnector::new(peripherals.BT, ble::Config::default())` (2 args, no `init_radio()` call). * WiFi: `esp_radio::wifi::new(peripherals.WIFI, WifiControllerConfig::default())` returns `(controller, interfaces)`; use `interfaces.station` (not `.sta`); configure with `WifiModeConfig::Station(StationConfig::default().with_ssid(...).with_password(...))`. -* **One uplink per build:** WiFi (`[network.wifi]`) or LTE (`[network.lte]`, needs a `[hardware.esp.modem]`; see [LTE](lte.md)). xtask generates the matching init as `net_stack` and spawns `mqtt_driver_task` on it. With both disabled, xtask omits the network constants and the `mqtt_driver_task` spawn from the generated `main.rs`; `ble_transport_task` is always spawned. +* **Uplinks:** WiFi (`[network.wifi]`), LTE (`[network.lte]`, needs a `[hardware.esp.modem]`; see [LTE](lte.md)), or both. xtask generates the init of the preferred one (WiFi when enabled) as `net_stack`, and with both the LTE stack as `lte_stack`, passed to `mqtt_driver_task` as its fallback. LAN direct and the CAN logger run on `net_stack` when it is WiFi. With both disabled, xtask omits the network constants and the `mqtt_driver_task` spawn from the generated `main.rs`; `ble_transport_task` is always spawned. * **LAN direct:** with `[network.lan] enabled = true` on a WiFi build, xtask enables `board-esp`'s `lan` feature (UDP and multicast in embassy-net) and spawns `start_lan` on `net_stack`: a task per connection and a spare, the UDP probe, and the address and mDNS task. An LTE build leaves it out. See [LAN direct](lan.md#esp-board). -* **MQTT over TLS:** for a `mqtts://` broker xtask enables `board-esp`'s `mqtt-tls` feature (MbedTLS, about 540 KB of flash) and passes the certificates as `MQTT_TLS`; plain builds leave it out. See [MQTT over TLS](mqtt-tls.md). +* **MQTT over TLS:** for a `mqtts://` broker xtask enables `board-esp`'s `mqtt-tls` feature (MbedTLS, about 540 KB of flash) and passes the certificates as `MQTT_TLS`; plain builds leave it out. TLS is optional hardening: the relay's frames are end-to-end encrypted either way. See [MQTT relay](mqtt-relay.md). * With `embassy-net 0.9`, the stack handle is `Stack<'static>` and TCP sockets are created with `TcpSocket::new(*stack, ...)`. * In the final binary crate, `esp-rtos` must enable `features = ["embassy", "esp-radio", "esp-alloc"]`; omitting `esp-radio` leads to unresolved `esp_rtos_*` linker errors. * **Heap/stack tuning warning:** `esp_alloc::heap_allocator!(size = ...)` and the linker-defined CPU0 stack share the same SRAM budget. If heap is too small, esp-radio/RTOS task creation can panic with `Failed to allocate stack`; if heap is too large, CPU0 can hit stack-guard panics. Keep large BLE/network buffers (for example `HostResources`) in `StaticCell` instead of task locals, and for ESP32-S3 with the current task mix prefer around `160 * 1024` heap unless profiling indicates otherwise. diff --git a/docs/ble.md b/docs/ble.md index 88d5dd5..d65c183 100644 --- a/docs/ble.md +++ b/docs/ble.md @@ -59,8 +59,8 @@ Encryption is checked via a per-connection `tx_auth: AtomicBool` (initialized `f ## State on subscribe trouble-host's `notify` sends nothing to a peer that hasn't enabled notifications (and still returns `Ok`), and the app subscribes only after the link is encrypted, so the first state update after connecting would otherwise be lost. `publish_single_state` keeps the last BLE state message in `core_interface::latest_ble_state()` (unlike `BLE_STATE_TX`, it isn't emptied when sent). When the app writes the TX characteristic's CCCD with notifications enabled, `gatt_event_task` signals `ble_tx_notify_task`, which sends that cached state (full state, original timestamp) through the normal path, `SUBSCRIBE_RESEND_DELAY_MS` (500 ms) later: a notification sent right as the CCCD write is accepted was lost on Android, before the app's notification stream was listening. It is still held until the link is encrypted. Nothing is sent if the vehicle hasn't published a state since boot. The CAN access state (`SystemState.can_access`, sent with the connected phone's `SystemState.phone_access`, see [Phone trust](#phone-trust)) the command availability (`SystemState.command_availability`) and the CAN bus health (`SystemState.can_bus_health`) are sent again too (`resend_can_access_state()`, `resend_command_availability()`, `resend_can_bus_health()`), and all three are repeated every few seconds anyway (see [CAN](can.md#read-write-policy), [Vehicle commands](commands.md#command-availability) and [Bus health](can.md#bus-health)). A message the app was already subscribed for may arrive twice; state updates are idempotent. -## MQTT client ID -The access state update also carries the [device identity](#device-identity) and `SystemState.mqtt_client_id`, the `network.mqtt.client_id` this device's topics are built from, and it is unset in a build without MQTT. The app can't know it otherwise, and needs it to use this device's topics. So give each device its own `client_id`. +## Device key ID on the relay +The access state update also carries the [device identity](#device-identity). Its key ID names the device's topics on the [MQTT relay](mqtt-relay.md) and is the device's MQTT client ID, so the app needs nothing else to find it there. `SystemState.mqtt_client_id` is deprecated and no longer sent. ## CAN read-write commands `SetCanReadWriteApprovalCommand` and `SetCanDevWriteUnlockCommand` are handled in `core-interface`'s dispatcher, not forwarded to the board: only from a phone in the paired-phone registry (checked against the stamped `source_device_id`), and answered with a `CommandResponse`. Once a phone is validated for the identified car, the approval needs a validated phone (see [Phone trust](#phone-trust)). Unlike phone management they don't need the pairing window. See [CAN](can.md#read-write-policy) for the policy. @@ -74,7 +74,7 @@ Pairing is Just Works, so bonding during a pairing window doesn't prove the phon | Approved | device + car (`CarDigest`) | The platform's own frames that don't act on the car ([TX classes](can.md#tx-classes)) | The owner's CAN read-write approval, given once at first setup | | Validated | phone + car | Vehicle commands (every basic and advanced command) | An in-car action the vehicle defines | -A vehicle command needs all three, plus the dev lock in development builds. The dispatcher refuses a command from a phone that isn't validated with `COMMAND_STATUS_CODE_REJECTED_NOT_VALIDATED`, after the read-only check, and hands the command it lets through a `CommandAuthorization` for its phone. The board's TX check reads the validation again when the command's frames are sent ([TX classes](can.md#tx-classes)). Plain MQTT has no phone identity and never gets an authorization. Through the [secure channel](architecture.md#secure-channel), a phone's commands carry its `ble:` ID and get exactly these checks and an authorization. +A vehicle command needs all three, plus the dev lock in development builds. The dispatcher refuses a command from a phone that isn't validated with `COMMAND_STATUS_CODE_REJECTED_NOT_VALIDATED`, after the read-only check, and hands the command it lets through a `CommandAuthorization` for its phone. The board's TX check reads the validation again when the command's frames are sent ([TX classes](can.md#tx-classes)). Through the [secure channel](architecture.md#secure-channel), a phone's commands carry its `ble:` ID and get exactly these checks and an authorization. **Validation session** (`validation.rs`), run by `core-interface` with methods from the vehicle: @@ -102,7 +102,7 @@ The board hands what it stored to `restore_device_identity()` at boot and stores ## Client keys A client (the app) reaches the device over the secure channel with its own X25519 static key, which it enrolls over BLE (`EnrollClientKeyCommand`, handled by the dispatcher, `client_keys.rs`): -* Only from a phone validated for the identified car (`REJECTED_NOT_VALIDATED` otherwise), and only over BLE (the MQTT dispatcher drops every system command). The key belongs to the sending phone (`CLIENT_KIND_PHONE`): it is stored under the phone's stamped `ble:` device ID, which the channel will stamp as `source_device_id` on what the phone sends through it. Enrolling again replaces the phone's key. Hubs (`CLIENT_KIND_HUB`), a key that isn't 32 bytes or is all zeros, a label over 32 bytes and a key enrolled by another client are refused. +* Only from a phone validated for the identified car (`REJECTED_NOT_VALIDATED` otherwise), and only over BLE (the secure channel drops every system command). The key belongs to the sending phone (`CLIENT_KIND_PHONE`): it is stored under the phone's stamped `ble:` device ID, which the channel will stamp as `source_device_id` on what the phone sends through it. Enrolling again replaces the phone's key. Hubs (`CLIENT_KIND_HUB`), a key that isn't 32 bytes or is all zeros, a label over 32 bytes and a key enrolled by another client are refused. * It is answered with the device identity. `ListPairedPhones` reports which phones have a key (`remote_key_enrolled`) and its label. * A phone's key goes away with its bond: removing the phone or pairing it again (`forget_phone_validation`), clearing the phones (`clear_paired_phones`), and a bond reset (`prune_phone_validations` at boot drops the keys of phones no longer bonded). A phone that loses its validation, when another car is approved, keeps its key: its vehicle commands are refused like over BLE. * `client_for_key()` maps a static public key to its client's ID and kind, for the channel's handshake. @@ -115,7 +115,7 @@ The keys are persisted like the validations: `encode_client_keys()` (a format ve The registry only mirrors the bonds (restored from flash at startup, updated on pairing and removal), so `ListPairedPhones` reports real bonds; `core-interface` answers it with each phone's trust level. Removing a phone from the registry also ends its validation and drops its [client key](#client-keys). `UpsertPairedPhone` is ignored on ESP: phones enter by pairing. ## Restart -`RestartCommand` is checked and answered by `core-interface`'s dispatcher, then forwarded to the board. It needs a bonded phone, and a validated one once a phone is validated for the identified car (see [Phone trust](#phone-trust)): a restart ends what the device is doing for the owner, such as a battery preconditioning session, and unlocks nothing. A refusal is answered like the approval's and never reaches the board. It doesn't need the pairing window. MQTT drops it, like every system command. +`RestartCommand` is checked and answered by `core-interface`'s dispatcher, then forwarded to the board. It needs a bonded phone, and a validated one once a phone is validated for the identified car (see [Phone trust](#phone-trust)): a restart ends what the device is doing for the owner, such as a battery preconditioning session, and unlocks nothing. A refusal is answered like the approval's and never reaches the board. It doesn't need the pairing window. The secure channel drops it, like every system command. The successful `CommandResponse` is queued before the command reaches the board, which waits `RESTART_RESPONSE_GRACE` (2 s) so the answer reaches the phone before the link goes down. Then: diff --git a/docs/commands.md b/docs/commands.md index e1ec776..9859ba3 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -19,7 +19,7 @@ Every command runs a check before its frames are built. The check is generic and ### The repeat limit Nothing else stops the same command from reaching the car many times in a row: a stuck button, an app bug or a replayed message each carry a new `message_id`, so the dispatcher's dedupe (firmware#15) doesn't catch them. Each command therefore has a minimum interval between two runs (`CommandRequirements::min_interval`, zero for no limit), checked by `admit` right after the requirements and before any frame is built. -* **Per command,** whoever sent it and over whichever transport: the limit protects the car, so another phone or an MQTT client can't get around it. A vehicle keeps one `RepeatGuard` for all its commands, keyed by kind (basic/advanced) and command id. +* **Per command,** whoever sent it and over whichever transport: the limit protects the car, so another phone or another transport can't get around it. A vehicle keeps one `RepeatGuard` for all its commands, keyed by kind (basic/advanced) and command id. * **What counts as a run:** every command that `admit` lets through starts the interval, whether or not it then reaches the car. A command refused by the gate or its requirements doesn't, and neither does one refused for repeating too soon, so the interval always runs from the last run. * **The answer** is a rejection like the others (`Rejection::TooSoon`, `REJECTED_UNAVAILABLE`): `command rejected: the same command was sent too recently, try again in N s`. * **Availability is not affected:** a command stays available inside its interval, so the app's buttons don't flicker after every press. A press inside the interval gets the rejection instead. @@ -27,9 +27,9 @@ Nothing else stops the same command from reaching the car many times in a row: a * System commands (restart, paired phones, CAN access approval, ...) are handled by the dispatcher, never reach a vehicle and have no limit. ### Always answered -A command always gets a `CommandResponse`, including when it is rejected because the device is read-only. The only exceptions are a repeated command, which is dropped unanswered, and a response whose transport is gone by the time it is sent (see [Architecture](architecture.md#transport-links-and-responses)). A rejection is `success: false` with the `COMMAND_STATUS_CODE_REJECTED_UNAVAILABLE` status code and a message that says why. The dispatcher's read-only refusal uses the same code. Vehicles answer through `respond_to_command`, which queues a rejection with `try_send` (`try_send_response`): nothing was sent to the car, so a dropped rejection only costs the app a retry, and waiting on a full `CMD_RESP_CHANNEL` could stall the handler behind the router and the BLE/MQTT drivers (see the `try_send` rules in [Architecture](architecture.md#channel-flow)). The response of a command that did run still uses the blocking send so its result isn't lost. +A command always gets a `CommandResponse`, including when it is rejected because the device is read-only. The only exceptions are a repeated command, which is dropped unanswered, and a response whose transport is gone by the time it is sent (see [Architecture](architecture.md#transport-links-and-responses)). A rejection is `success: false` with the `COMMAND_STATUS_CODE_REJECTED_UNAVAILABLE` status code and a message that says why. The dispatcher's read-only refusal uses the same code. Vehicles answer through `respond_to_command`, which queues a rejection with `try_send` (`try_send_response`): nothing was sent to the car, so a dropped rejection only costs the app a retry, and waiting on a full `CMD_RESP_CHANNEL` could stall the handler behind the router and the BLE driver (see the `try_send` rules in [Architecture](architecture.md#channel-flow)). The response of a command that did run still uses the blocking send so its result isn't lost. -The BLE and MQTT dispatcher already refuses vehicle commands while the device is read-only, before they reach the vehicle (see [CAN bus](can.md#read-write-policy)). The check repeats that against the live flag, because a command can wait in the queue while the policy changes, so the two use the same wording. +The BLE and secure channel dispatchers already refuse vehicle commands while the device is read-only, before they reach the vehicle (see [CAN bus](can.md#read-write-policy)). The check repeats that against the live flag, because a command can wait in the queue while the policy changes, so the two use the same wording. ### In a vehicle crate A handler decodes the command, calls the vehicle's admission function (for E-GMP `commands::admit_basic` / `admit_advanced`, which run `admit` with the command's id), and only if that passes goes on to build frames. It returns a `CommandError` (`Rejected` or `Failed`) and the handler task answers with `respond_to_command`. The requirements are plain functions of the vehicle state, so they are tested with fixture states and no executor. @@ -43,7 +43,7 @@ The app greys out the commands the device would reject, so the requirements are * while the device is read-only every command is unavailable, whatever was reported (a flip is published within a second); * a report older than `REPORT_MAX_AGE_MS` (5 s) counts as unavailable, so a vehicle that stopped reporting can't leave a command shown as available; * over BLE, every command is unavailable while the connected phone isn't validated for this car (see [Phone trust](ble.md#phone-trust)), since the device would refuse its commands (`ble_command_availability_at`). The app offers to validate the phone instead. -* **BLE and MQTT:** BLE gets both command sets. MQTT clients get the basic commands only (advanced commands are BLE only), at the MQTT state's rate: every 5 s while a client is active, once per MQTT idle period otherwise (`publish_command_availability_mqtt`). MQTT commands are not authenticated yet (`MQTT_COMMANDS_AUTHENTICATED`) and the device rejects all of them, so over MQTT every command is reported unavailable until that changes. A secure channel session (the LAN) is the remote tier too: it gets the basic commands as its phone would over BLE, and every advanced command reported unavailable, since they need Bluetooth (`client_command_availability_at`). +* **BLE and the secure channel:** BLE gets both command sets. A secure channel session (the LAN, the MQTT relay) is the remote tier: it gets the basic commands as its phone would over BLE, and every advanced command reported unavailable, since they need Bluetooth (`client_command_availability_at`). The LAN repeats it every 5 s, the relay every 30 s, and both send it at once when it changes. * **States:** `AVAILABLE`, `UNAVAILABLE` (not right now: read-only, state out of date, the car is driving, ...) and `UNSUPPORTED` (not on this car). Nothing sends `UNSUPPORTED` yet; how a car declares it is still to be decided. * **The app** must trust an availability only if it was received on the current connection and treat a command with no entry as unavailable. It never caches or persists it. * **Virtual car:** reports its commands from its simulated state, so the app's grey-out and rejection messages can be tried without a car (see below). Like any other platform they are unavailable until the device is read-write. diff --git a/docs/lan.md b/docs/lan.md index 59a16f3..f37ea11 100644 --- a/docs/lan.md +++ b/docs/lan.md @@ -11,7 +11,7 @@ enabled = true mdns = true ``` -Off by default. It works on the PC board and on ESP WiFi builds. An LTE build never has it (one uplink per build, and a carrier network doesn't let the phone reach the device): xtask says so and leaves it out. +Off by default. It works on the PC board and on ESP builds that join WiFi, including those that also join LTE (LAN direct then runs on WiFi only). An LTE-only build never has it (a carrier network doesn't let the phone reach the device): xtask says so and leaves it out. ## How it fits together @@ -19,8 +19,8 @@ Off by default. It works on the PC board and on ESP WiFi builds. An LTE build ne * **Connection slots.** The board asks `lan_accept(now)` for a slot when a TCP connection arrives. There are `LAN_MAX_CLIENTS` (2) slots. When all are taken, a connection that hasn't completed a handshake loses its slot to the new one; when every connection has a session, the new one is refused, so someone else on the network can't push the phone off. The board closes a connection when `lan_should_close` says so (no handshake within `HANDSHAKE_TIMEOUT_MS`, all its sessions ended, or its slot was taken back) and reports every close with `lan_close`, which ends its sessions. * **Frames in.** The board strips the 2-byte length prefix (a length of 0 or above `MAX_FRAME_BYTES` closes the connection, `lan_frame_length_ok`) and hands each frame to `lan_receive_frame`, which runs the secure channel and the dispatcher, and returns the handshake response or unknown-session frame to send back. -* **Frames out.** `lan_next_frame` (or `lan_try_next_frame` for a polling board) gives the next sealed frame for a connection, newest session first: command responses (a queue of 4 per connection, never waited on), then a system state with the session's client's command availability and `lan_address` (when the session starts, when either changes, and every `LAN_SYSTEM_STATE_REPEAT_MS` (5 s) even unchanged, which the app's receive timeout relies on), then the newest vehicle state, basic only like MQTT's (overwritten while unsent, so state never queues up; not throttled, the LAN is cheap). A client that handshakes again on the same connection moves to its new session. -* **Permissions:** the LAN is the remote tier, like MQTT and the relay: being on the same network is no proof of being at the car. A validated phone may send basic vehicle commands; advanced commands are refused with `REJECTED_UNAVAILABLE` and always reported unavailable to the session; system commands stay BLE-only. A phone that isn't validated is told every command is unavailable. +* **Frames out.** `lan_next_frame` (or `lan_try_next_frame` for a polling board) gives the next sealed frame for a connection, newest session first: command responses (a queue of 4 per connection, never waited on), then a system state with the session's client's command availability and `lan_address` (when the session starts, when either changes, and every `LAN_SYSTEM_STATE_REPEAT_MS` (5 s) even unchanged, which the app's receive timeout relies on), then the newest vehicle state, basic only like the relay's (overwritten while unsent, so state never queues up; not throttled, the LAN is cheap). A client that handshakes again on the same connection moves to its new session. +* **Permissions:** the LAN is the remote tier, like the relay: being on the same network is no proof of being at the car. A validated phone may send basic vehicle commands; advanced commands are refused with `REJECTED_UNAVAILABLE` and always reported unavailable to the session; system commands stay BLE-only. A phone that isn't validated is told every command is unavailable. * **Address.** The board reports its `ip:port` with `set_lan_address` (and `None` when it has none). It goes out as `SystemState.lan_address` with the CAN access state over BLE, and to every LAN session, whenever it changes. * **UDP discovery.** The board hands each datagram on `LAN_UDP_DISCOVERY_PORT` to `lan_discovery_reply`, which checks the probe (length, magic, version, a key ID that is this device's or all zero), limits replies to `LAN_MAX_REPLIES_PER_SECOND`, and builds the reply to send back to the sender. * **mDNS.** `lan_mdns_txt()` gives the TXT records (`id`, the device key ID, and `v`); the board announces `LAN_MDNS_SERVICE` under `lan_mdns_instance_name` (the BLE name and the key ID's first four characters, so two devices with the same name stay apart, and the same on every board), and again when its address changes. Nothing else is announced. Boards without an mDNS library use the responder in `lan_mdns.rs`: `lan_mdns_response` answers questions for the service's PTR, the instance's SRV and TXT, and the host's A record (`opencar-.local`) with all four records, and `lan_mdns_announcement` builds the unsolicited announcement. A query from a port other than 5353 is a one-shot "legacy unicast" query (what the app sends): the answer goes back to its sender with its ID and questions, TTLs of 10 s and no cache-flush bit; other answers go to the group. diff --git a/docs/lte.md b/docs/lte.md index 089c2b4..c663239 100644 --- a/docs/lte.md +++ b/docs/lte.md @@ -1,6 +1,6 @@ # LTE uplink -An ESP board with a cellular modem can reach the MQTT broker over LTE instead of WiFi. The modem is a plain data pipe: the firmware brings it online with AT commands, then runs PPP over the same UART and hands the link to `embassy-net`. Everything above the network stack (the MQTT driver, DNS, TLS) works the same over LTE as over WiFi. +An ESP board with a cellular modem can reach the MQTT broker over LTE, instead of WiFi or as a fallback for it. The modem is a plain data pipe: the firmware brings it online with AT commands, then runs PPP over the same UART and hands the link to `embassy-net`. Everything above the network stack (the MQTT driver, DNS, TLS) works the same over LTE as over WiFi. Related docs: [Architecture](architecture.md) · [Hardware setup](hardware-setup.md) @@ -26,7 +26,7 @@ ring_pin = 3 # optional, reserved for wake-up (not used yet) # config.toml: the SIM [network.wifi] -enabled = false # one uplink per build +enabled = false # or true to join WiFi too (see "WiFi and LTE together") [network.lte] enabled = true @@ -38,14 +38,24 @@ apn = "your.carrier.apn" xtask checks the combination before building: -* A build has one uplink: WiFi and LTE can't both be enabled. +* WiFi and LTE can both be enabled (see "WiFi and LTE together"). * `[network.lte]` needs a `[hardware.esp.modem]`; unknown keys in that section are errors, so a typo in a pin name doesn't go unnoticed. * The APN must be printable ASCII without `"` (it is quoted in an AT command), and the SIM PIN 4 to 8 digits. -* The SavvyCAN logger needs WiFi: on a carrier network nothing can connect to the device. +* The SavvyCAN logger needs WiFi: on a carrier network nothing can connect to the device. With both enabled it runs on WiFi. * The PC board refuses `[network.lte]`: on Linux the OS brings the modem up (ModemManager, NetworkManager) and the firmware uses it like any other network. The modem's UART is `UART1`. `board-esp` keeps the control lines (`ControlPin`) with their active level, because boards often put a transistor on PWRKEY or RESET, which inverts them. +## WiFi and LTE together + +With `[network.wifi]` and `[network.lte]` both enabled, the board joins both: WiFi at home, LTE on the road. + +* The MQTT relay prefers WiFi. It connects over WiFi when WiFi is up, over LTE otherwise, and moves to LTE as soon as WiFi drops. On LTE it moves back to WiFi once WiFi has stayed up for 20 seconds, so a car at the edge of the WiFi's range doesn't bounce between the two. Each move is a new broker connection: the app's sessions end and it handshakes again (see [MQTT relay](mqtt-relay.md)). +* LAN direct and the SavvyCAN logger run on WiFi only, as in a WiFi build. +* The modem stays online while the relay uses WiFi, so the fallback is immediate. That costs the SIM's idle data (a few PPP and DNS packets) and the modem's power. + +`mqtt_driver_task` takes the WiFi stack and the LTE stack as its fallback (`boards/esp/src/network.rs`). + ## Supported boards and modems | Modem | `kind` | Boards | @@ -75,7 +85,7 @@ The `wireless` status LED is lit while the PPP link is up (`FLAG_LTE`). ## Limits -* **Security over a public network:** the broker is on the internet once the device uses LTE, so use `mqtts://` with `auth_mode = "mtls"` (see [MQTT over TLS](mqtt-tls.md)); with `mqtt://` the state and credentials travel unencrypted. Inbound MQTT commands stay refused until they are authenticated (see [Architecture](architecture.md#channels)). +* **Security over a public network:** the broker is on the internet once the device uses LTE. The relay's frames are end-to-end encrypted, so the broker and the carrier only see ciphertext; `mqtts://` also hides the broker password and who talks to the device (see [MQTT relay](mqtt-relay.md)). * **IPv4 only:** the PDP context is `"IP"`. * **Data rate:** PPP at 115200 baud gives about 11 KB/s, plenty for MQTT. @@ -88,7 +98,7 @@ Most LTE modems have their own MQTT client, driven by AT commands (SIMCom `AT+CM * **TLS stays on the ESP.** WiFi builds need TLS on the ESP anyway, so the modem's TLS would only save RAM on LTE builds. It would also keep the client's private key on the modem, readable by whoever can reach its UART, and tie the TLS versions and cipher suites to the modem's firmware. * **No modem MQTT limits:** these clients speak MQTT 3.1.1 (the firmware uses v5), cap the payload size, and return binary payloads inside AT notifications. -What the modem's client would give: the ESP could deep-sleep while the modem keeps the session alive, and the AT channel would stay free while connected. If the sleep experiments below show that remote wake-up only works reliably that way, the client can be added as another MQTT driver for that modem: it would read and write the same `MQTT_RX_CHANNEL` / `MQTT_TX_CHANNEL`, and the power-on, SIM and registration steps would stay as they are. +What the modem's client would give: the ESP could deep-sleep while the modem keeps the session alive, and the AT channel would stay free while connected. If the sleep experiments below show that remote wake-up only works reliably that way, the client can be added as another MQTT driver for that modem: the relay's frames are opaque bytes, so it would hand them to the same `relay_receive_frame` / `relay_try_next_frame`, and the power-on, SIM and registration steps would stay as they are. ## Sleep and remote wake-up (not implemented) diff --git a/docs/mqtt-relay.md b/docs/mqtt-relay.md new file mode 100644 index 0000000..a72572a --- /dev/null +++ b/docs/mqtt-relay.md @@ -0,0 +1,140 @@ +# MQTT relay + +The MQTT relay lets the app reach the device from anywhere (LTE, another network) through any MQTT broker you run: a Mosquitto container, Home Assistant's Mosquitto add-on, a hosted broker. The broker only carries frames of the end-to-end encrypted [secure channel](architecture.md#secure-channel) between the app and the device, so it is **not trusted**: it can't read the state or send a command. The protocol (topics, client IDs, what the relay carries and how often) is in the contracts' [`docs/mqtt-relay.md`](https://github.com/OpenCarControls/contracts/blob/main/docs/mqtt-relay.md). + +Nothing but secure channel frames is accepted from MQTT, and nothing else is published there: there is no plaintext MQTT any more. Older app builds lose remote access (Bluetooth still works). + +Related docs: [Architecture](architecture.md) · [LAN direct](lan.md) · [LTE](lte.md) + +## How the device uses the broker + +The broker connection is the board's `mqtt_driver_task` (PC and ESP); everything else is in `core-interface`'s `relay.rs`. + +* **Identity.** The device connects with its device key ID as the MQTT client ID (`relay_client_id`) and subscribes to `opencar/{device_key_id}/d/+` (`relay_subscribe_filter`). Both come from the device identity made at first boot, so there is nothing to configure per device, and the app learns the key ID over BLE. Without an identity the driver waits. +* **Inbound.** Each message on a device topic goes to `relay_receive_frame` with its topic. The topic's last level is the client's key ID; the secure channel drops a handshake whose key doesn't have it, and the reply goes to that client's topic, `opencar/{device_key_id}/c/{client_key_id}`. Messages on any other topic are ignored. The frame is dispatched like one from the LAN: a validated phone's basic commands reach the vehicle, advanced ones are refused with `REJECTED_UNAVAILABLE`, system commands are dropped. +* **Outbound.** The driver publishes whatever `relay_try_next_frame` gives it, before each poll: command responses (`SECURE_TX_CHANNEL`), then a system state when due (the session's command availability and the LAN address: when the session starts, when either changes, and every 30 s), then the basic vehicle state, throttled per session: at most once a second while the session had an inbound frame (the app's 15 s heartbeat) within 35 s, otherwise every 30 s. Only each client's newest session gets state. With no session nothing is published. Frames go out at QoS 1, never retained; a frame the client can't take yet (four publications already waiting for their PUBACK) waits for the next round. +* **Broker sessions.** `relay_connect` starts a broker session once subscribed; `relay_disconnect` ends it, and every channel session it carried with it. A client's next frame then gets an unknown session frame on its topic and it handshakes again. +* **Uplink.** On an ESP build with WiFi and LTE, the driver connects over WiFi when it is up and over LTE otherwise, and reconnects on WiFi once it has been back for 20 s (see [LTE](lte.md#wifi-and-lte-together)). Each move is a new broker session. + +## Configuration + +`[network.mqtt]` in `config.toml`: + +```toml +[network.mqtt] +broker_url = "mqtt://192.168.0.100:1883" # or mqtts://broker.example.com (port 8883 unless given) +auth_mode = "basic" # none, basic or mtls +username = "my-car" # auth_mode = "basic" +password = "secret" + +# TLS (mqtts://) +ca_cert_file = "certs/ca.pem" # the CA the broker's certificate chains to +client_cert_file = "certs/my-car.pem" # auth_mode = "mtls": this device's certificate +client_key_file = "certs/my-car.key" # its private key, unencrypted +``` + +TLS and broker authentication are optional hardening, not the security model: they keep strangers off your broker and hide from the network which phones talk to the device. Every combination works: + +| `broker_url` | `auth_mode` | What the device does | +|---|---|---| +| `mqtt://` | `none` | Plain TCP, no credentials. | +| `mqtt://` | `basic` | Plain TCP with the username and password, which the network can see. xtask notes it. | +| `mqtts://` | `none` / `basic` | TLS, verifies the broker, then sends the username and password (if any) inside TLS. | +| `mqtts://` | `mtls` | TLS, verifies the broker, presents its certificate. `username` and `password` are ignored and not compiled in. | + +xtask refuses `mtls` with a `mqtt://` URL, an unknown `auth_mode`, and a `mqtts://` URL without `ca_cert_file`, and checks that every file it needs exists. Paths are relative to the firmware directory (`certs/` is gitignored) or absolute. All files are PEM; the CA file and the certificate file may hold a chain. `client_id` is no longer used (xtask warns if it is still set). + +Use the broker's DNS name in `broker_url`, the name its certificate is issued for. The device resolves it over DNS, on WiFi and on LTE. + +## Where the certificates live + +For now xtask compiles the three PEM files into the image (`MQTT_TLS` in the generated `main.rs`, a `core_interface::MqttTls`). Anyone who can read the device's flash can read the key, so give each device its own certificate, and revoke it at the broker (by removing its ACL entry) if a device is lost. + +The setup wizard will later write them to the device over BLE instead of compiling them in. The MQTT drivers only take a `MqttTls`, so that change stays outside them. The wizard will need: + +* A flash region for the credentials, next to the bond and phone stores (see [BLE](ble.md)), read at boot into a `MqttTls` before `mqtt_driver_task` is spawned. +* Ideally a key generated on the device, never leaving it: the wizard asks for a CSR, has it signed, and sends back the certificate and the CA. That needs MbedTLS's key generation and CSR writing (both are in the prebuilt libraries). +* A system command to set or replace them, BLE-only and limited to a validated phone in the pairing window, like the other system commands. + +## Making certificates + +Use your own CA, not a public one: the broker should trust only certificates you issued. ECDSA P-256 keys are much faster than RSA on the ESP. With OpenSSL: + +```bash +mkdir -p certs && cd certs + +# The CA. Keep ca.key offline: whoever has it can mint certificates for your broker. +openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \ + -keyout ca.key -out ca.pem -days 3650 -subj "/CN=Open Car Controls CA" \ + -addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign" + +# The broker: its DNS name in the subjectAltName. +openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \ + -keyout broker.key -out broker.csr -subj "/CN=broker.example.com" +openssl x509 -req -in broker.csr -CA ca.pem -CAkey ca.key -CAcreateserial -days 825 \ + -extfile <(printf "subjectAltName=DNS:broker.example.com\nextendedKeyUsage=serverAuth") \ + -out broker.pem + +# One per device: the CN is the broker username, e.g. the device key ID. +openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \ + -keyout my-car.key -out my-car.csr -subj "/CN=my-car" +openssl x509 -req -in my-car.csr -CA ca.pem -CAkey ca.key -CAcreateserial -days 825 \ + -extfile <(printf "extendedKeyUsage=clientAuth") -out my-car.pem +``` + +Make one for each phone the same way (CN `phone-`, see the app's docs). + +## Broker setup + +Any MQTT 5 broker works. The simplest is a Mosquitto container on your network with a password file, or Home Assistant's Mosquitto add-on with a user for the device and one per phone. + +A broker that others can reach should keep each client to its own topics. A Mosquitto ACL (`acl_file`), with one user per device (its device key ID, which the app shows) and per phone: + +```conf +# The device +user 1e1c177be4a37ca2c0ea +topic read opencar/1e1c177be4a37ca2c0ea/d/+ +topic write opencar/1e1c177be4a37ca2c0ea/c/+ +topic write opencar/1e1c177be4a37ca2c0ea/state + +# A phone (its client key ID is in the app's relay settings) +user phone-michael +topic write opencar/1e1c177be4a37ca2c0ea/d/6c9a288323521dc27247 +topic read opencar/1e1c177be4a37ca2c0ea/c/6c9a288323521dc27247 +topic read opencar/1e1c177be4a37ca2c0ea/state +``` + +With mTLS, have Mosquitto take the username from the certificate (`mosquitto.conf`): + +```conf +listener 8883 +cafile /etc/mosquitto/certs/ca.pem +certfile /etc/mosquitto/certs/broker.pem +keyfile /etc/mosquitto/certs/broker.key +tls_version tlsv1.2 +require_certificate true +use_identity_as_username true +allow_anonymous false +acl_file /etc/mosquitto/acl +``` + +To watch the relay from a computer (you only see ciphertext): + +```bash +mosquitto_sub -h 192.168.0.100 -u phone-michael -P secret -t 'opencar/+/c/#' -v +``` + +## On the device + +* **ESP:** MbedTLS through `mbedtls-rs` 0.2, the last release on esp-hal 1.1, from its prebuilt libraries with software crypto. It is behind `board-esp`'s `mqtt-tls` feature, which xtask turns on only for a `mqtts://` URL: it adds about 540 KB of flash, and the handshake's heap, so a `mqtt://` build is that much smaller. The handshake allocates its buffers from the heap (two 16 KB records plus the handshake state); the device logs the free heap once the handshake succeeds (`MQTT: TLS established, … B heap free`). TLS 1.2 and 1.3 are offered. +* **PC:** rustls with ring, always built in. +* Both log a failed handshake with its reason (on the ESP, MbedTLS's verify flags) and retry like any other failed connection. Bad TLS settings (a PEM that doesn't parse) stop the MQTT driver at boot instead of falling back to plain TCP. +* The secure channel's own cost (Noise, ChaCha20-Poly1305, BLAKE2s, protobuf) is shared with the LAN; the relay adds only its driver. +* The TCP and TLS stacks get their randomness from the hardware RNG, which is a true random source while the radio runs (BLE always does). + +## Limits + +* **Certificate dates aren't checked on the ESP.** It has no clock at boot, and the prebuilt MbedTLS is built without date checks, so an expired or not-yet-valid certificate is accepted (chain, signature and hostname are still checked). Revoke a certificate at the broker (its ACL entry), not by letting it expire. This only matters for who may use the broker: what reaches the car is decided by the secure channel. Checking dates needs the time from the network (LTE `AT+CCLK?` or SNTP) and MbedTLS built from source with its `hook-wall-clock` feature. The PC checks dates. +* **No hardware crypto on the ESP:** MbedTLS's hardware hooks need `mbedtls-rs` on esp-hal 1.2, held back until esp-radio supports it. A handshake takes noticeably longer than on a PC; it happens once per connection. +* **No session resumption:** each reconnect does a full handshake. +* **Flash size:** the prebuilt libraries carry features the device doesn't use (DTLS, a TLS server, X.509 writing). A from-source build with only the client parts would be much smaller, but needs a C cross-compiler in the build. diff --git a/docs/mqtt-tls.md b/docs/mqtt-tls.md deleted file mode 100644 index 820a610..0000000 --- a/docs/mqtt-tls.md +++ /dev/null @@ -1,120 +0,0 @@ -# MQTT over TLS (mTLS) - -Once the device uses LTE, the broker is on the public internet. With a `mqtts://` broker URL the device talks to it over TLS: it checks that the broker's certificate chains to your CA and names the broker's host, so nobody between the car and the broker can read the vehicle state or pose as the broker. With `auth_mode = "mtls"` the device also presents its own certificate, and the broker lets it in on that alone (no password in the image). The app does the same with a certificate of its own (see the app's `docs/mqtt-tls.md`). - -TLS protects the link to the broker, not the commands themselves: anyone the broker lets publish to a car's command topic could still send one. MQTT commands therefore stay refused (`MQTT_COMMANDS_AUTHENTICATED` in `dispatch.rs`) until they are signed per phone (contracts#8, firmware#16). - -## Configuration - -`[network.mqtt]` in `config.toml`: - -```toml -[network.mqtt] -broker_url = "mqtts://broker.example.com" # port 8883 unless given -client_id = "my-car" # also the topics' {client_id} -auth_mode = "mtls" - -ca_cert_file = "certs/ca.pem" # the CA the broker's certificate chains to -client_cert_file = "certs/my-car.pem" # this device's certificate -client_key_file = "certs/my-car.key" # its private key, unencrypted -``` - -| `broker_url` | `auth_mode` | What the device does | -|---|---|---| -| `mqtt://` | `basic` | Plain TCP with the username and password. xtask warns: use it only on a network you trust. | -| `mqtts://` | `basic` | TLS, verifies the broker, then sends the username and password inside TLS. | -| `mqtts://` | `mtls` | TLS, verifies the broker, presents its certificate. `username` and `password` are ignored and not compiled in. | - -xtask refuses `mtls` with a `mqtt://` URL, an unknown `auth_mode`, and a `mqtts://` URL without `ca_cert_file`, and checks that every file it needs exists. Paths are relative to the firmware directory (`certs/` is gitignored) or absolute. All files are PEM; the CA file and the certificate file may hold a chain. - -Use the broker's DNS name in `broker_url`, the name its certificate is issued for. The device resolves it over DNS, on WiFi and on LTE. - -## Where the certificates live - -For now xtask compiles the three PEM files into the image (`MQTT_TLS` in the generated `main.rs`, a `core_interface::MqttTls`). Anyone who can read the device's flash can read the key, so give each device its own certificate, and revoke it at the broker (by removing its ACL entry) if a device is lost. - -The setup wizard will later write them to the device over BLE instead of compiling them in. The MQTT drivers only take a `MqttTls`, so that change stays outside them. The wizard will need: - -* A flash region for the credentials, next to the bond and phone stores (see [BLE](ble.md)), read at boot into a `MqttTls` before `mqtt_driver_task` is spawned. -* Ideally a key generated on the device, never leaving it: the wizard asks for a CSR, has it signed, and sends back the certificate and the CA. That needs MbedTLS's key generation and CSR writing (both are in the prebuilt libraries). -* A system command to set or replace them, BLE-only and limited to a validated phone in the pairing window, like the other system commands. - -## Making certificates - -Use your own CA, not a public one: the broker should trust only certificates you issued. ECDSA P-256 keys are much faster than RSA on the ESP. With OpenSSL: - -```bash -mkdir -p certs && cd certs - -# The CA. Keep ca.key offline: whoever has it can mint certificates for your broker. -openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \ - -keyout ca.key -out ca.pem -days 3650 -subj "/CN=Open Car Controls CA" \ - -addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign" - -# The broker: its DNS name in the subjectAltName. -openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \ - -keyout broker.key -out broker.csr -subj "/CN=broker.example.com" -openssl x509 -req -in broker.csr -CA ca.pem -CAkey ca.key -CAcreateserial -days 825 \ - -extfile <(printf "subjectAltName=DNS:broker.example.com\nextendedKeyUsage=serverAuth") \ - -out broker.pem - -# One per device: the CN is the device's client_id, which the broker uses as its username. -openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes \ - -keyout my-car.key -out my-car.csr -subj "/CN=my-car" -openssl x509 -req -in my-car.csr -CA ca.pem -CAkey ca.key -CAcreateserial -days 825 \ - -extfile <(printf "extendedKeyUsage=clientAuth") -out my-car.pem -``` - -Make one for each phone the same way (CN `phone-`, see the app's docs). - -## Broker setup - -The broker must require a client certificate signed by your CA and map each certificate to a user. With Mosquitto 2.x (`mosquitto.conf`): - -```conf -listener 8883 -cafile /etc/mosquitto/certs/ca.pem -certfile /etc/mosquitto/certs/broker.pem -keyfile /etc/mosquitto/certs/broker.key -tls_version tlsv1.2 -require_certificate true -use_identity_as_username true -allow_anonymous false -acl_file /etc/mosquitto/acl -``` - -`use_identity_as_username` makes the certificate's CN the username, so the ACL (`/etc/mosquitto/acl`) can keep each device to its own topics and give each phone only the cars it drives: - -```conf -# Every device: only its own command and data topics (CN = client_id). -pattern read opencar/%u/cmd -pattern write opencar/%u/data - -# Each phone: the cars it may reach. -user phone-michael -topic write opencar/my-car/cmd -topic read opencar/my-car/data -``` - -Close port 1883, or keep it on localhost only. Other brokers (EMQX, HiveMQ, a cloud IoT broker) have the same settings under other names: verify client certificates against the CA, take the username from the certificate's CN, and an ACL per user. - -To check the broker from a computer: - -```bash -mosquitto_sub -h broker.example.com -p 8883 --cafile certs/ca.pem \ - --cert certs/phone-michael.pem --key certs/phone-michael.key -t 'opencar/my-car/data' -v -``` - -## On the device - -* **ESP:** MbedTLS through `mbedtls-rs` 0.2, the last release on esp-hal 1.1, from its prebuilt libraries with software crypto. It is behind `board-esp`'s `mqtt-tls` feature, which xtask turns on only for a `mqtts://` URL: it adds about 540 KB of flash. The handshake allocates its buffers from the heap (two 16 KB records plus the handshake state); the device logs the free heap once the handshake succeeds (`MQTT: TLS established, … B heap free`). TLS 1.2 and 1.3 are offered. -* **PC:** rustls with ring, always built in. -* Both log a failed handshake with its reason (on the ESP, MbedTLS's verify flags) and retry like any other failed connection. Bad TLS settings (a PEM that doesn't parse) stop the MQTT driver at boot instead of falling back to plain TCP. -* The TCP and TLS stacks get their randomness from the hardware RNG, which is a true random source while the radio runs (BLE always does). - -## Limits - -* **Certificate dates aren't checked on the ESP.** It has no clock at boot, and the prebuilt MbedTLS is built without date checks, so an expired or not-yet-valid certificate is accepted (chain, signature and hostname are still checked). Revoke a certificate at the broker (its ACL entry), not by letting it expire. Checking dates needs the time from the network (LTE `AT+CCLK?` or SNTP) and MbedTLS built from source with its `hook-wall-clock` feature. The PC checks dates. -* **No hardware crypto on the ESP:** MbedTLS's hardware hooks need `mbedtls-rs` on esp-hal 1.2, held back until esp-radio supports it. A handshake takes noticeably longer than on a PC; it happens once per connection. -* **No session resumption:** each reconnect does a full handshake. -* **Flash size:** the prebuilt libraries carry features the device doesn't use (DTLS, a TLS server, X.509 writing). A from-source build with only the client parts would be much smaller, but needs a C cross-compiler in the build. diff --git a/docs/testing.md b/docs/testing.md index a26aba1..1d0d667 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -7,7 +7,7 @@ The README has the quick-start commands; this page covers how the suites are org | Crate | Covers | Command | |---|---|---| -| `core-interface` | `passes_filter`, BLE/MQTT dispatch (platform_id gating, routing, `source_device_id` stamping, empty-source rejection), response routing, state publish split, CAN read-only flag and its change notifications, the CAN read-write policy (each condition blocking read-write, approval bound to one car, surviving a reboot and phone changes, relock conditions, bonded-phone-only BLE commands, MQTT never approving or unlocking, release builds without the dev lock, vehicle commands refused with the reason while read-only, the access state repeated while unchanged), the command requirements check (gate order, freshness, requirements, rejection responses that never block), the repeat limit (per command, from the last admitted run, after the requirements, not affecting availability), command availability (nothing before a report, read-only and old reports held back, publish on change, repeat and resend, MQTT basic commands only at the MQTT rate), per-bus CAN TX channels, SavvyCAN logging (GVRET parsing and encoding, session lifecycle, forced read-only), phone trust (vehicle commands and command frames needing a validated phone, validation sessions with code entry, in-car actions, attempts, cooldown and timeouts, validations bound to one car, who can change the approval or remove a validated phone, persistence and pruning to the bonds, the connected phone's access state), the secure channel's keys (the device identity made once and kept, its key ID against the contracts' test vectors, client key enrollment from a validated phone over BLE only, replaced on re-enrollment, dropped with the bond but kept when the validation ends, the store encoding), the secure channel (the Noise handshake and transport frames against the contracts' test vectors, unknown keys and replayed handshakes unanswered, the replay window, keepalives, session expiry, limits and replacement, key removal and link close ending sessions, messages stamped with the client's ID and authorized like BLE, system commands dropped, refusals sealed back to the session, de-duplication across BLE and the channel), the deprecated CAN debug commands being ignored, BLE chunking and reassembly (chunk headers, CRC, MTU limits, gaps, duplicates, sequence mismatches, timeouts, oversize messages) | `cargo test -p core-interface -- --test-threads=1` | +| `core-interface` | `passes_filter`, BLE and secure channel dispatch (platform_id gating, routing, `source_device_id` stamping, empty-source rejection), response routing, state publish split, CAN read-only flag and its change notifications, the CAN read-write policy (each condition blocking read-write, approval bound to one car, surviving a reboot and phone changes, relock conditions, bonded-phone-only BLE commands, release builds without the dev lock, vehicle commands refused with the reason while read-only, the access state repeated while unchanged), the command requirements check (gate order, freshness, requirements, rejection responses that never block), the repeat limit (per command, from the last admitted run, after the requirements, not affecting availability), command availability (nothing before a report, read-only and old reports held back, publish on change, repeat and resend), per-bus CAN TX channels, SavvyCAN logging (GVRET parsing and encoding, session lifecycle, forced read-only), phone trust (vehicle commands and command frames needing a validated phone, validation sessions with code entry, in-car actions, attempts, cooldown and timeouts, validations bound to one car, who can change the approval or remove a validated phone, persistence and pruning to the bonds, the connected phone's access state), the secure channel's keys (the device identity made once and kept, its key ID against the contracts' test vectors, client key enrollment from a validated phone over BLE only, replaced on re-enrollment, dropped with the bond but kept when the validation ends, the store encoding), the secure channel (the Noise handshake and transport frames against the contracts' test vectors, unknown keys and replayed handshakes unanswered, the replay window, keepalives, session expiry, limits and replacement, key removal and link close ending sessions, messages stamped with the client's ID and authorized like BLE, system commands dropped, refusals sealed back to the session, de-duplication across BLE and the channel), the MQTT relay (per-client topics, the handshake's topic check, what a session is sent and its throttle, basic commands only, no plaintext, a broker reconnect ending the sessions), the deprecated CAN debug commands being ignored, BLE chunking and reassembly (chunk headers, CRC, MTU limits, gaps, duplicates, sequence mismatches, timeouts, oversize messages) | `cargo test -p core-interface -- --test-threads=1` | | `virtual-car-controller` | `encode_state` proto encoding, worst-case state update fits the BLE message limit, CAN frame → state updates, `process_basic_command`, `tick_simulation` (initial defaults, ramp-up, park phase, odometer increment, door-lock preservation, cycle wraparound), the door lock refused while the simulated car drives and when pressed again inside its interval and sending a command frame for its phone, the simulated validation methods (button, cluster code), command availability and ids pinned to the wire | `cargo test -p virtual-car-controller -- --test-threads=1` | | `egmp-controller` | New state publishes no invented values, worst-case state update fits the BLE message limit, decoding of real CAN frames (charge port, windows, hazards), charge port state through AC and DC sessions, battery power, range, charging times, charge limits, climate state, temperatures in both units, preconditioning states, battery temperatures and 12 V voltage, distance unit, regen mode and level, tire pressures, command requirements and availability from fixture states, command ids pinned to the wire | `cargo test -p egmp-controller -- --test-threads=1` | | `board-pc` | `socketcan_to_core_frame` / `core_to_socketcan_frame` round-trips, the CAN read-write approval and phone validations file formats, BLE helpers | `cargo test -p board-pc -- --test-threads=1` | diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 25dbe98..5622058 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -218,7 +218,10 @@ fn wifi_enabled_default() -> bool { #[derive(Deserialize)] pub struct MqttConfig { pub broker_url: String, - pub client_id: String, + /// No longer used: the device's MQTT client ID is its device key ID + /// (docs/mqtt-relay.md in the contracts). Only read to warn about it. + pub client_id: Option, + #[serde(default = "auth_mode_default")] pub auth_mode: String, // Used for mTLS pub ca_cert_file: Option, @@ -229,16 +232,13 @@ pub struct MqttConfig { pub password: Option, } -#[derive(Deserialize)] -pub struct TransportConfig { - pub mqtt: TransportMqtt, - pub ble: TransportBle, +fn auth_mode_default() -> String { + "basic".to_string() } #[derive(Deserialize)] -pub struct TransportMqtt { - pub command_topic_template: String, - pub data_topic_template: String, +pub struct TransportConfig { + pub ble: TransportBle, } #[derive(Deserialize)] @@ -421,10 +421,12 @@ pub fn generate_fd_bus_declarations(buses: &[VehicleCanBus], bus_count: usize) - .collect() } -/// How the device secures its MQTT connection, from `[network.mqtt]`. +/// How the device secures its connection to the broker, from `[network.mqtt]`. The relay's +/// frames are end-to-end encrypted either way: this only protects the broker password and +/// hides who talks to the device from the network (docs/mqtt-relay.md in the contracts). #[derive(Debug, PartialEq)] pub enum MqttSecurity { - /// `mqtt://`: plain TCP. State and credentials travel unencrypted. + /// `mqtt://`: plain TCP. The broker password and the topics travel unencrypted. Plain, /// `mqtts://`: TLS, the broker verified against `ca`. With `client` (`auth_mode = /// "mtls"`) the device also presents its certificate and key. @@ -442,11 +444,11 @@ pub fn mqtt_security( ) -> Result { let tls = mqtt.broker_url.starts_with("mqtts://"); let mtls = match mqtt.auth_mode.as_str() { - "basic" => false, + "none" | "basic" => false, "mtls" => true, other => { return Err(format!( - "[network.mqtt].auth_mode must be \"basic\" or \"mtls\", got \"{other}\"" + "[network.mqtt].auth_mode must be \"none\", \"basic\" or \"mtls\", got \"{other}\"" )); } }; @@ -480,8 +482,8 @@ pub fn mqtt_security( } /// The generated `MQTT_TLS` constant (`Option`), and the -/// username and password to send. mTLS sends none: the broker takes the device's -/// identity from its certificate. +/// username and password to send. `none` and mTLS send none: with mTLS the broker takes +/// the device's identity from its certificate. pub fn mqtt_security_code(mqtt: &MqttConfig, security: &MqttSecurity) -> (String, String, String) { // Paths are relative to the generated `.app_build/src/main.rs`, hence `../../`. let include = |path: &str| { @@ -492,8 +494,9 @@ pub fn mqtt_security_code(mqtt: &MqttConfig, security: &MqttSecurity) -> (String }; format!("include_bytes!(\"{}\")", escape_rust_string(&path)) }; - let user = || escape_rust_string(mqtt.username.as_deref().unwrap_or("")); - let pass = || escape_rust_string(mqtt.password.as_deref().unwrap_or("")); + let basic = mqtt.auth_mode == "basic"; + let user = || escape_rust_string(mqtt.username.as_deref().filter(|_| basic).unwrap_or("")); + let pass = || escape_rust_string(mqtt.password.as_deref().filter(|_| basic).unwrap_or("")); match security { MqttSecurity::Plain => ( "#[allow(dead_code)]\nconst MQTT_TLS: Option = None;" @@ -538,10 +541,17 @@ pub fn checked_mqtt_security(config: &Config) -> MqttSecurity { eprintln!("\u{274c} {e}"); exit(1); }); + if mqtt.client_id.is_some() { + eprintln!( + "\u{26a0}\u{fe0f} [network.mqtt].client_id is no longer used: the device connects with its \ + device key ID. Remove it from config.toml." + ); + } if security == MqttSecurity::Plain { eprintln!( - "\u{26a0}\u{fe0f} MQTT uses plain TCP ({}): vehicle state and the broker password \ - travel unencrypted. Use mqtts:// for a broker outside your own network (docs/mqtt-tls.md).", + "\u{2139}\u{fe0f} MQTT uses plain TCP ({}): the car's state and commands stay end-to-end \ + encrypted, but the broker password and who talks to the device are visible on the \ + network. Use mqtts:// for a broker outside your own network (docs/mqtt-relay.md).", mqtt.broker_url ); } @@ -585,17 +595,6 @@ pub fn load_transport_contract() -> TransportConfig { toml::from_str(&content).expect("Failed to parse transport.toml") } -pub fn render_topic_from_template(template: &str, client_id: &str, field_name: &str) -> String { - if !template.contains("{client_id}") { - eprintln!( - "transport.toml {} must include '{{client_id}}': {}", - field_name, template - ); - exit(1); - } - template.replace("{client_id}", client_id) -} - pub fn escape_rust_string(value: &str) -> String { value.replace('\\', "\\\\").replace('"', "\\\"") } @@ -1210,7 +1209,7 @@ mod mqtt_security_tests { fn mqtt(url: &str, auth: &str) -> MqttConfig { MqttConfig { broker_url: url.into(), - client_id: "car".into(), + client_id: None, auth_mode: auth.into(), ca_cert_file: Some("certs/ca.pem".into()), client_cert_file: Some("certs/client_cert.pem".into()), @@ -1289,6 +1288,16 @@ mod mqtt_security_tests { assert_eq!((user.as_str(), pass.as_str()), ("", "")); } + #[test] + fn no_auth_sends_no_password_with_or_without_tls() { + for url in ["mqtt://broker", "mqtts://broker"] { + let config = mqtt(url, "none"); + let security = mqtt_security(&config, all_exist).unwrap(); + let (_, user, pass) = mqtt_security_code(&config, &security); + assert_eq!((user.as_str(), pass.as_str()), ("", "")); + } + } + #[test] fn plain_and_basic_keep_the_password() { let config = mqtt("mqtt://broker", "basic");