diff --git a/packages/at_secondary_server/lib/src/connection/base_connection.dart b/packages/at_secondary_server/lib/src/connection/base_connection.dart index aa19915ae..be09f45b1 100644 --- a/packages/at_secondary_server/lib/src/connection/base_connection.dart +++ b/packages/at_secondary_server/lib/src/connection/base_connection.dart @@ -5,43 +5,36 @@ import 'package:at_server_spec/at_server_spec.dart'; import 'package:at_utils/at_logger.dart'; /// Base class for common socket operations -abstract class BaseConnection extends AtConnection { - late final Socket? _socket; +abstract class BaseSocketConnection extends AtConnection { + final T _socket; + @override late AtConnectionMetaData metaData; late AtSignLogger logger; - BaseConnection(Socket? socket) { + BaseSocketConnection(this._socket) { logger = AtSignLogger(runtimeType.toString()); - socket?.setOption(SocketOption.tcpNoDelay, true); - _socket = socket; - } - - @override - AtConnectionMetaData getMetaData() { - return metaData; + _socket.setOption(SocketOption.tcpNoDelay, true); } @override Future close() async { try { - var address = getSocket().remoteAddress; - var port = getSocket().remotePort; - await _socket!.close(); + var address = underlying.remoteAddress; + var port = underlying.remotePort; + await _socket.close(); logger.finer('$address:$port Disconnected'); - getMetaData().isClosed = true; + metaData.isClosed = true; } on Exception { - getMetaData().isStale = true; + metaData.isStale = true; // Ignore exception on a connection close } on Error { - getMetaData().isStale = true; + metaData.isStale = true; // Ignore error on a connection close } } @override - Socket getSocket() { - return _socket!; - } + T get underlying => _socket; @override void write(String data) { @@ -49,10 +42,10 @@ abstract class BaseConnection extends AtConnection { throw ConnectionInvalidException('Connection is invalid'); } try { - getSocket().write(data); - getMetaData().lastAccessed = DateTime.now().toUtc(); + underlying.write(data); + metaData.lastAccessed = DateTime.now().toUtc(); } on Exception catch (e) { - getMetaData().isStale = true; + metaData.isStale = true; logger.severe(e.toString()); throw AtIOException(e.toString()); } diff --git a/packages/at_secondary_server/lib/src/connection/connection_factory.dart b/packages/at_secondary_server/lib/src/connection/connection_factory.dart index aa6392723..486b1580b 100644 --- a/packages/at_secondary_server/lib/src/connection/connection_factory.dart +++ b/packages/at_secondary_server/lib/src/connection/connection_factory.dart @@ -3,5 +3,5 @@ import 'dart:io'; import 'package:at_server_spec/at_server_spec.dart'; abstract class AtConnectionFactory { - T createConnection(Socket socket, {String? sessionId}); + T createSocketConnection(Socket socket, {String? sessionId}); } diff --git a/packages/at_secondary_server/lib/src/connection/inbound/dummy_inbound_connection.dart b/packages/at_secondary_server/lib/src/connection/inbound/dummy_inbound_connection.dart index bafad5cc5..8b94a14e6 100644 --- a/packages/at_secondary_server/lib/src/connection/inbound/dummy_inbound_connection.dart +++ b/packages/at_secondary_server/lib/src/connection/inbound/dummy_inbound_connection.dart @@ -1,5 +1,3 @@ -import 'dart:io'; - import 'package:at_secondary/src/connection/inbound/inbound_connection_metadata.dart'; import 'package:at_secondary/src/server/at_secondary_config.dart'; import 'package:at_server_spec/at_server_spec.dart'; @@ -30,12 +28,10 @@ class DummyInboundConnection implements InboundConnection { } @override - AtConnectionMetaData getMetaData() { - return metadata; - } + AtConnectionMetaData get metaData => metadata; @override - Socket getSocket() { + dynamic get underlying { throw UnimplementedError( "DummyInboundConnection.getSocket is not implemented"); } @@ -59,9 +55,6 @@ class DummyInboundConnection implements InboundConnection { bool isStream = false; - @override - Socket? receiverSocket; - @override bool isRequestAllowed() { return true; diff --git a/packages/at_secondary_server/lib/src/connection/inbound/inbound_connection_impl.dart b/packages/at_secondary_server/lib/src/connection/inbound/inbound_connection_impl.dart index dafbae817..79167af11 100644 --- a/packages/at_secondary_server/lib/src/connection/inbound/inbound_connection_impl.dart +++ b/packages/at_secondary_server/lib/src/connection/inbound/inbound_connection_impl.dart @@ -14,7 +14,7 @@ import 'package:at_server_spec/at_server_spec.dart'; import 'dummy_inbound_connection.dart'; -class InboundConnectionImpl extends BaseConnection +class InboundConnectionImpl extends BaseSocketConnection implements InboundConnection { @override bool? isMonitor = false; @@ -55,7 +55,7 @@ class InboundConnectionImpl extends BaseConnection /// A list of timestamps representing the times when requests were made. late final Queue requestTimestampQueue; - InboundConnectionImpl(Socket? socket, String? sessionId, {this.owningPool}) + InboundConnectionImpl(T socket, String? sessionId, {this.owningPool}) : super(socket) { metaData = InboundConnectionMetadata() ..sessionID = sessionId @@ -99,9 +99,9 @@ class InboundConnectionImpl extends BaseConnection // Without the above check, we were getting runtime errors on the next check // since DummyInboundConnection.getSocket throws a "not implemented" error - if (getSocket().remoteAddress.address == - connection.getSocket().remoteAddress.address && - getSocket().remotePort == connection.getSocket().remotePort) { + if (underlying.remoteAddress.address == + connection.underlying.remoteAddress.address && + underlying.remotePort == connection.underlying.remotePort) { return true; } @@ -111,7 +111,7 @@ class InboundConnectionImpl extends BaseConnection /// Returning true indicates to the caller that this connection **can** be closed if needed @override bool isInValid() { - if (getMetaData().isClosed || getMetaData().isStale) { + if (metaData.isClosed || metaData.isStale) { return true; } @@ -134,7 +134,7 @@ class InboundConnectionImpl extends BaseConnection // We're past the low water mark. Let's use some fancier logic to mark connections invalid increasingly aggressively. double idleTimeReductionFactor = 1 - (numConnectionsOverLwm / (poolMaxConnections - lowWaterMark)); - if (!getMetaData().isAuthenticated && !getMetaData().isPolAuthenticated) { + if (!metaData.isAuthenticated && !metaData.isPolAuthenticated) { // For **unauthenticated** connections, we deem invalid if idle time is greater than // ((maxIdleTime - minIdleTime) * (1 - numConnectionsOverLwm / (maxConnections - connectionsLowWaterMark))) + minIdleTime // @@ -182,9 +182,9 @@ class InboundConnectionImpl extends BaseConnection /// Get the idle time of the inbound connection since last write operation int _getIdleTimeMillis() { - var lastAccessedTime = getMetaData().lastAccessed; + var lastAccessedTime = metaData.lastAccessed; // if lastAccessedTime is not set, use created time - lastAccessedTime ??= getMetaData().created; + lastAccessedTime ??= metaData.created; var currentTime = DateTime.now().toUtc(); return currentTime.difference(lastAccessedTime!).inMilliseconds; } @@ -193,7 +193,7 @@ class InboundConnectionImpl extends BaseConnection /// false otherwise bool _idleForLongerThanMax() { var idleTimeMillis = _getIdleTimeMillis(); - if (getMetaData().isAuthenticated || getMetaData().isPolAuthenticated) { + if (metaData.isAuthenticated || metaData.isPolAuthenticated) { return idleTimeMillis > authenticatedMaxAllowableIdleTimeMillis; } else { return idleTimeMillis > unauthenticatedMaxAllowableIdleTimeMillis; @@ -207,9 +207,6 @@ class InboundConnectionImpl extends BaseConnection listener.listen(callback, streamCallBack); } - @override - Socket? receiverSocket; - bool? isStream; @override @@ -219,22 +216,22 @@ class InboundConnectionImpl extends BaseConnection // (Note however that, at time of writing, outbound_connection_impl also calls socket.destroy) // Some defensive code just in case we accidentally call close multiple times - if (getMetaData().isClosed) { + if (metaData.isClosed) { return; } try { - var address = getSocket().remoteAddress; - var port = getSocket().remotePort; - getSocket().destroy(); + var address = underlying.remoteAddress; + var port = underlying.remotePort; + underlying.destroy(); logger.finer(logger.getAtConnectionLogMessage( - getMetaData(), '$address:$port Disconnected')); - getMetaData().isClosed = true; + metaData, '$address:$port Disconnected')); + metaData.isClosed = true; } on Exception { - getMetaData().isStale = true; + metaData.isStale = true; // Ignore exception on a connection close } on Error { - getMetaData().isStale = true; + metaData.isStale = true; // Ignore error on a connection close } } @@ -244,7 +241,7 @@ class InboundConnectionImpl extends BaseConnection super.write(data); if (metaData is InboundConnectionMetadata) { logger.info(logger.getAtConnectionLogMessage( - metaData, 'SENT: ${BaseConnection.truncateForLogging(data)}')); + metaData, 'SENT: ${BaseSocketConnection.truncateForLogging(data)}')); } } diff --git a/packages/at_secondary_server/lib/src/connection/inbound/inbound_connection_manager.dart b/packages/at_secondary_server/lib/src/connection/inbound/inbound_connection_manager.dart index 41f3f2b05..6a9e2dee9 100644 --- a/packages/at_secondary_server/lib/src/connection/inbound/inbound_connection_manager.dart +++ b/packages/at_secondary_server/lib/src/connection/inbound/inbound_connection_manager.dart @@ -29,7 +29,7 @@ class InboundConnectionManager implements AtConnectionFactory { /// @param sessionId - current sessionId /// Throws a [InboundConnectionLimitException] if pool doesn't have capacity @override - InboundConnection createConnection(Socket? socket, {String? sessionId}) { + InboundConnection createSocketConnection(Socket socket, {String? sessionId}) { if (!_isInitialized) { init(defaultPoolSize); } diff --git a/packages/at_secondary_server/lib/src/connection/inbound/inbound_message_listener.dart b/packages/at_secondary_server/lib/src/connection/inbound/inbound_message_listener.dart index 8d91026c4..e7c1e1951 100644 --- a/packages/at_secondary_server/lib/src/connection/inbound/inbound_message_listener.dart +++ b/packages/at_secondary_server/lib/src/connection/inbound/inbound_message_listener.dart @@ -25,20 +25,16 @@ class InboundMessageListener { void listen(callback, streamCallBack) { onStreamCallBack = streamCallBack; onBufferEndCallBack = callback; - connection.getSocket().listen(_messageHandler, + connection.underlying.listen(_messageHandler, onDone: _finishedHandler, onError: _errorHandler); - connection - .getSocket() - .done - .onError((error, stackTrace) => (_errorHandler(error))); - connection.getMetaData().isListening = true; + connection.metaData.isListening = true; } /// Handles messages on the inbound client's connection and calls the verb executor /// Closes the inbound connection in case of any error. Future _messageHandler(data) async { //ignore the data read if the connection is stale or closed - if (connection.getMetaData().isStale || connection.getMetaData().isClosed) { + if (connection.metaData.isStale || connection.metaData.isClosed) { //clear buffer as data is redundant _buffer.clear(); return; @@ -46,14 +42,14 @@ class InboundMessageListener { // If connection is invalid, throws ConnectionInvalidException and closes the connection if (connection.isInValid()) { _buffer.clear(); - logger.info(logger.getAtConnectionLogMessage(connection.getMetaData(), + logger.info(logger.getAtConnectionLogMessage(connection.metaData, 'Inbound connection is invalid. Closing the connection')); await GlobalExceptionHandler.getInstance().handle( ConnectionInvalidException('Connection is invalid'), atConnection: connection); return; } - if (connection.getMetaData().isStream) { + if (connection.metaData.isStream) { await onStreamCallBack(data, connection); return; } @@ -76,8 +72,8 @@ class InboundMessageListener { //decode only when end of buffer is reached var command = utf8.decode(_buffer.getData()); command = command.trim(); - logger.info(logger.getAtConnectionLogMessage(connection.getMetaData(), - 'RCVD: ${BaseConnection.truncateForLogging(command)}')); + logger.info(logger.getAtConnectionLogMessage(connection.metaData, + 'RCVD: ${BaseSocketConnection.truncateForLogging(command)}')); // if command is '@exit', close the connection. if (command == '@exit') { await _finishedHandler(); diff --git a/packages/at_secondary_server/lib/src/connection/outbound/outbound_client.dart b/packages/at_secondary_server/lib/src/connection/outbound/outbound_client.dart index b26fc5f04..36be14c17 100644 --- a/packages/at_secondary_server/lib/src/connection/outbound/outbound_client.dart +++ b/packages/at_secondary_server/lib/src/connection/outbound/outbound_client.dart @@ -26,7 +26,7 @@ class OutboundClient { String? toHost; String? toPort; - OutboundConnection? outboundConnection; + OutboundSocketConnection? outboundConnection; bool isConnectionCreated = false; bool isHandShakeDone = false; DateTime lastUsed = DateTime.now(); @@ -374,13 +374,13 @@ class OutboundClient { } abstract class OutboundConnectionFactory { - Future createOutboundConnection( + Future createOutboundConnection( String host, int port, String toAtSign); } class DefaultOutboundConnectionFactory implements OutboundConnectionFactory { @override - Future createOutboundConnection( + Future createOutboundConnection( String host, int port, String toAtSign) async { AtSecurityContextImpl securityContext = AtSecurityContextImpl(); SecurityContext secConConnect = SecurityContext(); diff --git a/packages/at_secondary_server/lib/src/connection/outbound/outbound_connection.dart b/packages/at_secondary_server/lib/src/connection/outbound/outbound_connection.dart index 56e86cff5..a0596b0b4 100644 --- a/packages/at_secondary_server/lib/src/connection/outbound/outbound_connection.dart +++ b/packages/at_secondary_server/lib/src/connection/outbound/outbound_connection.dart @@ -3,12 +3,13 @@ import 'dart:io'; import 'package:at_secondary/src/connection/base_connection.dart'; import 'package:at_server_spec/at_server_spec.dart'; -// Represent an OutboundConnection to another user's secondary server. -abstract class OutboundConnection extends BaseConnection { - OutboundConnection(Socket? socket) : super(socket); +// Represent an OutboundConnection to another atServer +abstract class OutboundSocketConnection + extends BaseSocketConnection { + OutboundSocketConnection(T socket) : super(socket); } -/// Metadata information for [OutboundConnection] +/// Metadata information for [OutboundSocketConnection] class OutboundConnectionMetadata extends AtConnectionMetaData { String? toAtSign; bool isHandShakeSuccess = false; diff --git a/packages/at_secondary_server/lib/src/connection/outbound/outbound_connection_impl.dart b/packages/at_secondary_server/lib/src/connection/outbound/outbound_connection_impl.dart index da67ef428..daf544ad2 100644 --- a/packages/at_secondary_server/lib/src/connection/outbound/outbound_connection_impl.dart +++ b/packages/at_secondary_server/lib/src/connection/outbound/outbound_connection_impl.dart @@ -5,11 +5,12 @@ import 'package:at_secondary/src/server/at_secondary_impl.dart'; import 'package:at_secondary/src/utils/logging_util.dart'; import 'package:uuid/uuid.dart'; -class OutboundConnectionImpl extends OutboundConnection { +class OutboundConnectionImpl + extends OutboundSocketConnection { static int? outboundIdleTime = AtSecondaryServerImpl.getInstance().serverContext!.outboundIdleTimeMillis; - OutboundConnectionImpl(Socket? socket, String? toAtSign) : super(socket) { + OutboundConnectionImpl(T socket, String? toAtSign) : super(socket) { var sessionId = '_${Uuid().v4()}'; metaData = OutboundConnectionMetadata() ..sessionID = sessionId @@ -19,8 +20,8 @@ class OutboundConnectionImpl extends OutboundConnection { } int _getIdleTimeMillis() { - var lastAccessedTime = getMetaData().lastAccessed; - lastAccessedTime ??= getMetaData().created; + var lastAccessedTime = metaData.lastAccessed; + lastAccessedTime ??= metaData.created; var currentTime = DateTime.now().toUtc(); return currentTime.difference(lastAccessedTime!).inMilliseconds; } @@ -31,7 +32,7 @@ class OutboundConnectionImpl extends OutboundConnection { @override bool isInValid() { - return _isIdle() || getMetaData().isClosed || getMetaData().isStale; + return _isIdle() || metaData.isClosed || metaData.isStale; } @override @@ -40,22 +41,22 @@ class OutboundConnectionImpl extends OutboundConnection { // behaviour for outbound connections for now, not inbound connections // Some defensive code just in case we accidentally call close multiple times - if (getMetaData().isClosed) { + if (metaData.isClosed) { return; } try { - var socket = getSocket(); + var socket = underlying; var address = socket.remoteAddress; var port = socket.remotePort; socket.destroy(); logger.finer('$address:$port Disconnected'); - getMetaData().isClosed = true; + metaData.isClosed = true; } on Exception { - getMetaData().isStale = true; + metaData.isStale = true; // Ignore exception on a connection close } on Error { - getMetaData().isStale = true; + metaData.isStale = true; // Ignore error on a connection close } } @@ -64,6 +65,6 @@ class OutboundConnectionImpl extends OutboundConnection { void write(String data) { super.write(data); logger.info(logger.getAtConnectionLogMessage( - getMetaData(), 'SENT: ${BaseConnection.truncateForLogging(data)}')); + metaData, 'SENT: ${BaseSocketConnection.truncateForLogging(data)}')); } } diff --git a/packages/at_secondary_server/lib/src/connection/outbound/outbound_message_listener.dart b/packages/at_secondary_server/lib/src/connection/outbound/outbound_message_listener.dart index 230db4de6..298ac1f7a 100644 --- a/packages/at_secondary_server/lib/src/connection/outbound/outbound_message_listener.dart +++ b/packages/at_secondary_server/lib/src/connection/outbound/outbound_message_listener.dart @@ -18,17 +18,17 @@ class OutboundMessageListener { /// Listens to the underlying connection's socket if the connection is created. /// @throws [AtConnectException] if the connection is not yet created void listen() async { - outboundClient.outboundConnection?.getSocket().listen(_messageHandler, + outboundClient.outboundConnection?.underlying.listen(_messageHandler, onDone: _finishedHandler, onError: _errorHandler); - outboundClient.outboundConnection?.getMetaData().isListening = true; + outboundClient.outboundConnection?.metaData.isListening = true; } /// Handles responses from the remote secondary, adds to [_queue] for processing in [read] method /// Throws a [BufferOverFlowException] if buffer is unable to hold incoming data Future _messageHandler(data) async { //ignore the data if connection is closed or stale - if (outboundClient.outboundConnection!.getMetaData().isStale || - outboundClient.outboundConnection!.getMetaData().isClosed) { + if (outboundClient.outboundConnection!.metaData.isStale || + outboundClient.outboundConnection!.metaData.isClosed) { _buffer.clear(); return; } @@ -61,7 +61,7 @@ class OutboundMessageListener { _buffer.clear(); logger.info(logger.getAtConnectionLogMessage( outboundClient.outboundConnection!.metaData, - 'RCVD: ${BaseConnection.truncateForLogging(result)}')); + 'RCVD: ${BaseSocketConnection.truncateForLogging(result)}')); _queue.add(result); } } diff --git a/packages/at_secondary_server/lib/src/exception/global_exception_handler.dart b/packages/at_secondary_server/lib/src/exception/global_exception_handler.dart index c3faead04..a9088162e 100644 --- a/packages/at_secondary_server/lib/src/exception/global_exception_handler.dart +++ b/packages/at_secondary_server/lib/src/exception/global_exception_handler.dart @@ -121,11 +121,10 @@ class GlobalExceptionHandler { // For example if @alice performs lookup verb to @bob and @bob returns key not found exception // add error description only on @alice (not on @bob) // When connecting to other secondaries for lookup verb, a pol authenticated connection - // is established. atConnection.getMetaData().isPolAuthenticated is set to true. + // is established. atConnection.metaData.isPolAuthenticated is set to true. // When a user connects to his own secondary, an authenticate connection is created. - // atConnection.getMetaData().isAuthenticated is set to true. - if (exception is AtException && - atConnection.getMetaData().isAuthenticated) { + // atConnection.metaData.isAuthenticated is set to true. + if (exception is AtException && atConnection.metaData.isAuthenticated) { errorDescription = '${getErrorDescription(errorCode)} : ${exception.message}'; } else { @@ -137,7 +136,7 @@ class GlobalExceptionHandler { } String _getPrompt(AtConnection atConnection) { - var isAuthenticated = atConnection.getMetaData().isAuthenticated; + var isAuthenticated = atConnection.metaData.isAuthenticated; var atSign = AtSecondaryServerImpl.getInstance().currentAtSign; var prompt = isAuthenticated ? '$atSign@' : '@'; return prompt; @@ -153,13 +152,13 @@ class GlobalExceptionHandler { void _writeToSocket(AtConnection atConnection, String prompt, String? errorCode, String errorDescription) { - if (atConnection.getMetaData().clientVersion == + if (atConnection.metaData.clientVersion == AtConnectionMetaData.clientVersionNotAvailable) { atConnection.write('error:$errorCode-$errorDescription\n$prompt'); return; } // The JSON encoding of error message is supported by the client versions greater than 3.0.37 - if (Version.parse(atConnection.getMetaData().clientVersion) > + if (Version.parse(atConnection.metaData.clientVersion) > Version(3, 0, 37)) { logger.info( 'Client version supports json encoding.. returning Json encoded error message'); diff --git a/packages/at_secondary_server/lib/src/notification/resource_manager.dart b/packages/at_secondary_server/lib/src/notification/resource_manager.dart index 0d5bf2fc4..b7d0c9baa 100644 --- a/packages/at_secondary_server/lib/src/notification/resource_manager.dart +++ b/packages/at_secondary_server/lib/src/notification/resource_manager.dart @@ -140,7 +140,7 @@ class ResourceManager { } on Exception catch (e) { var msg = 'Connection failed to $toAtSign with exception: $e'; logger.warning(msg); - outBoundClient.inboundConnection.getMetaData().isClosed = true; + outBoundClient.inboundConnection.metaData.isClosed = true; throw ConnectionInvalidException(msg); } } diff --git a/packages/at_secondary_server/lib/src/server/at_secondary_impl.dart b/packages/at_secondary_server/lib/src/server/at_secondary_impl.dart index 7ba6feca5..a699958f8 100644 --- a/packages/at_secondary_server/lib/src/server/at_secondary_impl.dart +++ b/packages/at_secondary_server/lib/src/server/at_secondary_impl.dart @@ -448,8 +448,8 @@ class AtSecondaryServerImpl implements AtSecondaryServer { logger.finer( 'In _listen - clientSocket.peerCertificate : ${clientSocket.peerCertificate}'); var inBoundConnectionManager = InboundConnectionManager.getInstance(); - connection = inBoundConnectionManager.createConnection(clientSocket, - sessionId: sessionID); + connection = inBoundConnectionManager + .createSocketConnection(clientSocket, sessionId: sessionID); connection.acceptRequests(_executeVerbCallBack, _streamCallBack); connection.write('@'); } on InboundConnectionLimitException catch (e) { @@ -515,7 +515,7 @@ class AtSecondaryServerImpl implements AtSecondaryServer { void _executeVerbCallBack( String command, InboundConnection connection) async { logger.finer(logger.getAtConnectionLogMessage( - connection.getMetaData(), 'inside _executeVerbCallBack: $command')); + connection.metaData, 'inside _executeVerbCallBack: $command')); try { if (_isPaused) { await GlobalExceptionHandler.getInstance().handle( @@ -546,9 +546,9 @@ class AtSecondaryServerImpl implements AtSecondaryServer { } void _streamCallBack(List data, InboundConnection sender) { - var streamId = sender.getMetaData().streamId; + var streamId = sender.metaData.streamId; logger.finer(logger.getAtConnectionLogMessage( - sender.getMetaData(), 'stream id:$streamId')); + sender.metaData, 'stream id:$streamId')); if (_isPaused) { GlobalExceptionHandler.getInstance().handle( ServerIsPausedException( @@ -557,7 +557,7 @@ class AtSecondaryServerImpl implements AtSecondaryServer { return; } if (streamId != null) { - StreamManager.receiverSocketMap[streamId]!.getSocket().add(data); + StreamManager.receiverSocketMap[streamId]!.underlying.add(data); } } diff --git a/packages/at_secondary_server/lib/src/verb/handler/abstract_update_verb_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/abstract_update_verb_handler.dart index 0089bab46..f34699868 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/abstract_update_verb_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/abstract_update_verb_handler.dart @@ -66,7 +66,7 @@ abstract class AbstractUpdateVerbHandler extends ChangeVerbHandler { atData.data = value; final enrollApprovalId = - (atConnection.getMetaData() as InboundConnectionMetadata).enrollmentId; + (atConnection.metaData as InboundConnectionMetadata).enrollmentId; bool isAuthorized = true; // for legacy clients allow access by default if (enrollApprovalId != null) { if (atKey.contains('.')) { diff --git a/packages/at_secondary_server/lib/src/verb/handler/abstract_verb_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/abstract_verb_handler.dart index 53b3b816d..5594c8b90 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/abstract_verb_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/abstract_verb_handler.dart @@ -46,7 +46,7 @@ abstract class AbstractVerbHandler implements VerbHandler { Future processInternal( String command, InboundConnection atConnection) async { var response = Response(); - var atConnectionMetadata = atConnection.getMetaData(); + var atConnectionMetadata = atConnection.metaData; if (getVerb().requiresAuth() && !atConnectionMetadata.isAuthenticated) { throw UnAuthenticatedException('Command cannot be executed without auth'); } diff --git a/packages/at_secondary_server/lib/src/verb/handler/cram_verb_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/cram_verb_handler.dart index 4a4fee762..d92ca316e 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/cram_verb_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/cram_verb_handler.dart @@ -29,7 +29,7 @@ class CramVerbHandler extends AbstractVerbHandler { Response response, HashMap verbParams, InboundConnection atConnection) async { - var atConnectionMetadata = atConnection.getMetaData(); + var atConnectionMetadata = atConnection.metaData; var sessionID = atConnectionMetadata.sessionID; var digest = verbParams[AtConstants.atDigest]; var atSign = AtSecondaryServerImpl.getInstance().currentAtSign; diff --git a/packages/at_secondary_server/lib/src/verb/handler/delete_verb_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/delete_verb_handler.dart index 3c8081011..8a65b1fe7 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/delete_verb_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/delete_verb_handler.dart @@ -94,7 +94,7 @@ class DeleteVerbHandler extends ChangeVerbHandler { AtConstants.atCramSecretDeleted, AtData()..data = 'true'); } final enrollApprovalId = - (atConnection.getMetaData() as InboundConnectionMetadata).enrollmentId; + (atConnection.metaData as InboundConnectionMetadata).enrollmentId; bool isAuthorized = true; // for legacy clients allow access by default if (enrollApprovalId != null) { isAuthorized = await super.isAuthorized(enrollApprovalId, keyNamespace); diff --git a/packages/at_secondary_server/lib/src/verb/handler/enroll_verb_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/enroll_verb_handler.dart index 4e1749cfc..6f71854df 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/enroll_verb_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/enroll_verb_handler.dart @@ -60,7 +60,7 @@ class EnrollVerbHandler extends AbstractVerbHandler { final operation = verbParams['operation']; final currentAtSign = AtSecondaryServerImpl.getInstance().currentAtSign; //Approve, deny, revoke or list enrollments only on authenticated connections - if (operation != 'request' && !atConnection.getMetaData().isAuthenticated) { + if (operation != 'request' && !atConnection.metaData.isAuthenticated) { throw UnAuthenticatedException( 'Cannot $operation enrollment without authentication'); } @@ -137,7 +137,7 @@ class EnrollVerbHandler extends AbstractVerbHandler { // OTP is sent only in enrollment request which is submitted on // unauthenticated connection. - if (atConnection.getMetaData().isAuthenticated == false) { + if (atConnection.metaData.isAuthenticated == false) { var isValid = await isOTPValid(enrollParams.otp); if (!isValid) { _lastInvalidOtpReceivedInMills = @@ -167,22 +167,22 @@ class EnrollVerbHandler extends AbstractVerbHandler { responseJson['enrollmentId'] = newEnrollmentId; final enrollmentValue = EnrollDataStoreValue( - atConnection.getMetaData().sessionID!, + atConnection.metaData.sessionID!, enrollParams.appName!, enrollParams.deviceName!, enrollParams.apkamPublicKey!); enrollmentValue.namespaces = enrollNamespaces; enrollmentValue.requestType = EnrollRequestType.newEnrollment; AtData enrollData; - if (atConnection.getMetaData().authType != null && - atConnection.getMetaData().authType == AuthType.cram) { + if (atConnection.metaData.authType != null && + atConnection.metaData.authType == AuthType.cram) { // auto approve request from connection that is CRAM authenticated. enrollNamespaces[enrollManageNamespace] = 'rw'; enrollNamespaces[allNamespaces] = 'rw'; enrollmentValue.approval = EnrollApproval(EnrollmentStatus.approved.name); responseJson['status'] = 'approved'; final inboundConnectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; inboundConnectionMetadata.enrollmentId = newEnrollmentId; // Store default encryption private key and self encryption key(both encrypted) // for future retrieval @@ -314,7 +314,7 @@ class EnrollVerbHandler extends AbstractVerbHandler { AtConnection atConnection, String currentAtSign) async { Map> enrollmentRequestsMap = {}; String? enrollApprovalId = - (atConnection.getMetaData() as InboundConnectionMetadata).enrollmentId; + (atConnection.metaData as InboundConnectionMetadata).enrollmentId; List enrollmentKeysList = keyStore.getKeys(regex: newEnrollmentKeyPattern) as List; // If connection is authenticated via legacy PKAM, then enrollApprovalId is null. diff --git a/packages/at_secondary_server/lib/src/verb/handler/from_verb_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/from_verb_handler.dart index 75b4806f2..292febcfb 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/from_verb_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/from_verb_handler.dart @@ -47,7 +47,7 @@ class FromVerbHandler extends AbstractVerbHandler { currentAtSign); atConnection.initiatedBy = currentAtSign; var atConnectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; var fromAtSign = verbParams[AtConstants.atSign]; if (verbParams[AtConstants.clientConfig] != null && @@ -120,14 +120,13 @@ class FromVerbHandler extends AbstractVerbHandler { logger.finer('_verifyFromAtSign secondaryUrl : $secondaryUrl'); var secondaryInfo = SecondaryUtil.getSecondaryInfo(secondaryUrl); var host = secondaryInfo[0]; - var secSocket = atConnection.getSocket() as SecureSocket; + var secSocket = atConnection.underlying as SecureSocket; logger.finer('secSocket : $secSocket'); var cn = secSocket.peerCertificate; logger.finer('CN : $cn'); if (cn == null) { - logger.finer( - 'CN is null.stream flag ${atConnection.getMetaData().isStream}'); - return atConnection.getMetaData().isStream; + logger.finer('CN is null.stream flag ${atConnection.metaData.isStream}'); + return atConnection.metaData.isStream; } if (clientCertificateRequired!) { @@ -147,12 +146,13 @@ class FromVerbHandler extends AbstractVerbHandler { var x509Pem = cn.pem; // test with an internet available certificate to ensure we are picking out the SAN and not the CN var data = X509Utils.x509CertificateFromPem(x509Pem); - var subjectAlternativeName = data.subjectAlternativNames!; + var subjectAlternativeName = + data.tbsCertificate?.extensions?.subjectAlternativNames ?? []; logger.finer('SAN: $subjectAlternativeName'); if (subjectAlternativeName.contains(host)) { return true; } - var commonName = data.subject['2.5.4.3']!; + var commonName = data.tbsCertificate?.subject['2.5.4.3'] ?? ''; logger.finer('CN: $commonName'); if (commonName.contains(host)) { return true; diff --git a/packages/at_secondary_server/lib/src/verb/handler/info_verb_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/info_verb_handler.dart index 4b12570b6..e848469b5 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/info_verb_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/info_verb_handler.dart @@ -35,7 +35,7 @@ class InfoVerbHandler extends AbstractVerbHandler { Map infoMap = {}; String? apkamMetadataKey; String? result; - InboundConnectionMetadata atConnectionMetadata = atConnection.getMetaData() + InboundConnectionMetadata atConnectionMetadata = atConnection.metaData as InboundConnectionMetadata; // structure of what is returned is documented in the [Info] verb in at_server_spec var atSign = AtSecondaryServerImpl.getInstance().currentAtSign; diff --git a/packages/at_secondary_server/lib/src/verb/handler/keys_verb_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/keys_verb_handler.dart index c9bafc7d4..95023477e 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/keys_verb_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/keys_verb_handler.dart @@ -33,8 +33,7 @@ class KeysVerbHandler extends AbstractVerbHandler { final keyVisibility = verbParams[AtConstants.visibility]; final atSign = AtSecondaryServerImpl.getInstance().currentAtSign; bool hasManageAccess = false; - var connectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + var connectionMetadata = atConnection.metaData as InboundConnectionMetadata; final enrollIdFromMetadata = connectionMetadata.enrollmentId; if (enrollIdFromMetadata == null) { throw AtEnrollmentException( diff --git a/packages/at_secondary_server/lib/src/verb/handler/local_lookup_verb_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/local_lookup_verb_handler.dart index 0257be20b..210802297 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/local_lookup_verb_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/local_lookup_verb_handler.dart @@ -61,7 +61,7 @@ class LocalLookupVerbHandler extends AbstractVerbHandler { key = 'cached:$key'; } final enrollmentId = - (atConnection.getMetaData() as InboundConnectionMetadata).enrollmentId; + (atConnection.metaData as InboundConnectionMetadata).enrollmentId; bool isAuthorized = true; // for legacy clients allow access by default if (!isPublic && enrollmentId != null && keyNamespace != null) { isAuthorized = await super.isAuthorized(enrollmentId, keyNamespace); diff --git a/packages/at_secondary_server/lib/src/verb/handler/lookup_verb_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/lookup_verb_handler.dart index 264eeb89a..b647fab24 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/lookup_verb_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/lookup_verb_handler.dart @@ -43,7 +43,7 @@ class LookupVerbHandler extends AbstractVerbHandler { HashMap verbParams, InboundConnection atConnection) async { var atConnectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; var thisServersAtSign = cacheManager.atSign; var atAccessLog = await AtAccessLogManagerImpl.getInstance() .getAccessLog(thisServersAtSign); @@ -99,7 +99,7 @@ class LookupVerbHandler extends AbstractVerbHandler { bool isAuthorized = await _isAuthorizedToViewData(atConnection, lookupKey); if (!isAuthorized) { throw UnAuthorizedException( - 'Enrollment Id: ${(atConnection.getMetaData() as InboundConnectionMetadata).enrollmentId} is not authorized for lookup operation on the key: $lookupKey'); + 'Enrollment Id: ${(atConnection.metaData as InboundConnectionMetadata).enrollmentId} is not authorized for lookup operation on the key: $lookupKey'); } if (keyOwnersAtSign == thisServersAtSign) { // We're looking up data owned by this server's atSign @@ -272,7 +272,7 @@ class LookupVerbHandler extends AbstractVerbHandler { return true; } final enrollmentId = - (atConnection.getMetaData() as InboundConnectionMetadata).enrollmentId; + (atConnection.metaData as InboundConnectionMetadata).enrollmentId; bool isAuthorized = true; // for legacy clients allow access by default if (enrollmentId != null) { // Extract namespace from the key - 'some_key.wavi@alice' where "wavi" is diff --git a/packages/at_secondary_server/lib/src/verb/handler/monitor_verb_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/monitor_verb_handler.dart index 2497d98f9..59f8ee0cf 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/monitor_verb_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/monitor_verb_handler.dart @@ -40,7 +40,7 @@ class MonitorVerbHandler extends AbstractVerbHandler { Response response, HashMap verbParams, InboundConnection atConnection) async { - if (!atConnection.getMetaData().isAuthenticated) { + if (!atConnection.metaData.isAuthenticated) { throw UnAuthenticatedException( 'Failed to execute verb. monitor requires authentication'); } @@ -88,8 +88,7 @@ class MonitorVerbHandler extends AbstractVerbHandler { /// matches the pattern. Future _sendNotificationToClient(Notification notification) async { // If enrollmentId is null, then connection is authenticated via PKAM - if ((atConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId == + if ((atConnection.metaData as InboundConnectionMetadata).enrollmentId == null) { _sendLegacyNotification(notification); } else { @@ -130,7 +129,7 @@ class MonitorVerbHandler extends AbstractVerbHandler { Notification notification) async { // Fetch namespaces that are associated with the enrollmentId. var enrollmentKey = - '${(atConnection.getMetaData() as InboundConnectionMetadata).enrollmentId}.$newEnrollmentKeyPattern.$enrollManageNamespace${AtSecondaryServerImpl.getInstance().currentAtSign}'; + '${(atConnection.metaData as InboundConnectionMetadata).enrollmentId}.$newEnrollmentKeyPattern.$enrollManageNamespace${AtSecondaryServerImpl.getInstance().currentAtSign}'; EnrollDataStoreValue enrollDataStoreValue = await getEnrollDataStoreValue(enrollmentKey); // When an enrollment is revoked, avoid sending notifications to the @@ -138,19 +137,19 @@ class MonitorVerbHandler extends AbstractVerbHandler { if (enrollDataStoreValue.approval!.state != EnrollmentStatus.approved.name) { logger.finer( - 'EnrollmentId ${(atConnection.getMetaData() as InboundConnectionMetadata).enrollmentId} is not approved. Failed to send notifications'); + 'EnrollmentId ${(atConnection.metaData as InboundConnectionMetadata).enrollmentId} is not approved. Failed to send notifications'); return; } if (enrollDataStoreValue.namespaces.isEmpty) { logger.finer('No namespaces are enrolled for the enrollmentId:' - ' ${(atConnection.getMetaData() as InboundConnectionMetadata).enrollmentId}'); + ' ${(atConnection.metaData as InboundConnectionMetadata).enrollmentId}'); return; } // If notification does not contain ".", it indicates namespace is not present. // Do nothing. if (!notification.notification!.contains('.')) { logger.finest( - 'For enrollmentId: ${(atConnection.getMetaData() as InboundConnectionMetadata).enrollmentId}' + 'For enrollmentId: ${(atConnection.metaData as InboundConnectionMetadata).enrollmentId}' 'Failed to send notification because the key ${notification.notification} do not contain namespace'); return; } diff --git a/packages/at_secondary_server/lib/src/verb/handler/notify_list_verb_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/notify_list_verb_handler.dart index 1d8f36178..3c836b51d 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/notify_list_verb_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/notify_list_verb_handler.dart @@ -54,7 +54,7 @@ class NotifyListVerbHandler extends AbstractVerbHandler { throw IllegalArgumentException('Invalid date format'); } var atConnectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; var responseList = []; // If connection is authenticated, gets the received notifications of current atsign diff --git a/packages/at_secondary_server/lib/src/verb/handler/notify_verb_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/notify_verb_handler.dart index 855d3a7f5..5e155af60 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/notify_verb_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/notify_verb_handler.dart @@ -66,7 +66,7 @@ class NotifyVerbHandler extends AbstractVerbHandler { await processNotificationMutex.acquire(); atNotificationBuilder.reset(); var atConnectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; _validateNotifyVerbParams(verbParams); var currentAtSign = AtSecondaryServerImpl.getInstance().currentAtSign; // If '@' is missing before an atSign, the formatAtSign method prefixes '@' before atSign. @@ -275,11 +275,11 @@ class NotifyVerbHandler extends AbstractVerbHandler { HashMap verbParams, // fromAtSign represents who sent the notification. // on sender, fromAtSign is same as currentAtSign and on receiver side, - // If notification is of messageType "key" fromAtSign is fetched from verbparams + // If notification is of messageType "key" fromAtSign is fetched from verbParams // If notification is of messageType "text" fromAtSign is fetched from atConnectionMetadata.fromAtSign {String fromAtSign = ''}) { atNotificationBuilder = atNotificationBuilder - ..toAtSign = AtUtils.formatAtSign(verbParams[AtConstants.forAtSign]) + ..toAtSign = AtUtils.fixAtSign(verbParams[AtConstants.forAtSign] ?? '') ..fromAtSign = fromAtSign ..notificationDateTime = DateTime.now().toUtcMillisecondsPrecision() ..notification = _getFullFormedAtKey( @@ -291,7 +291,7 @@ class NotifyVerbHandler extends AbstractVerbHandler { ..notificationStatus = NotificationStatus.queued ..atMetaData = _getAtMetadataForNotification(verbParams) ..type = _getNotificationType( - AtUtils.formatAtSign(verbParams[AtConstants.forAtSign])!, + AtUtils.fixAtSign(verbParams[AtConstants.forAtSign] ?? ''), AtSecondaryServerImpl.getInstance().currentAtSign) ..ttl = getNotificationExpiryInMillis(verbParams[AtConstants.ttlNotification]) diff --git a/packages/at_secondary_server/lib/src/verb/handler/otp_verb_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/otp_verb_handler.dart index 06b986e0d..b68c6de01 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/otp_verb_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/otp_verb_handler.dart @@ -37,7 +37,7 @@ class OtpVerbHandler extends AbstractVerbHandler { } switch (operation) { case 'get': - if (!atConnection.getMetaData().isAuthenticated) { + if (!atConnection.metaData.isAuthenticated) { throw UnAuthenticatedException( 'otp:get requires authenticated connection'); } @@ -56,7 +56,7 @@ class OtpVerbHandler extends AbstractVerbHandler { case 'put': // Only client connection which has access to __manage access are allowed to store the semi permanent pass codes if (!(await _isClientAuthorizedToStoreSPP( - atConnection.getMetaData() as InboundConnectionMetadata, + atConnection.metaData as InboundConnectionMetadata, AtSecondaryServerImpl.getInstance().currentAtSign))) { throw InvalidRequestException( 'Client not allowed to not store semi permanent pass code'); diff --git a/packages/at_secondary_server/lib/src/verb/handler/pkam_verb_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/pkam_verb_handler.dart index 90797b2bd..b0b398c0f 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/pkam_verb_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/pkam_verb_handler.dart @@ -38,7 +38,7 @@ class PkamVerbHandler extends AbstractVerbHandler { Future processVerb(Response response, HashMap verbParams, AtConnection atConnection) async { var atConnectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; var enrollId = verbParams[AtConstants.enrollmentId]; var sessionID = atConnectionMetadata.sessionID; var atSign = AtSecondaryServerImpl.getInstance().currentAtSign; diff --git a/packages/at_secondary_server/lib/src/verb/handler/pol_verb_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/pol_verb_handler.dart index 00d049ed4..c16a75ee2 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/pol_verb_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/pol_verb_handler.dart @@ -52,7 +52,7 @@ class PolVerbHandler extends AbstractVerbHandler { HashMap verbParams, InboundConnection atConnection) async { InboundConnectionMetadata atConnectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; var fromAtSign = atConnectionMetadata.fromAtSign; var sessionID = atConnectionMetadata.sessionID; diff --git a/packages/at_secondary_server/lib/src/verb/handler/response/base_response_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/response/base_response_handler.dart index 46638caf0..cd65bf1b8 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/response/base_response_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/response/base_response_handler.dart @@ -20,10 +20,10 @@ abstract class BaseResponseHandler implements ResponseHandler { return; } var atConnectionMetadata = - connection.getMetaData() as InboundConnectionMetadata; + connection.metaData as InboundConnectionMetadata; var isAuthenticated = atConnectionMetadata.isAuthenticated; var atSign = AtSecondaryServerImpl.getInstance().currentAtSign; - var isPolAuthenticated = connection.getMetaData().isPolAuthenticated; + var isPolAuthenticated = connection.metaData.isPolAuthenticated; var fromAtSign = atConnectionMetadata.fromAtSign; var prompt = isAuthenticated ? '$atSign@' diff --git a/packages/at_secondary_server/lib/src/verb/handler/scan_verb_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/scan_verb_handler.dart index 4b33a194c..c6c2f8d1e 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/scan_verb_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/scan_verb_handler.dart @@ -55,7 +55,7 @@ class ScanVerbHandler extends AbstractVerbHandler { HashMap verbParams, InboundConnection atConnection) async { var atConnectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; var forAtSign = verbParams[AtConstants.forAtSign]; var scanRegex = verbParams[AtConstants.regex]; var showHiddenKeys = diff --git a/packages/at_secondary_server/lib/src/verb/handler/stats_verb_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/stats_verb_handler.dart index 725b1f200..229c0fbb4 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/stats_verb_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/stats_verb_handler.dart @@ -156,11 +156,10 @@ class StatsVerbHandler extends AbstractVerbHandler { } var result = []; List enrolledNamespaces = []; - if ((atConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId != + if ((atConnection.metaData as InboundConnectionMetadata).enrollmentId != null) { var enrollmentKey = - '${(atConnection.getMetaData() as InboundConnectionMetadata).enrollmentId}.$newEnrollmentKeyPattern.$enrollManageNamespace${AtSecondaryServerImpl.getInstance().currentAtSign}'; + '${(atConnection.metaData as InboundConnectionMetadata).enrollmentId}.$newEnrollmentKeyPattern.$enrollManageNamespace${AtSecondaryServerImpl.getInstance().currentAtSign}'; enrolledNamespaces = (await getEnrollDataStoreValue(enrollmentKey)) .namespaces .keys diff --git a/packages/at_secondary_server/lib/src/verb/handler/stream_verb_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/stream_verb_handler.dart index d6e88262b..dab3d018e 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/stream_verb_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/stream_verb_handler.dart @@ -47,13 +47,11 @@ class StreamVerbHandler extends AbstractVerbHandler { logger.severe('sender connection is null for stream id:$streamId'); throw UnAuthenticatedException('Invalid stream id'); } - senderConnection.getMetaData().isStream = true; - senderConnection.getMetaData().streamId = streamId; - atConnection.getMetaData().streamId = streamId; - senderConnection.receiverSocket = - StreamManager.receiverSocketMap[streamId]!.getSocket(); + senderConnection.metaData.isStream = true; + senderConnection.metaData.streamId = streamId; + atConnection.metaData.streamId = streamId; logger.info('writing stream ack'); - senderConnection.getSocket().write('stream:ack $streamId\n'); + senderConnection.underlying.write('stream:ack $streamId\n'); break; case 'done': var senderConnection = StreamManager.senderSocketMap[streamId]; @@ -66,8 +64,8 @@ class StreamVerbHandler extends AbstractVerbHandler { _cleanUp(streamId); break; case 'init': - if (!atConnection.getMetaData().isAuthenticated && - !atConnection.getMetaData().isPolAuthenticated) { + if (!atConnection.metaData.isAuthenticated && + !atConnection.metaData.isPolAuthenticated) { throw UnAuthenticatedException( 'Stream init requires either pol or auth'); } @@ -123,11 +121,11 @@ class StreamVerbHandler extends AbstractVerbHandler { void _cleanUp(String streamId) { final receiverConnection = StreamManager.receiverSocketMap[streamId]; if (receiverConnection != null) { - receiverConnection.getSocket().destroy(); + receiverConnection.underlying.destroy(); } final senderConnection = StreamManager.senderSocketMap[streamId]; if (senderConnection != null) { - senderConnection.getSocket().destroy(); + senderConnection.underlying.destroy(); } StreamManager.receiverSocketMap.remove(streamId); StreamManager.senderSocketMap.remove(streamId); diff --git a/packages/at_secondary_server/lib/src/verb/handler/sync_progressive_verb_handler.dart b/packages/at_secondary_server/lib/src/verb/handler/sync_progressive_verb_handler.dart index 5e5cc3396..68e5d0521 100644 --- a/packages/at_secondary_server/lib/src/verb/handler/sync_progressive_verb_handler.dart +++ b/packages/at_secondary_server/lib/src/verb/handler/sync_progressive_verb_handler.dart @@ -47,8 +47,8 @@ class SyncProgressiveVerbHandler extends AbstractVerbHandler { List syncResponse = []; await prepareResponse(capacity, syncResponse, commitEntryIterator, - enrollmentId: (atConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId); + enrollmentId: + (atConnection.metaData as InboundConnectionMetadata).enrollmentId); response.data = jsonEncode(syncResponse); } diff --git a/packages/at_secondary_server/pubspec.yaml b/packages/at_secondary_server/pubspec.yaml index 62b3da56a..cc0454671 100644 --- a/packages/at_secondary_server/pubspec.yaml +++ b/packages/at_secondary_server/pubspec.yaml @@ -8,6 +8,13 @@ publish_to: none environment: sdk: '>=2.15.0 <4.0.0' +dependency_overrides: + at_server_spec: + git: + ref: gkc/alpn + url: https://github.com/atsign-foundation/at_server + path: packages/at_server_spec + dependencies: args: 2.4.2 uuid: 3.0.7 @@ -19,7 +26,7 @@ dependencies: basic_utils: 5.7.0 ecdsa: 0.1.0 encrypt: 5.0.3 - at_commons: 4.0.0 + at_commons: 4.0.1 at_utils: 3.0.16 at_chops: 2.0.0 at_lookup: 3.0.45 diff --git a/packages/at_secondary_server/test/config_verb_test.dart b/packages/at_secondary_server/test/config_verb_test.dart index 32761fc4c..7b6eb59fb 100644 --- a/packages/at_secondary_server/test/config_verb_test.dart +++ b/packages/at_secondary_server/test/config_verb_test.dart @@ -6,9 +6,8 @@ import 'package:at_secondary/src/verb/handler/config_verb_handler.dart'; import 'package:at_server_spec/at_verb_spec.dart'; import 'package:test/test.dart'; import 'package:at_commons/at_commons.dart'; -import 'package:mocktail/mocktail.dart'; -class MockSecondaryKeyStore extends Mock implements SecondaryKeyStore {} +import 'test_utils.dart'; void main() { SecondaryKeyStore mockKeyStore = MockSecondaryKeyStore(); diff --git a/packages/at_secondary_server/test/cram_verb_test.dart b/packages/at_secondary_server/test/cram_verb_test.dart index d76006860..30e5a970f 100644 --- a/packages/at_secondary_server/test/cram_verb_test.dart +++ b/packages/at_secondary_server/test/cram_verb_test.dart @@ -12,17 +12,25 @@ import 'package:at_secondary/src/verb/handler/cram_verb_handler.dart'; import 'package:at_secondary/src/verb/handler/from_verb_handler.dart'; import 'package:at_server_spec/at_verb_spec.dart'; import 'package:crypto/crypto.dart'; -import 'package:test/test.dart'; import 'package:mocktail/mocktail.dart'; +import 'package:test/test.dart'; -class MockSecondaryKeyStore extends Mock implements SecondaryKeyStore {} +import 'test_utils.dart'; void main() { - SecondaryKeyStore mockKeyStore = MockSecondaryKeyStore(); + late SecondaryKeyStore mockKeyStore; + late MockSocket mockSocket; var storageDir = '${Directory.current.path}/test/hive'; late SecondaryKeyStoreManager keyStoreManager; - setUp(() async => keyStoreManager = await setUpFunc(storageDir)); + setUp(() async { + mockKeyStore = MockSecondaryKeyStore(); + mockSocket = MockSocket(); + when(() => mockSocket.setOption(SocketOption.tcpNoDelay, true)) + .thenReturn(true); + keyStoreManager = await setUpFunc(storageDir); + }); + group('A group of cram verb regex test', () { test('test from correct syntax with digest', () { var verb = Cram(); @@ -69,7 +77,7 @@ void main() { var fromVerbHandler = FromVerbHandler(keyStoreManager.getKeyStore()); AtSecondaryServerImpl.getInstance().currentAtSign = '@test_user_1'; var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); var fromVerbParams = HashMap(); fromVerbParams.putIfAbsent('atSign', () => 'test_user_1'); var response = Response(); @@ -84,7 +92,7 @@ void main() { var cramResponse = Response(); await verbHandler.processVerb(cramResponse, cramVerbParams, atConnection); var connectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; expect(connectionMetadata.isAuthenticated, true); expect(cramResponse.data, 'success'); }); @@ -98,7 +106,7 @@ void main() { var fromVerbHandler = FromVerbHandler(keyStoreManager.getKeyStore()); AtSecondaryServerImpl.getInstance().currentAtSign = '@test_user_1'; var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); var fromVerbParams = HashMap(); fromVerbParams.putIfAbsent('atSign', () => 'test_user_1'); var response = Response(); @@ -111,7 +119,7 @@ void main() { var verbHandler = CramVerbHandler(keyStoreManager.getKeyStore()); var cramResponse = Response(); var connectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; expect( () async => await verbHandler.processVerb( cramResponse, cramVerbParams, atConnection), @@ -123,7 +131,7 @@ void main() { var fromVerbHandler = FromVerbHandler(keyStoreManager.getKeyStore()); AtSecondaryServerImpl.getInstance().currentAtSign = '@test_user_1'; var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); var fromVerbParams = HashMap(); fromVerbParams.putIfAbsent('atSign', () => 'test_user_1'); var response = Response(); @@ -136,7 +144,7 @@ void main() { var verbHandler = CramVerbHandler(keyStoreManager.getKeyStore()); var cramResponse = Response(); var connectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; expect( () async => await verbHandler.processVerb( cramResponse, cramVerbParams, atConnection), diff --git a/packages/at_secondary_server/test/enroll_verb_test.dart b/packages/at_secondary_server/test/enroll_verb_test.dart index b041a9896..5d4d24e3e 100644 --- a/packages/at_secondary_server/test/enroll_verb_test.dart +++ b/packages/at_secondary_server/test/enroll_verb_test.dart @@ -22,14 +22,14 @@ void main() { test('A test to verify enroll requests get different enrollment ids', () async { Response response = Response(); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session'; // Enroll request String enrollmentRequest = 'enroll:request:{"appName":"wavi","deviceName":"mydevice","namespaces":{"wavi":"r"},"apkamPublicKey":"dummy_apkam_public_key"}'; HashMap enrollmentRequestVerbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; EnrollVerbHandler enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); await enrollVerbHandler.processVerb( @@ -46,7 +46,7 @@ void main() { 'enroll:request:{"appName":"wavi","deviceName":"mydevice","namespaces":{"buzz":"r"},"otp":"${response.data}","apkamPublicKey":"dummy_apkam_public_key"}'; enrollmentRequestVerbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = false; + inboundConnection.metaData.isAuthenticated = false; enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); await enrollVerbHandler.processVerb( response, enrollmentRequestVerbParams, inboundConnection); @@ -64,9 +64,9 @@ void main() { 'enroll:request:{"appName":"wavi","deviceName":"mydevice","namespaces":{"wavi":"r"},"apkamPublicKey":"dummy_apkam_public_key"}'; HashMap verbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().authType = AuthType.cram; - inboundConnection.getMetaData().sessionID = 'dummy_session'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.authType = AuthType.cram; + inboundConnection.metaData.sessionID = 'dummy_session'; Response response = Response(); EnrollVerbHandler enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); @@ -86,8 +86,8 @@ void main() { () async { Response response = Response(); // OTP Verb - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session'; HashMap otpVerbParams = getVerbParam(VerbSyntax.otp, 'otp:get'); OtpVerbHandler otpVerbHandler = OtpVerbHandler(secondaryKeyStore); @@ -99,7 +99,7 @@ void main() { 'enroll:request:{"appName":"wavi","deviceName":"mydevice","namespaces":{"buzz":"r"},"otp":"$otp","apkamPublicKey":"dummy_apkam_public_key"}'; HashMap enrollmentRequestVerbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = false; + inboundConnection.metaData.isAuthenticated = false; EnrollVerbHandler enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); await enrollVerbHandler.processVerb( @@ -120,9 +120,9 @@ void main() { 'enroll:request:{"appName":"wavi","deviceName":"mydevice","namespaces":{"wavi":"r"},"apkamPublicKey":"dummy_apkam_public_key"}'; HashMap verbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().authType = AuthType.cram; - inboundConnection.getMetaData().sessionID = 'dummy_session'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.authType = AuthType.cram; + inboundConnection.metaData.sessionID = 'dummy_session'; Response response = Response(); EnrollVerbHandler enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); @@ -143,8 +143,8 @@ void main() { 'enroll:request:{"appName":"wavi","deviceName":"mydevice","namespaces":{"wavi":"r"},"apkamPublicKey":"dummy_apkam_public_key"}'; HashMap verbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session'; Response response = Response(); EnrollVerbHandler enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); @@ -153,8 +153,8 @@ void main() { String enrollmentId = jsonDecode(response.data!)['enrollmentId']; String enrollmentList = 'enroll:list'; - (inboundConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId = enrollmentId; + (inboundConnection.metaData as InboundConnectionMetadata).enrollmentId = + enrollmentId; verbParams = getVerbParam(VerbSyntax.enroll, enrollmentList); await enrollVerbHandler.processVerb( response, verbParams, inboundConnection); @@ -165,14 +165,14 @@ void main() { 'A test to verify enrollment list without __manage namespace returns enrollment info of given enrollmentId', () async { Response response = Response(); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session'; // Enroll request String enrollmentRequest = 'enroll:request:{"appName":"wavi","deviceName":"mydevice","namespaces":{"wavi":"r"},"apkamPublicKey":"dummy_apkam_public_key"}'; HashMap enrollmentRequestVerbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; EnrollVerbHandler enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); await enrollVerbHandler.processVerb( @@ -190,7 +190,7 @@ void main() { 'enroll:request:{"appName":"wavi","deviceName":"mydevice","namespaces":{"wavi":"r"},"otp":"${response.data}","apkamPublicKey":"dummy_apkam_public_key"}'; enrollmentRequestVerbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = false; + inboundConnection.metaData.isAuthenticated = false; enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); await enrollVerbHandler.processVerb( response, enrollmentRequestVerbParams, inboundConnection); @@ -199,14 +199,14 @@ void main() { 'enroll:approve:{"enrollmentId":"$enrollmentId"}'; HashMap approveEnrollmentVerbParams = getVerbParam(VerbSyntax.enroll, approveEnrollment); - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); await enrollVerbHandler.processVerb( response, approveEnrollmentVerbParams, inboundConnection); // Enroll list String enrollmentList = 'enroll:list'; - (inboundConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId = enrollmentId; + (inboundConnection.metaData as InboundConnectionMetadata).enrollmentId = + enrollmentId; HashMap verbParams = getVerbParam(VerbSyntax.enroll, enrollmentList); await enrollVerbHandler.processVerb( @@ -232,8 +232,8 @@ void main() { setUp(() async { await verbTestsSetUp(); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session'; // OTP Verb HashMap otpVerbParams = getVerbParam(VerbSyntax.otp, 'otp:get'); @@ -256,7 +256,7 @@ void main() { 'enroll:request:{"appName":"wavi","deviceName":"mydevice","namespaces":{"wavi":"r"},"otp":"${response.data}","apkamPublicKey":"dummy_apkam_public_key"}'; HashMap enrollmentRequestVerbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = false; + inboundConnection.metaData.isAuthenticated = false; EnrollVerbHandler enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); await enrollVerbHandler.processVerb( @@ -267,7 +267,7 @@ void main() { 'enroll:$operation:{"enrollmentId":"$enrollmentId"}'; HashMap approveEnrollmentVerbParams = getVerbParam(VerbSyntax.enroll, approveEnrollment); - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); await enrollVerbHandler.processVerb( response, approveEnrollmentVerbParams, inboundConnection); @@ -289,8 +289,8 @@ void main() { String enrollmentRequest = 'enroll:approve:enrollmentid:123'; HashMap verbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = false; - inboundConnection.getMetaData().sessionID = 'dummy_session'; + inboundConnection.metaData.isAuthenticated = false; + inboundConnection.metaData.sessionID = 'dummy_session'; Response response = Response(); EnrollVerbHandler enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); @@ -309,8 +309,8 @@ void main() { String enrollmentRequest = 'enroll:deny:enrollmentid:123'; HashMap verbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = false; - inboundConnection.getMetaData().sessionID = 'dummy_session'; + inboundConnection.metaData.isAuthenticated = false; + inboundConnection.metaData.sessionID = 'dummy_session'; Response response = Response(); EnrollVerbHandler enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); @@ -328,8 +328,8 @@ void main() { String enrollmentRequest = 'enroll:revoke:enrollmentid:123'; HashMap verbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = false; - inboundConnection.getMetaData().sessionID = 'dummy_session'; + inboundConnection.metaData.isAuthenticated = false; + inboundConnection.metaData.sessionID = 'dummy_session'; Response response = Response(); EnrollVerbHandler enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); @@ -347,8 +347,8 @@ void main() { 'enroll:request:{"appName":"wavi","deviceName":"mydevice","namespaces":{"wavi":"r"},"apkamPublicKey":"dummy_apkam_public_key"}'; HashMap verbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = false; - inboundConnection.getMetaData().sessionID = 'dummy_session'; + inboundConnection.metaData.isAuthenticated = false; + inboundConnection.metaData.sessionID = 'dummy_session'; Response response = Response(); EnrollVerbHandler enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); @@ -374,10 +374,10 @@ void main() { 'enroll:revoke:{"enrollmentId":"$enrollmentId"}'; HashMap verbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session'; - (inboundConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId = '123'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session'; + (inboundConnection.metaData as InboundConnectionMetadata).enrollmentId = + '123'; Response response = Response(); EnrollVerbHandler enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); @@ -404,11 +404,11 @@ void main() { 'enroll:request:{"appName":"wavi","deviceName":"myDevice","namespaces":{"wavi":"rw"},"encryptedDefaultEncryptedPrivateKey":"dummy_encrypted_private_key","encryptedDefaultSelfEncryptionKey":"dummy_self_encrypted_key","apkamPublicKey":"dummy_apkam_public_key"}'; HashMap verbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().authType = AuthType.cram; - inboundConnection.getMetaData().sessionID = 'dummy_session'; - (inboundConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId = '123'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.authType = AuthType.cram; + inboundConnection.metaData.sessionID = 'dummy_session'; + (inboundConnection.metaData as InboundConnectionMetadata).enrollmentId = + '123'; Response responseObject = Response(); EnrollVerbHandler enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); @@ -431,11 +431,11 @@ void main() { 'enroll:request:{"appName":"wavi","deviceName":"myDevice","namespaces":{"wavi":"rw"},"encryptedDefaultEncryptedPrivateKey":"dummy_encrypted_private_key","encryptedDefaultSelfEncryptionKey":"dummy_self_encrypted_key","apkamPublicKey":"dummy_apkam_public_key"}'; HashMap verbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().authType = AuthType.cram; - inboundConnection.getMetaData().sessionID = 'dummy_session'; - (inboundConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId = '123'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.authType = AuthType.cram; + inboundConnection.metaData.sessionID = 'dummy_session'; + (inboundConnection.metaData as InboundConnectionMetadata).enrollmentId = + '123'; Response response = Response(); EnrollVerbHandler enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); @@ -453,7 +453,7 @@ void main() { test('A test to ensure enroll approval is not added to commit log', () async { Response response = Response(); - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; // GET OTP HashMap otpVerbParams = getVerbParam(VerbSyntax.otp, 'otp:get'); @@ -465,8 +465,8 @@ void main() { 'enroll:request:{"appName":"wavi","deviceName":"myDevice","namespaces":{"buzz":"rw"},"encryptedAPKAMSymmetricKey":"dummy_apkam_symmetric_key","apkamPublicKey":"dummy_apkam_public_key","otp":"${response.data}"}'; HashMap enrollmentVerbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = false; - inboundConnection.getMetaData().sessionID = 'dummy_session'; + inboundConnection.metaData.isAuthenticated = false; + inboundConnection.metaData.sessionID = 'dummy_session'; EnrollVerbHandler enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); await enrollVerbHandler.processVerb( @@ -477,8 +477,8 @@ void main() { String approveEnrollment = 'enroll:approve:{"enrollmentId":"$enrollmentId","encryptedDefaultEncryptedPrivateKey":"dummy_encrypted_private_key","encryptedDefaultSelfEncryptionKey":"dummy_self_encryption_key"}'; enrollmentVerbParams = getVerbParam(VerbSyntax.enroll, approveEnrollment); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session'; await enrollVerbHandler.processVerb( response, enrollmentVerbParams, inboundConnection); var approveEnrollmentResponse = jsonDecode(response.data!); @@ -504,7 +504,7 @@ void main() { HashMap totpVerbParams = getVerbParam(VerbSyntax.otp, totpCommand); OtpVerbHandler otpVerbHandler = OtpVerbHandler(secondaryKeyStore); - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; Response defaultResponse = Response(); await otpVerbHandler.processVerb( defaultResponse, totpVerbParams, inboundConnection); @@ -520,8 +520,8 @@ void main() { 'enroll:request:{"appName":"wavi","deviceName":"mydevice","namespaces":{"wavi":"r"},"otp":"$otp","apkamPublicKey":"dummy_apkam_public_key"}'; HashMap enrollVerbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = false; - inboundConnection.getMetaData().sessionID = 'dummy_session_id'; + inboundConnection.metaData.isAuthenticated = false; + inboundConnection.metaData.sessionID = 'dummy_session_id'; await enrollVerbHandler.processVerb( response, enrollVerbParams, inboundConnection); String enrollmentId = jsonDecode(response.data!)['enrollmentId']; @@ -533,8 +533,8 @@ void main() { 'enroll:approve:{"enrollmentId":"$enrollmentId"}'; enrollVerbParams = getVerbParam(VerbSyntax.enroll, approveEnrollmentCommand); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session_id'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session_id'; await enrollVerbHandler.processVerb( response, enrollVerbParams, inboundConnection); expect(response.isError, true); @@ -554,8 +554,8 @@ void main() { 'enroll:request:{"appName":"wavi","deviceName":"mydevice","namespaces":{"wavi":"r"},"otp":"$otp","apkamPublicKey":"dummy_apkam_public_key"}'; HashMap enrollVerbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = false; - inboundConnection.getMetaData().sessionID = 'dummy_session_id1'; + inboundConnection.metaData.isAuthenticated = false; + inboundConnection.metaData.sessionID = 'dummy_session_id1'; await enrollVerbHandler.processVerb( response, enrollVerbParams, inboundConnection); String enrollmentId = jsonDecode(response.data!)['enrollmentId']; @@ -567,8 +567,8 @@ void main() { 'enroll:deny:{"enrollmentId":"$enrollmentId"}'; enrollVerbParams = getVerbParam(VerbSyntax.enroll, approveEnrollmentCommand); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session_id'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session_id'; await enrollVerbHandler.processVerb( response, enrollVerbParams, inboundConnection); expect(response.isError, true); @@ -588,8 +588,8 @@ void main() { 'enroll:request:{"appName":"wavi","deviceName":"mydevice","namespaces":{"wavi":"r"},"otp":"$otp","apkamPublicKey":"dummy_apkam_public_key"}'; HashMap enrollVerbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = false; - inboundConnection.getMetaData().sessionID = 'dummy_session_id'; + inboundConnection.metaData.isAuthenticated = false; + inboundConnection.metaData.sessionID = 'dummy_session_id'; await enrollVerbHandler.processVerb( response, enrollVerbParams, inboundConnection); String enrollmentId = jsonDecode(response.data!)['enrollmentId']; @@ -606,8 +606,8 @@ void main() { 'enroll:approve:{"enrollmentId":"$enrollmentId"}'; enrollVerbParams = getVerbParam(VerbSyntax.enroll, approveEnrollmentCommand); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session_id'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session_id'; await enrollVerbHandler.processVerb( response, enrollVerbParams, inboundConnection); // Verify TTL is reset @@ -626,9 +626,9 @@ void main() { 'enroll:request:{"appName":"wavi","deviceName":"mydevice","namespaces":{"wavi":"r"},"otp":"$otp","apkamPublicKey":"dummy_apkam_public_key"}'; HashMap enrollVerbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().authType = AuthType.cram; - inboundConnection.getMetaData().sessionID = 'dummy_session_id'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.authType = AuthType.cram; + inboundConnection.metaData.sessionID = 'dummy_session_id'; await enrollVerbHandler.processVerb( response, enrollVerbParams, inboundConnection); String enrollmentId = jsonDecode(response.data!)['enrollmentId']; @@ -656,7 +656,7 @@ void main() { HashMap totpVerbParams = getVerbParam(VerbSyntax.otp, totpCommand); OtpVerbHandler otpVerbHandler = OtpVerbHandler(secondaryKeyStore); - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; await otpVerbHandler.processVerb( defaultResponse, totpVerbParams, inboundConnection); otp = defaultResponse.data; @@ -667,8 +667,8 @@ void main() { 'enroll:request:{"appName":"wavi","deviceName":"mydevice","namespaces":{"wavi":"r"},"otp":"$otp","apkamPublicKey":"dummy_apkam_public_key"}'; HashMap enrollVerbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = false; - inboundConnection.getMetaData().sessionID = 'dummy_session_id'; + inboundConnection.metaData.isAuthenticated = false; + inboundConnection.metaData.sessionID = 'dummy_session_id'; await enrollVerbHandler.processVerb( defaultResponse, enrollVerbParams, inboundConnection); enrollmentId = jsonDecode(defaultResponse.data!)['enrollmentId']; @@ -682,8 +682,8 @@ void main() { String denyEnrollmentCommand = 'enroll:deny:{"enrollmentId":"$enrollmentId"}'; enrollVerbParams = getVerbParam(VerbSyntax.enroll, denyEnrollmentCommand); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session_id'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session_id'; await enrollVerbHandler.processVerb( response, enrollVerbParams, inboundConnection); expect(jsonDecode(response.data!)['enrollmentId'], enrollmentId); @@ -693,8 +693,8 @@ void main() { 'enroll:approve:{"enrollmentId":"$enrollmentId"}'; enrollVerbParams = getVerbParam(VerbSyntax.enroll, approveEnrollmentCommand); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session_id'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session_id'; expect( () async => await enrollVerbHandler.processVerb( response, enrollVerbParams, inboundConnection), @@ -711,8 +711,8 @@ void main() { 'enroll:approve:{"enrollmentId":"$enrollmentId"}'; HashMap approveEnrollVerbParams = getVerbParam(VerbSyntax.enroll, approveEnrollmentCommand); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session_id'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session_id'; await enrollVerbHandler.processVerb( response, approveEnrollVerbParams, inboundConnection); expect(jsonDecode(response.data!)['enrollmentId'], enrollmentId); @@ -741,8 +741,8 @@ void main() { String denyEnrollmentCommand = 'enroll:revoke:{"enrollmentId":"$enrollmentId"}'; enrollVerbParams = getVerbParam(VerbSyntax.enroll, denyEnrollmentCommand); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session_id'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session_id'; expect( () async => await enrollVerbHandler.processVerb( response, enrollVerbParams, inboundConnection), @@ -789,8 +789,8 @@ void main() { EnrollVerbHandler.initialDelayInMilliseconds ]; enrollVerbHandler.enrollmentResponseDelayIntervalInMillis = 500; - inboundConnection.getMetaData().isAuthenticated = false; - inboundConnection.getMetaData().sessionID = 'dummy_session_id'; + inboundConnection.metaData.isAuthenticated = false; + inboundConnection.metaData.sessionID = 'dummy_session_id'; // First Invalid request String enrollmentRequest = 'enroll:request:{"appName":"wavi","deviceName":"mydevice","namespaces":{"wavi":"r"},"otp":"123","apkamPublicKey":"dummy_apkam_public_key"}'; @@ -800,7 +800,7 @@ void main() { await enrollVerbHandler.processVerb( response, enrollVerbParams, inboundConnection); // Do nothing on exception - } on AtEnrollmentException {} + } on AtEnrollmentException catch (_) {} expect(enrollVerbHandler.getEnrollmentResponseDelayInMilliseconds(), 100); // Second Invalid request and verify the delay response interval is incremented. enrollmentRequest = @@ -810,7 +810,7 @@ void main() { try { await enrollVerbHandler.processVerb( response, enrollVerbParams, inboundConnection); - } on AtEnrollmentException {} + } on AtEnrollmentException catch (_) {} expect(enrollVerbHandler.getEnrollmentResponseDelayInMilliseconds(), 200); // Third Invalid request and verify the delay response interval is incremented. enrollmentRequest = @@ -819,17 +819,17 @@ void main() { try { await enrollVerbHandler.processVerb( response, enrollVerbParams, inboundConnection); - } on AtEnrollmentException {} + } on AtEnrollmentException catch (_) {} expect(enrollVerbHandler.getEnrollmentResponseDelayInMilliseconds(), 300); // Get OTP and send a valid enrollment request. Verify the delay response is // not reset because the threshold is not met. OtpVerbHandler otpVerbHandler = OtpVerbHandler(secondaryKeyStore); - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; await otpVerbHandler.processVerb( response, getVerbParam(VerbSyntax.otp, 'otp:get'), inboundConnection); - inboundConnection.getMetaData().isAuthenticated = false; + inboundConnection.metaData.isAuthenticated = false; enrollmentRequest = 'enroll:request:{"appName":"wavi","deviceName":"mydevice","namespaces":{"wavi":"r"},"otp":"${response.data}","apkamPublicKey":"dummy_apkam_public_key"}'; enrollVerbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); @@ -842,10 +842,10 @@ void main() { // Wait for 5 seconds to for threshold to met to reset the delay in response. await Future.delayed(Duration(milliseconds: 500)); // Get OTP and send a valid Enrollment request - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; await otpVerbHandler.processVerb( response, getVerbParam(VerbSyntax.otp, 'otp:get'), inboundConnection); - inboundConnection.getMetaData().isAuthenticated = false; + inboundConnection.metaData.isAuthenticated = false; enrollmentRequest = 'enroll:request:{"appName":"wavi","deviceName":"mydevice","namespaces":{"wavi":"r"},"otp":"${response.data}","apkamPublicKey":"dummy_apkam_public_key"}'; enrollVerbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); diff --git a/packages/at_secondary_server/test/from_verb_test.dart b/packages/at_secondary_server/test/from_verb_test.dart index 8f9a37180..0ef74abc8 100644 --- a/packages/at_secondary_server/test/from_verb_test.dart +++ b/packages/at_secondary_server/test/from_verb_test.dart @@ -10,17 +10,23 @@ import 'package:at_secondary/src/utils/handler_util.dart'; import 'package:at_secondary/src/utils/secondary_util.dart'; import 'package:at_secondary/src/verb/handler/from_verb_handler.dart'; import 'package:at_server_spec/at_verb_spec.dart'; -import 'package:test/test.dart'; import 'package:mocktail/mocktail.dart'; - -class MockSecondaryKeyStore extends Mock implements SecondaryKeyStore {} +import 'package:test/test.dart'; +import 'test_utils.dart'; void main() { - SecondaryKeyStore mockKeyStore = MockSecondaryKeyStore(); + late SecondaryKeyStore mockKeyStore; + late MockSocket mockSocket; var storageDir = '${Directory.current.path}/test/hive'; late SecondaryKeyStoreManager keyStoreManager; - setUp(() async => keyStoreManager = await setUpFunc(storageDir)); + setUp(() async { + mockKeyStore = MockSecondaryKeyStore(); + mockSocket = MockSocket(); + when(() => mockSocket.setOption(SocketOption.tcpNoDelay, true)) + .thenReturn(true); + keyStoreManager = await setUpFunc(storageDir); + }); group('A group of from verb regex test', () { test('test from correct syntax with @', () { var verb = From(); @@ -106,14 +112,14 @@ void main() { var verbHandler = FromVerbHandler(keyStoreManager.getKeyStore()); AtSecondaryServerImpl.getInstance().currentAtSign = '@alice'; var inBoundSessionId = '123'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); var verbParams = HashMap(); verbParams.putIfAbsent('atSign', () => '@alice'); var response = Response(); await verbHandler.processVerb(response, verbParams, atConnection); expect(response.data!.startsWith('data:$inBoundSessionId@alice'), true); var connectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; expect(connectionMetadata.self, true); }); @@ -121,7 +127,7 @@ void main() { var verbHandler = FromVerbHandler(keyStoreManager.getKeyStore()); AtSecondaryServerImpl.getInstance().currentAtSign = '@alice'; var inBoundSessionId = '123'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); var verbParams = HashMap(); verbParams.putIfAbsent('atSign', () => 'alice'); var response = Response(); @@ -129,7 +135,7 @@ void main() { expect(response.data!.startsWith('data:$inBoundSessionId@alice'), true); expect(response.data!.split(':')[2], isNotNull); var connectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; expect(connectionMetadata.self, true); }); @@ -145,7 +151,7 @@ void main() { var response = Response(); await verbHandler.processVerb(response, verbParams, atConnection); expect(response.data.startsWith('proof:$inBoundSessionId@nairobi'), true); - InboundConnectionMetadata connectionMetadata = atConnection.getMetaData(); + InboundConnectionMetadata connectionMetadata = atConnection.metaData; expect(connectionMetadata.from, true); expect(connectionMetadata.fromAtSign, '@nairobi'); });*/ @@ -161,7 +167,7 @@ void main() { .addToBlockList({'@bob'}); AtSecondaryServerImpl.getInstance().currentAtSign = '@alice'; var inBoundSessionId = '123'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); var verbParams = HashMap(); verbParams.putIfAbsent('atSign', () => '@alice'); var response = Response(); @@ -169,7 +175,7 @@ void main() { expect(response.data!.startsWith('data:$inBoundSessionId@alice'), true); expect(response.data!.split(':')[2], isNotNull); var connectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; expect(connectionMetadata.self, true); }); @@ -182,7 +188,7 @@ void main() { .addToBlockList({'@bob'}); AtSecondaryServerImpl.getInstance().currentAtSign = '@alice'; var inBoundSessionId = '123'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); var verbParams = HashMap(); verbParams.putIfAbsent('atSign', () => '@bob'); var response = Response(); @@ -211,7 +217,7 @@ void main() { atConnection = InboundConnectionImpl(null, inBoundSessionId); await verbHandler.processVerb(response, verbParams, atConnection); expect(response.data.startsWith('proof:$inBoundSessionId@bob'), true); - InboundConnectionMetadata connectionMetadata = atConnection.getMetaData(); + InboundConnectionMetadata connectionMetadata = atConnection.metaData; expect(connectionMetadata.from, true); expect(connectionMetadata.fromAtSign, '@bob'); }); @@ -227,7 +233,7 @@ void main() { var response = Response(); await verbHandler.processVerb(response, verbParams, atConnection); expect(response.data.startsWith('proof:$inBoundSessionId@bob'), true); - InboundConnectionMetadata connectionMetadata = atConnection.getMetaData(); + InboundConnectionMetadata connectionMetadata = atConnection.metaData; expect(connectionMetadata.from, true); expect(connectionMetadata.fromAtSign, '@bob'); await AtConfig.getInstance().addToBlockList({'@bob'}); diff --git a/packages/at_secondary_server/test/inbound_connection_impl_test.dart b/packages/at_secondary_server/test/inbound_connection_impl_test.dart index 0c0112278..f6e63fa4b 100644 --- a/packages/at_secondary_server/test/inbound_connection_impl_test.dart +++ b/packages/at_secondary_server/test/inbound_connection_impl_test.dart @@ -2,13 +2,23 @@ import 'dart:io'; import 'package:at_secondary/src/connection/inbound/inbound_connection_impl.dart'; import 'package:at_server_spec/at_server_spec.dart'; +import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; +import 'test_utils.dart'; + void main() { + late MockSocket mockSocket; + + setUp(() async { + mockSocket = MockSocket(); + when(() => mockSocket.setOption(SocketOption.tcpNoDelay, true)) + .thenReturn(true); + }); + group('A test to verify the rate limiter on inbound connection', () { test('A test to verify requests exceeding the limit are rejected', () { - Socket? dummySocket; - AtConnection connection1 = InboundConnectionImpl(dummySocket, 'aaa'); + AtConnection connection1 = InboundConnectionImpl(mockSocket, 'aaa'); (connection1 as InboundConnectionImpl).maxRequestsPerTimeFrame = 1; connection1.timeFrameInMillis = Duration(milliseconds: 10).inMilliseconds; expect(connection1.isRequestAllowed(), true); @@ -17,8 +27,7 @@ void main() { test('A test to verify requests after the time window are accepted', () async { - Socket? dummySocket; - AtConnection connection1 = InboundConnectionImpl(dummySocket, 'aaa'); + AtConnection connection1 = InboundConnectionImpl(mockSocket, 'aaa'); (connection1 as InboundConnectionImpl).maxRequestsPerTimeFrame = 1; connection1.timeFrameInMillis = Duration(milliseconds: 2).inMilliseconds; expect(connection1.isRequestAllowed(), true); @@ -28,9 +37,8 @@ void main() { }); test('A test to verify request from different connection is allowed', () { - Socket? dummySocket; - AtConnection connection1 = InboundConnectionImpl(dummySocket, 'aaa'); - AtConnection connection2 = InboundConnectionImpl(dummySocket, 'aaa'); + AtConnection connection1 = InboundConnectionImpl(mockSocket, 'aaa'); + AtConnection connection2 = InboundConnectionImpl(mockSocket, 'aaa'); (connection1 as InboundConnectionImpl).maxRequestsPerTimeFrame = 1; (connection2 as InboundConnectionImpl).maxRequestsPerTimeFrame = 1; connection1.timeFrameInMillis = Duration(milliseconds: 10).inMilliseconds; diff --git a/packages/at_secondary_server/test/inbound_connection_manager_test.dart b/packages/at_secondary_server/test/inbound_connection_manager_test.dart index 96d389dd5..c2fe1bb39 100644 --- a/packages/at_secondary_server/test/inbound_connection_manager_test.dart +++ b/packages/at_secondary_server/test/inbound_connection_manager_test.dart @@ -5,13 +5,21 @@ import 'package:at_secondary/src/connection/inbound/connection_util.dart'; import 'package:at_secondary/src/connection/inbound/inbound_connection_manager.dart'; import 'package:at_secondary/src/server/at_secondary_impl.dart'; import 'package:at_secondary/src/server/server_context.dart'; +import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; +import 'test_utils.dart'; + void main() { + late MockSocket mockSocket; + setUp(() { var serverContext = AtSecondaryContext(); serverContext.unauthenticatedInboundIdleTimeMillis = 10000; AtSecondaryServerImpl.getInstance().serverContext = serverContext; + mockSocket = MockSocket(); + when(() => mockSocket.setOption(SocketOption.tcpNoDelay, true)) + .thenReturn(true); }); tearDown(() { @@ -21,19 +29,17 @@ void main() { group('A group of inbound connection manager tests', () { test('test inbound connection manager - create connection ', () { var connManager = InboundConnectionManager.getInstance(); - Socket? dummySocket; connManager.init(5); var createdConnection = - connManager.createConnection(dummySocket, sessionId: 'aaa'); - expect(createdConnection.getMetaData().sessionID, 'aaa'); - expect(createdConnection.getMetaData().isCreated, true); + connManager.createSocketConnection(mockSocket, sessionId: 'aaa'); + expect(createdConnection.metaData.sessionID, 'aaa'); + expect(createdConnection.metaData.isCreated, true); }); test('test inbound connection manager - current pool size', () { var connManager = InboundConnectionManager.getInstance(); connManager.init(2); - Socket? dummySocket; - connManager.createConnection(dummySocket, sessionId: 'aaa'); + connManager.createSocketConnection(mockSocket, sessionId: 'aaa'); expect(ConnectionUtil.getActiveConnectionSize(), 1); }); @@ -44,12 +50,12 @@ void main() { test('test inbound connection manager - connect limit test', () { var connManager = InboundConnectionManager.getInstance(); - Socket? dummySocket; connManager.init(2); - connManager.createConnection(dummySocket, sessionId: 'aaa'); - connManager.createConnection(dummySocket, sessionId: 'bbb'); + connManager.createSocketConnection(mockSocket, sessionId: 'aaa'); + connManager.createSocketConnection(mockSocket, sessionId: 'bbb'); expect( - () => connManager.createConnection(dummySocket, sessionId: 'ccc'), + () => + connManager.createSocketConnection(mockSocket, sessionId: 'ccc'), throwsA(predicate((dynamic e) => e is InboundConnectionLimitException && e.message == 'max limit reached on inbound pool'))); @@ -57,31 +63,28 @@ void main() { test('test inbound connection manager - has capacity true', () { var connManager = InboundConnectionManager.getInstance(); - Socket? dummySocket; connManager.init(5); - connManager.createConnection(dummySocket, sessionId: 'aaa'); - connManager.createConnection(dummySocket, sessionId: 'bbb'); - connManager.createConnection(dummySocket, sessionId: 'ccc'); + connManager.createSocketConnection(mockSocket, sessionId: 'aaa'); + connManager.createSocketConnection(mockSocket, sessionId: 'bbb'); + connManager.createSocketConnection(mockSocket, sessionId: 'ccc'); expect(connManager.hasCapacity(), true); }); test('test inbound connection manager - has capacity false', () { var connManager = InboundConnectionManager.getInstance(); - Socket? dummySocket; connManager.init(3); - connManager.createConnection(dummySocket, sessionId: 'aaa'); - connManager.createConnection(dummySocket, sessionId: 'bbb'); - connManager.createConnection(dummySocket, sessionId: 'ccc'); + connManager.createSocketConnection(mockSocket, sessionId: 'aaa'); + connManager.createSocketConnection(mockSocket, sessionId: 'bbb'); + connManager.createSocketConnection(mockSocket, sessionId: 'ccc'); expect(connManager.hasCapacity(), false); }); test('test inbound connection manager -clear connections', () { var connManager = InboundConnectionManager.getInstance(); - Socket? dummySocket; connManager.init(3); - connManager.createConnection(dummySocket, sessionId: 'aaa'); - connManager.createConnection(dummySocket, sessionId: 'bbb'); - connManager.createConnection(dummySocket, sessionId: 'ccc'); + connManager.createSocketConnection(mockSocket, sessionId: 'aaa'); + connManager.createSocketConnection(mockSocket, sessionId: 'bbb'); + connManager.createSocketConnection(mockSocket, sessionId: 'ccc'); connManager.removeAllConnections(); expect(ConnectionUtil.getActiveConnectionSize(), 0); }); diff --git a/packages/at_secondary_server/test/inbound_connection_pool_test.dart b/packages/at_secondary_server/test/inbound_connection_pool_test.dart index 3937fc6ea..e3c073be0 100644 --- a/packages/at_secondary_server/test/inbound_connection_pool_test.dart +++ b/packages/at_secondary_server/test/inbound_connection_pool_test.dart @@ -5,14 +5,19 @@ import 'package:at_secondary/src/connection/inbound/inbound_connection_impl.dart import 'package:at_secondary/src/connection/inbound/inbound_connection_pool.dart'; import 'package:at_secondary/src/server/at_secondary_impl.dart'; import 'package:at_secondary/src/server/server_context.dart'; +import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import 'package:at_utils/at_utils.dart'; +import 'test_utils.dart'; + var serverContext = AtSecondaryContext(); AtSignLogger logger = AtSignLogger('inbound_connection_pool_test'); void main() async { + late MockSocket mockSocket; + setUpAll(() { serverContext.unauthenticatedInboundIdleTimeMillis = 250; serverContext.authenticatedInboundIdleTimeMillis = 500; @@ -21,6 +26,10 @@ void main() async { serverContext.authenticatedMinAllowableIdleTimeMillis = 100; AtSecondaryServerImpl.getInstance().serverContext = serverContext; InboundConnectionPool.getInstance().init(10); + + mockSocket = MockSocket(); + when(() => mockSocket.setOption(SocketOption.tcpNoDelay, true)) + .thenReturn(true); }); tearDown(() { InboundConnectionPool.getInstance().clearAllConnections(); @@ -35,9 +44,8 @@ void main() async { test('test connection pool add connections', () { var poolInstance = InboundConnectionPool.getInstance(); poolInstance.init(5); - Socket? dummySocket; - var connection1 = InboundConnectionImpl(dummySocket, 'aaa'); - var connection2 = InboundConnectionImpl(dummySocket, 'bbb'); + var connection1 = InboundConnectionImpl(mockSocket, 'aaa'); + var connection2 = InboundConnectionImpl(mockSocket, 'bbb'); poolInstance.add(connection1); poolInstance.add(connection2); expect(poolInstance.getCapacity(), 5); @@ -46,8 +54,7 @@ void main() async { test('test connection pool has capacity', () { var poolInstance = InboundConnectionPool.getInstance(); poolInstance.init(2); - Socket? dummySocket; - var connection1 = InboundConnectionImpl(dummySocket, 'aaa'); + var connection1 = InboundConnectionImpl(mockSocket, 'aaa'); poolInstance.add(connection1); expect(poolInstance.hasCapacity(), true); }); @@ -55,9 +62,8 @@ void main() async { test('test connection pool has no capacity', () { var poolInstance = InboundConnectionPool.getInstance(); poolInstance.init(2); - Socket? dummySocket; - var connection1 = InboundConnectionImpl(dummySocket, 'aaa'); - var connection2 = InboundConnectionImpl(dummySocket, 'bbb'); + var connection1 = InboundConnectionImpl(mockSocket, 'aaa'); + var connection2 = InboundConnectionImpl(mockSocket, 'bbb'); poolInstance.add(connection1); poolInstance.add(connection2); expect(poolInstance.hasCapacity(), false); @@ -66,9 +72,8 @@ void main() async { test('test connection pool - clear closed connection', () { var poolInstance = InboundConnectionPool.getInstance(); poolInstance.init(2); - Socket? dummySocket; - var connection1 = MockInboundConnectionImpl(dummySocket, 'aaa'); - var connection2 = MockInboundConnectionImpl(dummySocket, 'bbb'); + var connection1 = MockInboundConnectionImpl(mockSocket, 'aaa'); + var connection2 = MockInboundConnectionImpl(mockSocket, 'bbb'); poolInstance.add(connection1); poolInstance.add(connection2); expect(poolInstance.getCurrentSize(), 2); @@ -80,10 +85,9 @@ void main() async { test('test connection pool - clear idle connection', () { var poolInstance = InboundConnectionPool.getInstance(); poolInstance.init(10); - Socket? dummySocket; - var connection1 = MockInboundConnectionImpl(dummySocket, 'aaa'); - var connection2 = MockInboundConnectionImpl(dummySocket, 'bbb'); - var connection3 = MockInboundConnectionImpl(dummySocket, 'ccc'); + var connection1 = MockInboundConnectionImpl(mockSocket, 'aaa'); + var connection2 = MockInboundConnectionImpl(mockSocket, 'bbb'); + var connection3 = MockInboundConnectionImpl(mockSocket, 'ccc'); poolInstance.add(connection1); poolInstance.add(connection2); poolInstance.add(connection3); @@ -97,12 +101,12 @@ void main() async { milliseconds: (serverContext.unauthenticatedInboundIdleTimeMillis * 0.2) .floor())); - print('connection 1: ${connection1.getMetaData().created} ' - '${connection1.getMetaData().lastAccessed} ${connection1.isInValid()}'); - print('connection 2: ${connection2.getMetaData().created} ' - '${connection2.getMetaData().lastAccessed} ${connection2.isInValid()}'); - print('connection 3: ${connection3.getMetaData().created} ' - '${connection3.getMetaData().lastAccessed} ${connection3.isInValid()}'); + print('connection 1: ${connection1.metaData.created} ' + '${connection1.metaData.lastAccessed} ${connection1.isInValid()}'); + print('connection 2: ${connection2.metaData.created} ' + '${connection2.metaData.lastAccessed} ${connection2.isInValid()}'); + print('connection 3: ${connection3.metaData.created} ' + '${connection3.metaData.lastAccessed} ${connection3.isInValid()}'); poolInstance.clearInvalidConnections(); expect(poolInstance.getCurrentSize(), 1); }); @@ -119,7 +123,8 @@ void main() async { (maxPoolSize * serverContext.inboundConnectionLowWaterMarkRatio) .floor(); for (int i = 0; i < lowWaterMark; i++) { - var mockConnection = MockInboundConnectionImpl(null, 'mock session $i'); + var mockConnection = + MockInboundConnectionImpl(mockSocket, 'mock session $i'); connections.add(mockConnection); poolInstance.add(mockConnection); } @@ -162,9 +167,10 @@ void main() async { int desiredPoolSize = (maxPoolSize * 0.9).floor(); int numUnauthenticated = 0; for (int i = 0; i < desiredPoolSize; i++) { - var mockConnection = MockInboundConnectionImpl(null, 'mock session $i'); + var mockConnection = + MockInboundConnectionImpl(mockSocket, 'mock session $i'); if (i.isEven) { - mockConnection.getMetaData().isAuthenticated = true; + mockConnection.metaData.isAuthenticated = true; } else { numUnauthenticated++; } @@ -279,17 +285,17 @@ int calcActualAllowableIdleTime( } class MockInboundConnectionImpl extends InboundConnectionImpl { - MockInboundConnectionImpl(Socket? socket, String sessionId) + MockInboundConnectionImpl(Socket socket, String sessionId) : super(socket, sessionId, owningPool: InboundConnectionPool.getInstance()); @override Future close() async { - getMetaData().isClosed = true; + metaData.isClosed = true; } @override void write(String data) { - getMetaData().lastAccessed = DateTime.now().toUtc(); + metaData.lastAccessed = DateTime.now().toUtc(); } } diff --git a/packages/at_secondary_server/test/local_lookup_meta_test.dart b/packages/at_secondary_server/test/local_lookup_meta_test.dart index 32c234efb..24a1942cf 100644 --- a/packages/at_secondary_server/test/local_lookup_meta_test.dart +++ b/packages/at_secondary_server/test/local_lookup_meta_test.dart @@ -1,3 +1,5 @@ +import 'dart:io'; + import 'package:at_persistence_spec/at_persistence_spec.dart'; import 'package:at_secondary/src/verb/handler/local_lookup_verb_handler.dart'; import 'package:at_server_spec/at_verb_spec.dart'; @@ -6,11 +8,16 @@ import 'package:at_secondary/src/utils/handler_util.dart'; import 'package:at_commons/at_commons.dart'; import 'package:mocktail/mocktail.dart'; -class MockSecondaryKeyStore extends Mock implements SecondaryKeyStore {} +import 'test_utils.dart'; void main() { SecondaryKeyStore mockKeyStore = MockSecondaryKeyStore(); + MockSocket mockSocket = MockSocket(); + setUpAll(() { + when(() => mockSocket.setOption(SocketOption.tcpNoDelay, true)) + .thenReturn(true); + }); group('A group of llookup meta verb tests', () { test('test llookup meta', () { var verb = LocalLookup(); diff --git a/packages/at_secondary_server/test/local_lookup_verb_test.dart b/packages/at_secondary_server/test/local_lookup_verb_test.dart index 319496159..9cc386411 100644 --- a/packages/at_secondary_server/test/local_lookup_verb_test.dart +++ b/packages/at_secondary_server/test/local_lookup_verb_test.dart @@ -22,10 +22,16 @@ import 'package:uuid/uuid.dart'; import 'test_utils.dart'; -class MockSecondaryKeyStore extends Mock implements SecondaryKeyStore {} - void main() { - SecondaryKeyStore mockKeyStore = MockSecondaryKeyStore(); + late SecondaryKeyStore mockKeyStore; + late MockSocket mockSocket; + + setUp(() { + mockKeyStore = MockSecondaryKeyStore(); + mockSocket = MockSocket(); + when(() => mockSocket.setOption(SocketOption.tcpNoDelay, true)) + .thenReturn(true); + }); group('A group of local_lookup verb tests', () { test('test lookup key-value', () { @@ -154,7 +160,7 @@ void main() { var fromVerbHandler = FromVerbHandler(keyStoreManager.getKeyStore()); AtSecondaryServerImpl.getInstance().currentAtSign = '@test_user_1'; var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); var fromVerbParams = HashMap(); fromVerbParams.putIfAbsent('atSign', () => 'test_user_1'); var response = Response(); @@ -170,7 +176,7 @@ void main() { await cramVerbHandler.processVerb( cramResponse, cramVerbParams, atConnection); var connectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; expect(connectionMetadata.isAuthenticated, true); expect(cramResponse.data, 'success'); //Update Verb @@ -205,7 +211,7 @@ void main() { var fromVerbHandler = FromVerbHandler(keyStoreManager.getKeyStore()); AtSecondaryServerImpl.getInstance().currentAtSign = '@test_user_1'; var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); var fromVerbParams = HashMap(); fromVerbParams.putIfAbsent('atSign', () => 'test_user_1'); var response = Response(); @@ -221,7 +227,7 @@ void main() { await cramVerbHandler.processVerb( cramResponse, cramVerbParams, atConnection); var connectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; expect(connectionMetadata.isAuthenticated, true); expect(cramResponse.data, 'success'); //Update Verb diff --git a/packages/at_secondary_server/test/lookup_meta_test.dart b/packages/at_secondary_server/test/lookup_meta_test.dart index 52cce4618..5ad1e03cd 100644 --- a/packages/at_secondary_server/test/lookup_meta_test.dart +++ b/packages/at_secondary_server/test/lookup_meta_test.dart @@ -6,13 +6,8 @@ import 'package:at_server_spec/at_verb_spec.dart'; import 'package:test/test.dart'; import 'package:at_secondary/src/utils/handler_util.dart'; import 'package:at_commons/at_commons.dart'; -import 'package:mocktail/mocktail.dart'; -class MockSecondaryKeyStore extends Mock implements SecondaryKeyStore {} - -class MockOutboundClientManager extends Mock implements OutboundClientManager {} - -class MockAtCacheManager extends Mock implements AtCacheManager {} +import 'test_utils.dart'; void main() { SecondaryKeyStore mockKeyStore = MockSecondaryKeyStore(); diff --git a/packages/at_secondary_server/test/lookup_verb_test.dart b/packages/at_secondary_server/test/lookup_verb_test.dart index 68b756ca0..4cd38ed99 100644 --- a/packages/at_secondary_server/test/lookup_verb_test.dart +++ b/packages/at_secondary_server/test/lookup_verb_test.dart @@ -349,7 +349,7 @@ void main() { 'all', bobData, key: '$alice:$keyName')!; - inboundConnection.getMetaData().isAuthenticated = + inboundConnection.metaData.isAuthenticated = true; // owner connection, authenticated when(() => mockOutboundConnection.write('lookup:all:$keyName\n')) @@ -377,7 +377,7 @@ void main() { // some key sharedBy @bob var keyName = 'some_key.some_namespace$bob'; - inboundConnection.getMetaData().isAuthenticated = + inboundConnection.metaData.isAuthenticated = true; // owner connection, authenticated when(() => mockOutboundConnection.write('lookup:all:$keyName\n')) @@ -406,7 +406,7 @@ void main() { expect(secondaryKeyStore.isKeyExists(keyName), false); expect(secondaryKeyStore.isKeyExists('$bob:$keyName'), true); - inboundConnection.getMetaData().isPolAuthenticated = + inboundConnection.metaData.isPolAuthenticated = true; // connection from @bob atServer to @alice atServer, polAuthenticated inboundConnection.metadata.self = false; inboundConnection.metadata.from = true; diff --git a/packages/at_secondary_server/test/monitor_verb_test.dart b/packages/at_secondary_server/test/monitor_verb_test.dart index 2b18ad218..a2ff23ad6 100644 --- a/packages/at_secondary_server/test/monitor_verb_test.dart +++ b/packages/at_secondary_server/test/monitor_verb_test.dart @@ -27,7 +27,7 @@ void main() { }); test('A test to verify monitor verb writes all notifications', () async { HashMap verbParams = HashMap(); - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; MonitorVerbHandler monitorVerbHandler = MonitorVerbHandler(secondaryKeyStore); await monitorVerbHandler.processVerb( @@ -62,7 +62,7 @@ void main() { () async { HashMap verbParams = HashMap(); verbParams[AtConstants.regex] = 'wavi'; - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; MonitorVerbHandler monitorVerbHandler = MonitorVerbHandler(secondaryKeyStore); await monitorVerbHandler.processVerb( @@ -122,9 +122,9 @@ void main() { () async { HashMap verbParams = HashMap(); verbParams[AtConstants.regex] = 'wavi'; - inboundConnection.getMetaData().isAuthenticated = true; - (inboundConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId = await setEnrollmentKey(jsonEncode({"wavi": "r"})); + inboundConnection.metaData.isAuthenticated = true; + (inboundConnection.metaData as InboundConnectionMetadata).enrollmentId = + await setEnrollmentKey(jsonEncode({"wavi": "r"})); MonitorVerbHandler monitorVerbHandler = MonitorVerbHandler(secondaryKeyStore); @@ -171,9 +171,8 @@ void main() { 'A test to verify notifications matching multiple namespaces in enrollment are pushed', () async { HashMap verbParams = HashMap(); - inboundConnection.getMetaData().isAuthenticated = true; - (inboundConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId = + inboundConnection.metaData.isAuthenticated = true; + (inboundConnection.metaData as InboundConnectionMetadata).enrollmentId = await setEnrollmentKey(jsonEncode({"wavi": "r", "buzz": 'rw'})); MonitorVerbHandler monitorVerbHandler = @@ -231,9 +230,8 @@ void main() { () async { HashMap verbParams = HashMap(); verbParams[AtConstants.regex] = 'wavi'; - inboundConnection.getMetaData().isAuthenticated = true; - (inboundConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId = + inboundConnection.metaData.isAuthenticated = true; + (inboundConnection.metaData as InboundConnectionMetadata).enrollmentId = await setEnrollmentKey(jsonEncode({"wavi": "r", "buzz": "rw"})); MonitorVerbHandler monitorVerbHandler = @@ -285,15 +283,15 @@ void main() { 'enroll:request:{"appName":"wavi","deviceName":"mydevice","namespaces":{"wavi":"rw"},"apkamPublicKey":"dummy_apkam_public_key"}'; HashMap enrollmentRequestVerbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().authType = AuthType.cram; - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session_id'; + inboundConnection.metaData.authType = AuthType.cram; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session_id'; EnrollVerbHandler enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); await enrollVerbHandler.processVerb( response, enrollmentRequestVerbParams, inboundConnection); - (inboundConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId = jsonDecode(response.data!)['enrollmentId']; + (inboundConnection.metaData as InboundConnectionMetadata).enrollmentId = + jsonDecode(response.data!)['enrollmentId']; expect(jsonDecode(response.data!)['status'], 'approved'); MonitorVerbHandler monitorVerbHandler = @@ -432,7 +430,7 @@ void main() { 'Verify unauthenticated exception is thrown when connection is not authenticated', () async { HashMap verbParams = HashMap(); - inboundConnection.getMetaData().isAuthenticated = false; + inboundConnection.metaData.isAuthenticated = false; MonitorVerbHandler monitorVerbHandler = MonitorVerbHandler(secondaryKeyStore); expect( @@ -449,7 +447,7 @@ void main() { () async { HashMap verbParams = HashMap(); verbParams[AtConstants.regex] = '['; - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; MonitorVerbHandler monitorVerbHandler = MonitorVerbHandler(secondaryKeyStore); await monitorVerbHandler.processVerb( @@ -478,9 +476,9 @@ void main() { () async { HashMap verbParams = HashMap(); verbParams[AtConstants.regex] = '['; - inboundConnection.getMetaData().isAuthenticated = true; - (inboundConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId = await setEnrollmentKey(jsonEncode({"wavi": "r"})); + inboundConnection.metaData.isAuthenticated = true; + (inboundConnection.metaData as InboundConnectionMetadata).enrollmentId = + await setEnrollmentKey(jsonEncode({"wavi": "r"})); MonitorVerbHandler monitorVerbHandler = MonitorVerbHandler(secondaryKeyStore); await monitorVerbHandler.processVerb( @@ -519,7 +517,7 @@ void main() { () async { HashMap verbParams = HashMap(); verbParams[AtConstants.monitorSelfNotifications] = 'selfNotifications'; - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; MonitorVerbHandler monitorVerbHandler = MonitorVerbHandler(secondaryKeyStore); await monitorVerbHandler.processVerb( @@ -555,7 +553,7 @@ void main() { 'A test to verify received notification is written to monitor connection invoking callback method', () async { HashMap verbParams = HashMap(); - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; MonitorVerbHandler monitorVerbHandler = MonitorVerbHandler(secondaryKeyStore); await monitorVerbHandler.processVerb( @@ -591,7 +589,7 @@ void main() { 'A test to verify sent notification is not written to monitor connection', () async { HashMap verbParams = HashMap(); - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; MonitorVerbHandler monitorVerbHandler = MonitorVerbHandler(secondaryKeyStore); await monitorVerbHandler.processVerb( @@ -623,8 +621,8 @@ void main() { Future setEnrollmentKey(String namespace) async { Response response = Response(); EnrollVerbHandler enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session'; // OTP Verb HashMap totpVerbParams = getVerbParam(VerbSyntax.otp, 'otp:get'); @@ -635,7 +633,7 @@ Future setEnrollmentKey(String namespace) async { 'enroll:request:{"appName":"wavi","deviceName":"mydevice","namespaces":$namespace,"otp":"${response.data}","apkamPublicKey":"dummy_apkam_public_key"}'; HashMap enrollmentRequestVerbParams = getVerbParam(VerbSyntax.enroll, enrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = false; + inboundConnection.metaData.isAuthenticated = false; enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); await enrollVerbHandler.processVerb( response, enrollmentRequestVerbParams, inboundConnection); @@ -645,7 +643,7 @@ Future setEnrollmentKey(String namespace) async { 'enroll:approve:{"enrollmentId":"$enrollmentId"}'; HashMap approveEnrollmentVerbParams = getVerbParam(VerbSyntax.enroll, approveEnrollmentRequest); - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; enrollVerbHandler = EnrollVerbHandler(secondaryKeyStore); await enrollVerbHandler.processVerb( response, approveEnrollmentVerbParams, inboundConnection); diff --git a/packages/at_secondary_server/test/notify_list_verb_test.dart b/packages/at_secondary_server/test/notify_list_verb_test.dart index f7c07a212..82b28edb6 100644 --- a/packages/at_secondary_server/test/notify_list_verb_test.dart +++ b/packages/at_secondary_server/test/notify_list_verb_test.dart @@ -14,13 +14,17 @@ import 'package:at_server_spec/at_verb_spec.dart'; import 'package:test/test.dart'; import 'package:mocktail/mocktail.dart'; -class MockSecondaryKeyStore extends Mock implements SecondaryKeyStore {} - -class MockOutboundClientManager extends Mock implements OutboundClientManager {} +import 'test_utils.dart'; void main() { SecondaryKeyStore mockKeyStore = MockSecondaryKeyStore(); OutboundClientManager mockOutboundClientManager = MockOutboundClientManager(); + MockSocket mockSocket = MockSocket(); + + setUpAll(() { + when(() => mockSocket.setOption(SocketOption.tcpNoDelay, true)) + .thenReturn(true); + }); var storageDir = '${Directory.current.path}/test/hive'; late SecondaryKeyStoreManager keyStoreManager; @@ -133,7 +137,7 @@ void main() { var metadata = InboundConnectionMetadata() ..fromAtSign = '@alice' ..isAuthenticated = true; - var atConnection = InboundConnectionImpl(null, inBoundSessionId) + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId) ..metaData = metadata; var response = Response(); await notifyListVerbHandler.processVerb( @@ -220,7 +224,7 @@ void main() { var metadata = InboundConnectionMetadata() ..fromAtSign = '@alice' ..isAuthenticated = true; - var atConnection = InboundConnectionImpl(null, inBoundSessionId) + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId) ..metaData = metadata; var response = Response(); await notifyListVerbHandler.processVerb( @@ -300,7 +304,7 @@ void main() { var metadata = InboundConnectionMetadata() ..fromAtSign = '@alice' ..isAuthenticated = true; - var atConnection = InboundConnectionImpl(null, inBoundSessionId) + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId) ..metaData = metadata; var response = Response(); await notifyListVerbHandler.processVerb( @@ -370,7 +374,7 @@ void main() { var metadata = InboundConnectionMetadata() ..fromAtSign = '@alice' ..isAuthenticated = true; - var atConnection = InboundConnectionImpl(null, inBoundSessionId) + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId) ..metaData = metadata; var response = Response(); await notifyListVerbHandler.processVerb( @@ -416,7 +420,7 @@ void main() { var metadata = InboundConnectionMetadata() ..fromAtSign = '@alice' ..isAuthenticated = true; - var atConnection = InboundConnectionImpl(null, inBoundSessionId) + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId) ..metaData = metadata; var response = Response(); await notifyFetchVerbHandler.processVerb( @@ -443,7 +447,7 @@ void main() { var metadata = InboundConnectionMetadata() ..fromAtSign = '@alice' ..isAuthenticated = true; - var atConnection = InboundConnectionImpl(null, inBoundSessionId) + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId) ..metaData = metadata; var response = Response(); await notifyFetchVerbHandler.processVerb( diff --git a/packages/at_secondary_server/test/notify_remove_test.dart b/packages/at_secondary_server/test/notify_remove_test.dart index 1e227a364..3d4193059 100644 --- a/packages/at_secondary_server/test/notify_remove_test.dart +++ b/packages/at_secondary_server/test/notify_remove_test.dart @@ -10,16 +10,20 @@ import 'package:at_secondary/src/utils/handler_util.dart'; import 'package:at_secondary/src/verb/handler/notify_list_verb_handler.dart'; import 'package:at_secondary/src/verb/handler/notify_remove_verb_handler.dart'; import 'package:at_server_spec/verbs.dart'; -import 'package:test/test.dart'; import 'package:mocktail/mocktail.dart'; +import 'package:test/test.dart'; -class MockSecondaryKeyStore extends Mock implements SecondaryKeyStore {} - -class MockOutboundClientManager extends Mock implements OutboundClientManager {} +import 'test_utils.dart'; void main() { SecondaryKeyStore mockKeyStore = MockSecondaryKeyStore(); OutboundClientManager mockOutboundClientManager = MockOutboundClientManager(); + MockSocket mockSocket = MockSocket(); + + setUpAll(() { + when(() => mockSocket.setOption(SocketOption.tcpNoDelay, true)) + .thenReturn(true); + }); var storageDir = '${Directory.current.path}/test/hive'; late SecondaryKeyStoreManager keyStoreManager; @@ -46,7 +50,7 @@ void main() { await AtNotificationKeystore.getInstance().put('122', notificationObj); // Dummy Inbound connection - var atConnection = InboundConnectionImpl(null, '123') + var atConnection = InboundConnectionImpl(mockSocket, '123') ..metaData = (InboundConnectionMetadata() ..fromAtSign = '@alice' ..isAuthenticated = true); diff --git a/packages/at_secondary_server/test/notify_verb_test.dart b/packages/at_secondary_server/test/notify_verb_test.dart index 492ec9a83..ff311e376 100644 --- a/packages/at_secondary_server/test/notify_verb_test.dart +++ b/packages/at_secondary_server/test/notify_verb_test.dart @@ -24,13 +24,17 @@ import 'package:crypto/crypto.dart'; import 'package:test/test.dart'; import 'package:mocktail/mocktail.dart'; -class MockSecondaryKeyStore extends Mock implements SecondaryKeyStore {} - -class MockOutboundClientManager extends Mock implements OutboundClientManager {} +import 'test_utils.dart'; void main() { SecondaryKeyStore mockKeyStore = MockSecondaryKeyStore(); OutboundClientManager mockOutboundClientManager = MockOutboundClientManager(); + MockSocket mockSocket = MockSocket(); + + setUpAll(() { + when(() => mockSocket.setOption(SocketOption.tcpNoDelay, true)) + .thenReturn(true); + }); var storageDir = '${Directory.current.path}/test/hive'; late SecondaryKeyStoreManager keyStoreManager; @@ -98,7 +102,7 @@ void main() { () { AtSecondaryServerImpl.getInstance().currentAtSign = '@alice'; var notifyVerb = NotifyVerbHandler(mockKeyStore); - var inboundConnection = InboundConnectionImpl(null, '123'); + var inboundConnection = InboundConnectionImpl(mockSocket, '123'); inboundConnection.metaData = InboundConnectionMetadata() ..isAuthenticated = true; var notifyResponse = Response(); @@ -167,7 +171,7 @@ void main() { test('test notify verb - invalid ttl value', () { AtSecondaryServerImpl.getInstance().currentAtSign = '@alice'; var notifyVerb = NotifyVerbHandler(mockKeyStore); - var inboundConnection = InboundConnectionImpl(null, '123'); + var inboundConnection = InboundConnectionImpl(mockSocket, '123'); inboundConnection.metaData = InboundConnectionMetadata() ..isAuthenticated = true; var notifyResponse = Response(); @@ -186,7 +190,7 @@ void main() { test('test notify verb - invalid ttb value', () { AtSecondaryServerImpl.getInstance().currentAtSign = '@alice'; var notifyVerb = NotifyVerbHandler(mockKeyStore); - var inboundConnection = InboundConnectionImpl(null, '123'); + var inboundConnection = InboundConnectionImpl(mockSocket, '123'); inboundConnection.metaData = InboundConnectionMetadata() ..isAuthenticated = true; var notifyResponse = Response(); @@ -204,7 +208,7 @@ void main() { test('test notify verb - ttr = -2 invalid value ', () { AtSecondaryServerImpl.getInstance().currentAtSign = '@alice'; var notifyVerb = NotifyVerbHandler(mockKeyStore); - var inboundConnection = InboundConnectionImpl(null, '123'); + var inboundConnection = InboundConnectionImpl(mockSocket, '123'); inboundConnection.metaData = InboundConnectionMetadata() ..isAuthenticated = true; var notifyResponse = Response(); @@ -240,7 +244,7 @@ void main() { AtSecondaryServerImpl.getInstance().currentAtSign = '@alice'; var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); var command = 'notify:update:messagetype:text:@bob:hello'; var regex = verb.syntax(); @@ -323,7 +327,7 @@ void main() { var fromVerbHandler = FromVerbHandler(keyStoreManager.getKeyStore()); AtSecondaryServerImpl.getInstance().currentAtSign = '@test_user_1'; var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); var fromVerbParams = HashMap(); fromVerbParams.putIfAbsent('atSign', () => 'test_user_1'); var response = Response(); @@ -339,7 +343,7 @@ void main() { await cramVerbHandler.processVerb( cramResponse, cramVerbParams, atConnection); var connectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; expect(connectionMetadata.isAuthenticated, true); expect(cramResponse.data, 'success'); //Notify Verb @@ -377,7 +381,7 @@ void main() { var fromVerbHandler = FromVerbHandler(keyStoreManager.getKeyStore()); AtSecondaryServerImpl.getInstance().currentAtSign = '@test_user_1'; var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); var fromVerbParams = HashMap(); fromVerbParams.putIfAbsent('atSign', () => 'test_user_1'); var response = Response(); @@ -393,7 +397,7 @@ void main() { await cramVerbHandler.processVerb( cramResponse, cramVerbParams, atConnection); var connectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; expect(connectionMetadata.isAuthenticated, true); expect(cramResponse.data, 'success'); //Notify Verb @@ -430,7 +434,7 @@ void main() { SecondaryKeyStore keyStore = keyStoreManager.getKeyStore(); var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); atConnection.metaData.isAuthenticated = true; var command = 'notify:update:messagetype:text:@bob:hello'; @@ -929,7 +933,7 @@ void main() { notifyFetch = NotifyFetchVerbHandler(keyStore); var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - atConnection = InboundConnectionImpl(null, inBoundSessionId); + atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); // first notification firstNotificationVerbParams.putIfAbsent('id', () => 'abc-123'); diff --git a/packages/at_secondary_server/test/otp_verb_test.dart b/packages/at_secondary_server/test/otp_verb_test.dart index 023672bbf..4afa46beb 100644 --- a/packages/at_secondary_server/test/otp_verb_test.dart +++ b/packages/at_secondary_server/test/otp_verb_test.dart @@ -22,7 +22,7 @@ void main() { Response response = Response(); HashMap verbParams = getVerbParam(VerbSyntax.otp, 'otp:get'); - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; OtpVerbHandler otpVerbHandler = OtpVerbHandler(secondaryKeyStore); await otpVerbHandler.processVerb(response, verbParams, inboundConnection); expect(response.data, isNotNull); @@ -36,7 +36,7 @@ void main() { Response response = Response(); HashMap verbParams = getVerbParam(VerbSyntax.otp, 'otp:get'); - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; OtpVerbHandler otpVerbHandler = OtpVerbHandler(secondaryKeyStore); await otpVerbHandler.processVerb( response, verbParams, inboundConnection); @@ -52,7 +52,7 @@ void main() { test('A test to verify otp:get with TTL set is active before TTL is met', () async { Response response = Response(); - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; HashMap verbParams = getVerbParam(VerbSyntax.otp, 'otp:get:ttl:1000'); OtpVerbHandler otpVerbHandler = OtpVerbHandler(secondaryKeyStore); @@ -64,7 +64,7 @@ void main() { test('A test to verify otp:get with TTL set expires after the TTL is met', () async { Response response = Response(); - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; HashMap verbParams = getVerbParam(VerbSyntax.otp, 'otp:get:ttl:1'); OtpVerbHandler otpVerbHandler = OtpVerbHandler(secondaryKeyStore); @@ -106,7 +106,7 @@ void main() { Response response = Response(); HashMap verbParams = getVerbParam(VerbSyntax.otp, 'otp:get'); - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; OtpVerbHandler otpVerbHandler = OtpVerbHandler(secondaryKeyStore); await otpVerbHandler.processVerb(response, verbParams, inboundConnection); expect(await otpVerbHandler.isOTPValid(response.data), true); @@ -117,7 +117,7 @@ void main() { Response response = Response(); HashMap verbParams = getVerbParam(VerbSyntax.otp, 'otp:get'); - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; OtpVerbHandler otpVerbHandler = OtpVerbHandler(secondaryKeyStore); otpVerbHandler.otpExpiryInMills = 1; await otpVerbHandler.processVerb(response, verbParams, inboundConnection); @@ -139,7 +139,7 @@ void main() { Response response = Response(); HashMap verbParams = getVerbParam(VerbSyntax.otp, 'otp:get'); - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; OtpVerbHandler otpVerbHandler = OtpVerbHandler(secondaryKeyStore); await otpVerbHandler.processVerb(response, verbParams, inboundConnection); String? otp = response.data; @@ -167,9 +167,9 @@ void main() { Response response = Response(); HashMap verbParams = getVerbParam(VerbSyntax.otp, 'otp:put:$passcode'); - inboundConnection.getMetaData().isAuthenticated = true; - (inboundConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId = enrollmentId; + inboundConnection.metaData.isAuthenticated = true; + (inboundConnection.metaData as InboundConnectionMetadata).enrollmentId = + enrollmentId; OtpVerbHandler otpVerbHandler = OtpVerbHandler(secondaryKeyStore); await otpVerbHandler.processVerb(response, verbParams, inboundConnection); expect(await otpVerbHandler.isOTPValid(passcode), true); @@ -183,9 +183,9 @@ void main() { Response response = Response(); HashMap verbParams = getVerbParam(VerbSyntax.otp, 'otp:put:$passcode'); - inboundConnection.getMetaData().isAuthenticated = true; - (inboundConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId = enrollmentId; + inboundConnection.metaData.isAuthenticated = true; + (inboundConnection.metaData as InboundConnectionMetadata).enrollmentId = + enrollmentId; OtpVerbHandler otpVerbHandler = OtpVerbHandler(secondaryKeyStore); await otpVerbHandler.processVerb(response, verbParams, inboundConnection); expect(await otpVerbHandler.isOTPValid(passcode), true); diff --git a/packages/at_secondary_server/test/outbound_client_manager_test.dart b/packages/at_secondary_server/test/outbound_client_manager_test.dart index 6800090b7..77f2378d8 100644 --- a/packages/at_secondary_server/test/outbound_client_manager_test.dart +++ b/packages/at_secondary_server/test/outbound_client_manager_test.dart @@ -4,9 +4,22 @@ import 'package:at_secondary/src/connection/inbound/inbound_connection_impl.dart import 'package:at_secondary/src/connection/outbound/outbound_connection_impl.dart'; import 'package:at_secondary/src/server/at_secondary_impl.dart'; import 'package:at_secondary/src/server/server_context.dart'; +import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; +import 'test_utils.dart'; + void main() { + MockSocket mockSocket_1 = MockSocket(); + MockSocket mockSocket_2 = MockSocket(); + + setUpAll(() { + when(() => mockSocket_1.setOption(SocketOption.tcpNoDelay, true)) + .thenReturn(true); + when(() => mockSocket_2.setOption(SocketOption.tcpNoDelay, true)) + .thenReturn(true); + }); + setUp(() { var serverContext = AtSecondaryContext(); serverContext.unauthenticatedInboundIdleTimeMillis = 50; @@ -16,8 +29,7 @@ void main() { group('A group of outbound client manager tests', () { test('test outbound client manager - create new client ', () { - Socket? dummySocket; - var inboundConnection = InboundConnectionImpl(dummySocket, 'aaa'); + var inboundConnection = InboundConnectionImpl(mockSocket_1, 'aaa'); var clientManager = AtSecondaryServerImpl.getInstance().outboundClientManager; clientManager.poolSize = 5; @@ -28,7 +40,7 @@ void main() { // test('test outbound client manager - get existing client ', () { // var dummySocket = DummySocket(1); - // var inboundConnection = InboundConnectionImpl(dummySocket, 'aaa'); + // var inboundConnection = InboundConnectionImpl(mockSocket, 'aaa'); // var clientManager = AtSecondaryServerImpl.getInstance().outboundClientManager; // clientManager.init(5); // var outBoundClient_1 = @@ -42,9 +54,9 @@ void main() { // }); // test('test outbound client manager - add multiple clients ', () { - // var dummySocket_1 = DummySocket(1); + // var mockSocket_1 = DummySocket(1); // var dummySocket_2 = DummySocket(2); - // var inboundConnection_1 = InboundConnectionImpl(dummySocket_1, 'aaa'); + // var inboundConnection_1 = InboundConnectionImpl(mockSocket_1, 'aaa'); // var inboundConnection_2 = InboundConnectionImpl(dummySocket_2, 'bbb'); // var clientManager = AtSecondaryServerImpl.getInstance().outboundClientManager; // clientManager.init(5); @@ -58,10 +70,10 @@ void main() { // }); // test('test outbound client manager - capacity exceeded ', () { - // //var dummySocket_1 = DummySocket(1); + // //var mockSocket_1 = DummySocket(1); // var dummySocket_2 = DummySocket(2); // var dummySocket_3 = DummySocket(3); - // var inboundConnection_1 = InboundConnectionImpl(dummySocket_1, 'aaa'); + // var inboundConnection_1 = InboundConnectionImpl(mockSocket_1, 'aaa'); // var inboundConnection_2 = InboundConnectionImpl(dummySocket_2, 'bbb'); // var inboundConnection_3 = InboundConnectionImpl(dummySocket_3, 'ccc'); // var clientManager = AtSecondaryServerImpl.getInstance().outboundClientManager; @@ -78,8 +90,7 @@ void main() { test( 'test outbound client manager - inbound is closed, outbound client is invalid', () { - Socket? dummySocket; - var inboundConnection = InboundConnectionImpl(dummySocket, 'aaa'); + var inboundConnection = InboundConnectionImpl(mockSocket_1, 'aaa'); var clientManager = AtSecondaryServerImpl.getInstance().outboundClientManager; clientManager.poolSize = 5; @@ -91,14 +102,13 @@ void main() { test( 'test outbound client manager - outbound client is closed, inbound is still valid', () { - Socket? dummySocket_1, dummySocket_2; - var inboundConnection = InboundConnectionImpl(dummySocket_1, 'aaa'); + var inboundConnection = InboundConnectionImpl(mockSocket_1, 'aaa'); var clientManager = AtSecondaryServerImpl.getInstance().outboundClientManager; clientManager.poolSize = 5; var outBoundClient_1 = clientManager.getClient('bob', inboundConnection); outBoundClient_1.outboundConnection = - OutboundConnectionImpl(dummySocket_2, 'bob'); + OutboundConnectionImpl(mockSocket_2, 'bob'); outBoundClient_1.close(); expect(inboundConnection.isInValid(), false); }); @@ -106,14 +116,13 @@ void main() { test( 'test outbound client manager - outbound client is idle and becomes invalid', () { - Socket? dummySocket_1, dummySocket_2; - var inboundConnection = InboundConnectionImpl(dummySocket_1, 'aaa'); + var inboundConnection = InboundConnectionImpl(mockSocket_1, 'aaa'); var clientManager = AtSecondaryServerImpl.getInstance().outboundClientManager; clientManager.poolSize = 5; var outBoundClient_1 = clientManager.getClient('bob', inboundConnection); outBoundClient_1.outboundConnection = - OutboundConnectionImpl(dummySocket_2, 'bob'); + OutboundConnectionImpl(mockSocket_2, 'bob'); expect(outBoundClient_1.isInValid(), false); sleep(Duration( milliseconds: AtSecondaryServerImpl.getInstance() diff --git a/packages/at_secondary_server/test/outbound_client_pool_test.dart b/packages/at_secondary_server/test/outbound_client_pool_test.dart index c18c23ed0..33f4c1456 100644 --- a/packages/at_secondary_server/test/outbound_client_pool_test.dart +++ b/packages/at_secondary_server/test/outbound_client_pool_test.dart @@ -7,12 +7,22 @@ import 'package:at_secondary/src/connection/outbound/outbound_connection_impl.da import 'package:at_secondary/src/notification/notify_connection_pool.dart'; import 'package:at_secondary/src/server/at_secondary_impl.dart'; import 'package:at_secondary/src/server/server_context.dart'; +import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; +import 'test_utils.dart'; + void main() async { // ignore: prefer_typing_uninitialized_variables late OutboundClientPool outboundClientPool; final int outboundIdleTimeMillis = 200; + MockSocket mockSocket = MockSocket(); + + setUpAll(() { + when(() => mockSocket.setOption(SocketOption.tcpNoDelay, true)) + .thenReturn(true); + }); + setUp(() { var serverContext = AtSecondaryContext(); serverContext.outboundIdleTimeMillis = outboundIdleTimeMillis; @@ -34,13 +44,12 @@ void main() async { expect(outboundClientPool.getCurrentSize(), 0); }); - Socket? dummySocket; OutboundClient newOutboundClient(String toAtSign) { - var inboundConnection = InboundConnectionImpl(dummySocket, toAtSign); + var inboundConnection = InboundConnectionImpl(mockSocket, toAtSign); OutboundClient outboundClient = OutboundClient(inboundConnection, toAtSign, AtSecondaryServerImpl.getInstance().secondaryAddressFinder); outboundClient.outboundConnection = - OutboundConnectionImpl(dummySocket, toAtSign); + OutboundConnectionImpl(mockSocket, toAtSign); return outboundClient; } diff --git a/packages/at_secondary_server/test/outbound_client_test.dart b/packages/at_secondary_server/test/outbound_client_test.dart index 1515bde24..e82f9d709 100644 --- a/packages/at_secondary_server/test/outbound_client_test.dart +++ b/packages/at_secondary_server/test/outbound_client_test.dart @@ -5,33 +5,39 @@ import 'package:at_secondary/src/connection/outbound/outbound_connection_impl.da import 'package:at_secondary/src/server/at_secondary_impl.dart'; import 'package:at_secondary/src/server/server_context.dart'; import 'package:at_commons/at_commons.dart'; +import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; +import 'test_utils.dart'; + void main() { + late MockSocket mockSocket; + setUp(() { var serverContext = AtSecondaryContext(); serverContext.outboundIdleTimeMillis = 50; AtSecondaryServerImpl.getInstance().serverContext = serverContext; + mockSocket = MockSocket(); + when(() => mockSocket.setOption(SocketOption.tcpNoDelay, true)) + .thenReturn(true); }); group('A group of outbound client tests', () { test('test outbound client - invalid outbound client if inbound is invalid', () { - Socket? dummySocket; - var connection1 = InboundConnectionImpl(dummySocket, 'aaa'); + var connection1 = InboundConnectionImpl(mockSocket, 'aaa'); var client = OutboundClient(connection1, 'bob', AtSecondaryServerImpl.getInstance().secondaryAddressFinder); - client.outboundConnection = OutboundConnectionImpl(dummySocket, 'bob'); + client.outboundConnection = OutboundConnectionImpl(mockSocket, 'bob'); connection1.close(); expect(client.isInValid(), true); }); test('test outbound client - invalid outbound client idle', () { - Socket? dummySocket; - var connection1 = InboundConnectionImpl(dummySocket, 'aaa'); + var connection1 = InboundConnectionImpl(mockSocket, 'aaa'); var client = OutboundClient(connection1, 'bob', AtSecondaryServerImpl.getInstance().secondaryAddressFinder); - client.outboundConnection = OutboundConnectionImpl(dummySocket, 'bob'); + client.outboundConnection = OutboundConnectionImpl(mockSocket, 'bob'); sleep(Duration( milliseconds: AtSecondaryServerImpl.getInstance() .serverContext! @@ -41,23 +47,21 @@ void main() { }); test('test outbound client - valid outbound client', () { - Socket? dummySocket; - var connection1 = InboundConnectionImpl(dummySocket, 'aaa'); + var connection1 = InboundConnectionImpl(mockSocket, 'aaa'); var client = OutboundClient(connection1, 'bob', AtSecondaryServerImpl.getInstance().secondaryAddressFinder); - client.outboundConnection = OutboundConnectionImpl(dummySocket, 'bob'); + client.outboundConnection = OutboundConnectionImpl(mockSocket, 'bob'); expect(client.isInValid(), false); }); test( 'test outbound client - stale connection - connection invalid exception', () { - Socket? dummySocket; - var connection1 = InboundConnectionImpl(dummySocket, 'aaa'); + var connection1 = InboundConnectionImpl(mockSocket, 'aaa'); var client = OutboundClient(connection1, 'bob', AtSecondaryServerImpl.getInstance().secondaryAddressFinder); - client.outboundConnection = OutboundConnectionImpl(dummySocket, 'bob'); - client.outboundConnection!.getMetaData().isStale = true; + client.outboundConnection = OutboundConnectionImpl(mockSocket, 'bob'); + client.outboundConnection!.metaData.isStale = true; expect( () => client.lookUp('test', handshake: false), throwsA(predicate( @@ -67,12 +71,11 @@ void main() { test( 'test outbound client - closed connection - connection invalid exception', () { - Socket? dummySocket; - var connection1 = InboundConnectionImpl(dummySocket, 'aaa'); + var connection1 = InboundConnectionImpl(mockSocket, 'aaa'); var client = OutboundClient(connection1, 'bob', AtSecondaryServerImpl.getInstance().secondaryAddressFinder); - client.outboundConnection = OutboundConnectionImpl(dummySocket, 'bob'); - client.outboundConnection!.getMetaData().isClosed = true; + client.outboundConnection = OutboundConnectionImpl(mockSocket, 'bob'); + client.outboundConnection!.metaData.isClosed = true; expect( () => client.lookUp('test', handshake: false), throwsA(predicate( diff --git a/packages/at_secondary_server/test/pkam_verb_test.dart b/packages/at_secondary_server/test/pkam_verb_test.dart index 2382d05a6..40143c00a 100644 --- a/packages/at_secondary_server/test/pkam_verb_test.dart +++ b/packages/at_secondary_server/test/pkam_verb_test.dart @@ -1,10 +1,8 @@ import 'dart:convert'; -import 'dart:io'; import 'package:at_commons/at_commons.dart'; import 'package:at_persistence_secondary_server/at_persistence_secondary_server.dart'; import 'package:at_secondary/src/enroll/enroll_datastore_value.dart'; -import 'package:at_secondary/src/server/at_secondary_impl.dart'; import 'package:at_secondary/src/utils/handler_util.dart'; import 'package:at_secondary/src/utils/secondary_util.dart'; import 'package:at_secondary/src/verb/handler/pkam_verb_handler.dart'; @@ -12,15 +10,12 @@ import 'package:at_server_spec/at_verb_spec.dart'; import 'package:test/test.dart'; import 'package:mocktail/mocktail.dart'; -class MockSecondaryKeyStore extends Mock implements SecondaryKeyStore {} +import 'test_utils.dart'; void main() { SecondaryKeyStore mockKeyStore = MockSecondaryKeyStore(); - var storageDir = '${Directory.current.path}/test/hive'; - SecondaryKeyStoreManager? keyStoreManager; group('pkam tests', () { - setUpAll(() async => keyStoreManager = await setUpFunc(storageDir)); test('test for pkam correct syntax', () { var verb = Pkam(); var command = 'pkam:edgvb1234'; @@ -52,7 +47,7 @@ void main() { }); test('test pkam verb handler getVerb', () { - var verbHandler = PkamVerbHandler(keyStoreManager!.getKeyStore()); + var verbHandler = PkamVerbHandler(mockKeyStore); var verb = verbHandler.getVerb(); expect(verb is Pkam, true); }); @@ -65,19 +60,19 @@ void main() { print('result : $result'); expect(result, true); }); - tearDownAll(() async => await tearDownFunc()); }); group('apkam tests', () { - setUpAll(() async { - keyStoreManager = await setUpFunc(storageDir); + late EnrollDataStoreValue enrollData; + late PkamVerbHandler pkamVerbHandler; + + setUpAll(() { + // dummy enroll value + enrollData = EnrollDataStoreValue( + 'enrollId', 'unit_test', 'test_device', 'dummy_public_key'); + pkamVerbHandler = PkamVerbHandler(mockKeyStore); }); - // dummy enroll value - EnrollDataStoreValue enrollData = EnrollDataStoreValue( - 'enrollId', 'unit_test', 'test_device', 'dummy_public_key'); - PkamVerbHandler pkamVerbHandler = PkamVerbHandler(mockKeyStore); - test('verify apkam behaviour - case: enrollment approved ', () async { enrollData.approval = EnrollApproval('approved'); AtData data = AtData()..data = jsonEncode(enrollData.toJson()); @@ -143,28 +138,5 @@ void main() { expect(apkamResult.response.errorMessage, 'enrollment_id: enrollId is expired or invalid'); }); - - tearDownAll(() async => await tearDownFunc()); }); } - -Future setUpFunc(storageDir) async { - AtSecondaryServerImpl.getInstance().currentAtSign = '@alice'; - var secondaryPersistenceStore = SecondaryPersistenceStoreFactory.getInstance() - .getSecondaryPersistenceStore( - AtSecondaryServerImpl.getInstance().currentAtSign)!; - var persistenceManager = - secondaryPersistenceStore.getHivePersistenceManager()!; - await persistenceManager.init(storageDir); - // persistenceManager.scheduleKeyExpireTask(1); //commented this line for coverage test - var keyStoreManager = secondaryPersistenceStore.getSecondaryKeyStoreManager(); - // keyStoreManager.init(); - return keyStoreManager; -} - -Future tearDownFunc() async { - var isExists = await Directory('test/hive').exists(); - if (isExists) { - Directory('test/hive/').deleteSync(recursive: true); - } -} diff --git a/packages/at_secondary_server/test/pol_verb_test.dart b/packages/at_secondary_server/test/pol_verb_test.dart index 03f5e2ccd..a48d8e61f 100644 --- a/packages/at_secondary_server/test/pol_verb_test.dart +++ b/packages/at_secondary_server/test/pol_verb_test.dart @@ -1,3 +1,5 @@ +import 'dart:io'; + import 'package:at_persistence_spec/at_persistence_spec.dart'; import 'package:at_secondary/src/caching/cache_manager.dart'; import 'package:at_secondary/src/connection/inbound/inbound_connection_impl.dart'; @@ -14,16 +16,18 @@ import 'package:at_server_spec/at_verb_spec.dart'; import 'package:test/test.dart'; import 'package:mocktail/mocktail.dart'; -class MockSecondaryKeyStore extends Mock implements SecondaryKeyStore {} - -class MockOutboundClientManager extends Mock implements OutboundClientManager {} - -class MockAtCacheManager extends Mock implements AtCacheManager {} +import 'test_utils.dart'; void main() { SecondaryKeyStore mockKeyStore = MockSecondaryKeyStore(); OutboundClientManager mockOutboundClientManager = MockOutboundClientManager(); AtCacheManager mockAtCacheManager = MockAtCacheManager(); + MockSocket mockSocket = MockSocket(); + + setUpAll(() { + when(() => mockSocket.setOption(SocketOption.tcpNoDelay, true)) + .thenReturn(true); + }); test('test pol Verb', () { var handler = PolVerbHandler( @@ -54,7 +58,7 @@ void main() { test('test pol verb - invalid syntax', () { var command = 'poll'; - var inbound = InboundConnectionImpl(null, null); + var inbound = InboundConnectionImpl(mockSocket, null); var defaultVerbExecutor = DefaultVerbExecutor(); var defaultVerbHandlerManager = DefaultVerbHandlerManager( mockKeyStore, diff --git a/packages/at_secondary_server/test/proxy_lookup_meta_test.dart b/packages/at_secondary_server/test/proxy_lookup_meta_test.dart index afe2470ff..0b6ff272d 100644 --- a/packages/at_secondary_server/test/proxy_lookup_meta_test.dart +++ b/packages/at_secondary_server/test/proxy_lookup_meta_test.dart @@ -6,13 +6,8 @@ import 'package:at_server_spec/at_verb_spec.dart'; import 'package:test/test.dart'; import 'package:at_secondary/src/utils/handler_util.dart'; import 'package:at_commons/at_commons.dart'; -import 'package:mocktail/mocktail.dart'; -class MockSecondaryKeyStore extends Mock implements SecondaryKeyStore {} - -class MockOutboundClientManager extends Mock implements OutboundClientManager {} - -class MockAtCacheManager extends Mock implements AtCacheManager {} +import 'test_utils.dart'; void main() { SecondaryKeyStore mockKeyStore = MockSecondaryKeyStore(); diff --git a/packages/at_secondary_server/test/proxy_lookup_verb_test.dart b/packages/at_secondary_server/test/proxy_lookup_verb_test.dart index afdaf0ef1..815adcb7d 100644 --- a/packages/at_secondary_server/test/proxy_lookup_verb_test.dart +++ b/packages/at_secondary_server/test/proxy_lookup_verb_test.dart @@ -69,7 +69,7 @@ void main() { () async {}); test('plookup - not in cache and does not exist on remote', () async { - inboundConnection.getMetaData().isAuthenticated = + inboundConnection.metaData.isAuthenticated = true; // owner connection, authenticated when(() => mockOutboundConnection.write('lookup:all:$keyName\n')) diff --git a/packages/at_secondary_server/test/scan_verb_test.dart b/packages/at_secondary_server/test/scan_verb_test.dart index 73a19f765..9ded39d92 100644 --- a/packages/at_secondary_server/test/scan_verb_test.dart +++ b/packages/at_secondary_server/test/scan_verb_test.dart @@ -1,4 +1,5 @@ import 'dart:convert'; +import 'dart:io'; import 'package:at_commons/at_commons.dart'; import 'package:at_persistence_secondary_server/at_persistence_secondary_server.dart'; @@ -14,12 +15,20 @@ import 'package:at_secondary/src/verb/handler/scan_verb_handler.dart'; import 'package:at_secondary/src/verb/manager/verb_handler_manager.dart'; import 'package:at_server_spec/at_server_spec.dart'; import 'package:at_server_spec/at_verb_spec.dart'; +import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import 'package:uuid/uuid.dart'; import 'test_utils.dart'; void main() { + MockSocket mockSocket = MockSocket(); + + setUpAll(() { + when(() => mockSocket.setOption(SocketOption.tcpNoDelay, true)) + .thenReturn(true); + }); + group('A group of scan verb tests', () { setUpAll(() async { await verbTestsSetUp(); @@ -71,7 +80,7 @@ void main() { test('test scan verb - invalid syntax', () { var command = 'scann'; - var inbound = InboundConnectionImpl(null, null); + var inbound = InboundConnectionImpl(mockSocket, null); var defaultVerbExecutor = DefaultVerbExecutor(); var defaultVerbHandlerManager = DefaultVerbHandlerManager( secondaryKeyStore, @@ -118,7 +127,7 @@ void main() { }); test('A test to verify all keys are returned for a simple scan', () async { AtSecondaryServerImpl.getInstance().currentAtSign = alice; - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; await secondaryKeyStore.put( 'public:location.wavi@alice', AtData()..data = 'dummy_value'); await secondaryKeyStore.put( @@ -143,7 +152,7 @@ void main() { 'A test to verify only keys matching the regex are returned when regex is supplied to scan', () async { AtSecondaryServerImpl.getInstance().currentAtSign = alice; - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; await secondaryKeyStore.put( 'public:location.wavi@alice', AtData()..data = 'dummy_value'); await secondaryKeyStore.put( @@ -166,7 +175,7 @@ void main() { 'A test to verify public hidden keys are returned when showhidden set to true', () async { AtSecondaryServerImpl.getInstance().currentAtSign = alice; - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; await secondaryKeyStore.put( 'public:__phone.wavi@alice', AtData()..data = 'dummy_value'); await secondaryKeyStore.put( @@ -185,7 +194,7 @@ void main() { 'A test to verify public hidden keys are not returned when showhidden set to false', () async { AtSecondaryServerImpl.getInstance().currentAtSign = alice; - inboundConnection.getMetaData().isAuthenticated = true; + inboundConnection.metaData.isAuthenticated = true; await secondaryKeyStore.put( 'public:__phone.wavi@alice', AtData()..data = 'dummy_value'); await secondaryKeyStore.put( @@ -213,9 +222,9 @@ void main() { test( 'A test to verify keys specific to forAtSign are returned on pol authenticated connection', () async { - inboundConnection.getMetaData().isPolAuthenticated = true; - (inboundConnection.getMetaData() as InboundConnectionMetadata) - .fromAtSign = '@bob'; + inboundConnection.metaData.isPolAuthenticated = true; + (inboundConnection.metaData as InboundConnectionMetadata).fromAtSign = + '@bob'; await secondaryKeyStore.put( '@bob:phone.wavi@alice', AtData()..data = 'dummy-value'); @@ -229,7 +238,7 @@ void main() { 'city.wavi@alice', AtData()..data = 'dummy-value'); List scanResponseKeys = await scanVerbHandler.getLocalKeys( - inboundConnection.getMetaData() as InboundConnectionMetadata, + inboundConnection.metaData as InboundConnectionMetadata, '.*', false, alice); @@ -240,9 +249,9 @@ void main() { test( 'A test to verify regex applied on pol authenticated connection returns only keys specific to forAtSign that matches the regex', () async { - inboundConnection.getMetaData().isPolAuthenticated = true; - (inboundConnection.getMetaData() as InboundConnectionMetadata) - .fromAtSign = '@bob'; + inboundConnection.metaData.isPolAuthenticated = true; + (inboundConnection.metaData as InboundConnectionMetadata).fromAtSign = + '@bob'; await secondaryKeyStore.put( '@bob:phone.wavi@alice', AtData()..data = 'dummy-value'); @@ -258,7 +267,7 @@ void main() { 'city.wavi@alice', AtData()..data = 'dummy-value'); List scanResponseKeys = await scanVerbHandler.getLocalKeys( - inboundConnection.getMetaData() as InboundConnectionMetadata, + inboundConnection.metaData as InboundConnectionMetadata, 'wavi', false, alice); @@ -319,8 +328,8 @@ void main() { test( 'A test to verify scan does not return the enrollment keys when enrollment namespace has __manage', () async { - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session'; var enrollmentId = Uuid().v4(); final enrollJson = { 'sessionId': '123', @@ -340,8 +349,8 @@ void main() { scanVerbHandler = ScanVerbHandler( secondaryKeyStore, mockOutboundClientManager, cacheManager); // Set enrollmentId to the inboundConnection to mimic the APKAM auth - (inboundConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId = enrollmentId; + (inboundConnection.metaData as InboundConnectionMetadata).enrollmentId = + enrollmentId; await scanVerbHandler.process('scan', inboundConnection); inboundConnection.lastWrittenData = inboundConnection.lastWrittenData! .split('\n')[0] @@ -357,8 +366,8 @@ void main() { test( 'A test to verify scan returns only the keys whose namespaces are authorized in enrollment request', () async { - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session'; var enrollmentId = Uuid().v4(); final enrollJson = { 'sessionId': '123', @@ -381,8 +390,8 @@ void main() { scanVerbHandler = ScanVerbHandler( secondaryKeyStore, mockOutboundClientManager, cacheManager); // Set enrollmentId to the inboundConnection to mimic the APKAM auth - (inboundConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId = enrollmentId; + (inboundConnection.metaData as InboundConnectionMetadata).enrollmentId = + enrollmentId; await scanVerbHandler.process('scan', inboundConnection); inboundConnection.lastWrittenData = inboundConnection.lastWrittenData! .split('\n')[0] @@ -395,9 +404,9 @@ void main() { test( 'A test to verify scan returns enrollment keys on a CRAM authenticated connection', () async { - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session'; - inboundConnection.getMetaData().authType = AuthType.cram; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session'; + inboundConnection.metaData.authType = AuthType.cram; var enrollmentId = Uuid().v4(); final enrollJson = { 'sessionId': '123', @@ -426,10 +435,10 @@ void main() { test('A test to verify enrollment has *:rw access', () async { var enrollmentId = Uuid().v4(); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session'; - (inboundConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId = enrollmentId; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session'; + (inboundConnection.metaData as InboundConnectionMetadata).enrollmentId = + enrollmentId; final enrollJson = { 'sessionId': '123', @@ -458,10 +467,10 @@ void main() { 'A test to verify scan returns all keys when enrollment has *:rw access', () async { var enrollmentId = Uuid().v4(); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session'; - (inboundConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId = enrollmentId; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session'; + (inboundConnection.metaData as InboundConnectionMetadata).enrollmentId = + enrollmentId; final enrollJson = { 'sessionId': '123', @@ -505,10 +514,10 @@ void main() { 'A test to verify multiple app access in enrollment buzz:r, wavi:rw, atmosphere:rw', () async { var enrollmentId = Uuid().v4(); - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session'; - (inboundConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId = enrollmentId; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session'; + (inboundConnection.metaData as InboundConnectionMetadata).enrollmentId = + enrollmentId; final enrollJson = { 'sessionId': '123', @@ -547,8 +556,8 @@ void main() { test( 'A test to verify keys without namespace are not returned when enrollmentId is supplied', () async { - inboundConnection.getMetaData().isAuthenticated = true; - inboundConnection.getMetaData().sessionID = 'dummy_session'; + inboundConnection.metaData.isAuthenticated = true; + inboundConnection.metaData.sessionID = 'dummy_session'; var enrollmentId = Uuid().v4(); final enrollJson = { 'sessionId': '123', @@ -573,8 +582,8 @@ void main() { scanVerbHandler = ScanVerbHandler( secondaryKeyStore, mockOutboundClientManager, cacheManager); // Set enrollmentId to the inboundConnection to mimic the APKAM auth - (inboundConnection.getMetaData() as InboundConnectionMetadata) - .enrollmentId = enrollmentId; + (inboundConnection.metaData as InboundConnectionMetadata).enrollmentId = + enrollmentId; await scanVerbHandler.process('scan', inboundConnection); inboundConnection.lastWrittenData = inboundConnection.lastWrittenData! .split('\n')[0] diff --git a/packages/at_secondary_server/test/stats_verb_test.dart b/packages/at_secondary_server/test/stats_verb_test.dart index 0de11dd26..6af16b132 100644 --- a/packages/at_secondary_server/test/stats_verb_test.dart +++ b/packages/at_secondary_server/test/stats_verb_test.dart @@ -24,16 +24,16 @@ import 'package:mocktail/mocktail.dart'; import 'test_utils.dart'; -class MockSecondaryKeyStore extends Mock implements SecondaryKeyStore {} - -class MockOutboundClientManager extends Mock implements OutboundClientManager {} - -class MockAtCacheManager extends Mock implements AtCacheManager {} - void main() { SecondaryKeyStore mockKeyStore = MockSecondaryKeyStore(); OutboundClientManager mockOutboundClientManager = MockOutboundClientManager(); AtCacheManager mockAtCacheManager = MockAtCacheManager(); + MockSocket mockSocket = MockSocket(); + + setUpAll(() { + when(() => mockSocket.setOption(SocketOption.tcpNoDelay, true)) + .thenReturn(true); + }); group('A group of stats verb tests', () { test('test stats getVerb', () { @@ -106,7 +106,7 @@ void main() { test('test stats verb - invalid syntax', () { var command = 'statsn'; - var inbound = InboundConnectionImpl(null, null); + var inbound = InboundConnectionImpl(mockSocket, null); var defaultVerbExecutor = DefaultVerbExecutor(); var defaultVerbHandlerManager = DefaultVerbHandlerManager( mockKeyStore, @@ -257,7 +257,7 @@ void main() { var verbParams2 = getVerbParam(regex, command2); var verbParams3 = getVerbParam(regex, command3); var verbParams4 = getVerbParam(regex, command4); - var atConnection = InboundConnectionImpl(null, '12345') + var atConnection = InboundConnectionImpl(mockSocket, '12345') ..metaData = metadata; var response = Response(); await notifyListVerbHandler.processVerb( diff --git a/packages/at_secondary_server/test/sync_unit_test.dart b/packages/at_secondary_server/test/sync_unit_test.dart index 13010ae4d..754ff9c99 100644 --- a/packages/at_secondary_server/test/sync_unit_test.dart +++ b/packages/at_secondary_server/test/sync_unit_test.dart @@ -20,6 +20,8 @@ import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import 'package:uuid/uuid.dart'; +import 'test_utils.dart'; + // How the server processes updates from the client (including the responses it generates) and what the expectations // are - i.e. can we reject? what happens when we reject? and more // How items are added to the commit log on the server such that they are available for sync to the clients @@ -45,15 +47,15 @@ Future setUpMethod() async { AtSecondaryServerImpl.getInstance().currentAtSign = atSign; } -class MockSecondaryKeyStore extends Mock implements SecondaryKeyStore {} - -class MockOutboundClientManager extends Mock implements OutboundClientManager {} - -class MockAtCacheManager extends Mock implements AtCacheManager {} - void main() { OutboundClientManager mockOutboundClientManager = MockOutboundClientManager(); AtCacheManager mockAtCacheManager = MockAtCacheManager(); + MockSocket mockSocket = MockSocket(); + + setUpAll(() { + when(() => mockSocket.setOption(SocketOption.tcpNoDelay, true)) + .thenReturn(true); + }); group( 'A group of tests to validate how server process the updates from the client', @@ -300,7 +302,7 @@ void main() { var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; var response = Response(); - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); atConnection.metaData.isAuthenticated = true; var batchVerbParams = HashMap(); batchVerbParams.putIfAbsent('json', () => batchRequestCommand); @@ -366,7 +368,7 @@ void main() { verbHandlerManager); var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; var response = Response(); - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); atConnection.metaData.isAuthenticated = true; var batchVerbParams = HashMap(); batchVerbParams.putIfAbsent('json', () => batchRequestCommand); @@ -436,7 +438,7 @@ void main() { secondaryPersistenceStore!.getSecondaryKeyStore()!); var response = Response(); var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); atConnection.metaData.isAuthenticated = true; var syncVerbParams = HashMap(); syncVerbParams.putIfAbsent(AtConstants.fromCommitSequence, () => '-1'); @@ -476,7 +478,7 @@ void main() { secondaryPersistenceStore!.getSecondaryKeyStore()!); var response = Response(); var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); atConnection.metaData.isAuthenticated = true; var syncVerbParams = HashMap(); syncVerbParams.putIfAbsent(AtConstants.fromCommitSequence, () => '-1'); @@ -518,7 +520,7 @@ void main() { syncProgressiveVerbHandler.capacity = 275; var response = Response(); var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); atConnection.metaData.isAuthenticated = true; var syncVerbParams = HashMap(); syncVerbParams.putIfAbsent(AtConstants.fromCommitSequence, () => '-1'); @@ -557,7 +559,7 @@ void main() { secondaryPersistenceStore!.getSecondaryKeyStore()!); var response = Response(); var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); atConnection.metaData.isAuthenticated = true; var syncVerbParams = HashMap(); syncVerbParams.putIfAbsent(AtConstants.fromCommitSequence, () => '-1'); @@ -631,7 +633,7 @@ void main() { secondaryPersistenceStore!.getSecondaryKeyStore()!); var response = Response(); var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); atConnection.metaData.isAuthenticated = true; var syncVerbParams = HashMap(); syncVerbParams.putIfAbsent(AtConstants.fromCommitSequence, () => '-1'); @@ -694,7 +696,7 @@ void main() { secondaryPersistenceStore!.getSecondaryKeyStore()!); var response = Response(); var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); atConnection.metaData.isAuthenticated = true; var syncVerbParams = HashMap(); syncVerbParams.putIfAbsent(AtConstants.fromCommitSequence, () => '-1'); @@ -734,7 +736,7 @@ void main() { secondaryPersistenceStore!.getSecondaryKeyStore()!); var response = Response(); var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); atConnection.metaData.isAuthenticated = true; var syncVerbParams = HashMap(); syncVerbParams.putIfAbsent(AtConstants.fromCommitSequence, () => '-1'); @@ -773,7 +775,7 @@ void main() { secondaryPersistenceStore!.getSecondaryKeyStore()!); var response = Response(); var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); atConnection.metaData.isAuthenticated = true; var syncVerbParams = HashMap(); syncVerbParams.putIfAbsent(AtConstants.fromCommitSequence, () => '-1'); @@ -820,7 +822,7 @@ void main() { secondaryPersistenceStore!.getSecondaryKeyStore()!); var response = Response(); var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); atConnection.metaData.isAuthenticated = true; var syncVerbParams = HashMap(); syncVerbParams.putIfAbsent(AtConstants.fromCommitSequence, () => '-1'); @@ -865,7 +867,7 @@ void main() { secondaryPersistenceStore!.getSecondaryKeyStore()!); var response = Response(); var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); atConnection.metaData.isAuthenticated = true; (atConnection.metaData as InboundConnectionMetadata).enrollmentId = enrollmentId; @@ -908,7 +910,7 @@ void main() { secondaryPersistenceStore!.getSecondaryKeyStore()!); var response = Response(); var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); atConnection.metaData.isAuthenticated = true; (atConnection.metaData as InboundConnectionMetadata).enrollmentId = enrollmentId; diff --git a/packages/at_secondary_server/test/sync_verb_test.dart b/packages/at_secondary_server/test/sync_verb_test.dart index 3a0e9fc02..bbae7fc34 100644 --- a/packages/at_secondary_server/test/sync_verb_test.dart +++ b/packages/at_secondary_server/test/sync_verb_test.dart @@ -13,11 +13,18 @@ import 'package:at_server_spec/at_verb_spec.dart'; import 'package:test/test.dart'; import 'package:mocktail/mocktail.dart'; -class MockSecondaryKeyStore extends Mock implements SecondaryKeyStore {} +import 'test_utils.dart'; void main() { SecondaryKeyStore mockKeyStore = MockSecondaryKeyStore(); + MockSocket mockSocket = MockSocket(); + + setUpAll(() { + when(() => mockSocket.setOption(SocketOption.tcpNoDelay, true)) + .thenReturn(true); + }); + group('A group of sync verb regex test', () { test('test sync correct syntax', () { var verb = Sync(); @@ -116,7 +123,7 @@ void main() { verbParams.putIfAbsent(AtConstants.fromCommitSequence, () => '0'); verbParams.putIfAbsent('limit', () => '10'); var inBoundSessionId = '123'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); await verbHandler.processVerb(response, verbParams, atConnection); Map syncResponseMap = (jsonDecode(response.data!)).first; diff --git a/packages/at_secondary_server/test/test_utils.dart b/packages/at_secondary_server/test/test_utils.dart index 0e9ae35f4..ff22f1812 100644 --- a/packages/at_secondary_server/test/test_utils.dart +++ b/packages/at_secondary_server/test/test_utils.dart @@ -36,10 +36,12 @@ class MockSecondaryAddressFinder extends Mock class MockOutboundConnectionFactory extends Mock implements OutboundConnectionFactory {} -class MockOutboundConnection extends Mock implements OutboundConnection {} +class MockOutboundConnection extends Mock implements OutboundSocketConnection {} class MockSecureSocket extends Mock implements SecureSocket {} +class MockSocket extends Mock implements Socket {} + class MockStreamSubscription extends Mock implements StreamSubscription {} String alice = '@alice'; @@ -144,13 +146,13 @@ verbTestsSetUp() async { AtConnectionMetaData outboundConnectionMetadata = OutboundConnectionMetadata(); outboundConnectionMetadata.sessionID = 'mock-session-id'; - when(() => mockOutboundConnection.getMetaData()) + when(() => mockOutboundConnection.metaData) .thenReturn(outboundConnectionMetadata); when(() => mockOutboundConnection.metaData) .thenReturn(outboundConnectionMetadata); mockSecureSocket = MockSecureSocket(); - when(() => mockOutboundConnection.getSocket()) + when(() => mockOutboundConnection.underlying) .thenAnswer((_) => mockSecureSocket); when(() => mockOutboundConnection.close()).thenAnswer((_) async => {}); diff --git a/packages/at_secondary_server/test/update_verb_test.dart b/packages/at_secondary_server/test/update_verb_test.dart index b1869847d..ae4910008 100644 --- a/packages/at_secondary_server/test/update_verb_test.dart +++ b/packages/at_secondary_server/test/update_verb_test.dart @@ -1,5 +1,6 @@ import 'dart:collection'; import 'dart:convert'; +import 'dart:io'; import 'package:at_commons/at_builders.dart'; import 'package:at_commons/at_commons.dart'; @@ -24,13 +25,16 @@ import 'package:uuid/uuid.dart'; import 'test_utils.dart'; -class MockSecondaryKeyStore extends Mock implements SecondaryKeyStore {} - void main() { - SecondaryKeyStore mockKeyStore = MockSecondaryKeyStore(); + late SecondaryKeyStore mockKeyStore; + late MockSocket mockSocket; setUpAll(() async { await verbTestsSetUpAll(); + mockKeyStore = MockSecondaryKeyStore(); + mockSocket = MockSocket(); + when(() => mockSocket.setOption(SocketOption.tcpNoDelay, true)) + .thenReturn(true); }); setUp(() async { @@ -523,7 +527,7 @@ void main() { keyStore, statsNotificationService, notificationManager); var response = Response(); var verbParams = handler.parse(command); - var atConnection = InboundConnectionImpl(null, null); + var atConnection = InboundConnectionImpl(mockSocket, null); expect( () => handler.processVerb(response, verbParams, atConnection), throwsA(predicate((dynamic e) => @@ -554,7 +558,7 @@ void main() { var fromVerbHandler = FromVerbHandler(secondaryKeyStore); AtSecondaryServerImpl.getInstance().currentAtSign = '@alice'; var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); var fromVerbParams = HashMap(); fromVerbParams.putIfAbsent('atSign', () => 'alice'); var response = Response(); @@ -570,7 +574,7 @@ void main() { await cramVerbHandler.processVerb( cramResponse, cramVerbParams, atConnection); var connectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; expect(connectionMetadata.isAuthenticated, true); expect(cramResponse.data, 'success'); //Update Verb @@ -601,7 +605,7 @@ void main() { var fromVerbHandler = FromVerbHandler(secondaryKeyStore); AtSecondaryServerImpl.getInstance().currentAtSign = '@alice'; var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); var fromVerbParams = HashMap(); fromVerbParams.putIfAbsent('atSign', () => 'alice'); var response = Response(); @@ -617,7 +621,7 @@ void main() { await cramVerbHandler.processVerb( cramResponse, cramVerbParams, atConnection); var connectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; expect(connectionMetadata.isAuthenticated, true); expect(cramResponse.data, 'success'); //Update Verb @@ -678,7 +682,7 @@ void main() { var fromVerbHandler = FromVerbHandler(secondaryKeyStore); AtSecondaryServerImpl.getInstance().currentAtSign = '@alice'; var inBoundSessionId = '_6665436c-29ff-481b-8dc6-129e89199718'; - var atConnection = InboundConnectionImpl(null, inBoundSessionId); + var atConnection = InboundConnectionImpl(mockSocket, inBoundSessionId); var fromVerbParams = HashMap(); fromVerbParams.putIfAbsent('atSign', () => 'alice'); var response = Response(); @@ -694,7 +698,7 @@ void main() { await cramVerbHandler.processVerb( cramResponse, cramVerbParams, atConnection); var connectionMetadata = - atConnection.getMetaData() as InboundConnectionMetadata; + atConnection.metaData as InboundConnectionMetadata; expect(connectionMetadata.isAuthenticated, true); expect(cramResponse.data, 'success'); //Update Verb @@ -962,7 +966,7 @@ void main() { keyStore, statsNotificationService, notificationManager); var response = Response(); var verbParams = handler.parse(command); - var atConnection = InboundConnectionImpl(null, null); + var atConnection = InboundConnectionImpl(mockSocket, null); await expectLater( () async => await handler.processVerb(response, verbParams, atConnection), @@ -986,7 +990,7 @@ void main() { keyStore, statsNotificationService, notificationManager); var response = Response(); var verbParams = handler.parse(command); - var atConnection = InboundConnectionImpl(null, null); + var atConnection = InboundConnectionImpl(mockSocket, null); await handler.processVerb(response, verbParams, atConnection); expect(response.isError, false); }); diff --git a/packages/at_server_spec/analysis_options.yaml b/packages/at_server_spec/analysis_options.yaml index 1f4622fcf..2d9208886 100644 --- a/packages/at_server_spec/analysis_options.yaml +++ b/packages/at_server_spec/analysis_options.yaml @@ -5,9 +5,12 @@ include: package:lints/recommended.yaml # For lint rules and documentation, see http://dart-lang.github.io/linter/lints. # Uncomment to specify additional rules. -# linter: -# rules: -# - camel_case_types +linter: + rules: + - camel_case_types + - await_only_futures + - unawaited_futures + - unnecessary_brace_in_string_interps analyzer: # exclude: diff --git a/packages/at_server_spec/bin/main.dart b/packages/at_server_spec/bin/main.dart deleted file mode 100644 index d721de6e1..000000000 --- a/packages/at_server_spec/bin/main.dart +++ /dev/null @@ -1,3 +0,0 @@ -void main(List arguments) { - print('Hello world!'); -} diff --git a/packages/at_server_spec/lib/src/connection/at_connection.dart b/packages/at_server_spec/lib/src/connection/at_connection.dart index ea3f9cda7..f1dafabdd 100644 --- a/packages/at_server_spec/lib/src/connection/at_connection.dart +++ b/packages/at_server_spec/lib/src/connection/at_connection.dart @@ -1,16 +1,13 @@ -import 'dart:io'; - -abstract class AtConnection { - /// Write a data to the underlying socket of the connection - /// @param - data - Data to write to the socket - /// @throws [AtIOException] for any exception during the operation - void write(String data); - - /// Retrieves the socket of underlying connection - Socket getSocket(); +abstract class AtConnection { + /// The underlying connection + T get underlying; /// Gets the connection metadata - AtConnectionMetaData getMetaData(); + AtConnectionMetaData get metaData; + + /// Write some [data] to the [underlying] connection. + /// Throws [AtIOException] for any exception during the operation + void write(String data); /// closes the underlying connection Future close(); diff --git a/packages/at_server_spec/lib/src/connection/inbound_connection.dart b/packages/at_server_spec/lib/src/connection/inbound_connection.dart index bab07d14b..76c655fd4 100644 --- a/packages/at_server_spec/lib/src/connection/inbound_connection.dart +++ b/packages/at_server_spec/lib/src/connection/inbound_connection.dart @@ -1,4 +1,3 @@ -import 'dart:io'; import 'package:at_server_spec/src/at_rate_limiter/at_rate_limiter.dart'; import 'package:at_server_spec/src/connection/at_connection.dart'; @@ -13,6 +12,4 @@ abstract class InboundConnection extends AtConnection implements AtRateLimiter { void acceptRequests(Function(String, InboundConnection) callback, Function(List, InboundConnection) streamCallback); - - Socket? receiverSocket; } diff --git a/packages/at_server_spec/pubspec.yaml b/packages/at_server_spec/pubspec.yaml index d03512c73..234e5e72d 100644 --- a/packages/at_server_spec/pubspec.yaml +++ b/packages/at_server_spec/pubspec.yaml @@ -1,6 +1,6 @@ name: at_server_spec description: A Dart library containing abstract classes that defines what implementations of the root and secondary servers are responsible for. -version: 3.0.16 +version: 4.0.0 repository: https://github.com/atsign-foundation/at_server homepage: https://docs.atsign.com documentation: https://docs.atsign.com/atplatform/secondaryserver @@ -9,8 +9,8 @@ environment: sdk: '>=2.15.0 <4.0.0' dependencies: - meta: ^1.8.0 - at_commons: ^4.0.0 + meta: ^1.11.0 + at_commons: ^4.0.1 dev_dependencies: - lints: ^1.0.1 + lints: ^3.0.0