Repository navigation
fix(jev): support secure scoped capture on native Windows #8620
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
xiaobaifly7
wants to merge
2
commits into
loopx-project:main
Choose a base branch
from
xiaobaifly7:fix/jev-windows-safe-capture
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+589
−21
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,10 +5,12 @@ | |
| import difflib | ||
| import hashlib | ||
| import os | ||
| from pathlib import Path | ||
| import stat | ||
| import subprocess | ||
| import tempfile | ||
| from typing import Any | ||
| from contextlib import ExitStack | ||
| from pathlib import Path | ||
| from typing import Any, BinaryIO | ||
|
|
||
| from .protocol import request_bytes | ||
|
|
||
|
|
@@ -43,11 +45,16 @@ def validate_paths(repo: Path, paths: list[str]) -> list[str]: | |
| raise ValueError("scope_requires_one_to_32_unique_files") | ||
| for name in paths: | ||
| path = Path(name) | ||
| parts = ( | ||
| tuple(part.casefold() for part in path.parts) | ||
| if os.name == "nt" | ||
| else path.parts | ||
| ) | ||
| if ( | ||
| not name | ||
| or path.is_absolute() | ||
| or ".." in path.parts | ||
| or ".git" in path.parts | ||
| or ".git" in parts | ||
| or name != path.as_posix() | ||
| or any(ord(char) < 32 for char in name) | ||
| ): | ||
|
|
@@ -58,8 +65,138 @@ def validate_paths(repo: Path, paths: list[str]) -> list[str]: | |
| return sorted(paths) | ||
|
|
||
|
|
||
| def _windows_identity( | ||
| info: os.stat_result, | ||
| *, | ||
| directory: bool = False, | ||
| ) -> tuple[int, int, int, int]: | ||
| attributes = getattr(info, "st_file_attributes", None) | ||
| if attributes is None: | ||
| raise ValueError("unsupported_capture_platform") | ||
| if stat.S_ISLNK(info.st_mode) or attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT: | ||
| raise ValueError("scope_escapes_workspace") | ||
| if not (stat.S_ISDIR if directory else stat.S_ISREG)(info.st_mode): | ||
| raise ValueError("scope_requires_regular_files") | ||
| if not info.st_dev or not info.st_ino: | ||
| raise ValueError("capture_identity_unavailable") | ||
| return info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns | ||
|
|
||
|
|
||
| def _windows_descriptor(target: Path, *, directory: bool = False) -> int: | ||
| import ctypes | ||
| import msvcrt | ||
| from ctypes import wintypes | ||
|
|
||
| kernel = ctypes.WinDLL("kernel32", use_last_error=True) | ||
| create = kernel.CreateFileW | ||
| create.argtypes = ( | ||
| wintypes.LPCWSTR, | ||
| wintypes.DWORD, | ||
| wintypes.DWORD, | ||
| wintypes.LPVOID, | ||
| wintypes.DWORD, | ||
| wintypes.DWORD, | ||
| wintypes.HANDLE, | ||
| ) | ||
| create.restype = wintypes.HANDLE | ||
| kernel.CloseHandle.argtypes = (wintypes.HANDLE,) | ||
| kernel.CloseHandle.restype = wintypes.BOOL | ||
| filename = os.path.abspath(target) | ||
| if not filename.startswith("\\\\?\\"): | ||
| filename = ( | ||
| "\\\\?\\UNC\\" + filename[2:] | ||
| if filename.startswith("\\\\") | ||
| else "\\\\?\\" + filename | ||
| ) | ||
| # Directories deny write/delete sharing to pin traversal; OPEN_REPARSE_POINT | ||
| # opens a raced-in link itself. BACKUP_SEMANTICS permits directory handles. | ||
| flags = 0x00200000 | (0x02000000 if directory else 0) | ||
| handle = create( | ||
| filename, 0x80000000, 0x1 if directory else 0x7, None, 3, flags, None | ||
| ) | ||
| if handle == wintypes.HANDLE(-1).value: | ||
| raise ctypes.WinError(ctypes.get_last_error()) | ||
| try: | ||
| return msvcrt.open_osfhandle(handle, os.O_RDONLY | os.O_BINARY | os.O_NOINHERIT) | ||
| except BaseException: | ||
| kernel.CloseHandle(handle) | ||
| raise | ||
|
|
||
|
|
||
| def _windows_open(target: Path) -> BinaryIO: | ||
| descriptor = _windows_descriptor(target) | ||
| try: | ||
| return os.fdopen(descriptor, "rb") | ||
| except BaseException: | ||
| os.close(descriptor) | ||
| raise | ||
|
|
||
|
|
||
| def _windows_final_path(descriptor: int) -> Path: | ||
| import ctypes | ||
| import msvcrt | ||
| from ctypes import wintypes | ||
|
|
||
| kernel = ctypes.WinDLL("kernel32", use_last_error=True) | ||
| final_path = kernel.GetFinalPathNameByHandleW | ||
| final_path.argtypes = ( | ||
| wintypes.HANDLE, | ||
| wintypes.LPWSTR, | ||
| wintypes.DWORD, | ||
| wintypes.DWORD, | ||
| ) | ||
| final_path.restype = wintypes.DWORD | ||
| buffer = ctypes.create_unicode_buffer(32768) | ||
| # FILE_NAME_NORMALIZED | VOLUME_NAME_DOS keeps root and file names comparable. | ||
| length = final_path(msvcrt.get_osfhandle(descriptor), buffer, len(buffer), 0) | ||
| if not 0 < length < len(buffer): | ||
| raise ValueError("capture_path_unavailable") | ||
| return Path(buffer.value) | ||
|
|
||
|
|
||
| def _windows_capture(repo: Path, target: Path) -> tuple[bytes, int] | None: | ||
| with ExitStack() as parents: | ||
| current = repo | ||
| canonical_repo = repo | ||
| for part in ("", *target.relative_to(repo).parts[:-1]): | ||
| current = current / part | ||
| try: | ||
| expected = _windows_identity(os.lstat(current), directory=True)[:2] | ||
| except FileNotFoundError: | ||
| return None | ||
| descriptor = _windows_descriptor(current, directory=True) | ||
| parents.callback(os.close, descriptor) | ||
| if _windows_identity(os.fstat(descriptor), directory=True)[:2] != expected: | ||
| raise ValueError("workspace_changed_during_capture") | ||
| if not part: | ||
| canonical_repo = _windows_final_path(descriptor) | ||
| try: | ||
| observed = os.lstat(target) | ||
| except FileNotFoundError: | ||
| return None | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] 已有的 Git 元数据目录通过短名选中时,目标尚未创建会得到 baseline_created。目标出现后,源刷新成功,Jev 报 capture_failed、清空基线且无事件。没有读取被排除的字节。 在把文件记为缺失前,取最深已打开父目录句柄的规范相对路径,使用现有范围规则检查。保留普通未创建文件的正例。 原生 NTFS 用真实短名选中一个不存在的 .git 子项,init 应失败且无状态。用相同方法选择普通目录的缺失文件,创建后仍产生事件。 |
||
| expected_file = _windows_identity(observed) | ||
| with _windows_open(target) as stream: | ||
| if _windows_identity(os.fstat(stream.fileno())) != expected_file: | ||
| raise ValueError("workspace_changed_during_capture") | ||
| canonical = _windows_final_path(stream.fileno()) | ||
| if not canonical.is_relative_to(canonical_repo): | ||
| raise ValueError("scope_escapes_workspace") | ||
| validate_paths( | ||
| canonical_repo, [canonical.relative_to(canonical_repo).as_posix()] | ||
| ) | ||
| raw = stream.read(MAX_BYTES + 1) | ||
| opened = os.fstat(stream.fileno()) | ||
| if ( | ||
| _windows_identity(opened) != expected_file | ||
| or _windows_identity(os.lstat(target)) != expected_file | ||
| ): | ||
| raise ValueError("workspace_changed_during_capture") | ||
| return raw, opened.st_mode & 0o111 | ||
|
|
||
|
|
||
| def capture(repo: Path, paths: list[str]) -> dict[str, Any]: | ||
| if not hasattr(os, "O_NOFOLLOW"): | ||
| windows = os.name == "nt" and not hasattr(os, "O_NOFOLLOW") | ||
| if not windows and not hasattr(os, "O_NOFOLLOW"): | ||
| raise ValueError("unsupported_capture_platform") | ||
| repo = repo.resolve() | ||
| paths = validate_paths(repo, paths) | ||
|
|
@@ -73,15 +210,24 @@ def capture(repo: Path, paths: list[str]) -> dict[str, Any]: | |
| target = repo / name | ||
| if target.is_symlink() or not target.resolve().is_relative_to(repo): | ||
| raise ValueError("scope_escapes_workspace") | ||
| if not target.exists(): | ||
| files[name] = None | ||
| continue | ||
| if not target.is_file(): | ||
| raise ValueError("scope_requires_regular_files") | ||
| # O_NOFOLLOW also rejects a final-component symlink introduced after check. | ||
| with os.fdopen(os.open(target, os.O_RDONLY | os.O_NOFOLLOW), "rb") as stream: | ||
| raw = stream.read(MAX_BYTES + 1) | ||
| mode = os.fstat(stream.fileno()).st_mode & 0o111 | ||
| if windows: | ||
| captured = _windows_capture(repo, target) | ||
| if captured is None: | ||
| files[name] = None | ||
| continue | ||
| raw, mode = captured | ||
| else: | ||
| if not target.exists(): | ||
| files[name] = None | ||
| continue | ||
| if not target.is_file(): | ||
| raise ValueError("scope_requires_regular_files") | ||
| # O_NOFOLLOW also rejects a final-component symlink introduced after check. | ||
| with os.fdopen( | ||
| os.open(target, os.O_RDONLY | os.O_NOFOLLOW), "rb" | ||
| ) as stream: | ||
| raw = stream.read(MAX_BYTES + 1) | ||
| mode = os.fstat(stream.fileno()).st_mode & 0o111 | ||
| size += len(raw) | ||
| if size > MAX_BYTES or b"\0" in raw: | ||
| raise ValueError("oversized_or_binary_scope") | ||
|
|
||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[P2] 请把这个排除规则用于实际打开对象的规范路径。当前
resolve()只检查是否仍在工作区;两种 Windows 路径表示可能指向同一对象,但只有原始字符串受规则约束。隔离的名称解析对照得到不同采集结果。请加原生 Windows 负例,确认两种表示都在读取前拒绝,并保留普通文件正例。