|
2 | 2 | import asyncio |
3 | 3 | import io |
4 | 4 | import shlex |
5 | | -import uuid |
6 | 5 | from collections.abc import Awaitable, Callable, Mapping, Sequence |
7 | | -from contextlib import suppress |
8 | 6 | from pathlib import Path, PurePath |
9 | 7 | from typing import Literal, NoReturn, TypeVar |
10 | 8 |
|
|
151 | 149 | fi |
152 | 150 | done |
153 | 151 | """.strip() |
154 | | -_EXCLUSIVE_CREATE_EXISTS_CODE = 13 |
155 | | -# Classify an already-visible target before any payload is staged. Without this the |
156 | | -# staging write runs first, so a target inside an executable but non-writable parent |
157 | | -# fails on permissions and the caller sees a write error instead of the collision error |
158 | | -# that tells it to use update_file. The atomic claim below still decides real races. |
159 | | -_TARGET_EXISTS_SCRIPT = 'target="$1"\nif [ -e "$target" ] || [ -L "$target" ]; then exit 13; fi\n' |
160 | | - |
161 | | -# ``ln`` claims the target name and fails when that name is already taken. Linking a |
162 | | -# fully written staging file means the content is complete before the name exists, so a |
163 | | -# failed or cancelled upload cannot leave a file behind that holds the name. The leading |
164 | | -# test rejects a name held by a directory, which ``ln`` would otherwise treat as a target |
165 | | -# directory and populate; the trailing test only classifies a failure, so "already |
166 | | -# exists" stays separable from any other error without parsing shell-specific stderr. |
167 | | -# ``ln`` is a regular command, unlike ``:``, so its failure still reaches the explicit |
168 | | -# exit mapping on shells where ``:`` is a special builtin. The caller creates the parent, |
169 | | -# so this script never has to create one as a different identity. |
170 | | -_EXCLUSIVE_CREATE_SCRIPT = ( |
171 | | - 'target="$1"\n' |
172 | | - 'source="$2"\n' |
173 | | - 'if [ -e "$target" ] || [ -L "$target" ]; then exit 13; fi\n' |
174 | | - 'ln "$source" "$target" 2>/dev/null && exit 0\n' |
175 | | - 'if [ -e "$target" ] || [ -L "$target" ]; then exit 13; fi\n' |
176 | | - "exit 14\n" |
177 | | -) |
178 | | - |
179 | 152 | _WRITE_ACCESS_CHECK_SCRIPT = ( |
180 | 153 | 'target="$1"\n' |
181 | 154 | 'if [ -e "$target" ]; then\n' |
@@ -981,69 +954,27 @@ async def write_new_file( |
981 | 954 | ) -> None: |
982 | 955 | """Write a file that must not already exist. |
983 | 956 |
|
984 | | - The target name is claimed in a single atomic step once the payload is complete, |
985 | | - so a concurrent creator either loses the race or keeps its own content, and a |
986 | | - failed write does not leave a partial file holding the name. |
| 957 | + This default checks the target and then writes, so it rejects the ordinary case of |
| 958 | + a create aimed at a path that is already occupied and leaves the existing content |
| 959 | + alone. It is not atomic: a creator that arrives between the check and the write is |
| 960 | + overwritten. A backend that can express an exclusive create should override this |
| 961 | + and claim the name in one step; ``UnixLocalSandboxSession`` does. |
987 | 962 |
|
988 | 963 | :param path: Absolute path in the container or path relative to the |
989 | 964 | workspace root. |
990 | 965 | :param data: A file-like object positioned at the start of the payload. |
991 | 966 | :param user: Optional sandbox user to perform the write as. |
992 | | - :raises FileExistsError: If the path already exists, including a dangling symlink. |
| 967 | + :raises FileExistsError: If the path already exists. |
993 | 968 | """ |
994 | | - # Validate the parent so grants and symlinked parents are still enforced, then |
995 | | - # keep the final component unresolved. A path policy that resolves symlinks would |
996 | | - # otherwise turn a dangling link at the target name into its absent target and let |
997 | | - # the create land there instead of being rejected. |
998 | | - requested = Path(path) |
999 | | - parent_path = await self._validate_path_access(requested.parent, for_write=True) |
1000 | | - workspace_path = parent_path / requested.name |
1001 | | - path_arg = sandbox_path_str(workspace_path) |
1002 | | - # A fixed-length staging basename. Deriving it from the destination made the |
1003 | | - # staging name longer than the destination, so a name that fits the filesystem's |
1004 | | - # component limit could still fail to stage. |
1005 | | - staging_path = parent_path / f".apply-patch-create-{uuid.uuid4().hex}" |
1006 | | - staging_arg = sandbox_path_str(staging_path) |
1007 | | - |
1008 | | - preflight = await self.exec( |
1009 | | - "sh", "-c", _TARGET_EXISTS_SCRIPT, "sh", path_arg, shell=False, user=user |
1010 | | - ) |
1011 | | - if preflight.exit_code == _EXCLUSIVE_CREATE_EXISTS_CODE: |
1012 | | - raise FileExistsError(path_arg) |
1013 | | - |
| 969 | + workspace_path = await self._validate_path_access(path, for_write=True) |
1014 | 970 | try: |
1015 | | - # Create the parent as the bound user so a fresh nested path is owned the same |
1016 | | - # way the ordinary write path owned it. |
1017 | | - await self.mkdir(parent_path, parents=True, user=user) |
1018 | | - await self.write(staging_path, data, user=user) |
1019 | | - # -c rather than -lc: this runs on a filesystem-only capability set, so it |
1020 | | - # must not source workspace-writable shell startup files. |
1021 | | - result = await self.exec( |
1022 | | - "sh", |
1023 | | - "-c", |
1024 | | - _EXCLUSIVE_CREATE_SCRIPT, |
1025 | | - "sh", |
1026 | | - path_arg, |
1027 | | - staging_arg, |
1028 | | - shell=False, |
1029 | | - user=user, |
1030 | | - ) |
1031 | | - if result.exit_code == _EXCLUSIVE_CREATE_EXISTS_CODE: |
1032 | | - raise FileExistsError(path_arg) |
1033 | | - if not result.ok(): |
1034 | | - raise WorkspaceArchiveWriteError( |
1035 | | - path=workspace_path, |
1036 | | - context={ |
1037 | | - "command": ["sh", "-c", "<exclusive_create>", path_arg, staging_arg], |
1038 | | - "stdout": result.stdout.decode("utf-8", errors="replace"), |
1039 | | - "stderr": result.stderr.decode("utf-8", errors="replace"), |
1040 | | - }, |
1041 | | - ) |
1042 | | - finally: |
1043 | | - # The staging entry is an implementation detail, and removing it must not |
1044 | | - # replace the outcome of the create. |
1045 | | - with suppress(Exception): |
1046 | | - await self.rm(staging_path, user=user) |
| 971 | + handle = await self.read(workspace_path, user=user) |
| 972 | + except (FileNotFoundError, WorkspaceReadNotFoundError): |
| 973 | + pass |
| 974 | + else: |
| 975 | + handle.close() |
| 976 | + raise FileExistsError(sandbox_path_str(workspace_path)) |
| 977 | + await self.write(workspace_path, data, user=user) |
1047 | 978 |
|
1048 | 979 | async def _check_read_with_exec( |
1049 | 980 | self, path: Path | str, *, user: str | User | None = None |
|
0 commit comments