Skip to content

api: Send simple User-Agent header #471

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Feb 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions lib/api/core.dart
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,16 @@ class ApiConnection {
bool _isOpen = true;

Future<T> send<T>(String routeName, T Function(Map<String, dynamic>) fromJson,
http.BaseRequest request) async {
http.BaseRequest request, {String? overrideUserAgent}) async {
assert(_isOpen);

assert(debugLog("${request.method} ${request.url}"));

addAuth(request);
request.headers.addAll(userAgentHeader());
if (overrideUserAgent != null) {
request.headers['User-Agent'] = overrideUserAgent;
}

final http.StreamedResponse response;
try {
Expand Down Expand Up @@ -136,13 +140,13 @@ class ApiConnection {
}

Future<T> post<T>(String routeName, T Function(Map<String, dynamic>) fromJson,
String path, Map<String, dynamic>? params) async {
String path, Map<String, dynamic>? params, {String? overrideUserAgent}) async {
final url = realmUrl.replace(path: "/api/v1/$path");
final request = http.Request('POST', url);
if (params != null) {
request.bodyFields = encodeParameters(params)!;
}
return send(routeName, fromJson, request);
return send(routeName, fromJson, request, overrideUserAgent: overrideUserAgent);
}

Future<T> postFileFromStream<T>(String routeName, T Function(Map<String, dynamic>) fromJson,
Expand Down Expand Up @@ -201,6 +205,13 @@ Map<String, String> authHeader({required String email, required String apiKey})
};
}

Map<String, String> userAgentHeader() {
return {
// TODO(#467) include platform, platform version, and app version
'User-Agent': 'ZulipFlutter',
};
}

Map<String, String>? encodeParameters(Map<String, dynamic>? params) {
return params?.map((k, v) =>
MapEntry(k, v is RawParameter ? v.value : jsonEncode(v)));
Expand Down
18 changes: 18 additions & 0 deletions lib/api/route/messages.dart
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,7 @@ Future<SendMessageResult> sendMessage(
bool? readBySender,
}) {
final supportsTypeDirect = connection.zulipFeatureLevel! >= 174; // TODO(server-7)
final supportsReadBySender = connection.zulipFeatureLevel! >= 236; // TODO(server-8)
return connection.post('sendMessage', SendMessageResult.fromJson, 'messages', {
if (destination is StreamDestination) ...{
'type': RawParameter('stream'),
Expand All @@ -195,6 +196,23 @@ Future<SendMessageResult> sendMessage(
if (queueId != null) 'queue_id': queueId, // TODO should this use RawParameter?
if (localId != null) 'local_id': localId, // TODO should this use RawParameter?
if (readBySender != null) 'read_by_sender': readBySender,
},
overrideUserAgent: switch ((supportsReadBySender, readBySender)) {
// Old servers use the user agent to decide if we're a UI client
// and so whether the message should be marked as read for its author
// (see #440). We are a UI client; so, use a value those servers will
// interpret correctly. With newer servers, passing `readBySender: true`
// gives the same result.
// TODO(#467) include platform, platform version, and app version
(false, _ ) => 'ZulipMobile/flutter',

// According to the doc, a user-agent heuristic is still used in this case:
// https://zulip.com/api/send-message#parameter-read_by_sender
// TODO find out if our default user agent would work with that.
// TODO(#467) include platform, platform version, and app version
(true, null) => 'ZulipMobile/flutter',

_ => null,
});
}

Expand Down
13 changes: 7 additions & 6 deletions lib/widgets/content.dart
Original file line number Diff line number Diff line change
Expand Up @@ -848,12 +848,13 @@ class RealmContentNetworkImage extends StatelessWidget {
gaplessPlayback: gaplessPlayback,
filterQuality: filterQuality,
isAntiAlias: isAntiAlias,

// Only send the auth header to the server `auth` belongs to.
headers: src.origin == account.realmUrl.origin
? authHeader(email: account.email, apiKey: account.apiKey)
: null,

headers: {
// Only send the auth header to the server `auth` belongs to.
if (src.origin == account.realmUrl.origin) ...authHeader(
email: account.email, apiKey: account.apiKey,
),
...userAgentHeader(),
},
cacheWidth: cacheWidth,
cacheHeight: cacheHeight,
);
Expand Down
12 changes: 10 additions & 2 deletions test/api/core_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ void main() {
check(connection.lastRequest!).isA<http.Request>()
..method.equals('GET')
..url.asString.equals('${eg.realmUrl.origin}$expectedRelativeUrl')
..headers.deepEquals(authHeader(email: eg.selfAccount.email, apiKey: eg.selfAccount.apiKey))
..headers.deepEquals({
...authHeader(email: eg.selfAccount.email, apiKey: eg.selfAccount.apiKey),
...userAgentHeader(),
})
..body.equals('');
});
}
Expand Down Expand Up @@ -52,6 +55,7 @@ void main() {
..url.asString.equals('${eg.realmUrl.origin}/api/v1/example/route')
..headers.deepEquals({
...authHeader(email: eg.selfAccount.email, apiKey: eg.selfAccount.apiKey),
...userAgentHeader(),
if (expectContentType)
'content-type': 'application/x-www-form-urlencoded; charset=utf-8',
})
Expand Down Expand Up @@ -82,7 +86,10 @@ void main() {
check(connection.lastRequest!).isA<http.MultipartRequest>()
..method.equals('POST')
..url.asString.equals('${eg.realmUrl.origin}/api/v1/example/route')
..headers.deepEquals(authHeader(email: eg.selfAccount.email, apiKey: eg.selfAccount.apiKey))
..headers.deepEquals({
...authHeader(email: eg.selfAccount.email, apiKey: eg.selfAccount.apiKey),
...userAgentHeader(),
})
..fields.deepEquals({})
..files.single.which((it) => it
..field.equals('file')
Expand Down Expand Up @@ -114,6 +121,7 @@ void main() {
..url.asString.equals('${eg.realmUrl.origin}/api/v1/example/route')
..headers.deepEquals({
...authHeader(email: eg.selfAccount.email, apiKey: eg.selfAccount.apiKey),
...userAgentHeader(),
if (expectContentType)
'content-type': 'application/x-www-form-urlencoded; charset=utf-8',
})
Expand Down
45 changes: 43 additions & 2 deletions test/api/route/messages_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import 'dart:convert';
import 'package:checks/checks.dart';
import 'package:http/http.dart' as http;
import 'package:test/scaffolding.dart';
import 'package:zulip/api/core.dart';
import 'package:zulip/api/model/model.dart';
import 'package:zulip/api/model/narrow.dart';
import 'package:zulip/api/route/messages.dart';
Expand Down Expand Up @@ -304,6 +305,7 @@ void main() {
String? localId,
bool? readBySender,
required Map<String, String> expectedBodyFields,
String? expectedUserAgent,
}) async {
connection.prepare(json: SendMessageResult(id: 42).toJson());
final result = await sendMessage(connection,
Expand All @@ -313,7 +315,8 @@ void main() {
check(connection.lastRequest).isA<http.Request>()
..method.equals('POST')
..url.path.equals('/api/v1/messages')
..bodyFields.deepEquals(expectedBodyFields);
..bodyFields.deepEquals(expectedBodyFields)
..headers['User-Agent'].equals(expectedUserAgent ?? userAgentHeader()['User-Agent']!);
}

test('smoke', () {
Expand All @@ -339,11 +342,13 @@ void main() {
return FakeApiConnection.with_((connection) async {
await checkSendMessage(connection,
destination: StreamDestination(streamId, topic), content: content,
readBySender: true,
expectedBodyFields: {
'type': 'stream',
'to': streamId.toString(),
'topic': topic,
'content': content,
'read_by_sender': 'true',
});
});
});
Expand All @@ -352,10 +357,12 @@ void main() {
return FakeApiConnection.with_((connection) async {
await checkSendMessage(connection,
destination: DmDestination(userIds: userIds), content: content,
readBySender: true,
expectedBodyFields: {
'type': 'direct',
'to': jsonEncode(userIds),
'content': content,
'read_by_sender': 'true',
});
});
});
Expand All @@ -364,11 +371,45 @@ void main() {
return FakeApiConnection.with_(zulipFeatureLevel: 173, (connection) async {
await checkSendMessage(connection,
destination: DmDestination(userIds: userIds), content: content,
readBySender: true,
expectedBodyFields: {
'type': 'private',
'to': jsonEncode(userIds),
'content': content,
});
'read_by_sender': 'true',
},
expectedUserAgent: 'ZulipMobile/flutter');
});
});

test('when readBySender is null, sends a User-Agent we know the server will recognize', () {
return FakeApiConnection.with_((connection) async {
await checkSendMessage(connection,
destination: StreamDestination(streamId, topic), content: content,
readBySender: null,
expectedBodyFields: {
'type': 'stream',
'to': streamId.toString(),
'topic': topic,
'content': content,
},
expectedUserAgent: 'ZulipMobile/flutter');
});
});

test('legacy: when server does not support readBySender, sends a User-Agent the server will recognize', () {
return FakeApiConnection.with_(zulipFeatureLevel: 235, (connection) async {
await checkSendMessage(connection,
destination: StreamDestination(streamId, topic), content: content,
readBySender: true,
expectedBodyFields: {
'type': 'stream',
'to': streamId.toString(),
'topic': topic,
'content': content,
'read_by_sender': 'true',
},
expectedUserAgent: 'ZulipMobile/flutter');
});
});
});
Expand Down
17 changes: 9 additions & 8 deletions test/widgets/content_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ void main() {
group('RealmContentNetworkImage', () {
final authHeaders = authHeader(email: eg.selfAccount.email, apiKey: eg.selfAccount.apiKey);

Future<String?> actualAuthHeader(WidgetTester tester, Uri src) async {
Future<Map<String, List<String>>> actualHeaders(WidgetTester tester, Uri src) async {
await testBinding.globalStore.add(eg.selfAccount, eg.initialSnapshot());
addTearDown(testBinding.reset);

Expand All @@ -301,20 +301,21 @@ void main() {
await tester.pump();
await tester.pump();

final headers = httpClient.request.headers.values;
check(authHeaders.keys).deepEquals(['Authorization']);
return headers['Authorization']?.single;
return httpClient.request.headers.values;
}

testWidgets('includes auth header if `src` on-realm', (tester) async {
check(await actualAuthHeader(tester, Uri.parse('https://chat.example/image.png')))
.isNotNull().equals(authHeaders['Authorization']!);
check(await actualHeaders(tester, Uri.parse('https://chat.example/image.png')))
.deepEquals({
'Authorization': [authHeaders['Authorization']!],
'User-Agent': [userAgentHeader()['User-Agent']!],
});
debugNetworkImageHttpClientProvider = null;
});

testWidgets('excludes auth header if `src` off-realm', (tester) async {
check(await actualAuthHeader(tester, Uri.parse('https://other.example/image.png')))
.isNull();
check(await actualHeaders(tester, Uri.parse('https://other.example/image.png')))
.deepEquals({'User-Agent': [userAgentHeader()['User-Agent']!]});
debugNetworkImageHttpClientProvider = null;
});

Expand Down