merge: isolate credentials across saved servers

This commit is contained in:
2026-10-24 02:28:14 +01:00
8 changed files with 496 additions and 19 deletions
@@ -0,0 +1,218 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/session/server_session.dart';
import 'package:shared_preferences/shared_preferences.dart';
const legacyKey = 'pipelines.session.cookie';
String profileKey(String id) =>
'pipelines.session.v2.${Uri.encodeComponent(id)}.cookie';
void main() {
final primary = Uri.parse('wss://primary.example/connect');
final backup = Uri.parse('ws://backup.example:8081/connect');
setUp(() async {
SharedPreferences.setMockInitialValues({});
await ServerSession.load();
});
Future<void> activate(String id, {bool migrateLegacy = false}) =>
ServerSession.activateServer(
id: id,
endpoints: [primary, backup],
migrateLegacy: migrateLegacy,
);
test(
'only exact trusted HTTP-normalized alias origins receive cookies',
() async {
SharedPreferences.setMockInitialValues({profileKey('a'): 'session=a'});
await activate('a');
for (final endpoint in [
primary,
backup,
Uri.parse('https://PRIMARY.example:443/files/data'),
Uri.parse('http://backup.example:8081/upload'),
]) {
expect(ServerSession.headersFor(endpoint), {'Cookie': 'session=a'});
}
for (final endpoint in [
Uri.parse('https://external.example/files'),
Uri.parse('https://child.primary.example/files'),
Uri.parse('https://primary.example:8443/files'),
Uri.parse('http://primary.example/files'),
Uri.parse('https://user:password@primary.example/files'),
Uri.parse('ftp://primary.example/files'),
Uri.parse('/files'),
]) {
expect(
ServerSession.headersFor(endpoint),
isEmpty,
reason: '$endpoint',
);
}
},
);
test(
'profiles sharing aliases still have isolated persisted sessions',
() async {
SharedPreferences.setMockInitialValues({
profileKey('a'): 'session=a',
profileKey('b'): 'session=b',
});
await activate('a');
expect(ServerSession.serverId, 'a');
final switching = activate('b');
expect(ServerSession.cookie, isNull);
await switching;
expect(ServerSession.headersFor(primary), {'Cookie': 'session=b'});
await activate('new');
expect(ServerSession.cookie, isNull);
expect(ServerSession.headersFor(primary), isEmpty);
await activate('a');
expect(ServerSession.cookie, 'session=a');
},
);
test(
'sign out changes only the selected profile and preserves legacy',
() async {
SharedPreferences.setMockInitialValues({
legacyKey: 'session=legacy',
profileKey('a'): 'session=a',
profileKey('b'): 'session=b',
});
await activate('a');
await ServerSession.signOut();
expect(ServerSession.headersFor(primary), isEmpty);
await activate('b');
expect(ServerSession.cookie, 'session=b');
await activate('a', migrateLegacy: true);
expect(ServerSession.cookie, isNull);
final prefs = await SharedPreferences.getInstance();
expect(prefs.getString(legacyKey), 'session=legacy');
await ServerSession.load();
expect(ServerSession.serverId, isNull);
expect(ServerSession.cookie, 'session=legacy');
},
);
test(
'legacy migration is explicit and never replaces a saved value',
() async {
SharedPreferences.setMockInitialValues({legacyKey: 'session=legacy'});
await activate('unrelated');
expect(ServerSession.cookie, isNull);
await activate('legacy-server', migrateLegacy: true);
expect(ServerSession.cookie, 'session=legacy');
final prefs = await SharedPreferences.getInstance();
await prefs.setString(legacyKey, 'session=changed');
await activate('legacy-server', migrateLegacy: true);
expect(ServerSession.cookie, 'session=legacy');
expect(prefs.getString(legacyKey), 'session=changed');
},
);
test(
'concurrent activation only publishes the most recent selection',
() async {
SharedPreferences.setMockInitialValues({
profileKey('a'): 'session=a',
profileKey('b'): 'session=b',
});
await Future.wait([activate('a'), activate('b')]);
expect(ServerSession.serverId, 'b');
expect(ServerSession.cookie, 'session=b');
},
);
test(
'invalid aliases are rejected without changing the current scope',
() async {
await activate('a');
for (final endpoints in <List<Uri>>[
[],
[Uri.parse('file:///tmp/test')],
[Uri.parse('https://user@primary.example')],
]) {
await expectLater(
ServerSession.activateServer(id: 'bad', endpoints: endpoints),
throwsArgumentError,
);
expect(ServerSession.serverId, 'a');
}
},
);
test(
'sign-in rejects addresses outside the selected trusted group',
() async {
await activate('a');
expect(
await ServerSession.signIn(
Uri.parse('https://other.example'),
'unused',
),
contains('not a trusted alias'),
);
expect(ServerSession.cookie, isNull);
},
);
test('late A login saves A without changing the active B session', () async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(() => server.close(force: true));
final endpoint = Uri.parse('http://127.0.0.1:${server.port}/connect');
final received = Completer<void>();
final release = Completer<void>();
final handled = Completer<void>();
server.listen((request) async {
await request.drain<void>();
received.complete();
await release.future;
request.response.cookies.add(Cookie('pipelines_session', 'late-a'));
request.response.statusCode = HttpStatus.found;
await request.response.close();
handled.complete();
});
SharedPreferences.setMockInitialValues({profileKey('b'): 'session=b'});
await ServerSession.activateServer(id: 'a', endpoints: [endpoint]);
final signingIn = ServerSession.signIn(endpoint, 'fixture-password');
await received.future;
await activate('b');
release.complete();
expect(await signingIn, isNull);
await handled.future;
expect(ServerSession.serverId, 'b');
expect(ServerSession.cookie, 'session=b');
await ServerSession.activateServer(id: 'a', endpoints: [endpoint]);
expect(ServerSession.cookie, 'pipelines_session=late-a');
});
test('sign out cancels a pending login for the same profile', () async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(() => server.close(force: true));
final endpoint = Uri.parse('http://127.0.0.1:${server.port}/connect');
final received = Completer<void>();
final release = Completer<void>();
server.listen((request) async {
await request.drain<void>();
received.complete();
await release.future;
request.response.cookies.add(Cookie('pipelines_session', 'too-late'));
await request.response.close();
});
await ServerSession.activateServer(id: 'a', endpoints: [endpoint]);
final signingIn = ServerSession.signIn(endpoint, 'fixture-password');
await received.future;
await ServerSession.signOut();
release.complete();
await signingIn;
expect(ServerSession.cookie, isNull);
await ServerSession.activateServer(id: 'a', endpoints: [endpoint]);
expect(ServerSession.cookie, isNull);
});
}
@@ -0,0 +1,138 @@
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/session/server_session.dart';
import 'package:pipelines_app/core/transport/channel_connect_io.dart' as socket;
import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_fetch_stub.dart'
as artifacts;
import 'package:pipelines_app/features/chat/data/upload/chat_upload_io.dart'
as upload;
import 'package:pipelines_app/features/updates/app_updates_io.dart' as updates;
import 'package:shared_preferences/shared_preferences.dart';
void main() {
late HttpServer trusted;
late HttpServer external;
late Uri trustedUri;
late Uri externalUri;
late Map<String, List<String?>> cookies;
setUp(() async {
cookies = {};
trusted = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
external = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
trustedUri = Uri.parse('http://127.0.0.1:${trusted.port}/');
externalUri = Uri.parse('http://127.0.0.1:${external.port}/');
for (final server in [trusted, external]) {
server.listen((request) async {
final name = '${server.port}${request.uri.path}';
cookies
.putIfAbsent(name, () => [])
.add(request.headers.value(HttpHeaders.cookieHeader));
if (request.uri.path == '/socket') {
final channel = await WebSocketTransformer.upgrade(request);
await channel.close();
return;
}
await request.drain<void>();
if (request.uri.path == '/redirect/version.json' ||
request.uri.path == '/redirect/socket') {
request.response.statusCode = HttpStatus.temporaryRedirect;
request.response.headers.set(
HttpHeaders.locationHeader,
externalUri.resolve(request.uri.path.split('/').last).toString(),
);
} else if (request.uri.path == '/login') {
request.response.statusCode = HttpStatus.found;
} else {
request.response.write('{"versionCode":1,"apk":"app.apk"}');
}
await request.response.close();
});
}
SharedPreferences.setMockInitialValues({
'pipelines.session.v2.fixture.cookie': 'pipelines_session=fixture',
'pipelines.session.cookie': 'pipelines_session=legacy',
});
await ServerSession.load();
await ServerSession.activateServer(id: 'fixture', endpoints: [trustedUri]);
});
tearDown(() async {
await trusted.close(force: true);
await external.close(force: true);
});
test('native requests authenticate only the selected exact origin', () async {
for (final uri in [trustedUri, externalUri]) {
await ServerSession.check(uri);
await artifacts.fetchArtifact(uri.resolve('artifact'));
await upload.postChatUpload(
uri.resolve('upload'),
name: 'fixture.txt',
mime: 'text/plain',
bytes: Uint8List.fromList([1, 2]),
);
await updates.fetchLatest(uri);
final channel = socket.connect(
uri.resolve('socket').replace(scheme: 'ws'),
);
await channel.ready;
await channel.stream.drain<void>();
await channel.sink.close();
for (final path in [
'/login',
'/artifact',
'/upload',
'/version.json',
'/socket',
]) {
expect(cookies['${uri.port}$path'], [
uri == trustedUri ? 'pipelines_session=fixture' : null,
], reason: '$uri $path');
}
}
});
test('updates do not follow redirects with a credential attached', () async {
await expectLater(
updates.fetchLatest(trustedUri.resolve('redirect/')),
throwsA(isA<HttpException>()),
);
expect(cookies['${trusted.port}/redirect/version.json'], [
'pipelines_session=fixture',
]);
expect(cookies['${external.port}/version.json'], isNull);
});
test(
'websocket handshakes do not follow credential-bearing redirects',
() async {
final channel = socket.connect(
trustedUri.resolve('redirect/socket').replace(scheme: 'ws'),
);
// Both the channel stream and ready report a failed handshake.
final streamDone = expectLater(channel.stream, emitsError(anything));
await expectLater(channel.ready, throwsA(anything));
await streamDone;
expect(cookies['${trusted.port}/redirect/socket'], [
'pipelines_session=fixture',
]);
expect(cookies['${external.port}/socket'], isNull);
},
);
test(
'load unbinds origins; legacy checking binds just its one server',
() async {
await ServerSession.load();
expect(ServerSession.serverId, isNull);
expect(ServerSession.headersFor(trustedUri), isEmpty);
await ServerSession.check(trustedUri);
await ServerSession.check(externalUri);
expect(cookies['${trusted.port}/login'], ['pipelines_session=legacy']);
expect(cookies['${external.port}/login'], [null]);
},
);
}