Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,8 @@ abstract class BaseAnalyticsEventAdaptor {
// Shared helpers
// ---------------------------------------------------------------------------

// Counts, flags and categories only — never the entry's text, location, or date
// (the day something was written about can be personal on its own).
Map<String, Object>? storyAnalyticParameters(
StoryDbModel story, {
int? topicTagsCount,
Expand All @@ -367,9 +369,6 @@ abstract class BaseAnalyticsEventAdaptor {
'version': story.version.toString(),
'type': story.type.name,
'starred': ?story.starred?.toString(),
'year': story.year.toString(),
'month': story.month.toString(),
'day': story.day.toString(),
'pinned': ?story.pinned?.toString(),
'gallery_template_id': ?story.galleryTemplateId,
'pages_count': (story.draftContent?.id != null ? story.draftContent : story.latestContent)?.richPages?.length
Expand Down
4 changes: 2 additions & 2 deletions lib/core/services/analytics/analytics_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import 'package:storypad/core/constants/app_constants.dart';
import 'package:storypad/core/services/analytics/adaptors/base_analytics_event_adaptor.dart';

// Logging analytics events without user-identifiable information: never user-typed
// text (search queries, tag/person names), coordinates, or which links were opened
// (only our own storypad.me domain is named — see urlAnalyticParameters).
// text (search queries, tag/person names), coordinates, an entry's date, or which
// links were opened (only our own storypad.me domain is named — see urlAnalyticParameters).
// All high-level methods live in [BaseAnalyticsEventAdaptor]. This class
// preserves the existing call-site API: AnalyticsService.instance.logXxx().
class AnalyticsService {
Expand Down
28 changes: 24 additions & 4 deletions lib/core/services/backups/nextcloud_cloud_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import 'dart:convert';
import 'dart:io' as io;

import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart' show visibleForTesting;
import 'package:storypad/core/objects/backup_exceptions/backup_exception.dart' as exp;
import 'package:storypad/core/objects/cloud_file_object.dart';
import 'package:storypad/core/objects/cloud_storage_quota_object.dart';
Expand Down Expand Up @@ -109,7 +110,7 @@ class NextcloudCloudService extends BackupCloudService {
await client.ping();
} catch (e) {
throw exp.AuthException(
'Could not connect to Nextcloud: $e',
'Could not connect to Nextcloud: ${describeError(e)}',
exp.AuthExceptionType.signInFailed,
context: 'connect',
serviceType: serviceType,
Expand Down Expand Up @@ -549,6 +550,25 @@ class NextcloudCloudService extends BackupCloudService {
return client;
}

/// Dio's and dart:io's error text names the server (`Failed host lookup:
/// 'cloud.example.com'`, `address = 192.168.1.20`), and that server is the
/// user's own, often at home. Exception messages end up in Crashlytics logs
/// (sync failures, Cloud Optimize), so only the kind of error goes into them:
/// its type, Dio's failure type and status code, and the OS error code.
@visibleForTesting
static String describeError(Object? error) {
return switch (error) {
DioException(:final type, :final response, error: final inner) =>
'DioException(${[
type.name,
if (response?.statusCode case final status?) 'status $status',
if (inner != null) describeError(inner),
].join(', ')})',
io.SocketException(:final osError) => 'SocketException(errno ${osError?.errorCode ?? '-'})',
_ => '${error.runtimeType}',
};
}

exp.BackupException _buildException(dynamic error, String methodName) {
if (error is exp.BackupException) return error;

Expand Down Expand Up @@ -597,7 +617,7 @@ class NextcloudCloudService extends BackupCloudService {
error.type == DioExceptionType.sendTimeout ||
error.type == DioExceptionType.connectionError) {
return exp.NetworkException(
'Network error during $methodName: $error',
'Network error during $methodName: ${describeError(error)}',
context: methodName,
serviceType: serviceType,
);
Expand All @@ -606,14 +626,14 @@ class NextcloudCloudService extends BackupCloudService {

if (error is io.SocketException || error is TimeoutException) {
return exp.NetworkException(
'Network error during $methodName: $error',
'Network error during $methodName: ${describeError(error)}',
context: methodName,
serviceType: serviceType,
);
}

return exp.ServiceException(
'Unknown error during $methodName: $error',
'Unknown error during $methodName: ${describeError(error)}',
exp.ServiceExceptionType.unexpectedError,
context: methodName,
serviceType: serviceType,
Expand Down
74 changes: 74 additions & 0 deletions test/core/services/analytics/adaptors/analytics_helpers_test.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:storypad/core/databases/models/place_db_model.dart';
import 'package:storypad/core/databases/models/story_content_db_model.dart';
import 'package:storypad/core/databases/models/story_db_model.dart';
import 'package:storypad/core/databases/models/story_page_db_model.dart';
import 'package:storypad/core/services/analytics/adaptors/none_analytics_event_adaptor.dart';
import 'package:storypad/core/types/path_type.dart';

// Test via a concrete subclass (NoneAnalyticsEventAdaptor) since the helpers
// are non-abstract methods on the abstract base.
Expand Down Expand Up @@ -111,4 +116,73 @@ void main() {
expect(adaptor.urlAnalyticParameters('http://[::1'), isNull);
});
});

group('storyAnalyticParameters', () {
final DateTime date = DateTime(2024, 2, 14);

final StoryDbModel story = StoryDbModel(
id: 1,
type: PathType.docs,
year: date.year,
month: date.month,
day: date.day,
hour: 9,
minute: 30,
second: 0,
starred: true,
pinned: false,
feeling: null,
tags: const ['1', '2'],
assets: null,
place: PlaceDbModel(latitude: 11.56, longitude: 104.92, placeName: 'Home', country: 'Cambodia'),
latestContent: StoryContentDbModel(
id: 2,
title: 'Private title',
plainText: 'Private text',
createdAt: date,
richPages: [
StoryPageDbModel.legacy(
id: 3,
title: 'Private title',
body: [
{'insert': 'Private text\n'},
],
wordCount: 2,
),
],
),
draftContent: null,
createdAt: date,
updatedAt: date,
movedToBinAt: null,
galleryTemplateId: null,
templateId: null,
event: null,
lastSavedDeviceId: 'test-device',
permanentlyDeletedAt: null,
);

test('sends counts, flags and categories', () {
final params = adaptor.storyAnalyticParameters(story, peopleTagsCount: 1)!;

expect(params['type'], 'docs');
expect(params['starred'], 'true');
expect(params['pages_count'], 1);
expect(params['tags_count'], 2);
expect(params['people_tags_count'], 1);
});

test("never sends the entry's date, text or location", () {
final params = adaptor.storyAnalyticParameters(story)!;

for (final key in ['year', 'month', 'day', 'hour', 'title', 'place', 'latitude', 'longitude']) {
expect(params.containsKey(key), isFalse, reason: key);
}

final values = params.values.map((v) => v.toString()).join(' ');
for (final secret in ['Private', 'Home', 'Cambodia', '11.56', '104.92', '2024']) {
expect(values, isNot(contains(secret)), reason: secret);
}
});
});
}
69 changes: 69 additions & 0 deletions test/core/services/nextcloud_cloud_service_test.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import 'dart:async';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:storypad/core/objects/backup_exceptions/backup_exception.dart';
import 'package:storypad/core/services/backups/backup_service_type.dart';
Expand Down Expand Up @@ -83,4 +87,69 @@ void main() {
expect(NextcloudCloudService.sanitizeFolderName('..'), isNull);
});
});

group('NextcloudCloudService.describeError', () {
// The server is the user's own; none of these may survive into an exception message
// (those reach Crashlytics logs).
const String host = 'cloud.example.com';
final RequestOptions request = RequestOptions(path: 'https://$host/remote.php/dav/files/me/StoryPad');

void expectNoServer(String description) {
expect(description, isNot(contains(host)));
expect(description, isNot(contains('192.168.1.20')));
expect(description, isNot(contains('remote.php')));
}

test('a failed DNS lookup keeps only the error kinds and errno', () {
final error = DioException.connectionError(
requestOptions: request,
reason: "Failed host lookup: '$host'",
error: const SocketException(
"Failed host lookup: '$host'",
osError: OSError('nodename nor servname provided, or not known', 8),
),
);

// Proves the raw text would have leaked, so the test can't pass vacuously.
expect(error.toString(), contains(host));

final description = NextcloudCloudService.describeError(error);
expect(description, 'DioException(connectionError, SocketException(errno 8))');
expectNoServer(description);
});

test('a refused connection drops the address and port', () {
final error = SocketException(
'Connection refused',
address: InternetAddress('192.168.1.20'),
port: 443,
osError: const OSError('Connection refused', 61),
);

final description = NextcloudCloudService.describeError(error);
expect(description, 'SocketException(errno 61)');
expectNoServer(description);
});

test('a bad response keeps the status code', () {
final error = DioException.badResponse(
statusCode: 502,
requestOptions: request,
response: Response(requestOptions: request, statusCode: 502, statusMessage: 'Bad Gateway from $host'),
);

final description = NextcloudCloudService.describeError(error);
expect(description, 'DioException(badResponse, status 502)');
expectNoServer(description);
});

test('anything else is reduced to its type', () {
expect(NextcloudCloudService.describeError(TimeoutException('timed out talking to $host')), 'TimeoutException');
expect(
NextcloudCloudService.describeError(const HandshakeException('bad certificate for $host')),
'HandshakeException',
);
expect(NextcloudCloudService.describeError(null), 'Null');
});
});
}
Loading