workout_app: add Google sign-in support for the Firebase sync account

Same pattern as todo and diet_guard_app: openFirebaseWithGoogle()
(google_platform.dart abstracts the plugin's platform-channel
dependence), isFirebaseConfigured() reading the stored session rather
than the account marker alone, and the settings screen offering
"Sign in with Google" ahead of the password form.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KdSp6Nbrs9xvsWkCMDN9a1
This commit is contained in:
Krzysztof Rudnicki 2026-08-12 23:38:41 +02:00
parent 3a5f0962de
commit 5d4d491fb7
14 changed files with 738 additions and 9 deletions

View File

@ -31,9 +31,27 @@ fi
# ── Guard: every lib/**/*.dart must appear in the coverage report ──────────────
# Flutter only reports files that are transitively imported by a test.
# Unreferenced files silently score 100% by absence — catch that here.
#
# Exception: a file whose only content is a conditional `export` (a
# platform-gate barrel like google_platform.dart, re-exporting google_platform_io.dart
# or google_platform_web.dart per dart.library.js_interop) has zero executable
# statements. Dart's coverage instrumentation never emits an SF: entry for such
# a file regardless of whether it was imported -- there is no "silently 100% by
# absence" for it to hide, since there is nothing to cover. Importing it (even
# transitively) is what makes its *resolved* sibling appear in lcov instead.
barrel_pattern="^(library;)?[[:space:]]*export[[:space:]]+'[^']+'[[:space:]]+if[[:space:]]*\([^)]+\)[[:space:]]+'[^']+';[[:space:]]*\$"
missing=0
while IFS= read -r dart_file; do
rel="${dart_file#"$APP_DIR"/}"
# Strip //-comments, ///-doc-comments and blank lines, then collapse
# whitespace, so a wrapped `export 'x' if (...) 'y';` statement (the
# platform-gate barrel shape) becomes matchable on one logical line
# regardless of how it's line-wrapped in source.
code_only=$(grep -vE '^[[:space:]]*(///|//|$)' "$dart_file" | tr '\n' ' ' | tr -s ' ')
if [[ $code_only =~ $barrel_pattern ]]; then
continue
fi
if ! grep -qF "SF:$rel" "$LCOV_INFO" && \
! grep -qF "SF:lib/${rel#lib/}" "$LCOV_INFO"; then
echo "MISSING FROM COVERAGE: $dart_file" >&2

View File

@ -13,6 +13,7 @@ import 'package:workout_app/models/workout_plan.dart';
import 'package:workout_app/services/backup_service.dart';
import 'package:workout_app/services/firebase_backend.dart';
import 'package:workout_app/services/github_device_auth.dart';
import 'package:workout_app/services/google_sign_in_backend.dart';
import 'package:workout_app/services/progression_sync_service.dart';
import 'package:workout_app/services/storage_service.dart';
import 'package:workout_app/services/sync_settings.dart';
@ -28,9 +29,12 @@ class SettingsScreen extends StatefulWidget {
super.key,
this.httpClient,
this.firebaseFactory,
this.googleFirebaseFactory,
this.googleAvailable,
this.accountLoader,
this.accountSaver,
this.accountClearer,
this.sessionProbe,
this.storageChecker,
this.storageRequester,
this.progressionPuller,
@ -43,6 +47,15 @@ class SettingsScreen extends StatefulWidget {
/// Builds the Firebase client. Injected so tests need no platform channel.
final Future<FirebaseRestClient?> Function()? firebaseFactory;
/// Builds the Firebase backend via Google sign-in. Separate from
/// [firebaseFactory] because it reaches the Google plugin's platform
/// channel, which `flutter test` has no binding for.
final Future<FirebaseRestClient?> Function()? googleFirebaseFactory;
/// Whether to offer the Google button. Defaults to what the platform
/// supports; injected by tests, whose host reports unsupported.
final bool? googleAvailable;
/// Keystore accessors for the Firebase account. Injected as a group so the
/// connect/disconnect flows are testable without a platform channel --
/// `flutter test` has no binding for one.
@ -54,6 +67,15 @@ class SettingsScreen extends StatefulWidget {
/// Forgets the account and any cached session. See [accountLoader].
final Future<void> Function()? accountClearer;
/// Whether a Firebase session is stored. See [accountLoader].
///
/// Separate from [accountLoader] because the two answer different
/// questions: the account marker is bookkeeping, the session is the
/// credential. A device can hold the second without the first, and
/// reporting only the first is what made a syncing phone read as
/// "not connected".
final Future<bool> Function()? sessionProbe;
/// Reads whether storage permission is held. Injected for the same reason as
/// [accountLoader]: `permission_handler` is a platform channel, and calling
/// it unguarded in `initState` made every settings-screen test throw.
@ -136,9 +158,74 @@ class _SettingsScreenState extends State<SettingsScreen> {
/// state instead of an empty form that looks unconfigured.
Future<void> _loadFirebaseAccount() async {
final account = await (widget.accountLoader ?? loadAccount)();
// The stored session, not the account marker, decides "connected": a
// Google sign-in leaves a refresh token that authenticates every request
// even when no marker was written beside it.
final connected = await (widget.sessionProbe ?? isFirebaseConfigured)();
if (!mounted) return;
if (account != null) _emailController.text = account.email;
setState(() => _firebaseConnected = account != null);
setState(() => _firebaseConnected = connected);
}
/// Signs in by picking a Google account -- the one-tap path.
///
/// A dismissed picker is not an error; a wrong-account sign-in reports why,
/// because that is the failure that otherwise looks like a working sync
/// which silently never syncs.
Future<void> _connectGoogle() async {
setState(() => _firebaseBusy = true);
try {
final client =
await (widget.googleFirebaseFactory ?? openFirebaseWithGoogle)();
if (!mounted) return;
if (client == null) {
setState(() => _firebaseBusy = false);
_setSyncStatus(
'Google sign-in was cancelled.',
_SyncStatusKind.pending,
);
return;
}
// openFirebaseWithGoogle stored the account under the email Firebase
// reported; reflect it rather than reading the (empty) form field.
final account = await (widget.accountLoader ?? storedAccount)();
// Report the persisted state, not the fact that the call returned a
// client: a non-null client only means sign-in succeeded in that
// moment, which is how four apps claimed "Connected" and then synced
// over GitHub after the next restart.
final connected = await (widget.sessionProbe ?? isFirebaseConfigured)();
if (!mounted) return;
if (account != null) _emailController.text = account.email;
setState(() {
_firebaseBusy = false;
_firebaseConnected = connected;
});
_setSyncStatus(
connected
? 'Connected to Firebase.'
: 'Signed in, but this device did not save the session - it will '
'sync over GitHub after a restart. Try connecting again.',
connected ? _SyncStatusKind.success : _SyncStatusKind.error,
);
} on FirebaseAuthError catch (error) {
if (!mounted) return;
setState(() {
_firebaseBusy = false;
_firebaseConnected = false;
});
_setSyncStatus(error.message, _SyncStatusKind.error);
} on Object catch (error) {
// Broader than Exception on purpose: a missing platform binding raises
// an Error, and anything escaping here leaves the button disabled and
// the screen stuck forever -- which is what happened on the phone
// before storedAccount() replaced loadAccount().
if (!mounted) return;
setState(() {
_firebaseBusy = false;
_firebaseConnected = false;
});
_setSyncStatus('Google sign-in failed: $error', _SyncStatusKind.error);
}
}
/// Stores the typed account and signs in immediately, so a typo surfaces
@ -183,8 +270,9 @@ class _SettingsScreenState extends State<SettingsScreen> {
// workout would push those defaults over the top. Connecting late is the
// normal path after a reinstall (the uninstall wipes the keystore), so
// this is the common case, not an edge one.
final restored = await (widget.progressionPuller ??
ProgressionSyncService().pullProgression)();
final restored =
await (widget.progressionPuller ??
ProgressionSyncService().pullProgression)();
if (!mounted) return;
setState(() {
@ -583,6 +671,18 @@ class _SettingsScreenState extends State<SettingsScreen> {
icon: const Icon(Icons.cloud_done),
label: const Text('Connect Firebase'),
),
// One tap, no typing -- the path that matters after a
// reinstall. Hidden where the platform has no programmatic
// Google flow (see google_platform.dart), because a button
// that always failed would be worse than none.
if (widget.googleAvailable ?? googleSignInSupported) ...[
const SizedBox(height: 12),
ElevatedButton.icon(
onPressed: _firebaseBusy ? null : _connectGoogle,
icon: const Icon(Icons.account_circle),
label: const Text('Sign in with Google'),
),
],
],
const SizedBox(height: 8),
// GitHub is the cutover mirror, not a choice competing with

View File

@ -16,6 +16,8 @@ import 'dart:developer';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:http/http.dart' as http;
import 'package:workout_app/services/google_sign_in_backend.dart';
/// The shared `kuhy-syncs` project.
///
@ -78,6 +80,17 @@ Future<FirebaseAccount?> loadAccount() async {
}
}
/// Reads the account from the keystore only, with no wrapper fallback.
///
/// [loadAccount] falls back to the desktop wrapper's `/sync-account` route
/// when the keystore is empty, which on Android resolves to `file:///` and
/// throws `No host specified in URI`. Callers reading back an account they
/// just wrote -- where a fallback would be wrong anyway -- use this instead.
/// Verified on the phone: without it, sign-in succeeded and then the settings
/// screen hung on "Signing in..." forever.
Future<FirebaseAccount?> storedAccount() async =>
FirebaseAccount.tryParse(await _secure.read(key: kFirebaseAccountKey));
/// Stores the per-device account. Keystore only — never prefs, never source.
Future<void> saveAccount(FirebaseAccount account) =>
_secure.write(key: kFirebaseAccountKey, value: account.toJsonString());
@ -94,12 +107,131 @@ Future<void> clearAccount() async {
/// token, so the usual path costs no authentication round trip.
Future<FirebaseRestClient?> openFirebase() async {
final account = await loadAccount();
if (account == null) return null;
if (account == null) {
// A stored refresh token IS a signed-in device, even with no account
// marker beside it. Treating the marker as the source of truth is what
// made a phone with a live session sync over GitHub and 401 forever --
// the credential was in the keystore the whole time, unused.
return _clientFromStoredSession();
}
return firebaseClientFor(
config: kProject.configFor(account.email),
store: credentialStore(),
password: account.password,
// A Google-provisioned account stores an empty password.
// Passing '' would make firebaseClientFor treat it as a usable
// credential and sign in with it, which fails; null correctly
// means "no password on this device".
password: account.password.isEmpty ? null : account.password,
// Deliberately NOT offering Google here. This path runs from background
// timers and, in some apps, before runApp -- offering it would let a
// non-interactive tick raise the OS account picker with no user action
// behind it. Interactive sign-in uses openFirebaseWithGoogle instead.
expectedUid: kSyncUid,
);
}
/// Signs in with Google alone, for a device that has no account stored yet.
///
/// This is the one-tap path: [openFirebase] needs an account in the keystore
/// to know which email to use, but a fresh install has none. The Google token
/// carries the identity, so nothing needs to be typed.
///
/// The account is stored under the email **Firebase reports**, never one read
/// from the UI: a fresh install has no email anywhere on the device, so taking
/// it from a text field would persist an empty account and send the next
/// launch down the password path with ''.
///
/// Returns null when the user dismisses the picker; throws [FirebaseAuthError]
/// when Google succeeds but resolves to a uid the security rules do not pin,
/// which would otherwise authenticate fine and then be denied every read and
/// write with no other symptom.
Future<FirebaseRestClient?> openFirebaseWithGoogle({
Future<String?> Function()? tokenFetcher,
Future<void> Function(FirebaseAccount)? accountSaver,
http.Client? httpClient,
}) async {
final token = await (tokenFetcher ?? googleIdToken)();
if (token == null) return null;
final auth = FirebaseTokenProvider(
apiKey: kProject.apiKey,
store: credentialStore(),
httpClient: httpClient,
);
final email = await auth.signInWithGoogle(
idToken: token,
expectedUid: kSyncUid,
);
// Saved unconditionally, and deliberately not gated on `email`:
// `signInWithIdp` omits that field whenever the Google account hides it, and
// gating the write on it returned a working client while persisting nothing,
// so the next launch looked unconfigured and fell back to GitHub-only.
// The session itself is already durable here -- signInWithGoogle stored the
// refresh token -- and that token, not the address, is the credential.
await (accountSaver ?? saveAccount)(
FirebaseAccount(email: email ?? '', password: ''),
);
return FirebaseRestClient(databaseUrl: kProject.databaseUrl, auth: auth);
}
/// Whether this device can actually authenticate against Firebase.
///
/// True when either half of the state is present: the account marker
/// [loadAccount] reads, or a stored refresh token. The token is the half that
/// matters -- it is what signs requests -- so reporting the marker alone calls
/// a working device "not connected", which is exactly how a phone that was in
/// fact syncing looked broken.
Future<bool> isFirebaseConfigured() async {
try {
final auth = FirebaseTokenProvider(
apiKey: kProject.apiKey,
store: credentialStore(),
);
if (await auth.hasSession()) return true;
// storedAccount, not loadAccount: on Android the latter falls back to the
// desktop wrapper's /sync-account route, which resolves to file:/// and
// throws "No host specified in URI" -- observed on the phone, where it
// turned a successful sign-in into "Google sign-in failed".
if (await storedAccount() == null) return false;
// A marker with no session behind it cannot sign a single request. Drop
// just the marker so the settings screen offers a sign-in instead of a
// dead banner -- not clearAccount(), which also sets the opt-out flag and
// would stop the desktop wrapper re-provisioning after the next sign-in.
await _secure.delete(key: kFirebaseAccountKey);
return false;
} on Object catch (error, stackTrace) {
log(
'session probe failed; reporting this device as not configured',
level: 1000,
error: error,
stackTrace: stackTrace,
);
return false;
}
}
/// Returns a client built from the keystore's refresh token alone, or null.
///
/// The recovery path for a device that has a live session but no account
/// marker -- the state a Google sign-in used to leave behind. Costs one
/// keystore read and no network round trip when there is no session, so it is
/// safe on the background-tick path [openFirebase] also serves.
Future<FirebaseRestClient?> _clientFromStoredSession() async {
try {
final auth = FirebaseTokenProvider(
apiKey: kProject.apiKey,
store: credentialStore(),
);
if (!await auth.hasSession()) return null;
return FirebaseRestClient(databaseUrl: kProject.databaseUrl, auth: auth);
} on Object catch (error, stackTrace) {
log(
'stored-session recovery failed; falling back to the GitHub mirror',
level: 1000,
error: error,
stackTrace: stackTrace,
);
return null;
}
}
// coverage:ignore-end

View File

@ -0,0 +1,11 @@
/// Platform gate for the programmatic Google sign-in flow.
///
/// Conditional export because the answer differs per platform *and* because
/// asking the plugin directly is unsafe: `supportsAuthenticate()` throws
/// `UnimplementedError` where no implementation is registered -- an `Error`,
/// not an `Exception`, so it escapes an ordinary catch and would take down
/// the settings screen's `build()`.
library;
export 'google_platform_io.dart'
if (dart.library.js_interop) 'google_platform_web.dart';

View File

@ -0,0 +1,10 @@
/// Whether the programmatic Google sign-in flow exists on this platform.
///
/// The io half: Android has the Credential Manager flow; Linux desktop does
/// not, and this app's desktop build is the web one anyway.
library;
import 'dart:io';
/// True only on Android, the one platform shipping the programmatic flow.
bool get googleSignInSupported => Platform.isAndroid;

View File

@ -0,0 +1,8 @@
/// Whether the programmatic Google sign-in flow exists on this platform.
///
/// The web half: Google Identity Services signs in only through its own
/// rendered button, so `authenticate()` throws `UnimplementedError` here.
library;
/// Always false: the web plugin has no programmatic sign-in.
bool get googleSignInSupported => false;

View File

@ -0,0 +1,122 @@
/// One-tap Google sign-in, kept apart from the rest of the sync wiring.
///
/// Why this is its own file: `crdt_sync` is deliberately pure Dart (only
/// `crypto` and `http`), because the same library runs on Linux desktop and
/// headless under systemd, where `google_sign_in` does not exist. So the
/// plugin lives here, in the app, and the library only ever receives a token
/// string through a closure.
///
/// What this buys: on a fresh install the sync account is reached by tapping
/// one account-picker row instead of typing a long password on a phone
/// keyboard. The password path stays as the fallback and as the machine
/// credential for desktop and the Python side.
library;
import 'dart:developer';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:workout_app/services/google_platform.dart' as platform_gate;
/// The account the security rules pin.
///
/// Not a secret -- it is already in the public `database.rules.json` -- but it
/// is the value that makes a wrong-account sign-in *fail loudly* instead of
/// authenticating fine and then being denied every read and write. See
/// `crdt-sync/tool/link_google.py`, which is what put the Google identity on
/// this uid in the first place.
const kSyncUid = 'OvA2REQyLIhAHOEjzwS1o877rgG3';
/// The project's **Web** OAuth client id, used as the audience for ID
/// tokens.
///
/// Public by design, exactly like [kProject]'s `apiKey`: it ships inside every
/// APK, and the security rules -- not its secrecy -- protect the data.
///
/// A plain const rather than a `--dart-define`, deliberately. As a
/// compile-time environment value it was empty in every build that matters:
/// the phone-deploy skill and CI both run a bare `flutter build apk
/// --release`, so released APKs would have shown a Google button that always
/// reported "cancelled" -- a visible control that can never succeed, which is
/// the exact thing the web platform gate exists to prevent.
///
/// Fill this in from Firebase console -> Project settings -> the `syncs-rest`
/// Web app's OAuth client (type "Web application"). Android must request a
/// token minted for the *web* client; an Android client id here yields a token
/// Firebase rejects with `audience mismatch`.
/// Empty until the Web OAuth client is registered; [googleSignInSupported] is
/// false while it is, so the button stays hidden rather than failing.
const kServerClientId =
'845446124781-prdoherj0v64vc6egvvcp3l0693khaur.apps.googleusercontent.com';
/// Whether this platform can sign in programmatically.
///
/// False on web, where Google Identity Services only signs in through its own
/// rendered button: `authenticate()` throws `UnimplementedError` there. The
/// desktop build of this app *is* the web build, so without this check the
/// "Sign in with Google" button would crash the settings screen on desktop
/// rather than falling back; see `google_platform.dart` for why this is a
/// platform check rather than a question asked of the plugin.
///
/// Also false when no client id is compiled in: a button that cannot possibly
/// succeed is worse than no button, and without this check an unconfigured
/// build reports "cancelled" and sends you debugging the OAuth console for a
/// problem that is really a missing constant.
bool get googleSignInSupported =>
platform_gate.googleSignInSupported && kServerClientId.isNotEmpty;
/// Returns a Google ID token for the signed-in account, or null.
///
/// Null rather than throwing when the user dismisses the picker: cancelling is
/// an ordinary outcome, and the caller falls back to the password path.
///
/// [signInFn] and [serverClientId] exist for tests, which cannot reach the
/// platform channel the plugin uses.
Future<String?> googleIdToken({
Future<String?> Function()? signInFn,
String serverClientId = kServerClientId,
}) async {
if (signInFn != null) return signInFn();
if (serverClientId.isEmpty) {
// A build without --dart-define=GOOGLE_SERVER_CLIENT_ID would otherwise
// fail inside the plugin with a far less obvious message.
log(
'Google sign-in unavailable: GOOGLE_SERVER_CLIENT_ID was not set at '
'build time; falling back to the password path',
level: 900,
);
return null;
}
// The plugin reaches the OS account picker through a platform channel,
// which `flutter test` has no binding for -- the same reason main.dart and
// firebase_backend.dart's keystore adapters are excluded. Everything above
// this point is pure Dart and is covered.
// coverage:ignore-start
try {
await GoogleSignIn.instance.initialize(serverClientId: serverClientId);
if (!GoogleSignIn.instance.supportsAuthenticate()) {
// Web/desktop: sign-in must go through the rendered GIS button, which
// this app does not host yet. Fall back rather than throwing.
log(
'Google sign-in is not available on this platform; falling back to '
'the password path',
level: 900,
);
return null;
}
final account = await GoogleSignIn.instance.authenticate();
return account.authentication.idToken;
} on GoogleSignInException catch (error, stackTrace) {
// Includes the user simply dismissing the picker, which is not an error
// worth surfacing -- but log it, because a *configuration* failure
// (unregistered SHA-1, wrong client id) arrives through the same path and
// is otherwise indistinguishable from "the user changed their mind".
log(
'Google sign-in did not complete',
level: 900,
error: error,
stackTrace: stackTrace,
);
return null;
}
// coverage:ignore-end
}

View File

@ -141,11 +141,11 @@ packages:
dependency: "direct main"
description:
path: crdt_sync_dart
ref: "crdt_sync_dart-v0.9.0"
resolved-ref: f902bbe0aa6689adbe4ef0ef6bb298655f4e136a
ref: "crdt_sync_dart-v0.10.0"
resolved-ref: "5f64a8959b1db342da1f73157b1148aa0dfa38a8"
url: "https://github.com/kuhyx/utils"
source: git
version: "0.9.0"
version: "0.10.0"
crypto:
dependency: transitive
description:
@ -297,6 +297,54 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.3"
google_identity_services_web:
dependency: transitive
description:
name: google_identity_services_web
sha256: "5d187c46dc59e02646e10fe82665fc3884a9b71bc1c90c2b8b749316d33ee454"
url: "https://pub.dev"
source: hosted
version: "0.3.3+1"
google_sign_in:
dependency: "direct main"
description:
name: google_sign_in
sha256: "521031b65853b4409b8213c0387d57edaad7e2a949ce6dea0d8b2afc9cb29763"
url: "https://pub.dev"
source: hosted
version: "7.2.0"
google_sign_in_android:
dependency: transitive
description:
name: google_sign_in_android
sha256: "57782125965ca87b03d42a147d40b046f1fd6a09141a58913e1b86671a5ef22e"
url: "https://pub.dev"
source: hosted
version: "7.2.16"
google_sign_in_ios:
dependency: transitive
description:
name: google_sign_in_ios
sha256: ac1e4c1205267cb7999d1d81333fccffdfda29e853f434bbaf71525498bb6950
url: "https://pub.dev"
source: hosted
version: "6.3.0"
google_sign_in_platform_interface:
dependency: transitive
description:
name: google_sign_in_platform_interface
sha256: "7f59208c42b415a3cca203571128d6f84f885fead2d5b53eb65a9e27f2965bb5"
url: "https://pub.dev"
source: hosted
version: "3.1.0"
google_sign_in_web:
dependency: transitive
description:
name: google_sign_in_web
sha256: d473003eeca892f96a01a64fc803378be765071cb0c265ee872c7f8683245d14
url: "https://pub.dev"
source: hosted
version: "1.1.3"
hooks:
dependency: transitive
description:

View File

@ -12,11 +12,15 @@ dependencies:
crdt_sync:
git:
url: https://github.com/kuhyx/utils
ref: crdt_sync_dart-v0.9.0
ref: crdt_sync_dart-v0.10.0
path: crdt_sync_dart
flutter:
sdk: flutter
flutter_secure_storage: ^10.3.1
# One-tap sign-in for the sync account. App-side only: crdt_sync stays pure
# Dart so it keeps working on Linux desktop and headless.
google_sign_in: ^7.2.0
http: ^1.6.0
path: ^1.9.1
path_provider: ^2.1.5

View File

@ -0,0 +1,88 @@
import 'dart:convert';
import 'package:crdt_sync/crdt_sync.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart' as http_testing;
import 'package:workout_app/services/firebase_backend.dart';
import 'package:workout_app/services/google_sign_in_backend.dart';
import 'fake_secure_storage.dart';
/// Answers a `signInWithIdp` call the way Firebase does.
http_testing.MockClient _signsInAs(String email, {String uid = kSyncUid}) =>
http_testing.MockClient(
(request) async => http.Response(
jsonEncode({
'idToken': 'id',
'refreshToken': 'refresh',
'expiresIn': '3600',
'email': email,
'localId': uid,
}),
200,
),
);
void main() {
// installFakeSecureStorage touches the test binary messenger, which only
// exists once the binding is initialised.
TestWidgetsFlutterBinding.ensureInitialized();
// openFirebaseWithGoogle reaches the keystore through a platform channel;
// the fake stands in so the account write is really exercised rather than
// stubbed out at the call site.
setUp(installFakeSecureStorage);
group('openFirebaseWithGoogle', () {
test('returns null when the picker is dismissed', () async {
// Cancelling is ordinary: no session, no account, no error.
final saved = <FirebaseAccount>[];
final client = await openFirebaseWithGoogle(
tokenFetcher: () async => null,
accountSaver: (account) async => saved.add(account),
);
expect(client, isNull);
expect(saved, isEmpty);
});
test('stores the account under the email Firebase reports', () async {
// The regression this test exists for. A fresh install has no email
// anywhere on the device, so it must come from the sign-in response. An
// earlier cut read it from the settings screen's text field -- empty on
// exactly this path -- and persisted FirebaseAccount(email: ''); the
// next launch then took the password branch with '' and failed.
final saved = <FirebaseAccount>[];
final client = await openFirebaseWithGoogle(
tokenFetcher: () async => 'a-token',
accountSaver: (account) async => saved.add(account),
httpClient: _signsInAs('signed-in@example.com'),
);
expect(client, isNotNull);
expect(saved, hasLength(1));
expect(saved.single.email, 'signed-in@example.com');
// No password to store: this device authenticates with the refresh
// token, and openFirebase() must not later try to sign in with ''.
expect(saved.single.password, isEmpty);
client!.close();
});
test('stores nothing when Google resolves to the wrong uid', () async {
// Authentication succeeds and the uid is wrong, which the security
// rules would deny on every read and write. Failing here -- with
// nothing persisted -- leaves the device retryable rather than stuck.
final saved = <FirebaseAccount>[];
await expectLater(
openFirebaseWithGoogle(
tokenFetcher: () async => 'a-token',
accountSaver: (account) async => saved.add(account),
httpClient: _signsInAs('someone@example.com', uid: 'a-different-uid'),
),
throwsA(isA<FirebaseAuthError>()),
);
expect(saved, isEmpty);
});
});
}

View File

@ -0,0 +1,14 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/google_sign_in_backend.dart';
void main() {
test('reports whether the programmatic Google flow exists here', () {
// Android is the only platform shipping it. Asked as a platform question
// rather than of the plugin, because GoogleSignIn.supportsAuthenticate()
// itself throws UnimplementedError where no implementation is registered
// -- an Error, not an Exception, so it would escape an ordinary catch and
// take down the settings screen's build(). The test host is Linux, so
// this is false here and the password path stays visible.
expect(googleSignInSupported, isFalse);
});
}

View File

@ -0,0 +1,13 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/google_platform_web.dart';
void main() {
test('the web half always reports the programmatic flow unsupported', () {
// The conditional export in google_platform.dart never pulls this file
// in on the Linux test host (it resolves to google_platform_io.dart
// instead), so it would otherwise never appear in coverage at all.
// Imported directly here for that reason, same pattern as
// sync_state_factory_web_test.dart elsewhere in this app family.
expect(googleSignInSupported, isFalse);
});
}

View File

@ -0,0 +1,33 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:workout_app/services/google_sign_in_backend.dart';
void main() {
group('googleIdToken', () {
test('returns the token the sign-in function yields', () async {
// The injected path: proves the closure is what feeds crdt_sync, and
// that no platform channel is touched to get there.
expect(
await googleIdToken(signInFn: () async => 'a-token'),
'a-token',
);
});
test('passes a null cancellation straight through', () async {
// Dismissing the picker is an ordinary outcome, not an error: the
// caller falls back to the password path.
expect(await googleIdToken(signInFn: () async => null), isNull);
});
test('reports "not configured" when the client id is missing', () async {
// A build without --dart-define=GOOGLE_SERVER_CLIENT_ID must fall back
// rather than failing deep inside the plugin with an opaque message.
expect(await googleIdToken(serverClientId: ''), isNull);
});
test('pins the uid the security rules expect', () {
// If this ever drifts from database.rules.json, a Google sign-in would
// be accepted here and then denied every read and write.
expect(kSyncUid, 'OvA2REQyLIhAHOEjzwS1o877rgG3');
});
});
}

View File

@ -65,9 +65,12 @@ void main() {
Widget _wrap({
http.Client? httpClient,
Future<FirebaseRestClient?> Function()? firebaseFactory,
Future<FirebaseRestClient?> Function()? googleFirebaseFactory,
bool? googleAvailable,
Future<FirebaseAccount?> Function()? accountLoader,
Future<void> Function(FirebaseAccount)? accountSaver,
Future<void> Function()? accountClearer,
Future<bool> Function()? sessionProbe,
Future<bool> Function()? storageChecker,
Future<bool> Function()? storageRequester,
Future<ProgressionSyncResult> Function()? progressionPuller,
@ -78,9 +81,19 @@ void main() {
// Injected so the widget never reaches the OS keystore, which
// `flutter test` has no platform-channel binding for.
firebaseFactory: firebaseFactory ?? () async => null,
googleFirebaseFactory: googleFirebaseFactory,
googleAvailable: googleAvailable,
accountLoader: accountLoader ?? () async => null,
accountSaver: accountSaver,
accountClearer: accountClearer,
// Defaults to whatever the injected account says, so a test that only
// stubs the account still describes one coherent device. The production
// probe reads the keystore this harness deliberately avoids, and would
// otherwise answer "no session" for a device the test declared signed
// in.
sessionProbe:
sessionProbe ??
() async => await (accountLoader ?? () async => null)() != null,
// Same reason: permission_handler is a platform channel too.
storageChecker: storageChecker ?? () async => false,
storageRequester: storageRequester,
@ -329,6 +342,121 @@ void main() {
expect(find.text('sync@example.com'), findsOneWidget);
});
testWidgets(
'Sign in with Google connects and reads back the persisted account',
(tester) async {
var sessionStored = false;
await _pump(
tester,
_wrap(
googleAvailable: true,
googleFirebaseFactory: () async {
sessionStored = true;
return _stubFirebaseClient();
},
accountLoader: () async => sessionStored
? const FirebaseAccount(email: 'g@example.com', password: '')
: null,
),
);
await _scrollToGitHubSync(tester);
await tester.ensureVisible(find.text('Sign in with Google'));
await tester.pump();
await tester.tap(find.text('Sign in with Google'));
await tester.pumpAndSettle();
expect(find.text('Connected to Firebase.'), findsOneWidget);
expect(find.text('g@example.com'), findsOneWidget);
},
);
testWidgets(
'Sign in with Google reports a cancelled picker as pending, not an error',
(tester) async {
await _pump(
tester,
_wrap(googleAvailable: true, googleFirebaseFactory: () async => null),
);
await _scrollToGitHubSync(tester);
await tester.ensureVisible(find.text('Sign in with Google'));
await tester.pump();
await tester.tap(find.text('Sign in with Google'));
await tester.pump();
await tester.pump();
expect(find.text('Google sign-in was cancelled.'), findsOneWidget);
},
);
testWidgets(
'Sign in with Google that does not persist a session reports the retry '
'message',
(tester) async {
await _pump(
tester,
_wrap(
googleAvailable: true,
googleFirebaseFactory: () async => _stubFirebaseClient(),
sessionProbe: () async => false,
),
);
await _scrollToGitHubSync(tester);
await tester.ensureVisible(find.text('Sign in with Google'));
await tester.pump();
await tester.tap(find.text('Sign in with Google'));
await tester.pumpAndSettle();
expect(
find.textContaining('did not save the session'),
findsOneWidget,
);
},
);
testWidgets('Sign in with Google wrong-account error surfaces the message', (
tester,
) async {
await _pump(
tester,
_wrap(
googleAvailable: true,
googleFirebaseFactory: () async =>
throw FirebaseAuthError('wrong uid'),
),
);
await _scrollToGitHubSync(tester);
await tester.ensureVisible(find.text('Sign in with Google'));
await tester.pump();
await tester.tap(find.text('Sign in with Google'));
await tester.pumpAndSettle();
expect(find.text('wrong uid'), findsOneWidget);
});
testWidgets('Sign in with Google generic failure surfaces the error text', (
tester,
) async {
await _pump(
tester,
_wrap(
googleAvailable: true,
googleFirebaseFactory: () async => throw StateError('boom'),
),
);
await _scrollToGitHubSync(tester);
await tester.ensureVisible(find.text('Sign in with Google'));
await tester.pump();
await tester.tap(find.text('Sign in with Google'));
await tester.pumpAndSettle();
expect(find.textContaining('Google sign-in failed'), findsOneWidget);
});
testWidgets('connecting pulls progression down immediately', (tester) async {
// Regression: connecting is the NORMAL path after a reinstall, because the
// uninstall wipes the keystore and startup's pull therefore found no