fix(api): redact every form of a configured credential from job errors

This commit is contained in:
imSp4rky
2026-11-24 17:13:17 -07:00
parent 4692e6bb96
commit 172b76bd76
4 changed files with 66 additions and 6 deletions
+40
View File
@@ -173,6 +173,46 @@ def test_a_job_error_hides_the_configured_credential(monkeypatch: pytest.MonkeyP
assert "EXAMPLE-pass-123" not in job.to_dict(include_full_details=True)["error_message"] assert "EXAMPLE-pass-123" not in job.to_dict(include_full_details=True)["error_message"]
@pytest.mark.parametrize(
"configured, secret",
[
({"default": ["user", "EXAMPLE-pass-123"]}, "EXAMPLE-pass-123"),
(["user", "EXAMPLE-pass-123", "EXAMPLE-extra-456"], "EXAMPLE-extra-456"),
("user:EXAMPLE-pass-123:EXAMPLE-extra-456", "EXAMPLE-extra-456"),
({"default": "user\n:EXAMPLE-pass-123\n"}, "EXAMPLE-pass-123"),
],
)
def test_a_job_error_hides_every_form_of_configured_credential(
monkeypatch: pytest.MonkeyPatch, configured: Any, secret: str
) -> None:
from datetime import datetime
from unshackle.core.api.download_manager import DownloadJob, JobStatus
monkeypatch.setattr(handlers.config, "credentials", {"EXAMPLE": configured})
job = DownloadJob("j1", JobStatus.FAILED, datetime(2026, 1, 1), "EXAMPLE", "t", {})
job.error_message = f"login failed with {secret}"
assert secret not in job.to_dict(include_full_details=True)["error_message"]
def test_a_job_error_hides_the_parts_of_a_per_request_credential() -> None:
from datetime import datetime
from unshackle.core.api.download_manager import DownloadJob, JobStatus
job = DownloadJob(
"j1",
JobStatus.FAILED,
datetime(2026, 1, 1),
"EXAMPLE",
"t",
{"credential": "user:EXAMPLE-pass-123:EXAMPLE-extra-456"},
)
job.error_message = "login failed with EXAMPLE-pass-123 and EXAMPLE-extra-456"
shown = job.to_dict(include_full_details=True)["error_message"]
assert "EXAMPLE-pass-123" not in shown and "EXAMPLE-extra-456" not in shown
def test_decrypting_without_content_keys_is_one_line(tmp_path: Any) -> None: def test_decrypting_without_content_keys_is_one_line(tmp_path: Any) -> None:
import click import click
+1 -3
View File
@@ -4081,9 +4081,7 @@ class dl:
else: else:
credentials = credentials.get("default") credentials = credentials.get("default")
if credentials: if credentials:
if isinstance(credentials, list): return Credential.from_config(credentials)
return Credential(*credentials)
return Credential.loads(credentials) # type: ignore
return None return None
def cdm_from_service_entry(self) -> bool: def cdm_from_service_entry(self) -> bool:
+19 -2
View File
@@ -19,6 +19,7 @@ from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, cast
from unshackle.core.api.events import bus, publish_service_event from unshackle.core.api.events import bus, publish_service_event
from unshackle.core.api.sanitize import sanitize_log from unshackle.core.api.sanitize import sanitize_log
from unshackle.core.credential import Credential
from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_path, redact_text from unshackle.core.utils.redact import REDACTED, URL_USERINFO_RE, redact_all, redact_path, redact_text
from unshackle.core.utils.service_params import cast_service_options, service_options from unshackle.core.utils.service_params import cast_service_options, service_options
@@ -49,6 +50,21 @@ def redact_parameters(parameters: Dict[str, Any]) -> Dict[str, Any]:
return redacted return redacted
def credential_secrets(value: Any) -> List[str]:
"""The secret parts of one credential in any form ``Credential.from_config`` loads."""
try:
credential = Credential.from_config(value)
except (AttributeError, TypeError, ValueError):
return []
parts = [
value if isinstance(value, str) else "",
credential.dumps(),
str(credential.password),
str(credential.extra or ""),
]
return [part for part in parts if len(part) >= 4] # short parts would blanket-replace and garble the text
def secret_values(parameters: Dict[str, Any], service: Optional[str] = None) -> List[str]: 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.""" """Raw secret strings carried in job parameters and the credentials configured for ``service``, longest first."""
if not isinstance(parameters, dict): if not isinstance(parameters, dict):
@@ -59,12 +75,13 @@ def secret_values(parameters: Dict[str, Any], service: Optional[str] = None) ->
configured = (config.credentials or {}).get(service) configured = (config.credentials or {}).get(service)
for value in configured.values() if isinstance(configured, dict) else [configured]: for value in configured.values() if isinstance(configured, dict) else [configured]:
if isinstance(value, str): secrets.extend(credential_secrets(value))
secrets.extend(secret_values({"credential": value}))
for key in ("credential", "password", "token", "api_key"): for key in ("credential", "password", "token", "api_key"):
value = parameters.get(key) value = parameters.get(key)
if isinstance(value, str) and value: if isinstance(value, str) and value:
secrets.append(value) secrets.append(value)
if key == "credential":
secrets.extend(credential_secrets(value))
if key == "credential" and ":" in value: if key == "credential" and ":" in value:
password = value.split(":", 1)[1] password = value.split(":", 1)[1]
if len(password) >= 4: # short passwords would blanket-replace and garble the text if len(password) >= 4: # short passwords would blanket-replace and garble the text
+6 -1
View File
@@ -4,7 +4,7 @@ import base64
import hashlib import hashlib
import re import re
from pathlib import Path from pathlib import Path
from typing import Optional, Union from typing import Any, Optional, Union
class Credential: class Credential:
@@ -54,6 +54,11 @@ class Credential:
value += f":{self.extra}" value += f":{self.extra}"
return base64.b64encode(value.encode()).decode() return base64.b64encode(value.encode()).decode()
@classmethod
def from_config(cls, value: Any) -> Credential:
"""Load a credential from its config form: a ``username:password`` text or a list."""
return cls(*value) if isinstance(value, list) else cls.loads(value)
@classmethod @classmethod
def loads(cls, text: str) -> Credential: def loads(cls, text: str) -> Credential:
""" """