55from typing import Optional
66import signal
77import os
8+ import re
9+ import uuid
810
911from netsecgame .game_components import Action , Observation , ActionType , GameStatus , GameState , AgentStatus , AgentRole
1012from netsecgame .game .global_defender import GlobalDefender
@@ -25,6 +27,16 @@ def convert_msg_dict_to_json(msg_dict: dict) -> str:
2527 raise TypeError (f"Error when converting msg to JSON:{ e } " ) from e
2628 return output_message
2729
30+ def sanitize_agent_name (name :str )-> str :
31+ """
32+ Sanitizes the agent name to be used as a filename.
33+ """
34+ safe_name = re .sub (r'[^a-zA-Z0-9_\-]' , '_' , name )
35+ safe_name = re .sub (r'_+' , '_' , safe_name )
36+ safe_name = safe_name .strip ('_' )[:200 ]
37+ if not safe_name :
38+ return f"agent_{ uuid .uuid4 ().hex [:8 ]} "
39+ return safe_name
2840
2941class GameCoordinator :
3042 """
@@ -312,10 +324,26 @@ async def run_game(self):
312324 self .logger .info (f"Coordinator received from agent { agent_addr } : { message } ." )
313325
314326 action = self ._parse_action_message (agent_addr , message )
315- if action :
327+ if action is not None :
316328 self ._dispatch_action (agent_addr , action )
329+ else :
330+ self ._spawn_task (self ._respond_on_bad_request , agent_addr , "Malformed Action" )
317331 self .logger .info ("\t Action processing task stopped." )
318-
332+
333+ async def _respond_on_bad_request (self , agent_addr : tuple , message : str )-> None :
334+ """
335+ Sends a response to the agent indicating that the request was bad.
336+ """
337+ output_message_dict = {
338+ "to_agent" : agent_addr ,
339+ "status" : str (GameStatus .BAD_REQUEST ),
340+ "observation" : None ,
341+ "message" : {
342+ "message" : f"Bad request received: { message } " ,
343+ }
344+ }
345+ await self ._agent_response_queues [agent_addr ].put (convert_msg_dict_to_json (output_message_dict ))
346+
319347 async def _process_join_game_action (self , agent_addr : tuple , action : Action )-> None :
320348 """
321349 Method for processing Action of type ActionType.JoinGame
@@ -327,7 +355,7 @@ async def _process_join_game_action(self, agent_addr: tuple, action: Action)->No
327355 try :
328356 self .logger .info (f"New Join request by { agent_addr } ." )
329357 if agent_addr not in self .agents :
330- agent_name = action .parameters ["agent_info" ].name
358+ agent_name = sanitize_agent_name ( str ( action .parameters ["agent_info" ].name ))
331359 agent_role = action .parameters ["agent_info" ].role
332360 if agent_role in AgentRole :
333361 # add agent to the world
0 commit comments