fscryptography 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.
- fscryptography/__init__.py +41 -0
- fscryptography/_directory.py +99 -0
- fscryptography/_filesystem.py +671 -0
- fscryptography/_journal.py +493 -0
- fscryptography/_master_key.py +294 -0
- fscryptography/crypto.py +89 -0
- fscryptography/errors.py +52 -0
- fscryptography/file_format.py +178 -0
- fscryptography/names/__init__.py +16 -0
- fscryptography/names/codec.py +116 -0
- fscryptography/names/tink_backend.py +28 -0
- fscryptography/names/validation.py +84 -0
- fscryptography/py.typed +0 -0
- fscryptography-0.1.0.dist-info/METADATA +168 -0
- fscryptography-0.1.0.dist-info/RECORD +18 -0
- fscryptography-0.1.0.dist-info/WHEEL +5 -0
- fscryptography-0.1.0.dist-info/licenses/LICENSE +25 -0
- fscryptography-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,671 @@
|
|
|
1
|
+
"""Filesystem operations backed by a Manager's reusable Tink primitives."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ctypes
|
|
6
|
+
import errno
|
|
7
|
+
import os
|
|
8
|
+
import stat
|
|
9
|
+
import struct
|
|
10
|
+
import sys
|
|
11
|
+
import tempfile
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import BinaryIO
|
|
14
|
+
|
|
15
|
+
from .errors import (
|
|
16
|
+
AtomicOperationError,
|
|
17
|
+
AuthenticationError,
|
|
18
|
+
BackendError,
|
|
19
|
+
DestinationConflictError,
|
|
20
|
+
FormatError,
|
|
21
|
+
InvalidPathError,
|
|
22
|
+
UnsupportedResourceError,
|
|
23
|
+
)
|
|
24
|
+
from .file_format import (
|
|
25
|
+
FIXED_HEADER_SIZE,
|
|
26
|
+
MAX_HEADER_SIZE,
|
|
27
|
+
build_header,
|
|
28
|
+
parse_header,
|
|
29
|
+
split_extension,
|
|
30
|
+
)
|
|
31
|
+
from .names import NameProfile, decrypt_name, encrypt_name, validate_name
|
|
32
|
+
from ._journal import Transaction
|
|
33
|
+
from ._directory import DirectoryAnchor, _renameat2
|
|
34
|
+
|
|
35
|
+
_CHUNK_SIZE = 1024 * 1024
|
|
36
|
+
_AT_FDCWD = -100
|
|
37
|
+
_RENAME_NOREPLACE = 1
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class _NonClosing:
|
|
41
|
+
"""Delegate binary I/O while keeping ownership with the caller."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, stream: BinaryIO) -> None:
|
|
44
|
+
self._stream = stream
|
|
45
|
+
|
|
46
|
+
def read(self, size: int = -1):
|
|
47
|
+
return self._stream.read(size)
|
|
48
|
+
|
|
49
|
+
def write(self, data: bytes):
|
|
50
|
+
return self._stream.write(data)
|
|
51
|
+
|
|
52
|
+
def flush(self):
|
|
53
|
+
return self._stream.flush()
|
|
54
|
+
|
|
55
|
+
def readable(self):
|
|
56
|
+
return self._stream.readable()
|
|
57
|
+
|
|
58
|
+
def writable(self):
|
|
59
|
+
return self._stream.writable()
|
|
60
|
+
|
|
61
|
+
def seekable(self):
|
|
62
|
+
return self._stream.seekable()
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def closed(self):
|
|
66
|
+
return self._stream.closed
|
|
67
|
+
|
|
68
|
+
def close(self):
|
|
69
|
+
self._stream.flush()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _profile() -> NameProfile:
|
|
73
|
+
if os.name == "nt":
|
|
74
|
+
return NameProfile.WINDOWS
|
|
75
|
+
if sys.platform.startswith("linux"):
|
|
76
|
+
return NameProfile.GNU_LINUX
|
|
77
|
+
raise UnsupportedResourceError("only Windows and GNU/Linux are supported")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _component_limit(parent: Path) -> int:
|
|
81
|
+
if os.name == "nt":
|
|
82
|
+
return 255
|
|
83
|
+
try:
|
|
84
|
+
value = os.pathconf(parent, "PC_NAME_MAX")
|
|
85
|
+
except (AttributeError, OSError, ValueError):
|
|
86
|
+
value = 255
|
|
87
|
+
return int(value) if isinstance(value, int) and value > 0 else 255
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _path(value: str | os.PathLike[str]) -> Path:
|
|
91
|
+
if not isinstance(value, (str, os.PathLike)):
|
|
92
|
+
raise TypeError("path must be str or os.PathLike")
|
|
93
|
+
result = Path(os.path.abspath(os.fspath(value)))
|
|
94
|
+
if result.name in {"", ".", ".."}:
|
|
95
|
+
raise InvalidPathError("path must identify a filesystem resource")
|
|
96
|
+
return result
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _validate_component(name: str, parent: Path) -> None:
|
|
100
|
+
validate_name(
|
|
101
|
+
name,
|
|
102
|
+
profile=_profile(),
|
|
103
|
+
max_component_bytes=_component_limit(parent),
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _publish_noreplace(source: Path, destination: Path) -> None:
|
|
108
|
+
"""Atomically rename within one filesystem without replacing a destination."""
|
|
109
|
+
# Transaction results live in a private sibling directory on the same filesystem.
|
|
110
|
+
if os.name == "nt":
|
|
111
|
+
try:
|
|
112
|
+
os.rename(source, destination)
|
|
113
|
+
return
|
|
114
|
+
except FileExistsError as exc:
|
|
115
|
+
raise DestinationConflictError("destination already exists") from exc
|
|
116
|
+
except OSError as exc:
|
|
117
|
+
raise AtomicOperationError("Windows no-replace publication failed") from exc
|
|
118
|
+
|
|
119
|
+
if sys.platform.startswith("linux"):
|
|
120
|
+
try:
|
|
121
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
122
|
+
renameat2 = libc.renameat2
|
|
123
|
+
except (AttributeError, OSError) as exc:
|
|
124
|
+
raise AtomicOperationError("renameat2(RENAME_NOREPLACE) is unavailable") from exc
|
|
125
|
+
renameat2.argtypes = (
|
|
126
|
+
ctypes.c_int,
|
|
127
|
+
ctypes.c_char_p,
|
|
128
|
+
ctypes.c_int,
|
|
129
|
+
ctypes.c_char_p,
|
|
130
|
+
ctypes.c_uint,
|
|
131
|
+
)
|
|
132
|
+
renameat2.restype = ctypes.c_int
|
|
133
|
+
result = renameat2(
|
|
134
|
+
_AT_FDCWD,
|
|
135
|
+
os.fsencode(source),
|
|
136
|
+
_AT_FDCWD,
|
|
137
|
+
os.fsencode(destination),
|
|
138
|
+
_RENAME_NOREPLACE,
|
|
139
|
+
)
|
|
140
|
+
if result == 0:
|
|
141
|
+
return
|
|
142
|
+
error = ctypes.get_errno()
|
|
143
|
+
if error == errno.EEXIST:
|
|
144
|
+
raise DestinationConflictError("destination already exists")
|
|
145
|
+
if error in {errno.ENOSYS, errno.EINVAL, errno.EOPNOTSUPP}:
|
|
146
|
+
raise AtomicOperationError(
|
|
147
|
+
f"Linux no-replace publication is unsupported: {os.strerror(error)}"
|
|
148
|
+
) from OSError(error, os.strerror(error))
|
|
149
|
+
raise OSError(error, os.strerror(error), str(destination))
|
|
150
|
+
|
|
151
|
+
raise AtomicOperationError("no verified no-replace primitive for this platform")
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _check_source(path: Path, *, directory: bool) -> os.stat_result:
|
|
155
|
+
try:
|
|
156
|
+
info = path.lstat()
|
|
157
|
+
except OSError:
|
|
158
|
+
raise
|
|
159
|
+
if stat.S_ISLNK(info.st_mode):
|
|
160
|
+
raise UnsupportedResourceError("symbolic links are not supported")
|
|
161
|
+
if directory and not stat.S_ISDIR(info.st_mode):
|
|
162
|
+
raise UnsupportedResourceError("resource is not a directory")
|
|
163
|
+
if not directory and not stat.S_ISREG(info.st_mode):
|
|
164
|
+
raise UnsupportedResourceError("resource is not a regular file")
|
|
165
|
+
return info
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _open_source(path: Path, expected: os.stat_result) -> BinaryIO:
|
|
169
|
+
"""Open the previously inspected regular file without following symlinks.
|
|
170
|
+
|
|
171
|
+
O_NOFOLLOW closes the lstat/open symlink substitution window on Linux.
|
|
172
|
+
The descriptor identity is checked again after open on every platform.
|
|
173
|
+
The returned stream owns the descriptor.
|
|
174
|
+
"""
|
|
175
|
+
flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0)
|
|
176
|
+
descriptor = os.open(path, flags)
|
|
177
|
+
try:
|
|
178
|
+
current = os.fstat(descriptor)
|
|
179
|
+
if not stat.S_ISREG(current.st_mode):
|
|
180
|
+
raise UnsupportedResourceError("resource is not a regular file")
|
|
181
|
+
if (current.st_dev, current.st_ino) != (expected.st_dev, expected.st_ino):
|
|
182
|
+
raise InvalidPathError("source changed while the operation was starting")
|
|
183
|
+
return os.fdopen(descriptor, "rb")
|
|
184
|
+
except BaseException:
|
|
185
|
+
os.close(descriptor)
|
|
186
|
+
raise
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _check_source_at(anchor: DirectoryAnchor, name: str, *, directory: bool) -> os.stat_result:
|
|
192
|
+
info = anchor.stat(name)
|
|
193
|
+
if stat.S_ISLNK(info.st_mode):
|
|
194
|
+
raise UnsupportedResourceError("symbolic links are not supported")
|
|
195
|
+
if directory and not stat.S_ISDIR(info.st_mode):
|
|
196
|
+
raise UnsupportedResourceError("resource is not a directory")
|
|
197
|
+
if not directory and not stat.S_ISREG(info.st_mode):
|
|
198
|
+
raise UnsupportedResourceError("resource is not a regular file")
|
|
199
|
+
return info
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _open_source_at(anchor: DirectoryAnchor, name: str, expected: os.stat_result) -> BinaryIO:
|
|
203
|
+
descriptor = anchor.open(name, os.O_RDONLY | getattr(os, "O_BINARY", 0))
|
|
204
|
+
try:
|
|
205
|
+
current = os.fstat(descriptor)
|
|
206
|
+
if not stat.S_ISREG(current.st_mode):
|
|
207
|
+
raise UnsupportedResourceError("resource is not a regular file")
|
|
208
|
+
if (current.st_dev, current.st_ino) != (expected.st_dev, expected.st_ino):
|
|
209
|
+
raise InvalidPathError("source changed while the operation was starting")
|
|
210
|
+
return os.fdopen(descriptor, "rb")
|
|
211
|
+
except BaseException:
|
|
212
|
+
os.close(descriptor)
|
|
213
|
+
raise
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _rename_directory_checked(
|
|
217
|
+
anchor: DirectoryAnchor,
|
|
218
|
+
source_name: str,
|
|
219
|
+
destination_name: str,
|
|
220
|
+
expected: os.stat_result,
|
|
221
|
+
) -> None:
|
|
222
|
+
"""Rename a directory without replacement and verify the moved identity."""
|
|
223
|
+
anchor.rename_noreplace(source_name, anchor.fd, destination_name)
|
|
224
|
+
try:
|
|
225
|
+
moved = anchor.stat(destination_name)
|
|
226
|
+
if not stat.S_ISDIR(moved.st_mode) or (moved.st_dev, moved.st_ino) != (expected.st_dev, expected.st_ino):
|
|
227
|
+
raise InvalidPathError("directory identity changed before rename")
|
|
228
|
+
anchor.sync()
|
|
229
|
+
except BaseException as exc:
|
|
230
|
+
try:
|
|
231
|
+
anchor.rename_noreplace(destination_name, anchor.fd, source_name)
|
|
232
|
+
anchor.sync()
|
|
233
|
+
except BaseException as restore_error:
|
|
234
|
+
raise AtomicOperationError(
|
|
235
|
+
"directory identity changed during rename; the moved entry could not be restored safely"
|
|
236
|
+
) from restore_error
|
|
237
|
+
if isinstance(exc, InvalidPathError):
|
|
238
|
+
raise
|
|
239
|
+
raise AtomicOperationError("directory rename failed verification; original entry was restored") from exc
|
|
240
|
+
|
|
241
|
+
def _read_exact(stream: BinaryIO, size: int) -> bytes:
|
|
242
|
+
chunks = bytearray()
|
|
243
|
+
while len(chunks) < size:
|
|
244
|
+
part = stream.read(size - len(chunks))
|
|
245
|
+
if not part:
|
|
246
|
+
raise FormatError("file header is truncated")
|
|
247
|
+
chunks.extend(part)
|
|
248
|
+
return bytes(chunks)
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _read_header(stream: BinaryIO):
|
|
252
|
+
fixed = _read_exact(stream, FIXED_HEADER_SIZE)
|
|
253
|
+
header_length = struct.unpack_from(">I", fixed, 12)[0]
|
|
254
|
+
if header_length < FIXED_HEADER_SIZE or header_length > MAX_HEADER_SIZE:
|
|
255
|
+
raise FormatError("file header length is outside supported limits")
|
|
256
|
+
return parse_header(fixed + _read_exact(stream, header_length - FIXED_HEADER_SIZE))
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _copy_encrypt(primitive, source: BinaryIO, destination: BinaryIO, aad: bytes) -> None:
|
|
260
|
+
try:
|
|
261
|
+
with primitive.new_encrypting_stream(_NonClosing(destination), aad) as encrypted:
|
|
262
|
+
while True:
|
|
263
|
+
chunk = source.read(_CHUNK_SIZE)
|
|
264
|
+
if not chunk:
|
|
265
|
+
break
|
|
266
|
+
encrypted.write(chunk)
|
|
267
|
+
except OSError:
|
|
268
|
+
raise
|
|
269
|
+
except Exception as exc:
|
|
270
|
+
raise BackendError("Tink Streaming AEAD encryption failed") from exc
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _copy_decrypt(primitive, source: BinaryIO, destination: BinaryIO, aad: bytes) -> None:
|
|
274
|
+
try:
|
|
275
|
+
with primitive.new_decrypting_stream(_NonClosing(source), aad) as decrypted:
|
|
276
|
+
while True:
|
|
277
|
+
chunk = decrypted.read(_CHUNK_SIZE)
|
|
278
|
+
if not chunk:
|
|
279
|
+
break
|
|
280
|
+
destination.write(chunk)
|
|
281
|
+
except OSError:
|
|
282
|
+
raise
|
|
283
|
+
except Exception as exc:
|
|
284
|
+
raise AuthenticationError("file content authentication failed") from exc
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _temporary_file(parent: Path) -> tuple[int, Path]:
|
|
288
|
+
fd, name = tempfile.mkstemp(prefix=".fscryptography-", dir=parent)
|
|
289
|
+
return fd, Path(name)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _sync_close(stream: BinaryIO) -> None:
|
|
293
|
+
stream.flush()
|
|
294
|
+
os.fsync(stream.fileno())
|
|
295
|
+
stream.close()
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def _sync_parent_directory(parent: Path) -> None:
|
|
299
|
+
"""Persist namespace changes where directory fsync is supported.
|
|
300
|
+
|
|
301
|
+
Windows currently relies on the platform's rename semantics and does not
|
|
302
|
+
claim crash-durable directory-entry updates through this helper.
|
|
303
|
+
"""
|
|
304
|
+
if os.name == "nt":
|
|
305
|
+
return
|
|
306
|
+
if not sys.platform.startswith("linux"):
|
|
307
|
+
raise AtomicOperationError("directory synchronization is unsupported on this platform")
|
|
308
|
+
flags = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0)
|
|
309
|
+
try:
|
|
310
|
+
descriptor = os.open(parent, flags)
|
|
311
|
+
try:
|
|
312
|
+
os.fsync(descriptor)
|
|
313
|
+
finally:
|
|
314
|
+
os.close(descriptor)
|
|
315
|
+
except OSError as exc:
|
|
316
|
+
raise AtomicOperationError(
|
|
317
|
+
"filesystem namespace update could not be synchronized"
|
|
318
|
+
) from exc
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def _retire_source(
|
|
322
|
+
source_path: Path,
|
|
323
|
+
transaction: Transaction,
|
|
324
|
+
expected: os.stat_result,
|
|
325
|
+
anchor: DirectoryAnchor | None,
|
|
326
|
+
*,
|
|
327
|
+
output_kind: str,
|
|
328
|
+
) -> None:
|
|
329
|
+
"""Move the expected source into private transaction storage before unlinking.
|
|
330
|
+
|
|
331
|
+
The quarantine entry is deliberately inside the journaled transaction
|
|
332
|
+
directory, so an interrupted retirement remains visible to recovery
|
|
333
|
+
inspection. The identity check is performed after the atomic rename.
|
|
334
|
+
"""
|
|
335
|
+
if anchor is None:
|
|
336
|
+
# Transaction directories currently inherit the parent's Windows ACL.
|
|
337
|
+
# Until an explicit private ACL is installed, do not treat that location
|
|
338
|
+
# as a protected quarantine; retain the previous identity-check behavior.
|
|
339
|
+
current = source_path.lstat()
|
|
340
|
+
if (current.st_dev, current.st_ino) != (expected.st_dev, expected.st_ino):
|
|
341
|
+
raise AtomicOperationError(
|
|
342
|
+
"source changed before removal; published output and source were preserved"
|
|
343
|
+
)
|
|
344
|
+
try:
|
|
345
|
+
source_path.unlink()
|
|
346
|
+
_sync_parent_directory(source_path.parent)
|
|
347
|
+
transaction.set_state("source_removed")
|
|
348
|
+
return
|
|
349
|
+
except Exception as exc:
|
|
350
|
+
if not source_path.exists():
|
|
351
|
+
raise AtomicOperationError(
|
|
352
|
+
"source was removed, but the namespace update could not be synchronized"
|
|
353
|
+
) from exc
|
|
354
|
+
raise AtomicOperationError(
|
|
355
|
+
f"{output_kind} was published but source removal failed"
|
|
356
|
+
) from exc
|
|
357
|
+
|
|
358
|
+
try:
|
|
359
|
+
if transaction.directory_fd is None:
|
|
360
|
+
raise RuntimeError("anchored source retirement requires a transaction directory descriptor")
|
|
361
|
+
anchor.rename_noreplace(source_path.name, transaction.directory_fd, "source")
|
|
362
|
+
except Exception as exc:
|
|
363
|
+
raise AtomicOperationError(
|
|
364
|
+
f"{output_kind} was published but the source could not be retained safely"
|
|
365
|
+
) from exc
|
|
366
|
+
|
|
367
|
+
try:
|
|
368
|
+
current = os.stat("source", dir_fd=transaction.directory_fd, follow_symlinks=False)
|
|
369
|
+
if (
|
|
370
|
+
not stat.S_ISREG(current.st_mode)
|
|
371
|
+
or (current.st_dev, current.st_ino) != (expected.st_dev, expected.st_ino)
|
|
372
|
+
):
|
|
373
|
+
try:
|
|
374
|
+
_renameat2(transaction.directory_fd, "source", anchor.fd, source_path.name)
|
|
375
|
+
anchor.sync()
|
|
376
|
+
os.fsync(transaction.directory_fd)
|
|
377
|
+
except Exception as restore_error:
|
|
378
|
+
raise AtomicOperationError(
|
|
379
|
+
"source identity changed; the unexpected entry remains in transaction storage "
|
|
380
|
+
"for explicit recovery inspection"
|
|
381
|
+
) from restore_error
|
|
382
|
+
raise AtomicOperationError(
|
|
383
|
+
"source identity changed before retirement; the unexpected source entry was restored"
|
|
384
|
+
)
|
|
385
|
+
|
|
386
|
+
# Persist both sides of the cross-directory rename before recording the
|
|
387
|
+
# retained state. A crash from this point is inspectable via txn/source.
|
|
388
|
+
anchor.sync()
|
|
389
|
+
os.fsync(transaction.directory_fd)
|
|
390
|
+
transaction.set_state("source_retained")
|
|
391
|
+
|
|
392
|
+
transaction.unlink_retained()
|
|
393
|
+
try:
|
|
394
|
+
os.fsync(transaction.directory_fd)
|
|
395
|
+
except OSError as exc:
|
|
396
|
+
raise AtomicOperationError(
|
|
397
|
+
"source was removed, but transaction storage could not be synchronized"
|
|
398
|
+
) from exc
|
|
399
|
+
transaction.set_state("source_removed")
|
|
400
|
+
except AtomicOperationError:
|
|
401
|
+
raise
|
|
402
|
+
except Exception as exc:
|
|
403
|
+
raise AtomicOperationError(
|
|
404
|
+
"published output remains available; source retirement is incomplete and requires inspection"
|
|
405
|
+
) from exc
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
class _FileOperations:
|
|
409
|
+
def __init__(self, manager) -> None:
|
|
410
|
+
self._manager = manager
|
|
411
|
+
|
|
412
|
+
def encrypt(
|
|
413
|
+
self,
|
|
414
|
+
path: str | os.PathLike[str],
|
|
415
|
+
*,
|
|
416
|
+
new_extension: str | None = None,
|
|
417
|
+
encrypt_name: bool = False,
|
|
418
|
+
) -> None:
|
|
419
|
+
self._manager._require_open()
|
|
420
|
+
source_path = _path(path)
|
|
421
|
+
anchor = DirectoryAnchor(source_path.parent) if sys.platform.startswith("linux") else None
|
|
422
|
+
try:
|
|
423
|
+
source_info = (_check_source_at(anchor, source_path.name, directory=False) if anchor is not None
|
|
424
|
+
else _check_source(source_path, directory=False))
|
|
425
|
+
profile = _profile()
|
|
426
|
+
limit = _component_limit(source_path.parent)
|
|
427
|
+
original_name = source_path.name
|
|
428
|
+
base, original_extension = split_extension(original_name)
|
|
429
|
+
|
|
430
|
+
if not isinstance(encrypt_name, bool):
|
|
431
|
+
raise TypeError("encrypt_name must be bool")
|
|
432
|
+
if encrypt_name:
|
|
433
|
+
if new_extension is not None:
|
|
434
|
+
raise ValueError("new_extension cannot be used when encrypt_name=True")
|
|
435
|
+
output_extension = None
|
|
436
|
+
destination_name = encrypt_name_fn(
|
|
437
|
+
original_name, self._manager._names_primitive, profile, limit
|
|
438
|
+
)
|
|
439
|
+
else:
|
|
440
|
+
output_extension = ".fscrypt" if new_extension is None else new_extension
|
|
441
|
+
# build_header performs strict structural validation; validate the
|
|
442
|
+
# complete destination component against the active filesystem too.
|
|
443
|
+
destination_name = base + output_extension
|
|
444
|
+
_validate_component(destination_name, source_path.parent)
|
|
445
|
+
|
|
446
|
+
if encrypt_name:
|
|
447
|
+
_validate_component(destination_name, source_path.parent)
|
|
448
|
+
header = build_header(
|
|
449
|
+
original_extension=None if encrypt_name else original_extension,
|
|
450
|
+
output_extension=output_extension,
|
|
451
|
+
encrypted_name=encrypt_name,
|
|
452
|
+
)
|
|
453
|
+
destination = source_path.with_name(destination_name)
|
|
454
|
+
if destination == source_path:
|
|
455
|
+
raise ValueError("encrypted destination must differ from the source path")
|
|
456
|
+
|
|
457
|
+
transaction = Transaction.begin(
|
|
458
|
+
source_path.parent, "file_encrypt", source_path.name, destination.name, source_info,
|
|
459
|
+
parent_fd=anchor.fd if anchor is not None else None,
|
|
460
|
+
)
|
|
461
|
+
|
|
462
|
+
except BaseException:
|
|
463
|
+
if anchor is not None:
|
|
464
|
+
anchor.close()
|
|
465
|
+
raise
|
|
466
|
+
temporary = transaction.result_path if anchor is None else None
|
|
467
|
+
output = None
|
|
468
|
+
published = False
|
|
469
|
+
try:
|
|
470
|
+
output = os.fdopen(transaction.open_result(), "wb")
|
|
471
|
+
with (_open_source_at(anchor, source_path.name, source_info) if anchor is not None else _open_source(source_path, source_info)) as original:
|
|
472
|
+
output.write(header)
|
|
473
|
+
_copy_encrypt(
|
|
474
|
+
self._manager._content_primitive,
|
|
475
|
+
original,
|
|
476
|
+
output,
|
|
477
|
+
header,
|
|
478
|
+
)
|
|
479
|
+
_sync_close(output)
|
|
480
|
+
transaction.set_result_ready(transaction.stat_result())
|
|
481
|
+
if anchor is not None:
|
|
482
|
+
transaction.rename_result_to(anchor.fd, destination.name)
|
|
483
|
+
anchor.sync()
|
|
484
|
+
else:
|
|
485
|
+
_publish_noreplace(temporary, destination)
|
|
486
|
+
_sync_parent_directory(source_path.parent)
|
|
487
|
+
published = True
|
|
488
|
+
transaction.set_state("published")
|
|
489
|
+
_retire_source(
|
|
490
|
+
source_path,
|
|
491
|
+
transaction,
|
|
492
|
+
source_info,
|
|
493
|
+
anchor,
|
|
494
|
+
output_kind="encrypted output",
|
|
495
|
+
)
|
|
496
|
+
transaction.set_state("complete")
|
|
497
|
+
transaction.finish()
|
|
498
|
+
finally:
|
|
499
|
+
if output is not None and not output.closed:
|
|
500
|
+
output.close()
|
|
501
|
+
transaction.close()
|
|
502
|
+
if anchor is not None:
|
|
503
|
+
anchor.close()
|
|
504
|
+
# An unpublished result is retained for explicit inspection.
|
|
505
|
+
|
|
506
|
+
def decrypt(self, path: str | os.PathLike[str]) -> None:
|
|
507
|
+
self._manager._require_open()
|
|
508
|
+
source_path = _path(path)
|
|
509
|
+
anchor = DirectoryAnchor(source_path.parent) if sys.platform.startswith("linux") else None
|
|
510
|
+
try:
|
|
511
|
+
source_info = (_check_source_at(anchor, source_path.name, directory=False) if anchor is not None
|
|
512
|
+
else _check_source(source_path, directory=False))
|
|
513
|
+
profile = _profile()
|
|
514
|
+
limit = _component_limit(source_path.parent)
|
|
515
|
+
|
|
516
|
+
except BaseException:
|
|
517
|
+
if anchor is not None:
|
|
518
|
+
anchor.close()
|
|
519
|
+
raise
|
|
520
|
+
transaction = None
|
|
521
|
+
output = None
|
|
522
|
+
published = False
|
|
523
|
+
try:
|
|
524
|
+
with (_open_source_at(anchor, source_path.name, source_info) if anchor is not None else _open_source(source_path, source_info)) as encrypted:
|
|
525
|
+
header = _read_header(encrypted)
|
|
526
|
+
if header.encrypted_name:
|
|
527
|
+
destination_name = decrypt_name(
|
|
528
|
+
source_path.name,
|
|
529
|
+
self._manager._names_primitive,
|
|
530
|
+
profile=profile,
|
|
531
|
+
max_component_bytes=limit,
|
|
532
|
+
)
|
|
533
|
+
else:
|
|
534
|
+
output_extension = header.output_extension or ""
|
|
535
|
+
if output_extension and not source_path.name.endswith(output_extension):
|
|
536
|
+
raise FormatError("current filename does not match authenticated output extension")
|
|
537
|
+
base = source_path.name[:-len(output_extension)] if output_extension else source_path.name
|
|
538
|
+
destination_name = base + (header.original_extension or "")
|
|
539
|
+
_validate_component(destination_name, source_path.parent)
|
|
540
|
+
|
|
541
|
+
destination = source_path.with_name(destination_name)
|
|
542
|
+
if destination == source_path:
|
|
543
|
+
raise ValueError("decrypted destination must differ from the source path")
|
|
544
|
+
transaction = Transaction.begin(
|
|
545
|
+
source_path.parent, "file_decrypt", source_path.name, destination.name, source_info,
|
|
546
|
+
parent_fd=anchor.fd if anchor is not None else None,
|
|
547
|
+
)
|
|
548
|
+
fd = (os.open("result", os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600, dir_fd=transaction.directory_fd)
|
|
549
|
+
if transaction.directory_fd is not None else
|
|
550
|
+
os.open(transaction.result_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600))
|
|
551
|
+
output = os.fdopen(fd, "wb")
|
|
552
|
+
_copy_decrypt(
|
|
553
|
+
self._manager._content_primitive,
|
|
554
|
+
encrypted,
|
|
555
|
+
output,
|
|
556
|
+
header.raw,
|
|
557
|
+
)
|
|
558
|
+
_sync_close(output)
|
|
559
|
+
transaction.set_result_ready(transaction.stat_result())
|
|
560
|
+
if anchor is not None:
|
|
561
|
+
transaction.rename_result_to(anchor.fd, destination.name)
|
|
562
|
+
anchor.sync()
|
|
563
|
+
os.fsync(transaction.directory_fd)
|
|
564
|
+
else:
|
|
565
|
+
_publish_noreplace(transaction.result_path, destination)
|
|
566
|
+
_sync_parent_directory(source_path.parent)
|
|
567
|
+
_sync_parent_directory(transaction.directory)
|
|
568
|
+
published = True
|
|
569
|
+
transaction.set_state("published")
|
|
570
|
+
_retire_source(
|
|
571
|
+
source_path,
|
|
572
|
+
transaction,
|
|
573
|
+
source_info,
|
|
574
|
+
anchor,
|
|
575
|
+
output_kind="plaintext",
|
|
576
|
+
)
|
|
577
|
+
transaction.set_state("complete")
|
|
578
|
+
transaction.finish()
|
|
579
|
+
finally:
|
|
580
|
+
if output is not None and not output.closed:
|
|
581
|
+
output.close()
|
|
582
|
+
if transaction is not None:
|
|
583
|
+
transaction.close()
|
|
584
|
+
if anchor is not None:
|
|
585
|
+
anchor.close()
|
|
586
|
+
# Unpublished output is retained for explicit inspection.
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
class _DirectoryOperations:
|
|
590
|
+
def __init__(self, manager) -> None:
|
|
591
|
+
self._manager = manager
|
|
592
|
+
|
|
593
|
+
def encrypt(self, path: str | os.PathLike[str]) -> None:
|
|
594
|
+
self._manager._require_open()
|
|
595
|
+
source = _path(path)
|
|
596
|
+
anchor = DirectoryAnchor(source.parent) if sys.platform.startswith("linux") else None
|
|
597
|
+
transaction = None
|
|
598
|
+
try:
|
|
599
|
+
source_info = (_check_source_at(anchor, source.name, directory=True) if anchor is not None
|
|
600
|
+
else _check_source(source, directory=True))
|
|
601
|
+
destination_name = encrypt_name_fn(
|
|
602
|
+
source.name,
|
|
603
|
+
self._manager._names_primitive,
|
|
604
|
+
_profile(),
|
|
605
|
+
_component_limit(source.parent),
|
|
606
|
+
)
|
|
607
|
+
_validate_component(destination_name, source.parent)
|
|
608
|
+
destination = source.with_name(destination_name)
|
|
609
|
+
transaction = Transaction.begin(
|
|
610
|
+
source.parent, "dir_encrypt", source.name, destination.name, source_info,
|
|
611
|
+
parent_fd=anchor.fd if anchor is not None else None,
|
|
612
|
+
)
|
|
613
|
+
if anchor is not None:
|
|
614
|
+
_rename_directory_checked(anchor, source.name, destination.name, source_info)
|
|
615
|
+
else:
|
|
616
|
+
_publish_noreplace(source, destination)
|
|
617
|
+
_sync_parent_directory(source.parent)
|
|
618
|
+
transaction.set_state("published")
|
|
619
|
+
transaction.set_state("source_removed")
|
|
620
|
+
transaction.set_state("complete")
|
|
621
|
+
transaction.finish()
|
|
622
|
+
finally:
|
|
623
|
+
if transaction is not None:
|
|
624
|
+
transaction.close()
|
|
625
|
+
if anchor is not None:
|
|
626
|
+
anchor.close()
|
|
627
|
+
|
|
628
|
+
def decrypt(self, path: str | os.PathLike[str]) -> None:
|
|
629
|
+
self._manager._require_open()
|
|
630
|
+
source = _path(path)
|
|
631
|
+
anchor = DirectoryAnchor(source.parent) if sys.platform.startswith("linux") else None
|
|
632
|
+
transaction = None
|
|
633
|
+
try:
|
|
634
|
+
source_info = (_check_source_at(anchor, source.name, directory=True) if anchor is not None
|
|
635
|
+
else _check_source(source, directory=True))
|
|
636
|
+
destination_name = decrypt_name(
|
|
637
|
+
source.name,
|
|
638
|
+
self._manager._names_primitive,
|
|
639
|
+
profile=_profile(),
|
|
640
|
+
max_component_bytes=_component_limit(source.parent),
|
|
641
|
+
)
|
|
642
|
+
_validate_component(destination_name, source.parent)
|
|
643
|
+
destination = source.with_name(destination_name)
|
|
644
|
+
transaction = Transaction.begin(
|
|
645
|
+
source.parent, "dir_decrypt", source.name, destination.name, source_info,
|
|
646
|
+
parent_fd=anchor.fd if anchor is not None else None,
|
|
647
|
+
)
|
|
648
|
+
if anchor is not None:
|
|
649
|
+
anchor.rename_noreplace(source.name, anchor.fd, destination.name)
|
|
650
|
+
anchor.sync()
|
|
651
|
+
else:
|
|
652
|
+
_publish_noreplace(source, destination)
|
|
653
|
+
_sync_parent_directory(source.parent)
|
|
654
|
+
transaction.set_state("published")
|
|
655
|
+
transaction.set_state("source_removed")
|
|
656
|
+
transaction.set_state("complete")
|
|
657
|
+
transaction.finish()
|
|
658
|
+
finally:
|
|
659
|
+
if transaction is not None:
|
|
660
|
+
transaction.close()
|
|
661
|
+
if anchor is not None:
|
|
662
|
+
anchor.close()
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
def encrypt_name_fn(name: str, primitive, profile: NameProfile, limit: int) -> str:
|
|
666
|
+
return encrypt_name(
|
|
667
|
+
name,
|
|
668
|
+
primitive,
|
|
669
|
+
profile=profile,
|
|
670
|
+
max_component_bytes=limit,
|
|
671
|
+
)
|