22
33import asyncio
44import io
5+ import os
56import shutil
67import signal
78import subprocess
@@ -671,14 +672,15 @@ async def test_write_new_file_creates_a_file_and_its_parents(tmp_path: Path) ->
671672class _ExitCodeUnixLocalSession (UnixLocalSandboxSession ):
672673 """Drives the shared exec-based exclusive create with a chosen exit code."""
673674
674- def __init__ (self , root : Path , exit_code : int ) -> None :
675+ def __init__ (self , root : Path , exit_code : int , * , preflight_exit_code : int = 0 ) -> None :
675676 super ().__init__ (
676677 state = UnixLocalSandboxSessionState (
677678 manifest = Manifest (root = str (root )),
678679 snapshot = NoopSnapshot (id = "noop" ),
679680 )
680681 )
681682 self ._exit_code = exit_code
683+ self ._preflight_exit_code = preflight_exit_code
682684 self .exec_commands : list [tuple [str , ...]] = []
683685 self .writes : list [Path ] = []
684686 self .removed : list [Path ] = []
@@ -690,8 +692,12 @@ async def _exec_internal(
690692 timeout : float | None = None ,
691693 ) -> ExecResult :
692694 _ = timeout
693- self .exec_commands .append (tuple (str (part ) for part in command ))
694- return ExecResult (stdout = b"" , stderr = b"" , exit_code = self ._exit_code )
695+ parts = tuple (str (part ) for part in command )
696+ self .exec_commands .append (parts )
697+ # The collision preflight is the invocation that receives only the target.
698+ is_preflight = not any ("ln " in part for part in parts )
699+ code = self ._preflight_exit_code if is_preflight else self ._exit_code
700+ return ExecResult (stdout = b"" , stderr = b"" , exit_code = code )
695701
696702 async def write (self , path : Path , data : io .IOBase , * , user : object = None ) -> None :
697703 _ = (data , user )
@@ -720,17 +726,32 @@ async def mkdir(
720726
721727@pytest .mark .asyncio
722728async def test_write_new_file_with_a_bound_user_reports_an_existing_name (tmp_path : Path ) -> None :
723- """Exit 13 from the exclusive-create script means the name was already taken."""
724- session = _ExitCodeUnixLocalSession (tmp_path , exit_code = 13 )
729+ """A target that is already visible is rejected before any payload is staged."""
730+ session = _ExitCodeUnixLocalSession (tmp_path , exit_code = 0 , preflight_exit_code = 13 )
731+
732+ with pytest .raises (FileExistsError ):
733+ await session .write_new_file (
734+ Path ("notes.txt" ), io .BytesIO (b"payload" ), user = User (name = "sandbox-user" )
735+ )
736+
737+ # No payload bytes were uploaded, so a create onto an occupied name costs one probe
738+ # rather than a full staged write that is then discarded.
739+ assert session .writes == []
740+ assert session .removed == []
741+
742+
743+ @pytest .mark .asyncio
744+ async def test_write_new_file_with_a_bound_user_reports_a_racing_creator (tmp_path : Path ) -> None :
745+ """A creator that wins between the preflight and the link still loses the name."""
746+ session = _ExitCodeUnixLocalSession (tmp_path , exit_code = 13 , preflight_exit_code = 0 )
725747
726748 with pytest .raises (FileExistsError ):
727749 await session .write_new_file (
728750 Path ("notes.txt" ), io .BytesIO (b"payload" ), user = User (name = "sandbox-user" )
729751 )
730752
731- # The payload only ever reached a staging name, and that staging entry is cleaned up,
732- # so a rejected create leaves nothing behind at the requested name.
733- assert [path .name for path in session .writes ] != ["notes.txt" ]
753+ # Here the payload was staged before the race was detected, and the staging entry is
754+ # still cleaned up rather than left in the workspace.
734755 assert all (path .name .startswith (".apply-patch-create-" ) for path in session .writes )
735756 assert session .removed == session .writes
736757 assert session .made_dirs != []
@@ -927,3 +948,32 @@ async def test_apply_patch_create_accepts_a_destination_at_the_component_limit(
927948 )
928949
929950 assert (tmp_path / long_name ).read_text () == "hello"
951+
952+
953+ @pytest .mark .skipif (os .geteuid () == 0 , reason = "root bypasses directory write permissions" )
954+ @pytest .mark .asyncio
955+ async def test_apply_patch_create_reports_collision_inside_a_read_only_parent (
956+ tmp_path : Path ,
957+ ) -> None :
958+ """A visible collision must classify as a collision, not as a permission failure.
959+
960+ Staging before classifying meant a target inside an executable but non-writable
961+ parent failed on the staging write, so the caller was told the write failed instead
962+ of being told to use update_file.
963+ """
964+ session = _exclusive_write_session (tmp_path )
965+ parent = tmp_path / "locked"
966+ parent .mkdir ()
967+ target = parent / "notes.txt"
968+ target .write_bytes (b"important\n " )
969+ parent .chmod (0o555 )
970+ try :
971+ with pytest .raises (ApplyPatchDiffError ):
972+ await session .apply_patch (
973+ ApplyPatchOperation (
974+ type = "create_file" , path = "locked/notes.txt" , diff = "+clobbered\n "
975+ )
976+ )
977+ assert target .read_bytes () == b"important\n "
978+ finally :
979+ parent .chmod (0o755 )
0 commit comments