forked from kenzuya/unshackle
fix(remote): answer malformed input with one line and keep secrets out of logs
This commit is contained in:
@@ -49,11 +49,18 @@ def redact_parameters(parameters: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return redacted
|
||||
|
||||
|
||||
def secret_values(parameters: Dict[str, Any]) -> List[str]:
|
||||
"""Raw secret strings carried in job parameters, longest first, for scrubbing free text."""
|
||||
def secret_values(parameters: Dict[str, Any], service: Optional[str] = None) -> List[str]:
|
||||
"""Raw secret strings carried in job parameters and the credentials configured for ``service``, longest first."""
|
||||
if not isinstance(parameters, dict):
|
||||
return []
|
||||
secrets: List[str] = []
|
||||
if service:
|
||||
from unshackle.core.config import config
|
||||
|
||||
configured = (config.credentials or {}).get(service)
|
||||
for value in configured.values() if isinstance(configured, dict) else [configured]:
|
||||
if isinstance(value, str):
|
||||
secrets.extend(secret_values({"credential": value}))
|
||||
for key in ("credential", "password", "token", "api_key"):
|
||||
value = parameters.get(key)
|
||||
if isinstance(value, str) and value:
|
||||
@@ -77,10 +84,10 @@ def owner_id(api_key: Optional[str]) -> Optional[str]:
|
||||
return hashlib.sha256(api_key.encode()).hexdigest()[:16]
|
||||
|
||||
|
||||
def _redact_text(text: Optional[str], parameters: Dict[str, Any]) -> Optional[str]:
|
||||
def _redact_text(text: Optional[str], parameters: Dict[str, Any], service: Optional[str] = None) -> Optional[str]:
|
||||
"""Mask proxy userinfo and any known parameter secrets that leaked into a free-text field
|
||||
(error message / details / traceback / job worker stderr) before the API returns the field."""
|
||||
return redact_text(text, secret_values(parameters))
|
||||
return redact_text(text, secret_values(parameters, service))
|
||||
|
||||
|
||||
class JobStatus(Enum):
|
||||
@@ -183,7 +190,10 @@ class DownloadJob:
|
||||
names = ("error_message", "error_details", "error_traceback", "worker_stderr")
|
||||
self.redacted = (
|
||||
raw,
|
||||
{name: redact_path(_redact_text(text, self.parameters)) for name, text in zip(names, raw)},
|
||||
{
|
||||
name: redact_path(_redact_text(text, self.parameters, self.service))
|
||||
for name, text in zip(names, raw)
|
||||
},
|
||||
)
|
||||
result.update(
|
||||
{
|
||||
@@ -237,7 +247,7 @@ def record_job_history(job: DownloadJob) -> None:
|
||||
"output_files": job.output_files,
|
||||
"skipped_titles": job.skipped_titles,
|
||||
"parameters": redact_parameters(job.parameters),
|
||||
"error_message": _redact_text(job.error_message, job.parameters),
|
||||
"error_message": _redact_text(job.error_message, job.parameters, job.service),
|
||||
}
|
||||
try:
|
||||
path = history_path()
|
||||
@@ -867,7 +877,9 @@ class DownloadQueueManager:
|
||||
except Exception as e:
|
||||
job.status = JobStatus.FAILED
|
||||
job.error_message = str(e)
|
||||
log.error(f"Job {job.job_id} failed: {e}")
|
||||
log.error(
|
||||
f"Job {job.job_id} failed: {_redact_text(job.error_message, job.parameters, job.service)}"
|
||||
)
|
||||
finally:
|
||||
job.completed_time = datetime.now()
|
||||
record_job_history(job)
|
||||
@@ -905,7 +917,7 @@ class DownloadQueueManager:
|
||||
job.error_code = job.error_code or api_error.error_code.value
|
||||
job.error_traceback = job.error_traceback or traceback.format_exc()
|
||||
|
||||
log.error(f"Download failed for job {job.job_id}: {e}")
|
||||
log.error(f"Download failed for job {job.job_id}: {_redact_text(str(e), job.parameters, job.service)}")
|
||||
raise
|
||||
|
||||
def worker_speed_limit(self) -> Optional[float]:
|
||||
@@ -1045,8 +1057,8 @@ class DownloadQueueManager:
|
||||
|
||||
# A service can echo a credential or a proxy URL into its output, so scrub it before
|
||||
# it reaches the log as well, not only the API response.
|
||||
safe_stdout = _redact_text(stdout.strip(), job.parameters)
|
||||
safe_stderr = _redact_text(stderr.strip(), job.parameters)
|
||||
safe_stdout = _redact_text(stdout.strip(), job.parameters, job.service)
|
||||
safe_stderr = _redact_text(stderr.strip(), job.parameters, job.service)
|
||||
if stdout.strip():
|
||||
log.debug(f"Worker stdout for job {job.job_id}: {safe_stdout}")
|
||||
if stderr.strip():
|
||||
|
||||
@@ -328,7 +328,12 @@ def write_client_cache(cache_data: Any, cache_tag: str) -> None:
|
||||
continue
|
||||
if not isinstance(content, str):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "cache values must be base64 strings")
|
||||
decompressed = safe_inflate(base64.b64decode(content)).decode("utf-8")
|
||||
try:
|
||||
decompressed = safe_inflate(base64.b64decode(content)).decode("utf-8")
|
||||
except (ValueError, zlib.error):
|
||||
raise APIError(
|
||||
APIErrorCode.INVALID_INPUT, f"cache value {sanitize_log(key)} is not compressed text"
|
||||
) from None
|
||||
if not safe_cache_payload(decompressed):
|
||||
log.warning(f"Rejecting session cache file {sanitize_log(key)}: it holds a type a peer may not send")
|
||||
continue
|
||||
@@ -1894,6 +1899,23 @@ def resolve_vcodec(value: Any) -> Optional[list]:
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, f"Invalid vcodec: {e.format_message()}")
|
||||
|
||||
|
||||
def wanted_refusal(wanted: Any) -> Optional[str]:
|
||||
"""Why the job worker could not parse ``wanted``, or None when it can."""
|
||||
if not wanted:
|
||||
return None
|
||||
from unshackle.core.utils.click_types import SeasonRange
|
||||
|
||||
tokens = re.split(r"\s*[,;]\s*", wanted) if isinstance(wanted, str) else wanted
|
||||
if not isinstance(tokens, list) or not all(isinstance(t, str) for t in tokens):
|
||||
return "wanted must be a string or a list of strings"
|
||||
try:
|
||||
if any(not re.match(r"^!?\d+x\d+(\.\d+)?$", t) for t in tokens):
|
||||
SeasonRange().parse_tokens(*tokens)
|
||||
except (click.BadParameter, ValueError) as e:
|
||||
return f"Invalid wanted parameter: {e}"
|
||||
return None
|
||||
|
||||
|
||||
def validate_download_parameters(data: Dict[str, Any]) -> Optional[str]:
|
||||
"""
|
||||
Validate download parameters and return error message if invalid.
|
||||
@@ -2180,6 +2202,10 @@ async def download_handler(data: Dict[str, Any], request: Optional[web.Request]
|
||||
require_fields(data, "service", "title_id")
|
||||
service_tag = data["service"]
|
||||
title_id = data["title_id"]
|
||||
if not isinstance(title_id, str):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "title_id must be a string", details={"title_id": title_id})
|
||||
if refusal := wanted_refusal(data.get("wanted")):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, refusal, details={"wanted": data.get("wanted")})
|
||||
|
||||
server, info, data = await relay_target(data, request)
|
||||
normalized_service = info["tag"] if info else validate_service(service_tag, request)
|
||||
@@ -2219,7 +2245,7 @@ async def download_handler(data: Dict[str, Any], request: Optional[web.Request]
|
||||
cast_or_refuse(cli_params, click.Context(click.Command(normalized_service)), sent)
|
||||
service_params = {**defaults, **sent}
|
||||
|
||||
filtered_params = {k: v for k, v in data.items() if k not in ["service", "title_id"]}
|
||||
filtered_params = {k: v for k, v in data.items() if k not in ["service", "title_id", "owner_key"]}
|
||||
# Overlay any dl-relevant keys from `serve:` config (e.g. downloads, workers) so the API
|
||||
# respects server-side defaults without each client having to send them.
|
||||
serve_overrides = {
|
||||
@@ -3937,6 +3963,8 @@ async def session_segments_handler(
|
||||
track_ids = data.get("track_ids", [])
|
||||
if not track_ids:
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "Missing required parameter: track_ids")
|
||||
if not isinstance(track_ids, list) or not all(isinstance(t, str) for t in track_ids):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "track_ids must be an array of strings")
|
||||
|
||||
try:
|
||||
result: Dict[str, Any] = {}
|
||||
@@ -4881,7 +4909,10 @@ def handle_proxy_license(
|
||||
|
||||
if not challenge_b64:
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "Missing required parameter: challenge")
|
||||
challenge_bytes = base64.b64decode(challenge_b64)
|
||||
try:
|
||||
challenge_bytes = base64.b64decode(challenge_b64)
|
||||
except (TypeError, ValueError):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "challenge is not base64") from None
|
||||
|
||||
if drm_type not in ("widevine", "playready"):
|
||||
raise APIError(
|
||||
|
||||
@@ -157,11 +157,14 @@ def api_handler(handler: Handler) -> Handler:
|
||||
|
||||
|
||||
async def json_body(request: web.Request) -> Any:
|
||||
"""The request's JSON body; raises INVALID_INPUT when it does not parse."""
|
||||
"""The request's JSON object; raises INVALID_INPUT when it does not parse or is not an object."""
|
||||
try:
|
||||
return await request.json()
|
||||
data = await request.json()
|
||||
except Exception as e:
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "Invalid JSON request body", details={"error": str(e)}) from e
|
||||
if not isinstance(data, dict):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "The request body must be a JSON object")
|
||||
return data
|
||||
|
||||
|
||||
HEARTBEAT_INTERVAL = 30.0
|
||||
|
||||
@@ -11,9 +11,13 @@ MAX_CACHE_KEY_DEPTH = 8
|
||||
MAX_SESSION_CACHE_KEYS = 64
|
||||
|
||||
|
||||
def sanitize_log(value: object) -> str:
|
||||
"""Sanitise a value for safe logging by removing newlines and control characters."""
|
||||
return str(value).replace("\n", "").replace("\r", "").replace("\x00", "")
|
||||
CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f-\x9f]")
|
||||
CONTROL_CHARS_BUT_LF = re.compile(r"[\x00-\x09\x0b-\x1f\x7f-\x9f]")
|
||||
|
||||
|
||||
def sanitize_log(value: object, keep_lines: bool = False) -> str:
|
||||
"""Remove control characters, and so ANSI escapes, from a value; newlines too unless ``keep_lines``."""
|
||||
return (CONTROL_CHARS_BUT_LF if keep_lines else CONTROL_CHARS).sub("", str(value))
|
||||
|
||||
|
||||
def safe_cache_key(key: object) -> Optional[str]:
|
||||
|
||||
Reference in New Issue
Block a user