3737 StaleTurnError ,
3838 StdioMCP ,
3939 TurnNeedsAttention ,
40+ function_tool ,
4041)
4142from agents .state import SessionState
4243from tests ._asyncio import timeout
@@ -732,57 +733,6 @@ def git(cwd: Path, *args: str) -> str:
732733 assert (linked / ".agents" / "protected" ).read_text () == "metadata"
733734
734735
735- def _macos_identity_probe (directory : Path ) -> str :
736- source = directory / "identity-probe.c"
737- probe = directory / "identity-probe"
738- source .write_text (
739- r"""
740- #include <mach/mach.h>
741- #include <mach/task_special_ports.h>
742- #include <stdio.h>
743- #include <unistd.h>
744-
745- // Match the no-report global-name query in the pinned Seatbelt tests.
746- extern const int SANDBOX_CHECK_NO_REPORT;
747- extern int sandbox_check(pid_t, const char *, int, ...);
748-
749- int main(void) {
750- const int global_name_filter = 2;
751- const char *services[] = {
752- "com.apple.system.opendirectoryd.libinfo",
753- "com.apple.system.DirectoryService.libinfo_v1",
754- "com.apple.system.opendirectoryd.membership",
755- };
756- mach_port_t port = MACH_PORT_NULL;
757- kern_return_t status = task_get_special_port(mach_task_self(), TASK_BOOTSTRAP_PORT, &port);
758- int present = status == KERN_SUCCESS && MACH_PORT_VALID(port);
759- printf("bootstrap port status=%d present=%d\n", status, present);
760- if (present) {
761- mach_port_deallocate(mach_task_self(), port);
762- }
763- for (size_t i = 0; i < sizeof(services) / sizeof(services[0]); ++i) {
764- int result = sandbox_check(
765- getpid(), "mach-lookup", global_name_filter | SANDBOX_CHECK_NO_REPORT, services[i]
766- );
767- printf("mach-lookup %s=%d\n", services[i], result);
768- }
769- return 0;
770- }
771- """ ,
772- encoding = "utf-8" ,
773- )
774- try :
775- subprocess .run (
776- ["/usr/bin/xcrun" , "--sdk" , "macosx" , "clang" , "-o" , str (probe ), str (source )],
777- capture_output = True ,
778- timeout = 15 ,
779- check = True ,
780- )
781- except (OSError , subprocess .SubprocessError ) as error :
782- return f"printf 'identity probe build unavailable (%s)\\ n' { type (error ).__name__ } "
783- return f"{ shlex .quote (str (probe ))} || printf 'identity probe exit=%s\\ n' \" $?\" "
784-
785-
786736@pytest .mark .skipif (sys .platform not in ("linux" , "darwin" ), reason = "requires native Unix" )
787737@(
788738 pytest .mark .requires_native_linux_sandbox
@@ -870,29 +820,12 @@ def git(cwd: Path, *args: str) -> str:
870820 "DYLD_SYNTHETIC_MARKER" : "synthetic-explicit-loader-value" ,
871821 },
872822 )
873- # Darwin's id -F fails when getpwuid cannot resolve the real UID.
874- macos_uid_lookup = ("/usr/bin/id" , "-F" )
875- ssh = "/usr/bin/ssh" if sys .platform == "darwin" else "ssh"
876- ssh_command = f"{ ssh } -G -T -F /dev/null credential.example.invalid"
877823 if sys .platform == "darwin" :
878- identity_probe = _macos_identity_probe (linked )
879- ssh_probe = (
880- f"ssh_config=$({ ssh_command } & ssh_pid=$!; "
881- 'if ! wait "$ssh_pid"; then '
882- 'printf "trusted SSH pid=%s, UID lookup exit=%s\\ n" "$ssh_pid" "$uid_status" >&2; '
883- "exit 1; fi) && printf '%s\\ n' \" $ssh_config\" | grep -q '^user '; "
884- )
885- # Keep checking Git and write grants after recording the real SSH exit.
886- ssh_probe = (
887- f"{ identity_probe } ; "
888- f"uid_status=0; { shlex .join (macos_uid_lookup )} >/dev/null 2>&1 || uid_status=$?; "
889- 'printf "trusted UID lookup exit=%s\\ n" "$uid_status"; '
890- f"ssh_status=0; ({ ssh_probe } ) || ssh_status=$?; "
891- 'printf "trusted SSH config exit=%s\\ n" "$ssh_status"; '
892- )
824+ identity_check = f'test "$(/usr/bin/id -u)" = { os .geteuid ()} ; '
893825 else :
894- ssh_probe = (
895- f'ssh_config=$({ ssh_command } ); printf "%s\\ n" "$ssh_config" | grep -q "^user "; '
826+ identity_check = (
827+ "ssh_config=$(ssh -G -T -F /dev/null credential.example.invalid); "
828+ 'printf "%s\\ n" "$ssh_config" | grep -q "^user "; '
896829 )
897830 command = (
898831 'set -eu; test "$(fixture-tool)" = "fixture tool"; '
@@ -902,7 +835,7 @@ def git(cwd: Path, *args: str) -> str:
902835 f'test "$TMPDIR" = { shlex .quote (str (job_temp ))} ; '
903836 'test -z "${OPENAI_API_KEY+x}${openai_api_key+x}${CODEX_API_KEY+x}${LD_LIBRARY_PATH+x}"; '
904837 'test -z "${ld_synthetic_marker+x}${DYLD_SYNTHETIC_MARKER+x}"; '
905- f"{ ssh_probe } "
838+ f"{ identity_check } "
906839 "printf 'protocol=https\\ nhost=credential.example.invalid\\ n\\ n' "
907840 "| git credential fill | grep -qx password=synthetic-git-password; "
908841 'scratch=$(mktemp -d "$TMPDIR/sdk-job.XXXXXX"); printf job > "$scratch/result"; '
@@ -961,68 +894,7 @@ def popleft(self) -> list[dict[str, Any]]:
961894 turn = await session .submit ("Create and commit the artifact." )
962895 assert (await turn .get_result ()).final_output == "done"
963896 output = "\n " .join (command_outputs )
964- failure = output
965- if sys .platform == "darwin" and (
966- probe := re .search (r"^trusted SSH pid=([0-9]+), UID lookup exit=[0-9]+\r?$" , output , re .M )
967- ):
968- pid = probe [1 ]
969- denial = "no matching Mach lookup denial visible"
970- try :
971- log = subprocess .run (
972- [
973- "/usr/bin/log" ,
974- "show" ,
975- "--last" ,
976- "1m" ,
977- "--predicate" ,
978- f'eventMessage CONTAINS "ssh({ pid } ) deny(" '
979- 'AND eventMessage CONTAINS " mach-lookup "' ,
980- ],
981- capture_output = True ,
982- text = True ,
983- timeout = 5 ,
984- check = False ,
985- )
986- if match := re .search (rf"ssh\({ pid } \) deny\([0-9]+\) mach-lookup [\w.-]+" , log .stdout ):
987- denial = match [0 ]
988- except (OSError , subprocess .TimeoutExpired ):
989- pass
990- control = (
991- f"status=0; { shlex .join (macos_uid_lookup )} >/dev/null 2>&1 || status=$?; "
992- 'printf "UID lookup exit=%s\\ n" "$status"; '
993- f"status=0; { ssh_command } >/dev/null 2>&1 || status=$?; "
994- 'printf "SSH config exit=%s\\ n" "$status"; '
995- f"{ identity_probe } "
996- )
997- host_lookup = "identity probe unavailable"
998- try :
999- host_lookup = subprocess .run (
1000- ["/bin/sh" , "-c" , control ],
1001- capture_output = True ,
1002- text = True ,
1003- timeout = 5 ,
1004- check = True ,
1005- ).stdout .strip ()
1006- except (OSError , subprocess .SubprocessError ):
1007- pass
1008- responses .respond (
1009- function_call (
1010- "exec_command" ,
1011- {"cmd" : control , "login" : False , "yield_time_ms" : 5000 },
1012- "strict-identity" ,
1013- )
1014- )
1015- responses .respond (assistant_output ("done" ))
1016- strict_environment = Environment .local (cwd = linked , tools = ["exec_command" ])
1017- try :
1018- async with timeout (20 ), agent .session (environment = strict_environment ) as session :
1019- turn = await session .submit ("Check account lookup." )
1020- await turn .get_result ()
1021- strict_lookup = tool_output (responses .requests [- 1 ], "strict-identity" )
1022- except (AssertionError , TimeoutError , NativeError ) as error :
1023- strict_lookup = f"identity probe unavailable ({ type (error ).__name__ } )"
1024- failure = f"{ output } \n Host { host_lookup } \n Strict { strict_lookup } \n { denial } "
1025- assert "Process exited with code 0" in output , failure
897+ assert "Process exited with code 0" in output , output
1026898 advertised = json .dumps (responses .requests [0 ])
1027899 assert "Fixture for selected-skill" in advertised
1028900 assert "Fixture for hidden-skill" not in advertised
@@ -1033,11 +905,49 @@ def popleft(self) -> list[dict[str, Any]]:
1033905 assert (linked / ".agents" / "marker" ).read_text () == "protected"
1034906 (job_result ,) = job_temp .glob ("sdk-job.*/result" )
1035907 assert job_result .read_text () == "job"
1036- if sys .platform == "darwin" :
1037- assert "trusted SSH config exit=0" in output .splitlines (), (
1038- f"{ failure } \n Trusted Git, job temp, and write-fence assertions passed."
908+
909+
910+ @pytest .mark .skipif (sys .platform != "darwin" , reason = "requires macOS directory services" )
911+ @pytest .mark .requires_native_macos_sandbox
912+ async def test_macos_local_session_can_read_host_account_with_an_application_tool (
913+ responses : ResponsesFixture , tmp_path : Path
914+ ) -> None :
915+ @function_tool
916+ async def inspect_host_account () -> str :
917+ account_name = await asyncio .to_thread (
918+ subprocess .run ,
919+ ["/usr/bin/id" , "-F" ],
920+ capture_output = True ,
921+ text = True ,
922+ check = True ,
923+ timeout = 5 ,
1039924 )
1040- assert "trusted UID lookup exit=0" in output .splitlines (), failure
925+ ssh_config = await asyncio .to_thread (
926+ subprocess .run ,
927+ ["/usr/bin/ssh" , "-G" , "-T" , "-F" , "/dev/null" , "credential.example.invalid" ],
928+ capture_output = True ,
929+ text = True ,
930+ check = True ,
931+ timeout = 5 ,
932+ )
933+ assert account_name .stdout .strip ()
934+ assert any (line .startswith ("user " ) for line in ssh_config .stdout .splitlines ())
935+ return "Host account lookup completed."
936+
937+ responses .respond (function_call ("inspect_host_account" , {}, "host-identity" ))
938+ responses .respond (assistant_output ("done" ))
939+ agent = Agent (
940+ instructions = "Use the supplied host account tool." ,
941+ tools = [inspect_host_account ],
942+ provider = NativeProvider (base_url = responses .url , api_key = "synthetic-model-key" ),
943+ )
944+ environment = Environment .local (
945+ cwd = tmp_path , tools = ["exec_command" ], write_policy = "trusted_workspace_write"
946+ )
947+ async with timeout (30 ), agent .session (environment = environment ) as session :
948+ turn = await session .submit ("Check the host account." )
949+ assert (await turn .get_result ()).final_output == "done"
950+ assert tool_output (responses .requests [- 1 ], "host-identity" ) == "Host account lookup completed."
1041951
1042952
1043953@pytest .mark .skipif (sys .platform != "darwin" , reason = "requires macOS Xcode and Homebrew" )
0 commit comments