Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_router(zmq_context, master_config):
seraph = Seraph(master_config)
seraph.start()
try:
client = zmq_context.socket(transport.REQ)
client.connect(master_config.db_queue)
worker = zmq_context.socket(transport.REQ)
worker.connect(const.ORACLE_QUEUE)
worker.send(b'READY')
client.send(cbor2.dumps(['FOO']))
client_addr, empty, msg = worker.recv_multipart()
assert cbor2.loads(msg) == ['FOO']
worker.send_multipart([client_addr, empty, cbor2.dumps(['BAR'])])
assert cbor2.loads(client.recv()) == ['BAR']
finally:
seraph.quit()
seraph.join()
def _deserialize_value(self, data):
return cbor2.loads(data)
def test_oracle_badly_formed_request(mock_seraph, task):
assert mock_seraph.recv() == b'READY'
mock_seraph.send_multipart([b'foo', b'', b'', b'', b''])
address, empty, resp = mock_seraph.recv_multipart()
assert cbor2.loads(resp) == ['ERROR', repr('')]
# Therefore, Exception is caught instead of specific exceptions.
# TODO: The payload is documented at
# https://docs.google.com/document/d/1rJXlOqCGomPKEKx2ReoofZTXQt9dtDiW_BHU7FYsj-k/edit#
# and will be moved to a .rst file
code = aiocoap.numbers.codes.Code.VALID
# TODO: Decide upon the correct format of message
message = ''
try:
if not Ingest.is_available():
message = '{"busy": true}'
raise aiocoap.error.CommunicationKilled(message)
try:
payload = cbor2.loads(request.payload)
except Exception:
raise ValueError('Payload must be a dictionary')
asset = payload['asset']
timestamp = payload['timestamp']
key = payload['key']
# readings or sensor_values are optional
try:
readings = payload['readings']
except KeyError:
readings = payload['sensor_values'] # sensor_values is deprecated
# if optional then
# TODO: confirm, do we want to check this?
if not isinstance(readings, dict):
# is raised out of a handler, it is permanently disabled by aiocoap.
# Therefore, Exception is caught instead of specific exceptions.
# TODO: The payload is documented at
# https://docs.google.com/document/d/1rJXlOqCGomPKEKx2ReoofZTXQt9dtDiW_BHU7FYsj-k/edit#
# and will be moved to a .rst file
code = aiocoap.numbers.codes.Code.INTERNAL_SERVER_ERROR
increment_discarded_counter = True
message = ''
try:
if not Ingest.is_available():
message = '{"busy": true}'
else:
payload = cbor2.loads(request.payload)
if not isinstance(payload, dict):
raise ValueError('Payload must be a dictionary')
asset = payload.get('asset')
timestamp = payload.get('timestamp')
key = payload.get('key')
# readings and sensor_readings are optional
try:
readings = payload['readings']
except KeyError:
readings = payload.get('sensor_values') # sensor_values is deprecated
increment_discarded_counter = False
async def _native_recv(self):
while True:
try:
msg = await self._socket.receive()
except TypeError:
return None
except TimeoutError:
return None
if msg.type == aiohttp.WSMsgType.TEXT:
msg = json.loads(msg.data)
elif msg.type == aiohttp.WSMsgType.BINARY:
msg = cbor2.loads(msg.data, tag_hook=encoder.cbor2_decoder)
elif msg.type == aiohttp.WSMsgType.CLOSING:
pass
elif msg.type == aiohttp.WSMsgType.CLOSED or msg.type == aiohttp.WSMsgType.CLOSE:
raise EOFError()
elif msg.type == aiohttp.WSMsgType.ERROR:
raise ConnectionError() from self._socket.exception()
else:
raise ValueError('Unhandled result type')
logging.debug('>> ' + str(msg))
# Greenlet is spawned here in order to not block main loop. Message handler may send messages and
# wait for response. In order to get a response this loop must be spinning.
fut = asyncio.get_event_loop().create_task(self.on_recv(msg))
fut.add_done_callback(lambda f: f.exception()) # make sure exception is retrieved
# XXX: Chrome does not currently supply token binding in the clientDataJSON
# if not _verify_token_binding_id(c):
# raise RegistrationRejectedException('Unable to verify token binding ID.')
# Step 7.
#
# Compute the hash of response.clientDataJSON using SHA-256.
client_data_hash = _get_client_data_hash(decoded_cd)
# Step 8.
#
# Perform CBOR decoding on the attestationObject field of
# the AuthenticatorAttestationResponse structure to obtain
# the attestation statement format fmt, the authenticator
# data authData, and the attestation statement attStmt.
att_obj = cbor2.loads(_webauthn_b64_decode(attestation_object))
att_stmt = att_obj.get('attStmt')
auth_data = att_obj.get('authData')
fmt = att_obj.get('fmt')
if not auth_data or len(auth_data) < 37:
raise RegistrationRejectedException(
'Auth data must be at least 37 bytes.')
# Step 9.
#
# Verify that the RP ID hash in authData is indeed the
# SHA-256 hash of the RP ID expected by the RP.
auth_data_rp_id_hash = _get_auth_data_rp_id_hash(auth_data)
# NOTE: In Python 3, `auth_data_rp_id_hash` will be bytes,
# which is expected in `_verify_rp_id_hash()`.
if not _verify_rp_id_hash(auth_data_rp_id_hash, self.rp_id):
raise RegistrationRejectedException(
Returns None if the file does not exist or is empty.
"""
try:
raw_data = self.vfs.read(b'replicated-data')
except IOError as e:
if e.errno != errno.ENOENT:
raise
return None
# If empty, treat as missing.
if not raw_data:
return None
try:
data = cbor2.loads(raw_data)
except cbor2.CBORDecodeError as e:
raise error.Abort(b'malformed CBOR data: %s' % e)
return data
def on_incoming_binary_frame(self, incoming_binary):
try:
self.logger.debug(incoming_binary)
incoming_json = cbor2.loads(incoming_binary)
except ValueError as e:
self.logger.exception(e)
message = '"{0}" is not valid CBOR'.format(incoming_binary)
return self.on_internal_error(message)
self.on_incoming_json(incoming_json)
def data_received(self, data):
peername = self.transport_.get_extra_info('peername')
if data is not None:
self.message_ += data
full_message_length = 0
if len(self.message_) >= LENGTH_BYTES:
full_message_length = int.from_bytes(self.message_[:LENGTH_BYTES], "big")
if len(self.message_) - LENGTH_BYTES < full_message_length:
return
else:
return
decoded = loads(data[LENGTH_BYTES:])
function = decoded["function"]
function_data = decoded["data"]
f = getattr(self.api_, function)
if f is not None:
print(f'Message of size {full_message_length}: {function}({function_data[:100]}) from {peername}')
f(function_data)
else:
print(f'Invalid message: {function} from {peername}')