diff --git a/gprofiler/client.py b/gprofiler/client.py index 15c42e9a8..8bd73cba1 100644 --- a/gprofiler/client.py +++ b/gprofiler/client.py @@ -18,9 +18,10 @@ import json from io import BytesIO from typing import IO, TYPE_CHECKING, Any, Dict, List, Optional, Tuple, cast +from urllib.parse import quote_plus import requests -from requests import Session +from requests import RequestException, Session from gprofiler import __version__ from gprofiler.exceptions import APIError @@ -168,9 +169,15 @@ def _send_request( api_version: str = None, params: Dict[str, str] = None, ) -> Dict: - return self._request_url( - method, "{}/{}".format(self.get_base_url(api_version), path), data, files, timeout, params - ) + try: + return self._request_url( + method, "{}/{}".format(self.get_base_url(api_version), path), data, files, timeout, params + ) + except RequestException as e: + # requests exceptions embed the request URL, which contains the token ("key=") - redact it + # so it doesn't leak when the exception is logged. + e.args = (str(e).replace(quote_plus(self._key), "***").replace(self._key, "***"),) + raise e from None def get(self, path: str, data: Any = None, **kwargs: Any) -> Dict: return self._send_request("GET", path, data, **kwargs) diff --git a/gprofiler/log.py b/gprofiler/log.py index 0d35ec2b6..00a6e4caf 100644 --- a/gprofiler/log.py +++ b/gprofiler/log.py @@ -19,6 +19,7 @@ import re import sys import time +from io import TextIOWrapper from logging import LogRecord from typing import Any, Dict, Mapping, Optional from urllib.parse import urlparse @@ -137,6 +138,17 @@ class GProfilerFormatter(_ExtraFormatter, _UTCFormatter): pass +class _PrivateRotatingFileHandler(logging.handlers.RotatingFileHandler): + def _open(self) -> TextIOWrapper: + # applies to the initial file, an existing file left by an older version, and files created on rotation + stream = super()._open() + try: + os.chmod(self.baseFilename, 0o600) + except OSError: + pass # e.g. rootless run with a writable log file owned by another user - keep logging as before + return stream + + def initial_root_logger_setup( stream_level: int, log_file_path: str, @@ -152,8 +164,10 @@ def initial_root_logger_setup( stream_handler.setFormatter(GProfilerFormatter(LOGS_FORMAT)) logger_adapter.logger.addHandler(stream_handler) - os.makedirs(os.path.dirname(log_file_path), exist_ok=True) - file_handler = logging.handlers.RotatingFileHandler( + # logs may contain sensitive data: a log dir we create is owner-only (an existing dir, e.g. $HOME when running + # rootless with --log-file, is left as is), and log files are owner-only. + os.makedirs(os.path.dirname(log_file_path), mode=0o700, exist_ok=True) + file_handler = _PrivateRotatingFileHandler( log_file_path, maxBytes=rotate_max_bytes, backupCount=rotate_backup_count,