Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix cross-platform db issue #431

Closed
wants to merge 5 commits into from
Closed
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
19 changes: 16 additions & 3 deletions client/utils/storage.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import os
import ctypes
import shelve # persistance
import hmac # security
Expand Down Expand Up @@ -30,22 +31,34 @@ def mac(value):
mac.update(repr(value).encode('utf-8'))
return mac.hexdigest()

def open_db():
try:
return shelve.open(SHELVE_FILE)
except:
# just catch everything because there are a variety of errors that a corrupt db can cause
# if there is some other error that will happen on the retry hopefully
for name in os.listdir("."):
if name.startswith(SHELVE_FILE):
os.rename(name, name + ".corrupt")
return shelve.open(SHELVE_FILE)


def contains(root, key):
key = '{}-{}'.format(root, key)
with shelve.open(SHELVE_FILE) as db:
with open_db() as db:
return key in db

def store(root, key, value):
key = '{}-{}'.format(root, key)
with shelve.open(SHELVE_FILE) as db:
with open_db() as db:
db[key] = {'value': value, 'mac': mac(value)}
return value

def get(root, key, default=None):
if not contains(root, key):
return default
key = '{}-{}'.format(root, key)
with shelve.open(SHELVE_FILE) as db:
with open_db() as db:
data = db[key]
if not hmac.compare_digest(data['mac'], mac(data['value'])):
raise ProtocolException('{} was tampered. Reverse changes, or redownload assignment'.format(SHELVE_FILE))
Expand Down
17 changes: 17 additions & 0 deletions tests/end_to_end/storage_corrupt_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import json
import tempfile

from tests.end_to_end.end_to_end_test import EndToEndTest


class EncryptionTest(EndToEndTest):
def testEncrypt(self):
self.copy_examples()
stdout, stderr = self.run_ok("-q", "q1")
self.assertOnlyInvalidGrant(stderr)
# mess up the shelve
self.add_file(".ok_storage.dir", "\0")
self.add_file(".ok_storage.bak", "\0")
self.add_file(".ok_storage.dat", "\0")
stdout, stderr = self.run_ok("-q", "q1")
self.assertOnlyInvalidGrant(stderr)