Skip to content

Commit

Permalink
Solve Websocket error handling (#657)
Browse files Browse the repository at this point in the history
* Problem: If the frontend or a user send and incorrect auth payload, the endpoint just stop sharing data without return anything or close the connection.

Solution: Handle error issues on the endpoint to always return status field and the reason why it's failing, and closing the connection.

* Fix: Solve test issue after the failed response.
  • Loading branch information
nesitor authored Jul 17, 2024
1 parent 35dd30a commit a27a488
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
22 changes: 14 additions & 8 deletions src/aleph/vm/orchestrator/views/operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,17 +125,23 @@ async def authenticate_websocket_for_vm_or_403(execution: VmExecution, vm_hash:
first_message = await ws.receive_json()
except TypeError as error:
logging.exception(error)
await ws.send_json({"status": "failed", "reason": str(error)})
raise web.HTTPForbidden(body="Invalid auth package")
credentials = first_message["auth"]
authenticated_sender = await authenticate_websocket_message(credentials)

if is_sender_authorized(authenticated_sender, execution.message):
logger.debug(f"Accepted request to access logs by {authenticated_sender} on {vm_hash}")
return True

logger.debug(f"Denied request to access logs by {authenticated_sender} on {vm_hash}")
await ws.send_json({"status": "failed", "reason": "unauthorized sender"})
raise web.HTTPForbidden(body="Unauthorized sender")
try:
authenticated_sender = await authenticate_websocket_message(credentials)

if is_sender_authorized(authenticated_sender, execution.message):
logger.debug(f"Accepted request to access logs by {authenticated_sender} on {vm_hash}")
return True

logger.debug(f"Denied request to access logs by {authenticated_sender} on {vm_hash}")
await ws.send_json({"status": "failed", "reason": "unauthorized sender"})
raise web.HTTPForbidden(body="Unauthorized sender")
except Exception as error:
await ws.send_json({"status": "failed", "reason": str(error)})
raise web.HTTPForbidden(body="Unauthorized sender")


@cors_allow_all
Expand Down
3 changes: 3 additions & 0 deletions tests/supervisor/views/test_operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,9 @@ async def test_websocket_logs_invalid_auth(aiohttp_client, mocker):
await websocket.send_json({"auth": "invalid auth package"})
response = await websocket.receive()
# Subject to change in the future, for now the connexion si broken and closed
assert response.type == aiohttp.WSMsgType.TEXT
assert response.data == '{"status": "failed", "reason": "string indices must be integers"}'
response = await websocket.receive()
assert response.type == aiohttp.WSMsgType.CLOSE
assert websocket.closed

Expand Down

0 comments on commit a27a488

Please sign in to comment.