From 724a77fa07466d45f19c6216dfda6781cc943ab9 Mon Sep 17 00:00:00 2001 From: "Alexandre G.-Raymond" Date: Wed, 3 Dec 2025 21:22:12 +0100 Subject: [PATCH] Potential fix for code scanning alert no. 3: Uncontrolled data used in path expression Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com> --- shabda/cache.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/shabda/cache.py b/shabda/cache.py index 265d3a3..e0b1ee4 100644 --- a/shabda/cache.py +++ b/shabda/cache.py @@ -14,7 +14,10 @@ def save(key, value, ttl=60 * 60 * 24): """Write a key:value pair to cache.""" # ttl is "time to live" of the item in seconds - filepath = CACHE_PATH + key + filepath = os.path.normpath(os.path.join(CACHE_PATH, key)) + # Ensure the normalized filepath is within CACHE_PATH + if not filepath.startswith(os.path.normpath(CACHE_PATH)): + raise Exception("Invalid cache key: path traversal detected") expiry = int(time.time() + ttl) cache = (expiry, value) with open(filepath, "w+b") as file: @@ -23,7 +26,10 @@ def save(key, value, ttl=60 * 60 * 24): def load(key): """Read the value for given key from cache.""" - filepath = CACHE_PATH + key + filepath = os.path.normpath(os.path.join(CACHE_PATH, key)) + # Ensure the normalized filepath is within CACHE_PATH + if not filepath.startswith(os.path.normpath(CACHE_PATH)): + raise Exception("Invalid cache key: path traversal detected") try: with open(filepath, "r+b") as file: expiry, value = pickle.load(file)