drive-artifacts 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,4 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """GitHub Actions artifacts, stored in your own Google Drive."""
3
+
4
+ __version__ = "0.1.0"
@@ -0,0 +1,6 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """`python -m drive_artifacts` entry point."""
3
+
4
+ from drive_artifacts.cli import main
5
+
6
+ raise SystemExit(main())
@@ -0,0 +1,13 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """The published OAuth client this package ships with.
3
+
4
+ The Chaos Bureau's Desktop-app client for the "Drive Artifacts" consent screen, which is
5
+ in production and asks for `drive.file` only. Google documents installed-app client
6
+ secrets as not secret (https://developers.google.com/identity/protocols/oauth2#installed),
7
+ so both values are committed on purpose. DRIVE_ARTIFACTS_CLIENT_ID/SECRET in the
8
+ environment override them, for a fork or a private client of your own.
9
+ """
10
+
11
+ CLIENT_ID = "301726695005-8mrsj8dv6t4hpjkuadj28788i6itmrac.apps.googleusercontent.com"
12
+ # Not a credential: Google treats installed-app client secrets as public (see docstring).
13
+ CLIENT_SECRET = "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" # noqa: S105
@@ -0,0 +1,332 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Which files an artifact holds, how they become one zip, and how that zip is opened safely."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import glob
7
+ import hashlib
8
+ import lzma
9
+ import os
10
+ import re
11
+ import stat
12
+ import zipfile
13
+ import zlib
14
+ from collections.abc import Iterator, Sequence
15
+ from dataclasses import dataclass
16
+ from pathlib import Path, PurePosixPath
17
+ from typing import Any, cast
18
+
19
+ from drive_artifacts.errors import IntegrityError, UsageError
20
+
21
+ FIXED_DATE = (1980, 1, 1, 0, 0, 0) # deterministic archives: same tree, same digest
22
+ CHUNK = 1 << 20
23
+ _MAGIC = re.compile(r"[*?\[]")
24
+ _DRIVE = re.compile(r"[A-Za-z]:") # a Windows drive prefix; other colons are legal POSIX names
25
+
26
+
27
+ @dataclass(frozen=True, slots=True)
28
+ class Resolved:
29
+ """What a set of `path` patterns matched: the files, the directories that stay empty, and the
30
+ root their names in the archive are relative to."""
31
+
32
+ files: list[Path]
33
+ empty_dirs: list[Path]
34
+ root: Path
35
+
36
+
37
+ @dataclass(frozen=True, slots=True)
38
+ class ZipResult:
39
+ """A zip that was built: where it is, its size and digest, and how many files it holds."""
40
+
41
+ path: Path
42
+ size: int
43
+ sha256: str
44
+ file_count: int
45
+
46
+
47
+ def _norm(path: Path | str) -> Path:
48
+ """Absolute and lexically normalised. Symlinks are never resolved: a link keeps its own name."""
49
+ return Path(os.path.abspath(path)) # noqa: PTH100 - Path.resolve() would follow symlinks
50
+
51
+
52
+ def _is_hidden(path: Path, base: Path) -> bool:
53
+ """A dot-name below `base` hides `path`; `base` itself and everything above it never count."""
54
+ try:
55
+ parts = path.relative_to(base).parts
56
+ except ValueError: # a pattern that climbs out of its search path with `..`: the name speaks
57
+ parts = path.parts[-1:]
58
+ return any(part.startswith(".") for part in parts)
59
+
60
+
61
+ def _crosses_directory_link(path: Path, base: Path) -> bool:
62
+ """Whether `path`, below `base`, is or lies under a link to a directory. A wildcard must not
63
+ reach through one: `dist/*` and `**` see what a walk of `dist` sees, on every Python (3.11
64
+ and 3.12 follow such links under `**`, 3.13 does not), and a link back to an ancestor cannot
65
+ multiply the tree. The search base itself is exempt: a link the pattern names is walked."""
66
+ try:
67
+ parts = path.relative_to(base).parts
68
+ except ValueError: # a pattern that climbs out of its search path with `..`
69
+ return False
70
+ here = base
71
+ for part in parts:
72
+ here = here / part
73
+ if here.is_symlink() and here.is_dir():
74
+ return True
75
+ return False
76
+
77
+
78
+ def _expand(path: Path, *, include_hidden: bool) -> tuple[set[Path], set[Path]]:
79
+ """A file is itself; a directory is every file below it plus its empty directories.
80
+
81
+ Links keep their own names. A link to a file is that file's content under the link's name; a
82
+ broken link (or a socket, fifo, device) is dropped; a link to a directory is not descended into
83
+ unless a pattern names it, which makes it the top of the walk.
84
+ """
85
+ if path.is_file():
86
+ return ({path}, set())
87
+ files: set[Path] = set()
88
+ empty: set[Path] = set()
89
+ for dirpath, dirnames, filenames in os.walk(path):
90
+ here = Path(dirpath)
91
+ if not include_hidden:
92
+ dirnames[:] = [d for d in dirnames if not d.startswith(".")]
93
+ filenames = [f for f in filenames if not f.startswith(".")]
94
+ filenames = [f for f in filenames if (here / f).is_file()]
95
+ for name in filenames:
96
+ files.add(here / name)
97
+ if not filenames and not dirnames and here != path:
98
+ empty.add(here)
99
+ return files, empty
100
+
101
+
102
+ def _matches(pattern: str, cwd: Path, *, include_hidden: bool) -> tuple[set[Path], set[Path]]:
103
+ # Not Path.glob: it matches dotfiles unconditionally and rejects absolute patterns.
104
+ hits = glob.glob(pattern, root_dir=cwd, recursive=True, include_hidden=include_hidden) # noqa: PTH207
105
+ base = _search_base(pattern, cwd) # hiddenness is judged below the search path only
106
+ files: set[Path] = set()
107
+ empty: set[Path] = set()
108
+ for hit in hits:
109
+ p = _norm(cwd / hit)
110
+ if not include_hidden and _is_hidden(p, base):
111
+ continue
112
+ if _crosses_directory_link(p, base):
113
+ continue
114
+ f, e = _expand(p, include_hidden=include_hidden)
115
+ files |= f
116
+ empty |= e
117
+ return files, empty
118
+
119
+
120
+ def resolve_paths(patterns: Sequence[str], cwd: Path, *, include_hidden: bool = False) -> Resolved:
121
+ """GitHub `path` semantics: one pattern per line, `!` excludes, `#` comments, directories expand."""
122
+ cwd = _norm(cwd)
123
+ lines = [line for raw in patterns if (line := raw.strip()) and not line.startswith("#")]
124
+ includes = [line for line in lines if not line.startswith("!")]
125
+ excludes = [line[1:].strip() for line in lines if line.startswith("!")]
126
+ files: set[Path] = set()
127
+ empty: set[Path] = set()
128
+ excluded: set[Path] = set()
129
+ for pattern in includes:
130
+ f, e = _matches(pattern, cwd, include_hidden=include_hidden)
131
+ files |= f
132
+ empty |= e
133
+ for pattern in excludes:
134
+ ex_files, ex_empty = _matches(pattern, cwd, include_hidden=include_hidden)
135
+ excluded |= ex_files | ex_empty
136
+ files -= excluded
137
+ occupied = {parent for f in files for parent in f.parents} # every directory holding a file
138
+ empty = {d for d in empty if d not in excluded and d not in occupied}
139
+ if not files and not empty:
140
+ return Resolved([], [], cwd)
141
+ bases = [str(_search_base(p, cwd)) for p in includes]
142
+ try:
143
+ root = Path(os.path.commonpath(bases))
144
+ except ValueError as exc: # two Windows drives
145
+ raise UsageError(
146
+ f"the paths share no common directory to root the archive at ({exc}); "
147
+ "upload them as separate artifacts"
148
+ ) from exc
149
+ return Resolved(sorted(files), sorted(empty), root)
150
+
151
+
152
+ def _search_base(pattern: str, cwd: Path) -> Path:
153
+ """GitHub's search path: the pattern's literal prefix, whether or not it exists, so the archive
154
+ layout never depends on what happens to be on disk; the parent when the prefix is a file."""
155
+ parts: list[str] = []
156
+ for part in Path(pattern.strip()).parts:
157
+ if _MAGIC.search(part):
158
+ break
159
+ parts.append(part)
160
+ base = _norm(cwd / Path(*parts)) if parts else cwd
161
+ return base.parent if base.is_file() else base
162
+
163
+
164
+ def sha256_file(path: Path) -> str:
165
+ """The hex SHA-256 of a file."""
166
+ with path.open("rb") as fh:
167
+ return hashlib.file_digest(fh, "sha256").hexdigest()
168
+
169
+
170
+ def _arcname(path: Path, root: Path) -> str:
171
+ """The name `path` gets in the zip. Refuse here what `safe_extract` would refuse there."""
172
+ try:
173
+ name = path.relative_to(root).as_posix()
174
+ except ValueError:
175
+ raise UsageError(
176
+ f"cannot archive {path}: it lies outside {root}, the directory the patterns "
177
+ "search (a pattern climbs out of it with `..`)"
178
+ ) from None
179
+ if "\\" in name or _DRIVE.match(name.split("/", 1)[0]):
180
+ raise UsageError(
181
+ f"cannot archive {path}: extraction refuses the name {name!r} "
182
+ "(it holds a backslash or starts with a drive letter)"
183
+ )
184
+ return name
185
+
186
+
187
+ def build_zip(resolved: Resolved, dest: Path, *, compression_level: int = 6) -> ZipResult:
188
+ """One deterministic zip: sorted posix arcnames, fixed timestamps, mode bits kept."""
189
+ if not 0 <= compression_level <= 9:
190
+ raise ValueError("compression_level must be 0..9")
191
+ method = zipfile.ZIP_STORED if compression_level == 0 else zipfile.ZIP_DEFLATED
192
+ entries: list[tuple[str, Path | None]] = []
193
+ entries.extend((_arcname(p, resolved.root), p) for p in resolved.files)
194
+ entries.extend((_arcname(d, resolved.root) + "/", None) for d in resolved.empty_dirs)
195
+ entries.sort(key=lambda e: e[0])
196
+ dest.parent.mkdir(parents=True, exist_ok=True)
197
+ with zipfile.ZipFile(
198
+ dest, "w", compression=method, compresslevel=compression_level or None
199
+ ) as zf:
200
+ for arcname, src in entries:
201
+ info = zipfile.ZipInfo(arcname, date_time=FIXED_DATE)
202
+ if src is None:
203
+ info.external_attr = (stat.S_IFDIR | 0o755) << 16
204
+ zf.writestr(info, b"")
205
+ continue
206
+ meta = src.stat()
207
+ info.external_attr = (stat.S_IFREG | stat.S_IMODE(meta.st_mode)) << 16
208
+ info.file_size = meta.st_size # streamed entries need the size up front to choose zip64
209
+ info.compress_type = method
210
+ # A hand-built ZipInfo does not inherit the ZipFile's level and zipfile has no public
211
+ # setter for it (the typeshed stubs do not know the attribute, hence the cast).
212
+ cast("Any", info)._compresslevel = compression_level
213
+ with src.open("rb") as fh, zf.open(info, "w") as out:
214
+ while chunk := fh.read(CHUNK):
215
+ out.write(chunk)
216
+ return ZipResult(dest, dest.stat().st_size, sha256_file(dest), len(resolved.files))
217
+
218
+
219
+ # What decoding a member can raise: a bad CRC or header, a truncated or garbled stream, a method we
220
+ # cannot undo, encryption, or a name that is not valid UTF-8. All of them mean "this archive is bad".
221
+ _DECODE_ERRORS = (
222
+ zipfile.BadZipFile,
223
+ zlib.error,
224
+ lzma.LZMAError,
225
+ EOFError,
226
+ NotImplementedError,
227
+ RuntimeError,
228
+ UnicodeDecodeError,
229
+ )
230
+
231
+
232
+ def _check_member(name: str, dest: Path) -> Path:
233
+ pure = PurePosixPath(name)
234
+ if (
235
+ not name
236
+ or name.startswith(("/", "\\"))
237
+ or ".." in pure.parts
238
+ or any(_DRIVE.match(part) for part in pure.parts[:1])
239
+ or "\\" in name
240
+ or (not pure.parts and not name.endswith("/")) # "." names the destination, not a file
241
+ ):
242
+ raise IntegrityError(f"unsafe path in archive: {name!r}")
243
+ target = (dest / Path(*pure.parts)).resolve()
244
+ if not target.is_relative_to(dest):
245
+ raise IntegrityError(f"unsafe path in archive: {name!r}")
246
+ return target
247
+
248
+
249
+ def _plan(infos: list[zipfile.ZipInfo], dest: Path) -> list[tuple[zipfile.ZipInfo, Path]]:
250
+ """Validate every member before anything is written: unsafe paths, repeated names, and a file
251
+ that is also a directory prefix of another member all raise here, never half-way through."""
252
+ plan: list[tuple[zipfile.ZipInfo, Path]] = []
253
+ seen: set[tuple[str, ...]] = set()
254
+ files: set[tuple[str, ...]] = set()
255
+ for info in infos:
256
+ target = _check_member(info.filename, dest)
257
+ key = PurePosixPath(info.filename).parts
258
+ if key: # () is the destination itself
259
+ if key in seen:
260
+ raise IntegrityError(
261
+ f"archive members conflict: {info.filename!r} repeats an earlier member"
262
+ )
263
+ seen.add(key)
264
+ if not info.is_dir():
265
+ files.add(key)
266
+ plan.append((info, target))
267
+ for info, _ in plan:
268
+ key = PurePosixPath(info.filename).parts
269
+ for depth in range(1, len(key)):
270
+ if key[:depth] in files:
271
+ raise IntegrityError(
272
+ f"archive members conflict: {info.filename!r} lies under "
273
+ f"{'/'.join(key[:depth])!r}, which the archive holds as a file"
274
+ )
275
+ return plan
276
+
277
+
278
+ def _decoded_chunks(zf: zipfile.ZipFile, info: zipfile.ZipInfo) -> Iterator[bytes]:
279
+ """The member's bytes; only failures of the archive itself become IntegrityError."""
280
+ try:
281
+ with zf.open(info) as src:
282
+ while chunk := src.read(CHUNK):
283
+ yield chunk
284
+ except (*_DECODE_ERRORS, OSError) as exc: # nothing is being written here; bz2 raises OSError
285
+ raise IntegrityError(f"corrupt or unextractable member {info.filename!r}: {exc}") from exc
286
+
287
+
288
+ def _write_member(zf: zipfile.ZipFile, info: zipfile.ZipInfo, target: Path) -> None:
289
+ """Write errors (full disk, permissions) are real OSErrors and propagate unwrapped."""
290
+ target.parent.mkdir(parents=True, exist_ok=True)
291
+ with target.open("wb") as out:
292
+ for chunk in _decoded_chunks(zf, info):
293
+ out.write(chunk)
294
+ mode = info.external_attr >> 16
295
+ regular = stat.S_IFMT(mode) in (0, stat.S_IFREG) # a symlink entry is just text here
296
+ # Windows honours only the read-only flag of chmod, and both values leave the file writable.
297
+ target.chmod(0o755 if regular and mode & 0o111 else 0o644)
298
+
299
+
300
+ def safe_extract(
301
+ zip_path: Path,
302
+ dest: Path,
303
+ *,
304
+ max_members: int = 200_000,
305
+ max_total_bytes: int = 64 * 2**30,
306
+ ) -> list[Path]:
307
+ """Extract with zip-slip and zip-bomb guards. Returns the files written.
308
+
309
+ Every member is validated before the first byte is written.
310
+ """
311
+ dest = dest.resolve()
312
+ try:
313
+ zf = zipfile.ZipFile(zip_path)
314
+ except (zipfile.BadZipFile, UnicodeDecodeError) as exc:
315
+ raise IntegrityError(f"not a readable zip archive: {zip_path} ({exc})") from exc
316
+ written: list[Path] = []
317
+ with zf:
318
+ infos = zf.infolist()
319
+ if len(infos) > max_members:
320
+ raise IntegrityError(f"archive has {len(infos)} members, more than {max_members}")
321
+ total = sum(i.file_size for i in infos)
322
+ if total > max_total_bytes:
323
+ raise IntegrityError(f"archive expands to {total} bytes, more than {max_total_bytes}")
324
+ plan = _plan(infos, dest)
325
+ dest.mkdir(parents=True, exist_ok=True)
326
+ for info, target in plan:
327
+ if info.is_dir():
328
+ target.mkdir(parents=True, exist_ok=True)
329
+ else:
330
+ _write_member(zf, info, target)
331
+ written.append(target)
332
+ return written