|
| 1 | +from base64 import b64decode, b64encode, urlsafe_b64encode |
| 2 | +from hashlib import sha256 |
| 3 | +from json import JSONDecodeError |
| 4 | +from json import dump as json_dump |
| 5 | +from json import load as json_load |
| 6 | +from os import makedirs, path, urandom |
| 7 | +from time import time |
| 8 | +from typing import Optional |
| 9 | + |
| 10 | +from appdirs import user_data_dir |
| 11 | +from cryptography.fernet import Fernet, InvalidToken |
| 12 | +from cryptography.hazmat.primitives import hashes |
| 13 | +from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC |
| 14 | + |
| 15 | +APPNAME = "firebolt" |
| 16 | + |
| 17 | + |
| 18 | +def generate_salt() -> str: |
| 19 | + return b64encode(urandom(16)).decode("ascii") |
| 20 | + |
| 21 | + |
| 22 | +def generate_file_name(username: str, password: str) -> str: |
| 23 | + username_hash = sha256(username.encode("utf-8")).hexdigest()[:32] |
| 24 | + password_hash = sha256(password.encode("utf-8")).hexdigest()[:32] |
| 25 | + |
| 26 | + return f"{username_hash}{password_hash}.json" |
| 27 | + |
| 28 | + |
| 29 | +class TokenSecureStorage: |
| 30 | + def __init__(self, username: str, password: str): |
| 31 | + """ |
| 32 | + Class for permanent storage of token in the filesystem in encrypted way |
| 33 | +
|
| 34 | + :param username: username used for toke encryption |
| 35 | + :param password: password used for toke encryption |
| 36 | + """ |
| 37 | + self._data_dir = user_data_dir(appname=APPNAME) |
| 38 | + makedirs(self._data_dir, exist_ok=True) |
| 39 | + |
| 40 | + self._token_file = path.join( |
| 41 | + self._data_dir, generate_file_name(username, password) |
| 42 | + ) |
| 43 | + |
| 44 | + self.salt = self._get_salt() |
| 45 | + self.encrypter = FernetEncrypter(self.salt, username, password) |
| 46 | + |
| 47 | + def _get_salt(self) -> str: |
| 48 | + """ |
| 49 | + Get salt from the file if exists, or generate a new one |
| 50 | +
|
| 51 | + :return: salt |
| 52 | + """ |
| 53 | + res = self._read_data_json() |
| 54 | + return res.get("salt", generate_salt()) |
| 55 | + |
| 56 | + def _read_data_json(self) -> dict: |
| 57 | + """ |
| 58 | + Read json token file |
| 59 | +
|
| 60 | + :return: json object as dict |
| 61 | + """ |
| 62 | + if not path.exists(self._token_file): |
| 63 | + return {} |
| 64 | + |
| 65 | + with open(self._token_file) as f: |
| 66 | + try: |
| 67 | + return json_load(f) |
| 68 | + except JSONDecodeError: |
| 69 | + return {} |
| 70 | + |
| 71 | + def get_cached_token(self) -> Optional[str]: |
| 72 | + """ |
| 73 | + Get decrypted token using username and password |
| 74 | + If the token not found or token cannot be decrypted using username, password |
| 75 | + None will be returned |
| 76 | +
|
| 77 | + :return: token or None |
| 78 | + """ |
| 79 | + res = self._read_data_json() |
| 80 | + if "token" not in res: |
| 81 | + return None |
| 82 | + |
| 83 | + # Ignore expired tokens |
| 84 | + if "expiration" in res and res["expiration"] <= int(time()): |
| 85 | + return None |
| 86 | + |
| 87 | + return self.encrypter.decrypt(res["token"]) |
| 88 | + |
| 89 | + def cache_token(self, token: str, expiration_ts: int) -> None: |
| 90 | + """ |
| 91 | +
|
| 92 | + :param token: |
| 93 | + :return: |
| 94 | + """ |
| 95 | + token = self.encrypter.encrypt(token) |
| 96 | + |
| 97 | + with open(self._token_file, "w") as f: |
| 98 | + json_dump( |
| 99 | + {"token": token, "salt": self.salt, "expiration": expiration_ts}, f |
| 100 | + ) |
| 101 | + |
| 102 | + |
| 103 | +class FernetEncrypter: |
| 104 | + def __init__(self, salt: str, username: str, password: str): |
| 105 | + """ |
| 106 | +
|
| 107 | + :param salt: |
| 108 | + :param username: |
| 109 | + :param password: |
| 110 | + """ |
| 111 | + |
| 112 | + kdf = PBKDF2HMAC( |
| 113 | + algorithm=hashes.SHA256(), |
| 114 | + salt=b64decode(salt), |
| 115 | + length=32, |
| 116 | + iterations=39000, |
| 117 | + ) |
| 118 | + self.fernet = Fernet( |
| 119 | + urlsafe_b64encode( |
| 120 | + kdf.derive(bytes(f"{username}{password}", encoding="utf-8")) |
| 121 | + ) |
| 122 | + ) |
| 123 | + |
| 124 | + def encrypt(self, data: str) -> str: |
| 125 | + return self.fernet.encrypt(bytes(data, encoding="utf-8")).decode("utf-8") |
| 126 | + |
| 127 | + def decrypt(self, data: str) -> Optional[str]: |
| 128 | + try: |
| 129 | + return self.fernet.decrypt(bytes(data, encoding="utf-8")).decode("utf-8") |
| 130 | + except InvalidToken: |
| 131 | + return None |
0 commit comments