django-cloud-backup 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,62 @@
1
+ import hashlib
2
+
3
+ from .config import BackupConfig, CHANGED_HISTORY, CHANGED_OVERWRITE, CHANGED_PROTECT # noqa: F401 re-export
4
+
5
+
6
+ class BaseBackup:
7
+
8
+ def __init__(self, storage, base_backup_dir, logger, config=None):
9
+ self.storage = storage
10
+ self.logger = logger
11
+ self.base_backup_dir = storage.ensure_folder(base_backup_dir)
12
+ # no config = the default config resolved from the legacy global settings
13
+ self.config = config if config is not None else BackupConfig()
14
+ self.encryption_key = self.config.encryption_key
15
+
16
+ def get_existing_backup_files(self, backup_dir, include_metadata=False):
17
+ if isinstance(backup_dir, str):
18
+ backup_dir = self.storage.ensure_folder(backup_dir, parent=self.base_backup_dir)
19
+ return self.storage.list_files(backup_dir, include_metadata=include_metadata)
20
+
21
+ @staticmethod
22
+ def get_hash(f):
23
+ return f.get('hash')
24
+
25
+ @staticmethod
26
+ def content_hash(f):
27
+ """The md5 of the backed-up content: prefers the md5 recorded in metadata at
28
+ upload time (still the plaintext hash when the stored bytes are encrypted)
29
+ over the storage backend's hash of the stored bytes."""
30
+ return (f.get('metadata') or {}).get('md5') or f.get('hash')
31
+
32
+ def get_files_by_name(self, directory, include_metadata=False):
33
+ """
34
+ :param directory: folder path string or a folder handle from the storage
35
+ :return: {file name: [file dicts]} for the files already in the backup
36
+ """
37
+ files_by_name = {}
38
+ for f in self.get_existing_backup_files(directory, include_metadata=include_metadata):
39
+ files_by_name.setdefault(f['name'], []).append(f)
40
+ return files_by_name
41
+
42
+ def get_file_hashes(self, directory, get_hash=None, include_metadata=False):
43
+ """
44
+ :param directory: folder path string or a folder handle from the storage
45
+ :param get_hash: optional override to hash a file dict differently
46
+ :param include_metadata: pass True when get_hash reads file metadata
47
+ """
48
+ if get_hash is None:
49
+ get_hash = self.get_hash
50
+ return {name: [get_hash(f) for f in files]
51
+ for name, files in self.get_files_by_name(directory, include_metadata).items()}
52
+
53
+ @staticmethod
54
+ def md5sum(filename, block_size=65536):
55
+ file_hash = hashlib.md5()
56
+ with open(filename, "rb") as f:
57
+ for block in iter(lambda: f.read(block_size), b""):
58
+ file_hash.update(block)
59
+ return file_hash.hexdigest()
60
+
61
+ def check_upload(self, stored_file, local_file):
62
+ return self.storage.verify_upload(stored_file, local_file)
@@ -0,0 +1,36 @@
1
+ import os
2
+ import bz2
3
+ import subprocess
4
+ from shutil import copyfileobj
5
+
6
+
7
+ def decompress(filename):
8
+ extension = filename[filename.rfind('.') + 1:].lower()
9
+ decompressed_name = filename[:- 1 * (len(extension) + 1)]
10
+
11
+ if extension == 'bz2':
12
+ with bz2.BZ2File(filename, 'rb') as input_file:
13
+ with open(decompressed_name, 'wb') as output:
14
+ copyfileobj(input_file, output)
15
+ os.remove(filename)
16
+
17
+ elif extension == 'gz':
18
+ subprocess.call(['gunzip', filename])
19
+
20
+ else:
21
+ raise ValueError('Unknown file type: ' + filename)
22
+
23
+ return decompressed_name
24
+
25
+
26
+ def compress(filename, compression_type):
27
+ if compression_type == 'bz2':
28
+ with open(filename, 'rb') as input_file:
29
+ with bz2.BZ2File(filename + '.' + compression_type, 'wb', compresslevel=1) as output:
30
+ copyfileobj(input_file, output, 1024*1024)
31
+ os.remove(filename)
32
+
33
+ elif compression_type == 'gz':
34
+ subprocess.call(['gzip', filename])
35
+
36
+ return filename + '.' + compression_type
cloud_backup/config.py ADDED
@@ -0,0 +1,87 @@
1
+ """Named backup configurations.
2
+
3
+ settings.BACKUP_CONFIGS maps config names to dicts so one project can back up to
4
+ several destinations with different behaviour - e.g. an encrypted, object-locked
5
+ offsite store plus an unencrypted database copy for a staging server:
6
+
7
+ BACKUP_CONFIGS = {
8
+ 'default': {
9
+ 'storage': {'backend': 's3', ..., 'lock': {...}},
10
+ 'encryption': True,
11
+ 'changed_files': 'protect',
12
+ },
13
+ 'staging': {
14
+ 'storage': {'backend': 's3', 'bucket': 'staging-transfer', ...},
15
+ 'encryption': False,
16
+ 'dirs': [], # database only
17
+ 'retention': [{'days': 1, 'number': 2}],
18
+ },
19
+ }
20
+
21
+ Config keys: storage (BACKUP_STORAGE-style dict), encryption (True = derive from the
22
+ encrypted-credentials SETTINGS_KEY, or a urlsafe-base64 32-byte key string), db
23
+ (include the database, default True), db_dir, dirs, s3_dirs, retention,
24
+ changed_files. A key absent from a named config inherits the corresponding legacy
25
+ global setting (BACKUP_STORAGE, BACKUP_ENCRYPTION, BACKUP_DIRS, ...), which is also
26
+ how installations without BACKUP_CONFIGS keep working unchanged - their globals
27
+ simply become the 'default' config.
28
+
29
+ The web UI and un-parameterised Celery tasks always use the default config; other
30
+ configs are reached with backup_website --config / restore_db --config or by
31
+ scheduling the tasks with kwargs={'config': 'staging'}.
32
+ """
33
+ from django.conf import settings
34
+ from django.core.exceptions import ImproperlyConfigured
35
+
36
+ from .encryption import resolve_key
37
+
38
+ DEFAULT_CONFIG = 'default'
39
+
40
+ CHANGED_OVERWRITE = 'overwrite'
41
+ CHANGED_PROTECT = 'protect'
42
+ CHANGED_HISTORY = 'history'
43
+
44
+
45
+ class BackupConfig:
46
+ """Resolved settings for one backup destination. Every value falls back to the
47
+ legacy global setting so BackupConfig() alone reproduces pre-BACKUP_CONFIGS
48
+ behaviour exactly."""
49
+
50
+ def __init__(self, name=DEFAULT_CONFIG, config=None):
51
+ self.name = name
52
+ config = config or {}
53
+ self.storage_settings = config.get('storage',
54
+ getattr(settings, 'BACKUP_STORAGE', None) or {'backend': 'gdrive'})
55
+ self.root = self.storage_settings.get('root', getattr(settings, 'BACKUP_ROOT', 'django_backup'))
56
+ self.include_db = config.get('db', True)
57
+ self.db_dir = config.get('db_dir', getattr(settings, 'BACKUP_DB_DIR', self.root + '/db'))
58
+ self.dirs = config.get('dirs', getattr(settings, 'BACKUP_DIRS', []))
59
+ self.s3_dirs = config.get('s3_dirs', getattr(settings, 'S3_BACKUP_DIRS', []))
60
+ self.retention = config.get('retention', getattr(settings, 'BACKUP_DB_RETENTION', None))
61
+ # fails fast on a bad key before anything is backed up
62
+ self.encryption_key = resolve_key(config.get('encryption',
63
+ getattr(settings, 'BACKUP_ENCRYPTION', None)))
64
+ self.changed_files = config.get('changed_files',
65
+ getattr(settings, 'BACKUP_CHANGED_FILES', CHANGED_OVERWRITE))
66
+ if self.changed_files not in (CHANGED_OVERWRITE, CHANGED_PROTECT, CHANGED_HISTORY):
67
+ raise ImproperlyConfigured(f"changed_files for backup config '{name}' must be one of "
68
+ f'{CHANGED_OVERWRITE!r}, {CHANGED_PROTECT!r}, {CHANGED_HISTORY!r}')
69
+
70
+
71
+ def get_config(name=None):
72
+ configs = getattr(settings, 'BACKUP_CONFIGS', None)
73
+ if not configs:
74
+ if name not in (None, DEFAULT_CONFIG):
75
+ raise ImproperlyConfigured(f'BACKUP_CONFIGS is not defined so backup config {name!r} does not exist')
76
+ return BackupConfig()
77
+ if name is None:
78
+ if DEFAULT_CONFIG in configs:
79
+ name = DEFAULT_CONFIG
80
+ elif len(configs) == 1:
81
+ name = next(iter(configs))
82
+ else:
83
+ raise ImproperlyConfigured(f"Several BACKUP_CONFIGS and none named '{DEFAULT_CONFIG}' - "
84
+ f'specify one of: {", ".join(configs)}')
85
+ if name not in configs:
86
+ raise ImproperlyConfigured(f'Unknown backup config {name!r} - available: {", ".join(configs)}')
87
+ return BackupConfig(name, configs[name])
@@ -0,0 +1,267 @@
1
+ """Optional client-side encryption of backup content, enabled per backup config
2
+ (the 'encryption' key in a BACKUP_CONFIGS entry, or the legacy global
3
+ BACKUP_ENCRYPTION setting): True reuses the encrypted-credentials SETTINGS_KEY,
4
+ or a dedicated urlsafe-base64 32-byte key (the same format as a Fernet key, so
5
+ encrypted_credentials.encrypted_file.random_key() generates one). This module is
6
+ settings-agnostic - callers resolve their config's key with resolve_key() and
7
+ pass the raw key bytes in.
8
+
9
+ Format v1 - chunked AES-256-GCM (the STREAM construction, as used by age/Tink):
10
+
11
+ Header (28 bytes, also the associated data for every chunk):
12
+ 0-5 magic b'DCBENC'
13
+ 6 version 0x01
14
+ 7 flags 0x00 (reserved)
15
+ 8-11 chunk_size uint32 big-endian (writers here use 1 MiB)
16
+ 12-27 salt 16 random bytes per file
17
+
18
+ file_key = HKDF-SHA256(master_key, salt=salt, info=b'django-cloud-backup v1')
19
+
20
+ Body - chunks of chunk_size plaintext (the last carries the remainder):
21
+ nonce (12 bytes) = 11-byte big-endian chunk counter || final flag byte
22
+ chunk = AESGCM(file_key).encrypt(nonce, plaintext, associated_data=header)
23
+
24
+ The per-file random salt makes nonce reuse across files impossible, the final
25
+ flag byte defeats truncation at a chunk boundary, and a wrong key fails cleanly
26
+ on the first chunk. Given a fixed salt the ciphertext is deterministic, which
27
+ is what lets EncryptingReader support backward seeks by re-encrypting.
28
+ """
29
+ import base64
30
+ import binascii
31
+ import hashlib
32
+ import io
33
+ import os
34
+ import struct
35
+
36
+ from django.core.exceptions import ImproperlyConfigured
37
+
38
+ from encrypted_credentials.django_credentials import env_key_name
39
+
40
+ MAGIC = b'DCBENC'
41
+ VERSION = 1
42
+ FLAGS = 0
43
+ CHUNK_SIZE = 1024 * 1024
44
+ SALT_LEN = 16
45
+ HEADER_LEN = 28
46
+ TAG_LEN = 16
47
+ KEY_INFO = b'django-cloud-backup v1'
48
+
49
+ INSTALL_HINT = 'pip install django-cloud-backup[encryption]'
50
+
51
+
52
+ class DecryptionError(Exception):
53
+ pass
54
+
55
+
56
+ def resolve_key(encryption_setting):
57
+ """Turn a config's encryption value into raw key bytes: falsy -> None
58
+ (encryption off), True -> the encrypted-credentials SETTINGS_KEY from the
59
+ environment, a string -> a dedicated urlsafe-base64 32-byte key."""
60
+ if not encryption_setting:
61
+ return None
62
+ if encryption_setting is True:
63
+ key_base64 = os.environ.get(env_key_name)
64
+ if not key_base64:
65
+ raise ImproperlyConfigured(f'Backup encryption is True but {env_key_name} is not in the environment')
66
+ else:
67
+ key_base64 = encryption_setting
68
+ try:
69
+ key = base64.urlsafe_b64decode(key_base64)
70
+ except (binascii.Error, ValueError) as e:
71
+ raise ImproperlyConfigured('Backup encryption key is not valid urlsafe base64') from e
72
+ if len(key) != 32:
73
+ raise ImproperlyConfigured('Backup encryption key must decode to 32 bytes')
74
+ return key
75
+
76
+
77
+ def _new_aesgcm(key, salt):
78
+ try:
79
+ from cryptography.hazmat.primitives import hashes
80
+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM
81
+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF
82
+ except ImportError as e:
83
+ raise ImproperlyConfigured(f'Backup encryption requires the cryptography package - {INSTALL_HINT}') from e
84
+ file_key = HKDF(algorithm=hashes.SHA256(), length=32, salt=salt, info=KEY_INFO).derive(key)
85
+ return AESGCM(file_key)
86
+
87
+
88
+ def _build_header(salt):
89
+ return MAGIC + bytes((VERSION, FLAGS)) + struct.pack('>I', CHUNK_SIZE) + salt
90
+
91
+
92
+ def _nonce(counter, final):
93
+ return counter.to_bytes(11, 'big') + (b'\x01' if final else b'\x00')
94
+
95
+
96
+ def _chunk_count(plaintext_size):
97
+ # an empty file still gets one (empty) authenticated chunk
98
+ return max(1, -(-plaintext_size // CHUNK_SIZE))
99
+
100
+
101
+ def encrypted_size(plaintext_size):
102
+ return HEADER_LEN + plaintext_size + TAG_LEN * _chunk_count(plaintext_size)
103
+
104
+
105
+ def is_encrypted(filename):
106
+ with open(filename, 'rb') as f:
107
+ return f.read(len(MAGIC)) == MAGIC
108
+
109
+
110
+ def encrypt_file(source_filename, dest_filename, key):
111
+ """Encrypt source_filename to dest_filename, returning the ciphertext md5
112
+ hexdigest (what the storage backends will see and verify against)."""
113
+ salt = os.urandom(SALT_LEN)
114
+ header = _build_header(salt)
115
+ aesgcm = _new_aesgcm(key, salt)
116
+ md5 = hashlib.md5(header)
117
+ with open(source_filename, 'rb') as source, open(dest_filename, 'wb') as dest:
118
+ dest.write(header)
119
+ counter = 0
120
+ chunk = source.read(CHUNK_SIZE)
121
+ while True:
122
+ next_chunk = source.read(CHUNK_SIZE)
123
+ final = not next_chunk
124
+ encrypted = aesgcm.encrypt(_nonce(counter, final), chunk, header)
125
+ md5.update(encrypted)
126
+ dest.write(encrypted)
127
+ if final:
128
+ break
129
+ counter += 1
130
+ chunk = next_chunk
131
+ return md5.hexdigest()
132
+
133
+
134
+ def decrypt_in_place(filename, key):
135
+ """Decrypt filename over itself if it is an encrypted backup, so restore
136
+ code needs no knowledge of whether encryption was on when the backup was
137
+ made. Returns False (leaving the file untouched) for plaintext backups."""
138
+ tmp_name = filename + '.decrypt-tmp'
139
+ with open(filename, 'rb') as source:
140
+ header = source.read(HEADER_LEN)
141
+ if not header.startswith(MAGIC):
142
+ return False
143
+ if key is None:
144
+ raise ImproperlyConfigured(f'{filename} is an encrypted backup but this backup config '
145
+ f'has no encryption key')
146
+ if len(header) < HEADER_LEN or header[len(MAGIC)] != VERSION:
147
+ raise DecryptionError(f'Unsupported encrypted backup header in {filename}')
148
+ chunk_size = struct.unpack('>I', header[8:12])[0]
149
+ if chunk_size == 0:
150
+ raise DecryptionError(f'Unsupported encrypted backup header in {filename}')
151
+ aesgcm = _new_aesgcm(key, header[12:])
152
+ from cryptography.exceptions import InvalidTag
153
+ frame_size = chunk_size + TAG_LEN
154
+ try:
155
+ with open(tmp_name, 'wb') as dest:
156
+ counter = 0
157
+ frame = source.read(frame_size)
158
+ while True:
159
+ next_frame = source.read(frame_size)
160
+ final = not next_frame
161
+ try:
162
+ dest.write(aesgcm.decrypt(_nonce(counter, final), frame, header))
163
+ except InvalidTag as e:
164
+ raise DecryptionError(f'Could not decrypt {filename} - wrong encryption key '
165
+ f'or corrupted/truncated backup file') from e
166
+ if final:
167
+ break
168
+ counter += 1
169
+ frame = next_frame
170
+ except BaseException:
171
+ if os.path.exists(tmp_name):
172
+ os.remove(tmp_name)
173
+ raise
174
+ os.replace(tmp_name, filename)
175
+ return True
176
+
177
+
178
+ class EncryptingReader(io.RawIOBase):
179
+ """Read-only file-like wrapper that encrypts a seekable source stream on
180
+ the fly, so file backups upload without a ciphertext temp file. Seekable:
181
+ length probes (seek to end) are answered arithmetically, and backward
182
+ seeks rewind the source and re-encrypt forward - the salt is fixed at
183
+ construction so the ciphertext is reproducible."""
184
+
185
+ def __init__(self, stream, plaintext_size, key, logger=None):
186
+ self.stream = stream
187
+ self.plaintext_size = plaintext_size
188
+ self.chunks = _chunk_count(plaintext_size)
189
+ self.total_size = encrypted_size(plaintext_size)
190
+ self.salt = os.urandom(SALT_LEN)
191
+ self.header = _build_header(self.salt)
192
+ self.aesgcm = _new_aesgcm(key, self.salt)
193
+ self.logger = logger
194
+ self.restarts = 0
195
+ self._restart()
196
+
197
+ def _restart(self):
198
+ self.stream.seek(0)
199
+ self.buffer = self.header
200
+ self.chunk_index = 0
201
+ self.position = 0
202
+
203
+ def _read_source(self, size):
204
+ data = b''
205
+ while len(data) < size:
206
+ block = self.stream.read(size - len(data))
207
+ if not block:
208
+ raise IOError('Source file shrank while being encrypted for backup')
209
+ data += block
210
+ return data
211
+
212
+ def _encrypt_next_chunk(self):
213
+ final = self.chunk_index == self.chunks - 1
214
+ size = self.plaintext_size - CHUNK_SIZE * (self.chunks - 1) if final else CHUNK_SIZE
215
+ encrypted = self.aesgcm.encrypt(_nonce(self.chunk_index, final), self._read_source(size), self.header)
216
+ self.chunk_index += 1
217
+ return encrypted
218
+
219
+ def readable(self):
220
+ return True
221
+
222
+ def seekable(self):
223
+ return True
224
+
225
+ def tell(self):
226
+ return self.position
227
+
228
+ def read(self, size=-1):
229
+ if size is None or size < 0:
230
+ size = self.total_size - self.position
231
+ while len(self.buffer) < size and self.chunk_index < self.chunks:
232
+ self.buffer += self._encrypt_next_chunk()
233
+ data = self.buffer[:size]
234
+ self.buffer = self.buffer[len(data):]
235
+ self.position += len(data)
236
+ return data
237
+
238
+ def readinto(self, b):
239
+ data = self.read(len(b))
240
+ b[:len(data)] = data
241
+ return len(data)
242
+
243
+ def seek(self, offset, whence=io.SEEK_SET):
244
+ if whence == io.SEEK_SET:
245
+ target = offset
246
+ elif whence == io.SEEK_CUR:
247
+ target = self.position + offset
248
+ elif whence == io.SEEK_END:
249
+ target = self.total_size + offset
250
+ else:
251
+ raise ValueError(f'invalid whence ({whence})')
252
+ if target == self.total_size:
253
+ # a length probe - jump to the end without encrypting anything
254
+ self.buffer = b''
255
+ self.chunk_index = self.chunks
256
+ self.position = target
257
+ return target
258
+ if target < self.position:
259
+ self._restart()
260
+ self.restarts += 1
261
+ if self.logger and self.restarts == 3:
262
+ self.logger.warning('Backup upload is repeatedly seeking backwards through an encrypting '
263
+ 'stream, which re-encrypts from the start each time')
264
+ while self.position < target:
265
+ if not self.read(min(CHUNK_SIZE, target - self.position)):
266
+ break
267
+ return self.position