Skip to content

Commit

Permalink
Fix handling concurrent runs of dummy secret tool
Browse files Browse the repository at this point in the history
  • Loading branch information
arkq committed Apr 15, 2022
1 parent 372ec83 commit 2790ed2
Showing 1 changed file with 37 additions and 22 deletions.
59 changes: 37 additions & 22 deletions integrations/docker/images/chip-build-tizen/secret-tool.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/python3
# Dummy Password Manager for Tizen Studio CLI

import fcntl
import os
import pickle
import sys
Expand All @@ -11,36 +12,57 @@ class Secrets:

def __init__(self, filename: str):
self.filename = filename
self.dirty = False
self.secrets = {}
self.fp = None

def __enter__(self):
self.fp = open(self.filename, "a+b")
fcntl.flock(self.fp.fileno(), fcntl.LOCK_EX)
self._load()
return self

def __exit__(self, _type, value, tb):
if self.dirty:
self._save()
fcntl.flock(self.fp.fileno(), fcntl.LOCK_UN)
self.fp.close()

@staticmethod
def _build_key(label: str, **kw):
return label + ":" + str(tuple(sorted(kw.items())))

def load(self):
def _load(self):
try:
with open(self.filename, "rb") as f:
self.secrets = pickle.load(f)
except (IOError, ValueError) as e:
self.fp.seek(0)
self.secrets = pickle.load(self.fp)
except EOFError:
# Unpickling an empty file is not an error for us
pass
except ValueError as e:
print("ERROR: " + str(e), file=sys.stderr)

def save(self):
def _save(self):
try:
with open(self.filename, "wb") as f:
pickle.dump(self.secrets, f)
self.fp.seek(0)
self.fp.truncate()
pickle.dump(self.secrets, self.fp)
except IOError as e:
print("ERROR: " + str(e), file=sys.stderr)

def clear(self, label: str, **kw):
key = self._build_key(label, **kw)
self.secrets.pop(key, None)
self.dirty = True

def store(self, label: str, password: str, **kw):
key = self._build_key(label, **kw)
self.secrets[key] = password
self.dirty = True

def lookup(self, label: str, **kw):
key = self._build_key(label, **kw)
print(self.secrets)
return self.secrets.get(key, "")


Expand All @@ -63,18 +85,11 @@ def lookup(self, label: str, **kw):
args = parser.parse_args()
kw = dict(zip(args.kw[:: 2], args.kw[1:: 2]))

with open(os.path.expanduser("~/.secretsdb.log"), "a") as f:
f.write("%s: %s: %s\n" % (args.command, args.label, kw))

secrets = Secrets(os.path.expanduser("~/.secretsdb"))
secrets.load()

if args.command == "clear":
secrets.clear(args.label, **kw)
secrets.save()
elif args.command == "store":
secrets.store(args.label, args.password, **kw)
secrets.save()
elif args.command == "lookup":
password = secrets.lookup(args.label, **kw)
print(password)
with Secrets(os.path.expanduser("~/.secretsdb")) as secrets:
if args.command == "clear":
secrets.clear(args.label, **kw)
elif args.command == "store":
secrets.store(args.label, args.password, **kw)
elif args.command == "lookup":
password = secrets.lookup(args.label, **kw)
print(password)

0 comments on commit 2790ed2

Please sign in to comment.