Files
plezy/test/services/prefs_store_atomic_write_windows_test.dart
T
edde746 3f49bcabf8 fix(prefs): replace the desktop preference store atomically
Upstream shared_preferences_windows and _linux write the whole preference
document with a bare `writeAsStringSync`. That opens with the default
`FileMode.write`, which truncates the live file before writing it, so every
single preference write has a window in which the only copy on disk is empty
or half-written. A crash, power loss, forced reboot or antivirus interception
inside that window leaves a document that fails to parse on every subsequent
launch — and the store holds the credential-vault key, so the loss is not
recoverable by rewriting it. This is the corruption class behind #1732; the
recovery path already landed is a band-aid over it.

Vendor both packages under packages/ — the convention saf_util and
wakelock_plus already follow — and stage, flush, then rename over the target.
The flush has to precede the rename or it could publish contents that were
never committed, the same corruption by another route. Staging uses one fixed
sibling name rather than a stamped one, because the file is a plaintext copy
of the vault key, tracker refresh tokens and Seerr cookies; it is created in
the target's own directory so rename stays on one volume and the mode matches
what the canonical file would have had, and a stale one is swept once the
canonical document has been read cleanly. Both deltas are marked in-source and
in provenance.json with the refresh contract.

Atomicity is proven, not asserted. A hard link to the store observes the old
document after a write, which only holds when the directory entry was replaced
— truncate-in-place would have rewritten the shared inode, and that test does
fail against unpatched upstream. Upstream's own suites still pass unchanged in
both packages and now run in CI, so the patch keeps the contract it inherited.
Windows `MoveFileExW` replacement semantics cannot be proven on a POSIX runner
or a memory file system, so they get their own test on the existing
windows-latest job, including replacement while a reader holds the file open —
antivirus and Search Indexer both do.
2026-08-01 06:59:20 +02:00

100 lines
4.0 KiB
Dart

@TestOn('windows')
library;
import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider_windows/path_provider_windows.dart';
import 'package:plezy/services/prefs_recovery.dart';
import 'package:shared_preferences_platform_interface/types.dart';
import 'package:shared_preferences_windows/shared_preferences_windows.dart';
/// The vendored `shared_preferences_windows` atomic write, on real NTFS.
///
/// `prefs_store_atomic_write_test.dart` covers the same patch through the
/// Linux twin and runs everywhere, but it can only prove POSIX `rename(2)`.
/// The store this all exists to protect lives on Windows (#1732), and there
/// the replacement goes through `MoveFileExW` with MOVEFILE_REPLACE_EXISTING —
/// which a POSIX runner and a memory file system are both silent about. Run by
/// the windows-native-test job in CI.
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late Directory support;
late File store;
late File staging;
late SharedPreferencesAsyncWindows backend;
const options = SharedPreferencesOptions();
setUp(() async {
support = await Directory.systemTemp.createTemp('plezy_atomic_write_win_');
store = File(p.join(support.path, prefsStoreFileName));
staging = File('${store.path}.tmp');
backend = SharedPreferencesAsyncWindows()..pathProvider = _TempPathProviderWindows(support.path);
});
tearDown(() async {
if (await support.exists()) await support.delete(recursive: true);
});
test('rename replaces an existing document on NTFS', () async {
// The bare `MoveFileW` this would otherwise compile to fails outright when
// the destination exists. If the vendored write ever loses its replace
// semantics, every preference write after the first one fails silently —
// `_writePreferences` swallows the exception and returns false.
await backend.setString('theme', 'dark', options);
await backend.setString('theme', 'light', options);
expect(jsonDecode(await store.readAsString()), containsPair('theme', 'light'));
expect(await staging.exists(), isFalse);
});
test('a replaced document is complete and parseable', () async {
for (var i = 0; i < 25; i++) {
await backend.setString('key$i', 'value$i', options);
// Every intermediate state is a whole document, never a truncation.
expect(PrefsRecovery.describeStoreDamage(await store.readAsBytes()), isNull);
}
final document = jsonDecode(await store.readAsString()) as Map<String, dynamic>;
expect(document, containsPair('key0', 'value0'));
expect(document, containsPair('key24', 'value24'));
});
test('a stale staging file is swept once the document reads cleanly', () async {
await backend.setString('theme', 'dark', options);
await staging.writeAsString('{"credential_vault_key_v1":"left-behind"', flush: true);
final reader = SharedPreferencesAsyncWindows()..pathProvider = _TempPathProviderWindows(support.path);
await reader.getPreferences(const GetPreferencesParameters(filter: PreferencesFilters()), options);
expect(await staging.exists(), isFalse);
});
test('an open reader does not block the replacement', () async {
// Windows keeps mandatory locks on open handles, and antivirus and Search
// Indexer both hold the store open. A replacement that a reader can veto
// would turn every preference write into a silent no-op on exactly the
// machines most likely to have damaged the store in the first place.
await backend.setString('theme', 'dark', options);
final handle = await store.open();
addTearDown(handle.close);
await backend.setString('theme', 'light', options);
expect(jsonDecode(await store.readAsString()), containsPair('theme', 'light'));
});
}
class _TempPathProviderWindows extends PathProviderWindows {
_TempPathProviderWindows(this.supportPath);
final String supportPath;
@override
Future<String?> getApplicationSupportPath() async => supportPath;
}