E2E-encrypt diet_guard sync and export keys
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (mypy, mypy, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (pylint, pylint, ) (push) Has been cancelled
pre-commit / pre-commit (${{ matrix.group }}) (rest, , mypy,pylint) (push) Has been cancelled
Tests / test (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
repo-contract / repo contract (push) Has been cancelled

Every sync payload (food log, banks, budget, catering credential,
Body, export keyring) now lives on diet-guard-sync/devices-e2e, sealed
with the Argon2id key from the shared crdt-sync passphrase; record
ids, tombstones and clocks stay clear. Old plaintext nodes are copied
once and never written or deleted. Locked = no pull, no push.

- PC: _sync_e2e.open_e2e over crdt-sync 0.11.0, key and copy memo in
  ~/.local/share/diet_guard/e2e; undecryptable peers are skipped.
- Phone/desktop: sync_e2e.dart, crdt_sync_flutter 0.8.1, lock icon
  in Settings; pullExportKeys goes through the same open.
- wake-alarm weigh-ins read from wake-alarm-sync/devices-e2e (own
  header), on both sides.

Todo: fda71ed1

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-12 10:29:20 +01:00
parent 649a324f8a
commit 617e1ec879
51 changed files with 1269 additions and 272 deletions

View File

@ -108,9 +108,9 @@ repos:
# the manifest becomes an unresolvable hook environment rather
# than merely an old one.
- gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.12.0#subdirectory=gatelock
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.0#subdirectory=freedays
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.3.0#subdirectory=sickdays
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.0#subdirectory=crdt-sync
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.2#subdirectory=freedays
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.3#subdirectory=sickdays
- mcp>=2,<3
- pydantic
- defusedxml==0.7.1

View File

@ -43,6 +43,18 @@ A sync tick pulls every other device's log from `kuhyx/syncs`
`(time, desc)` dedup), **re-signs every persisted entry**, rebuilds the food
bank, pushes back.
**End-to-end encrypted** (since 2026-11-12, `_sync_e2e.py` /
`app/lib/services/sync_e2e.dart`): everything lives on
`diet-guard-sync/devices-e2e` (revs `revs-e2e`, header `diet-guard-sync/e2e`),
fields sealed with a key from the shared passphrase
(`~/.config/crdt-sync/password`; keystore + lock icon in Settings on the
phone). Record ids, tombstones and clocks stay clear, so the food banks' ids
(food names) are visible. The old plaintext `diet-guard-sync/devices` (and
its `export_keys.json` keyring) is copied over and never written or deleted.
Locked = `SyncError` / `SyncLockedException`: nothing is pulled or pushed.
The PC keeps its derived key and copy memo in `~/.local/share/diet_guard/e2e`.
The wake-alarm weigh-ins come from `wake-alarm-sync/devices-e2e` (own header).
**On the PC, sync is event-driven — there is no periodic timer.** The old
`diet-guard-sync.timer` (~15 min) was deleted: it paid a network round-trip on
every idle tick to approximate the two moments state actually changes here.

View File

@ -6,6 +6,8 @@ library;
import 'dart:async';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'
show E2ePassphraseButton;
import 'package:diet_guard_app/models/meal_schedule.dart';
import 'package:diet_guard_app/screens/github_mirror_screen.dart';
import 'package:diet_guard_app/screens/settings_kuchnia.dart';
@ -15,6 +17,7 @@ import 'package:diet_guard_app/services/firebase_backend.dart';
import 'package:diet_guard_app/services/firebase_client.dart';
import 'package:diet_guard_app/services/google_sign_in_backend.dart';
import 'package:diet_guard_app/services/meal_schedule_service.dart';
import 'package:diet_guard_app/services/sync_e2e.dart';
import 'package:diet_guard_app/ui/cues.dart';
import 'package:diet_guard_app/ui/macro_kind.dart';
import 'package:diet_guard_app/ui/theme.dart';
@ -191,6 +194,15 @@ class _SettingsScreenState extends State<SettingsScreen>
trailing: const Icon(Icons.chevron_right),
onTap: () => unawaited(_openSyncSettings()),
),
// End-to-end encryption passphrase: closed lock while the last
// sync found no usable key, so nothing syncs until it is set.
ValueListenableBuilder<bool>(
valueListenable: syncLocked,
builder: (_, locked, _) => ListTile(
contentPadding: EdgeInsets.zero,
leading: E2ePassphraseButton(locked: locked),
),
),
// Legacy mirror: muted tint marks it as the secondary path.
ListTile(
contentPadding: EdgeInsets.zero,

View File

@ -6,10 +6,10 @@
/// is never deleted or overwritten, each id is its own record, and two
/// devices that mint a key at the same moment both keep both.
///
/// NOTE: the synced copy sits in Firebase RTDB in plaintext, so Firebase can
/// read these keys (and therefore the sealed login in any export it could get
/// hold of) until crdt E2E lands. `export_keys` must move under that
/// encryption too: `~/src/utils/TODO-crdt-e2e-encryption.md`.
/// The synced copy is end-to-end encrypted under the shared crdt-sync
/// passphrase (`sync_e2e.dart`), on `diet-guard-sync/devices-e2e`. The old
/// plaintext `diet-guard-sync/devices/<id>/export_keys.json` nodes are
/// copied over once and then neither read nor written by this app.
library;
import 'dart:convert';

View File

@ -8,6 +8,7 @@ import 'package:diet_guard_app/services/export_keyring_sync.dart';
import 'package:diet_guard_app/services/firebase_client.dart';
import 'package:diet_guard_app/services/github_client_factory.dart';
import 'package:diet_guard_app/services/sync_device_id.dart';
import 'package:diet_guard_app/services/sync_e2e.dart';
import 'package:diet_guard_app/services/sync_settings.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
@ -31,7 +32,7 @@ Future<void> pullExportKeys() async {
final client = createGitHubClient(await SyncSettings.load());
try {
await syncExportKeys(
await syncBackend(client),
await openDietGuardStore(await syncBackend(client)),
keyring: defaultKeyring(),
devicesDir: syncDevicesDir,
);

View File

@ -1,8 +1,9 @@
/// The `export_keys` document: the keyring as a crdt_sync log.
///
/// One record per key id, never deleted, so the merge is a plain union and
/// concurrent mints on two devices both survive. See `export_keyring.dart`
/// for the plaintext-at-Firebase caveat.
/// concurrent mints on two devices both survive. [syncExportKeys] must be
/// handed the end-to-end encrypted store (`sync_e2e.dart`): these are the
/// keys that open every export.
library;
import 'dart:convert';
@ -70,6 +71,7 @@ Future<void> syncExportKeys(
deviceId: id,
legacyDeviceId: deviceId == null ? legacySyncDeviceId : null,
pathPrefix: devicesDir,
revsPath: syncRevsDir,
localLog: _toLog(await keyring.all(), id),
encode: (log) => jsonEncode({
for (final entry in log.entries) entry.key: entry.value.toJson(),

View File

@ -14,16 +14,24 @@ import 'package:diet_guard_app/services/wake_alarm_weights.dart';
/// Runs the Body sync against [client], under [devicesDir].
///
/// [wakeAlarm] is wake-alarm's own encrypted store; null (locked, or not
/// opened) skips the weigh-in ingest and nothing else.
///
/// No-ops when [BodyService] is uninitialised (a widget test, or an isolate
/// that never loaded it), so it can neither publish nor clobber anything.
Future<void> syncBody(RemoteStore client, {required String devicesDir}) async {
Future<void> syncBody(
RemoteStore client, {
required String devicesDir,
RemoteStore? wakeAlarm,
}) async {
if (!BodyService.isInitialized) return;
await ingestWakeAlarmWeights(client);
if (wakeAlarm != null) await ingestWakeAlarmWeights(wakeAlarm);
final merged = await syncLog(
client: client,
deviceId: currentSyncDeviceId,
legacyDeviceId: legacySyncDeviceId,
pathPrefix: devicesDir,
revsPath: syncRevsDir,
localLog: bodyToLog(BodyService.instance.document),
encode: encodeBodyForPush,
decode: parseRemoteBody,

View File

@ -5,8 +5,14 @@ import 'package:diet_guard_app/services/github_client_factory.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';
/// Where every device's synced files live on the remote.
const syncDevicesDir = 'diet-guard-sync/devices';
/// Where every device's synced files live on the remote: the end-to-end
/// encrypted twin of the old plaintext `diet-guard-sync/devices` (see
/// `sync_e2e.dart`; `E2eLayout.of` derives the same names).
const syncDevicesDir = 'diet-guard-sync/devices-e2e';
/// Where peers publish their (keyed) revisions, apart from the old
/// plaintext `diet-guard-sync/revs` the E2E copy fingerprints.
const syncRevsDir = 'diet-guard-sync/revs-e2e';
/// SharedPreferences key holding this install's device id.
///

View File

@ -0,0 +1,86 @@
/// End-to-end encryption of everything this app syncs.
///
/// Every blob under `diet-guard-sync/devices-e2e` (food log, banks, budget,
/// catering credential, Body, export keyring) is sealed with a key derived
/// from the shared crdt-sync passphrase kept in the OS keystore; Firebase and
/// the GitHub mirror only see record ids, tombstones and clocks. The
/// wake-alarm weigh-ins live on their own prefix with their own header, so
/// they get a second store over the same backend.
///
/// Fail closed: without a usable key nothing is pulled or pushed. The old
/// plaintext `diet-guard-sync/devices` is copied over on open (picking up
/// writes from builds not yet migrated) and never written or deleted here.
/// Mirrors `diet_guard/_sync_e2e.py`.
library;
import 'dart:developer';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:crdt_sync_flutter/crdt_sync_flutter.dart'
show openEncryptedStoreFromKeystore;
import 'package:flutter/foundation.dart';
/// The plaintext prefix every pre-E2E build wrote; only the copy reads it.
const legacyDevicesDir = 'diet-guard-sync/devices';
/// Where the wake-alarm app published before E2E.
const legacyWakeAlarmDir = 'wake-alarm-sync/devices';
/// Argon2id cost for a header this device creates; only tests lower it.
@visibleForTesting
Argon2Params e2eArgon2Params = Argon2Params.recommended;
/// Whether the last open found no usable key, for the lock button.
final ValueNotifier<bool> syncLocked = ValueNotifier<bool>(false);
/// Thrown instead of syncing when end-to-end encryption has no usable key.
class SyncLockedException implements Exception {
/// Creates the exception for [reason].
const SyncLockedException(this.reason);
/// Why the store is locked.
final E2eLockReason reason;
@override
String toString() => 'sync locked (${reason.name})';
}
Future<E2eState> _open(RemoteStore backend, String oldPrefix) =>
openEncryptedStoreFromKeystore(
store: backend,
oldPrefix: oldPrefix,
params: e2eArgon2Params,
);
/// The encrypted diet_guard store over [backend], the outermost store.
///
/// Throws [SyncLockedException] when locked, so no caller can fall through
/// to a plaintext sync.
Future<RemoteStore> openDietGuardStore(RemoteStore backend) async {
final state = await _open(backend, legacyDevicesDir);
syncLocked.value = state is! E2eReady;
if (state is E2eReady) return state.store;
throw SyncLockedException(
state is E2eLocked ? state.reason : E2eLockReason.badHeader,
);
}
/// The encrypted wake-alarm store over [backend], or null when locked or
/// unreachable.
///
/// Its weigh-ins are optional input to the diet sync, so nothing here may
/// fail the tick: a lock or a transport error skips only the ingest.
Future<RemoteStore?> openWakeAlarmStore(RemoteStore backend) async {
try {
final state = await _open(backend, legacyWakeAlarmDir);
return state is E2eReady ? state.store : null;
} on Object catch (error, stackTrace) {
log(
'wake-alarm store unavailable; skipping weigh-ins',
level: 900,
error: error,
stackTrace: stackTrace,
);
return null;
}
}

View File

@ -24,6 +24,7 @@ import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/sync_body.dart';
import 'package:diet_guard_app/services/sync_budget_local.dart';
import 'package:diet_guard_app/services/sync_device_id.dart';
import 'package:diet_guard_app/services/sync_e2e.dart';
import 'package:diet_guard_app/services/sync_merge.dart';
import 'package:diet_guard_app/services/sync_merge_kuchnia.dart';
import 'package:diet_guard_app/services/sync_state_factory.dart';
@ -32,10 +33,19 @@ const String _devicesDir = syncDevicesDir;
/// Runs one full sync tick: pull, merge, persist, push.
///
/// [backend] is the outermost raw store (the Firebase/GitHub mirror);
/// everything goes through its end-to-end encrypted view, and a locked
/// device throws [SyncLockedException] before a single read or write.
///
/// Returns the merged log as it now sits on disk locally. Propagates any
/// [GitHubSyncError] from the client for the caller (auto-sync / the manual
/// "Sync now" action) to decide how to report.
Future<DayLog> runSync(RemoteStore client, {SyncStateStore? stateStore}) async {
Future<DayLog> runSync(
RemoteStore backend, {
SyncStateStore? stateStore,
}) async {
final client = await openDietGuardStore(backend);
final wakeAlarm = await openWakeAlarmStore(backend);
final logService = LogStorageService.instance;
final local = await logService.readLog();
@ -44,6 +54,7 @@ Future<DayLog> runSync(RemoteStore client, {SyncStateStore? stateStore}) async {
deviceId: currentSyncDeviceId,
legacyDeviceId: legacySyncDeviceId,
pathPrefix: _devicesDir,
revsPath: syncRevsDir,
localLog: dayLogToLog(local),
encode: encodeLogForPush,
decode: parseRemoteLog,
@ -65,7 +76,7 @@ Future<DayLog> runSync(RemoteStore client, {SyncStateStore? stateStore}) async {
await _syncManualBank(client);
await _syncKuchniaCredential(client);
await _syncExportKeys(client);
await syncBody(client, devicesDir: _devicesDir);
await syncBody(client, devicesDir: _devicesDir, wakeAlarm: wakeAlarm);
return merged;
}
@ -80,6 +91,7 @@ Future<void> _syncFoodBank(RemoteStore client) async {
deviceId: currentSyncDeviceId,
legacyDeviceId: legacySyncDeviceId,
pathPrefix: _devicesDir,
revsPath: syncRevsDir,
localLog: foodBankToLog(await FoodBankService.instance.readBank()),
encode: encodeFoodBankForPush,
decode: parseRemoteFoodBank,
@ -102,6 +114,7 @@ Future<void> _syncManualBank(RemoteStore client) async {
deviceId: currentSyncDeviceId,
legacyDeviceId: legacySyncDeviceId,
pathPrefix: _devicesDir,
revsPath: syncRevsDir,
localLog: manualBankToLog(local),
encode: encodeManualBankForPush,
decode: parseRemoteManualBank,
@ -118,6 +131,7 @@ Future<void> _syncBudget(RemoteStore client) async {
deviceId: currentSyncDeviceId,
legacyDeviceId: legacySyncDeviceId,
pathPrefix: _devicesDir,
revsPath: syncRevsDir,
localLog: localBudgetLog(),
encode: encodeBudgetForPush,
decode: parseRemoteBudget,
@ -149,8 +163,7 @@ Future<void> _syncExportKeys(RemoteStore client) async {
///
/// The phone runs its own catering importer, so it cannot fetch anything until
/// the panel password reaches it -- that is the whole reason this credential
/// syncs at all. It is plaintext on the wire, like the rest of the synced
/// state; see `sync_merge_kuchnia.dart`.
/// syncs at all. Sealed end-to-end like the rest of the synced state.
///
/// A device that has no credential contributes an empty log, so it neither
/// blocks nor clobbers a peer's real value -- it relays it. Mirrors
@ -162,6 +175,7 @@ Future<void> _syncKuchniaCredential(RemoteStore client) async {
deviceId: currentSyncDeviceId,
legacyDeviceId: legacySyncDeviceId,
pathPrefix: _devicesDir,
revsPath: syncRevsDir,
localLog: credentialToLog(
KuchniaCredentialService.username,
KuchniaCredentialService.password,

View File

@ -1,7 +1,8 @@
/// Morning weigh-ins from the wake-alarm app, as Body weight candidates.
///
/// The wake-alarm phone app publishes
/// `wake-alarm-sync/devices/<id>/alarm.json`: a crdt_sync Log whose
/// `wake-alarm-sync/devices-e2e/<id>/alarm.json` (end-to-end encrypted, read
/// through wake-alarm's own `EncryptingStore`): a crdt_sync Log whose
/// `alarm` record carries `fields[name] = [value, hlc]`. Two fields hold
/// weights:
///
@ -25,7 +26,7 @@ import 'package:diet_guard_app/services/body_service.dart';
import 'package:diet_guard_app/services/sync_merge_body.dart';
/// Where the wake-alarm app publishes, one directory per device.
const wakeAlarmDevicesDir = 'wake-alarm-sync/devices';
const wakeAlarmDevicesDir = 'wake-alarm-sync/devices-e2e';
const _latestField = 'latest_weight_kg';
const _sessionsField = 'morning_sessions';

View File

@ -5,10 +5,10 @@ packages:
dependency: transitive
description:
name: android_file_picker
sha256: "868183c959e754e915954d8074c20cfa4cfdb4684b35ecc08378437be1a542d8"
sha256: "04c1306eda42c23ecbf449c909f4fa05c5e66fc48cf5f994d8d08b9d45e5396b"
url: "https://pub.dev"
source: hosted
version: "2.1.3"
version: "2.1.5"
archive:
dependency: transitive
description:
@ -157,11 +157,20 @@ packages:
dependency: "direct main"
description:
path: crdt_sync_dart
ref: "crdt_sync_dart-v0.12.1"
resolved-ref: "6641d85f0550ca60433fc8e0d13a3dafdbb664d6"
ref: "crdt_sync_dart-v0.14.1"
resolved-ref: edd0f7a7882cb1d3904932ba94faa282d08165df
url: "https://github.com/kuhyx/utils"
source: git
version: "0.12.1"
version: "0.14.1"
crdt_sync_flutter:
dependency: "direct main"
description:
path: crdt_sync_flutter
ref: "crdt_sync_flutter-v0.8.1"
resolved-ref: "3225af8365481677d61a8cabec0c0ad4d0407567"
url: "https://github.com/kuhyx/utils"
source: git
version: "0.8.1"
cross_file:
dependency: transitive
description:
@ -190,11 +199,11 @@ packages:
dependency: "direct main"
description:
path: data_transfer_flutter
ref: "data_transfer_flutter-v0.2.1"
resolved-ref: d4fca83c9f2ed33b3315cd838b9ca532ae8e559c
ref: "data_transfer_flutter-v0.2.2"
resolved-ref: eef7af4c86837ee82891493587ff3456297e5dea
url: "https://github.com/kuhyx/utils"
source: git
version: "0.2.1"
version: "0.2.2"
dbus:
dependency: transitive
description:
@ -263,10 +272,10 @@ packages:
dependency: transitive
description:
name: file_picker
sha256: c64036857780d7125f011d543f89eedcb5df61da473668bace4eee9ab875284d
sha256: "079dc46b753abbddb7f77cd87e6ed9ecc62902580707514568321bdf8e050a86"
url: "https://pub.dev"
source: hosted
version: "13.3.2"
version: "13.3.3"
file_picker_darwin:
dependency: transitive
description:
@ -279,10 +288,10 @@ packages:
dependency: transitive
description:
name: file_picker_linux
sha256: c6562fc7d426db2fb85ea66fe2627953d2709932df5584ceaacf0aa5e39cf4da
sha256: "9215ee8c672508cdd9a325202669f849e1baac883658626b3abed5d7777e6a4b"
url: "https://pub.dev"
source: hosted
version: "2.0.2"
version: "2.0.4"
file_picker_platform_interface:
dependency: transitive
description:
@ -295,10 +304,10 @@ packages:
dependency: transitive
description:
name: file_picker_web
sha256: a2288008280aabe371aff029466b3405e60838e0a1d714767488c59b926c8b8c
sha256: "50749a6da2984fc29609e102ad4d80fd1d07e6895150f8e4922086167d9d45d8"
url: "https://pub.dev"
source: hosted
version: "4.2.0"
version: "4.2.1"
file_selector:
dependency: transitive
description:
@ -494,11 +503,11 @@ packages:
dependency: "direct main"
description:
path: github_device_auth
ref: "github_device_auth-v0.3.2"
resolved-ref: "4ccaba1bb3e495ef72d70c6a7e7d7ec98d755792"
ref: "github_device_auth-v0.4.0"
resolved-ref: "3084080d744c348a217727e26a6be838e7d5a4ff"
url: "https://github.com/kuhyx/utils"
source: git
version: "0.3.2"
version: "0.4.0"
google_account_token:
dependency: "direct main"
description:
@ -941,11 +950,11 @@ packages:
dependency: "direct main"
description:
path: sync_settings_ui
ref: "sync_settings_ui-v0.6.2"
resolved-ref: "95cd3731ede686114353d32ae6c286ad1694b488"
ref: "sync_settings_ui-v0.7.3"
resolved-ref: "02d9d689e921d80ec155af9903164c3d2d259dce"
url: "https://github.com/kuhyx/utils"
source: git
version: "0.6.2"
version: "0.7.3"
synchronized:
dependency: transitive
description:
@ -1110,10 +1119,10 @@ packages:
dependency: transitive
description:
name: windows_file_picker
sha256: "18452aa293de3b6961c6d05b0e71b4be7bb90c67635abdd3aa5c4e75dd875072"
sha256: cd1be37ada0abcfaa55bddb7410e8515844e35cd77669c35d9a28a15722299d8
url: "https://pub.dev"
source: hosted
version: "2.0.1"
version: "2.0.2"
workmanager:
dependency: "direct main"
description:

View File

@ -2,7 +2,7 @@ name: diet_guard_app
description: "Companion phone app for diet_guard: log meals on the go."
publish_to: 'none'
version: 1.0.155+1
version: 1.0.157+1
environment:
sdk: ^3.12.2
@ -12,8 +12,14 @@ dependencies:
crdt_sync:
git:
url: https://github.com/kuhyx/utils
ref: crdt_sync_dart-v0.12.1
ref: crdt_sync_dart-v0.14.1
path: crdt_sync_dart
# Keystore-backed end-to-end encryption open + the passphrase lock button.
crdt_sync_flutter:
git:
url: https://github.com/kuhyx/utils
ref: crdt_sync_flutter-v0.8.1
path: crdt_sync_flutter
crypto: 3.0.8
cryptography: 2.9.0
@ -21,7 +27,7 @@ dependencies:
data_transfer_flutter:
git:
url: https://github.com/kuhyx/utils
ref: data_transfer_flutter-v0.2.1
ref: data_transfer_flutter-v0.2.2
path: data_transfer_flutter
fl_chart: 1.3.1
flutter:
@ -34,7 +40,7 @@ dependencies:
github_device_auth:
git:
url: https://github.com/kuhyx/utils
ref: github_device_auth-v0.3.2
ref: github_device_auth-v0.4.0
path: github_device_auth
# One-tap Google ID token via the framework AccountManager chooser (FOSS).
google_account_token:
@ -57,7 +63,7 @@ dependencies:
sync_settings_ui:
git:
url: https://github.com/kuhyx/utils
ref: sync_settings_ui-v0.6.2
ref: sync_settings_ui-v0.7.3
path: sync_settings_ui
url_launcher: 6.3.3
uuid: 4.6.0

View File

@ -0,0 +1,35 @@
/// A GitHub stand-in that persists the end-to-end encryption header, which
/// the sync service writes and re-reads; every other request goes to [inner].
library;
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
/// Wraps [inner] so `…/e2e` PUTs are stored and served back on GET.
MockClient e2eMock(Future<http.Response> Function(http.Request) inner) {
String? header;
return MockClient((request) async {
if (request.url.path.endsWith('/e2e.json')) {
// Firebase REST: the value is a JSON-encoded string.
if (request.method == 'PUT') {
header = jsonDecode(request.body) as String;
return http.Response(request.body, 200);
}
return http.Response(jsonEncode(header), 200);
}
if (!request.url.path.endsWith('/e2e')) return inner(request);
if (request.method == 'PUT') {
final body = jsonDecode(request.body) as Map<String, dynamic>;
header = utf8.decode(base64.decode(body['content'] as String));
return http.Response(jsonEncode({'content': {}, 'sha': 'h'}), 200);
}
final text = header;
if (text == null) return http.Response('', 404);
return http.Response(
jsonEncode({'content': base64.encode(utf8.encode(text)), 'sha': 'h'}),
200,
);
});
}

View File

@ -1,3 +1,5 @@
import 'package:crdt_sync/crdt_sync.dart' show Argon2Params, resetE2eCopyMemo;
import 'package:diet_guard_app/services/sync_e2e.dart' show e2eArgon2Params;
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
@ -12,10 +14,19 @@ void installFakeSecureStorage({
Map<String, String>? initial,
bool throwing = false,
}) {
const channel = MethodChannel(
'plugins.it_nomads.com/flutter_secure_storage',
const channel = MethodChannel('plugins.it_nomads.com/flutter_secure_storage');
resetE2eCopyMemo();
e2eArgon2Params = const Argon2Params(
memoryKiB: 8,
iterations: 1,
parallelism: 1,
);
final store = <String, String>{...?initial};
// Sync is end-to-end encrypted, so a device with no passphrase is locked;
// tests that sync start with one unless they pass their own `initial`.
final store = <String, String>{
'crdt_sync_e2e_passphrase': 'test-passphrase',
...?initial,
};
final messenger =
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;

View File

@ -17,6 +17,7 @@ import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher_platform_interface/link.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import '../e2e_github_header.dart';
import '../fake_secure_storage.dart';
import '../label_finders.dart';
@ -96,7 +97,7 @@ void main() {
testWidgets('device flow happy path saves the token and syncs', (
tester,
) async {
final mock = MockClient((req) async {
final mock = e2eMock((req) async {
if (req.url.path.contains('device/code')) {
return http.Response(
jsonEncode({
@ -150,7 +151,7 @@ void main() {
testWidgets('device flow connects but surfaces a post-connect sync failure', (
tester,
) async {
final mock = MockClient((req) async {
final mock = e2eMock((req) async {
if (req.url.path.contains('device/code')) {
return http.Response(
jsonEncode({

View File

@ -144,19 +144,21 @@ void main() {
);
expect(find.text('WXYZ-1234'), findsOneWidget);
await pumpUntil(
tester,
() => find.textContaining('access_denied').evaluate().isNotEmpty,
);
await pumpUntil(tester, () => _errorIcon().evaluate().isNotEmpty);
expect(find.textContaining('access_denied'), findsOneWidget);
expect(_errorIcon(), findsOneWidget);
await tester.tap(find.text('Open GitHub & copy code'));
await tester.tap(byIconLabel('Open GitHub & copy code'));
await tester.pump();
expect(launcher.launched, 'https://github.com/login/device');
await tester.tap(find.text('Cancel'));
await tester.tap(byIconLabel('Cancel'));
await settle(tester);
});
});
}
/// The dialog's error glyph, whose spoken label carries GitHub's error.
Finder _errorIcon() => find.byWidgetPredicate(
(w) => w is Icon && (w.semanticLabel ?? '').contains('access_denied'),
);

View File

@ -17,6 +17,7 @@ import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher_platform_interface/link.dart';
import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart';
import '../e2e_github_header.dart';
import '../fake_secure_storage.dart';
import '../label_finders.dart';
@ -120,7 +121,7 @@ void main() {
});
});
testWidgets('Test connection reports success', (tester) async {
final mock = MockClient((_) async => http.Response('{}', 200));
final mock = e2eMock((_) async => http.Response('{}', 200));
await tester.runAsync(() async {
await tester.pumpWidget(
MaterialApp(home: GitHubMirrorScreen(httpClient: mock)),
@ -134,7 +135,7 @@ void main() {
});
});
testWidgets('Test connection reports failure', (tester) async {
final mock = MockClient((_) async => http.Response('', 403));
final mock = e2eMock((_) async => http.Response('', 403));
await tester.runAsync(() async {
await tester.pumpWidget(
MaterialApp(home: GitHubMirrorScreen(httpClient: mock)),
@ -148,7 +149,7 @@ void main() {
});
});
testWidgets('Sync now runs a sync tick and reports success', (tester) async {
final mock = MockClient((req) async {
final mock = e2eMock((req) async {
if (req.method == 'PUT') return http.Response('{}', 200);
// A bare `/repos/<owner>/<repo>` GET is crdt_sync's GitHubClient
// probing whether the repo itself exists (vs. a content path just
@ -182,7 +183,7 @@ void main() {
await SyncHealth.recordFailure();
expect((await SyncHealth.read()).failureKind, SyncFailureKind.failed);
final mock = MockClient((req) async {
final mock = e2eMock((req) async {
if (req.method == 'PUT') return http.Response('{}', 200);
if (req.method == 'GET' && req.url.pathSegments.length == 3) {
return http.Response('{}', 200);

View File

@ -14,6 +14,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sync_settings_ui/sync_settings_ui.dart' show SyncSettingsScreen;
import '../fake_secure_storage.dart';
import '../label_finders.dart';
@ -179,7 +180,7 @@ void main() {
await tester.tap(byIconLabel('Sync settings'));
await settle(tester);
expect(find.text('Firebase sync'), findsOneWidget);
expect(find.byType(SyncSettingsScreen), findsOneWidget);
});
});
testWidgets('Sync settings wires storedAccount, not loadAccount, as the '
@ -206,7 +207,7 @@ void main() {
await settle(tester);
expect(find.text('sync@example.com'), findsOneWidget);
expect(find.text('Disconnect'), findsOneWidget);
expect(byIconLabel('Disconnect'), findsOneWidget);
});
});
testWidgets(

View File

@ -20,6 +20,7 @@ import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../e2e_github_header.dart';
import '../fake_secure_storage.dart';
void main() {
@ -55,7 +56,7 @@ void main() {
SharedPreferences.setMockInitialValues({});
installFakeSecureStorage();
var puts = 0;
final mock = MockClient((req) async {
final mock = e2eMock((req) async {
if (req.method == 'PUT') puts++;
return http.Response('', 404);
});
@ -73,7 +74,7 @@ void main() {
});
installFakeSecureStorage(initial: {'sync.token': 't'});
var puts = 0;
final mock = MockClient((req) async {
final mock = e2eMock((req) async {
if (req.method == 'PUT') {
puts++;
return http.Response('{}', 200); // Contents-API PUT succeeded
@ -112,7 +113,7 @@ void main() {
resetSyncDeviceIdForTest();
installFakeSecureStorage(initial: {'sync.token': 't'});
final pushedPaths = <String>[];
final mock = MockClient((req) async {
final mock = e2eMock((req) async {
if (req.method == 'PUT') {
pushedPaths.add(req.url.path);
return http.Response('{}', 200);

View File

@ -26,6 +26,7 @@ import 'package:http/testing.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../fake_notifications.dart';
import '../e2e_github_header.dart';
import '../fake_secure_storage.dart';
const _manual = Nutrition(
@ -135,7 +136,7 @@ void main() {
});
installFakeSecureStorage(initial: {'sync.token': 't'});
var requests = 0;
final mock = MockClient((req) async {
final mock = e2eMock((req) async {
requests++;
return http.Response('', 404);
});
@ -157,7 +158,7 @@ void main() {
});
installFakeSecureStorage(initial: {'sync.token': 't'});
var requests = 0;
final mock = MockClient((req) async {
final mock = e2eMock((req) async {
requests++;
return http.Response('', 404);
});
@ -195,15 +196,15 @@ void main() {
'"source":"manual","slot":12,"day":"$day"},'
'"${day}T11:30:00.000Z-0000-pc"]},"deleted":false,'
'"deleted_hlc":null}}';
final mock = MockClient((req) async {
final mock = e2eMock((req) async {
if (req.method == 'PUT') return http.Response('{}', 200);
if (req.method == 'GET' && req.url.pathSegments.length == 3) {
return http.Response('{}', 200);
}
if (req.url.path.endsWith('/devices')) {
if (req.url.path.endsWith('/devices-e2e')) {
return http.Response('[{"name":"pc","type":"dir"}]', 200);
}
if (req.url.path.endsWith('/devices/pc/food_log.json')) {
if (req.url.path.endsWith('/devices-e2e/pc/food_log.json')) {
// The Contents API returns base64 in a `content` field, not raw JSON.
return http.Response(
jsonEncode({'content': base64.encode(utf8.encode(remote))}),

View File

@ -9,7 +9,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'body_test_support.dart';
const _dir = 'diet-guard-sync/devices';
const _dir = 'diet-guard-sync/devices-e2e';
void main() {
tearDown(BodyService.resetForTesting);
@ -39,7 +39,7 @@ void main() {
);
final remote = MemoryRemote({
'$_dir/pc-uuid/body.json': encodeBodyForPush(bodyToLog(peer)),
'wake-alarm-sync/devices/phone/alarm.json': jsonEncode({
'wake-alarm-sync/devices-e2e/phone/alarm.json': jsonEncode({
'alarm': {
'fields': {
'morning_sessions': [
@ -53,7 +53,7 @@ void main() {
}),
});
await syncBody(remote, devicesDir: _dir);
await syncBody(remote, devicesDir: _dir, wakeAlarm: remote);
final body = BodyService.instance;
expect(body.birth, '1995-03-01');

View File

@ -0,0 +1,165 @@
// End-to-end encryption of the diet_guard sync tick (`sync_e2e.dart`).
//
// The fake GitHub stores what is PUT, so the header written on first use
// reads back and the sealed blobs are the bytes a real backend would hold.
import 'dart:convert';
import 'dart:io';
import 'package:crdt_sync/crdt_sync.dart' show E2eLockReason, RemoteStore;
import 'package:diet_guard_app/services/app_settings_service.dart';
import 'package:diet_guard_app/services/budget_history_service.dart';
import 'package:diet_guard_app/services/document_store_io.dart';
import 'package:diet_guard_app/services/export_keyring_default.dart';
import 'package:diet_guard_app/services/foodbank_service.dart';
import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/sync_e2e.dart';
import 'package:diet_guard_app/services/sync_merge.dart';
import 'package:diet_guard_app/services/sync_service.dart';
import 'package:flutter_test/flutter_test.dart';
import '../fake_secure_storage.dart';
import 'sync_service_test_support.dart';
const _new = 'diet-guard-sync/devices-e2e';
const _old = 'diet-guard-sync/devices';
String _text(Map<String, dynamic> put) =>
utf8.decode(base64.decode(put['content'] as String));
void main() {
late Directory tempDir;
setUp(() async {
TestWidgetsFlutterBinding.ensureInitialized();
installFakeSecureStorage();
tempDir = await Directory.systemTemp.createTemp('diet_guard_e2e_test_');
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
BudgetHistoryService.resetForTesting(store: FileDocumentStore(tempDir));
});
tearDown(() async {
LogStorageService.resetForTesting();
FoodBankService.resetForTesting();
AppSettingsService.resetForTesting();
BudgetHistoryService.resetForTesting();
await tempDir.delete(recursive: true);
});
test('the pushed food log holds no plaintext field', () async {
await LogStorageService.instance.logMeal('secret oatmeal', manualNutrition);
final fake = FakeGitHub();
await runSync(fake.buildClient());
final blob = _text(fake.putsByPath['$_new/phone/food_log.json']!);
expect(blob, isNot(contains('secret')));
expect(blob, isNot(contains('"fields"')));
expect(blob, isNot(contains('kcal')));
expect(await fake.opened('$_new/phone/food_log.json'), contains('secret'));
});
test('nothing is written to the old plaintext prefix or revs', () async {
await LogStorageService.instance.logMeal('oatmeal', manualNutrition);
final fake = FakeGitHub();
await runSync(fake.buildClient());
expect(fake.putsByPath, isNotEmpty);
for (final path in fake.putsByPath.keys) {
expect(path, isNot(startsWith('$_old/')));
expect(path, isNot(startsWith('diet-guard-sync/revs/')));
}
expect(fake.putsByPath, contains('diet-guard-sync/revs-e2e/phone'));
});
test('export keys are pushed sealed, never to the old node', () async {
await defaultKeyring().ensureNewest();
final fake = FakeGitHub();
await runSync(fake.buildClient());
final sealed = fake.putsByPath['$_new/phone/export_keys.json'];
expect(sealed, isNotNull);
final opened = (await fake.opened('$_new/phone/export_keys.json'))!;
final record = (jsonDecode(opened) as Map).values.single as Map;
final keyB64 = ((record['fields'] as Map)['k'] as List).first as String;
expect(_text(sealed!), isNot(contains(keyB64)));
expect(fake.putsByPath, isNot(contains('$_old/phone/export_keys.json')));
});
test('an old plaintext peer log is copied, merged, and left alone', () async {
await LogStorageService.instance.logMeal('peer porridge', manualNutrition);
final local = await LogStorageService.instance.readLog();
final peerLog = encodeLogForPush(dayLogToLog(local));
await LogStorageService.instance.writeLog(const {});
final fake = FakeGitHub(
deviceDirs: const ['pc'],
files: {'$_old/pc/food_log.json': peerLog},
);
final merged = await runSync(fake.buildClient());
final descs = merged.values.expand((e) => e).map((e) => e.desc);
expect(descs, contains('peer porridge'));
expect(
_text(fake.putsByPath['$_new/pc/food_log.json']!),
isNot(contains('porridge')),
);
expect(fake.files['$_old/pc/food_log.json'], peerLog);
});
test('no passphrase: locked, nothing read or written', () async {
installFakeSecureStorage(initial: const {'crdt_sync_e2e_passphrase': ''});
final fake = FakeGitHub();
await expectLater(
runSync(fake.buildClient()),
throwsA(isA<SyncLockedException>()),
);
expect(fake.puts, isEmpty);
expect(syncLocked.value, isTrue);
expect(
const SyncLockedException(E2eLockReason.wrongKey).toString(),
contains('wrongKey'),
);
});
test('a wake-alarm transport failure skips only the weigh-ins', () async {
await LogStorageService.instance.logMeal('oatmeal', manualNutrition);
final fake = FakeGitHub();
final store = _FailingPath(fake.buildClient(), 'wake-alarm-sync/e2e');
await runSync(store);
expect(fake.putsByPath, contains('$_new/phone/food_log.json'));
expect(await openWakeAlarmStore(store), isNull);
});
}
/// Delegates to [inner] but fails every read of [path].
class _FailingPath implements RemoteStore {
_FailingPath(this.inner, this.path);
final RemoteStore inner;
final String path;
@override
Future<String?> getFileText(String p) =>
p == path ? Future.error(Exception('down')) : inner.getFileText(p);
@override
Future<List<String>> listDirectory(String p) => inner.listDirectory(p);
@override
Future<void> putFileText(String p, String text, {required String message}) =>
inner.putFileText(p, text, message: message);
@override
Future<void> deleteFile(String p, {String message = ''}) =>
inner.deleteFile(p, message: message);
@override
Future<bool> canAccessRemote() => inner.canAccessRemote();
@override
void close() => inner.close();
}

View File

@ -14,20 +14,20 @@ import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/sync_service.dart';
import 'package:flutter_test/flutter_test.dart';
import '../fake_secure_storage.dart';
import 'sync_service_test_support.dart';
void main() {
late Directory tempDir;
setUp(() async {
TestWidgetsFlutterBinding.ensureInitialized();
installFakeSecureStorage();
tempDir = await Directory.systemTemp.createTemp('diet_guard_sync_test_');
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
BudgetHistoryService.resetForTesting(
store: FileDocumentStore(tempDir),
);
BudgetHistoryService.resetForTesting(store: FileDocumentStore(tempDir));
});
tearDown(() async {
@ -39,30 +39,24 @@ void main() {
});
group('budget sync', () {
test(
'pushes the local budget when no other devices have synced',
() async {
await AppSettingsService.instance.saveDailyKcalGoal(2000);
final fake = FakeGitHub();
await runSync(fake.buildClient());
test('pushes the local budget when no other devices have synced', () async {
await AppSettingsService.instance.saveDailyKcalGoal(2000);
final fake = FakeGitHub();
await runSync(fake.buildClient());
expect(
fake.putsByPath.containsKey(
'diet-guard-sync/devices/phone/budget.json',
),
isTrue,
);
},
);
expect(
fake.putsByPath.containsKey(
'diet-guard-sync/devices-e2e/phone/budget.json',
),
isTrue,
);
});
test('remote-only budget is adopted locally', () async {
final remoteJson = remoteBudgetJson(
kcal: 1800,
t: '2026-01-01T09:00:00',
);
final remoteJson = remoteBudgetJson(kcal: 1800, t: '2026-01-01T09:00:00');
final fake = FakeGitHub(
deviceDirs: const ['pc'],
files: {'diet-guard-sync/devices/pc/budget.json': remoteJson},
files: {'diet-guard-sync/devices-e2e/pc/budget.json': remoteJson},
);
await runSync(fake.buildClient());
expect(AppSettingsService.dailyKcalGoal, 1800);
@ -70,13 +64,10 @@ void main() {
test('a local edit later than a remote edit wins', () async {
await AppSettingsService.instance.saveDailyKcalGoal(1500); // now
final remoteJson = remoteBudgetJson(
kcal: 1800,
t: '2020-01-01T09:00:00',
);
final remoteJson = remoteBudgetJson(kcal: 1800, t: '2020-01-01T09:00:00');
final fake = FakeGitHub(
deviceDirs: const ['pc'],
files: {'diet-guard-sync/devices/pc/budget.json': remoteJson},
files: {'diet-guard-sync/devices-e2e/pc/budget.json': remoteJson},
);
await runSync(fake.buildClient());
expect(AppSettingsService.dailyKcalGoal, 1500);
@ -84,13 +75,10 @@ void main() {
test('a remote edit later than a local edit wins', () async {
await AppSettingsService.instance.saveDailyKcalGoal(1500); // now
final remoteJson = remoteBudgetJson(
kcal: 1800,
t: '2999-01-01T09:00:00',
);
final remoteJson = remoteBudgetJson(kcal: 1800, t: '2999-01-01T09:00:00');
final fake = FakeGitHub(
deviceDirs: const ['pc'],
files: {'diet-guard-sync/devices/pc/budget.json': remoteJson},
files: {'diet-guard-sync/devices-e2e/pc/budget.json': remoteJson},
);
await runSync(fake.buildClient());
expect(AppSettingsService.dailyKcalGoal, 1800);
@ -101,7 +89,7 @@ void main() {
final fake = FakeGitHub(
deviceDirs: const ['pc'],
files: const {
'diet-guard-sync/devices/pc/budget.json': '{not valid json',
'diet-guard-sync/devices-e2e/pc/budget.json': '{not valid json',
},
);
await runSync(fake.buildClient());
@ -114,11 +102,9 @@ void main() {
final fake = FakeGitHub();
await runSync(fake.buildClient());
final pushed =
fake.putsByPath['diet-guard-sync/devices/phone/budget.json']!;
final pushedText = utf8.decode(
base64.decode(pushed['content'] as String),
);
final pushedText = (await fake.opened(
'diet-guard-sync/devices-e2e/phone/budget.json',
))!;
expect(jsonDecode(pushedText), isEmpty);
expect(AppSettingsService.dailyKcalGoal, 2200);
},

View File

@ -16,20 +16,20 @@ import 'package:diet_guard_app/services/log_storage_service.dart';
import 'package:diet_guard_app/services/sync_service.dart';
import 'package:flutter_test/flutter_test.dart';
import '../fake_secure_storage.dart';
import 'sync_service_test_support.dart';
void main() {
late Directory tempDir;
setUp(() async {
TestWidgetsFlutterBinding.ensureInitialized();
installFakeSecureStorage();
tempDir = await Directory.systemTemp.createTemp('diet_guard_sync_test_');
LogStorageService.resetForTesting(store: FileDocumentStore(tempDir));
FoodBankService.resetForTesting(store: FileDocumentStore(tempDir));
await AppSettingsService.initForTesting(FileDocumentStore(tempDir));
BudgetHistoryService.resetForTesting(
store: FileDocumentStore(tempDir),
);
BudgetHistoryService.resetForTesting(store: FileDocumentStore(tempDir));
});
tearDown(() async {
@ -49,24 +49,32 @@ void main() {
// syncLog always pushes, even an empty merged result: food_log.json,
// budget.json, food_bank.json, food_bank_manual.json -- plus this
// device's revision, published after the log so a peer can never cache
// "seen rev X" against a log it never received.
expect(fake.puts, hasLength(5));
// "seen rev X" against a log it never received. Then export_keys.json,
// and the two encryption headers (diet_guard's and wake-alarm's).
expect(
fake.putsByPath.keys.where((p) => !p.endsWith('/e2e')),
hasLength(6),
);
expect(fake.puts, hasLength(8));
});
test("skips its own device id ('phone') when listing", () async {
final fake = FakeGitHub(
deviceDirs: const ['pc', 'phone'],
files: const {
'diet-guard-sync/devices/pc/food_log.json': '{}',
'diet-guard-sync/devices/pc/budget.json': '{}',
'diet-guard-sync/devices-e2e/pc/food_log.json': '{}',
'diet-guard-sync/devices-e2e/pc/budget.json': '{}',
},
);
await runSync(fake.buildClient());
// Both the food-log and budget pulls skip "phone" (this device) and
// only ever read "pc"'s files.
expect(fake.fileGets, [
'diet-guard-sync/devices/pc/food_log.json',
'diet-guard-sync/devices/pc/budget.json',
]);
expect(
fake.fileGets.where((p) => p.startsWith('diet-guard-sync/devices-e2e/')),
[
'diet-guard-sync/devices-e2e/pc/food_log.json',
'diet-guard-sync/devices-e2e/pc/budget.json',
],
);
});
test('skips a device with no pushed file yet', () async {
final fake = FakeGitHub(deviceDirs: const ['pc']);
@ -76,7 +84,7 @@ void main() {
test('ignores a device whose pushed file is not a JSON object', () async {
final fake = FakeGitHub(
deviceDirs: const ['pc'],
files: const {'diet-guard-sync/devices/pc/food_log.json': '[]'},
files: const {'diet-guard-sync/devices-e2e/pc/food_log.json': '[]'},
);
final merged = await runSync(fake.buildClient());
expect(merged, isEmpty);
@ -85,7 +93,7 @@ void main() {
final fake = FakeGitHub(
deviceDirs: const ['pc'],
files: const {
'diet-guard-sync/devices/pc/food_log.json': '{not valid json',
'diet-guard-sync/devices-e2e/pc/food_log.json': '{not valid json',
},
);
final merged = await runSync(fake.buildClient());
@ -111,7 +119,7 @@ void main() {
});
final fake = FakeGitHub(
deviceDirs: const ['pc'],
files: {'diet-guard-sync/devices/pc/food_log.json': remoteLog},
files: {'diet-guard-sync/devices-e2e/pc/food_log.json': remoteLog},
);
final merged = await runSync(fake.buildClient());
final descs = merged.values.expand((e) => e).map((e) => e.desc).toSet();
@ -145,7 +153,7 @@ void main() {
});
final fake = FakeGitHub(
deviceDirs: const ['pc'],
files: {'diet-guard-sync/devices/pc/food_log.json': remoteLog},
files: {'diet-guard-sync/devices-e2e/pc/food_log.json': remoteLog},
);
final merged = await runSync(fake.buildClient());
final descs = merged.values.expand((e) => e).map((e) => e.desc).toSet();
@ -161,16 +169,13 @@ void main() {
expect(bank.containsKey('oatmeal'), isTrue);
});
test('pushes a payload without hmac', () async {
await LogStorageService.instance.logMeal(
'oatmeal',
manualNutrition,
);
await LogStorageService.instance.logMeal('oatmeal', manualNutrition);
final fake = FakeGitHub();
await runSync(fake.buildClient());
final pushed =
fake.putsByPath['diet-guard-sync/devices/phone/food_log.json']!;
final pushedText = utf8.decode(base64.decode(pushed['content'] as String));
final pushedText = (await fake.opened(
'diet-guard-sync/devices-e2e/phone/food_log.json',
))!;
expect(pushedText, isNot(contains('hmac')));
});
test('pushes in the new Record-based wire format', () async {
@ -178,9 +183,9 @@ void main() {
final fake = FakeGitHub();
await runSync(fake.buildClient());
final pushed =
fake.putsByPath['diet-guard-sync/devices/phone/food_log.json']!;
final pushedText = utf8.decode(base64.decode(pushed['content'] as String));
final pushedText = (await fake.opened(
'diet-guard-sync/devices-e2e/phone/food_log.json',
))!;
final decoded = jsonDecode(pushedText) as Map<String, dynamic>;
final record = decoded.values.single as Map<String, dynamic>;
expect(record, containsPair('id', isA<String>()));
@ -188,11 +193,11 @@ void main() {
});
test("reuses this device's existing sha when it has pushed before", () async {
final fake = FakeGitHub(
files: const {'diet-guard-sync/devices/phone/food_log.json': '{}'},
files: const {'diet-guard-sync/devices-e2e/phone/food_log.json': '{}'},
);
await runSync(fake.buildClient());
expect(
fake.putsByPath['diet-guard-sync/devices/phone/food_log.json']!['sha'],
fake.putsByPath['diet-guard-sync/devices-e2e/phone/food_log.json']!['sha'],
'f-phone',
);
});

View File

@ -65,6 +65,41 @@ class FakeGitHub {
/// sync tick does both.
final Map<String, Map<String, dynamic>> putsByPath = {};
/// A directory listing for [path], or null when it is not a directory.
///
/// [deviceDirs] populate both the encrypted prefix and the old plaintext
/// one; any other directory is derived from [files].
List<Map<String, String>>? _list(String path) {
final names = <String>{
if (path == 'diet-guard-sync/devices-e2e' ||
path == 'diet-guard-sync/devices')
...deviceDirs,
for (final key in files.keys)
if (key.startsWith('$path/'))
key.substring(path.length + 1).split('/')[0],
};
if (names.isEmpty) return null;
return [
for (final name in names)
{
'type': files.containsKey('$path/$name') ? 'file' : 'dir',
'name': name,
'path': '$path/$name',
'sha': 'd-$name',
},
];
}
/// The opened (decrypted) text of what was pushed to [path].
Future<String?> opened(String path) async {
final state = await openEncryptedStore(
store: buildClient(),
oldPrefix: 'diet-guard-sync/devices',
readPassphrase: () async => 'test-passphrase',
);
return await (state as E2eReady).store.getFileText(path);
}
GitHubClient buildClient() => GitHubClient(
owner: 'o',
repo: 'r',
@ -84,22 +119,12 @@ class FakeGitHub {
final body = jsonDecode(req.body) as Map<String, dynamic>;
puts.add(body);
putsByPath[path] = body;
// Stored, so the encryption header (and anything sealed) reads back.
files[path] = utf8.decode(base64.decode(body['content'] as String));
return http.Response('{}', 200);
}
if (path == 'diet-guard-sync/devices') {
return http.Response(
jsonEncode([
for (final d in deviceDirs)
{
'type': 'dir',
'name': d,
'path': 'diet-guard-sync/devices/$d',
'sha': 'd-$d',
},
]),
200,
);
}
final listing = _list(path);
if (listing != null) return http.Response(jsonEncode(listing), 200);
if (!files.containsKey(path)) return http.Response('', 404);
fileGets.add(path);
final content = base64.encode(utf8.encode(files[path]!));
@ -110,12 +135,9 @@ class FakeGitHub {
final sha =
segments.length == 4 &&
segments[0] == 'diet-guard-sync' &&
segments[1] == 'devices'
segments[1] == 'devices-e2e'
? 'f-${segments[2]}'
: null;
return http.Response(
jsonEncode({'content': content, 'sha': ?sha}),
200,
);
return http.Response(jsonEncode({'content': content, 'sha': ?sha}), 200);
}
}

View File

@ -0,0 +1,11 @@
# Dependencies held below latest stable in this repo, and why. `transitive:`
# entries are predicates: they clear themselves when the blocker moves, so
# they carry no `expires`; everything else is discretionary and expires.
exceptions:
- ecosystem: toolchain
package: flutter
pinned: "3.47.9"
reason: local toolchain /opt/flutter is 3.47.9; fleet-wide Flutter 3.50 bump is separate work
blocked_by: local-toolchain
expires: "2026-11-26"

View File

@ -2,8 +2,9 @@
The wake-alarm phone app publishes ``latest_weight_kg`` and a short
``morning_sessions`` list on its own ``alarm.json`` in the shared Firebase
project. Reading it through diet_guard's *own* sync client -- paths are
absolute there -- means no import of ``wake_alarm`` and no second sign-in.
project, end-to-end encrypted under ``wake-alarm-sync/devices-e2e``. Reading
it over diet_guard's *own* backend -- paths are absolute there -- means no
import of ``wake_alarm`` and no second sign-in.
Stamping rules (``docs/DOCS-body.md``): ``latest_weight_kg`` carries its
field's Hlc time, so a re-typed weigh-in wins; ``morning_sessions`` entries
@ -21,16 +22,21 @@ import json
import logging
from typing import TYPE_CHECKING
from crdt_sync import Hlc, MirrorSyncClient, RemoteSyncError
from crdt_sync import E2eLockedError, Hlc, MirrorSyncClient, RemoteSyncError
from diet_guard._body_store import MAX_KG, MIN_KG, WeightCandidate, stamp_ms
from diet_guard._sync_e2e import (
LEGACY_WAKE_ALARM_DIR,
E2eStore,
open_e2e,
read_sealed,
)
if TYPE_CHECKING:
from crdt_sync import RemoteStore
_logger = logging.getLogger(__name__)
WAKE_ALARM_DEVICES_DIR = "wake-alarm-sync/devices"
_LATEST_FIELD = "latest_weight_kg"
_SESSIONS_FIELD = "morning_sessions"
# A crdt_sync field on the wire is ``[value, hlc]``.
@ -105,19 +111,25 @@ def weight_candidates(published: list[tuple[str, str]]) -> list[WeightCandidate]
def fetch_alarm_logs(client: RemoteStore) -> list[tuple[str, str]]:
"""Every wake-alarm device's raw ``alarm.json``; ``[]`` on any failure.
"""Every wake-alarm device's decrypted ``alarm.json``; ``[]`` on any failure.
Firebase-only (the primary of a mirror client): wake-alarm never
published weigh-ins to the GitHub mirror.
published weigh-ins to the GitHub mirror. wake-alarm's records are sealed
under their own header, so its store is opened over ``client``'s raw
backend; a locked or unreadable namespace skips the ingest, never the
diet sync around it.
"""
store = client.primary if isinstance(client, MirrorSyncClient) else client
raw = client.raw if isinstance(client, E2eStore) else client
primary = raw.primary if isinstance(raw, MirrorSyncClient) else raw
try:
store = open_e2e(primary, LEGACY_WAKE_ALARM_DIR)
prefix = store.layout.prefix
published = []
for device in store.list_directory(WAKE_ALARM_DEVICES_DIR):
text = store.get_file_text(f"{WAKE_ALARM_DEVICES_DIR}/{device}/alarm.json")
for device in store.list_directory(prefix):
text = read_sealed(store, f"{prefix}/{device}/alarm.json")
if text is not None:
published.append((device, text))
except RemoteSyncError as exc:
except (E2eLockedError, RemoteSyncError) as exc:
_logger.info("wake-alarm weigh-ins unreadable (%s); skipped", exc)
return []
return published

View File

@ -27,6 +27,9 @@ FOOD_LOG_FILE: Path = DATA_DIR / "food_log.json"
# peer's records are already merged into the local log, so state that outlived
# its log would skip peers whose data had been lost.
SYNC_STATE_FILE: Path = DATA_DIR / "sync_state.json"
# End-to-end encryption state kept between gate processes: the derived key
# (0600) and which old plaintext revisions were already copied under E2E.
E2E_STATE_DIR: Path = DATA_DIR / "e2e"
# The user's personal "food bank": every food they have logged before, with its
# full macros, keyed by name. This is the ONLY corpus the gate's autocomplete
# searches -- Open Food Facts is used to *fill* a new food's macros, never to

View File

@ -46,6 +46,7 @@ from diet_guard._state_sync import (
from diet_guard._sync_banks import _sync_budget, _sync_food_bank, _sync_manual_bank
from diet_guard._sync_body import sync_body
from diet_guard._sync_client import _client_for_run
from diet_guard._sync_e2e import read_sealed
from diet_guard._sync_errors import SyncError
from diet_guard._sync_kuchnia import _sync_kuchnia_credential
from diet_guard._sync_paths import _DEVICES_DIR, _REVS_DIR, _device_log_path
@ -119,7 +120,7 @@ def _pull_remote_logs(
# revision forward so it stays skipped next tick.
seen_revs[device_id] = remote_rev
continue
text = client.get_file_text(_device_log_path(device_id))
text = read_sealed(client, _device_log_path(device_id))
if text is None:
continue
try:

View File

@ -37,6 +37,7 @@ from diet_guard._meal_schedule_store import (
from diet_guard._meal_schedule_store import (
write_raw_history as write_raw_schedule,
)
from diet_guard._sync_e2e import E2eStore, read_sealed
from diet_guard._sync_paths import (
_device_budget_path,
_device_food_bank_path,
@ -91,7 +92,7 @@ def _sync_food_bank(client: GitHubSyncClient, device_ids: Sequence[str]) -> None
for device_id in device_ids:
if identity.is_own(device_id):
continue
text = client.get_file_text(_device_food_bank_path(device_id))
text = read_sealed(client, _device_food_bank_path(device_id))
if text is None:
continue
try:
@ -135,10 +136,15 @@ def _primary_only_text(client: GitHubSyncClient, path: str) -> str | None:
2 empty and **zero** non-empty. No curated food exists on the mirror alone,
so nothing is lost. A client with no ``primary`` (the GitHub-only case) is
read directly, which is the same backend either way.
Under E2E the client is an :class:`E2eStore`; its ``primary_only`` view
keeps the same narrowing with decryption in front of it.
"""
if isinstance(client, E2eStore):
return read_sealed(client.primary_only(), path)
if isinstance(client, MirrorSyncClient):
return client.primary.get_file_text(path)
return client.get_file_text(path)
return read_sealed(client.primary, path)
return read_sealed(client, path)
def _sync_manual_bank(client: GitHubSyncClient, device_ids: Sequence[str]) -> None:
@ -196,7 +202,7 @@ def _sync_budget(client: GitHubSyncClient, device_ids: Sequence[str]) -> None:
for device_id in device_ids:
if identity.is_own(device_id):
continue
text = client.get_file_text(_device_budget_path(device_id))
text = read_sealed(client, _device_budget_path(device_id))
if text is None:
continue
try:

View File

@ -22,6 +22,7 @@ from typing import TYPE_CHECKING
from crdt_sync import (
CONFIG_FILE,
ConfigError,
E2eLockedError,
FirebaseAuthError,
GitHubSyncClient,
RemoteSyncError,
@ -36,6 +37,7 @@ from diet_guard._constants import (
SYNC_TIMEOUT_SECONDS,
SYNC_TOKEN_FILE,
)
from diet_guard._sync_e2e import E2eStore, open_e2e
from diet_guard._sync_errors import SyncError
if TYPE_CHECKING:
@ -70,7 +72,26 @@ def _remote_client(github: GitHubSyncClient) -> RemoteStore:
return github
def _client_for_run() -> RemoteStore:
def _encrypted(raw: RemoteStore) -> E2eStore:
"""Wrap ``raw`` in end-to-end encryption, failing closed.
A locked store becomes a :class:`SyncError`, which every caller already
reports and survives -- the gate keeps its own lock decision -- and
nothing is ever pulled or pushed in plaintext.
"""
try:
return open_e2e(raw)
except E2eLockedError as exc:
message = f"sync locked (end-to-end encryption): {exc}"
raise SyncError(message) from exc
def _client_for_run() -> E2eStore:
"""Return the end-to-end encrypted store for one sync run."""
return _encrypted(_raw_client_for_run())
def _raw_client_for_run() -> RemoteStore:
"""Return the backend for one sync run, requiring only *one* to be set up.
The PAT is no longer mandatory. Firebase is the primary backend now, and
@ -155,13 +176,14 @@ def _apply_timeout(client: RemoteStore, seconds: float) -> None:
vars(target)["_timeout_seconds"] = seconds
def _client_for_interactive_run() -> RemoteStore:
def _client_for_interactive_run() -> E2eStore:
"""Return a sync client budgeted for a path the user is waiting on.
Same backends as :func:`_client_for_run`, but with
:data:`~diet_guard._constants.INTERACTIVE_TIMEOUT_SECONDS` in place of the
background tick's much longer budget.
"""
client = _client_for_run()
_apply_timeout(client, INTERACTIVE_TIMEOUT_SECONDS)
return client
raw = _raw_client_for_run()
# Tightened before the E2E open, which already makes requests.
_apply_timeout(raw, INTERACTIVE_TIMEOUT_SECONDS)
return _encrypted(raw)

123
diet_guard/_sync_e2e.py Normal file
View File

@ -0,0 +1,123 @@
"""End-to-end encryption of every payload this app syncs.
Every blob under ``diet-guard-sync/devices-e2e`` is sealed with a key derived
(Argon2id) from the shared crdt-sync passphrase in
``~/.config/crdt-sync/password``; Firebase and the GitHub mirror only ever see
record ids, tombstones and clocks. The wake-alarm weigh-ins this app reads
live on their own prefix (``wake-alarm-sync/devices-e2e``) with their own
header, hence a second store over the same raw backend.
Fail closed: no passphrase, a wrong one or an unreadable header raises
:class:`~crdt_sync.E2eLockedError` and nothing is pulled or pushed -- never a
plaintext fallback.
The old plaintext prefix is copied over (and never deleted) while a device
not yet migrated may still write it; see :func:`open_e2e` for when.
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from crdt_sync import (
PASSWORD_FILE,
E2eDecryptError,
E2eLayout,
E2eLockedError,
EncryptingStore,
MirrorSyncClient,
open_encrypted_client,
)
from diet_guard._constants import E2E_STATE_DIR
if TYPE_CHECKING:
from crdt_sync import Argon2Params, E2eKey, RemoteStore
_logger = logging.getLogger(__name__)
#: The plaintext prefix every pre-E2E build wrote; read only by the copy.
LEGACY_DEVICES_DIR = "diet-guard-sync/devices"
#: Where the wake-alarm app published before E2E.
LEGACY_WAKE_ALARM_DIR = "wake-alarm-sync/devices"
DIET_LAYOUT = E2eLayout.of(LEGACY_DEVICES_DIR)
WAKE_ALARM_LAYOUT = E2eLayout.of(LEGACY_WAKE_ALARM_DIR)
#: Argon2id cost for a header this device creates; None is the library's
#: default. Only tests lower it.
ARGON2_PARAMS: Argon2Params | None = None
class E2eStore(EncryptingStore):
"""An :class:`EncryptingStore` that remembers the backend it wraps.
The raw backend is what a second prefix (wake-alarm) is opened over, and
its Firebase half is what the primary-only reads go to.
"""
def __init__(self, raw: RemoteStore, key: E2eKey, layout: E2eLayout) -> None:
"""Wrap ``raw`` for ``layout``, sealing with ``key``."""
super().__init__(raw, key, layout)
self.raw = raw
self.layout = layout
def primary_only(self) -> EncryptingStore:
"""The same encryption over the Firebase half alone (no mirror)."""
raw = self.raw
inner = raw.primary if isinstance(raw, MirrorSyncClient) else raw
return EncryptingStore(inner, self.key, self.layout)
def _read_passphrase() -> str:
"""The shared crdt-sync passphrase, or "" when this machine has none."""
try:
return PASSWORD_FILE.read_text().strip()
except OSError:
return ""
def open_e2e(raw: RemoteStore, old_prefix: str = LEGACY_DEVICES_DIR) -> E2eStore:
"""Unlock ``old_prefix``'s encrypted twin over ``raw``.
diet_guard's own prefix keeps its derived key and copy memo in
:data:`E2E_STATE_DIR`, so a fresh gate process neither re-runs Argon2id
nor re-reads every old blob. The wake-alarm prefix does not: its phone
publishes no revisions, so a persisted memo would never see a phone not
yet migrated write a new alarm, and the copy reruns once per process.
Raises:
E2eLockedError: No passphrase, a wrong one, an unreadable header, or
a copy that met a blob it cannot open.
"""
# An empty passphrase still opens with diet_guard's cached key; without
# one the library raises E2eLockedError.
passphrase = _read_passphrase()
state_dir = E2E_STATE_DIR if old_prefix == LEGACY_DEVICES_DIR else None
try:
store, layout = open_encrypted_client(
raw,
old_prefix,
passphrase=passphrase,
params=ARGON2_PARAMS,
state_dir=state_dir,
)
except E2eDecryptError as exc:
raise E2eLockedError(str(exc)) from exc
return E2eStore(raw, store.key, layout)
def read_sealed(store: RemoteStore, path: str) -> str | None:
"""``store.get_file_text``, with an undecryptable blob treated as absent.
A peer sealed under another key, tampered with, or written by a newer
format is skipped (and so retried next tick), never fatal: one bad peer
must not stall the merge of every other one.
"""
try:
return store.get_file_text(path)
except E2eDecryptError as exc:
_logger.warning("e2e: skipping %s: %s", path, exc)
return None

View File

@ -29,6 +29,7 @@ from diet_guard._kuchnia_credential_store import (
write_synced_credential,
)
from diet_guard._kuchnia_errors import KuchniaError
from diet_guard._sync_e2e import read_sealed
from diet_guard._sync_paths import _device_kuchnia_path
from diet_guard.sync_merge import (
credential_to_log,
@ -116,7 +117,7 @@ def _sync_kuchnia_credential(
for device_id in device_ids:
if identity.is_own(device_id):
continue
text = client.get_file_text(_device_kuchnia_path(device_id))
text = read_sealed(client, _device_kuchnia_path(device_id))
if text is None:
continue
try:

View File

@ -12,11 +12,16 @@ constant; see :mod:`diet_guard._device`.
from __future__ import annotations
_DEVICES_DIR = "diet-guard-sync/devices"
from diet_guard._sync_e2e import DIET_LAYOUT
#: The end-to-end encrypted prefix (``diet-guard-sync/devices-e2e``); the old
#: plaintext ``diet-guard-sync/devices`` is only ever read, by the E2E copy.
_DEVICES_DIR = DIET_LAYOUT.prefix
#: Where per-device revision markers live, used to skip re-reading an
#: unchanged remote log.
_REVS_DIR = "diet-guard-sync/revs"
#: unchanged remote log. Keyed (HMAC) by the encrypting store, and kept out
#: of the old ``diet-guard-sync/revs`` the copy fingerprints.
_REVS_DIR = DIET_LAYOUT.revs_path
def _device_log_path(device_id: str) -> str:

View File

@ -46,6 +46,7 @@ from diet_guard._device import device_identity
from diet_guard._state_sync import read_raw_log, resign_entry, write_raw_log
from diet_guard._sync import _remote_revisions
from diet_guard._sync_client import _client_for_interactive_run
from diet_guard._sync_e2e import read_sealed
from diet_guard._sync_errors import SyncError
from diet_guard._sync_paths import _DEVICES_DIR, _device_log_path
from diet_guard.sync_merge import daylog_to_log, log_to_daylog, parse_remote_log
@ -116,7 +117,7 @@ def _merge_peer_logs(
"""Merge each peer's pushed log into ``merged``; report whether any landed."""
changed = False
for device_id in peers:
text = client.get_file_text(_device_log_path(device_id))
text = read_sealed(client, _device_log_path(device_id))
if text is None:
continue
try:

View File

@ -10,6 +10,7 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import patch
from crdt_sync import Argon2Params
import freedays
import sickdays
@ -18,6 +19,19 @@ if TYPE_CHECKING:
from unittest.mock import _patch
#: The passphrase every test device shares, unless a test says otherwise.
TEST_PHRASE = "test-passphrase"
#: Argon2id at a cost a test suite can afford thousands of times.
TEST_ARGON2 = Argon2Params(memory_kib=8, iterations=1, parallelism=1)
def _passphrase_file(tmp_path: Path) -> Path:
path = tmp_path / "crdt-sync-password"
path.write_text(TEST_PHRASE)
return path
def state_redirects(tmp_path: Path) -> list[_patch[object]]:
"""Every patch that points diet_guard state and network at ``tmp_path``."""
return [
@ -71,6 +85,13 @@ def state_redirects(tmp_path: Path) -> list[_patch[object]]:
"diet_guard._sync.SYNC_STATE_FILE",
tmp_path / "sync_state.json",
),
# End-to-end encryption: never the real ~/.config/crdt-sync/password,
# a cheap Argon2id cost, and the key/copy memo beside the other state.
patch("diet_guard._sync_e2e.PASSWORD_FILE", _passphrase_file(tmp_path)),
patch("diet_guard._sync_e2e.ARGON2_PARAMS", TEST_ARGON2),
patch("diet_guard._sync_e2e.E2E_STATE_DIR", tmp_path / "e2e"),
# The library's per-process copy memo must not leak between tests.
patch.dict("crdt_sync._e2e_store._copied", clear=True),
# Without this a test that syncs mints a uuid into the REAL
# ~/.local/share/diet_guard/.device_id, and this machine's live sync
# identity is decided by whichever test happened to run first.

View File

@ -57,3 +57,68 @@ def _mock_client(
# no revision map means every peer is fetched, exactly as before.
del client.get_string_map
return client
#: Paths only the end-to-end encryption touches: the two headers, and the
#: old plaintext prefixes the one-time copy reads.
_E2E_BOOKKEEPING = ("diet-guard-sync/e2e", "wake-alarm-sync/e2e")
_OLD_PREFIXES = ("diet-guard-sync/devices/", "wake-alarm-sync/devices/")
def _data_paths(method: MagicMock) -> list[str]:
"""The paths ``method`` was called with, minus E2E header/copy traffic."""
return [
call.args[0]
for call in method.call_args_list
if call.args[0] not in _E2E_BOOKKEEPING
and not call.args[0].startswith(_OLD_PREFIXES)
and call.args[0] not in {"diet-guard-sync/devices", "wake-alarm-sync/devices"}
]
class DictStore:
"""In-memory ``RemoteStore``: paths are keys, directories are derived."""
def __init__(self, files: dict[str, str] | None = None) -> None:
"""Start with ``files`` (path -> text)."""
self.files = dict(files or {})
self.puts: list[str] = []
def list_directory(self, path: str) -> list[str]:
"""Immediate children of ``path``."""
prefix = f"{path}/"
return sorted(
{
k[len(prefix) :].split("/", 1)[0]
for k in self.files
if k.startswith(prefix)
}
)
def get_file_text(self, path: str) -> str | None:
"""The stored text, or None."""
return self.files.get(path)
def put_file_text(self, path: str, text: str, *, message: str) -> None:
"""Store ``text`` and record the write."""
del message
self.files[path] = text
self.puts.append(path)
def get_string_map(self, path: str) -> dict[str, str]:
"""Leaf children of ``path`` with their text."""
prefix = f"{path}/"
return {
k[len(prefix) :]: v
for k, v in self.files.items()
if k.startswith(prefix) and "/" not in k[len(prefix) :]
}
def delete_file(self, path: str, *, message: str = "") -> None:
"""Forget ``path``."""
del message
self.files.pop(path, None)
def can_access_remote(self) -> bool:
"""Always reachable."""
return True

View File

@ -18,6 +18,7 @@ from diet_guard.sync_merge._body import (
log_to_body,
parse_remote_body,
)
from diet_guard.tests._sync_fakes import DictStore, _data_paths
# 2026-09-27 ~21:00 UTC: after that morning's weigh-in, as a real publish is.
_HLC = Hlc(wall_time_ms=1_790_535_000_000, counter=0, node_id="phone").to_str()
@ -86,24 +87,29 @@ class TestWeightCandidates:
assert [c.kg for c in cands] == [71.0]
class _DownStore(DictStore):
def list_directory(self, path: str) -> list[str]:
raise RemoteSyncError(path)
class TestFetchAlarmLogs:
def test_reads_every_device_and_skips_missing_files(self) -> None:
store = MagicMock()
store.list_directory.return_value = ["a", "b"]
store.get_file_text.side_effect = ["{}", None]
store = DictStore(
{
"wake-alarm-sync/devices-e2e/a/alarm.json": "{}",
"wake-alarm-sync/devices-e2e/b/other.json": "{}",
}
)
assert fetch_alarm_logs(store) == [("a", "{}")]
def test_mirror_reads_the_primary_only(self) -> None:
mirror = MagicMock(spec=MirrorSyncClient)
mirror.primary = MagicMock()
mirror.primary.list_directory.return_value = []
assert fetch_alarm_logs(mirror) == []
mirror.primary.list_directory.assert_called_once()
primary = DictStore({"wake-alarm-sync/devices-e2e/a/alarm.json": "{}"})
mirror = DictStore({"wake-alarm-sync/devices-e2e/m/alarm.json": "{}"})
assert fetch_alarm_logs(MirrorSyncClient(primary, mirror)) == [("a", "{}")]
assert mirror.puts == []
def test_a_remote_failure_reads_as_nothing(self) -> None:
store = MagicMock()
store.list_directory.side_effect = RemoteSyncError("down")
assert fetch_alarm_logs(store) == []
assert fetch_alarm_logs(_DownStore()) == []
class TestLogAdapter:
@ -181,17 +187,18 @@ class TestSyncBody:
"src": "manual",
"t": "2026-09-20T08:00:00+02:00",
}
path = "diet-guard-sync/devices/peer/body.json"
path = "diet-guard-sync/devices-e2e/peer/body.json"
client = self._client({path: encode_body_for_push(body_to_log(peer_doc))})
_sync_body.sync_body(client, ["peer", device_id()])
assert weights() == {"2026-09-20": 74.0}
pushed = client.put_file_text.call_args.args
assert pushed[0] == f"diet-guard-sync/devices/{device_id()}/body.json"
assert pushed[0] == f"diet-guard-sync/devices-e2e/{device_id()}/body.json"
def test_skips_missing_and_unparsable_peers(self) -> None:
client = self._client({"diet-guard-sync/devices/bad/body.json": "{oops"})
client = self._client({"diet-guard-sync/devices-e2e/bad/body.json": "{oops"})
_sync_body.sync_body(client, ["bad", "absent"])
client.put_file_text.assert_not_called()
# Only wake-alarm's encryption header, created on first use; no body.
assert _data_paths(client.put_file_text) == []
def test_ingests_phone_weigh_ins_first(self) -> None:
client = self._client({})

View File

@ -25,7 +25,7 @@ def _client(logs: dict[str, dict[str, object]]) -> MagicMock:
client = MagicMock()
client.list_directory.return_value = list(logs)
files = {
f"diet-guard-sync/devices/{dev}/food_log.json": json.dumps(recs)
f"diet-guard-sync/devices-e2e/{dev}/food_log.json": json.dumps(recs)
for dev, recs in logs.items()
}
client.get_file_text.side_effect = files.get
@ -124,7 +124,7 @@ class TestApply:
list(_prune_peers.apply_prune(client, ["dead"]))
deleted = [call.args[0] for call in client.delete_file.call_args_list]
assert "diet-guard-sync/revs/dead" in deleted
assert "diet-guard-sync/revs-e2e/dead" in deleted
def test_apply_deletes_all_four_paths(self) -> None:
client = MagicMock()

View File

@ -16,7 +16,12 @@ from diet_guard import _sync, _sync_client
from diet_guard._device import device_id
from diet_guard._foodbank_search import lookup_food
from diet_guard._state import load_log, log_meal
from diet_guard.tests._sync_fakes import _mock_client, _nutrition, _write_token
from diet_guard.tests._sync_fakes import (
_data_paths,
_mock_client,
_nutrition,
_write_token,
)
class TestReadToken:
@ -51,14 +56,14 @@ class TestRunSync:
merged = _sync.run_sync()
assert sum(len(entries) for entries in merged.values()) == 1
pushed = [call.args[0] for call in client.put_file_text.call_args_list]
pushed = _data_paths(client.put_file_text)
# The log push, the derived bank rebuilt from that same log, and this
# device's revision -- published *after* the log, so a peer can never
# cache "seen rev X" against a log it never received.
assert pushed == [
f"diet-guard-sync/devices/{device_id()}/food_bank.json",
f"diet-guard-sync/devices/{device_id()}/food_log.json",
f"diet-guard-sync/revs/{device_id()}",
f"diet-guard-sync/devices-e2e/{device_id()}/food_bank.json",
f"diet-guard-sync/devices-e2e/{device_id()}/food_log.json",
f"diet-guard-sync/revs-e2e/{device_id()}",
]
log_call = next(
call
@ -66,16 +71,18 @@ class TestRunSync:
if call.args[0].endswith("food_log.json")
)
pushed_json = log_call.args[1]
# Sealed: one envelope record, id in clear, fields encrypted.
pushed = json.loads(pushed_json)
(record,) = pushed.values()
assert "fields" in record
assert "id" in record
assert pushed["v"] == 1
((rid, record),) = pushed["r"].items()
assert rid
assert set(record) == {"d", "dh", "h", "p"}
def test_skips_its_own_device_id_when_listing(self) -> None:
_write_token()
client = _mock_client(
devices=("pc", "phone"),
files={"diet-guard-sync/devices/phone/food_log.json": "{}"},
files={"diet-guard-sync/devices-e2e/phone/food_log.json": "{}"},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync.run_sync()
@ -83,16 +90,16 @@ class TestRunSync:
# body -- skips "pc" (this device) and only ever reads "phone"'s files.
# The wake-alarm weigh-ins are another app's devices, all read: the
# mock lists the same two ids for every directory.
requested_paths = [call.args[0] for call in client.get_file_text.call_args_list]
requested_paths = _data_paths(client.get_file_text)
assert requested_paths == [
"diet-guard-sync/devices/phone/food_log.json",
"diet-guard-sync/devices/phone/budget.json",
"diet-guard-sync/devices/phone/food_bank.json",
"diet-guard-sync/devices/phone/food_bank_manual.json",
"diet-guard-sync/devices/phone/kuchnia.json",
"wake-alarm-sync/devices/pc/alarm.json",
"wake-alarm-sync/devices/phone/alarm.json",
"diet-guard-sync/devices/phone/body.json",
"diet-guard-sync/devices-e2e/phone/food_log.json",
"diet-guard-sync/devices-e2e/phone/budget.json",
"diet-guard-sync/devices-e2e/phone/food_bank.json",
"diet-guard-sync/devices-e2e/phone/food_bank_manual.json",
"diet-guard-sync/devices-e2e/phone/kuchnia.json",
"wake-alarm-sync/devices-e2e/pc/alarm.json",
"wake-alarm-sync/devices-e2e/phone/alarm.json",
"diet-guard-sync/devices-e2e/phone/body.json",
]
def test_skips_a_device_with_no_pushed_file_yet(self) -> None:
@ -106,7 +113,7 @@ class TestRunSync:
_write_token()
client = _mock_client(
devices=("phone",),
files={"diet-guard-sync/devices/phone/food_log.json": "[]"},
files={"diet-guard-sync/devices-e2e/phone/food_log.json": "[]"},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
merged = _sync.run_sync()
@ -119,7 +126,9 @@ class TestRunSync:
_write_token()
client = _mock_client(
devices=("phone",),
files={"diet-guard-sync/devices/phone/food_log.json": "{not valid json"},
files={
"diet-guard-sync/devices-e2e/phone/food_log.json": "{not valid json"
},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
merged = _sync.run_sync()
@ -146,7 +155,7 @@ class TestRunSync:
)
client = _mock_client(
devices=("phone",),
files={"diet-guard-sync/devices/phone/food_log.json": remote_log_json},
files={"diet-guard-sync/devices-e2e/phone/food_log.json": remote_log_json},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
merged = _sync.run_sync()
@ -181,7 +190,7 @@ class TestRunSync:
)
client = _mock_client(
devices=("phone",),
files={"diet-guard-sync/devices/phone/food_log.json": remote_log_json},
files={"diet-guard-sync/devices-e2e/phone/food_log.json": remote_log_json},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync.run_sync()

View File

@ -84,7 +84,7 @@ class TestClientForRun:
_sync_client, "firebase_client_for", lambda app: ("firebase", app)
)
assert _sync_client._client_for_run() == ("firebase", "diet_guard")
assert _sync_client._raw_client_for_run() == ("firebase", "diet_guard")
def test_unusable_firebase_config_becomes_a_sync_error(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch

View File

@ -35,7 +35,7 @@ class TestSyncFoodBank:
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync.run_sync()
pushed = [call.args[0] for call in client.put_file_text.call_args_list]
assert f"diet-guard-sync/devices/{device_id()}/food_bank.json" in pushed
assert f"diet-guard-sync/devices-e2e/{device_id()}/food_bank.json" in pushed
def test_a_food_the_phone_logged_reaches_the_gate(self) -> None:
"""The payoff: a food eaten on the phone autocompletes on the PC.
@ -64,7 +64,7 @@ class TestSyncFoodBank:
)
client = _mock_client(
devices=("phone",),
files={"diet-guard-sync/devices/phone/food_log.json": remote_log_json},
files={"diet-guard-sync/devices-e2e/phone/food_log.json": remote_log_json},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync.run_sync()
@ -92,7 +92,7 @@ class TestSyncFoodBank:
)
client = _mock_client(
devices=("phone",),
files={"diet-guard-sync/devices/phone/food_bank.json": remote},
files={"diet-guard-sync/devices-e2e/phone/food_bank.json": remote},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync.run_sync()
@ -120,7 +120,7 @@ class TestSyncFoodBank:
)
client = _mock_client(
devices=("phone",),
files={"diet-guard-sync/devices/phone/food_bank.json": remote},
files={"diet-guard-sync/devices-e2e/phone/food_bank.json": remote},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync.run_sync()
@ -131,7 +131,7 @@ class TestSyncFoodBank:
log_meal("apple", Nutrition(95, 0.5, 25, 0.3, 180, "manual"), 8)
client = _mock_client(
devices=("phone",),
files={"diet-guard-sync/devices/phone/food_bank.json": "{not json"},
files={"diet-guard-sync/devices-e2e/phone/food_bank.json": "{not json"},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync.run_sync()
@ -143,7 +143,7 @@ class TestSyncFoodBank:
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync.run_sync()
pushed = [call.args[0] for call in client.put_file_text.call_args_list]
assert f"diet-guard-sync/devices/{device_id()}/food_bank.json" not in pushed
assert f"diet-guard-sync/devices-e2e/{device_id()}/food_bank.json" not in pushed
class TestSyncManualBank:
@ -164,7 +164,9 @@ class TestSyncManualBank:
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync.run_sync()
pushed = [call.args[0] for call in client.put_file_text.call_args_list]
assert f"diet-guard-sync/devices/{device_id()}/food_bank_manual.json" in pushed
assert (
f"diet-guard-sync/devices-e2e/{device_id()}/food_bank_manual.json" in pushed
)
def test_a_remote_curated_entry_is_adopted_locally(self) -> None:
"""The point of the whole feature: a food added on the phone is usable
@ -191,7 +193,7 @@ class TestSyncManualBank:
)
client = _mock_client(
devices=("phone",),
files={"diet-guard-sync/devices/phone/food_bank_manual.json": remote},
files={"diet-guard-sync/devices-e2e/phone/food_bank_manual.json": remote},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync.run_sync()
@ -220,7 +222,7 @@ class TestSyncManualBank:
)
client = _mock_client(
devices=("phone",),
files={"diet-guard-sync/devices/phone/food_bank_manual.json": remote},
files={"diet-guard-sync/devices-e2e/phone/food_bank_manual.json": remote},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync.run_sync()
@ -232,7 +234,7 @@ class TestSyncManualBank:
client = _mock_client(
devices=("phone",),
files={
"diet-guard-sync/devices/phone/food_bank_manual.json": "{not json",
"diet-guard-sync/devices-e2e/phone/food_bank_manual.json": "{not json",
},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):

View File

@ -36,7 +36,7 @@ class TestSyncBudget:
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync.run_sync()
pushed_paths = {call.args[0] for call in client.put_file_text.call_args_list}
assert f"diet-guard-sync/devices/{device_id()}/budget.json" in pushed_paths
assert f"diet-guard-sync/devices-e2e/{device_id()}/budget.json" in pushed_paths
def test_refreshes_the_weight_from_the_log_after_the_merge(self) -> None:
"""The hook runs last, on every successful tick, into the sync log."""
@ -63,7 +63,9 @@ class TestSyncBudget:
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync.run_sync()
pushed_paths = {call.args[0] for call in client.put_file_text.call_args_list}
assert f"diet-guard-sync/devices/{device_id()}/budget.json" not in pushed_paths
assert (
f"diet-guard-sync/devices-e2e/{device_id()}/budget.json" not in pushed_paths
)
def test_remote_only_budget_is_adopted_locally(self) -> None:
"""Only the phone has ever set a budget -- the PC adopts it."""
@ -71,7 +73,7 @@ class TestSyncBudget:
remote_json = _remote_budget_json(kcal=1800, t="2026-01-01T09:00:00")
client = _mock_client(
devices=("phone",),
files={"diet-guard-sync/devices/phone/budget.json": remote_json},
files={"diet-guard-sync/devices-e2e/phone/budget.json": remote_json},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync.run_sync()
@ -84,7 +86,7 @@ class TestSyncBudget:
remote_json = _remote_budget_json(kcal=1800, t="2020-01-01T09:00:00")
client = _mock_client(
devices=("phone",),
files={"diet-guard-sync/devices/phone/budget.json": remote_json},
files={"diet-guard-sync/devices-e2e/phone/budget.json": remote_json},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync.run_sync()
@ -102,7 +104,7 @@ class TestSyncBudget:
remote_json = _remote_budget_json(kcal=1800, t="2999-01-01T09:00:00")
client = _mock_client(
devices=("phone",),
files={"diet-guard-sync/devices/phone/budget.json": remote_json},
files={"diet-guard-sync/devices-e2e/phone/budget.json": remote_json},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync.run_sync()
@ -120,7 +122,7 @@ class TestSyncBudget:
remote_json = _remote_budget_json(kcal=1800, t="2999-01-01T09:00:00")
client = _mock_client(
devices=("phone",),
files={"diet-guard-sync/devices/phone/budget.json": remote_json},
files={"diet-guard-sync/devices-e2e/phone/budget.json": remote_json},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync.run_sync()
@ -157,7 +159,7 @@ class TestSyncBudget:
write_budget(2000)
client = _mock_client(
devices=("phone",),
files={"diet-guard-sync/devices/phone/budget.json": "{not valid json"},
files={"diet-guard-sync/devices-e2e/phone/budget.json": "{not valid json"},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync.run_sync()

View File

@ -47,8 +47,8 @@ class TestPullSkipsOwnLegacyPath:
)
fetched = [call.args[0] for call in client.get_file_text.call_args_list]
assert "diet-guard-sync/devices/pc/food_log.json" not in fetched
assert "diet-guard-sync/devices/phone/food_log.json" in fetched
assert "diet-guard-sync/devices-e2e/pc/food_log.json" not in fetched
assert "diet-guard-sync/devices-e2e/phone/food_log.json" in fetched
def test_pulls_the_legacy_path_once_it_is_disowned(self) -> None:
"""Negative control: with no legacy id, devices/pc/ IS a peer.
@ -69,4 +69,4 @@ class TestPullSkipsOwnLegacyPath:
)
fetched = [call.args[0] for call in client.get_file_text.call_args_list]
assert "diet-guard-sync/devices/pc/food_log.json" in fetched
assert "diet-guard-sync/devices-e2e/pc/food_log.json" in fetched

View File

@ -0,0 +1,309 @@
"""End-to-end encryption of the sync payloads (``_sync_e2e``).
Runs the real sync tick over a dict-backed remote, so the header, the sealed
blobs and the keyed revisions are the bytes a real backend would hold.
"""
from __future__ import annotations
import json
import logging
from typing import TYPE_CHECKING
from unittest.mock import patch
from crdt_sync import (
E2eCipher,
E2eDecryptError,
E2eLayout,
E2eLockedError,
MirrorSyncClient,
seal_log_text,
)
import pytest
from diet_guard import _sync, _sync_client, _sync_e2e
from diet_guard._body_ingest import fetch_alarm_logs
from diet_guard._device import device_id
from diet_guard._state import load_log, log_meal
from diet_guard._state_sync import read_raw_log, write_raw_log
from diet_guard._sync_banks import _primary_only_text
from diet_guard.sync_merge import daylog_to_log
from diet_guard.tests._sync_fakes import DictStore, _nutrition, _write_token
if TYPE_CHECKING:
from pathlib import Path
_PRIVATE_MEAL = "secret oatmeal"
_OLD = "diet-guard-sync/devices"
_NEW = "diet-guard-sync/devices-e2e"
def _run(store: DictStore) -> None:
_write_token()
with patch.object(_sync_client, "GitHubSyncClient", return_value=store):
_sync.run_sync()
def _peer_log(desc: str) -> str:
"""A plaintext food log a pre-E2E peer pushed, holding one meal."""
log_meal(desc, _nutrition(), slot=480)
log = daylog_to_log(read_raw_log())
write_raw_log({})
return json.dumps({rid: rec.to_dict() for rid, rec in log.items()})
def _all_meals() -> list[str]:
return [entry["desc"] for entries in load_log().values() for entry in entries]
class TestSealedPush:
def test_pushed_blobs_hold_no_plaintext(self) -> None:
log_meal(_PRIVATE_MEAL, _nutrition(), slot=480)
store = DictStore()
_run(store)
own = f"{_NEW}/{device_id()}"
log_blob = store.files[f"{own}/food_log.json"]
assert "secret" not in log_blob
assert '"fields"' not in log_blob
assert '"desc"' not in log_blob
# Record ids stay clear by design (kuhy's call: ids, tombstones and
# clocks are metadata). The food banks key records by food name, so
# only their *fields* are asserted sealed here.
for path, text in store.files.items():
assert "kcal" not in text, path
assert "protein" not in text, path
def test_nothing_is_written_to_the_old_plaintext_prefix(self) -> None:
log_meal(_PRIVATE_MEAL, _nutrition(), slot=480)
store = DictStore()
_run(store)
assert store.puts
for path in store.puts:
assert not path.startswith(f"{_OLD}/"), path
assert not path.startswith("diet-guard-sync/revs/"), path
assert f"diet-guard-sync/revs-e2e/{device_id()}" in store.files
assert "diet-guard-sync/e2e" in store.files
def test_another_device_with_the_passphrase_reads_it_back(self) -> None:
log_meal(_PRIVATE_MEAL, _nutrition(), slot=480)
store = DictStore()
_run(store)
reader = _sync_e2e.open_e2e(store)
text = reader.get_file_text(f"{_NEW}/{device_id()}/food_log.json")
assert text is not None
assert _PRIVATE_MEAL in text
class TestMigration:
def test_old_plaintext_peer_log_is_copied_and_merged(self) -> None:
peer = _peer_log("peer porridge")
store = DictStore({f"{_OLD}/phone/food_log.json": peer})
_run(store)
assert "peer porridge" in _all_meals()
# Copied under E2E, and the old node left exactly as it was.
assert "porridge" not in store.files[f"{_NEW}/phone/food_log.json"]
assert store.files[f"{_OLD}/phone/food_log.json"] == peer
def test_old_plaintext_export_keys_move_under_e2e(self) -> None:
key_b64 = "c2VjcmV0LWV4cG9ydC1rZXktYnl0ZXMtMzItbG9uZyE="
keyring = {
"kid1": {
"id": "kid1",
"fields": {"k": [key_b64, "2026-11-01T00:00:00.000Z-0000-phone"]},
"deleted": False,
}
}
old_path = f"{_OLD}/phone/export_keys.json"
store = DictStore({old_path: json.dumps(keyring)})
_run(store)
sealed = store.files[f"{_NEW}/phone/export_keys.json"]
assert key_b64 not in sealed
assert store.files[old_path] == json.dumps(keyring)
reader = _sync_e2e.open_e2e(store)
assert key_b64 in (reader.get_file_text(f"{_NEW}/phone/export_keys.json") or "")
class TestLocked:
def test_no_passphrase_fails_closed_without_any_write(self, tmp_path: Path) -> None:
log_meal(_PRIVATE_MEAL, _nutrition(), slot=480)
store = DictStore()
missing = tmp_path / "no-such-password"
with (
patch.object(_sync_e2e, "PASSWORD_FILE", missing),
pytest.raises(_sync.SyncError, match="locked"),
):
_run(store)
assert store.puts == []
def test_wrong_passphrase_fails_closed(self, tmp_path: Path) -> None:
store = DictStore()
# Another device creates the header under the test passphrase.
with patch.object(_sync_e2e, "E2E_STATE_DIR", tmp_path / "other-device"):
_sync_e2e.open_e2e(store)
store.puts.clear()
other = tmp_path / "other-password"
other.write_text("a different passphrase")
with (
patch.object(_sync_e2e, "PASSWORD_FILE", other),
pytest.raises(_sync.SyncError, match="locked"),
):
_run(store)
assert store.puts == []
def test_locked_pull_reports_a_reason_instead_of_raising(
self, tmp_path: Path
) -> None:
_write_token()
with (
patch.object(_sync_e2e, "PASSWORD_FILE", tmp_path / "none"),
patch.object(_sync_client, "GitHubSyncClient", return_value=DictStore()),
):
reason = _sync.pull_shared_log()
assert reason is not None
assert "locked" in reason
def test_unreadable_header_is_locked(self) -> None:
store = DictStore({"diet-guard-sync/e2e": "not a header"})
with pytest.raises(_sync.SyncError, match="locked"):
_run(store)
class TestUndecryptablePeer:
def test_peer_sealed_under_another_key_is_skipped(
self, caplog: pytest.LogCaptureFixture
) -> None:
log_meal("mine", _nutrition(), slot=480)
layout = E2eLayout.of(_OLD)
path = f"{_NEW}/stranger/food_log.json"
record = {
"id": "r1",
"fields": {"desc": ["x", "2026-11-01T00:00:00.000Z-0000-s"]},
}
alien = seal_log_text(
json.dumps({"r1": record}),
E2eCipher(b"\x01" * 32),
path=path,
)
store = DictStore({path: alien})
with caplog.at_level(logging.WARNING):
_run(store)
assert layout.prefix == _NEW
assert "skipping" in caplog.text
assert _all_meals() == ["mine"]
_COPY = "crdt_sync._e2e_store.copy_to_encrypted"
class TestCopyMemo:
def _store_with_old_revs(self) -> DictStore:
return DictStore(
{
f"{_OLD}/phone/budget.json": "{}",
"diet-guard-sync/revs/phone": "rev-1",
}
)
def test_a_new_process_skips_the_copy_when_old_revisions_are_unchanged(
self,
) -> None:
store = self._store_with_old_revs()
_sync_e2e.open_e2e(store)
with (
patch.dict("crdt_sync._e2e_store._copied", clear=True),
patch(_COPY, return_value=0) as copy,
):
_sync_e2e.open_e2e(store)
copy.assert_not_called()
def test_changed_old_revisions_copy_again(self) -> None:
store = self._store_with_old_revs()
_sync_e2e.open_e2e(store)
store.files["diet-guard-sync/revs/phone"] = "rev-2"
with patch(_COPY, return_value=1) as copy:
_sync_e2e.open_e2e(store)
copy.assert_called_once()
def test_the_cached_key_opens_without_the_passphrase(self, tmp_path: Path) -> None:
store = DictStore()
_sync_e2e.open_e2e(store)
with patch.object(_sync_e2e, "PASSWORD_FILE", tmp_path / "gone"):
assert _sync_e2e.open_e2e(store).layout.prefix == _NEW
def test_wake_alarm_copies_once_per_process(self) -> None:
store = DictStore()
_sync_e2e.open_e2e(store, _sync_e2e.LEGACY_WAKE_ALARM_DIR)
assert not (_sync_e2e.E2E_STATE_DIR).exists()
with (
patch.dict("crdt_sync._e2e_store._copied", clear=True),
patch(_COPY, return_value=0) as copy,
):
_sync_e2e.open_e2e(store, _sync_e2e.LEGACY_WAKE_ALARM_DIR)
copy.assert_called_once()
def test_a_copy_meeting_an_unopenable_blob_is_locked(self) -> None:
store = DictStore()
with (
patch(_COPY, side_effect=E2eDecryptError("bad")),
pytest.raises(E2eLockedError),
):
_sync_e2e.open_e2e(store)
class TestWakeAlarmIngest:
def test_old_plaintext_alarm_is_copied_and_read_decrypted(self) -> None:
alarm = json.dumps(
{
"alarm": {
"id": "alarm",
"fields": {"alarm_hour": [7, "2026-11-01T00:00:00.000Z-0000-p"]},
"deleted": False,
}
}
)
store = DictStore({"wake-alarm-sync/devices/p1/alarm.json": alarm})
diet = _sync_e2e.open_e2e(store)
published = fetch_alarm_logs(diet)
assert [device for device, _ in published] == ["p1"]
assert json.loads(published[0][1])["alarm"]["fields"]["alarm_hour"][0] == 7
sealed = store.files["wake-alarm-sync/devices-e2e/p1/alarm.json"]
assert "alarm_hour" not in sealed
assert "wake-alarm-sync/e2e" in store.files
def test_locked_wake_alarm_is_skipped(self, tmp_path: Path) -> None:
store = DictStore()
diet = _sync_e2e.open_e2e(store)
with patch.object(_sync_e2e, "PASSWORD_FILE", tmp_path / "gone"):
assert fetch_alarm_logs(diet) == []
def test_reads_only_the_firebase_half_of_a_mirror(self) -> None:
primary = DictStore()
mirror = DictStore()
client = MirrorSyncClient(primary, mirror)
diet = _sync_e2e.open_e2e(client)
mirror.puts.clear()
fetch_alarm_logs(diet)
assert not any(p.startswith("wake-alarm-sync") for p in mirror.puts)
class TestPrimaryOnly:
def test_e2e_store_reads_the_primary_decrypted(self) -> None:
primary = DictStore()
mirror = DictStore()
diet = _sync_e2e.open_e2e(MirrorSyncClient(primary, mirror))
path = f"{_NEW}/peer/body.json"
diet.put_file_text(path, '{"x": 1}', message="t")
mirror.files.pop(path)
assert _primary_only_text(diet, path) == '{"x": 1}'
assert '"x"' not in primary.files[path]
def test_plain_store_is_read_directly(self) -> None:
store = DictStore({"a/b": "text"})
assert _primary_only_text(store, "a/b") == "text"

View File

@ -93,7 +93,7 @@ def test_a_peer_credential_is_cached_locally() -> None:
"""Receiving a peer's credential is what makes a wiped device work again."""
client = _client(
{
"diet-guard-sync/devices/phone/kuchnia.json": _peer_push(
"diet-guard-sync/devices-e2e/phone/kuchnia.json": _peer_push(
"peer@example.com", "peer-pass", 1_800_000_000_000
)
}
@ -109,7 +109,7 @@ def test_an_unchanged_credential_is_not_rewritten() -> None:
"""Re-running the tick must not rewrite the file every time."""
client = _client(
{
"diet-guard-sync/devices/phone/kuchnia.json": _peer_push(
"diet-guard-sync/devices-e2e/phone/kuchnia.json": _peer_push(
"peer@example.com", "peer-pass", 1_800_000_000_000
)
}
@ -127,8 +127,8 @@ def test_an_unparsable_peer_file_is_skipped(
"""One bad peer file must not take out the tick for every other device."""
client = _client(
{
"diet-guard-sync/devices/bad/kuchnia.json": "{not json",
"diet-guard-sync/devices/phone/kuchnia.json": _peer_push(
"diet-guard-sync/devices-e2e/bad/kuchnia.json": "{not json",
"diet-guard-sync/devices-e2e/phone/kuchnia.json": _peer_push(
"peer@example.com", "peer-pass", 1_800_000_000_000
),
}
@ -146,7 +146,7 @@ def test_a_missing_peer_file_is_skipped() -> None:
_write_handwritten("me@example.com\nhunter2\n")
_sync_kuchnia_credential(client, ["phone"])
client.get_file_text.assert_called_once_with(
"diet-guard-sync/devices/phone/kuchnia.json"
"diet-guard-sync/devices-e2e/phone/kuchnia.json"
)
@ -197,7 +197,7 @@ def test_a_touched_handwritten_file_cannot_clobber_a_peer() -> None:
phone_ms = int((time.time() - 3600) * 1000)
client = _client(
{
"diet-guard-sync/devices/phone/kuchnia.json": _peer_push(
"diet-guard-sync/devices-e2e/phone/kuchnia.json": _peer_push(
"phone@example.com", "new-phone-pass", phone_ms
)
}

View File

@ -119,7 +119,7 @@ class TestPullSkipsUnchangedPeers:
text = json.dumps({})
client = _mock_client(
devices=("phone",),
files={"diet-guard-sync/devices/phone/food_log.json": text},
files={"diet-guard-sync/devices-e2e/phone/food_log.json": text},
)
state = SyncState(pushed_rev=None, peer_revs={"phone": "rev-1"})
@ -152,8 +152,11 @@ class TestNoOpPushSuppression:
_sync.run_sync()
pushed_second = [call.args[0] for call in client.put_file_text.call_args_list]
assert f"diet-guard-sync/devices/{device_id()}/food_log.json" in pushed_first
assert (
f"diet-guard-sync/devices/{device_id()}/food_log.json" not in pushed_second
f"diet-guard-sync/devices-e2e/{device_id()}/food_log.json" in pushed_first
)
assert f"diet-guard-sync/revs/{device_id()}" not in pushed_second
assert (
f"diet-guard-sync/devices-e2e/{device_id()}/food_log.json"
not in pushed_second
)
assert f"diet-guard-sync/revs-e2e/{device_id()}" not in pushed_second

View File

@ -26,7 +26,12 @@ from diet_guard._device import device_id
from diet_guard._state import log_meal
from diet_guard._state_sync import read_raw_log, write_raw_log
from diet_guard.sync_merge import daylog_to_log
from diet_guard.tests._sync_fakes import _mock_client, _nutrition, _write_token
from diet_guard.tests._sync_fakes import (
_data_paths,
_mock_client,
_nutrition,
_write_token,
)
def _state_store() -> FileSyncStateStore:
@ -123,7 +128,7 @@ class TestRefreshPeerLogs:
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync_refresh.refresh_peer_logs()
client.get_file_text.assert_not_called()
assert _data_paths(client.get_file_text) == []
def test_skips_this_device(self) -> None:
"""Merging our own pushed log back in is pure waste."""
@ -133,7 +138,7 @@ class TestRefreshPeerLogs:
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync_refresh.refresh_peer_logs()
client.get_file_text.assert_not_called()
assert _data_paths(client.get_file_text) == []
def test_a_missing_remote_file_is_skipped(self) -> None:
_write_token()
@ -149,7 +154,7 @@ class TestRefreshPeerLogs:
_write_token()
client = _mock_client(
devices=("phone",),
files={"diet-guard-sync/devices/phone/food_log.json": "{not json"},
files={"diet-guard-sync/devices-e2e/phone/food_log.json": "{not json"},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
@ -162,7 +167,7 @@ class TestRefreshPeerLogs:
text = _peer_log_text()
client = _mock_client(
devices=("phone",),
files={"diet-guard-sync/devices/phone/food_log.json": text},
files={"diet-guard-sync/devices-e2e/phone/food_log.json": text},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
@ -180,13 +185,14 @@ class TestRefreshPeerLogs:
text = _peer_log_text()
client = _mock_client(
devices=("phone",),
files={"diet-guard-sync/devices/phone/food_log.json": text},
files={"diet-guard-sync/devices-e2e/phone/food_log.json": text},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
_sync_refresh.refresh_peer_logs()
client.put_file_text.assert_not_called()
# The encryption header may be created on a first-ever open; no data.
assert _data_paths(client.put_file_text) == []
def test_preserves_pushed_rev(self) -> None:
"""Overwriting it would make this device stop pushing forever."""
@ -196,7 +202,7 @@ class TestRefreshPeerLogs:
text = _peer_log_text()
client = _mock_client(
devices=("phone",),
files={"diet-guard-sync/devices/phone/food_log.json": text},
files={"diet-guard-sync/devices-e2e/phone/food_log.json": text},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):
@ -212,7 +218,7 @@ class TestRefreshPeerLogs:
text = _peer_log_text()
client = _mock_client(
devices=("phone", "other"),
files={"diet-guard-sync/devices/phone/food_log.json": text},
files={"diet-guard-sync/devices-e2e/phone/food_log.json": text},
)
with patch.object(_sync_client, "GitHubSyncClient", return_value=client):

View File

@ -5,10 +5,10 @@ description = "Tkinter/systemd log-to-unlock meal gate with calorie/macro budget
requires-python = ">=3.14"
dependencies = [
"gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.13.0#subdirectory=gatelock",
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync",
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.0#subdirectory=freedays",
"crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.0#subdirectory=crdt-sync",
"freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.2#subdirectory=freedays",
"holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds",
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.4.0#subdirectory=sickdays",
"sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.3#subdirectory=sickdays",
"defusedxml==0.7.1",
"requests==2.34.2",
]

View File

@ -3,9 +3,9 @@
bandit==1.9.4
codespell==2.4.3
coverage==7.17.2
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.9.2#subdirectory=crdt-sync
crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.0#subdirectory=crdt-sync
defusedxml==0.7.1
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.0#subdirectory=freedays
freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.2#subdirectory=freedays
gatelock @ git+https://github.com/kuhyx/utils@gatelock-v0.13.0#subdirectory=gatelock
holds @ git+https://github.com/kuhyx/utils@holds-v0.1.0#subdirectory=holds
mcp==2.3.0
@ -21,4 +21,4 @@ pytest-xdist==3.8.0
pytest-xvfb==3.1.1
requests==2.34.2
ruff==0.17.4
sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.4.0#subdirectory=sickdays
sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.3#subdirectory=sickdays