bwpass: Unlock vault if session ID is invalid

If the cached session ID is not valid (e.g. `bw lock` has been run since
the cache file was written), `Vault.load()` will now attempt to unlock
the vault again and update the saved session ID.
master
Dustin 2019-04-30 17:44:21 -05:00
parent 481da11776
commit ff8414a888
1 changed files with 27 additions and 2 deletions

View File

@ -36,6 +36,10 @@ class BitwardenError(Exception):
pass pass
class LockedVaultError(BitwardenError):
pass
class PinentryError(Exception): class PinentryError(Exception):
pass pass
@ -133,7 +137,12 @@ class Vault:
self.load_cache() self.load_cache()
return self return self
self.unlock() self.unlock()
self.get_items() try:
self.get_items()
except LockedVaultError:
self.lock()
self.unlock()
self.get_items()
return self return self
def get_items(self): def get_items(self):
@ -161,6 +170,18 @@ class Vault:
with open(self.cache) as f: with open(self.cache) as f:
self.items = json.load(f) self.items = json.load(f)
def lock(self) -> None:
uid = os.getuid()
fn = os.path.join(
tempfile.gettempdir(),
f'.bw_session-{uid}',
)
try:
os.unlink(fn)
except FileNotFoundError:
pass
self.session_id = None
def unlock(self) -> None: def unlock(self) -> None:
uid = os.getuid() uid = os.getuid()
fn = os.path.join( fn = os.path.join(
@ -215,7 +236,11 @@ class Vault:
) )
data = p.communicate(stdin_bytes)[0].decode('utf-8') data = p.communicate(stdin_bytes)[0].decode('utf-8')
if p.returncode != 0: if p.returncode != 0:
raise BitwardenError(data.rstrip('\n')) msg = data.rstrip('\n')
if msg == 'Vault is locked.':
raise LockedVaultError(msg)
else:
raise BitwardenError(msg)
return data return data