Skip to content

Commit

Permalink
Merge pull request #469 from atsign-foundation/no_internet
Browse files Browse the repository at this point in the history
fix: update exception handling for AtLookup.findSecondary()
  • Loading branch information
srieteja authored Dec 5, 2023
2 parents af5d9ad + 073e4b0 commit 630179c
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 36 deletions.
28 changes: 17 additions & 11 deletions packages/at_auth/lib/src/at_auth_impl.dart
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@ class AtAuthImpl implements AtAuth {
}
if (atAuthKeys == null) {
throw AtAuthenticationException(
'keys either were not provided in the AtAuthRequest, or could not be read from provided keys file');
'keys either were not provided in the AtAuthRequest,'
' or could not be read from provided keys file');
}
enrollmentIdFromRequest ??= atAuthKeys.enrollmentId;
var pkamPrivateKey = atAuthKeys.apkamPrivateKey;
Expand All @@ -86,10 +87,12 @@ class AtAuthImpl implements AtAuth {
var pkamResponse = (await pkamAuthenticator!
.authenticate(enrollmentId: enrollmentIdFromRequest));
isPkamAuthenticated = pkamResponse.isSuccessful;
} on Exception catch (e) {
_logger.severe('Caught exception: $e');
} on AtException catch (e) {
_logger.severe('Caught $e');
throw AtAuthenticationException(
'Unable to authenticate- ${e.toString()}');
'Unable to authenticate | Cause: ${e.message}');
} on Exception catch (e) {
throw AtAuthenticationException('Unable to authenticate | Cause: $e');
}
_logger.finer(
'PKAM auth result: ${isPkamAuthenticated ? 'success' : 'failed'}');
Expand All @@ -113,7 +116,7 @@ class AtAuthImpl implements AtAuth {
if (!cramAuthResult.isSuccessful) {
throw AtAuthenticationException(
'Cram authentication failed. Please check the cram key'
' and try again \n(or) contact support@atsign.com');
' and try again (or) contact support@atsign.com');
}
//2. generate key pairs
var atAuthKeys = _generateKeyPairs(atOnboardingRequest.authMode,
Expand All @@ -127,7 +130,8 @@ class AtAuthImpl implements AtAuth {
//3. update pkam public key through enrollment or manually based on app preference
String? enrollmentIdFromServer;
if (atOnboardingRequest.enableEnrollment) {
// server will update the apkam public key during enrollment.So don't have to manually update in this scenario.
// server will update the apkam public key during enrollment.
// So don't have to manually update in this scenario.
enrollmentIdFromServer = await _sendOnboardingEnrollment(
atOnboardingRequest, atAuthKeys, atLookUp!);
atAuthKeys.enrollmentId = enrollmentIdFromServer;
Expand All @@ -142,20 +146,20 @@ class AtAuthImpl implements AtAuth {
_logger.finer('PkamPublicKey update result: $pkamUpdateResult');
}

//3. Close connection to server
//4. Close connection to server
try {
await (atLookUp as AtLookupImpl).close();
} on Exception catch (e) {
_logger.severe('error while closing connection to server: $e');
}

//4. Init _atLookUp again and attempt pkam auth
//5. Init _atLookUp again and attempt pkam auth
// atLookUp = AtLookupImpl(atOnboardingRequest.atSign,
// atOnboardingRequest.rootDomain, atOnboardingRequest.rootPort);
atLookUp!.atChops = atChops;

var isPkamAuthenticated = false;
//5. Do pkam auth
//6. Do pkam auth
pkamAuthenticator ??=
PkamAuthenticator(atOnboardingRequest.atSign, atLookUp!);
try {
Expand All @@ -169,7 +173,8 @@ class AtAuthImpl implements AtAuth {
throw AtAuthenticationException('Pkam auth returned false');
}

//5. If Pkam auth is success, update encryption public key to secondary and delete cram key from server
//7. If Pkam auth is success, update encryption public key to secondary
// and delete cram key from server
final encryptionPublicKey = atAuthKeys.defaultEncryptionPublicKey;
UpdateVerbBuilder updateBuilder = UpdateVerbBuilder()
..atKey = 'publickey'
Expand All @@ -178,7 +183,8 @@ class AtAuthImpl implements AtAuth {
..sharedBy = atOnboardingRequest.atSign;
String? encryptKeyUpdateResult = await atLookUp!.executeVerb(updateBuilder);
_logger.info('Encryption public key update result $encryptKeyUpdateResult');
// deleting cram secret from the keystore as cram auth is complete

//8. Delete cram secret from the keystore as cram auth is complete
DeleteVerbBuilder deleteBuilder = DeleteVerbBuilder()
..atKey = AtConstants.atCramSecret;
String? deleteResponse = await atLookUp!.executeVerb(deleteBuilder);
Expand Down
2 changes: 2 additions & 0 deletions packages/at_lookup/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
## 3.0.42
- fix: more informative exception messages
## 3.0.41
- feat: introduce methods cramAuthenticate and close into the AtLookup interface
- deprecate: authenticate_cram() from AtLookupImpl. [cramAuthenticate should be used instead]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,35 +150,37 @@ class SecondaryUrlFinder {
// then the secondary domain name will be deemed to be the portion of rootDomain after 'proxy:'
// and the secondary port will be deemed to be the rootPort
return '${_rootDomain.substring("proxy:".length)}:$_rootPort';
} else {
String? address;
for (int i = 0; i <= retryDelaysMillis.length; i++) {
try {
address = await _findSecondary(atSign);
return address;
} catch (e) {
if (i == retryDelaysMillis.length) {
_logger.severe('AtLookup.findSecondary $atSign failed with $e'
' : ${retryDelaysMillis.length + 1} failures, giving up');
rethrow;
} else {
_logger.info('AtLookup.findSecondary $atSign failed with $e'
' : will retry in ${retryDelaysMillis[i]} milliseconds');
await Future.delayed(Duration(milliseconds: retryDelaysMillis[i]));
}
}
String? address;
for (int i = 0; i <= retryDelaysMillis.length; i++) {
try {
address = await _findSecondary(atSign);
return address;
} catch (e) {
if (i < retryDelaysMillis.length) {
_logger.info('AtLookup.findSecondary for $atSign failed with $e'
' : will retry in ${retryDelaysMillis[i]} milliseconds');
await Future.delayed(Duration(milliseconds: retryDelaysMillis[i]));
continue;
}
_logger.severe('AtLookup.findSecondary for $atSign failed with $e'
' : ${retryDelaysMillis.length + 1} failures, giving up');
if (e is RootServerConnectivityException) {
throw RootServerConnectivityException(
'Unable to establish connection with root server.'
' Please check your internet connection and try again');
}
}
throw AtConnectException(
'CacheableSecondaryAddressFinder.SecondaryUrlFinder.findSecondaryUrl'
' : ${retryDelaysMillis.length + 1} failures, giving up');
}
throw AtConnectException('Could not fetch secondary address for $atSign :'
' ${retryDelaysMillis.length + 1} failures, giving up');
}

Future<String?> _findSecondary(String atsign) async {
String? response;
SecureSocket? socket;
try {
_logger.finer('AtLookup.findSecondary received atsign: $atsign');
_logger.finer('findSecondaryUrl: received atsign: $atsign');
if (atsign.startsWith('@')) atsign = atsign.replaceFirst('@', '');
var answer = '';
String? secondary;
Expand All @@ -188,7 +190,7 @@ class SecondaryUrlFinder {

socket = await _socketFactory.createSocket(
_rootDomain, '$_rootPort', SecureSocketConfig());

_logger.finer('findSecondaryUrl: connection to root server established');
// listen to the received data event stream
socket.listen((List<int> event) async {
_logger.finest('root socket listener received: $event');
Expand Down Expand Up @@ -221,7 +223,7 @@ class SecondaryUrlFinder {
await socket.flush();
socket.destroy();
_logger.finer(
'AtLookup.findSecondary got answer: $secondary and closing connection');
'findSecondaryUrl got answer: $secondary and closing connection');
return response;
}
}
Expand All @@ -230,8 +232,10 @@ class SecondaryUrlFinder {
socket.destroy();
throw AtTimeoutException('AtLookup.findSecondary timed out');
} on SocketException catch (se) {
_logger.severe(
'_findSecondary caught exception [$se] while connecting to root server url');
throw RootServerConnectivityException(
'_findSecondary caught exception [$se] while connecting to root server url $_rootDomain on port $_rootPort');
'Could not connect to Root Server at $_rootDomain:$_rootPort');
} on Exception catch (exception) {
_logger.severe('AtLookup.findSecondary connection to ' +
_rootDomain +
Expand All @@ -246,7 +250,7 @@ class SecondaryUrlFinder {
exception.toString());
} catch (error, stackTrace) {
_logger.severe(
'AtLookup.findSecondary connection to root server failed with error: $error');
'findSecondaryUrl: connection to root server failed with error: $error');
_logger.severe(stackTrace);
if (socket != null) {
socket.destroy();
Expand Down
2 changes: 1 addition & 1 deletion packages/at_lookup/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: at_lookup
description: A Dart library that contains the core commands that can be used with a secondary server (scan, update, lookup, llookup, plookup, etc.)
version: 3.0.38
version: 3.0.42
repository: https://github.com/atsign-foundation/at_libraries
homepage: https://atsign.com
documentation: https://docs.atsign.com/
Expand Down

0 comments on commit 630179c

Please sign in to comment.