Skip to content

Commit

Permalink
Add secrets to manager
Browse files Browse the repository at this point in the history
  • Loading branch information
dheyay committed Mar 19, 2024
1 parent f4b63f8 commit d05c151
Show file tree
Hide file tree
Showing 10 changed files with 27 additions and 13 deletions.
2 changes: 2 additions & 0 deletions uaclient/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
livepatch,
)
from uaclient import log as pro_log
from uaclient import secret_manager
from uaclient import status as ua_status
from uaclient import system, timer, util
from uaclient.clouds import AutoAttachCloudInstance # noqa: F401
Expand Down Expand Up @@ -64,6 +65,7 @@ def attach_with_token(
)
from uaclient.timer.update_messaging import update_motd_messages

secret_manager.secrets.add_secret(token)
contract_client = contract.UAContractClient(cfg)
attached_at = datetime.datetime.now(tz=datetime.timezone.utc)
new_machine_token = contract_client.add_contract_machine(
Expand Down
1 change: 1 addition & 0 deletions uaclient/api/u/pro/attach/magic/wait/v1.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ def _wait(
else:
raise e

# TODO: Add secrets to secret manager
if wait_resp and wait_resp.get("contractToken") is not None:
return MagicAttachWaitResult(
user_code=wait_resp["userCode"],
Expand Down
13 changes: 12 additions & 1 deletion uaclient/apt.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,15 @@
import apt_pkg # type: ignore
from apt.progress.base import AcquireProgress # type: ignore

from uaclient import event_logger, exceptions, gpg, messages, system, util
from uaclient import (
event_logger,
exceptions,
gpg,
messages,
secret_manager,
system,
util,
)
from uaclient.defaults import ESM_APT_ROOTDIR

APT_HELPER_TIMEOUT = 60.0 # 60 second timeout used for apt-helper call
Expand Down Expand Up @@ -545,9 +553,11 @@ def add_auth_apt_repo(
"""
try:
username, password = credentials.split(":")
secret_manager.secrets.add_secret(password)
except ValueError: # Then we have a bearer token
username = "bearer"
password = credentials
secret_manager.secrets.add_secret(password)
series = system.get_release_info().series
if repo_url.endswith("/"):
repo_url = repo_url[:-1]
Expand Down Expand Up @@ -596,6 +606,7 @@ def add_apt_auth_conf_entry(repo_url, login, password):
orig_content = system.load_file(apt_auth_file)
else:
orig_content = ""

repo_auth_line = (
"machine {repo_path} login {login} password {password}"
"{cmt}".format(
Expand Down
3 changes: 2 additions & 1 deletion uaclient/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1433,7 +1433,8 @@ def setup_logging(log_level, log_file=None, logger=None):
file_handler.setFormatter(JsonArrayFormatter())
file_handler.setLevel(log_level)
file_handler.set_name("upro-file")
file_handler.addFilter(pro_log.RedactionFilter())
file_handler.addFilter(pro_log.RegexRedactionFilter())
file_handler.addFilter(pro_log.KnownSecretRedactionFilter())
logger.addHandler(file_handler)


Expand Down
3 changes: 2 additions & 1 deletion uaclient/daemon/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ def setup_logging(console_level, log_level, log_file, logger=None):
logger.setLevel(log_level)

logger.handlers = []
logger.addFilter(pro_log.SecretRedactionFilter())
logger.addFilter(pro_log.RegexRedactionFilter)
logger.addFilter(pro_log.KnownSecretRedactionFilter())

console_handler = logging.StreamHandler(sys.stderr)
console_handler.setFormatter(logging.Formatter("%(message)s"))
Expand Down
2 changes: 2 additions & 0 deletions uaclient/entitlements/livepatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
http,
livepatch,
messages,
secret_manager,
snap,
system,
util,
Expand Down Expand Up @@ -170,6 +171,7 @@ def setup_livepatch_config(
return False
if process_token:
livepatch_token = entitlement_cfg.get("resourceToken")
secret_manager.secrets.add_secret(livepatch_token)
if not livepatch_token:
LOG.debug(
"No specific resourceToken present. Using machine token as"
Expand Down
1 change: 1 addition & 0 deletions uaclient/files/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ def read(self) -> Optional[dict]:
return None
try:
content = json.loads(content, cls=util.DatetimeAwareJSONDecoder)
# TODO: Add secrets to secret Manager
except Exception:
pass
return content # type: ignore
Expand Down
6 changes: 3 additions & 3 deletions uaclient/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@
from uaclient.config import UAConfig


class RedactionFilter(logging.Filter):
class RegexRedactionFilter(logging.Filter):
"""A logging filter to redact confidential info"""

def filter(self, record: logging.LogRecord):
record.msg = util.redact_sensitive_logs(str(record.msg))
return True


class SecretRedactionFilter(logging.Filter):
class KnownSecretRedactionFilter(logging.Filter):
"""A logging filter to redact confidential info"""

def filter(self, record: logging.LogRecord):
Expand Down Expand Up @@ -111,5 +111,5 @@ def setup_journald_logging(log_level, logger):
console_handler = logging.StreamHandler()
console_handler.setFormatter(JsonArrayFormatter())
console_handler.setLevel(log_level)
console_handler.addFilter(RedactionFilter())
console_handler.addFilter(RegexRedactionFilter())
logger.addHandler(console_handler)
7 changes: 1 addition & 6 deletions uaclient/secret_manager.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import re


class SecretManager:
def __init__(self):
self._secrets = []
Expand All @@ -18,9 +15,7 @@ def clear_secrets(self) -> None:
def redact_secrets(self, log_record: str) -> str:
redacted_record = log_record
for secret in self._secrets:
redacted_record = re.sub(
f"({re.escape(secret)})", "<REDACTED>", redacted_record
)
redacted_record = redacted_record.replace(secret, "<REDACTED>")
return redacted_record


Expand Down
2 changes: 1 addition & 1 deletion uaclient/tests/test_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def test_unredacted_text(self, caplog_text):
)
@pytest.mark.parametrize("caplog_text", [logging.INFO], indirect=True)
def test_redacted_text(self, caplog_text, raw_log, expected):
LOG.addFilter(pro_log.RedactionFilter())
LOG.addFilter(pro_log.RegexRedactionFilter())
LOG.info(raw_log)
log = caplog_text()
assert expected in log
Expand Down

0 comments on commit d05c151

Please sign in to comment.