Skip to content

Commit 29df77f

Browse files
committed
fix(config): detect failed writes of empty string settings
Preferences::putString() returns 0 for an empty value on success and on failure. Verify empty writes by reading the key back so a failed factory reset is reported instead of restarting with the old Wi-Fi or MQTT secrets. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012JY8RZscs5W8tLQMuZB95K
1 parent 56c140e commit 29df77f

2 files changed

Lines changed: 24 additions & 3 deletions

File tree

‎src/ConfigManager.cpp‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -134,10 +134,16 @@ bool ConfigManager::load() {
134134
return true;
135135
}
136136

137-
// Preferences::putString() returns the stored length, so 0 is a failure only
138-
// for a non-empty value; an empty string cannot be told apart from an error.
137+
// Preferences::putString() returns the stored length, so 0 means a failure only
138+
// for a non-empty value. An empty string returns 0 on success and on failure,
139+
// so it is verified by reading it back: a failed write leaves the old value
140+
// (or the sentinel default) behind.
139141
static bool putStringChecked(Preferences &prefs, const char *key, const String &value) {
140-
return prefs.putString(key, value) == value.length();
142+
const size_t written = prefs.putString(key, value);
143+
if (value.length() > 0) {
144+
return written == value.length();
145+
}
146+
return prefs.getString(key, "\x01") == value;
141147
}
142148

143149
bool ConfigManager::save() {

‎test/native/config_persistence/test_config_persistence.cpp‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,20 @@ void test_single_failed_put_fails_save() {
7070
EXPECT(ConfigManager::save());
7171
}
7272

73+
void test_failed_empty_string_write_is_detected() {
74+
section("a failed write of an empty string fails save()");
75+
resetStore();
76+
storeCustomConfig();
77+
EXPECT(ConfigManager::getWiFi().ssid == "pool-net");
78+
79+
ConfigManager::getWiFi().ssid = "";
80+
Preferences::s_failingPutKeys.insert("wifi_ssid");
81+
EXPECT(!ConfigManager::save()); // the old SSID would be loaded again on boot
82+
83+
Preferences::s_failingPutKeys.clear();
84+
EXPECT(ConfigManager::save());
85+
}
86+
7387
void test_failed_factory_reset_restores_nvs() {
7488
section("failed factory reset leaves the previous configuration in NVS");
7589
resetStore();
@@ -141,6 +155,7 @@ void test_legacy_mapping_keys_are_migrated() {
141155

142156
int main() {
143157
test_single_failed_put_fails_save();
158+
test_failed_empty_string_write_is_detected();
144159
test_failed_factory_reset_restores_nvs();
145160
test_mapping_is_written_as_one_record();
146161
test_legacy_mapping_keys_are_migrated();

0 commit comments

Comments
 (0)