epic(#939): close the stale-read window, and a verdict on #190

Epic D of Feature #853. A different defect class from Epic B: these stores
ARE correctly per-radio and bled anyway, through timing.

**D2, #158: the window was an unexpected disconnect.** A manual
`disconnect()` clears `_selfPublicKey`; `_handleDisconnection()` did not. So
after a drop, every per-radio store, and the one `channels_screen` builds
from `selfPublicKeyHex`, still held the previous radio's prefix. Connect a
DIFFERENT radio and any read before its SELF_INFO landed served the old
radio's history. That matches #158 being seen on desktop and not Android:
it is a race, not a logic error.

`_clearStorageScopeKeys()` now runs on an unexpected drop. It clears
`_selfPublicKey` as well as the eleven connector-owned stores and
StorageService, because `channels_screen` does not share those instances and
derives its key from the getter, so clearing only the stores would have left
that path reading stale.

Verified before relying on it: every one of the thirteen per-radio stores
guards on an empty key, in BOTH directions. I checked rather than assumed,
because if any had used a bare prefix instead, clearing the key would have
created a NEW unscoped global key, which is the exact bug class this Feature
exists to remove. The names and deviceId stay, so the UI can still say which
radio it is reconnecting to; only the data-scoping identity goes.

**D1, #190: its named root cause is addressed, proven not argued.** #190
blamed slot-index keying with no PSK binding. Two mechanisms landed since:
PSK-identity keying (#194) and the reuse-clear in `setChannel` (#193). Rather
than assert that, there are tests reproducing #190's own scenario, a slot
reassigned to a different channel:

- keyed by PSK, the newly added channel reads a different key and sees
  nothing of the old occupant, which is #190's reproduction
- the old occupant keeps its own history, because this is isolation by
  identity rather than deletion
- the index fallback still works and still warns, pinning the remaining
  surface

What remains of #190 is the index fallback firing before the channel list has
loaded, which is #333 and a timing problem, so it belongs to this Epic rather
than to #190. Recommendation for the owner: close #190 as superseded by #193,
#194 and this Epic. Not closing it myself; it is his call and D1 was scoped
as a verdict with evidence, not a closure.

Suite 1,425 pass, analyze clean, format clean.

Citadel: meshcore-open-pdx, meshcore-open-cwd
Refs #939, #158, #190, #333, #853

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
pull/949/head
diffwireauto 1 month ago
parent afbab311e6
commit 12f2903a11

@ -3202,6 +3202,36 @@ class MeshCoreConnector extends ChangeNotifier {
unawaited(service.loadForDevice(key == null ? null : pubKeyToHex(key)));
}
/// Drops the identity that scopes every per-radio store, so a read before
/// the next radio's SELF_INFO returns nothing instead of the last radio's
/// data (#158).
///
/// Every store below treats an empty key as "no radio": loads nothing,
/// writes nothing. That is deliberate and is the #754 precedent, so this is
/// a fail-closed reset rather than a cache invalidation.
///
/// `_selfPublicKey` goes too, because `channels_screen` builds its own store
/// from `selfPublicKeyHex` rather than sharing these instances, so clearing
/// only the stores here would leave that path reading a stale prefix.
@visibleForTesting
void clearStorageScopeKeysForTest() => _clearStorageScopeKeys();
void _clearStorageScopeKeys() {
_selfPublicKey = null;
_channelMessageStore.setPublicKeyHex = '';
_messageStore.setPublicKeyHex = '';
_channelOrderStore.setPublicKeyHex = '';
_channelSettingsStore.setPublicKeyHex = '';
_channelRegionScopeStore.setPublicKeyHex = '';
_contactSettingsStore.setPublicKeyHex = '';
_contactStore.setPublicKeyHex = '';
_channelStore.setPublicKeyHex = '';
_unreadStore.setPublicKeyHex = '';
_discoveryContactStore.setPublicKeyHex = '';
storageService?.setPublicKeyHex = '';
_applySelfKeyToBlockService();
}
void _resetConnectionHandshakeState() {
_selfPublicKey = null;
_applySelfKeyToBlockService();
@ -9427,6 +9457,18 @@ class MeshCoreConnector extends ChangeNotifier {
// Preserve deviceId and displayName for UI display during reconnection
// They're only cleared on manual disconnect via disconnect() method
_hasReceivedDeviceInfo = false;
// But NOT the identity that scopes stored data (#158). A manual
// disconnect() clears _selfPublicKey; an unexpected drop did not, so
// every per-radio store, and the one channels_screen builds from
// `selfPublicKeyHex`, kept the previous radio's prefix. Connect a
// DIFFERENT radio after a drop and any read before its SELF_INFO lands
// served the old radio's history. Desktop-only in practice, which is
// where #158 was seen.
//
// Cleared here so those reads fail closed and return nothing, the #754
// precedent. The names above stay, so the UI can still say which radio it
// is reconnecting to; it is only the data-scoping identity that goes.
_clearStorageScopeKeys();
_maxContacts = _defaultMaxContacts;
_maxChannels = _defaultMaxChannels;
_resetSyncProgressState();

@ -0,0 +1,169 @@
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/connector/meshcore_connector.dart';
import 'package:meshcore_open/models/channel_message.dart';
import 'package:meshcore_open/storage/channel_message_store.dart';
import 'package:meshcore_open/storage/drift/blob_store.dart';
import 'package:meshcore_open/storage/drift/offband_database.dart';
import 'package:meshcore_open/storage/prefs_manager.dart';
import 'package:shared_preferences/shared_preferences.dart';
/// #939 Epic D: the scope-key lifecycle.
///
/// A different defect class from Epic B's global keys. These stores ARE
/// correctly per-radio; they bled anyway, through timing. The scope key is set
/// on SELF_INFO, and an unexpected disconnect did not clear it, so connecting a
/// different radio left a window in which any read served the previous radio's
/// data (#158).
///
/// Also carries D1's verdict on #190, as a test rather than an argument.
void main() {
late OffbandDatabase db;
setUp(() async {
SharedPreferences.setMockInitialValues({});
PrefsManager.reset();
await PrefsManager.initialize();
db = OffbandDatabase(NativeDatabase.memory());
BlobStore.overrideForTest(BlobStore(db));
});
tearDown(() async {
await db.close();
BlobStore.clearTestOverride();
});
ChannelMessage msg(String text) => ChannelMessage(
senderName: 's',
text: text,
timestamp: DateTime.fromMillisecondsSinceEpoch(1700000000000),
isOutgoing: false,
channelIndex: 0,
messageId: 'id-$text',
);
group('#158 the stale-read window after an unexpected drop', () {
test(
'clearing the scope keys makes a read fail closed, not serve radio A',
() async {
// Radio A connects and stores history.
final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20;
await store.saveChannelMessages(0, [msg('radio A only')]);
expect((await store.loadChannelMessages(0)).length, 1);
// The drop. Before this fix _handleDisconnection left the key in
// place, so this store still answered as radio A.
store.setPublicKeyHex = '';
expect(
await store.loadChannelMessages(0),
isEmpty,
reason:
'with no radio identity a read must return nothing. '
'Serving radio A here is #158',
);
},
);
test('and a write in that window is refused, not misfiled', () async {
final store = ChannelMessageStore()..setPublicKeyHex = '';
await store.saveChannelMessages(0, [msg('arrived mid-reconnect')]);
// Bring radio A back and confirm nothing was filed under it.
store.setPublicKeyHex = 'a' * 20;
expect(
await store.loadChannelMessages(0),
isEmpty,
reason:
'a message arriving before SELF_INFO must not be written '
'under whichever radio connects next',
);
});
test('the connector clears every store on an unexpected drop', () async {
// Exercises the real reset rather than a hand-cleared store, so the
// test fails if a store is added to the connector and left out of
// _clearStorageScopeKeys.
final connector = MeshCoreConnector();
connector.clearStorageScopeKeysForTest();
expect(
connector.selfPublicKeyHex,
isEmpty,
reason:
'channels_screen builds its own store from this getter, so '
'clearing the connector-owned stores alone would leave that '
'path reading a stale prefix',
);
});
});
group('#190 verdict: a reused slot cannot surface the old occupant', () {
// #190's reproduction: scan a new channel's QR, and the new channel shows
// the previous occupant's history (#echo). Its named root cause was
// slot-index keying with no PSK binding. Two mechanisms landed since, and
// this proves the scenario rather than arguing it.
test(
'PSK identity, not slot index, decides which history is read',
() async {
final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20;
// The old occupant of slot 0.
store.channelPskResolver = (_) => 'psk_old';
await store.saveChannelMessages(0, [msg('old #echo history')]);
// The slot is reassigned: same index 0, different PSK.
store.channelPskResolver = (_) => 'psk_new';
expect(
await store.loadChannelMessages(0),
isEmpty,
reason:
'#190 exactly: the newly added channel must not see the '
'previous occupant\'s messages. Keyed by PSK (#194) it reads a '
'different key entirely',
);
},
);
test('and the old occupant\'s history is still its own', () async {
final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20;
store.channelPskResolver = (_) => 'psk_old';
await store.saveChannelMessages(0, [msg('old #echo history')]);
store.channelPskResolver = (_) => 'psk_new';
await store.saveChannelMessages(0, [msg('new channel')]);
store.channelPskResolver = (_) => 'psk_old';
expect(
(await store.loadChannelMessages(0)).single.text,
'old #echo history',
reason:
'isolation by identity, not deletion: if that channel comes '
'back to any slot it still has its own history',
);
});
test('the index fallback is what remains, and it warns', () async {
// With no resolver the store falls back to the slot-index key. That is
// legitimate before the channel list has loaded and is the #333 race,
// which is a TIMING problem and therefore this Epic's subject rather
// than #190's. Pinned here so the remaining surface is explicit.
final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20;
await store.saveChannelMessages(0, [msg('written without a PSK')]);
expect(
(await store.loadChannelMessages(0)).single.text,
'written without a PSK',
reason:
'the fallback still works; what it cannot do is tell two '
'occupants of one slot apart, which is why _storageKey logs a '
'warning when it fires',
);
});
});
}
Loading…
Cancel
Save

Powered by TurnKey Linux.