feat(SystemHandler,ConfigManager): add system.set_identity sysadmin command (F-060)

Device identity (serial/hw_family/hw_revision) has been read-only from
production firmware since NVS provisioning — serial derives the MQTT
password and hw_family/hw_revision select the OTA channel, so an
uncontrolled write path could desync MQTT auth or brick OTA to the
wrong hardware. This adds one narrow, deliberate exception: an
MQTT-only system.set_identity command for correcting a
mis-provisioned unit or reassigning a serial after a board swap,
without a USB/serial reflash.

Rejected over WebSocket/HTTP/UART by design (same pattern as
identify's WebSocket-only check); requires all three fields together
to avoid partial-identity states; forces a reboot after a successful
write since MQTT credentials/hostname/AP SSID are derived from serial
only once at boot. Firmware does not update the backend device record
itself — that's the caller's (console's) responsibility in the same
operation.

Also includes docs/README.md's rule 6 (console API reference sync
requirement) from an earlier uncommitted session, which this change
follows.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-20 20:09:39 +03:00
co-authored by Claude Sonnet 5
parent 28b175b4fc
commit 64a8bc2b88
7 changed files with 174 additions and 8 deletions
+31
View File
@@ -80,3 +80,34 @@ Before writing any new code, surface any dirty working tree and deal with it fir
- Pure refactors with no behaviour change
- Log message tweaks
- Doc-only commits
**6. Console API Reference is mandatory.**
Any new command/API endpoint, or a change to an existing one's contents/response/errors, must be reflected in the console's live API Reference page — not just in `docs/reference/api-reference.md`. The two are separate files in separate repos and neither auto-syncs from the other; both must be updated by hand in the same change.
### Console API Reference location
`C:\development\bellsystems-cp\frontend\src\pages\engineering\developer\ApiReferencePage.jsx`
This is a different repo (`bellsystems-cp`, the backend/console repo) from this firmware repo (`project-vesper`) — open it directly by path, it will not show up in a search scoped to this repo.
### How to update it
Commands are grouped into a `NAMESPACES` array. Each entry is `{ id, label, description, commands: [...] }` — one entry per namespace (e.g. `system`, `clock`, `relay`, `ota`, `firmware`, `network`, or `root` for commands with no prefix). Find the matching namespace (or add a new one) and add/edit a command object in its `commands` array with these fields:
| Field | Required | Meaning |
|---|---|---|
| `cmd` | yes | Full command name, e.g. `"clock.set_time"` |
| `handler` | yes | The C++ handler class that services it, e.g. `"ClockHandler"` |
| `transports` | yes | Array/label of which transports accept it — usually `['All']`; narrow it if the command is transport-restricted (e.g. `identify` is WebSocket-only, `ping` is unavailable on RTC-less variants) |
| `description` | yes | What the command does, plus any caveats (rejection conditions, variant restrictions, blocking behaviour) |
| `contents` | yes (`null` if none) | Array of request fields, or `null` if the command takes no `contents` body |
| `contents[].field` | yes | Field name as it appears in the JSON `contents` object |
| `contents[].type` | yes | Wire type: `string`, `int`, `bool`, `int[]`, `object`, etc. |
| `contents[].required` | yes | `true`/`false` — whether the field is mandatory. If a command requires "at least one of" a set of optional fields, say so in `notes` on each and add an error entry for the all-missing case |
| `contents[].notes` | yes | What the field means, valid ranges/values, 0-based vs 1-based indexing (call this out explicitly — this API mixes both), defaults, and interactions with other fields |
| `response` | yes | Exact success wire-format JSON as a string, matching the real `{ "status": "SUCCESS", "type": "<cmd>", "message"/"data": ... }` envelope the firmware actually sends |
| `errors` | yes (`[]` if none) | Array of `{ message, condition }` — `message` is the exact error string the firmware emits, `condition` is when it fires. Should cover every `CommandResult::err()` path in the handler |
| `example` | yes | One or more realistic full request JSON payloads (`{ "v": 2, "cmd": "...", "contents": {...} }`), as a string |
| `warning` | yes (`null` if none) | Set for anything destructive or irreversible (reboot, factory reset, rollback) — short caller-facing warning string |
When adding a **new namespace**, also check `UART_WHITELIST` near the top of the file — if the command should be reachable over UART, add its name there too (UART only accepts whitelisted commands).
Keep `docs/reference/api-reference.md` (this repo) and the console page in sync — update both in the same change whenever a command is added or changed.
+19
View File
@@ -69,6 +69,7 @@ Every feature — user-facing or significant internal mechanism — is listed he
| F-057 | QA-to-shipping stats reset — `telemetry.reset_boot_data` (lifetime boot count + SD boot log) and `logs.clear` (SD debug logs) | v2.1.6 | Stable |
| F-058 | Fix: NTP sync RTC corruption on flaky internet — de-dup guard, retry cooldown, large-jump consensus check | v2.1.7 | Stable |
| F-059 | Fix: partition table mismatch blocking safe OTA to pre-restructure field devices | v2.1.7 | Stable |
| F-060 | `system.set_identity` — sysadmin override of factory-set device identity (serial/hw_family/hw_revision) | v2.1.7 | Stable |
---
@@ -976,3 +977,21 @@ With this in place, OTA to the existing field devices is safe going forward —
Verified: `pio run` (all four environments) + manual decode of `partitions.bin` against the field-device `partitions.csv`.
Subsystem: `platformio.ini`, `no_fs.csv` (new)
---
### F-060 — `system.set_identity`: sysadmin override of factory-set device identity
Device identity (`serial`, `hw_family`, `hw_revision`) has been factory-set-and-read-only since the NVS provisioning work — production firmware loads it once at boot and previously had no write path at all (`ConfigManager::saveDeviceIdentityToNVS()` had been deliberately removed). That's still the right default: `serial` derives the MQTT password (`HMAC-SHA256(MQTT_SECRET, serial)`), and `hw_family`/`hw_revision` select the OTA channel/binary, so an uncontrolled identity change can desync MQTT auth or pull firmware built for the wrong board.
This adds a narrow, deliberate exception: a new `system.set_identity` command lets a sysadmin overwrite identity on an already-deployed device — e.g. correcting a mis-provisioned unit, or reassigning a serial after a board swap — without a USB/serial reflash.
**Design constraints, by intent:**
- **MQTT-only.** Rejected over WebSocket/HTTP with an explicit transport check in the handler (same pattern as `identify`'s WebSocket-only restriction), and not added to `UARTTransport::WHITELIST`, so UART drops it by default. This means the command is only reachable by publishing to the device's MQTT command topic — i.e. only from the backend/console, not from a device on the local network probing the WebSocket/UART surface.
- **All three fields required together.** No partial update. Matches the existing boot-time invariant (`loadDeviceIdentityFromNVS()` already fails if any of the three is empty) — there's no valid state with only some of them set.
- **Forces a reboot after a successful write.** MQTT credentials, hostname, and AP SSID are all derived from `serial` once at boot (`ConfigManager::begin()`); they will not recompute live, so the device would otherwise keep authenticating with the *old* derived password after its stored identity already changed. Reply is sent first, then reboot after 2s (same pattern as `system.restart`).
- **Firmware does not update the backend.** This command only writes the device's own NVS + in-RAM copy. The backend device record (and re-derived MQTT password) must be updated in the same operation by whatever triggers this command — documented as a caller responsibility in both the handler and `ConfigManager::saveDeviceIdentityToNVS()`.
Not gated behind an additional `confirm` field in the command body — the console UI is expected to require its own confirmation step before ever publishing this command, so no device-side friction was added on top of that.
Subsystem: `src/ConfigManager/ConfigManager.hpp`, `src/ConfigManager/ConfigManager.cpp`, `src/Communication/Handlers/SystemHandler/SystemHandler.hpp`, `src/Communication/Handlers/SystemHandler/SystemHandler.cpp`
+27
View File
@@ -449,6 +449,33 @@ Reboot the device. Response is sent before reboot (2s delay).
---
### `system.set_identity`
Overwrite the device's factory-set identity (`serial`, `hw_family`, `hw_revision`) in NVS and reboot to apply it. Intended for sysadmin use only — e.g. reassigning a serial after a board swap, or correcting a mis-provisioned unit — via the backend console, which is responsible for updating its own device record (including re-deriving the MQTT password from the new serial) in the same operation. Firmware does not touch the backend record itself.
> **Warning:** Non-reversible from the device's perspective, and dangerous if the backend device record isn't updated to match — a serial mismatch will break MQTT auth (password is derived from serial), and a wrong `hw_family`/`hw_revision` can pull an OTA build for the wrong hardware. Device restarts 2s after a successful response to apply the new identity.
| | |
|---|---|
| Handler | SystemHandler |
| Transports | MQTT only |
| Contents | `serial` (required), `hw_family` (required), `hw_revision` (required) |
```json
{ "v": 2, "cmd": "system.set_identity", "contents": { "serial": "PV000000000001", "hw_family": "VS", "hw_revision": "01" } }
```
**Errors:**
| Message | Condition |
|---|---|
| `system.set_identity is only available via MQTT` | Sent over WebSocket, HTTP, or UART |
| `Missing required fields: serial, hw_family, hw_revision (all required)` | One or more fields absent or not a string |
| `serial, hw_family and hw_revision must be non-empty` | One or more fields present but empty |
| `Failed to persist new identity to NVS — device identity unchanged` | NVS write/commit failed |
---
## Firmware Namespace — `FirmwareHandler`
---
@@ -29,7 +29,8 @@ std::vector<String> SystemHandler::commands() const {
"system.get_settings", // backward-compat alias — routes to handleGetConfig
"system.get_device_info", "system.health",
"system.get_all", "system.get_telemetry",
"system.factory_reset", "system.restart"
"system.factory_reset", "system.restart",
"system.set_identity"
};
}
@@ -46,6 +47,7 @@ CommandResult SystemHandler::execute(const CommandEnvelope& envelope) {
if (envelope.command == "system.get_telemetry") return handleGetTelemetry(envelope);
if (envelope.command == "system.factory_reset") return handleFactoryReset(envelope);
if (envelope.command == "system.restart") return handleRestart(envelope);
if (envelope.command == "system.set_identity") return handleSetIdentity(envelope);
return CommandResult::err(envelope.command, "Unknown system command");
}
@@ -313,4 +315,47 @@ CommandResult SystemHandler::handleRestart(const CommandEnvelope& e) {
return CommandResult::ok("system.restart", "Device will restart in 2 seconds");
}
CommandResult SystemHandler::handleSetIdentity(const CommandEnvelope& e) {
// Sysadmin-only override of factory-set device identity. Restricted to MQTT so it can
// only be triggered from the backend/console, which is expected to update its own
// device record (and re-derive the MQTT password from the new serial) in lockstep —
// see ConfigManager::saveDeviceIdentityToNVS() for the full rationale.
if (e.transport != CommandEnvelope::Transport::MQTT) {
return CommandResult::err("system.set_identity", "system.set_identity is only available via MQTT");
}
if (!e.contents["serial"].is<const char*>() ||
!e.contents["hw_family"].is<const char*>() ||
!e.contents["hw_revision"].is<const char*>()) {
return CommandResult::err("system.set_identity",
"Missing required fields: serial, hw_family, hw_revision (all required)");
}
String serial = e.contents["serial"].as<String>();
String hwFamily = e.contents["hw_family"].as<String>();
String hwRevision = e.contents["hw_revision"].as<String>();
if (serial.isEmpty() || hwFamily.isEmpty() || hwRevision.isEmpty()) {
return CommandResult::err("system.set_identity",
"serial, hw_family and hw_revision must be non-empty");
}
LOG_WARNING(TAG, "Device identity override requested via MQTT command");
bool ok = _configManager.saveDeviceIdentityToNVS(serial, hwFamily, hwRevision);
if (!ok) {
return CommandResult::err("system.set_identity",
"Failed to persist new identity to NVS — device identity unchanged");
}
// MQTT credentials, hostname and AP SSID were derived from the OLD serial at boot
// and won't recompute without a restart, so force one after the reply goes out.
xTaskCreate([](void*) {
vTaskDelay(pdMS_TO_TICKS(2000));
ESP.restart();
}, "setIdentityRebootTask", 1024, nullptr, 1, nullptr);
return CommandResult::ok("system.set_identity",
"Device identity updated. Restarting in 2 seconds to apply.");
}
#endif // HAS_RTC
@@ -40,6 +40,7 @@ private:
CommandResult handleGetTelemetry(const CommandEnvelope& e);
CommandResult handleFactoryReset(const CommandEnvelope& e);
CommandResult handleRestart(const CommandEnvelope& e);
CommandResult handleSetIdentity(const CommandEnvelope& e);
};
#endif // HAS_RTC
+40 -3
View File
@@ -193,9 +193,46 @@ bool ConfigManager::loadDeviceIdentityFromNVS() {
return true;
}
// REMOVED: saveDeviceIdentityToNVS() - Production firmware MUST NOT write device identity
// Device identity (serial, hwFamily, hwRevision) is factory-set ONLY and stored in NVS by backend provisioning
// Production firmware reads these values once at boot and keeps them in RAM
// Device identity is factory-set and normally READ-ONLY from production firmware —
// see loadDeviceIdentityFromNVS() above. This is the sole write path, reserved for
// the sysadmin-only system.set_identity command (MQTT transport only). It exists to
// let a sysadmin correct/reassign identity on already-deployed hardware; ordinary
// application code must never call this.
//
// Callers MUST update the backend device record (serial/hw_family/hw_revision, and
// re-derive the MQTT password from the new serial) in the same operation — this
// method only updates the device's own NVS + in-RAM copy, and does not touch MQTT
// credentials, hostname, or AP SSID, all of which were already derived from the OLD
// serial at boot. A reboot is required after calling this for those to be
// recomputed consistently.
bool ConfigManager::saveDeviceIdentityToNVS(const String& serial, const String& hwFamily, const String& hwRevision) {
if (serial.isEmpty() || hwFamily.isEmpty() || hwRevision.isEmpty()) {
LOG_ERROR(TAG, "ConfigManager - ❌ saveDeviceIdentityToNVS: all three fields are required");
return false;
}
LOG_WARNING(TAG, "═══════════════════════════════════════════════════════════════════════════");
LOG_WARNING(TAG, " ⚠️ DEVICE IDENTITY OVERRIDE (sysadmin command)");
LOG_WARNING(TAG, " 🆔 Serial: %s -> %s", deviceConfig.serial.c_str(), serial.c_str());
LOG_WARNING(TAG, " 🔧 HW Family: %s -> %s", deviceConfig.hwFamily.c_str(), hwFamily.c_str());
LOG_WARNING(TAG, " 📐 HW Revision: %s -> %s", deviceConfig.hwRevision.c_str(), hwRevision.c_str());
LOG_WARNING(TAG, "═══════════════════════════════════════════════════════════════════════════");
bool ok = writeNVSString(NVS_SERIAL_KEY, serial);
ok &= writeNVSString(NVS_HW_FAMILY_KEY, hwFamily);
ok &= writeNVSString(NVS_HW_REVISION_KEY, hwRevision);
ok &= commitNVS();
if (!ok) {
LOG_ERROR(TAG, "ConfigManager - ❌ Failed to persist device identity override to NVS");
return false;
}
deviceConfig.serial = serial;
deviceConfig.hwFamily = hwFamily;
deviceConfig.hwRevision = hwRevision;
return true;
}
String ConfigManager::readNVSString(const char* key, const String& defaultValue) {
if (nvsHandle == 0) {
+9 -3
View File
@@ -321,9 +321,10 @@ public:
const ClockConfig& getClockConfig() const { return clockConfig; }
const GeneralConfig& getGeneralConfig() const { return generalConfig; }
// Device identity methods (READ-ONLY - factory set via separate factory firmware)
// These values are loaded ONCE at boot from NVS and kept in RAM
// Production firmware CANNOT modify device identity
// Device identity getters — factory-set via separate factory firmware, loaded
// ONCE at boot from NVS and kept in RAM. Not writable through normal config
// flows; the only write path is saveDeviceIdentityToNVS() below, reserved for
// the sysadmin-only system.set_identity command.
String getSerial() const { return deviceConfig.serial; }
String getHwFamily() const { return deviceConfig.hwFamily; }
String getHwRevision() const { return deviceConfig.hwRevision; }
@@ -337,6 +338,11 @@ public:
// No-op: version is compiled in, not stored. Kept for call-site compatibility.
void setFwVersion(const String&) {}
// Sysadmin override: overwrites factory-set device identity in NVS and in RAM.
// Gated to the system.set_identity command (MQTT-only). Caller is responsible
// for updating the backend device record to match — this call does not.
bool saveDeviceIdentityToNVS(const String& serial, const String& hwFamily, const String& hwRevision);
// Configuration update methods for app commands
void updateTimeConfig(long gmtOffsetSec, int daylightOffsetSec);
void updateNetworkConfig(const String& hostname, bool useStaticIP, IPAddress ip, IPAddress gateway,