Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions scripts/zwik_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -445,15 +445,20 @@ def from_prefix(cls, prefix):
return obj


def sanitize_pat(text):
"""Remove zwik PAT tokens from a string to avoid leaking credentials."""
if "zwik_pat_" in text:
text = re.sub("zwik_pat_[a-zA-Z0-9_-]{5,}", "zwik_pat_******", text)
return text


class CustomFormatter(logging.Formatter):
def __init__(self, fmt=None, datefmt=None):
super().__init__(fmt, datefmt)

def format(self, record):
result = super().format(record)
if "zwik_pat_" in result:
result = re.sub("zwik_pat_[a-zA-Z0-9_-]{5,}", "zwik_pat_******", result)
return result
return sanitize_pat(result)


class EnvironmentDependencies:
Expand Down Expand Up @@ -1546,7 +1551,7 @@ def export_environment(self, output_path, file_format=None):
)
writer.writeheader()
for pkg_name, data in packages.items():
writer.writerow(data)
writer.writerow({**data, "url": sanitize_pat(data["url"])})

log.info("Environment exported to %s", output_path)

Expand Down
33 changes: 33 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -562,6 +562,39 @@ def test_export(self):
env.export_environment(export_path, export_format)
self.assertTrue(os.path.exists(export_path))

def test_export_csv_doesnt_contain_PAT(self):
"""
This test ensures that the export functionality doesn't include the
PAT token in the exported file, as it is a sensitive information
"""
env = ZwikEnvironment.from_yaml(ZwikSettings(), self.yaml_file)
self.create_env(env)

# Inject a conda-meta package whose URL contains a PAT token
fake_pat = "zwik_pat_secrettoken12345"
fake_url = "http://{}@127.0.0.1/channel/noarch/fake-1.0-0.conda".format(
fake_pat
)
fake_pkg_meta = {
"name": "fake-package",
"version": "1.0",
"url": fake_url,
}
conda_meta_dir = os.path.join(env.prefix, "conda-meta")
fake_meta_path = os.path.join(conda_meta_dir, "fake-package-1.0-0.json")
with open(fake_meta_path, "w") as fp:
json.dump(fake_pkg_meta, fp)

export_path = os.path.join(self.working_dir, "export_file.csv")
env.export_environment(export_path, "csv")
self.assertTrue(os.path.exists(export_path))

with open(export_path) as fp:
csv_content = fp.read()

self.assertNotIn(fake_pat, csv_content)
self.assertIn("zwik_pat_******", csv_content)

@mock.patch("scripts.zwik_client.check_installation")
@mock.patch("scripts.zwik_client.apply_workarounds")
@mock.patch("scripts.zwik_client.handle_environment")
Expand Down
Loading