Skip to content

Commit

Permalink
protocol: use JSON helpers for control messages
Browse files Browse the repository at this point in the history
Drop the manual error checking on 'init' messages and avoid the total
lack of error checking for 'kill' and 'authorize' messages.
  • Loading branch information
allisonkarlitskaya committed Jan 31, 2024
1 parent c820261 commit cbcc596
Showing 1 changed file with 8 additions and 20 deletions.
28 changes: 8 additions & 20 deletions src/cockpit/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import logging
import uuid

from .jsonutil import JsonError, JsonObject, JsonValue, create_object, get_str, typechecked
from .jsonutil import JsonError, JsonObject, JsonValue, create_object, get_int, get_str, typechecked

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -206,23 +206,14 @@ def do_init(self, message: JsonObject) -> None:
def do_kill(self, host: 'str | None', group: 'str | None', message: JsonObject) -> None:
raise NotImplementedError

def transport_control_received(self, command, message):
def transport_control_received(self, command: str, message: JsonObject) -> None:
if command == 'init':
try:
if int(message['version']) != 1:
raise CockpitProtocolError('incorrect version number', 'protocol-error')
except KeyError as exc:
raise CockpitProtocolError('version field is missing', 'protocol-error') from exc
except ValueError as exc:
raise CockpitProtocolError('version field is not an int', 'protocol-error') from exc

try:
self.init_host = message['host']
except KeyError as exc:
raise CockpitProtocolError('missing host field', 'protocol-error') from exc
if get_int(message, 'version') != 1:
raise CockpitProtocolError('incorrect version number')
self.init_host = get_str(message, 'host')
self.do_init(message)
elif command == 'kill':
self.do_kill(message.get('host'), message.get('group'), message)
self.do_kill(get_str(message, 'host', None), get_str(message, 'group', None), message)
elif command == 'authorize':
self.do_authorize(message)
else:
Expand All @@ -247,11 +238,8 @@ async def request_authorization(
self.authorizations.pop(cookie)

def do_authorize(self, message: JsonObject) -> None:
cookie = message.get('cookie')
response = message.get('response')

if not isinstance(cookie, str) or not isinstance(response, str):
raise CockpitProtocolError('invalid authorize response')
cookie = get_str(message, 'cookie')
response = get_str(message, 'response')

if self.authorizations is None or cookie not in self.authorizations:
logger.warning('no matching authorize request')
Expand Down

0 comments on commit cbcc596

Please sign in to comment.