async def test_simple_messaging(backchannel): """Show simple messages being passed to and from the test subject.""" expected_schema = MessageSchema({ '@type': 'test/protocol/1.0/test', '@id': str, 'msg': 'pong' }) ping = Message({ '@type': 'test/protocol/1.0/test', 'msg': 'ping' }) print('Sending message:', ping.pretty_print()) pong = await backchannel.send_and_await_reply_async( ping, timeout=1 ) print('Received message:', pong.pretty_print()) assert pong.mtc[ CONFIDENTIALITY | INTEGRITY | AUTHENTICATED_ORIGIN | DESERIALIZE_OK ] assert not pong.mtc[NONREPUDIATION] assert pong.mtc.ad['sender_vk'] == crypto.bytes_to_b58(backchannel.their_vk) assert pong.mtc.ad['recip_vk'] == crypto.bytes_to_b58(backchannel.my_vk) assert expected_schema.validate(pong)
def _send(self, message_body): message = Message(message_body) print('Sending message:', message.pretty_print()) reply = self.connection.send_and_await_reply(message, return_route='all', timeout=5) print('Response:', reply.pretty_print()) return reply
async def test_routing_many(event, dispatcher, conn): """ Test that routing to a module works. """ dispatcher.called_module = None class TestModule1(Module): """ Simple module for testing """ DOC_URI = '' PROTOCOL = 'test_protocol' VERSION = '1.0' @route async def testing_type(self, _msg, **kwargs): """ Test that this method is called """ kwargs['dispatcher'].called_module = 1 kwargs['event'].set() class TestModule2(Module): """ Simple module for testing """ DOC_URI = '' PROTOCOL = 'test_protocol' VERSION = '2.0' @route async def testing_type(self, _msg, **kwargs): """ Test that this methodis called """ kwargs['dispatcher'].called_module = 2 kwargs['event'].set() conn.route_module(TestModule1()) conn.route_module(TestModule2()) test_msg = Message({ '@type': 'test_protocol/1.0/testing_type', 'test': 'test' }) await dispatcher.dispatch(test_msg, event=event, dispatcher=dispatcher) await event.wait() assert event.is_set() assert dispatcher.called_module == 1 event.clear() test_msg = Message({ '@type': 'test_protocol/2.0/testing_type', 'test': 'test' }) await dispatcher.dispatch(test_msg, event=event, dispatcher=dispatcher) await event.wait() assert event.is_set() assert dispatcher.called_module == 2 assert dispatcher.handlers conn.clear_routes() assert not dispatcher.handlers
async def test_routing_many(event, dispatcher, conn): """Test that routing to a module works.""" dispatcher.called_module = None class TestModule1(Module): """Simple module for testing""" protocol = "test_protocol/1.0" route = ModuleRouter(protocol) @route async def testing_type(self, _msg, **kwargs): """Test that this method is called""" kwargs["dispatcher"].called_module = 1 kwargs["event"].set() class TestModule2(Module): """Simple module for testing""" protocol = "test_protocol/2.0" route = ModuleRouter(protocol) @route async def testing_type(self, _msg, **kwargs): """Test that this methodis called""" kwargs["dispatcher"].called_module = 2 kwargs["event"].set() conn.route_module(TestModule1()) conn.route_module(TestModule2()) test_msg = Message.parse_obj({ "@type": "test_protocol/1.0/testing_type", "test": "test" }) await dispatcher.dispatch(test_msg, event=event, dispatcher=dispatcher) await event.wait() assert event.is_set() assert dispatcher.called_module == 1 event.clear() test_msg = Message.parse_obj({ "@type": "test_protocol/2.0/testing_type", "test": "test" }) await dispatcher.dispatch(test_msg, event=event, dispatcher=dispatcher) await event.wait() assert event.is_set() assert dispatcher.called_module == 2 assert dispatcher.handlers conn.clear_routes() assert not dispatcher.handlers
def build_invite(label: str, connection_key: str, endpoint: str) -> str: msg = Message({ '@type': INVITE, 'label': label, 'recipientKeys': [connection_key], 'serviceEndpoint': endpoint, 'routingKeys': [] }) b64_invite = base64.urlsafe_b64encode(bytes(msg.serialize(), 'utf-8')).decode('ascii') return '{}?c_i={}'.format(endpoint, b64_invite)
async def test_trust_ping_with_response_requested_true(connection): """Test that subject responds to trust pings.""" expected_trust_pong_schema = MessageSchema({ "@type": Any(TYPE, ALT_TYPE), "@id": str, "~thread": { "thid": str }, Optional("~timing"): { Optional("in_time"): str, Optional("out_time"): str }, Optional("comment"): str }) trust_ping = Message({ "@type": TYPE, # "@id" is added by the staticagent lib "response_requested": True }) #print('Sending message:', trust_ping.pretty_print()) trust_pong = await connection.send_and_await_reply_async(trust_ping, timeout=1) #print('Received message:', trust_pong.pretty_print()) assert trust_pong.mtc.is_authcrypted() # are you, you and am I, me? assert trust_pong.mtc.sender == crypto.bytes_to_b58( connection.recipients[0]) assert trust_pong.mtc.recipient == connection.verkey_b58 assert expected_trust_pong_schema(trust_pong) assert trust_pong['~thread']['thid'] == trust_ping.id
def build_response(req_id: str, my_did: str, my_vk: str, endpoint: str) -> Message: return Message({ '@type': RESPONSE, '@id': str(uuid.uuid4()), '~thread': { 'thid': req_id, 'sender_order': 0 }, 'connection': { 'DID': my_did, 'DIDDoc': { "@context": "https://w3id.org/did/v1", "id": my_did, "publicKey": [{ "id": my_did + "#keys-1", "type": "Ed25519VerificationKey2018", "controller": my_did, "publicKeyBase58": my_vk }], "service": [{ "id": my_did + ";indy", "type": "IndyAgent", "recipientKeys": [my_vk], "routingKeys": [], "serviceEndpoint": endpoint, }], } } })
def build_request(label: str, my_did: str, my_vk: str, endpoint: str) -> Message: """ Construct a connection request. """ return Message({ '@type': REQUEST, '@id': str(uuid.uuid4()), 'label': label, 'connection': { 'DID': my_did, 'DIDDoc': { "@context": "https://w3id.org/did/v1", "id": my_did, "publicKey": [{ "id": my_did + "#keys-1", "type": "Ed25519VerificationKey2018", "controller": my_did, "publicKeyBase58": my_vk }], "service": [{ "id": my_did + ";indy", "type": "IndyAgent", "recipientKeys": [my_vk], "routingKeys": [], "serviceEndpoint": endpoint, }], } } })
async def send_offer_credential(self, conn, cred_def_id: str, attrs: dict) -> str: """Send a credential offer to the agent under test.""" print('>>>>>xxx>>>>offer-credential[init_2.py]') (attach, self.offer) = await self.provider.issue_credential_v1_0_issuer_create_credential_offer(cred_def_id) self.attrs = attrs preview_attrs = self.attrs_to_preview_attrs(attrs) id = self.make_uuid() msg = Message({ "@type": "{}/offer-credential".format(Handler.PID), 'comment': "Credential offer from aries-protocol-test-suite", 'credential_preview': { '@type': '{}/credential-preview'.format(Handler.PID), 'attributes': preview_attrs, }, 'offers~attach': [ { '@id': id, 'mime-type': "application/json", 'data': { 'base64': attach } } ] }) return await self.send_async(msg, conn)
async def responder(connection, query, comment): """Send a query request and return the response.""" # Send the request req = Message({ '@type': Suite.TYPE_PREFIX + 'discover-features/1.0/query', 'query': query, 'comment': comment, }) resp = await connection.send_and_await_reply_async(req, timeout=1) # Validate the response assert resp.mtc.is_authcrypted() assert resp.mtc.sender == crypto.bytes_to_b58(connection.recipients[0]) assert resp.mtc.recipient == connection.verkey_b58 msg_type = Suite.TYPE_PREFIX + 'discover-features/1.0/disclose' alt_msg_type = Suite.ALT_TYPE_PREFIX + 'discover-features/1.0/disclose' resp_schema = MessageSchema({ '@type': Any(msg_type, alt_msg_type), '@id': str, 'protocols': [{ 'pid': str, 'roles': [str] }] }) resp_schema(resp) # Return the response return resp
async def responder(connection, query, comment): """Send a query request and return the response.""" # Send the request req = Message({ '@type': 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/discover-features/1.0/query', 'query': query, 'comment': comment, }) resp = await connection.send_and_await_reply_async(req, timeout=1) # Validate the response assert resp.mtc.is_authcrypted() assert resp.mtc.sender == crypto.bytes_to_b58(connection.recipients[0]) assert resp.mtc.recipient == connection.verkey_b58 resp_schema = MessageSchema({ '@type': 'did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/discover-features/1.0/disclose', '@id': str, 'protocols': [{ 'pid': str, 'roles': [str] }] }) resp_schema(resp) # Return the response return resp
def main(): """Main.""" args = config() _did, my_vk, my_sk, their_vk, endpoint = create_or_recall_keys(args.replace) conn = StaticConnection(my_vk, my_sk, their_vk, endpoint) ping = Message({ "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/trust_ping/1.0/ping", "response_requested": True }) print('Pinging connection:', ping.pretty_print()) reply = conn.send_and_await_reply( ping, return_route='all', timeout=5 ) print('Response:', reply.pretty_print())
def main(): """Main.""" args = config() _did, my_vk, my_sk, their_vk, endpoint = create_or_recall_keys( args.replace) conn = StaticConnection(my_vk, my_sk, their_vk, endpoint) ping = Message({ "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/trust_ping/1.0/ping", "response_requested": True }) print('Pinging connection:', ping.pretty_print()) reply = conn.send_and_await_reply(ping, return_route='all', timeout=5) print('Response:', reply.pretty_print()) @conn.route('did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/basicmessage/1.0/message') async def basic_message_auto_responder(msg, conn): """Automatically respond to basicmessages.""" await conn.send_async({ "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/" "basicmessage/1.0/message", "~l10n": { "locale": "en" }, "sent_time": utils.timestamp(), "content": "You said: {}".format(msg['content']) }) async def handle(request): """aiohttp handle POST.""" response = [] with conn.reply_handler(response.append): await conn.handle(await request.read()) if response: return web.Response(body=response.pop()) raise web.HTTPAccepted() app = web.Application() app.add_routes([web.post('/', handle)]) web.run_app(app, port=args.port)
def parse_invite(invite_url: str) -> Message: """ Parse an invite url """ matches = re.match('(.+)?c_i=(.+)', invite_url) assert matches, 'Improperly formatted invite url!' invite_msg = Message.deserialize( base64.urlsafe_b64decode(matches.group(2)).decode('ascii')) INVITE_SCHEMA(invite_msg) return invite_msg
async def test_simple_messaging(connection): """Show simple messages being passed to and from the test subject.""" expected_schema = MessageSchema({ '@type': 'test/protocol/1.0/test', '@id': str, 'msg': 'pong' }) ping = Message({'@type': 'test/protocol/1.0/test', 'msg': 'ping'}) print('Sending message:', ping.pretty_print()) pong = await connection.send_and_await_reply_async(ping, timeout=1) print('Received message:', pong.pretty_print()) assert pong.mtc.is_authcrypted() assert pong.mtc.sender == crypto.bytes_to_b58(connection.recipients[0]) assert pong.mtc.recipient == connection.verkey_b58 assert expected_schema(pong)
def test_pack_unpack_auth(alice, bob): """Test the pack-unpack loop with authcrypt.""" msg = Message.parse_obj({"@type": "doc;protocol/1.0/name"}) packed_msg = alice.pack(msg) assert isinstance(packed_msg, bytes) unpacked_msg = bob.unpack(packed_msg) assert isinstance(unpacked_msg, Message) assert hasattr(unpacked_msg, "mtc") assert unpacked_msg.mtc.is_authcrypted() assert unpacked_msg.mtc.sender == alice.verkey_b58 assert unpacked_msg.mtc.recipient == bob.verkey_b58
async def test_simple_route(event, dispatcher, conn): """ Test using route decorator on a method. """ @conn.route('test_protocol/1.0/testing_type') async def test(msg, **kwargs): # pylint: disable=unused-variable assert msg['test'] == 'test' kwargs['event'].set() await dispatcher.dispatch(Message({ '@type': 'test_protocol/1.0/testing_type', 'test': 'test' }), event=event) assert event.is_set()
async def test_receiver(backchannel, connection): """Agent under test can receive and handle basic messages.""" content = random_string() msg = Message({ '@type': HTTP_MSG_TYPE, '~l10n': {'locale': 'en'}, 'sent_time': timestamp(), 'content': content }) assert MSG_VALID(msg) await connection.send_async(msg) reported = await backchannel.basic_message_v1_0_get_message( connection, msg.id ) assert content == reported
def create_invitation(self): """ Create and return an invite. """ conn_vk, conn_sk = crypto.create_keypair() connection = StaticConnection(conn_vk, conn_sk, b'', '', dispatcher=self.dispatcher) conn_vk_b58 = crypto.bytes_to_b58(conn_vk) self.connections[conn_vk_b58] = connection connection.state = ConnectionState() connection.state.role = Roles.INVITER connection.state.transition(Events.SEND_INVITE) invitation = Message({ '@type': self.type('invitation'), 'label': 'static-iiw', 'recipientKeys': [conn_vk_b58], 'serviceEndpoint': self.endpoint, 'routingKeys': [] }) invitation_url = '{}?c_i={}'.format( self.endpoint, crypto.bytes_to_b64(invitation.serialize().encode())) return connection, invitation_url
async def test_simple_route(event, dispatcher, conn): """Test using route decorator on a method.""" @conn.route("test_protocol/1.0/testing_type") async def test(msg, **kwargs): # pylint: disable=unused-variable assert msg["test"] == "test" kwargs["event"].set() await dispatcher.dispatch( Message.parse_obj({ "@type": "test_protocol/1.0/testing_type", "test": "test" }), event=event, ) assert event.is_set()
def test_pack_unpack_auth(keys, alice, bob): """ Test the pack-unpack loop with authcrypt. """ alice_vk, _alice_sk, bob_vk, _bob_sk = keys msg = Message({'@type': 'doc;protocol/1.0/name'}) packed_msg = alice.pack(msg) assert isinstance(packed_msg, bytes) unpacked_msg = bob.unpack(packed_msg) assert isinstance(unpacked_msg, Message) assert hasattr(unpacked_msg, 'mtc') assert unpacked_msg.mtc[ CONFIDENTIALITY | INTEGRITY | DESERIALIZE_OK | AUTHENTICATED_ORIGIN ] assert unpacked_msg.mtc[NONREPUDIATION] is False assert unpacked_msg.mtc.ad['sender_vk'] == crypto.bytes_to_b58(alice_vk) assert unpacked_msg.mtc.ad['recip_vk'] == crypto.bytes_to_b58(bob_vk)
async def test_routing_module_explicit_def(event, dispatcher, conn, route_args, route_kwargs, send_type): """Test that routing to a module works.""" class TestModule(Module): """Simple module for testing""" protocol = "test_protocol/1.0" route = ModuleRouter(protocol) @route(*route_args, **route_kwargs) async def route_gets_called(self, _msg, **kwargs): """Test that this method is called""" kwargs["event"].set() mod = TestModule() conn.route_module(mod) test_msg = Message.parse_obj({"@type": send_type, "test": "test"}) await dispatcher.dispatch(test_msg, event=event) assert event.is_set()
async def test_routing_module_explicit_def(event, dispatcher, conn, route_args, route_kwargs, send_type): """ Test that routing to a module works. """ class TestModule(Module): """ Simple module for testing """ DOC_URI = '' PROTOCOL = 'test_protocol' VERSION = '1.0' @route(*route_args, **route_kwargs) async def route_gets_called(self, _msg, **kwargs): """ Test that this method is called """ kwargs['event'].set() mod = TestModule() conn.route_module(mod) test_msg = Message({'@type': send_type, 'test': 'test'}) await dispatcher.dispatch(test_msg, event=event) assert event.is_set()
async def test_routing_no_matching_version(event, dispatcher, conn): """Test error raised on no matching handlers.""" class TestModule(Module): """Simple module for testing""" protocol = "test_protocol/1.0" route = ModuleRouter(protocol) @route async def testing_type(self, _msg, **kwargs): """Test that this method is called""" kwargs["event"].set() mod = TestModule() conn.route_module(mod) test_msg = Message.parse_obj({ "@type": "test_protocol/3.0/testing_type", "test": "test" }) with pytest.raises(NoRegisteredHandlerException): await dispatcher.dispatch(test_msg, event=event)
async def send_request_presentation(self, conn, proof_request: dict) -> str: """Send a request-presentation message to the agent under test.""" ( attach, self.proof_request ) = await self.provider.present_proof_v1_0_verifier_request_presentation( proof_request) msg = Message({ "@type": "{}/request-presentation".format(Handler.PP_PID), 'comment': "Request presentation from aries-protocol-test-suite", 'request_presentations~attach': [{ '@id': self.make_uuid(), 'mime-type': "application/json", 'data': { 'base64': attach } }] }) id = await self.send_async(msg, conn) return id
async def test_routing_module_simple(event, dispatcher, conn): """ Test that routing to a module works. """ class TestModule(Module): """ Simple module for testing """ DOC_URI = '' PROTOCOL = 'test_protocol' VERSION = '1.0' @route async def testing_type(self, _msg, **kwargs): """ Test that this method is called """ kwargs['event'].set() mod = TestModule() conn.route_module(mod) test_msg = Message({ '@type': 'test_protocol/1.0/testing_type', 'test': 'test' }) await dispatcher.dispatch(test_msg, event=event) assert event.is_set()
async def test_routing_no_matching_version(event, dispatcher, conn): """ Test error raised on no matching handlers. """ class TestModule(Module): """ Simple module for testing """ DOC_URI = '' PROTOCOL = 'test_protocol' VERSION = '1.0' @route async def testing_type(self, _msg, **kwargs): """ Test that this method is called """ kwargs['event'].set() mod = TestModule() conn.route_module(mod) test_msg = Message({ '@type': 'test_protocol/3.0/testing_type', 'test': 'test' }) with pytest.raises(NoRegisteredHandlerException): await dispatcher.dispatch(test_msg, event=event)
async def test_routing_minor_version_different(event, dispatcher, conn): """Test routing when minor version is different.""" class TestModule(Module): """Simple module for testing""" protocol = "test_protocol/1.0" route = ModuleRouter(protocol) @route async def testing_type(self, _msg, **kwargs): """Test that this method is called""" kwargs["event"].set() mod = TestModule() conn.route_module(mod) test_msg = Message.parse_obj({ "@type": "test_protocol/1.0/testing_type", "test": "test" }) await dispatcher.dispatch(test_msg, event=event) assert event.is_set()
def response(): yield Message.parse_obj({"@type": "doc;protocol/1.0/response"})
def message(): yield Message.parse_obj({"@type": "doc;protocol/1.0/name"})