flat-packager 0.4.1__tar.gz → 0.4.2__tar.gz
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.
- {flat_packager-0.4.1/src/flat_packager.egg-info → flat_packager-0.4.2}/PKG-INFO +12 -2
- {flat_packager-0.4.1 → flat_packager-0.4.2}/README.md +11 -1
- {flat_packager-0.4.1 → flat_packager-0.4.2}/pyproject.toml +1 -1
- {flat_packager-0.4.1 → flat_packager-0.4.2}/src/flat_packager/__init__.py +1 -1
- {flat_packager-0.4.1 → flat_packager-0.4.2}/src/flat_packager/content.py +4 -1
- {flat_packager-0.4.1 → flat_packager-0.4.2}/src/flat_packager/unpack.py +147 -47
- {flat_packager-0.4.1 → flat_packager-0.4.2/src/flat_packager.egg-info}/PKG-INFO +12 -2
- {flat_packager-0.4.1 → flat_packager-0.4.2}/tests/test_roundtrip.py +162 -3
- {flat_packager-0.4.1 → flat_packager-0.4.2}/LICENSE +0 -0
- {flat_packager-0.4.1 → flat_packager-0.4.2}/setup.cfg +0 -0
- {flat_packager-0.4.1 → flat_packager-0.4.2}/src/flat_packager/archive.py +0 -0
- {flat_packager-0.4.1 → flat_packager-0.4.2}/src/flat_packager/inspect.py +0 -0
- {flat_packager-0.4.1 → flat_packager-0.4.2}/src/flat_packager/pack.py +0 -0
- {flat_packager-0.4.1 → flat_packager-0.4.2}/src/flat_packager/text_encoding.py +0 -0
- {flat_packager-0.4.1 → flat_packager-0.4.2}/src/flat_packager/verify.py +0 -0
- {flat_packager-0.4.1 → flat_packager-0.4.2}/src/flat_packager.egg-info/SOURCES.txt +0 -0
- {flat_packager-0.4.1 → flat_packager-0.4.2}/src/flat_packager.egg-info/dependency_links.txt +0 -0
- {flat_packager-0.4.1 → flat_packager-0.4.2}/src/flat_packager.egg-info/entry_points.txt +0 -0
- {flat_packager-0.4.1 → flat_packager-0.4.2}/src/flat_packager.egg-info/requires.txt +0 -0
- {flat_packager-0.4.1 → flat_packager-0.4.2}/src/flat_packager.egg-info/top_level.txt +0 -0
- {flat_packager-0.4.1 → flat_packager-0.4.2}/tests/test_version.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: flat-packager
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.2
|
|
4
4
|
Summary: Pack a repository into one flat text archive and restore it later.
|
|
5
5
|
Author: Thomas
|
|
6
6
|
License-Expression: MIT
|
|
@@ -219,11 +219,21 @@ The restore step rejects:
|
|
|
219
219
|
- absolute archive paths
|
|
220
220
|
- `..`, `.`, empty, or backslash path segments
|
|
221
221
|
- duplicate archive paths
|
|
222
|
-
- file or directory records nested underneath an archived symlink
|
|
222
|
+
- file or directory records nested underneath an archived symlink or file,
|
|
223
|
+
checked before anything is written for that record
|
|
224
|
+
- a symlink or file that would replace a directory other entries live in
|
|
223
225
|
- chunk records that are missing, out of order, corrupt, or attached to the
|
|
224
226
|
wrong file
|
|
225
227
|
- corrupt base64, size, or SHA-256 data
|
|
226
228
|
|
|
229
|
+
As a second layer, restores create directories one component at a time without
|
|
230
|
+
following symlinks and create files exclusively (`O_EXCL`/`O_NOFOLLOW`). Writes
|
|
231
|
+
therefore cannot be routed outside the output directory, including through
|
|
232
|
+
names that collide on case-insensitive filesystems such as default macOS.
|
|
233
|
+
|
|
234
|
+
Setuid, setgid, and sticky mode bits are stripped on restore. Pass
|
|
235
|
+
`--preserve-special-bits` to keep them for archives you trust.
|
|
236
|
+
|
|
227
237
|
Restored symlinks may still point outside the restored repository, because that
|
|
228
238
|
is valid repository content. Use `--no-symlinks` if you want symlink targets
|
|
229
239
|
written as text files instead.
|
|
@@ -188,11 +188,21 @@ The restore step rejects:
|
|
|
188
188
|
- absolute archive paths
|
|
189
189
|
- `..`, `.`, empty, or backslash path segments
|
|
190
190
|
- duplicate archive paths
|
|
191
|
-
- file or directory records nested underneath an archived symlink
|
|
191
|
+
- file or directory records nested underneath an archived symlink or file,
|
|
192
|
+
checked before anything is written for that record
|
|
193
|
+
- a symlink or file that would replace a directory other entries live in
|
|
192
194
|
- chunk records that are missing, out of order, corrupt, or attached to the
|
|
193
195
|
wrong file
|
|
194
196
|
- corrupt base64, size, or SHA-256 data
|
|
195
197
|
|
|
198
|
+
As a second layer, restores create directories one component at a time without
|
|
199
|
+
following symlinks and create files exclusively (`O_EXCL`/`O_NOFOLLOW`). Writes
|
|
200
|
+
therefore cannot be routed outside the output directory, including through
|
|
201
|
+
names that collide on case-insensitive filesystems such as default macOS.
|
|
202
|
+
|
|
203
|
+
Setuid, setgid, and sticky mode bits are stripped on restore. Pass
|
|
204
|
+
`--preserve-special-bits` to keep them for archives you trust.
|
|
205
|
+
|
|
196
206
|
Restored symlinks may still point outside the restored repository, because that
|
|
197
207
|
is valid repository content. Use `--no-symlinks` if you want symlink targets
|
|
198
208
|
written as text files instead.
|
|
@@ -28,7 +28,10 @@ def file_content_bytes(path: str, record: dict[str, Any]) -> bytes:
|
|
|
28
28
|
content = record.get("content")
|
|
29
29
|
if not isinstance(content, str):
|
|
30
30
|
raise ValueError(f"{path}: content must be a UTF-8 string")
|
|
31
|
-
|
|
31
|
+
try:
|
|
32
|
+
return content.encode("utf-8")
|
|
33
|
+
except UnicodeEncodeError as exc:
|
|
34
|
+
raise ValueError(f"{path}: content is not valid UTF-8 text") from exc
|
|
32
35
|
|
|
33
36
|
|
|
34
37
|
def validate_inline_file_record(record: dict[str, Any]) -> int:
|
|
@@ -8,6 +8,7 @@ import binascii
|
|
|
8
8
|
import hashlib
|
|
9
9
|
import os
|
|
10
10
|
import shutil
|
|
11
|
+
import stat
|
|
11
12
|
import sys
|
|
12
13
|
import tempfile
|
|
13
14
|
from dataclasses import dataclass, field
|
|
@@ -20,6 +21,11 @@ from .content import file_content_bytes, validate_inline_file_record
|
|
|
20
21
|
|
|
21
22
|
ArchiveRecord = tuple[int, dict[str, Any]]
|
|
22
23
|
|
|
24
|
+
O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)
|
|
25
|
+
O_BINARY = getattr(os, "O_BINARY", 0)
|
|
26
|
+
PERMISSION_BITS = 0o777
|
|
27
|
+
ALL_MODE_BITS = 0o7777
|
|
28
|
+
|
|
23
29
|
|
|
24
30
|
@dataclass
|
|
25
31
|
class ActiveFile:
|
|
@@ -31,6 +37,7 @@ class ActiveFile:
|
|
|
31
37
|
seen_size: int = 0
|
|
32
38
|
hasher: Any = field(default_factory=hashlib.sha256)
|
|
33
39
|
handle: Any | None = None
|
|
40
|
+
target: Path | None = None
|
|
34
41
|
mode: int | None = None
|
|
35
42
|
|
|
36
43
|
|
|
@@ -68,6 +75,14 @@ def parse_args() -> argparse.Namespace:
|
|
|
68
75
|
action="store_true",
|
|
69
76
|
help="Restore symlinks as small text files containing their target path.",
|
|
70
77
|
)
|
|
78
|
+
parser.add_argument(
|
|
79
|
+
"--preserve-special-bits",
|
|
80
|
+
action="store_true",
|
|
81
|
+
help=(
|
|
82
|
+
"Restore setuid, setgid, and sticky mode bits. By default only "
|
|
83
|
+
"read/write/execute permission bits are restored."
|
|
84
|
+
),
|
|
85
|
+
)
|
|
71
86
|
return parser.parse_args()
|
|
72
87
|
|
|
73
88
|
|
|
@@ -98,8 +113,58 @@ def safe_relative_parts(rel_path: str) -> tuple[str, ...]:
|
|
|
98
113
|
return parts
|
|
99
114
|
|
|
100
115
|
|
|
101
|
-
def
|
|
102
|
-
|
|
116
|
+
def ensure_safe_dir(root: Path, parts: tuple[str, ...]) -> Path:
|
|
117
|
+
"""Create ``root/parts`` one component at a time without following symlinks.
|
|
118
|
+
|
|
119
|
+
Every existing component must be a real directory. This keeps writes inside
|
|
120
|
+
``root`` even when an archive tries to route a path through a symlink,
|
|
121
|
+
including through case-insensitive name collisions.
|
|
122
|
+
"""
|
|
123
|
+
current = root
|
|
124
|
+
for index, part in enumerate(parts):
|
|
125
|
+
current = current / part
|
|
126
|
+
try:
|
|
127
|
+
metadata = os.lstat(current)
|
|
128
|
+
except FileNotFoundError:
|
|
129
|
+
os.mkdir(current)
|
|
130
|
+
continue
|
|
131
|
+
rel = "/".join(parts[: index + 1])
|
|
132
|
+
if stat.S_ISLNK(metadata.st_mode):
|
|
133
|
+
raise ValueError(f"{rel}: refusing to write through symlink")
|
|
134
|
+
if not stat.S_ISDIR(metadata.st_mode):
|
|
135
|
+
raise ValueError(f"{rel}: path component is not a directory")
|
|
136
|
+
return current
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def create_new_file(root: Path, rel_path: str) -> tuple[Any, Path]:
|
|
140
|
+
"""Create a new file inside ``root``; never follow or replace existing entries."""
|
|
141
|
+
parts = safe_relative_parts(rel_path)
|
|
142
|
+
parent = ensure_safe_dir(root, parts[:-1])
|
|
143
|
+
target = parent / parts[-1]
|
|
144
|
+
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | O_NOFOLLOW | O_BINARY
|
|
145
|
+
try:
|
|
146
|
+
fd = os.open(target, flags, 0o666)
|
|
147
|
+
except FileExistsError as exc:
|
|
148
|
+
raise ValueError(
|
|
149
|
+
f"{rel_path}: output path already exists (case-insensitive name collision?)"
|
|
150
|
+
) from exc
|
|
151
|
+
return os.fdopen(fd, "wb"), target
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def apply_file_mode(handle: Any, target: Path, mode: int | None) -> None:
|
|
155
|
+
if mode is None:
|
|
156
|
+
return
|
|
157
|
+
if hasattr(os, "fchmod"):
|
|
158
|
+
os.fchmod(handle.fileno(), mode)
|
|
159
|
+
else:
|
|
160
|
+
os.chmod(target, mode)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def write_new_file(root: Path, rel_path: str, content: bytes, mode: int | None) -> None:
|
|
164
|
+
handle, target = create_new_file(root, rel_path)
|
|
165
|
+
with handle:
|
|
166
|
+
handle.write(content)
|
|
167
|
+
apply_file_mode(handle, target, mode)
|
|
103
168
|
|
|
104
169
|
|
|
105
170
|
def validate_header(line_number: int, payload: dict[str, Any]) -> int:
|
|
@@ -127,9 +192,14 @@ def validate_mode(record: dict[str, Any]) -> None:
|
|
|
127
192
|
raise ValueError(f"{record.get('path')}: invalid mode {mode!r}")
|
|
128
193
|
|
|
129
194
|
|
|
130
|
-
def mode_from_record(
|
|
195
|
+
def mode_from_record(
|
|
196
|
+
record: dict[str, Any],
|
|
197
|
+
preserve_special_bits: bool = False,
|
|
198
|
+
) -> int | None:
|
|
131
199
|
mode = record.get("mode")
|
|
132
|
-
|
|
200
|
+
if not isinstance(mode, int):
|
|
201
|
+
return None
|
|
202
|
+
return mode & (ALL_MODE_BITS if preserve_special_bits else PERMISSION_BITS)
|
|
133
203
|
|
|
134
204
|
|
|
135
205
|
def decode_base64(path: str, content: Any) -> bytes:
|
|
@@ -144,6 +214,7 @@ def decode_base64(path: str, content: Any) -> bytes:
|
|
|
144
214
|
def process_inline_file(
|
|
145
215
|
record: dict[str, Any],
|
|
146
216
|
write_root: Path | None,
|
|
217
|
+
preserve_special_bits: bool = False,
|
|
147
218
|
) -> int:
|
|
148
219
|
path = record_path(record)
|
|
149
220
|
validate_mode(record)
|
|
@@ -151,12 +222,9 @@ def process_inline_file(
|
|
|
151
222
|
content = file_content_bytes(path, record)
|
|
152
223
|
|
|
153
224
|
if write_root is not None:
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
mode = mode_from_record(record)
|
|
158
|
-
if mode is not None:
|
|
159
|
-
os.chmod(target, mode)
|
|
225
|
+
write_new_file(
|
|
226
|
+
write_root, path, content, mode_from_record(record, preserve_special_bits)
|
|
227
|
+
)
|
|
160
228
|
|
|
161
229
|
return expected_size
|
|
162
230
|
|
|
@@ -164,13 +232,15 @@ def process_inline_file(
|
|
|
164
232
|
def process_file_v1(
|
|
165
233
|
record: dict[str, Any],
|
|
166
234
|
write_root: Path | None,
|
|
235
|
+
preserve_special_bits: bool = False,
|
|
167
236
|
) -> int:
|
|
168
|
-
return process_inline_file(record, write_root)
|
|
237
|
+
return process_inline_file(record, write_root, preserve_special_bits)
|
|
169
238
|
|
|
170
239
|
|
|
171
240
|
def start_active_file(
|
|
172
241
|
record: dict[str, Any],
|
|
173
242
|
write_root: Path | None,
|
|
243
|
+
preserve_special_bits: bool = False,
|
|
174
244
|
) -> ActiveFile | None:
|
|
175
245
|
path = record_path(record)
|
|
176
246
|
validate_mode(record)
|
|
@@ -187,25 +257,20 @@ def start_active_file(
|
|
|
187
257
|
if not isinstance(expected_sha256, str) or expected_sha256 == "":
|
|
188
258
|
raise ValueError(f"{path}: sha256 must be a non-empty string")
|
|
189
259
|
|
|
190
|
-
mode = mode_from_record(record)
|
|
260
|
+
mode = mode_from_record(record, preserve_special_bits)
|
|
191
261
|
if expected_chunks == 0:
|
|
192
262
|
if expected_size != 0:
|
|
193
263
|
raise ValueError(f"{path}: zero chunks with non-zero size")
|
|
194
264
|
if hashlib.sha256(b"").hexdigest() != expected_sha256:
|
|
195
265
|
raise ValueError(f"{path}: sha256 mismatch")
|
|
196
266
|
if write_root is not None:
|
|
197
|
-
|
|
198
|
-
target.parent.mkdir(parents=True, exist_ok=True)
|
|
199
|
-
target.write_bytes(b"")
|
|
200
|
-
if mode is not None:
|
|
201
|
-
os.chmod(target, mode)
|
|
267
|
+
write_new_file(write_root, path, b"", mode)
|
|
202
268
|
return None
|
|
203
269
|
|
|
204
270
|
handle = None
|
|
271
|
+
target = None
|
|
205
272
|
if write_root is not None:
|
|
206
|
-
target =
|
|
207
|
-
target.parent.mkdir(parents=True, exist_ok=True)
|
|
208
|
-
handle = target.open("wb")
|
|
273
|
+
handle, target = create_new_file(write_root, path)
|
|
209
274
|
|
|
210
275
|
return ActiveFile(
|
|
211
276
|
path=path,
|
|
@@ -213,6 +278,7 @@ def start_active_file(
|
|
|
213
278
|
expected_size=expected_size,
|
|
214
279
|
expected_sha256=expected_sha256,
|
|
215
280
|
handle=handle,
|
|
281
|
+
target=target,
|
|
216
282
|
mode=mode,
|
|
217
283
|
)
|
|
218
284
|
|
|
@@ -258,9 +324,9 @@ def process_chunk_record(
|
|
|
258
324
|
raise ValueError(f"{path}: sha256 mismatch")
|
|
259
325
|
|
|
260
326
|
if active.handle is not None:
|
|
327
|
+
assert active.target is not None
|
|
328
|
+
apply_file_mode(active.handle, active.target, active.mode)
|
|
261
329
|
active.handle.close()
|
|
262
|
-
if active.mode is not None:
|
|
263
|
-
os.chmod(active.handle.name, active.mode)
|
|
264
330
|
return None
|
|
265
331
|
|
|
266
332
|
|
|
@@ -268,15 +334,15 @@ def process_dir_record(
|
|
|
268
334
|
record: dict[str, Any],
|
|
269
335
|
write_root: Path | None,
|
|
270
336
|
dir_modes: list[tuple[Path, int]],
|
|
337
|
+
preserve_special_bits: bool = False,
|
|
271
338
|
) -> None:
|
|
272
|
-
record_path(record)
|
|
339
|
+
path = record_path(record)
|
|
273
340
|
validate_mode(record)
|
|
274
341
|
if write_root is None:
|
|
275
342
|
return
|
|
276
343
|
|
|
277
|
-
target =
|
|
278
|
-
|
|
279
|
-
mode = mode_from_record(record)
|
|
344
|
+
target = ensure_safe_dir(write_root, safe_relative_parts(path))
|
|
345
|
+
mode = mode_from_record(record, preserve_special_bits)
|
|
280
346
|
if mode is not None:
|
|
281
347
|
dir_modes.append((target, mode))
|
|
282
348
|
|
|
@@ -297,29 +363,50 @@ def process_symlink_record(
|
|
|
297
363
|
if write_root is None:
|
|
298
364
|
return
|
|
299
365
|
|
|
300
|
-
output_target = safe_output_path(write_root, path)
|
|
301
|
-
output_target.parent.mkdir(parents=True, exist_ok=True)
|
|
302
366
|
if no_symlinks:
|
|
303
|
-
|
|
367
|
+
write_new_file(write_root, path, (target + "\n").encode("utf-8"), None)
|
|
304
368
|
return
|
|
305
|
-
|
|
369
|
+
parts = safe_relative_parts(path)
|
|
370
|
+
output_target = ensure_safe_dir(write_root, parts[:-1]) / parts[-1]
|
|
371
|
+
try:
|
|
372
|
+
os.symlink(target, output_target)
|
|
373
|
+
except FileExistsError as exc:
|
|
374
|
+
raise ValueError(
|
|
375
|
+
f"{path}: output path already exists (case-insensitive name collision?)"
|
|
376
|
+
) from exc
|
|
306
377
|
|
|
307
378
|
|
|
308
379
|
def logical_record(record: dict[str, Any]) -> dict[str, Any]:
|
|
309
380
|
return {key: value for key, value in record.items() if key != "content"}
|
|
310
381
|
|
|
311
382
|
|
|
312
|
-
def
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
383
|
+
def check_path_ancestry(
|
|
384
|
+
path: str,
|
|
385
|
+
record_type: str,
|
|
386
|
+
path_types: dict[str, str],
|
|
387
|
+
implied_dirs: set[str],
|
|
388
|
+
) -> None:
|
|
389
|
+
"""Reject ``path`` before anything is written for it.
|
|
390
|
+
|
|
391
|
+
A path may not sit under an archived symlink or file, and a non-directory
|
|
392
|
+
may not take the place of a directory that earlier entries live in.
|
|
393
|
+
"""
|
|
394
|
+
parts = safe_relative_parts(path)
|
|
395
|
+
for index in range(1, len(parts)):
|
|
396
|
+
ancestor = "/".join(parts[:index])
|
|
397
|
+
ancestor_type = path_types.get(ancestor)
|
|
398
|
+
if ancestor_type == "symlink":
|
|
399
|
+
raise ValueError(f"{path}: path is nested under archived symlink {ancestor}")
|
|
400
|
+
if ancestor_type == "file":
|
|
322
401
|
raise ValueError(f"{path}: path is nested under archived file {ancestor}")
|
|
402
|
+
if record_type != "dir" and path in implied_dirs:
|
|
403
|
+
raise ValueError(f"{path}: archived {record_type} replaces a parent directory")
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def record_implied_dirs(path: str, implied_dirs: set[str]) -> None:
|
|
407
|
+
parts = safe_relative_parts(path)
|
|
408
|
+
for index in range(1, len(parts)):
|
|
409
|
+
implied_dirs.add("/".join(parts[:index]))
|
|
323
410
|
|
|
324
411
|
|
|
325
412
|
def validate_end_record(
|
|
@@ -360,6 +447,7 @@ def process_archive(
|
|
|
360
447
|
write_root: Path | None = None,
|
|
361
448
|
no_symlinks: bool = False,
|
|
362
449
|
collect_records: bool = False,
|
|
450
|
+
preserve_special_bits: bool = False,
|
|
363
451
|
) -> ArchiveManifest:
|
|
364
452
|
records_iter = read_json_lines(archive_path)
|
|
365
453
|
try:
|
|
@@ -372,6 +460,7 @@ def process_archive(
|
|
|
372
460
|
records: list[ArchiveRecord] = []
|
|
373
461
|
seen_paths: set[str] = set()
|
|
374
462
|
path_types: dict[str, str] = {}
|
|
463
|
+
implied_dirs: set[str] = set()
|
|
375
464
|
entries = 0
|
|
376
465
|
files = 0
|
|
377
466
|
dirs = 0
|
|
@@ -395,18 +484,26 @@ def process_archive(
|
|
|
395
484
|
path = record_path(record)
|
|
396
485
|
if path in seen_paths:
|
|
397
486
|
raise ValueError(f"{path}: duplicate archive path")
|
|
487
|
+
check_path_ancestry(path, str(record_type), path_types, implied_dirs)
|
|
398
488
|
seen_paths.add(path)
|
|
399
489
|
path_types[path] = str(record_type)
|
|
490
|
+
record_implied_dirs(path, implied_dirs)
|
|
400
491
|
|
|
401
492
|
if record_type == "dir":
|
|
402
|
-
process_dir_record(
|
|
493
|
+
process_dir_record(
|
|
494
|
+
record, write_root, dir_modes, preserve_special_bits
|
|
495
|
+
)
|
|
403
496
|
dirs += 1
|
|
404
497
|
elif record_type == "file":
|
|
405
498
|
encoding = record.get("encoding")
|
|
406
499
|
if version == 1 or encoding in {"base64", "utf8"}:
|
|
407
|
-
bytes_count += process_inline_file(
|
|
500
|
+
bytes_count += process_inline_file(
|
|
501
|
+
record, write_root, preserve_special_bits
|
|
502
|
+
)
|
|
408
503
|
elif encoding == "base64-chunks":
|
|
409
|
-
active_file = start_active_file(
|
|
504
|
+
active_file = start_active_file(
|
|
505
|
+
record, write_root, preserve_special_bits
|
|
506
|
+
)
|
|
410
507
|
bytes_count += int(record["size"])
|
|
411
508
|
else:
|
|
412
509
|
raise ValueError(
|
|
@@ -434,13 +531,13 @@ def process_archive(
|
|
|
434
531
|
raise ValueError(f"unknown record type {record_type!r}")
|
|
435
532
|
except KeyError as exc:
|
|
436
533
|
raise ValueError(f"line {line_number}: missing required key {exc}") from exc
|
|
437
|
-
except
|
|
438
|
-
raise
|
|
534
|
+
except (ValueError, TypeError) as exc:
|
|
535
|
+
raise ValueError(f"line {line_number}: {exc}") from exc
|
|
536
|
+
except OSError as exc:
|
|
537
|
+
raise OSError(f"line {line_number}: {exc}") from exc
|
|
439
538
|
|
|
440
539
|
if not saw_end:
|
|
441
540
|
raise ValueError("archive is missing end record")
|
|
442
|
-
|
|
443
|
-
validate_path_ancestry(path_types)
|
|
444
541
|
finally:
|
|
445
542
|
if active_file is not None and active_file.handle is not None:
|
|
446
543
|
active_file.handle.close()
|
|
@@ -514,6 +611,7 @@ def restore_archive(
|
|
|
514
611
|
overwrite: bool,
|
|
515
612
|
verify_only: bool,
|
|
516
613
|
no_symlinks: bool,
|
|
614
|
+
preserve_special_bits: bool = False,
|
|
517
615
|
) -> tuple[int, int]:
|
|
518
616
|
if verify_only:
|
|
519
617
|
manifest = process_archive(archive_path)
|
|
@@ -534,6 +632,7 @@ def restore_archive(
|
|
|
534
632
|
archive_path,
|
|
535
633
|
write_root=staging_dir,
|
|
536
634
|
no_symlinks=no_symlinks,
|
|
635
|
+
preserve_special_bits=preserve_special_bits,
|
|
537
636
|
)
|
|
538
637
|
replace_output_with_staging(staging_dir, output_dir, overwrite)
|
|
539
638
|
staging_dir = None
|
|
@@ -556,6 +655,7 @@ def main() -> int:
|
|
|
556
655
|
overwrite=args.overwrite,
|
|
557
656
|
verify_only=args.verify_only,
|
|
558
657
|
no_symlinks=args.no_symlinks,
|
|
658
|
+
preserve_special_bits=args.preserve_special_bits,
|
|
559
659
|
)
|
|
560
660
|
except (OSError, ValueError, FileExistsError) as exc:
|
|
561
661
|
print(f"error: {exc}", file=sys.stderr)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: flat-packager
|
|
3
|
-
Version: 0.4.
|
|
3
|
+
Version: 0.4.2
|
|
4
4
|
Summary: Pack a repository into one flat text archive and restore it later.
|
|
5
5
|
Author: Thomas
|
|
6
6
|
License-Expression: MIT
|
|
@@ -219,11 +219,21 @@ The restore step rejects:
|
|
|
219
219
|
- absolute archive paths
|
|
220
220
|
- `..`, `.`, empty, or backslash path segments
|
|
221
221
|
- duplicate archive paths
|
|
222
|
-
- file or directory records nested underneath an archived symlink
|
|
222
|
+
- file or directory records nested underneath an archived symlink or file,
|
|
223
|
+
checked before anything is written for that record
|
|
224
|
+
- a symlink or file that would replace a directory other entries live in
|
|
223
225
|
- chunk records that are missing, out of order, corrupt, or attached to the
|
|
224
226
|
wrong file
|
|
225
227
|
- corrupt base64, size, or SHA-256 data
|
|
226
228
|
|
|
229
|
+
As a second layer, restores create directories one component at a time without
|
|
230
|
+
following symlinks and create files exclusively (`O_EXCL`/`O_NOFOLLOW`). Writes
|
|
231
|
+
therefore cannot be routed outside the output directory, including through
|
|
232
|
+
names that collide on case-insensitive filesystems such as default macOS.
|
|
233
|
+
|
|
234
|
+
Setuid, setgid, and sticky mode bits are stripped on restore. Pass
|
|
235
|
+
`--preserve-special-bits` to keep them for archives you trust.
|
|
236
|
+
|
|
227
237
|
Restored symlinks may still point outside the restored repository, because that
|
|
228
238
|
is valid repository content. Use `--no-symlinks` if you want symlink targets
|
|
229
239
|
written as text files instead.
|
|
@@ -4,6 +4,7 @@ import base64
|
|
|
4
4
|
import hashlib
|
|
5
5
|
import os
|
|
6
6
|
import shutil
|
|
7
|
+
import stat
|
|
7
8
|
import subprocess
|
|
8
9
|
import sys
|
|
9
10
|
import tempfile
|
|
@@ -273,18 +274,116 @@ class RoundTripTests(unittest.TestCase):
|
|
|
273
274
|
self.assertTrue((output / "link").is_dir())
|
|
274
275
|
self.assertEqual((output / "link" / "owned.txt").read_text(encoding="utf-8"), "owned\n")
|
|
275
276
|
|
|
277
|
+
def restore_expecting_error(self, archive: Path, pattern: str) -> Path:
|
|
278
|
+
output = self.work_dir / "output"
|
|
279
|
+
with self.assertRaisesRegex(ValueError, pattern):
|
|
280
|
+
restore_archive(
|
|
281
|
+
archive_path=archive,
|
|
282
|
+
output_dir=output,
|
|
283
|
+
overwrite=False,
|
|
284
|
+
verify_only=False,
|
|
285
|
+
no_symlinks=False,
|
|
286
|
+
)
|
|
287
|
+
self.assertFalse(output.exists())
|
|
288
|
+
return output
|
|
289
|
+
|
|
290
|
+
def make_outside_dir(self) -> Path:
|
|
291
|
+
outside = self.work_dir / "outside"
|
|
292
|
+
outside.mkdir()
|
|
293
|
+
return outside
|
|
294
|
+
|
|
276
295
|
def test_archive_symlink_ancestor_is_rejected(self) -> None:
|
|
277
296
|
archive = self.work_dir / "archive.flat.txt"
|
|
297
|
+
outside = self.make_outside_dir()
|
|
298
|
+
write_archive(
|
|
299
|
+
archive,
|
|
300
|
+
[
|
|
301
|
+
symlink_record("link", str(outside)),
|
|
302
|
+
file_record("link/owned.txt", b"owned\n"),
|
|
303
|
+
],
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
self.restore_expecting_error(archive, "nested under archived symlink")
|
|
307
|
+
self.assertEqual(list(outside.iterdir()), [])
|
|
308
|
+
|
|
309
|
+
def test_chunked_file_under_archive_symlink_does_not_escape(self) -> None:
|
|
310
|
+
archive = self.work_dir / "archive.flat.txt"
|
|
311
|
+
outside = self.make_outside_dir()
|
|
312
|
+
content = b"owned\n"
|
|
313
|
+
with archive.open("w", encoding="utf-8", newline="\n") as handle:
|
|
314
|
+
emit_json_line(handle, {"type": ARCHIVE_KIND, "version": 2})
|
|
315
|
+
emit_json_line(handle, symlink_record("link", str(outside)))
|
|
316
|
+
emit_json_line(
|
|
317
|
+
handle,
|
|
318
|
+
{
|
|
319
|
+
"type": "file",
|
|
320
|
+
"path": "link/owned.txt",
|
|
321
|
+
"mode": 0o644,
|
|
322
|
+
"size": len(content),
|
|
323
|
+
"sha256": hashlib.sha256(content).hexdigest(),
|
|
324
|
+
"encoding": "base64-chunks",
|
|
325
|
+
"chunks": 1,
|
|
326
|
+
},
|
|
327
|
+
)
|
|
328
|
+
emit_json_line(
|
|
329
|
+
handle,
|
|
330
|
+
{
|
|
331
|
+
"type": "chunk",
|
|
332
|
+
"path": "link/owned.txt",
|
|
333
|
+
"index": 0,
|
|
334
|
+
"size": len(content),
|
|
335
|
+
"content": base64.b64encode(content).decode("ascii"),
|
|
336
|
+
},
|
|
337
|
+
)
|
|
338
|
+
emit_json_line(handle, {"type": "end", "entries": 2, "files": 1})
|
|
339
|
+
|
|
340
|
+
self.restore_expecting_error(archive, "nested under archived symlink")
|
|
341
|
+
self.assertEqual(list(outside.iterdir()), [])
|
|
342
|
+
|
|
343
|
+
def test_dir_under_archive_symlink_does_not_escape(self) -> None:
|
|
344
|
+
archive = self.work_dir / "archive.flat.txt"
|
|
345
|
+
outside = self.make_outside_dir()
|
|
346
|
+
write_archive(
|
|
347
|
+
archive,
|
|
348
|
+
[
|
|
349
|
+
symlink_record("link", str(outside)),
|
|
350
|
+
{"type": "dir", "path": "link/created", "mode": 0o755},
|
|
351
|
+
],
|
|
352
|
+
)
|
|
353
|
+
|
|
354
|
+
self.restore_expecting_error(archive, "nested under archived symlink")
|
|
355
|
+
self.assertEqual(list(outside.iterdir()), [])
|
|
356
|
+
|
|
357
|
+
def test_symlink_replacing_populated_directory_is_rejected(self) -> None:
|
|
358
|
+
archive = self.work_dir / "archive.flat.txt"
|
|
359
|
+
outside = self.make_outside_dir()
|
|
360
|
+
write_archive(
|
|
361
|
+
archive,
|
|
362
|
+
[
|
|
363
|
+
file_record("dir/a.txt", b"a\n"),
|
|
364
|
+
symlink_record("dir", str(outside)),
|
|
365
|
+
],
|
|
366
|
+
)
|
|
367
|
+
|
|
368
|
+
self.restore_expecting_error(archive, "replaces a parent directory")
|
|
369
|
+
self.assertEqual(list(outside.iterdir()), [])
|
|
370
|
+
|
|
371
|
+
def test_case_variant_of_symlink_cannot_redirect_restore(self) -> None:
|
|
372
|
+
# On case-insensitive filesystems "Link" and "link" are the same entry.
|
|
373
|
+
# The restore must refuse rather than write through the symlink; on
|
|
374
|
+
# case-sensitive filesystems the archive is simply valid.
|
|
375
|
+
archive = self.work_dir / "archive.flat.txt"
|
|
376
|
+
outside = self.make_outside_dir()
|
|
278
377
|
output = self.work_dir / "output"
|
|
279
378
|
write_archive(
|
|
280
379
|
archive,
|
|
281
380
|
[
|
|
282
|
-
symlink_record("
|
|
381
|
+
symlink_record("Link", str(outside)),
|
|
283
382
|
file_record("link/owned.txt", b"owned\n"),
|
|
284
383
|
],
|
|
285
384
|
)
|
|
286
385
|
|
|
287
|
-
|
|
386
|
+
try:
|
|
288
387
|
restore_archive(
|
|
289
388
|
archive_path=archive,
|
|
290
389
|
output_dir=output,
|
|
@@ -292,8 +391,68 @@ class RoundTripTests(unittest.TestCase):
|
|
|
292
391
|
verify_only=False,
|
|
293
392
|
no_symlinks=False,
|
|
294
393
|
)
|
|
394
|
+
except ValueError as exc:
|
|
395
|
+
self.assertIn("refusing to write through symlink", str(exc))
|
|
396
|
+
self.assertFalse(output.exists())
|
|
397
|
+
else:
|
|
398
|
+
self.assertEqual((output / "link" / "owned.txt").read_bytes(), b"owned\n")
|
|
399
|
+
self.assertEqual(list(outside.iterdir()), [])
|
|
295
400
|
|
|
296
|
-
|
|
401
|
+
def test_special_mode_bits_are_stripped_by_default(self) -> None:
|
|
402
|
+
archive = self.work_dir / "archive.flat.txt"
|
|
403
|
+
output = self.work_dir / "output"
|
|
404
|
+
record = file_record("run.sh", b"#!/bin/sh\n")
|
|
405
|
+
record["mode"] = 0o6755
|
|
406
|
+
write_archive(archive, [record])
|
|
407
|
+
|
|
408
|
+
restore_archive(
|
|
409
|
+
archive_path=archive,
|
|
410
|
+
output_dir=output,
|
|
411
|
+
overwrite=False,
|
|
412
|
+
verify_only=False,
|
|
413
|
+
no_symlinks=False,
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
self.assertEqual(stat.S_IMODE((output / "run.sh").stat().st_mode), 0o755)
|
|
417
|
+
|
|
418
|
+
@unittest.skipIf(os.name == "nt", "sticky bit is POSIX-only")
|
|
419
|
+
def test_preserve_special_bits_opt_in(self) -> None:
|
|
420
|
+
# The sticky bit on a directory is settable by its owner on Linux and
|
|
421
|
+
# macOS, unlike setuid/setgid which the OS may silently clear.
|
|
422
|
+
archive = self.work_dir / "archive.flat.txt"
|
|
423
|
+
write_archive(archive, [{"type": "dir", "path": "shared", "mode": 0o1777}])
|
|
424
|
+
|
|
425
|
+
for preserve, expected in ((False, 0o777), (True, 0o1777)):
|
|
426
|
+
output = self.work_dir / f"output-{preserve}"
|
|
427
|
+
restore_archive(
|
|
428
|
+
archive_path=archive,
|
|
429
|
+
output_dir=output,
|
|
430
|
+
overwrite=False,
|
|
431
|
+
verify_only=False,
|
|
432
|
+
no_symlinks=False,
|
|
433
|
+
preserve_special_bits=preserve,
|
|
434
|
+
)
|
|
435
|
+
self.assertEqual(stat.S_IMODE((output / "shared").stat().st_mode), expected)
|
|
436
|
+
|
|
437
|
+
def test_invalid_utf8_text_content_is_a_clean_error(self) -> None:
|
|
438
|
+
archive = self.work_dir / "archive.flat.txt"
|
|
439
|
+
write_archive(
|
|
440
|
+
archive,
|
|
441
|
+
[
|
|
442
|
+
{
|
|
443
|
+
"type": "file",
|
|
444
|
+
"path": "x.txt",
|
|
445
|
+
"mode": 0o644,
|
|
446
|
+
"size": 1,
|
|
447
|
+
"sha256": "0" * 64,
|
|
448
|
+
"encoding": "utf8",
|
|
449
|
+
"content": "\ud800",
|
|
450
|
+
}
|
|
451
|
+
],
|
|
452
|
+
)
|
|
453
|
+
|
|
454
|
+
with self.assertRaisesRegex(ValueError, "line 2: x.txt: content is not valid UTF-8"):
|
|
455
|
+
load_and_validate_archive(archive)
|
|
297
456
|
|
|
298
457
|
def test_non_empty_output_without_overwrite_raises_file_exists_error(self) -> None:
|
|
299
458
|
source = self.work_dir / "source"
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|