Skip to content

Commit b53999e

Browse files
authored
fix: support Windows long paths during plugin archive extraction (#10193)
* fix: support Windows long paths during plugin archive extraction * fix: address Windows plugin path review comments * fix: shorten archive root SHA to eight characters
1 parent 9c6b603 commit b53999e

2 files changed

Lines changed: 139 additions & 1 deletion

File tree

‎astrbot/core/star/updater.py‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import asyncio
22
import os
3+
import re
34
import shutil
45
import tempfile
56
import zipfile
7+
from copy import copy
68
from pathlib import Path
79

810
import yaml
@@ -477,11 +479,38 @@ def validate_plugin_archive(cls, zip_path: str) -> str:
477479
return str(inspection["metadata_entry"])
478480

479481
def _extract_plugin_archive(self, zip_path: str, target_dir: str) -> None:
482+
"""Extract a validated plugin archive and flatten its repository directory.
483+
484+
Args:
485+
zip_path: Path to the downloaded plugin archive.
486+
target_dir: Directory that will receive the plugin files.
487+
488+
Raises:
489+
ValueError: If the archive is not a valid plugin.
490+
OSError: If extraction or moving the extracted files fails.
491+
RuntimeError: If the target directory cannot be created.
492+
"""
480493
self.validate_plugin_archive(zip_path)
481494
ensure_dir(target_dir)
482495
logger.info(f"Extracting archive: {zip_path}")
483496
with zipfile.ZipFile(zip_path, "r") as z:
484497
update_dir = self._resolve_archive_root_dir(z.namelist())
485-
z.extractall(target_dir)
498+
root_parts = update_dir.replace("\\", "/").split("/")
499+
archive_root = root_parts[0]
500+
match = re.fullmatch(r"(.+)-([0-9a-fA-F]{40})", archive_root)
501+
if match and all(
502+
name == archive_root or name.startswith(archive_root + "/")
503+
for name in z.namelist()
504+
):
505+
short_root = f"{match[1]}-{match[2][:8]}"
506+
# Shorten the temporary repository directory before extraction.
507+
# Keep orig_filename intact for ZIP local-header validation.
508+
for member in z.infolist():
509+
member = copy(member)
510+
member.filename = short_root + member.filename[len(archive_root) :]
511+
z.extract(member, target_dir)
512+
update_dir = str(Path(short_root).joinpath(*root_parts[1:]))
513+
else:
514+
z.extractall(target_dir)
486515

487516
self._finalize_extracted_archive(zip_path, target_dir, update_dir)

‎tests/test_updater_socks.py‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import asyncio
2+
import builtins
23
import ntpath
4+
import os
35
import posixpath
46
import zipfile
57
from dataclasses import dataclass, field
@@ -397,6 +399,113 @@ def test_plugin_unzip_file_accepts_metadata_yml(tmp_path: Path) -> None:
397399
assert not zip_path.exists()
398400

399401

402+
@pytest.mark.parametrize("target_kind", ["absolute", "relative"])
403+
def test_plugin_unzip_file_handles_long_archive_paths(
404+
tmp_path: Path,
405+
monkeypatch: pytest.MonkeyPatch,
406+
target_kind: str,
407+
) -> None:
408+
zip_path = tmp_path / "plugin.zip"
409+
target_dir = tmp_path / "plugin"
410+
archive_root = "demo-plugin-" + "a" * 40
411+
# The original destination is 270 characters; shortening the SHA saves 32.
412+
filename_length = 270 - len(str(target_dir / archive_root)) - 1
413+
assert 3 < filename_length <= 255
414+
member_path = "x" * (filename_length - 3) + ".py"
415+
416+
with zipfile.ZipFile(zip_path, "w") as archive:
417+
archive.writestr(
418+
f"{archive_root}/metadata.yaml",
419+
"name: demo\ndesc: Demo plugin\nversion: 1.0.0\nauthor: AstrBot Team\n",
420+
)
421+
archive.writestr(f"{archive_root}/{member_path}", "VALUE = 1\n")
422+
archive.writestr(f"{archive_root}/empty/", "")
423+
424+
original_open = builtins.open
425+
426+
def open_with_path_limit(file, mode="r", *args, **kwargs):
427+
# Enforce MAX_PATH even on hosts that support longer paths.
428+
if isinstance(file, (str, os.PathLike)):
429+
path = os.fspath(file)
430+
if len(os.path.abspath(path)) >= 260:
431+
raise FileNotFoundError(2, "Path exceeds MAX_PATH", path)
432+
return original_open(file, mode, *args, **kwargs)
433+
434+
monkeypatch.setattr(builtins, "open", open_with_path_limit)
435+
target = str(target_dir)
436+
if target_kind == "relative":
437+
monkeypatch.chdir(tmp_path)
438+
target = "plugin"
439+
440+
updater = _PluginUpdater.__new__(_PluginUpdater)
441+
updater._extract_plugin_archive(str(zip_path), target)
442+
443+
assert (target_dir / member_path).read_text(encoding="utf-8") == "VALUE = 1\n"
444+
assert (target_dir / "metadata.yaml").is_file()
445+
assert (target_dir / "empty").is_dir()
446+
assert {entry.name for entry in target_dir.iterdir()} == {
447+
"metadata.yaml",
448+
member_path,
449+
"empty",
450+
}
451+
assert not zip_path.exists()
452+
453+
454+
@pytest.mark.parametrize(
455+
("archive_root", "extracted_root"),
456+
[
457+
("demo-" + "a" * 40, "demo-" + "a" * 8),
458+
("demo-" + "A" * 40 + "/plugin", "demo-" + "A" * 8 + "/plugin"),
459+
("demo-main", "demo-main"),
460+
("demo-v1.0.0", "demo-v1.0.0"),
461+
("demo-12345678", "demo-12345678"),
462+
("demo-" + "g" * 40, "demo-" + "g" * 40),
463+
("./demo-" + "a" * 40, "demo-" + "a" * 40),
464+
("", ""),
465+
],
466+
)
467+
def test_plugin_unzip_file_only_shortens_full_root_sha(
468+
tmp_path: Path,
469+
monkeypatch: pytest.MonkeyPatch,
470+
archive_root: str,
471+
extracted_root: str,
472+
) -> None:
473+
zip_path = tmp_path / "plugin.zip"
474+
target_dir = tmp_path / "plugin"
475+
prefix = f"{archive_root}/" if archive_root else ""
476+
internal_path = "src/nested-" + "a" * 40 + "/main.py"
477+
with zipfile.ZipFile(zip_path, "w") as archive:
478+
if archive_root:
479+
archive.writestr(f"{archive_root}/", "")
480+
archive.writestr(
481+
f"{prefix}metadata.yaml",
482+
"name: demo\ndesc: Demo plugin\nversion: 1.0.0\nauthor: AstrBot Team\n",
483+
)
484+
archive.writestr(f"{prefix}{internal_path}", "VALUE = 1\n")
485+
486+
original_open = builtins.open
487+
destinations = []
488+
489+
def record_destination(file, mode="r", *args, **kwargs):
490+
if mode == "wb" and isinstance(file, (str, os.PathLike)):
491+
destinations.append(Path(file))
492+
return original_open(file, mode, *args, **kwargs)
493+
494+
monkeypatch.setattr(builtins, "open", record_destination)
495+
updater = _PluginUpdater.__new__(_PluginUpdater)
496+
updater._extract_plugin_archive(str(zip_path), str(target_dir))
497+
498+
assert destinations == [
499+
target_dir / extracted_root / "metadata.yaml",
500+
target_dir / extracted_root / internal_path,
501+
]
502+
assert (target_dir / internal_path).read_text(encoding="utf-8") == "VALUE = 1\n"
503+
assert (target_dir / "metadata.yaml").is_file()
504+
if extracted_root:
505+
assert not (target_dir / extracted_root).exists()
506+
assert not zip_path.exists()
507+
508+
400509
def test_plugin_unzip_file_rejects_archive_without_metadata(tmp_path: Path) -> None:
401510
zip_path = tmp_path / "plugin.zip"
402511
target_dir = tmp_path / "plugin"

0 commit comments

Comments
 (0)