Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions build.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ targets:
builders:
open_car_builders|constants_builder:
enabled: true
open_car_builders|secure_channel_constants_builder:
enabled: true
open_car_builders|mqtt_config_builder:
enabled: true
open_car_builders|proto_builder:
Expand Down
12 changes: 12 additions & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ If a paired device later reports a different non-zero `platform_id`, `vehicleSta
| `canBusHealthProvider` | Each CAN bus's health by bus id (`SystemState.can_bus_health`): the device's status for the last few seconds and its counters since boot. From the current connection only, like `canAccessStateProvider`; BLE only. `AppEntryRouter` listens to it from the start, so the report sent when the app subscribes is kept for the settings |
| `canAccessActionsProvider` | Approves or withdraws vehicle control and toggles the developer write lock |
| `phoneAccessStateProvider` | What the device allows this phone (`SystemState.phone_access`): its trust level, whether the car has a validated phone, its validation session. From the current connection only, like `canAccessStateProvider` |
| `clientKeyEnrollmentProvider` | Enrolls this phone's client key with the device and pins the device identity, over Bluetooth once the phone is validated. `AppEntryRouter` listens to it from the start. See [Secure channel keys](#secure-channel-keys) |
| `deviceIdentityMismatchProvider` | The identity the device reported when it differs from the pinned one, for the dashboard banner; in memory only |
| `phoneValidationActionsProvider` | Lists the validation methods and the paired phones, and starts, answers or cancels a validation |
| `commandAvailabilityProvider` | Which commands the device accepts now (`SystemState.command_availability`), from the current connection only: null until reported on it, cleared on every transport or connection change and when the device goes quiet, never cached. Over MQTT it covers the basic commands |
| `vehicleHistoryProvider` | Recent values of the series the paired vehicle's tiles draw (charts, sparklines), sampled from live state only, in memory |
Expand Down Expand Up @@ -100,6 +102,16 @@ Pairing doesn't prove a phone is the owner's, so the device only accepts vehicle
* The limits (`[ble.phone_validation]` in `transport.toml`) are generated with the other constants as `kBlePhoneValidation*`, for the instructions. The session messages carry the time and attempts left.
* `phoneValidationMethodText` maps each `method_id` to the app's text, with a generic text per kind for an id the app doesn't know.

### Secure channel keys
The secure channel (contracts `docs/secure-channel.md`) lets the app reach the device off Bluetooth, over a link it doesn't trust (LAN, relay). It rests on two keys, both exchanged over the bonded Bluetooth link:

* **The app's client key:** one X25519 key pair per install, made on first use by `ClientKeyStore` (`lib/secure/client_key.dart`) and kept in `flutter_secure_storage` (Android Keystore), never in `SharedPreferences`. Tests use an in-memory `SecretStore`.
* **The device identity:** the device's X25519 public key and key ID (`SystemState.device_identity`, and the answer to `EnrollClientKey`). `PinnedDeviceIdentity.fromReport` (`lib/secure/device_identity.dart`) only accepts a 32-byte key whose key ID matches it. The app pins it per vehicle in `PairedVehicleConfig` (`devicePublicKey`, `deviceKeyId`), with the client key the device last accepted (`enrolledClientKey`), so unpairing forgets all three.

`clientKeyEnrollmentProvider` does the enrollment, over Bluetooth (and the debug HTTP transport) only. On each connection, once `phoneAccessStateProvider` reports the phone validated, it lists the paired phones and sends `EnrollClientKey` (kind phone, labelled with the phone's model, cut to `max_client_label_bytes`) when the device doesn't list this phone with a key, no identity is pinned, or the device last accepted another client key. A failure leaves it for the next connection. The device answers with its identity, which the app pins if it has none.

A reported identity that differs from the pinned one (the device was erased or replaced, or isn't the same device) is never pinned silently: `deviceIdentityMismatchProvider` holds it, nothing is enrolled, and the dashboard shows "The device has a new identity" with Unpair or Trust new identity. Trusting it pins the new key, forgets the enrolled client key and enrolls again.

### Command availability
The device decides which commands it accepts right now and reports it (firmware `docs/commands.md`, "Command availability"): `SystemState.command_availability`, over BLE and over MQTT (basic commands only), repeated every few seconds. The app greys out the tiles of commands the device doesn't accept, and the dashboard leaves out the tiles of commands reported `UNSUPPORTED` (not on this car; nothing sends that yet), so the tiles after them close the gap. They stay left out in every later connection (see below). A tap on a greyed-out tile (`CommandControl`) says why when the app knows: the device reports no reason, so it comes from the transport and the access states (`commandUnavailableReason`). The device rejects an unavailable command with `COMMAND_STATUS_CODE_REJECTED_UNAVAILABLE` even if the app sends it anyway, and `sendVehicleCommand` shows its reason.

Expand Down
4 changes: 2 additions & 2 deletions docs/ble.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ The device advertises **only** while its pairing window is open: after its pairi
* **Device hidden from this phone:** once a buttonless device has a paired phone, it advertises without its name or service UUID, so a phone it doesn't know (app reinstalled, new phone, bond forgotten in Android's settings) never finds it. The firmware's recovery is a bond reset by power-cycling (firmware `docs/ble.md`): after `kBlePowerCycleResetShortBoots` power-ons in a row that each lose power within `kBlePowerCycleResetUptimeSeconds`, the next power-on clears every bond and opens the first-setup window. `HelpScreen` (`lib/screens/help_screen.dart`) explains pairing mode and these steps with the contract's values; it is reachable from the wizard's header and its error step (the scan timeout message points there), the dashboard's settings screen, and the bond-lost banner.
* Android can still report such a device to the wizard's scan, filtered on the service UUID, although it advertises neither the UUID nor its name: it matches from the services it cached while the phone was paired (seen on a Pixel). The scan then doesn't time out. The wizard therefore treats a device found **without a name** as outside pairing mode (in pairing mode the firmware puts its name in every advertisement): the found step says so and links to Help, and Pair stays available, since a phone that still has its bond pairs that way. If Pair then ends in the stale-bond drop, the warning tells the user to reset the paired phones instead of "tap Pair again": outside pairing mode the firmware doesn't clear the old bond, so another attempt would fail the same way.
* **HTTP debug path** (debug builds only): the wizard offers host/port entry + POST `/pairing` + POST `/pair`; saves config with `transportPreference = http`.
* **Unpair:** Unpair on a card of the Vehicles screen, or Unpair vehicle in settings for the current one → confirmation dialog → `pairedVehiclesProvider.notifier.unpair()` → the next vehicle becomes current, or with none left the router returns to the wizard. Unpairing only forgets the vehicle in the app; the device keeps its bond, so pairing again needs it in pairing mode.
* **Unpair:** Unpair on a card of the Vehicles screen, or Unpair vehicle in settings for the current one → confirmation dialog → `pairedVehiclesProvider.notifier.unpair()` → the next vehicle becomes current, or with none left the router returns to the wizard. Unpairing only forgets the vehicle in the app, with its pinned device identity (see [Secure channel keys](architecture.md#secure-channel-keys)); the device keeps its bond and this phone's client key, so pairing again needs it in pairing mode.
* **`createBond()` is never called** — bonding is driven by the write-probe, not explicit bond requests.
* **Stale-bond recovery:** if the firmware drops the link after connecting (it had a stale bond, the phone forgot it), `disconnectCompleter` fires and the wizard returns to the "found" step with a warning banner. Firmware clears its entry on that drop; the next Pair tap succeeds normally (the user sees two OS pairing prompts in total).
* **Phone validation:** bonding doesn't make a phone trusted. Pairing is Just Works, so a newly paired phone (and one that paired again after a bond reset, or a device moved to another car) can send system commands, but no vehicle command until it is validated in the car. See [Phone validation](architecture.md#phone-validation). Trust is only read from `SystemState.phone_access` on the current connection, never cached.
* **Phone validation:** bonding doesn't make a phone trusted. Pairing is Just Works, so a newly paired phone (and one that paired again after a bond reset, or a device moved to another car) can send system commands, but no vehicle command until it is validated in the car. See [Phone validation](architecture.md#phone-validation). Trust is only read from `SystemState.phone_access` on the current connection, never cached. Once validated, the app enrolls its client key for the secure channel ([Secure channel keys](architecture.md#secure-channel-keys)).

## BLE specifics
* **Library:** `flutter_reactive_ble: ^5.4.1`. Singleton in `lib/providers/ble_provider.dart` (`bleProvider`).
Expand Down
3 changes: 3 additions & 0 deletions docs/code-generation.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,13 @@ It does not need to run on every build, only when its inputs change. Unlike Rust
|---|---|---|
| `contracts/**/*.proto` | `lib/generated/**/*.pb.dart` | `ProtoBuilder` |
| `contracts/opencar/cars/*/v1/meta.toml` + `transport.toml` | `lib/cars/<vehicle>/constants.g.dart` | `ConstantsBuilder` |
| `contracts/opencar/core/v1/transport.toml` (`[secure_channel]`) | `lib/secure/secure_channel_constants.g.dart` | `SecureChannelConstantsBuilder` |
| `config.toml.example` (+ optional `config.toml`, and the `certs/` files it names) | `lib/config/mqtt_broker_config.g.dart` | `MqttConfigBuilder` |

**`constants.g.dart`** exposes: `kPlatformId` (CRC32), `kPlatformName`, `kCanBusCount`, BLE UUIDs, MQTT topic templates, `kBlePairingWindowSeconds`, `kBleScanTimeoutSeconds`, and the BLE size and chunking constants (`kBleAttMtu`, `kBleMaxChunkBytes`, `kBleMaxMessageBytes`, `kBleChunk*`, `kBleCrcBytes`, `kBleMaxChunks`, `kBleMinAttMtu`, `kBleReassemblyTimeoutMs`). Never copy-paste TOML values — always import from the generated file.

**`secure_channel_constants.g.dart`** exposes the [secure channel](architecture.md#secure-channel-keys) constants, which don't depend on the vehicle: `kSecureChannelProtocol`, `kSecureChannelPrologueLabel`, the frame types (`kSecureFrameType*`) and the sizes, limits and timeouts (`kSecureChannel*`).

**`mqtt_broker_config.g.dart`** exposes: `kMqttBrokerHost/Port`, `kMqttUsername/Password` (empty with mTLS), `kMqttCaCertPem`, `kMqttClientCertPem`, `kMqttClientKeyPem` (the PEM files of `[broker]`, empty when unused; see [MQTT over TLS](mqtt-tls.md)), `kMqttClientId`, `kDebugServerHost/Port`, `kDebugServerPollingIntervalMs`.

## Local config
Expand Down
1 change: 1 addition & 0 deletions docs/ui-screens.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ Opened from the settings button in the dashboard header. A back button and the t
### Paired phones
The phones paired with the device, in the order they were paired (BLE only). The device doesn't know phone names, so each phone shows as "This phone" or "Another phone" with the end of its id. Each has a trust chip: **Validated** or **Not validated**.

* A phone with a client key enrolled for the [secure channel](architecture.md#secure-channel-keys) shows "Remote access set up", with the label it enrolled with (the phone's model).
* This phone, when it isn't validated, has **Validate**.
* Other phones have **Remove**, with a confirmation. Once a phone is validated in this car, only a validated phone can remove a validated phone, so on a phone that isn't validated the button is disabled with that reason. The device only removes phones during its pairing window and doesn't answer an accepted request, so the app reads the list again and says so if the phone is still there.
* Removing this phone's own bond and clearing all phones are part of unpairing and [#25](https://github.com/OpenCarControls/mobile-app/issues/25).
Expand Down
1 change: 1 addition & 0 deletions docs/ui.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ The screenshot predates the single controls tile and the sheet.
| Banner | When | Action |
|---|---|---|
| Wrong vehicle platform | The device reports a different platform (`vehicleStateProvider` sets `mismatchedPlatformId`) | Unpair |
| The device has a new identity | The device reports a key other than the one pinned for this vehicle (`deviceIdentityMismatchProvider`, see [Secure channel keys](architecture.md#secure-channel-keys)) | Unpair, or trust the new identity |
| The device no longer knows this phone | Repeated early drops (`bleBondLostProvider`) | Help, or unpair and pair again |
| Control isn't approved | The car is identified but the CAN read-write approval is missing or for another car (`canAccessNeedsApproval`) | Review: the approval dialog |
| Validate this phone | This phone is bonded but not validated in this car ([phone validation](ui-screens.md#phone-validation)) | Validate: the validation flow |
Expand Down
38 changes: 37 additions & 1 deletion lib/config/paired_vehicle_config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,18 @@ class PairedVehicleConfig {
/// device over BLE; null until it has, and MQTT stays off until then.
final String? mqttClientId;

/// The device's secure channel public key (32 bytes), pinned from the first
/// identity it reported over Bluetooth. Null until then. A device reporting
/// another key later doesn't replace it: the user decides.
final List<int>? devicePublicKey;

/// The device key ID of [devicePublicKey].
final String? deviceKeyId;

/// The app's client public key that this device last accepted, so a new
/// client key (app data cleared) is enrolled again.
final List<int>? enrolledClientKey;

const PairedVehicleConfig({
String? id,
this.name,
Expand All @@ -71,15 +83,23 @@ class PairedVehicleConfig {
this.mqttUsername,
this.mqttPassword,
this.mqttClientId,
this.devicePublicKey,
this.deviceKeyId,
this.enrolledClientKey,
}) : id = id ?? vehicleId;

/// A copy with the given fields replaced. [clearName] goes back to the
/// platform's name.
/// platform's name. [clearEnrolledClientKey] forgets which client key the
/// device accepted.
PairedVehicleConfig copyWith({
String? id,
String? name,
bool clearName = false,
String? mqttClientId,
List<int>? devicePublicKey,
String? deviceKeyId,
List<int>? enrolledClientKey,
bool clearEnrolledClientKey = false,
}) => PairedVehicleConfig(
id: id ?? this.id,
name: clearName ? null : name ?? this.name,
Expand All @@ -93,6 +113,11 @@ class PairedVehicleConfig {
mqttUsername: mqttUsername,
mqttPassword: mqttPassword,
mqttClientId: mqttClientId ?? this.mqttClientId,
devicePublicKey: devicePublicKey ?? this.devicePublicKey,
deviceKeyId: deviceKeyId ?? this.deviceKeyId,
enrolledClientKey: clearEnrolledClientKey
? null
: enrolledClientKey ?? this.enrolledClientKey,
);

/// Keys what is stored per vehicle (saved layouts, cached state, activity
Expand Down Expand Up @@ -126,6 +151,11 @@ class PairedVehicleConfig {
if (mqttUsername != null) 'mqttUsername': mqttUsername,
if (mqttPassword != null) 'mqttPassword': mqttPassword,
if (mqttClientId != null) 'mqttClientId': mqttClientId,
if (devicePublicKey != null)
'devicePublicKey': base64Encode(devicePublicKey!),
if (deviceKeyId != null) 'deviceKeyId': deviceKeyId,
if (enrolledClientKey != null)
'enrolledClientKey': base64Encode(enrolledClientKey!),
};

factory PairedVehicleConfig._fromJson(Map<String, dynamic> j) =>
Expand All @@ -144,7 +174,13 @@ class PairedVehicleConfig {
mqttUsername: j['mqttUsername'] as String?,
mqttPassword: j['mqttPassword'] as String?,
mqttClientId: j['mqttClientId'] as String?,
devicePublicKey: _bytes(j['devicePublicKey']),
deviceKeyId: j['deviceKeyId'] as String?,
enrolledClientKey: _bytes(j['enrolledClientKey']),
);

static List<int>? _bytes(Object? base64) =>
base64 is String ? base64Decode(base64) : null;
}

/// The paired vehicles and which one is current: the only one with live links.
Expand Down
4 changes: 4 additions & 0 deletions lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import 'package:open_car_app/providers/connection_activity_provider.dart';
import 'package:open_car_app/providers/dashboard_layout_provider.dart';
import 'package:open_car_app/providers/paired_vehicle_provider.dart';
import 'package:open_car_app/providers/vehicle_summary_provider.dart';
import 'package:open_car_app/providers/secure_channel_provider.dart';
import 'package:open_car_app/providers/selected_vehicle_provider.dart';
import 'package:open_car_app/providers/theme_provider.dart';
import 'package:open_car_app/screens/dashboard/dashboard_screen.dart';
Expand Down Expand Up @@ -99,6 +100,9 @@ class AppEntryRouter extends ConsumerWidget {
// Listen from the start of each connection, so the bus health sent when
// the app subscribes is already there when the settings first show it.
ref.listen(canBusHealthProvider, (_, _) {});
// Enrolls this phone's client key once it is validated in the car, and
// pins the device identity (see the provider).
ref.listen(clientKeyEnrollmentProvider, (_, _) {});
final vehicle = ref.watch(selectedVehicleProvider);
final setupPending = ref.watch(wizardSetupPendingProvider);
if (vehicle == null || setupPending) return const PairingWizardScreen();
Expand Down
11 changes: 11 additions & 0 deletions lib/models/paired_phone.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,27 @@ class PairedPhoneInfo {
/// app doesn't know its own BLE address.
final bool isThisPhone;

/// The phone has a client key enrolled, so it can reach the device over the
/// secure channel (LAN, relay) as well as Bluetooth.
final bool remoteKeyEnrolled;

/// The label the phone enrolled its key with; empty without a key.
final String remoteKeyLabel;

const PairedPhoneInfo({
required this.deviceId,
required this.trust,
required this.isThisPhone,
this.remoteKeyEnrolled = false,
this.remoteKeyLabel = '',
});

factory PairedPhoneInfo.fromProto(PairedPhone phone) => PairedPhoneInfo(
deviceId: List.unmodifiable(phone.deviceId),
trust: phone.trust,
isThisPhone: phone.isRequester,
remoteKeyEnrolled: phone.remoteKeyEnrolled,
remoteKeyLabel: phone.remoteKeyLabel,
);

bool get isValidated => trust == PhoneTrustLevel.PHONE_TRUST_LEVEL_VALIDATED;
Expand Down
Loading