Skip to content
Draft
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
10 changes: 8 additions & 2 deletions shabda/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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)
Expand Down