66import subprocess
77import logging
88import os
9+ import re
910from scripts .scheduler import get_scheduler
1011
1112app = FastAPI (
@@ -242,10 +243,28 @@ def list_containers():
242243 except Exception :
243244 return []
244245
246+ def validate_container_name (name : str ) -> str :
247+ """
248+ Validate a Docker container name to avoid passing arbitrary user input
249+ directly to subprocess calls.
250+ """
251+ # Allow common Docker name characters only and enforce a reasonable length
252+ if not name or len (name ) > 128 :
253+ raise HTTPException (status_code = 400 , detail = "Invalid container name length" )
254+ if not re .fullmatch (r"[a-zA-Z0-9._-]+" , name ):
255+ raise HTTPException (status_code = 400 , detail = "Invalid container name format" )
256+ return name
257+
245258@app .get ("/logs/container/{container_name}" , tags = ["Docker" ])
246259def get_container_logs (container_name : str ):
247260 try :
248- result = subprocess .run (["docker" , "logs" , "--tail" , "1000" , container_name ], capture_output = True , text = True , check = True )
261+ safe_name = validate_container_name (container_name )
262+ result = subprocess .run (
263+ ["docker" , "logs" , "--tail" , "1000" , safe_name ],
264+ capture_output = True ,
265+ text = True ,
266+ check = True ,
267+ )
249268 return {"logs" : result .stdout }
250269 except subprocess .CalledProcessError as e :
251270 return {"logs" : f"[ERROR] Failed to get logs: { e .stderr } " }
@@ -255,7 +274,8 @@ def stream_log(filename: str):
255274 def event_generator ():
256275 if filename .startswith ("container:" ):
257276 container = filename .split ("container:" )[1 ]
258- cmd = ["docker" , "logs" , "-f" , "--tail" , "10" , container ]
277+ safe_container = validate_container_name (container )
278+ cmd = ["docker" , "logs" , "-f" , "--tail" , "10" , safe_container ]
259279 else :
260280 filepath = f"{ LOGS_DIR } /{ filename } "
261281 if not os .path .exists (filepath ):
0 commit comments