tasklite-engine 3.0.0.dev0__py3-none-any.whl → 3.0.0.dev2__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.
Files changed (60) hide show
  1. tasklite/__init__.py +42 -18
  2. tasklite/__main__.py +205 -0
  3. tasklite/_report.py +562 -0
  4. tasklite/backend/__init__.py +19 -2
  5. tasklite/backend/base.py +327 -156
  6. tasklite/backend/memory.py +261 -339
  7. tasklite/backend/sqlite_backend.py +416 -488
  8. tasklite/edit.py +1276 -0
  9. tasklite/engine/__init__.py +6 -7
  10. tasklite/engine/_worker_bootstrap.py +221 -0
  11. tasklite/engine/_worker_runtime.py +229 -0
  12. tasklite/engine/admission.py +20 -114
  13. tasklite/engine/authorization.py +989 -0
  14. tasklite/engine/channel.py +531 -468
  15. tasklite/engine/completion.py +193 -275
  16. tasklite/engine/config.py +5 -11
  17. tasklite/engine/dispatch.py +299 -384
  18. tasklite/engine/governor.py +134 -69
  19. tasklite/engine/in_flight.py +20 -88
  20. tasklite/engine/launcher.py +1173 -0
  21. tasklite/engine/recovery.py +147 -100
  22. tasklite/engine/resource.py +50 -103
  23. tasklite/engine/runtime.py +158 -525
  24. tasklite/engine/scheduler.py +9 -46
  25. tasklite/engine/session.py +60 -15
  26. tasklite/engine/store.py +235 -462
  27. tasklite/engine/types.py +29 -40
  28. tasklite/engine/wait.py +8 -0
  29. tasklite/exceptions.py +0 -1
  30. tasklite/models/artifact.py +84 -62
  31. tasklite/models/context.py +37 -30
  32. tasklite/models/graph.py +114 -0
  33. tasklite/models/job.py +3 -5
  34. tasklite/models/records.py +482 -0
  35. tasklite/models/state.py +19 -125
  36. tasklite/models/trigger.py +63 -3
  37. tasklite/pipeline.py +92 -100
  38. tasklite/resource.py +79 -2
  39. tasklite/snapshot.py +608 -405
  40. tasklite/testing.py +424 -11
  41. tasklite/utils/artifact.py +1091 -179
  42. tasklite/utils/encoding.py +21 -40
  43. tasklite/utils/ipc.py +49 -1
  44. tasklite/utils/lockfile.py +50 -19
  45. tasklite/wrappers/__init__.py +1 -1
  46. tasklite/wrappers/discovery.py +13 -16
  47. tasklite/wrappers/http.py +77 -43
  48. {tasklite_engine-3.0.0.dev0.dist-info → tasklite_engine-3.0.0.dev2.dist-info}/METADATA +23 -16
  49. tasklite_engine-3.0.0.dev2.dist-info/RECORD +60 -0
  50. tasklite/contrib/__init__.py +0 -7
  51. tasklite/engine/execution_access.py +0 -39
  52. tasklite/engine/files.py +0 -52
  53. tasklite/engine/ops.py +0 -25
  54. tasklite/engine/selection.py +0 -186
  55. tasklite/hooks.py +0 -49
  56. tasklite/triggers.py +0 -47
  57. tasklite_engine-3.0.0.dev0.dist-info/RECORD +0 -58
  58. {tasklite_engine-3.0.0.dev0.dist-info → tasklite_engine-3.0.0.dev2.dist-info}/WHEEL +0 -0
  59. {tasklite_engine-3.0.0.dev0.dist-info → tasklite_engine-3.0.0.dev2.dist-info}/licenses/LICENSE +0 -0
  60. {tasklite_engine-3.0.0.dev0.dist-info → tasklite_engine-3.0.0.dev2.dist-info}/top_level.txt +0 -0
@@ -1,155 +1,449 @@
1
- """磁盘产物路径校验与不跟随链接的删除原语。
1
+ """跨平台统一路径策略(PathPolicy)与不跟随链接的安全清理原语。
2
2
 
3
- 删除要求 fd 相对操作能力;目录额外要求 Linux mountinfo。身份校验仅覆盖
4
- 单次删除操作,不保存声明期身份,也不承诺识别此前已完成的普通父目录替换。
3
+ 本模块是全引擎路径词法校验、前缀规范化、受保护路径派生与双向重叠拦截、
4
+ 授权层级冲突求值以及平台安全文件/目录清理的唯一真相源。
5
+
6
+ 平台安全边界:
7
+ - POSIX 适配器:依赖 ``dir_fd`` / ``O_NOFOLLOW`` / ``O_DIRECTORY``、
8
+ ``(st_dev, st_ino)`` 身份校验及 Linux ``/proc/self/mountinfo`` 挂载边界。
9
+ - Windows 适配器:仅调用 3 个无特权 ``kernel32`` 函数(``CreateFileW`` 省略
10
+ ``FILE_SHARE_DELETE`` 内核级钉锁父目录及递归子目录、
11
+ ``GetFileInformationByHandle`` 复核卷与文件索引、``CloseHandle``),结合
12
+ ``os.lstat`` 原生 ``st_file_attributes`` / ``st_reparse_tag`` 区分 symlink、
13
+ fail-closed 拒绝 NTFS Junction/卷挂载点与未知重解析点;不隐式移除只读位、
14
+ 不吞并文件占用错误(WinError 32 / WinError 5 原样传播)。
5
15
  """
6
16
  from __future__ import annotations
7
17
 
18
+ import ctypes
19
+ import ntpath
8
20
  import os
21
+ import posixpath
9
22
  import re
10
23
  import stat
11
24
  import sys
12
- from collections.abc import Callable
13
- from pathlib import Path
14
- from typing import Sequence
25
+ from abc import ABC, abstractmethod
26
+ from collections.abc import Callable, Sequence
27
+ from dataclasses import dataclass
28
+ from pathlib import Path, PurePath, PurePosixPath, PureWindowsPath
29
+ from typing import Any, Literal
15
30
 
16
- from ..models.artifact import ArtifactDeclaration
31
+ from .lockfile import lock_path_for
17
32
 
18
- _DIRECTORY_OPEN_FLAGS = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
33
+ PathKind = Literal["missing", "file", "directory", "broken_symlink"]
34
+ TargetType = Literal["file", "directory"]
35
+ InspectMode = Literal["strict", "pre_delete", "lookup"]
36
+ EntryClass = Literal[
37
+ "missing",
38
+ "file",
39
+ "directory",
40
+ "broken_symlink",
41
+ "live_symlink",
42
+ "mount_point",
43
+ "unsafe_reparse",
44
+ "unsupported",
45
+ ]
19
46
 
47
+ _DIRECTORY_OPEN_FLAGS = (
48
+ os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0)
49
+ )
20
50
 
21
- def _execute_pre_deletes(
22
- policy: "ArtifactPathPolicy",
23
- declarations: Sequence[ArtifactDeclaration],
24
- ) -> None:
25
- """按声明顺序执行前置删除;缺失目标由路径原语幂等吸收。"""
26
- for declaration in declarations:
27
- policy.remove_existing(declaration)
51
+ # Windows 文件属性与重解析点常量
52
+ _FILE_ATTRIBUTE_DIRECTORY = 0x00000010
53
+ _FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400
54
+ _IO_REPARSE_TAG_MOUNT_POINT = 0xa0000003
55
+ _IO_REPARSE_TAG_SYMLINK = 0xa000000c
56
+ _IO_REPARSE_TAG_NAME_SURROGATE_MASK = 0x20000000
57
+ _IO_REPARSE_TAG_DEDUP = 0x80000013
58
+ _IO_REPARSE_TAG_WOF = 0x80000017
59
+ _IO_REPARSE_TAG_CLOUD_MASK = 0xFFFF0000
60
+ _IO_REPARSE_TAG_CLOUD_PREFIX = 0x90000000
28
61
 
62
+ _FILE_READ_ATTRIBUTES = 0x00000080
63
+ _FILE_SHARE_READ = 0x00000001
64
+ _FILE_SHARE_WRITE = 0x00000002
65
+ _OPEN_EXISTING = 3
66
+ _FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000
67
+ _FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
68
+ _INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value
29
69
 
30
- class ArtifactPathPolicy:
31
- """路径范围配置;不登记全局所有权或持久执行阶段。"""
32
70
 
33
- def __init__(
34
- self,
35
- *,
36
- output_roots: str | Path | Sequence[str | Path] | None = None,
37
- protected_roots: Sequence[str | Path] = (),
38
- authorization_check: Callable[[str, str], bool] | None = None,
39
- ) -> None:
40
- if isinstance(output_roots, (str, Path)):
41
- output_roots = [output_roots]
42
- self.output_roots = tuple(Path(root).resolve() for root in (output_roots or ()))
43
- self.protected_roots = tuple(Path(root).resolve() for root in protected_roots)
44
- self._authorization_check = authorization_check
45
-
46
- def resolve(
47
- self, path: str | Path, *, sandbox: bool = True, delete_existing: bool = False,
48
- ) -> str:
49
- """返回受允许的规范路径;仅前删可接受断链,不授权链接指向的目标。"""
50
- return self._resolve(path, sandbox=sandbox, allow_leaf_symlink=delete_existing)
51
-
52
- def _resolve(
71
+ @dataclass(frozen=True)
72
+ class InspectedPath:
73
+ """路径策略检查结果值对象。"""
74
+
75
+ canonical_path: str
76
+ comparison_key: str
77
+ kind: PathKind
78
+
79
+ @property
80
+ def exists(self) -> bool:
81
+ return self.kind != "missing"
82
+
83
+ @property
84
+ def target_type(self) -> TargetType:
85
+ return "directory" if self.kind == "directory" else "file"
86
+
87
+
88
+ @dataclass(frozen=True)
89
+ class AuthorizationMatch:
90
+ """纯内存授权匹配与冲突求值结果。"""
91
+
92
+ covered: bool
93
+ grant_conflict: str | None
94
+ exact_path: str | None
95
+
96
+
97
+ @dataclass(frozen=True)
98
+ class EntryInspection:
99
+ """适配器对单个目录项(绝不跟随叶链接)的底层探测结果。"""
100
+
101
+ entry_class: EntryClass
102
+ is_dir_symlink: bool = False
103
+
104
+
105
+ # ── 跨平台纯词法与路径段元组工具 ──────────────────────────────────────────
106
+
107
+
108
+ def _is_safe_windows_data_reparse_tag(tag: int) -> bool:
109
+ """仅放行非名称代理的已知数据重解析点(OneDrive Cloud / Dedup / WOF)。"""
110
+ if tag & _IO_REPARSE_TAG_NAME_SURROGATE_MASK:
111
+ return False
112
+ if tag in (_IO_REPARSE_TAG_DEDUP, _IO_REPARSE_TAG_WOF):
113
+ return True
114
+ if (tag & _IO_REPARSE_TAG_CLOUD_MASK) == _IO_REPARSE_TAG_CLOUD_PREFIX:
115
+ return True
116
+ return False
117
+
118
+
119
+ def _strip_windows_extended_prefix(path_str: str) -> str:
120
+ """剥离 Win32 扩展长度前缀 ``\\\\?\\`` 并规范盘符为大写。"""
121
+ result = path_str
122
+ if result.startswith("\\\\?\\"):
123
+ body = result[4:]
124
+ if body.upper().startswith("UNC\\"):
125
+ result = "\\\\" + body[4:]
126
+ else:
127
+ result = body
128
+ if len(result) >= 2 and result[1] == ":" and result[0].isalpha():
129
+ result = result[0].upper() + result[1:]
130
+ return result
131
+
132
+
133
+ def is_platform_abs_path(
134
+ norm_path: str,
135
+ *,
136
+ is_windows: bool | None = None,
137
+ ) -> bool:
138
+ """判断词法规范化后的路径是否为目标平台绝对路径(Windows 需盘符根或 UNC)。"""
139
+ win = (os.name == "nt") if is_windows is None else is_windows
140
+ if win:
141
+ drive, tail = ntpath.splitdrive(norm_path)
142
+ return bool(drive) and tail.startswith("\\")
143
+ return norm_path.startswith("/")
144
+
145
+
146
+ def validate_and_normalize_lexical(
147
+ path: str | Path,
148
+ *,
149
+ is_windows: bool | None = None,
150
+ ) -> str:
151
+ """校验路径词法边界(拒空串/空字节/Windows 盘符相对/无盘符根相对/设备路径)。"""
152
+ win = (os.name == "nt") if is_windows is None else is_windows
153
+ if not isinstance(path, (str, os.PathLike)):
154
+ raise ValueError("artifact path must be a non-empty path without null bytes")
155
+ raw = os.fspath(path)
156
+ if not isinstance(raw, str) or not raw or "\x00" in raw:
157
+ raise ValueError("artifact path must be a non-empty path without null bytes")
158
+
159
+ if not win:
160
+ norm = posixpath.normpath(raw)
161
+ if norm.startswith("//"):
162
+ norm = "/" + norm.lstrip("/")
163
+ return norm
164
+
165
+ slash_norm = raw.replace("/", "\\")
166
+ lower = slash_norm.lower()
167
+ if lower.startswith("\\\\.\\") or lower.startswith("\\??\\"):
168
+ raise ValueError(f"device path is not allowed: {raw!r}")
169
+ if lower.startswith("\\\\?\\"):
170
+ body = slash_norm[4:]
171
+ if body.lower().startswith("unc\\"):
172
+ slash_norm = "\\\\" + body[4:]
173
+ elif len(body) >= 3 and body[0].isalpha() and body[1] == ":" and body[2] == "\\":
174
+ slash_norm = body
175
+ else:
176
+ raise ValueError(f"device path is not allowed: {raw!r}")
177
+
178
+ drive, tail = ntpath.splitdrive(slash_norm)
179
+ if drive:
180
+ if not drive.startswith("\\\\") and not tail.startswith("\\"):
181
+ raise ValueError(f"drive-relative path is not allowed: {raw!r}")
182
+ elif slash_norm.startswith("\\"):
183
+ raise ValueError(f"root-relative path without drive is not allowed: {raw!r}")
184
+
185
+ norm = ntpath.normpath(slash_norm)
186
+ return _strip_windows_extended_prefix(norm)
187
+
188
+
189
+ def resolve_lexical_path(
190
+ path: str | Path,
191
+ base_dir: str | Path,
192
+ *,
193
+ is_windows: bool | None = None,
194
+ ) -> str:
195
+ """按固定基准目录将路径解析为词法规范绝对路径(不触碰磁盘)。"""
196
+ win = (os.name == "nt") if is_windows is None else is_windows
197
+ norm = validate_and_normalize_lexical(path, is_windows=win)
198
+ base_norm = validate_and_normalize_lexical(base_dir, is_windows=win)
199
+ if win:
200
+ path_drive, path_tail = ntpath.splitdrive(norm)
201
+ if path_drive.startswith("\\\\") and not path_tail:
202
+ return f"{path_drive}\\"
203
+ if not is_platform_abs_path(base_norm, is_windows=True):
204
+ base_norm = _strip_windows_extended_prefix(
205
+ ntpath.normpath(os.path.abspath(base_norm).replace("/", "\\"))
206
+ )
207
+ if is_platform_abs_path(norm, is_windows=True):
208
+ return norm
209
+ return _join_platform_path(base_norm, (norm,), is_windows=True)
210
+
211
+ if not is_platform_abs_path(base_norm, is_windows=False):
212
+ base_norm = posixpath.normpath(os.path.abspath(base_norm))
213
+ if base_norm.startswith("//"):
214
+ base_norm = "/" + base_norm.lstrip("/")
215
+ if is_platform_abs_path(norm, is_windows=False):
216
+ return norm
217
+ return _join_platform_path(base_norm, (norm,), is_windows=False)
218
+
219
+
220
+ def _comparison_key_for_path(path_str: str, *, is_windows: bool) -> str:
221
+ """生成跨调用一致的平台比较键(Windows 统一小写与反斜杠,POSIX 保原样)。"""
222
+ if is_windows:
223
+ normalized = _strip_windows_extended_prefix(ntpath.normpath(path_str.replace("/", "\\")))
224
+ return normalized.lower()
225
+ normalized = posixpath.normpath(path_str)
226
+ if normalized.startswith("//"):
227
+ normalized = "/" + normalized.lstrip("/")
228
+ return normalized
229
+
230
+
231
+ def _path_parts(comparison_key: str, *, is_windows: bool) -> tuple[str, ...]:
232
+ """按平台 PurePath 拆分路径段元组,禁止字符串前缀误匹配。"""
233
+ if is_windows:
234
+ return PureWindowsPath(comparison_key).parts
235
+ return PurePosixPath(comparison_key).parts
236
+
237
+
238
+ def _parts_overlap(first: tuple[str, ...], second: tuple[str, ...]) -> bool:
239
+ """双向段元组前缀重叠判定(相等、父子、子父均返回 True)。"""
240
+ if not first or not second:
241
+ return False
242
+ shorter = min(len(first), len(second))
243
+ return first[:shorter] == second[:shorter]
244
+
245
+
246
+ def _is_root_path(path_str: str, *, is_windows: bool) -> bool:
247
+ """判断路径是否为文件系统根、Windows 盘符根或 UNC 共享根。"""
248
+ pure: PurePath = PureWindowsPath(path_str) if is_windows else PurePosixPath(path_str)
249
+ return pure.parent == pure
250
+
251
+
252
+ def _join_platform_path(base: str, parts: Sequence[str], *, is_windows: bool) -> str:
253
+ if is_windows:
254
+ return _strip_windows_extended_prefix(ntpath.normpath(ntpath.join(base, *parts)))
255
+ joined = posixpath.normpath(posixpath.join(base, *parts))
256
+ if joined.startswith("//"):
257
+ joined = "/" + joined.lstrip("/")
258
+ return joined
259
+
260
+
261
+ def _split_parent_and_name(path_str: str, *, is_windows: bool) -> tuple[str, str]:
262
+ pure: PurePath = PureWindowsPath(path_str) if is_windows else PurePosixPath(path_str)
263
+ return str(pure.parent), pure.name
264
+
265
+
266
+ def derive_protected_paths(
267
+ state_path: str | Path | None,
268
+ protected_roots: Sequence[str | Path] = (),
269
+ ) -> tuple[Path, ...]:
270
+ """由状态库路径单点派生全部 5 项受保护内部路径并合并额外受保护根。"""
271
+ derived: list[Path] = []
272
+ if state_path is not None:
273
+ sp = Path(state_path)
274
+ sp_str = str(sp)
275
+ derived.extend(
276
+ (
277
+ sp,
278
+ Path(f"{sp_str}-wal"),
279
+ Path(f"{sp_str}-shm"),
280
+ Path(f"{sp_str}-journal"),
281
+ lock_path_for(sp),
282
+ )
283
+ )
284
+ for root in protected_roots:
285
+ derived.append(Path(root))
286
+ return tuple(derived)
287
+
288
+
289
+ def evaluate_authorization(
290
+ existing: Sequence[tuple[str, TargetType]],
291
+ target: str | InspectedPath,
292
+ target_type: TargetType | None = None,
293
+ *,
294
+ is_windows: bool | None = None,
295
+ ) -> AuthorizationMatch:
296
+ """纯内存授权匹配与冲突求值(基于平台比较键的 PurePath.parts 元组)。
297
+
298
+ 规则:
299
+ - ``exact_path``:命中的既有存储主键 ``path``(用于精确撤销及 Windows 大小写原地覆盖)。
300
+ - ``covered``:同键且同类型,或存在任意 ``"directory"`` 祖先。
301
+ - ``grant_conflict``:同键重复(无论类型是否相同)、存在 ``"file"`` 祖先、
302
+ 或候选为 ``"file"`` 且存在任意子路径授权;父子目录嵌套及目录下文件授权均允许。
303
+ """
304
+ win = (os.name == "nt") if is_windows is None else is_windows
305
+ if isinstance(target, InspectedPath):
306
+ target_key = target.comparison_key
307
+ effective_type: TargetType | None = (
308
+ target_type if target_type is not None else target.target_type
309
+ )
310
+ else:
311
+ target_key = _comparison_key_for_path(os.fspath(target), is_windows=win)
312
+ effective_type = target_type
313
+
314
+ target_parts = _path_parts(target_key, is_windows=win)
315
+ covered = False
316
+ grant_conflict: str | None = None
317
+ exact_path: str | None = None
318
+
319
+ for existing_path, existing_type in existing:
320
+ ex_key = _comparison_key_for_path(existing_path, is_windows=win)
321
+ ex_parts = _path_parts(ex_key, is_windows=win)
322
+
323
+ if ex_parts == target_parts:
324
+ exact_path = existing_path
325
+ if effective_type is not None and (
326
+ existing_type == effective_type or existing_type == "directory"
327
+ ):
328
+ covered = True
329
+ if grant_conflict is None:
330
+ grant_conflict = (
331
+ f"Authorization already exists for path {existing_path!r} "
332
+ f"(target_type={existing_type!r})"
333
+ )
334
+ elif len(ex_parts) < len(target_parts) and target_parts[: len(ex_parts)] == ex_parts:
335
+ if existing_type == "directory":
336
+ covered = True
337
+ elif existing_type == "file" and grant_conflict is None:
338
+ grant_conflict = (
339
+ f"Cannot authorize path under existing file authorization "
340
+ f"{existing_path!r}"
341
+ )
342
+ elif len(target_parts) < len(ex_parts) and ex_parts[: len(target_parts)] == target_parts:
343
+ if effective_type == "file" and grant_conflict is None:
344
+ grant_conflict = (
345
+ f"Cannot authorize path as 'file' because descendant authorization "
346
+ f"{existing_path!r} already exists"
347
+ )
348
+
349
+ return AuthorizationMatch(
350
+ covered=covered,
351
+ grant_conflict=grant_conflict,
352
+ exact_path=exact_path,
353
+ )
354
+
355
+
356
+ # ── 内部平台文件系统 Seam(POSIX / Windows / 测试 Fake Adapter)───────────
357
+
358
+
359
+ class FilesystemAdapter(ABC):
360
+ """路径规范化与安全清理的内部平台 Seam。"""
361
+
362
+ is_windows: bool
363
+
364
+ @abstractmethod
365
+ def path_lexists(self, path: str) -> bool:
366
+ """非跟随判断路径是否存在(权限错误必须原样传播)。"""
367
+
368
+ @abstractmethod
369
+ def realpath(self, path: str) -> str:
370
+ """解析已存在前缀的真实规范路径(展开父级链接/Junction/8.3 短名并剥离前缀)。"""
371
+
372
+ @abstractmethod
373
+ def inspect_entry(self, path: str) -> EntryInspection:
374
+ """非跟随探测单个路径的形态分类(缺失返回 missing,权限错误原样传播)。"""
375
+
376
+ @abstractmethod
377
+ def recover_leaf_case(self, canonical_parent: str, leaf_name: str) -> str:
378
+ """在叶已存在且非链接/重解析点时回收平台真实大小写。"""
379
+
380
+ @abstractmethod
381
+ def delete_target(
53
382
  self,
54
- path: str | Path,
383
+ target: str,
55
384
  *,
56
- sandbox: bool,
57
- allow_leaf_symlink: bool,
58
- ) -> str:
59
- raw = os.fspath(path)
60
- if not isinstance(raw, str) or not raw or "\x00" in raw:
61
- raise ValueError("artifact path must be a non-empty path without null bytes")
62
- target = Path(raw)
63
- if not target.is_absolute() and sandbox and self.output_roots:
64
- target = self.output_roots[0] / target
65
- target = Path(os.path.abspath(target))
66
- try:
67
- leaf = os.lstat(target)
68
- except FileNotFoundError:
69
- leaf = None
70
- if leaf is not None and stat.S_ISLNK(leaf.st_mode):
71
- if not allow_leaf_symlink:
72
- raise ValueError(f"artifact leaf must not be a symlink: {target}")
73
- try:
74
- os.stat(target)
75
- except FileNotFoundError:
76
- pass
77
- except OSError as error:
78
- raise ValueError(f"cannot inspect artifact leaf: {target}") from error
79
- else:
80
- raise ValueError(f"artifact leaf must not be a symlink: {target}")
81
- try:
82
- target = target.parent.resolve() / target.name
83
- except RuntimeError as error:
84
- raise ValueError(f"cannot resolve artifact path: {target}") from error
85
- else:
86
- try:
87
- target = target.resolve()
88
- except RuntimeError as error:
89
- raise ValueError(f"cannot resolve artifact path: {target}") from error
90
- if sandbox and self.output_roots and not any(
91
- target.is_relative_to(root) for root in self.output_roots
92
- ):
93
- raise ValueError(f"artifact path is outside output roots: {target}")
94
- if target.parent == target:
95
- raise ValueError(f"filesystem root cannot be an artifact: {target}")
96
- for root in self.output_roots:
97
- if root.is_relative_to(target):
98
- raise ValueError(f"artifact must not cover an output root: {target}")
99
- for root in self.protected_roots:
100
- if root.is_relative_to(target) or target.is_relative_to(root):
101
- raise ValueError(f"artifact overlaps a protected root: {target}")
102
- return str(target)
103
-
104
- def remove_existing(self, declaration: ArtifactDeclaration) -> None:
105
- """仅以前删授权删除已有对象,其他清理权限不代替该授权。"""
106
- target = self._target(declaration, allow_leaf_symlink=True)
107
- if not self._exists(target):
108
- return
109
- if not declaration.delete_existing:
110
- raise FileExistsError(str(target))
111
- self._remove(target, declaration, allow_leaf_symlink=True)
112
-
113
- def cleanup(self, declaration: ArtifactDeclaration, *, success: bool) -> None:
114
- """只应用指定结局的清理授权,缺失路径视为已移除。"""
115
- if type(success) is not bool:
116
- raise TypeError("success must be a bool")
117
- authorized = declaration.delete_on_success if success else declaration.delete_on_failure
118
- if authorized:
119
- target = self._target(declaration)
120
- if self._exists(target):
121
- self._remove(target, declaration)
122
-
123
- def entry_exists(self, declaration: ArtifactDeclaration) -> bool:
124
- """以非跟随方式判断声明目标是否存在;访问错误不降级为缺失。"""
125
- return self._exists(self._target(declaration))
385
+ allow_broken_leaf_symlink: bool,
386
+ revalidate: Callable[[], None],
387
+ authorize: Callable[[str, TargetType], bool] | None,
388
+ ) -> bool:
389
+ """在父目录锁保护下核验身份、复核授权并执行非跟随单对象或安全递归删除。"""
126
390
 
127
- @staticmethod
128
- def _exists(target: Path) -> bool:
391
+
392
+ class PosixFilesystemAdapter(FilesystemAdapter):
393
+ """POSIX / Linux 适配器:完整保留 dir_fd / O_NOFOLLOW / O_DIRECTORY 与 mountinfo。"""
394
+
395
+ is_windows = False
396
+
397
+ def path_lexists(self, path: str) -> bool:
129
398
  try:
130
- os.lstat(target)
399
+ os.lstat(path)
131
400
  return True
132
- except FileNotFoundError:
401
+ except (FileNotFoundError, NotADirectoryError):
133
402
  return False
134
403
 
135
- def _target(
136
- self,
137
- declaration: ArtifactDeclaration,
138
- *,
139
- allow_leaf_symlink: bool = False,
140
- ) -> Path:
141
- target = self._resolve(
142
- declaration.path,
143
- sandbox=declaration.sandbox,
144
- allow_leaf_symlink=allow_leaf_symlink,
145
- )
146
- if target != declaration.path:
147
- raise ValueError(f"artifact parent path changed: {declaration.path}")
148
- return Path(target)
404
+ def realpath(self, path: str) -> str:
405
+ try:
406
+ resolved = os.path.realpath(path)
407
+ except RuntimeError as error:
408
+ raise ValueError(f"cannot resolve artifact path: {path}") from error
409
+ if resolved.startswith("//"):
410
+ resolved = "/" + resolved.lstrip("/")
411
+ return resolved
412
+
413
+ def inspect_entry(self, path: str) -> EntryInspection:
414
+ try:
415
+ st = os.lstat(path)
416
+ except (FileNotFoundError, NotADirectoryError):
417
+ return EntryInspection("missing")
418
+ return self._classify_stat(st, path)
419
+
420
+ @staticmethod
421
+ def _classify_stat(st: os.stat_result, path: str) -> EntryInspection:
422
+ if stat.S_ISLNK(st.st_mode):
423
+ try:
424
+ os.stat(path)
425
+ except FileNotFoundError:
426
+ return EntryInspection("broken_symlink")
427
+ except OSError as error:
428
+ raise ValueError(f"cannot inspect artifact leaf: {path}") from error
429
+ return EntryInspection("live_symlink")
430
+ if getattr(st, "st_file_attributes", 0) & _FILE_ATTRIBUTE_REPARSE_POINT:
431
+ return EntryInspection("unsafe_reparse")
432
+ if stat.S_ISDIR(st.st_mode):
433
+ return EntryInspection("directory")
434
+ if stat.S_ISREG(st.st_mode):
435
+ return EntryInspection("file")
436
+ return EntryInspection("unsupported")
437
+
438
+ def recover_leaf_case(self, canonical_parent: str, leaf_name: str) -> str:
439
+ return _join_platform_path(canonical_parent, (leaf_name,), is_windows=False)
149
440
 
150
441
  @staticmethod
151
442
  def _require_relative_operations() -> None:
152
- if not all(operation in os.supports_dir_fd for operation in (os.open, os.stat, os.unlink, os.rmdir)):
443
+ if not all(
444
+ operation in os.supports_dir_fd
445
+ for operation in (os.open, os.stat, os.unlink, os.rmdir)
446
+ ):
153
447
  raise NotImplementedError("safe directory-relative artifact deletion is unavailable")
154
448
  if os.listdir not in os.supports_fd:
155
449
  raise NotImplementedError("safe directory enumeration is unavailable")
@@ -160,52 +454,6 @@ class ArtifactPathPolicy:
160
454
  def _same_object(first: os.stat_result, second: os.stat_result) -> bool:
161
455
  return (first.st_dev, first.st_ino) == (second.st_dev, second.st_ino)
162
456
 
163
- def _remove(
164
- self,
165
- target: Path,
166
- declaration: ArtifactDeclaration,
167
- *,
168
- allow_leaf_symlink: bool = False,
169
- ) -> None:
170
- self._require_relative_operations()
171
- before = target.parent.stat(follow_symlinks=False)
172
- parent_fd = os.open(target.parent, _DIRECTORY_OPEN_FLAGS)
173
- try:
174
- if not self._same_object(before, os.fstat(parent_fd)):
175
- raise ValueError(f"artifact parent identity changed: {target.parent}")
176
- self._target(declaration, allow_leaf_symlink=allow_leaf_symlink)
177
- try:
178
- entry = os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False)
179
- except FileNotFoundError:
180
- return
181
-
182
- target_type = "directory" if stat.S_ISDIR(entry.st_mode) else "file"
183
- if self._authorization_check is not None and not self._authorization_check(
184
- str(target), target_type,
185
- ):
186
- raise PermissionError(f"artifact authorization scope changed before deletion: {target}")
187
-
188
- if stat.S_ISDIR(entry.st_mode):
189
- if any(point.is_relative_to(target) for point in self._mount_points()):
190
- raise ValueError(f"artifact directory contains a mount: {target}")
191
-
192
- def guard() -> None:
193
- self._target(declaration, allow_leaf_symlink=allow_leaf_symlink)
194
- if not self._same_object(before, target.parent.stat(follow_symlinks=False)):
195
- raise ValueError(f"artifact parent identity changed: {target.parent}")
196
- current = os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False)
197
- if not self._same_object(entry, current):
198
- raise ValueError(f"artifact identity changed during deletion: {target}")
199
-
200
- self._remove_at(
201
- parent_fd,
202
- target,
203
- guard,
204
- allow_symlink=allow_leaf_symlink,
205
- )
206
- finally:
207
- os.close(parent_fd)
208
-
209
457
  @staticmethod
210
458
  def _mount_points() -> tuple[Path, ...]:
211
459
  """Linux 挂载表包含同设备 bind mount;无法确认边界时拒绝递归。"""
@@ -231,8 +479,62 @@ class ArtifactPathPolicy:
231
479
  except (OSError, UnicodeError, ValueError) as error:
232
480
  raise NotImplementedError("cannot establish artifact mount boundaries") from error
233
481
 
482
+ def delete_target(
483
+ self,
484
+ target: str,
485
+ *,
486
+ allow_broken_leaf_symlink: bool,
487
+ revalidate: Callable[[], None],
488
+ authorize: Callable[[str, TargetType], bool] | None,
489
+ ) -> bool:
490
+ self._require_relative_operations()
491
+ target_path = Path(target)
492
+ before = target_path.parent.stat(follow_symlinks=False)
493
+ parent_fd = os.open(target_path.parent, _DIRECTORY_OPEN_FLAGS)
494
+ try:
495
+ if not self._same_object(before, os.fstat(parent_fd)):
496
+ raise ValueError(f"artifact parent identity changed: {target_path.parent}")
497
+ revalidate()
498
+ try:
499
+ entry = os.stat(target_path.name, dir_fd=parent_fd, follow_symlinks=False)
500
+ except FileNotFoundError:
501
+ return False
502
+
503
+ target_type: TargetType = "directory" if stat.S_ISDIR(entry.st_mode) else "file"
504
+ if authorize is not None and not authorize(str(target_path), target_type):
505
+ raise PermissionError(
506
+ f"artifact authorization scope changed before deletion: {target_path}"
507
+ )
508
+
509
+ if stat.S_ISDIR(entry.st_mode):
510
+ if any(point.is_relative_to(target_path) for point in self._mount_points()):
511
+ raise ValueError(f"artifact directory contains a mount: {target_path}")
512
+
513
+ def guard() -> None:
514
+ revalidate()
515
+ if not self._same_object(before, target_path.parent.stat(follow_symlinks=False)):
516
+ raise ValueError(f"artifact parent identity changed: {target_path.parent}")
517
+ current = os.stat(target_path.name, dir_fd=parent_fd, follow_symlinks=False)
518
+ if not self._same_object(entry, current):
519
+ raise ValueError(f"artifact identity changed during deletion: {target_path}")
520
+
521
+ self._remove_at(
522
+ parent_fd,
523
+ target_path,
524
+ guard,
525
+ allow_symlink=allow_broken_leaf_symlink,
526
+ )
527
+ return True
528
+ finally:
529
+ os.close(parent_fd)
530
+
234
531
  def _remove_at(
235
- self, parent_fd: int, target: Path, guard: Callable[[], None], *, allow_symlink: bool,
532
+ self,
533
+ parent_fd: int,
534
+ target: Path,
535
+ guard: Callable[[], None],
536
+ *,
537
+ allow_symlink: bool,
236
538
  ) -> None:
237
539
  guard()
238
540
  parent_now = target.parent.stat(follow_symlinks=False)
@@ -242,21 +544,21 @@ class ArtifactPathPolicy:
242
544
  if stat.S_ISLNK(entry.st_mode):
243
545
  if not allow_symlink:
244
546
  raise ValueError(f"artifact leaf must not be a symlink: {target}")
245
- elif getattr(entry, "st_file_attributes", 0) & 0x400:
547
+ elif getattr(entry, "st_file_attributes", 0) & _FILE_ATTRIBUTE_REPARSE_POINT:
246
548
  raise ValueError(f"artifact contains an unsafe reparse point: {target}")
247
549
  elif stat.S_ISDIR(entry.st_mode):
248
550
  if entry.st_dev != os.fstat(parent_fd).st_dev or os.path.ismount(target):
249
551
  raise ValueError(f"artifact deletion must not cross a mount: {target}")
250
- child_fd = os.open(target.name, _DIRECTORY_OPEN_FLAGS,
251
- dir_fd=parent_fd)
552
+ child_fd = os.open(target.name, _DIRECTORY_OPEN_FLAGS, dir_fd=parent_fd)
252
553
  try:
253
554
  if not self._same_object(entry, os.fstat(child_fd)):
254
555
  raise ValueError(f"artifact directory identity changed: {target}")
255
556
  for name in os.listdir(child_fd):
256
557
  self._remove_at(child_fd, target / name, guard, allow_symlink=True)
257
558
  guard()
258
- if not self._same_object(entry, os.stat(target.name, dir_fd=parent_fd,
259
- follow_symlinks=False)):
559
+ if not self._same_object(
560
+ entry, os.stat(target.name, dir_fd=parent_fd, follow_symlinks=False)
561
+ ):
260
562
  raise ValueError(f"artifact directory identity changed: {target}")
261
563
  os.rmdir(target.name, dir_fd=parent_fd)
262
564
  finally:
@@ -269,3 +571,613 @@ class ArtifactPathPolicy:
269
571
  if not self._same_object(entry, current):
270
572
  raise ValueError(f"artifact identity changed during deletion: {target}")
271
573
  os.unlink(target.name, dir_fd=parent_fd)
574
+
575
+
576
+ # ── Windows 适配器(仅 3 个无特权 kernel32 函数,显式 64 位安全签名)────
577
+
578
+
579
+ if sys.platform == "win32":
580
+ from ctypes import wintypes
581
+
582
+ class _FILETIME(ctypes.Structure):
583
+ _fields_ = [
584
+ ("dwLowDateTime", wintypes.DWORD),
585
+ ("dwHighDateTime", wintypes.DWORD),
586
+ ]
587
+
588
+ class _BY_HANDLE_FILE_INFORMATION(ctypes.Structure):
589
+ _fields_ = [
590
+ ("dwFileAttributes", wintypes.DWORD),
591
+ ("ftCreationTime", _FILETIME),
592
+ ("ftLastAccessTime", _FILETIME),
593
+ ("ftLastWriteTime", _FILETIME),
594
+ ("dwVolumeSerialNumber", wintypes.DWORD),
595
+ ("nFileSizeHigh", wintypes.DWORD),
596
+ ("nFileSizeLow", wintypes.DWORD),
597
+ ("nNumberOfLinks", wintypes.DWORD),
598
+ ("nFileIndexHigh", wintypes.DWORD),
599
+ ("nFileIndexLow", wintypes.DWORD),
600
+ ]
601
+
602
+ _kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
603
+ _kernel32.CreateFileW.argtypes = [
604
+ wintypes.LPCWSTR,
605
+ wintypes.DWORD,
606
+ wintypes.DWORD,
607
+ ctypes.c_void_p,
608
+ wintypes.DWORD,
609
+ wintypes.DWORD,
610
+ wintypes.HANDLE,
611
+ ]
612
+ _kernel32.CreateFileW.restype = wintypes.HANDLE
613
+
614
+ _kernel32.GetFileInformationByHandle.argtypes = [
615
+ wintypes.HANDLE,
616
+ ctypes.POINTER(_BY_HANDLE_FILE_INFORMATION),
617
+ ]
618
+ _kernel32.GetFileInformationByHandle.restype = wintypes.BOOL
619
+
620
+ _kernel32.CloseHandle.argtypes = [wintypes.HANDLE]
621
+ _kernel32.CloseHandle.restype = wintypes.BOOL
622
+
623
+
624
+ def _classify_windows_stat(st: os.stat_result, path: str) -> EntryInspection:
625
+ """按 Windows st_file_attributes 与 st_reparse_tag 分类单个目录项。"""
626
+ attrs = getattr(st, "st_file_attributes", 0)
627
+ reparse_tag = getattr(st, "st_reparse_tag", 0)
628
+ is_dir_attr = bool(attrs & _FILE_ATTRIBUTE_DIRECTORY)
629
+
630
+ if attrs & _FILE_ATTRIBUTE_REPARSE_POINT:
631
+ if reparse_tag == _IO_REPARSE_TAG_SYMLINK:
632
+ try:
633
+ os.stat(path)
634
+ except FileNotFoundError:
635
+ return EntryInspection("broken_symlink", is_dir_symlink=is_dir_attr)
636
+ except OSError as error:
637
+ raise ValueError(f"cannot inspect artifact leaf: {path}") from error
638
+ return EntryInspection("live_symlink", is_dir_symlink=is_dir_attr)
639
+ if reparse_tag == _IO_REPARSE_TAG_MOUNT_POINT:
640
+ return EntryInspection("mount_point")
641
+ if (
642
+ _is_safe_windows_data_reparse_tag(reparse_tag)
643
+ and stat.S_ISREG(st.st_mode)
644
+ and not is_dir_attr
645
+ ):
646
+ return EntryInspection("file")
647
+ return EntryInspection("unsafe_reparse")
648
+
649
+ if stat.S_ISLNK(st.st_mode):
650
+ try:
651
+ os.stat(path)
652
+ except FileNotFoundError:
653
+ return EntryInspection("broken_symlink", is_dir_symlink=is_dir_attr)
654
+ except OSError as error:
655
+ raise ValueError(f"cannot inspect artifact leaf: {path}") from error
656
+ return EntryInspection("live_symlink", is_dir_symlink=is_dir_attr)
657
+
658
+ if stat.S_ISDIR(st.st_mode):
659
+ return EntryInspection("directory")
660
+ if stat.S_ISREG(st.st_mode):
661
+ return EntryInspection("file")
662
+ return EntryInspection("unsupported")
663
+
664
+
665
+ class WindowsFilesystemAdapter(FilesystemAdapter):
666
+ """Windows 适配器:CreateFileW 省略 FILE_SHARE_DELETE 内核钉锁父目录 + lstat 分类。"""
667
+
668
+ is_windows = True
669
+
670
+ def path_lexists(self, path: str) -> bool:
671
+ try:
672
+ os.lstat(path)
673
+ return True
674
+ except (FileNotFoundError, NotADirectoryError):
675
+ return False
676
+
677
+ def realpath(self, path: str) -> str:
678
+ try:
679
+ resolved = os.path.realpath(path)
680
+ except RuntimeError as error:
681
+ raise ValueError(f"cannot resolve artifact path: {path}") from error
682
+ return _strip_windows_extended_prefix(ntpath.normpath(resolved))
683
+
684
+ def inspect_entry(self, path: str) -> EntryInspection:
685
+ try:
686
+ st = os.lstat(path)
687
+ except (FileNotFoundError, NotADirectoryError):
688
+ return EntryInspection("missing")
689
+ return _classify_windows_stat(st, path)
690
+
691
+ def recover_leaf_case(self, canonical_parent: str, leaf_name: str) -> str:
692
+ candidate = _join_platform_path(canonical_parent, (leaf_name,), is_windows=True)
693
+ try:
694
+ resolved = self.realpath(candidate)
695
+ except (OSError, ValueError):
696
+ return candidate
697
+ res_parent, res_name = _split_parent_and_name(resolved, is_windows=True)
698
+ if _comparison_key_for_path(res_parent, is_windows=True) == _comparison_key_for_path(
699
+ canonical_parent, is_windows=True
700
+ ):
701
+ return _join_platform_path(canonical_parent, (res_name,), is_windows=True)
702
+ return candidate
703
+
704
+ @staticmethod
705
+ def _same_lstat(first: os.stat_result, second: os.stat_result) -> bool:
706
+ return (first.st_dev, first.st_ino) == (second.st_dev, second.st_ino)
707
+
708
+ @staticmethod
709
+ def _open_pinned_directory(path: str) -> int:
710
+ """以省略 FILE_SHARE_DELETE 的句柄钉锁目录,防止清理期间被重命名或移走。"""
711
+ if sys.platform != "win32":
712
+ raise NotImplementedError("WindowsFilesystemAdapter requires Windows")
713
+ handle = _kernel32.CreateFileW(
714
+ path,
715
+ _FILE_READ_ATTRIBUTES,
716
+ _FILE_SHARE_READ | _FILE_SHARE_WRITE,
717
+ None,
718
+ _OPEN_EXISTING,
719
+ _FILE_FLAG_BACKUP_SEMANTICS | _FILE_FLAG_OPEN_REPARSE_POINT,
720
+ None,
721
+ )
722
+ if handle is None or handle == _INVALID_HANDLE_VALUE:
723
+ err = ctypes.get_last_error()
724
+ raise ctypes.WinError(err)
725
+ return int(handle)
726
+
727
+ @staticmethod
728
+ def _close_handle(handle: int) -> None:
729
+ if sys.platform == "win32":
730
+ _kernel32.CloseHandle(handle)
731
+
732
+ @staticmethod
733
+ def _get_handle_info(handle: int) -> tuple[int, int, int]:
734
+ """读取句柄的 (dwFileAttributes, dwVolumeSerialNumber, nFileIndex64)。"""
735
+ if sys.platform != "win32":
736
+ raise NotImplementedError("WindowsFilesystemAdapter requires Windows")
737
+ info = _BY_HANDLE_FILE_INFORMATION()
738
+ if not _kernel32.GetFileInformationByHandle(handle, ctypes.byref(info)):
739
+ err = ctypes.get_last_error()
740
+ raise ctypes.WinError(err)
741
+ file_index = (info.nFileIndexHigh << 32) | info.nFileIndexLow
742
+ return (int(info.dwFileAttributes), int(info.dwVolumeSerialNumber), int(file_index))
743
+
744
+ @classmethod
745
+ def _verify_pinned_dir(
746
+ cls,
747
+ handle: int,
748
+ expected_lstat: os.stat_result,
749
+ path: str,
750
+ ) -> None:
751
+ """校验钉锁句柄仍指向同一常规非重解析目录。
752
+
753
+ 注:Python 3.12+ 在 Windows 上经 FileIdInfo 读取 64 位卷序列号,其低 32 位与
754
+ BY_HANDLE_FILE_INFORMATION.dwVolumeSerialNumber 一致。
755
+ """
756
+ attrs, vol_serial, file_index = cls._get_handle_info(handle)
757
+ if attrs & _FILE_ATTRIBUTE_REPARSE_POINT:
758
+ raise ValueError(f"artifact parent contains an unsafe reparse point: {path}")
759
+ if not (attrs & _FILE_ATTRIBUTE_DIRECTORY):
760
+ raise ValueError(f"artifact parent is not a directory: {path}")
761
+ if (
762
+ (expected_lstat.st_dev & 0xFFFFFFFF) != vol_serial
763
+ or (expected_lstat.st_ino & 0xFFFFFFFFFFFFFFFF) != file_index
764
+ ):
765
+ raise ValueError(f"artifact parent identity changed: {path}")
766
+
767
+ def delete_target(
768
+ self,
769
+ target: str,
770
+ *,
771
+ allow_broken_leaf_symlink: bool,
772
+ revalidate: Callable[[], None],
773
+ authorize: Callable[[str, TargetType], bool] | None,
774
+ ) -> bool:
775
+ parent, _ = _split_parent_and_name(target, is_windows=True)
776
+ before_parent = os.lstat(parent)
777
+ parent_cls = _classify_windows_stat(before_parent, parent)
778
+ if parent_cls.entry_class != "directory":
779
+ raise ValueError(f"artifact parent is not a regular directory: {parent}")
780
+
781
+ parent_handle = self._open_pinned_directory(parent)
782
+ try:
783
+ self._verify_pinned_dir(parent_handle, before_parent, parent)
784
+ revalidate()
785
+
786
+ try:
787
+ entry_st = os.lstat(target)
788
+ except FileNotFoundError:
789
+ return False
790
+
791
+ entry_info = _classify_windows_stat(entry_st, target)
792
+ if entry_info.entry_class == "live_symlink":
793
+ raise ValueError(f"artifact leaf must not be a symlink: {target}")
794
+ if entry_info.entry_class == "broken_symlink" and not allow_broken_leaf_symlink:
795
+ raise ValueError(f"artifact leaf must not be a symlink: {target}")
796
+ if entry_info.entry_class == "mount_point":
797
+ raise ValueError(
798
+ f"artifact contains an unsafe reparse point (junction or mount point): {target}"
799
+ )
800
+ if entry_info.entry_class == "unsafe_reparse":
801
+ raise ValueError(f"artifact contains an unsafe reparse point: {target}")
802
+ if entry_info.entry_class == "unsupported":
803
+ raise ValueError(f"unsupported artifact object: {target}")
804
+
805
+ actual_type: TargetType = (
806
+ "directory" if entry_info.entry_class == "directory" else "file"
807
+ )
808
+ if authorize is not None and not authorize(target, actual_type):
809
+ raise PermissionError(
810
+ f"artifact authorization scope changed before deletion: {target}"
811
+ )
812
+
813
+ def guard() -> None:
814
+ revalidate()
815
+ self._verify_pinned_dir(parent_handle, before_parent, parent)
816
+ parent_now = os.lstat(parent)
817
+ if not self._same_lstat(before_parent, parent_now):
818
+ raise ValueError(f"artifact parent identity changed: {parent}")
819
+ current_st = os.lstat(target)
820
+ if not self._same_lstat(entry_st, current_st):
821
+ raise ValueError(f"artifact identity changed during deletion: {target}")
822
+
823
+ if entry_info.entry_class == "directory":
824
+ self._remove_dir_recursive(target, entry_st, guard)
825
+ return True
826
+
827
+ guard()
828
+ current_st = os.lstat(target)
829
+ if not self._same_lstat(entry_st, current_st):
830
+ raise ValueError(f"artifact identity changed during deletion: {target}")
831
+ if entry_info.entry_class == "broken_symlink" and entry_info.is_dir_symlink:
832
+ os.rmdir(target)
833
+ else:
834
+ os.unlink(target)
835
+ return True
836
+ finally:
837
+ self._close_handle(parent_handle)
838
+
839
+ def _remove_dir_recursive(
840
+ self,
841
+ directory: str,
842
+ expected_st: os.stat_result,
843
+ guard: Callable[[], None],
844
+ ) -> None:
845
+ """钉锁当前子目录并递归清空其内容,随后释放子句柄、复验身份并 rmdir。"""
846
+ guard()
847
+ child_handle = self._open_pinned_directory(directory)
848
+ closed = False
849
+ try:
850
+ self._verify_pinned_dir(child_handle, expected_st, directory)
851
+ for name in os.listdir(directory):
852
+ guard()
853
+ child_path = _join_platform_path(directory, (name,), is_windows=True)
854
+ child_st = os.lstat(child_path)
855
+ child_info = _classify_windows_stat(child_st, child_path)
856
+
857
+ if child_info.entry_class == "mount_point":
858
+ raise ValueError(
859
+ f"artifact contains an unsafe reparse point (junction or mount point): {child_path}"
860
+ )
861
+ if child_info.entry_class == "unsafe_reparse":
862
+ raise ValueError(f"artifact contains an unsafe reparse point: {child_path}")
863
+ if child_info.entry_class == "unsupported":
864
+ raise ValueError(f"unsupported artifact object: {child_path}")
865
+
866
+ if child_info.entry_class in ("live_symlink", "broken_symlink"):
867
+ # 目录递归内仅删链接本体,绝不跟随进入链接目标。
868
+ if child_info.is_dir_symlink:
869
+ os.rmdir(child_path)
870
+ else:
871
+ os.unlink(child_path)
872
+ elif child_info.entry_class == "directory":
873
+ self._remove_dir_recursive(child_path, child_st, guard)
874
+ else:
875
+ os.unlink(child_path)
876
+
877
+ # 仍持有上层父目录钉锁的前提下关闭当前子目录句柄,再复验身份并删除空目录。
878
+ self._close_handle(child_handle)
879
+ closed = True
880
+ guard()
881
+ current_st = os.lstat(directory)
882
+ current_info = _classify_windows_stat(current_st, directory)
883
+ if current_info.entry_class != "directory" or not self._same_lstat(
884
+ expected_st, current_st
885
+ ):
886
+ raise ValueError(f"artifact directory identity changed: {directory}")
887
+ os.rmdir(directory)
888
+ finally:
889
+ if not closed:
890
+ self._close_handle(child_handle)
891
+
892
+
893
+ def _default_adapter() -> FilesystemAdapter:
894
+ if sys.platform == "win32":
895
+ return WindowsFilesystemAdapter()
896
+ return PosixFilesystemAdapter()
897
+
898
+
899
+ # ── 统一路径策略深模块 PathPolicy ────────────────────────────────────────
900
+
901
+
902
+ class PathPolicy:
903
+ """跨平台统一路径规范化、受保护路径拦截、安全清理与授权判定深模块。"""
904
+
905
+ def __init__(
906
+ self,
907
+ *,
908
+ base_dir: str | Path | None = None,
909
+ state_path: str | Path | None = None,
910
+ protected_roots: Sequence[str | Path] = (),
911
+ adapter: FilesystemAdapter | None = None,
912
+ ) -> None:
913
+ self._adapter: FilesystemAdapter = adapter if adapter is not None else _default_adapter()
914
+ self._is_windows: bool = self._adapter.is_windows
915
+
916
+ if base_dir is not None:
917
+ self._base_dir_fixed = True
918
+ self._base_dir: str | None = self._canonicalize_anchor(base_dir)
919
+ else:
920
+ self._base_dir_fixed = False
921
+ self._base_dir = None
922
+
923
+ raw_protected = derive_protected_paths(state_path, protected_roots)
924
+ canonical_protected: list[Path] = []
925
+ protected_parts: list[tuple[str, ...]] = []
926
+ seen_keys: set[str] = set()
927
+ for item in raw_protected:
928
+ inspected, _ = self._canonicalize_path(item)
929
+ if inspected.comparison_key not in seen_keys:
930
+ seen_keys.add(inspected.comparison_key)
931
+ canonical_protected.append(Path(inspected.canonical_path))
932
+ protected_parts.append(_path_parts(inspected.comparison_key, is_windows=self._is_windows))
933
+ self._protected_paths: tuple[Path, ...] = tuple(canonical_protected)
934
+ self._protected_parts: tuple[tuple[str, ...], ...] = tuple(protected_parts)
935
+
936
+ @property
937
+ def protected_paths(self) -> tuple[Path, ...]:
938
+ """全部已规范化的受保护路径集合(含 state_path 5 项及附加受保护根)。"""
939
+ return self._protected_paths
940
+
941
+ @property
942
+ def adapter(self) -> FilesystemAdapter:
943
+ return self._adapter
944
+
945
+ @property
946
+ def fixed_base_dir(self) -> str | None:
947
+ """构造期显式固定的规范基准目录;未固定时返回 None。"""
948
+ return self._base_dir if self._base_dir_fixed else None
949
+
950
+ def _effective_base_dir(self) -> str:
951
+ if self._base_dir_fixed and self._base_dir is not None:
952
+ return self._base_dir
953
+ return self._canonicalize_anchor(os.getcwd())
954
+
955
+ def _canonicalize_anchor(self, anchor: str | Path) -> str:
956
+ raw = validate_and_normalize_lexical(anchor, is_windows=self._is_windows)
957
+ if not self._is_absolute(raw):
958
+ cwd = validate_and_normalize_lexical(os.getcwd(), is_windows=self._is_windows)
959
+ raw = _join_platform_path(cwd, (raw,), is_windows=self._is_windows)
960
+ if self._adapter.path_lexists(raw):
961
+ return self._adapter.realpath(raw)
962
+ return raw
963
+
964
+ def _is_absolute(self, norm_path: str) -> bool:
965
+ return is_platform_abs_path(norm_path, is_windows=self._is_windows)
966
+
967
+ def comparison_key_for(self, path: str | Path) -> str:
968
+ """为已锚定或词法路径生成纯内存平台比较键。"""
969
+ norm = validate_and_normalize_lexical(path, is_windows=self._is_windows)
970
+ if not self._is_absolute(norm):
971
+ norm = _join_platform_path(self._effective_base_dir(), (norm,), is_windows=self._is_windows)
972
+ return _comparison_key_for_path(norm, is_windows=self._is_windows)
973
+
974
+ def _canonicalize_path(self, path: str | Path) -> tuple[InspectedPath, EntryInspection]:
975
+ """词法校验 + 锚定 base_dir + 展开最长已存在父前缀(绝不跟随叶链接)。
976
+
977
+ 向内部同时返回 ``(InspectedPath, EntryInspection)``,供 ``inspect()`` 与
978
+ ``is_protected()`` 直接复用叶节点探测结果,避免重复 ``lstat``。
979
+ """
980
+ norm = validate_and_normalize_lexical(path, is_windows=self._is_windows)
981
+ if not self._is_absolute(norm):
982
+ abs_str = _join_platform_path(
983
+ self._effective_base_dir(), (norm,), is_windows=self._is_windows
984
+ )
985
+ else:
986
+ abs_str = norm
987
+
988
+ if _is_root_path(abs_str, is_windows=self._is_windows):
989
+ canonical = abs_str
990
+ entry = self._adapter.inspect_entry(canonical)
991
+ kind: PathKind = "directory" if entry.entry_class == "directory" else "missing"
992
+ return (
993
+ InspectedPath(
994
+ canonical_path=canonical,
995
+ comparison_key=_comparison_key_for_path(canonical, is_windows=self._is_windows),
996
+ kind=kind,
997
+ ),
998
+ entry,
999
+ )
1000
+
1001
+ parent, leaf_name = _split_parent_and_name(abs_str, is_windows=self._is_windows)
1002
+ tail_parts: list[str] = [leaf_name]
1003
+ cursor = parent
1004
+ while not self._adapter.path_lexists(cursor):
1005
+ if _is_root_path(cursor, is_windows=self._is_windows):
1006
+ break
1007
+ next_parent, seg = _split_parent_and_name(cursor, is_windows=self._is_windows)
1008
+ tail_parts.append(seg)
1009
+ cursor = next_parent
1010
+
1011
+ if self._adapter.path_lexists(cursor):
1012
+ resolved_prefix = self._adapter.realpath(cursor)
1013
+ else:
1014
+ resolved_prefix = cursor
1015
+
1016
+ tail_parts.reverse()
1017
+ if len(tail_parts) == 1:
1018
+ # 父目录存在:仅非跟随探测叶节点,非链接/重解析点时回收叶真实大小写。
1019
+ canonical_parent = resolved_prefix
1020
+ candidate = _join_platform_path(
1021
+ canonical_parent, (leaf_name,), is_windows=self._is_windows
1022
+ )
1023
+ entry = self._adapter.inspect_entry(candidate)
1024
+ if entry.entry_class in ("file", "directory"):
1025
+ canonical = self._adapter.recover_leaf_case(canonical_parent, leaf_name)
1026
+ else:
1027
+ canonical = candidate
1028
+ else:
1029
+ canonical = _join_platform_path(
1030
+ resolved_prefix, tail_parts, is_windows=self._is_windows
1031
+ )
1032
+ entry = EntryInspection("missing")
1033
+
1034
+ kind_map: dict[EntryClass, PathKind] = {
1035
+ "missing": "missing",
1036
+ "file": "file",
1037
+ "directory": "directory",
1038
+ "broken_symlink": "broken_symlink",
1039
+ "live_symlink": "file",
1040
+ "mount_point": "directory",
1041
+ "unsafe_reparse": "file",
1042
+ "unsupported": "file",
1043
+ }
1044
+ return (
1045
+ InspectedPath(
1046
+ canonical_path=canonical,
1047
+ comparison_key=_comparison_key_for_path(canonical, is_windows=self._is_windows),
1048
+ kind=kind_map[entry.entry_class],
1049
+ ),
1050
+ entry,
1051
+ )
1052
+
1053
+ def _overlaps_protected(self, comparison_key: str) -> bool:
1054
+ target_parts = _path_parts(comparison_key, is_windows=self._is_windows)
1055
+ return any(_parts_overlap(target_parts, prot) for prot in self._protected_parts)
1056
+
1057
+ def is_protected(self, path: str | Path) -> bool:
1058
+ """判断路径是否与已配置的受保护路径双向重叠(含叶链接/重解析点目标,异常时 fail-closed 返回 True)。"""
1059
+ try:
1060
+ inspected, entry = self._canonicalize_path(path)
1061
+ if self._overlaps_protected(inspected.comparison_key):
1062
+ return True
1063
+ if entry.entry_class in ("live_symlink", "mount_point", "unsafe_reparse"):
1064
+ resolved = self._adapter.realpath(inspected.canonical_path)
1065
+ resolved_key = _comparison_key_for_path(resolved, is_windows=self._is_windows)
1066
+ if self._overlaps_protected(resolved_key):
1067
+ return True
1068
+ except Exception:
1069
+ return True
1070
+ return False
1071
+
1072
+ def inspect(
1073
+ self,
1074
+ path: str | Path,
1075
+ *,
1076
+ mode: InspectMode = "strict",
1077
+ verify_unchanged: bool = False,
1078
+ ) -> InspectedPath:
1079
+ """统一路径规范化与安全检查入口(strict / pre_delete / lookup)。"""
1080
+ if mode not in ("strict", "pre_delete", "lookup"):
1081
+ raise ValueError(f"Unsupported inspect mode: {mode!r}")
1082
+
1083
+ inspected, entry = self._canonicalize_path(path)
1084
+ if verify_unchanged and inspected.comparison_key != self.comparison_key_for(path):
1085
+ raise ValueError(f"artifact parent path changed: {path}")
1086
+ if mode == "lookup":
1087
+ return inspected
1088
+
1089
+ if _is_root_path(inspected.canonical_path, is_windows=self._is_windows):
1090
+ raise ValueError(f"filesystem root cannot be an artifact: {inspected.canonical_path}")
1091
+
1092
+ if self._overlaps_protected(inspected.comparison_key):
1093
+ raise ValueError(f"artifact overlaps a protected root: {inspected.canonical_path}")
1094
+
1095
+ if entry.entry_class == "live_symlink":
1096
+ raise ValueError(f"artifact leaf must not be a symlink: {inspected.canonical_path}")
1097
+ if entry.entry_class == "broken_symlink":
1098
+ if mode != "pre_delete":
1099
+ raise ValueError(
1100
+ f"artifact leaf must not be a symlink: {inspected.canonical_path}"
1101
+ )
1102
+ return InspectedPath(
1103
+ canonical_path=inspected.canonical_path,
1104
+ comparison_key=inspected.comparison_key,
1105
+ kind="broken_symlink",
1106
+ )
1107
+ if entry.entry_class == "mount_point":
1108
+ raise ValueError(
1109
+ f"artifact contains an unsafe reparse point (junction or mount point): "
1110
+ f"{inspected.canonical_path}"
1111
+ )
1112
+ if entry.entry_class == "unsafe_reparse":
1113
+ raise ValueError(
1114
+ f"artifact contains an unsafe reparse point: {inspected.canonical_path}"
1115
+ )
1116
+ return inspected
1117
+
1118
+ def delete(
1119
+ self,
1120
+ target: str | InspectedPath,
1121
+ *,
1122
+ allow_broken_leaf_symlink: bool = False,
1123
+ authorize: Callable[[str, TargetType], bool] | None = None,
1124
+ ) -> bool:
1125
+ """校验路径未漂移后经平台适配器执行非跟随安全删除(缺失返回 False)。"""
1126
+ mode: InspectMode = "pre_delete" if allow_broken_leaf_symlink else "strict"
1127
+ if isinstance(target, InspectedPath):
1128
+ expected_key = target.comparison_key
1129
+ raw_target = target.canonical_path
1130
+ else:
1131
+ expected_key = self.comparison_key_for(target)
1132
+ raw_target = target
1133
+
1134
+ inspected = self.inspect(raw_target, mode=mode)
1135
+ if inspected.comparison_key != expected_key:
1136
+ raise ValueError(f"artifact parent path changed: {raw_target}")
1137
+ if not inspected.exists:
1138
+ return False
1139
+
1140
+ def revalidate() -> None:
1141
+ current = self.inspect(inspected.canonical_path, mode=mode)
1142
+ if current.comparison_key != expected_key:
1143
+ raise ValueError(f"artifact parent path changed: {raw_target}")
1144
+
1145
+ return self._adapter.delete_target(
1146
+ inspected.canonical_path,
1147
+ allow_broken_leaf_symlink=allow_broken_leaf_symlink,
1148
+ revalidate=revalidate,
1149
+ authorize=authorize,
1150
+ )
1151
+
1152
+ def evaluate_authorization(
1153
+ self,
1154
+ existing: Sequence[tuple[str, TargetType]],
1155
+ target: str | InspectedPath,
1156
+ target_type: TargetType | None = None,
1157
+ ) -> AuthorizationMatch:
1158
+ """委托纯内存授权匹配与冲突求值(绑定当前策略平台语义)。"""
1159
+ return evaluate_authorization(
1160
+ existing,
1161
+ target,
1162
+ target_type,
1163
+ is_windows=self._is_windows,
1164
+ )
1165
+
1166
+
1167
+ __all__ = [
1168
+ "AuthorizationMatch",
1169
+ "EntryInspection",
1170
+ "FilesystemAdapter",
1171
+ "InspectMode",
1172
+ "InspectedPath",
1173
+ "PathKind",
1174
+ "PathPolicy",
1175
+ "PosixFilesystemAdapter",
1176
+ "TargetType",
1177
+ "WindowsFilesystemAdapter",
1178
+ "derive_protected_paths",
1179
+ "evaluate_authorization",
1180
+ "is_platform_abs_path",
1181
+ "resolve_lexical_path",
1182
+ "validate_and_normalize_lexical",
1183
+ ]