mirror of
https://github.com/kuhyx/utils.git
synced 2026-11-10 20:27:15 +01:00
Everything an app needs to move from GitHub to Firebase without each one reinventing the wiring. Python: - _config.py: FirebaseConfig.load() + firebase_client_for(app) + mirror_client_for(app, github). One config file, read in one place. Credential caches stay per-app (~/.config/<app>/firebase_auth.json) -- one file written by several processes is a corruption waiting to happen. - tool/preflight_firebase.py: validates the config before any data moves. Catches a wrong-region databaseUrl (which answers 404 with a correctUrl body rather than an error, so it would otherwise pass every check and break mid-migration) and confirms the uid in the ID token matches the uid the rules pin -- sign_in() returns None and discards localId, so the uid is decoded from the JWT. - tool/interop_seed.py: the missing Python half of the cross-language check. interop_check.dart asserts it can see a record written by Python, but nothing ever wrote one, so it could only ever fail. Dart: - firebase_config.dart: the same config shape, kept free of dart:io so it works on web and Android, where the file does not exist at all and credentials belong in flutter_secure_storage. - PersistedSyncStateStore: the revision cache, persisted. Without it a phone forgets every peer revision on each cold start and re-downloads everything -- the exact traffic the revision scheme exists to avoid, and what the free-tier headroom depends on. Verified live against the real database: preflight passes all five checks, the Dart smoke test passes end to end, and Python <-> Dart interop is OK. Python 226 tests at 100% branch coverage; Dart 218 tests, both new files at 100% line coverage. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SJ9sxEw3ymzXNjL7SHNpJc
233 lines
6.5 KiB
Dart
233 lines
6.5 KiB
Dart
/// Tests for the shared Firebase configuration on the Dart side.
|
|
///
|
|
/// The failure modes asserted here are the ones that would otherwise surface
|
|
/// as an authentication error long after the real mistake, so each is checked
|
|
/// to name the field at fault rather than merely to throw.
|
|
library;
|
|
|
|
import 'dart:convert';
|
|
|
|
import 'package:crdt_sync/crdt_sync.dart';
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:http/testing.dart' as http_testing;
|
|
import 'package:test/test.dart';
|
|
|
|
const _valid = {
|
|
'apiKey': 'AIzaSyExample',
|
|
'databaseUrl':
|
|
'https://kuhy-syncs-default-rtdb.europe-west1.firebasedatabase.app',
|
|
'projectId': 'kuhy-syncs',
|
|
'uid': 'OvA2REQyLIhAHOEjzwS1o877rgG3',
|
|
'email': 'sync@example.com',
|
|
};
|
|
|
|
/// A [RemoteStore] that does nothing, standing in for the GitHub client.
|
|
class _StubRemote implements RemoteStore {
|
|
@override
|
|
Future<List<String>> listDirectory(String path) async => [];
|
|
|
|
@override
|
|
Future<String?> getFileText(String path) async => null;
|
|
|
|
@override
|
|
Future<void> putFileText(
|
|
String path,
|
|
String text, {
|
|
required String message,
|
|
}) async {}
|
|
|
|
@override
|
|
Future<void> deleteFile(String path, {String message = ''}) async {}
|
|
|
|
@override
|
|
Future<bool> canAccessRemote() async => true;
|
|
|
|
@override
|
|
void close() {}
|
|
}
|
|
|
|
void main() {
|
|
group('FirebaseConfig', () {
|
|
test('parses a valid config', () {
|
|
final config = FirebaseConfig.parse(jsonEncode(_valid));
|
|
|
|
expect(config.apiKey, 'AIzaSyExample');
|
|
expect(config.projectId, 'kuhy-syncs');
|
|
expect(config.uid, 'OvA2REQyLIhAHOEjzwS1o877rgG3');
|
|
expect(config.email, 'sync@example.com');
|
|
expect(config.databaseUrl, endsWith('europe-west1.firebasedatabase.app'));
|
|
});
|
|
|
|
test('ignores the scaffold comment keys', () {
|
|
final annotated = {..._valid, '_comment_apiKey': 'where to find it'};
|
|
|
|
expect(
|
|
FirebaseConfig.parse(jsonEncode(annotated)).apiKey,
|
|
'AIzaSyExample',
|
|
);
|
|
});
|
|
|
|
test('agrees with the Python side on the field names', () {
|
|
// Both languages read the same file; a rename on one side only would
|
|
// break the other silently.
|
|
final config = FirebaseConfig.parse(jsonEncode(_valid));
|
|
|
|
expect(config.databaseUrl, _valid['databaseUrl']);
|
|
expect(config.uid, _valid['uid']);
|
|
});
|
|
|
|
for (final field in _valid.keys) {
|
|
test('names $field when it is missing', () {
|
|
final incomplete = {..._valid}..remove(field);
|
|
|
|
expect(
|
|
() => FirebaseConfig.parse(jsonEncode(incomplete)),
|
|
throwsA(
|
|
isA<ConfigException>().having(
|
|
(e) => e.message,
|
|
'message',
|
|
contains(field),
|
|
),
|
|
),
|
|
);
|
|
});
|
|
}
|
|
|
|
test('names an empty field', () {
|
|
final blank = {..._valid, 'uid': ' '};
|
|
|
|
expect(
|
|
() => FirebaseConfig.parse(jsonEncode(blank)),
|
|
throwsA(
|
|
isA<ConfigException>().having(
|
|
(e) => e.message,
|
|
'message',
|
|
contains('uid'),
|
|
),
|
|
),
|
|
);
|
|
});
|
|
|
|
test('names an unfilled placeholder', () {
|
|
final unfilled = {..._valid, 'apiKey': 'PASTE_WEB_API_KEY_HERE'};
|
|
|
|
expect(
|
|
() => FirebaseConfig.parse(jsonEncode(unfilled)),
|
|
throwsA(
|
|
isA<ConfigException>().having(
|
|
(e) => e.message,
|
|
'message',
|
|
contains('placeholder for: apiKey'),
|
|
),
|
|
),
|
|
);
|
|
});
|
|
|
|
test('rejects unparsable JSON', () {
|
|
expect(
|
|
() => FirebaseConfig.parse('{not json'),
|
|
throwsA(isA<ConfigException>()),
|
|
);
|
|
});
|
|
|
|
test('rejects a non-object document', () {
|
|
expect(
|
|
() => FirebaseConfig.parse('["a list"]'),
|
|
throwsA(isA<ConfigException>()),
|
|
);
|
|
});
|
|
|
|
test('has a readable toString on the exception', () {
|
|
expect(ConfigException('boom').toString(), contains('boom'));
|
|
});
|
|
});
|
|
|
|
group('client construction', () {
|
|
test('refuses to build without a session or a password', () async {
|
|
// Better than signing in with an empty password and failing remotely.
|
|
await expectLater(
|
|
firebaseClientFor(
|
|
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
|
store: InMemoryCredentialStore(),
|
|
),
|
|
throwsA(isA<ConfigException>()),
|
|
);
|
|
});
|
|
|
|
test('signs in with the password when there is no session', () async {
|
|
// The first-run path: no cached refresh token, so it must exchange the
|
|
// password for one rather than failing.
|
|
final store = InMemoryCredentialStore();
|
|
final sentTo = <String>[];
|
|
final mock = http_testing.MockClient((request) async {
|
|
sentTo.add(request.url.path);
|
|
return http.Response(
|
|
jsonEncode({
|
|
'idToken': 'id',
|
|
'refreshToken': 'refresh',
|
|
'expiresIn': '3600',
|
|
'localId': _valid['uid'],
|
|
}),
|
|
200,
|
|
);
|
|
});
|
|
|
|
final client = await firebaseClientFor(
|
|
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
|
store: store,
|
|
password: 'hunter2',
|
|
httpClient: mock,
|
|
);
|
|
|
|
expect(sentTo.single, contains('signInWithPassword'));
|
|
expect(await store.load(), isNotNull, reason: 'session must persist');
|
|
client.close();
|
|
});
|
|
|
|
test('reuses a stored session without a password', () async {
|
|
final store = InMemoryCredentialStore();
|
|
await store.save(
|
|
FirebaseCredentials(
|
|
idToken: 'id',
|
|
refreshToken: 'refresh',
|
|
expiresAt: DateTime.now().add(const Duration(hours: 1)),
|
|
),
|
|
);
|
|
|
|
final client = await firebaseClientFor(
|
|
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
|
store: store,
|
|
);
|
|
|
|
expect(client, isA<FirebaseRestClient>());
|
|
client.close();
|
|
});
|
|
|
|
test(
|
|
'mirrorStoreFor makes Firebase primary and GitHub the mirror',
|
|
() async {
|
|
// Which backend is authoritative is the one thing a rollback depends on.
|
|
final store = InMemoryCredentialStore();
|
|
await store.save(
|
|
FirebaseCredentials(
|
|
idToken: 'id',
|
|
refreshToken: 'refresh',
|
|
expiresAt: DateTime.now().add(const Duration(hours: 1)),
|
|
),
|
|
);
|
|
final github = _StubRemote();
|
|
|
|
final mirror = await mirrorStoreFor(
|
|
config: FirebaseConfig.parse(jsonEncode(_valid)),
|
|
store: store,
|
|
githubClient: github,
|
|
);
|
|
|
|
expect(mirror.primary, isA<FirebaseRestClient>());
|
|
expect(mirror.mirror, same(github));
|
|
mirror.close();
|
|
},
|
|
);
|
|
});
|
|
}
|