|
| 1 | +"""A generic persistence layer, optionally encrypted on Windows, OSX, and Linux. |
| 2 | +
|
| 3 | +Should a certain encryption is unavailable, exception will be raised at run-time, |
| 4 | +rather than at import time. |
| 5 | +
|
| 6 | +By successfully creating and using a certain persistence object, |
| 7 | +app developer would naturally know whether the data are protected by encryption. |
| 8 | +""" |
| 9 | +import abc |
| 10 | +import os |
| 11 | +import errno |
| 12 | +try: |
| 13 | + from pathlib import Path # Built-in in Python 3 |
| 14 | +except: |
| 15 | + from pathlib2 import Path # An extra lib for Python 2 |
| 16 | + |
| 17 | + |
| 18 | +try: |
| 19 | + ABC = abc.ABC |
| 20 | +except AttributeError: # Python 2.7, abc exists, but not ABC |
| 21 | + ABC = abc.ABCMeta("ABC", (object,), {"__slots__": ()}) # type: ignore |
| 22 | + |
| 23 | + |
| 24 | +def _mkdir_p(path): |
| 25 | + """Creates a directory, and any necessary parents. |
| 26 | +
|
| 27 | + This implementation based on a Stack Overflow question that can be found here: |
| 28 | + https://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python |
| 29 | +
|
| 30 | + If the path provided is an existing file, this function raises an exception. |
| 31 | + :param path: The directory name that should be created. |
| 32 | + """ |
| 33 | + if not path: |
| 34 | + return # NO-OP |
| 35 | + try: |
| 36 | + os.makedirs(path) |
| 37 | + except OSError as exp: |
| 38 | + if exp.errno == errno.EEXIST and os.path.isdir(path): |
| 39 | + pass |
| 40 | + else: |
| 41 | + raise |
| 42 | + |
| 43 | + |
| 44 | +class BasePersistence(ABC): |
| 45 | + """An abstract persistence defining the common interface of this family""" |
| 46 | + |
| 47 | + is_encrypted = False # Default to False. To be overridden by sub-classes. |
| 48 | + |
| 49 | + @abc.abstractmethod |
| 50 | + def save(self, content): |
| 51 | + # type: (str) -> None |
| 52 | + """Save the content into this persistence""" |
| 53 | + raise NotImplementedError |
| 54 | + |
| 55 | + @abc.abstractmethod |
| 56 | + def load(self): |
| 57 | + # type: () -> str |
| 58 | + """Load content from this persistence""" |
| 59 | + raise NotImplementedError |
| 60 | + |
| 61 | + @abc.abstractmethod |
| 62 | + def time_last_modified(self): |
| 63 | + """Get the last time when this persistence has been modified""" |
| 64 | + raise NotImplementedError |
| 65 | + |
| 66 | + @abc.abstractmethod |
| 67 | + def get_location(self): |
| 68 | + """Return the file path which this persistence stores (meta)data into""" |
| 69 | + raise NotImplementedError |
| 70 | + |
| 71 | + |
| 72 | +class FilePersistence(BasePersistence): |
| 73 | + """A generic persistence, storing data in a plain-text file""" |
| 74 | + |
| 75 | + def __init__(self, location): |
| 76 | + if not location: |
| 77 | + raise ValueError("Requires a file path") |
| 78 | + self._location = os.path.expanduser(location) |
| 79 | + _mkdir_p(os.path.dirname(self._location)) |
| 80 | + |
| 81 | + def save(self, content): |
| 82 | + # type: (str) -> None |
| 83 | + """Save the content into this persistence""" |
| 84 | + with open(self._location, 'w+') as handle: |
| 85 | + handle.write(content) |
| 86 | + |
| 87 | + def load(self): |
| 88 | + # type: () -> str |
| 89 | + """Load content from this persistence""" |
| 90 | + with open(self._location, 'r') as handle: |
| 91 | + return handle.read() |
| 92 | + |
| 93 | + def time_last_modified(self): |
| 94 | + return os.path.getmtime(self._location) |
| 95 | + |
| 96 | + def touch(self): |
| 97 | + """To touch this file-based persistence without writing content into it""" |
| 98 | + Path(self._location).touch() # For os.path.getmtime() to work |
| 99 | + |
| 100 | + def get_location(self): |
| 101 | + return self._location |
| 102 | + |
| 103 | + |
| 104 | +class FilePersistenceWithDataProtection(FilePersistence): |
| 105 | + """A generic persistence with data stored in a file, |
| 106 | + protected by Win32 encryption APIs on Windows""" |
| 107 | + is_encrypted = True |
| 108 | + |
| 109 | + def __init__(self, location, entropy=''): |
| 110 | + """Initialization could fail due to unsatisfied dependency""" |
| 111 | + # pylint: disable=import-outside-toplevel |
| 112 | + from .windows import WindowsDataProtectionAgent |
| 113 | + self._dp_agent = WindowsDataProtectionAgent(entropy=entropy) |
| 114 | + super(FilePersistenceWithDataProtection, self).__init__(location) |
| 115 | + |
| 116 | + def save(self, content): |
| 117 | + super(FilePersistenceWithDataProtection, self).save( |
| 118 | + self._dp_agent.protect(content)) |
| 119 | + |
| 120 | + def load(self): |
| 121 | + return self._dp_agent.unprotect( |
| 122 | + super(FilePersistenceWithDataProtection, self).load()) |
| 123 | + |
| 124 | + |
| 125 | +class KeychainPersistence(BasePersistence): |
| 126 | + """A generic persistence with data stored in, |
| 127 | + and protected by native Keychain libraries on OSX""" |
| 128 | + is_encrypted = True |
| 129 | + |
| 130 | + def __init__(self, signal_location, service_name, account_name): |
| 131 | + """Initialization could fail due to unsatisfied dependency. |
| 132 | +
|
| 133 | + :param signal_location: See :func:`persistence.LibsecretPersistence.__init__` |
| 134 | + """ |
| 135 | + if not (service_name and account_name): # It would hang on OSX |
| 136 | + raise ValueError("service_name and account_name are required") |
| 137 | + from .osx import Keychain # pylint: disable=import-outside-toplevel |
| 138 | + self._file_persistence = FilePersistence(signal_location) # Favor composition |
| 139 | + self._Keychain = Keychain # pylint: disable=invalid-name |
| 140 | + self._service_name = service_name |
| 141 | + self._account_name = account_name |
| 142 | + |
| 143 | + def save(self, content): |
| 144 | + with self._Keychain() as locker: |
| 145 | + locker.set_generic_password( |
| 146 | + self._service_name, self._account_name, content) |
| 147 | + self._file_persistence.touch() # For time_last_modified() |
| 148 | + |
| 149 | + def load(self): |
| 150 | + with self._Keychain() as locker: |
| 151 | + return locker.get_generic_password( |
| 152 | + self._service_name, self._account_name) |
| 153 | + |
| 154 | + def time_last_modified(self): |
| 155 | + return self._file_persistence.time_last_modified() |
| 156 | + |
| 157 | + def get_location(self): |
| 158 | + return self._file_persistence.get_location() |
| 159 | + |
| 160 | + |
| 161 | +class LibsecretPersistence(BasePersistence): |
| 162 | + """A generic persistence with data stored in, |
| 163 | + and protected by native libsecret libraries on Linux""" |
| 164 | + is_encrypted = True |
| 165 | + |
| 166 | + def __init__(self, signal_location, schema_name, attributes, **kwargs): |
| 167 | + """Initialization could fail due to unsatisfied dependency. |
| 168 | +
|
| 169 | + :param string signal_location: |
| 170 | + Besides saving the real payload into encrypted storage, |
| 171 | + this class will also touch this signal file. |
| 172 | + Applications may listen a FileSystemWatcher.Changed event for reload. |
| 173 | + https://docs.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher.changed?view=netframework-4.8#remarks |
| 174 | + :param string schema_name: See :func:`libsecret.LibSecretAgent.__init__` |
| 175 | + :param dict attributes: See :func:`libsecret.LibSecretAgent.__init__` |
| 176 | + """ |
| 177 | + # pylint: disable=import-outside-toplevel |
| 178 | + from .libsecret import ( # This uncertain import is deferred till runtime |
| 179 | + LibSecretAgent, trial_run) |
| 180 | + trial_run() |
| 181 | + self._agent = LibSecretAgent(schema_name, attributes, **kwargs) |
| 182 | + self._file_persistence = FilePersistence(signal_location) # Favor composition |
| 183 | + |
| 184 | + def save(self, content): |
| 185 | + if self._agent.save(content): |
| 186 | + self._file_persistence.touch() # For time_last_modified() |
| 187 | + |
| 188 | + def load(self): |
| 189 | + return self._agent.load() |
| 190 | + |
| 191 | + def time_last_modified(self): |
| 192 | + return self._file_persistence.time_last_modified() |
| 193 | + |
| 194 | + def get_location(self): |
| 195 | + return self._file_persistence.get_location() |
| 196 | + |
| 197 | +# We could also have a KeyringPersistence() which can then be used together |
| 198 | +# with a FilePersistence to achieve |
| 199 | +# https://github.com/AzureAD/microsoft-authentication-extensions-for-python/issues/12 |
| 200 | +# But this idea is not pursued at this time. |
| 201 | + |
0 commit comments