Add runtime fallback from CozyBridge to bearer-token flow for Drive intents

Introduces WorkplaceIntentAccessMode (BridgeAccessMode/BearerTokenAccessMode)
so both intent-creation flows share one call shape through the
datasource/repository/interactor stack, diverging only in implementation.

WorkplaceComposerAttachmentExtension now retries via the bearer-token flow
whenever the CozyBridge fetchJson attempt throws at runtime, not just when
the bridge is statically unavailable.

Claude-Session: https://claude.ai/code/session_01JuQMRy7LTrkJLqU54NNKrr
This commit is contained in:
Dang Dat committed 2026-09-07 14:33:21 +07:00
1 parent 99261bfd89
commit 3bc0c2d569
12 files changed
+292 -96

No files matched your search

+1
View File
@@ -19,6 +19,7 @@ env:
workplace/test/presentation/view/drive_intent_web_view_modal_web_test.dart
core/test/utils/html/editor_script/quoted_reply_enter_handler_script_browser_test.dart
workplace/test/data/workplace_datasource_impl_web_test.dart
workplace/test/presentation/extension/workplace_composer_attachment_extension_web_test.dart
jobs:
analyze-test:
@@ -1,10 +1,11 @@
import '../../domain/entity/workplace_intent.dart';
import '../../domain/entity/workplace_intent_access_mode.dart';
import '../../domain/entity/workplace_intent_config.dart';
abstract class WorkplaceDataSource {
Future<WorkplaceIntent> createIntent({
required Uri platformUrl,
String? accessToken,
required WorkplaceIntentAccessMode accessMode,
required WorkplaceIntentConfig config,
});
Future<String> exchangeToken(Uri platformUrl, String oidcIdToken);
@@ -11,6 +11,7 @@ import '../model/workplace_intent_response.dart';
import '../bridge/cozy_bridge.dart';
import '../workplace_dio.dart';
import '../../domain/entity/workplace_intent.dart';
import '../../domain/entity/workplace_intent_access_mode.dart';
import '../../domain/entity/workplace_intent_config.dart';
class WorkplaceDataSourceImpl implements WorkplaceDataSource {
@@ -27,26 +28,35 @@ class WorkplaceDataSourceImpl implements WorkplaceDataSource {
@override
Future<WorkplaceIntent> createIntent({
required Uri platformUrl,
String? accessToken,
required WorkplaceIntentAccessMode accessMode,
required WorkplaceIntentConfig config,
}) async {
final body = _buildIntentRequest(config);
// The container app already holds the stack session, so no bearer token;
// fall back to the direct bearer-token flow when the bridge isn't usable.
if (CozyBridge.isSupported && CozyBridge.isAvailable) {
final data = await CozyBridge.fetchJson(
method: 'POST',
path: '/intents',
body: body,
);
return parseIntentResponse(data);
}
return switch (accessMode) {
BridgeAccessMode() => _createIntentViaBridge(body),
BearerTokenAccessMode(:final accessToken) =>
_createIntentViaBearerToken(platformUrl, accessToken, body),
};
}
if (accessToken == null || accessToken.isEmpty) {
throw StateError('Drive access token is required');
}
// No token: the container app already holds the stack session.
Future<WorkplaceIntent> _createIntentViaBridge(
Map<String, dynamic> body,
) async {
final data = await CozyBridge.fetchJson(
method: 'POST',
path: '/intents',
body: body,
);
return parseIntentResponse(data);
}
Future<WorkplaceIntent> _createIntentViaBearerToken(
Uri platformUrl,
String accessToken,
Map<String, dynamic> body,
) async {
final response = await WorkplaceDio.instance.post(
platformUrl.replace(
pathSegments: [
@@ -1,5 +1,6 @@
import '../datasource/workplace_datasource.dart';
import '../../domain/entity/workplace_intent.dart';
import '../../domain/entity/workplace_intent_access_mode.dart';
import '../../domain/entity/workplace_intent_config.dart';
import '../../domain/repository/workplace_repository.dart';
@@ -11,11 +12,11 @@ class WorkplaceRepositoryImpl implements WorkplaceRepository {
@override
Future<WorkplaceIntent> createIntent({
required Uri platformUrl,
String? accessToken,
required WorkplaceIntentAccessMode accessMode,
required WorkplaceIntentConfig config,
}) => _dataSource.createIntent(
platformUrl: platformUrl,
accessToken: accessToken,
accessMode: accessMode,
config: config,
);
@@ -0,0 +1,16 @@
/// How a Drive intent request authenticates: same shape for callers,
/// diverse implementation per variant.
sealed class WorkplaceIntentAccessMode {
const WorkplaceIntentAccessMode();
}
/// Container app already holds the stack session; no token needed.
class BridgeAccessMode extends WorkplaceIntentAccessMode {
const BridgeAccessMode();
}
/// Direct REST call authenticated with an exchanged Drive access token.
class BearerTokenAccessMode extends WorkplaceIntentAccessMode {
final String accessToken;
const BearerTokenAccessMode(this.accessToken);
}
@@ -1,10 +1,11 @@
import '../entity/workplace_intent.dart';
import '../entity/workplace_intent_access_mode.dart';
import '../entity/workplace_intent_config.dart';
abstract class WorkplaceRepository {
Future<WorkplaceIntent> createIntent({
required Uri platformUrl,
String? accessToken,
required WorkplaceIntentAccessMode accessMode,
required WorkplaceIntentConfig config,
});
Future<String> exchangeToken(Uri platformUrl, String oidcIdToken);
@@ -1,6 +1,7 @@
import 'package:core/presentation/state/failure.dart';
import 'package:core/presentation/state/success.dart';
import 'package:dartz/dartz.dart';
import '../entity/workplace_intent_access_mode.dart';
import '../entity/workplace_intent_config.dart';
import '../repository/workplace_repository.dart';
import '../state/workplace_intent_state.dart';
@@ -12,14 +13,14 @@ class CreateDriveIntentInteractor {
Stream<Either<Failure, Success>> execute(
Uri platformUrl,
String? accessToken, {
WorkplaceIntentAccessMode accessMode, {
required WorkplaceIntentConfig config,
}) async* {
try {
yield Right(CreatingWorkplaceIntent());
final intent = await _repository.createIntent(
platformUrl: platformUrl,
accessToken: accessToken,
accessMode: accessMode,
config: config,
);
yield Right(CreateWorkplaceIntentSuccess(intent));
@@ -11,6 +11,7 @@ import 'package:workplace/data/model/workplace_intent_request.dart';
import 'package:workplace/data/repository_impl/workplace_repository_impl.dart';
import 'package:workplace/domain/entity/workplace_action_config.dart';
import 'package:workplace/domain/entity/workplace_intent.dart';
import 'package:workplace/domain/entity/workplace_intent_access_mode.dart';
import 'package:workplace/domain/entity/workplace_intent_config.dart';
import 'package:workplace/domain/entity/workplace_theme.dart';
import 'package:workplace/domain/exceptions/workplace_exceptions.dart';
@@ -57,19 +58,26 @@ class WorkplaceComposerAttachmentExtension implements ComposerAttachmentPlugin {
Uri platformUrl, {
required WorkplaceFilePickerConfigRequest filePickerConfig,
}) async {
// Mobile has no container app, so it authenticates against Drive directly;
// on web the bridge proxies through a session that already exists, unless
// the bridge itself is unavailable, in which case fall back to direct auth.
String? accessToken;
if (!CozyBridge.isSupported || !CozyBridge.isAvailable) {
final oidcToken = oidcTokenGetter();
if (oidcToken == null) throw StateError('OIDC token is unavailable');
accessToken = await _exchangeAccessToken(platformUrl, oidcToken);
if (accessToken == null) throw StateError('Drive access token exchange failed');
// Try the bridge first; any failure falls back to the bearer-token flow.
if (CozyBridge.isSupported && CozyBridge.isAvailable) {
try {
return await _createIntent(
platformUrl,
const BridgeAccessMode(),
filePickerConfig: filePickerConfig,
);
} catch (_) {
// fall through to the bearer-token flow below
}
}
final oidcToken = oidcTokenGetter();
if (oidcToken == null) throw StateError('OIDC token is unavailable');
final accessToken = await _exchangeAccessToken(platformUrl, oidcToken);
if (accessToken == null) throw StateError('Drive access token exchange failed');
return _createIntent(
platformUrl,
accessToken,
BearerTokenAccessMode(accessToken),
filePickerConfig: filePickerConfig,
);
}
@@ -100,13 +108,13 @@ class WorkplaceComposerAttachmentExtension implements ComposerAttachmentPlugin {
Future<WorkplaceIntent> _createIntent(
Uri platformUrl,
String? accessToken, {
WorkplaceIntentAccessMode accessMode, {
required WorkplaceFilePickerConfigRequest filePickerConfig,
}) async {
WorkplaceIntent? intent;
await for (final either in _createIntentInteractor.execute(
platformUrl,
accessToken,
accessMode,
config: WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: filePickerConfig.sharingLink.label),
addAsAttachment: filePickerConfig.downloadLink == null
@@ -7,6 +7,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:workplace/data/datasource_impl/workplace_datasource_impl.dart';
import 'package:workplace/data/workplace_dio.dart';
import 'package:workplace/domain/entity/workplace_action_config.dart';
import 'package:workplace/domain/entity/workplace_intent_access_mode.dart';
import 'package:workplace/domain/entity/workplace_intent_config.dart';
import 'package:workplace/domain/entity/workplace_theme.dart';
@@ -247,7 +248,7 @@ void main() {
final result = await datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com'),
accessToken: 'test-token',
accessMode: const BearerTokenAccessMode('test-token'),
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: WorkplaceActionConfig(label: 'https://attach.url'),
@@ -265,7 +266,7 @@ void main() {
await datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com/api/'),
accessToken: 'test-token',
accessMode: const BearerTokenAccessMode('test-token'),
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: WorkplaceActionConfig(label: 'https://attach.url'),
@@ -285,7 +286,7 @@ void main() {
await datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com'),
accessToken: 'test-token',
accessMode: const BearerTokenAccessMode('test-token'),
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: WorkplaceActionConfig(label: 'https://attach.url'),
@@ -305,7 +306,7 @@ void main() {
await datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com'),
accessToken: 'my-secret-token',
accessMode: const BearerTokenAccessMode('my-secret-token'),
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: WorkplaceActionConfig(label: 'https://attach.url'),
@@ -325,7 +326,7 @@ void main() {
await datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com'),
accessToken: 'test-token',
accessMode: const BearerTokenAccessMode('test-token'),
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: WorkplaceActionConfig(label: 'https://attach.url'),
@@ -358,7 +359,7 @@ void main() {
await datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com'),
accessToken: 'test-token',
accessMode: const BearerTokenAccessMode('test-token'),
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: WorkplaceActionConfig(
@@ -386,7 +387,7 @@ void main() {
await datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com'),
accessToken: 'test-token',
accessMode: const BearerTokenAccessMode('test-token'),
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
theme: WorkplaceTheme.light,
@@ -401,45 +402,13 @@ void main() {
expect(config['downloadLink'], isNull);
});
test('Should reject a null access token when the cozy bridge is unavailable', () async {
WorkplaceDio.setInstance(Dio()..httpClientAdapter = _MockAdapter(intentResponse));
expect(
() => datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com'),
accessToken: null,
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
theme: WorkplaceTheme.light,
),
),
throwsA(isA<StateError>()),
);
});
test('Should reject an empty access token when the cozy bridge is unavailable', () async {
WorkplaceDio.setInstance(Dio()..httpClientAdapter = _MockAdapter(intentResponse));
expect(
() => datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com'),
accessToken: '',
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
theme: WorkplaceTheme.light,
),
),
throwsA(isA<StateError>()),
);
});
test('Should propagate DioException on network error', () async {
WorkplaceDio.setInstance(Dio()..httpClientAdapter = _ErrorAdapter());
expect(
() => datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com'),
accessToken: 'test-token',
accessMode: const BearerTokenAccessMode('test-token'),
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
addAsAttachment: WorkplaceActionConfig(label: 'https://attach.url'),
@@ -3,7 +3,6 @@ library;
import 'dart:convert';
import 'dart:js_interop';
import 'dart:js_interop_unsafe';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
@@ -11,24 +10,11 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:workplace/data/datasource_impl/workplace_datasource_impl.dart';
import 'package:workplace/data/workplace_dio.dart';
import 'package:workplace/domain/entity/workplace_action_config.dart';
import 'package:workplace/domain/entity/workplace_intent_access_mode.dart';
import 'package:workplace/domain/entity/workplace_intent_config.dart';
import 'package:workplace/domain/entity/workplace_theme.dart';
@JS('window')
external JSObject get _window;
/// Installs a fake `window._cozyBridge.fetchJSON` so `CozyBridge.isAvailable` is true.
void _installBridge(JSAny? Function(JSObject options) handler) {
JSPromise<JSAny?> fetchJson(JSObject options) =>
Future<JSAny?>.value(handler(options)).toJS;
final bridge = JSObject();
bridge['fetchJSON'] = fetchJson.toJS;
_window['_cozyBridge'] = bridge;
}
/// Removes the bridge so `CozyBridge.isAvailable` is false (`isSupported` stays true on chrome).
void _removeBridge() => _window['_cozyBridge'] = null;
import '../test_utils/cozy_bridge_test_helper.dart';
/// Captures the last request and returns a fixed JSON response.
class _MockAdapter implements HttpClientAdapter {
@@ -81,20 +67,21 @@ void main() {
});
tearDown(() {
_removeBridge();
removeCozyBridge();
WorkplaceDio.setInstance(originalDio);
});
group('WorkplaceDataSourceImpl::createIntent::CozyBridge::', () {
test('Should return WorkplaceIntent via the bridge when available', () async {
JSObject? capturedOptions;
_installBridge((options) {
installCozyBridge((options) {
capturedOptions = options;
return intentResponse.jsify();
});
final result = await datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com'),
accessMode: const BridgeAccessMode(),
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
theme: WorkplaceTheme.light,
@@ -109,13 +96,13 @@ void main() {
expect(decoded['path'], equals('/intents'));
});
test('Should reject a null access token when the bridge is unavailable', () async {
_removeBridge();
test('Should propagate the error when the bridge fetchJSON call throws', () async {
installCozyBridge((options) => throw StateError('bridge rejected'));
expect(
() => datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com'),
accessToken: null,
accessMode: const BridgeAccessMode(),
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
theme: WorkplaceTheme.light,
@@ -125,14 +112,13 @@ void main() {
);
});
test('Should fall back to the bearer-token flow when the bridge is unavailable but an access token is present', () async {
_removeBridge();
test('Should use the bearer-token flow when explicitly requested', () async {
final adapter = _MockAdapter(intentResponse);
WorkplaceDio.setInstance(Dio()..httpClientAdapter = adapter);
final result = await datasource.createIntent(
platformUrl: Uri.parse('https://platform.example.com'),
accessToken: 'test-token',
accessMode: const BearerTokenAccessMode('test-token'),
config: const WorkplaceIntentConfig(
addAsLink: WorkplaceActionConfig(label: 'https://link.url'),
theme: WorkplaceTheme.light,
@@ -0,0 +1,178 @@
@TestOn('chrome')
library;
import 'dart:convert';
import 'dart:js_interop';
import 'package:core/presentation/resources/image_paths.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:workplace/data/model/workplace_enums.dart';
import 'package:workplace/data/model/workplace_intent_request.dart';
import 'package:workplace/data/workplace_dio.dart';
import 'package:workplace/presentation/extension/workplace_composer_attachment_extension.dart';
import 'package:workplace/presentation/mixin/drive_picker_state_mixin.dart';
import 'package:workplace/presentation/widget/drive_attachment_picker_button.dart';
import '../../test_utils/cozy_bridge_test_helper.dart';
// Queues responses per HTTP request; used only by the bearer-token fallback.
class _SequentialAdapter implements HttpClientAdapter {
final List<dynamic> _queue;
int _index = 0;
_SequentialAdapter(this._queue);
@override
Future<ResponseBody> fetch(
RequestOptions options,
Stream<Uint8List>? requestStream,
Future? cancelFuture,
) async {
return ResponseBody.fromString(
jsonEncode(_queue[_index++]),
200,
headers: {
Headers.contentTypeHeader: ['application/json; charset=utf-8'],
},
);
}
@override
void close({bool force = false}) {}
}
class _ErrorAdapter implements HttpClientAdapter {
@override
Future<ResponseBody> fetch(
RequestOptions options,
Stream<Uint8List>? requestStream,
Future? cancelFuture,
) async =>
throw DioException(requestOptions: options, message: 'Network error');
@override
void close({bool force = false}) {}
}
final _platformUri = Uri.parse('https://platform.example.com');
final _tokenResponse = {'access_token': 'drive-access-token'};
final _bridgeIntentResponse = {
'data': {
'id': 'intent-bridge',
'attributes': {
'action': 'PICK',
'type': 'files',
'permissions': ['GET'],
'services': [
{'href': 'https://drive.example.com/pick'},
],
},
},
};
final _bearerIntentResponse = {
'data': {
'id': 'intent-bearer',
'attributes': {
'action': 'PICK',
'type': 'files',
'permissions': ['GET'],
'services': [
{'href': 'https://drive.example.com/pick'},
],
},
},
};
WorkplaceComposerAttachmentExtension _makeExtension(ValueListenable<Uri?> notifier) =>
WorkplaceComposerAttachmentExtension(
workplaceUri: notifier,
uploadFromUrlSupported: () => true,
oidcTokenGetter: () => 'oidc-token',
maxAttachmentSizeBytesGetter: () => null,
remainingAttachmentCapacityBytesGetter: (_) => null,
);
const _filePickerConfig = WorkplaceFilePickerConfigRequest(
sharingLink: WorkplaceActionConfigRequest(label: 'Link'),
downloadLink: WorkplaceActionConfigRequest(label: 'Attachment'),
theme: WorkplaceThemeConfigRequest(type: WorkplaceThemeType.light),
);
void main() {
late Dio originalDio;
setUp(() => originalDio = WorkplaceDio.instance);
tearDown(() {
removeCozyBridge();
WorkplaceDio.setInstance(originalDio);
});
Future<FetchDriveIntentCallback> extractCallback(
WidgetTester tester,
WorkplaceComposerAttachmentExtension ext,
) async {
await tester.pumpWidget(MaterialApp(
home: Builder(
builder: (ctx) => ext.buildToolbarButton(
ctx,
composerId: 'composer-1',
imagePaths: ImagePaths(),
),
),
));
return tester
.widget<DriveAttachmentPickerButton>(find.byType(DriveAttachmentPickerButton))
.session
.onFetchIntent;
}
group('WorkplaceComposerAttachmentExtension::_fetchIntent::CozyBridge fallback::', () {
testWidgets('returns via the bridge without touching WorkplaceDio when it succeeds', (tester) async {
installCozyBridge((_) => _bridgeIntentResponse.jsify());
WorkplaceDio.setInstance(Dio()..httpClientAdapter = _ErrorAdapter());
final ext = _makeExtension(ValueNotifier<Uri?>(_platformUri));
final callback = await extractCallback(tester, ext);
final result = await tester.runAsync(
() => callback(filePickerConfig: _filePickerConfig),
);
expect(result!.intentId, equals('intent-bridge'));
});
testWidgets('falls back to bearer-token flow when the bridge call throws', (tester) async {
installCozyBridge((_) => throw StateError('bridge rejected'));
WorkplaceDio.setInstance(
Dio()..httpClientAdapter = _SequentialAdapter([_tokenResponse, _bearerIntentResponse]),
);
final ext = _makeExtension(ValueNotifier<Uri?>(_platformUri));
final callback = await extractCallback(tester, ext);
final result = await tester.runAsync(
() => callback(filePickerConfig: _filePickerConfig),
);
expect(result!.intentId, equals('intent-bearer'));
});
testWidgets('propagates the bearer-flow error when both the bridge and the fallback fail', (tester) async {
installCozyBridge((_) => throw StateError('bridge rejected'));
WorkplaceDio.setInstance(Dio()..httpClientAdapter = _ErrorAdapter());
final ext = _makeExtension(ValueNotifier<Uri?>(_platformUri));
final callback = await extractCallback(tester, ext);
await tester.runAsync(() async {
await expectLater(
callback(filePickerConfig: _filePickerConfig),
throwsA(isA<DioException>()),
);
});
});
});
}
@@ -0,0 +1,24 @@
// ignore_for_file: avoid_web_libraries_in_flutter
// Only ever imported from @TestOn('chrome') test files.
import 'dart:js_interop';
import 'dart:js_interop_unsafe';
@JS('window')
external JSObject get _window;
/// Installs a fake `window._cozyBridge.fetchJSON` so `CozyBridge.isAvailable`
/// is true. `handler` returning normally resolves the fake promise; throwing
/// rejects it, simulating a bridge-side failure.
void installCozyBridge(JSAny? Function(JSObject options) handler) {
JSPromise<JSAny?> fetchJson(JSObject options) =>
Future<JSAny?>.value(handler(options)).toJS;
final bridge = JSObject();
bridge['fetchJSON'] = fetchJson.toJS;
_window['_cozyBridge'] = bridge;
}
/// Removes the bridge so `CozyBridge.isAvailable` is false
/// (`isSupported` stays true on chrome).
void removeCozyBridge() => _window['_cozyBridge'] = null;