Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

22.6 KB
Raw Blame
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

"""disable_sandbox skips safety checks and the blocklist; run with PYTHONPATH=studio/backend."""

import io
import os
import sys

import pytest

import core.inference.tools as tools
from core.inference.tools import (
    _SANDBOX_TEMP_DIRNAME,
    _bash_exec,
    _build_bypass_env,
    _build_safe_env,
    _is_cred_location_env_name,
    _is_secret_env_name,
    _is_secret_env_value,
    _python_exec,
)
from core.inference.safetensors_agentic import run_safetensors_tool_loop

_POSIX_ONLY = pytest.mark.skipif(
    sys.platform == "win32", reason = "preexec_fn / setsid are POSIX-only"
)


@pytest.mark.parametrize(
    "name",
    [
        "HF_TOKEN",
        "HUGGING_FACE_HUB_TOKEN",
        "WANDB_API_KEY",
        "GH_TOKEN",
        "GITHUB_TOKEN",
        "OPENAI_API_KEY",
        "ANTHROPIC_API_KEY",
        "AWS_SECRET_ACCESS_KEY",
        "AWS_ACCESS_KEY_ID",
        "AZURE_CLIENT_SECRET",
        "GOOGLE_APPLICATION_CREDENTIALS",
        "MY_DB_PASSWORD",
        "x_api_key",
        "SOME_PRIVATE_KEY",
        "LD_PRELOAD",
    ],
)
def test_secret_names_are_flagged(name):
    assert _is_secret_env_name(name) is True


@pytest.mark.parametrize(
    "name", ["PATH", "HOME", "LANG", "TERM", "PWD", "SHELL", "HOSTVAR", "MY_VAR"]
)
def test_benign_names_are_not_flagged(name):
    assert _is_secret_env_name(name) is False


def test_bypass_env_keeps_benign_strips_secret_repoints_home(monkeypatch, tmp_path):
    monkeypatch.setenv("HOSTVAR", "benign-123")
    monkeypatch.setenv("HF_TOKEN", "secret-abc")
    env = _build_bypass_env(str(tmp_path))
    assert env.get("HOSTVAR") == "benign-123"
    assert "HF_TOKEN" not in env
    assert env["HOME"] == str(tmp_path)
    assert env["TMPDIR"] == str(tmp_path / _SANDBOX_TEMP_DIRNAME)


def test_safe_env_excludes_host_and_secret(monkeypatch, tmp_path):
    monkeypatch.setenv("HOSTVAR", "benign-123")
    monkeypatch.setenv("HF_TOKEN", "secret-abc")
    env = _build_safe_env(str(tmp_path))
    assert "HOSTVAR" not in env
    assert "HF_TOKEN" not in env


class _FakeProc:
    """Popen double with a missing pid, so process-group capture finds nothing and drain never kills."""

    returncode = 0
    pid = 2**22

    def __init__(self):
        self.stdout = io.StringIO("FAKEOUT")

    def wait(self, timeout = None):
        return 0

    def poll(self):
        return 0

    def kill(self):
        pass


@pytest.fixture
def captured_popen(monkeypatch):
    cap = {}

    def fake_popen(cmd, **kwargs):
        # First call only: on macOS a later `ps` Popen would replace the tool launch.
        cap.setdefault("cmd", cmd)
        cap.setdefault("kwargs", kwargs)
        return _FakeProc()

    monkeypatch.setattr(tools.subprocess, "Popen", fake_popen)
    return cap


@pytest.fixture
def captured_prepared_launch(monkeypatch):
    cap = {}

    def fake_spawn(prepared, **kwargs):
        cap["prepared"] = prepared
        cap["kwargs"] = kwargs
        return _FakeProc()

    monkeypatch.setattr(tools.os_sandbox, "spawn_prepared_launch", fake_spawn)
    return cap


def _carries(preexec, expected) -> bool:
    """A backend that isolates COMPOSES its pre-exec onto the plan's rather than replacing it, so on such a host the identity is one closure down."""
    if preexec is expected:
        return True
    return any(cell.cell_contents is expected for cell in (preexec.__closure__ or ()))


@_POSIX_ONLY
def test_python_sandboxed_uses_sandbox_preexec_and_safe_env(captured_prepared_launch, monkeypatch):
    monkeypatch.setenv("HF_TOKEN", "secret-abc")
    _python_exec("print(1)", None, 5, "t", disable_sandbox = False)
    kwargs = captured_prepared_launch["kwargs"]
    if "preexec_fn" in kwargs:
        assert _carries(kwargs["preexec_fn"], tools._sandbox_preexec)
    else:
        # The same setup without a Python pre-exec: setsid and umask by Popen, the rest by setpriv/prlimit.
        argv = captured_prepared_launch["prepared"].argv
        assert kwargs["start_new_session"] is True and kwargs["umask"] == 0o077
        assert argv[1:5] == ("--no-new-privs", "--pdeathsig", "KILL", "--")
    assert "HF_TOKEN" not in kwargs["env"]


@_POSIX_ONLY
def test_python_bypass_uses_bypass_preexec_and_bypass_env(captured_popen, monkeypatch):
    monkeypatch.setenv("HOSTVAR", "benign-xyz")
    monkeypatch.setenv("HF_TOKEN", "secret-abc")
    _python_exec("print(1)", None, 5, "t", disable_sandbox = True)
    assert captured_popen["kwargs"]["start_new_session"] is True
    assert "preexec_fn" not in captured_popen["kwargs"]
    env = captured_popen["kwargs"]["env"]
    assert env.get("HOSTVAR") == "benign-xyz"
    assert env.get("PYTHONIOENCODING") == "utf-8"
    assert "HF_TOKEN" not in env


def test_bash_blocklist_enforced_when_sandboxed(captured_popen):
    out = _bash_exec("rm -rf /", None, 5, "t", disable_sandbox = False)
    assert "Blocked" in out
    assert "cmd" not in captured_popen


def test_bash_blocklist_skipped_when_bypassed(captured_popen):
    out = _bash_exec("rm -rf /", None, 5, "t", disable_sandbox = True)
    assert out == "FAKEOUT"
    # Git for Windows gives an absolute argv[0] path, so compare the program name.
    shell = os.path.basename(captured_popen["cmd"][0]).lower()
    assert shell in ("bash", "bash.exe", "cmd", "cmd.exe")


@_POSIX_ONLY
def test_bash_bypass_uses_bypass_preexec(captured_popen, monkeypatch):
    monkeypatch.delenv("PYTHONIOENCODING", raising = False)
    _bash_exec("echo hi", None, 5, "t", disable_sandbox = True)
    assert captured_popen["kwargs"]["start_new_session"] is True
    assert "preexec_fn" not in captured_popen["kwargs"]
    assert "PYTHONIOENCODING" not in captured_popen["kwargs"]["env"]


@_POSIX_ONLY
def test_python_bypass_real_exec_sees_host_env_but_not_secret(monkeypatch):
    monkeypatch.setenv("HOSTVAR", "benign-xyz")
    monkeypatch.setenv("HF_TOKEN", "secret-pqr")
    code = (
        "import os;"
        "print('H=' + str(os.environ.get('HOSTVAR')),"
        " 'T=' + str(os.environ.get('HF_TOKEN')))"
    )
    out = _python_exec(code, None, 30, "test-bypass", disable_sandbox = True)
    assert "H=benign-xyz" in out
    assert "T=None" in out
    assert "secret-pqr" not in out


@_POSIX_ONLY
def test_bypass_preexec_only_sets_session(monkeypatch):
    calls = {"setsid": 0}
    monkeypatch.setattr(
        tools.os, "setsid", lambda: calls.__setitem__("setsid", calls["setsid"] + 1)
    )
    if tools._resource is not None:
        monkeypatch.setattr(
            tools._resource,
            "setrlimit",
            lambda *a, **k: pytest.fail("bypass pre-exec must not set rlimits"),
        )
    tools._bypass_preexec()
    assert calls["setsid"] == 1


def test_request_model_bypass_default_false():
    from models.inference import ChatCompletionRequest
    assert ChatCompletionRequest.model_fields["bypass_permissions"].default is False


@pytest.mark.parametrize(
    "confirm,bypass,effective_confirm",
    [
        (False, False, False),
        (True, False, True),
        (False, True, False),
        (True, True, False),
    ],
)
def test_confirm_precedence_rule(confirm, bypass, effective_confirm):
    assert (bool(confirm) and not bool(bypass)) is effective_confirm


_DEFAULT_TOOLS = [
    {"type": "function", "function": {"name": "python"}},
    {"type": "function", "function": {"name": "web_search"}},
]


def _tool_call(name, args_json):
    return f'<tool_call>{{"name": "{name}", "arguments": {args_json}}}</tool_call>'


def _multi_turn(turns):
    it = iter(turns)

    def _gen(_messages):
        try:
            yield next(it)
        except StopIteration:
            return

    return _gen


def test_loop_forwards_disable_sandbox_and_does_not_gate():
    seen = []

    def fake_exec(
        name,
        arguments,
        *,
        cancel_event = None,
        timeout = None,
        session_id = None,
        thread_id = None,
        rag_scope = None,
        disable_sandbox = False,
    ):
        seen.append(disable_sandbox)
        return f"RAN[{name}]"

    events = list(
        run_safetensors_tool_loop(
            single_turn = _multi_turn([_tool_call("python", '{"code": "x"}'), "done"]),
            messages = [{"role": "user", "content": "hi"}],
            tools = _DEFAULT_TOOLS,
            execute_tool = fake_exec,
            session_id = "s",
            confirm_tool_calls = False,
            bypass_permissions = True,
        )
    )
    assert seen == [True]
    starts = [e for e in events if e["type"] == "tool_start"]
    assert starts and starts[0]["awaiting_confirmation"] is False
    assert starts[0]["approval_id"] == ""


def test_loop_bypass_overrides_confirm_for_direct_callers():
    def fake_exec(
        name,
        arguments,
        *,
        cancel_event = None,
        timeout = None,
        session_id = None,
        thread_id = None,
        rag_scope = None,
        disable_sandbox = False,
    ):
        return f"RAN[{name}]"

    events = list(
        run_safetensors_tool_loop(
            single_turn = _multi_turn([_tool_call("python", '{"code": "x"}'), "done"]),
            messages = [{"role": "user", "content": "hi"}],
            tools = _DEFAULT_TOOLS,
            execute_tool = fake_exec,
            session_id = "s",
            confirm_tool_calls = True,
            bypass_permissions = True,
        )
    )
    starts = [e for e in events if e["type"] == "tool_start"]
    assert starts and starts[0]["awaiting_confirmation"] is False
    assert starts[0]["approval_id"] == ""


def test_gguf_loop_confirm_gate_respects_bypass():
    # The GGUF loop needs a live llama-server, so check its gate via AST.
    import ast
    import inspect
    import textwrap

    llama_cpp = pytest.importorskip("core.inference.llama_cpp")
    src = textwrap.dedent(
        inspect.getsource(llama_cpp.LlamaCppBackend.generate_chat_completion_with_tools)
    )
    gates = [
        node
        for node in ast.walk(ast.parse(src))
        if isinstance(node, ast.Assign)
        and any(getattr(t, "id", None) == "needs_confirm" for t in node.targets)
    ]
    assert gates, "could not find the needs_confirm gate in the GGUF loop"
    names = {n.id for g in gates for n in ast.walk(g.value) if isinstance(n, ast.Name)}
    assert "confirm_tool_calls" in names
    assert "bypass_permissions" in names


@pytest.mark.parametrize(
    "name",
    ["SSH_AUTH_SOCK", "SSH_AGENT_PID", "GPG_AGENT_INFO", "GNUPGHOME", "KUBECONFIG"],
)
def test_broker_capability_names_are_flagged(name):
    assert _is_secret_env_name(name) is True


@pytest.mark.parametrize(
    "value",
    [
        "https://user:[email protected]/simple",
        "https://[email protected]/org/private.git",
        "https://[email protected]/simple",
        "https://ghp_1234:@npm.pkg.github.com/simple",
        "postgres://dbuser:[email protected]/app",
    ],
)
def test_url_userinfo_values_are_flagged(value):
    assert _is_secret_env_value(value) is True


@pytest.mark.parametrize(
    "value",
    [
        "https://example.invalid/simple",
        "http://proxy.corp.example:8080",
        "https://pypi.corp.example/simple",
        "redis://localhost:6379/0",
        "https://example.invalid/path?ref=a@b",
    ],
)
def test_non_credential_url_values_are_not_flagged(value):
    assert _is_secret_env_value(value) is False


def test_url_userinfo_value_is_stripped_even_with_benign_name(monkeypatch, tmp_path):
    monkeypatch.setenv("MY_FEED", "https://user:[email protected]/simple")
    monkeypatch.setenv("REPO_URL", "https://[email protected]/org/private.git")
    monkeypatch.setenv("PLAIN_URL", "https://example.invalid/simple")
    env = _build_bypass_env(str(tmp_path))
    assert "MY_FEED" not in env
    assert "REPO_URL" not in env
    assert env.get("PLAIN_URL") == "https://example.invalid/simple"


def test_bypass_env_keeps_noncredential_proxy_and_index_urls(monkeypatch, tmp_path):
    monkeypatch.setenv("HTTP_PROXY", "http://proxy.corp.example:8080")
    monkeypatch.setenv("PIP_INDEX_URL", "https://pypi.corp.example/simple")
    monkeypatch.setenv("PIP_EXTRA_INDEX_URL", "https://user:[email protected]/simple")
    env = _build_bypass_env(str(tmp_path))
    assert env["HTTP_PROXY"] == "http://proxy.corp.example:8080"
    assert env["PIP_INDEX_URL"] == "https://pypi.corp.example/simple"
    assert "PIP_EXTRA_INDEX_URL" not in env


def test_aws_imds_disable_flag_is_kept_but_creds_stripped(monkeypatch, tmp_path):
    # AWS_EC2_METADATA_DISABLED is a non-secret opt-out and must be kept.
    monkeypatch.setenv("AWS_EC2_METADATA_DISABLED", "true")
    monkeypatch.setenv("AWS_ACCESS_KEY_ID", "AKIAEXAMPLE")
    monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "shhh")
    assert _is_secret_env_name("AWS_EC2_METADATA_DISABLED") is False
    assert _is_secret_env_name("AWS_ACCESS_KEY_ID") is True
    env = _build_bypass_env(str(tmp_path))
    assert env.get("AWS_EC2_METADATA_DISABLED") == "true"
    assert "AWS_ACCESS_KEY_ID" not in env
    assert "AWS_SECRET_ACCESS_KEY" not in env


@pytest.mark.parametrize(
    "name",
    [
        "SQLCONNSTR_DB",  # Azure App Service injected connection strings
        "MYSQLCONNSTR_DB",
        "SQLAZURECONNSTR_DB",
        "POSTGRESQLCONNSTR_DB",
        "CUSTOMCONNSTR_CACHE",
        "WEBSITE_CONTENTAZUREFILECONNECTIONSTRING",
    ],
)
def test_connection_string_names_are_flagged(name):
    assert _is_secret_env_name(name) is True


@pytest.mark.parametrize(
    "value",
    [
        "Server=tcp:db;Database=app;User ID=u;Password=p@ss;",
        "DefaultEndpointsProtocol=https;AccountName=x;AccountKey=abc123==;",
        "Endpoint=sb://x;SharedAccessKeyName=n;SharedAccessKey=zzz=",
    ],
)
def test_connection_string_values_are_flagged(value):
    assert _is_secret_env_value(value) is True


@pytest.mark.parametrize(
    "value",
    [
        "Server=tcp:db;Database=app;User ID=u;",
        "Endpoint=sb://x;SharedAccessKeyName=n",
        "AccountName=x;EndpointSuffix=core.windows.net",
    ],
)
def test_connection_string_noncredential_values_are_not_flagged(value):
    assert _is_secret_env_value(value) is False


def test_connection_string_value_stripped_even_with_benign_name(monkeypatch, tmp_path):
    monkeypatch.setenv("APP_DB", "Server=tcp:db;Database=app;User ID=u;Password=p@ss;")
    monkeypatch.setenv("SQLCONNSTR_DB", "DefaultEndpointsProtocol=https;AccountKey=abc==")
    env = _build_bypass_env(str(tmp_path))
    assert "APP_DB" not in env
    assert "SQLCONNSTR_DB" not in env


def test_bypass_env_repoints_all_temp_vars(monkeypatch, tmp_path):
    # Windows tempfile honours TEMP/TMP, not TMPDIR; all three must repoint.
    monkeypatch.setenv("TEMP", "/host/tmp")
    monkeypatch.setenv("TMP", "/host/tmp")
    env = _build_bypass_env(str(tmp_path))
    expected = str(tmp_path / _SANDBOX_TEMP_DIRNAME)
    assert env["TMPDIR"] == expected
    assert env["TEMP"] == expected
    assert env["TMP"] == expected


@pytest.mark.parametrize(
    "name",
    [
        "HF_HOME",
        "HF_HUB_CACHE",
        "HUGGINGFACE_HUB_CACHE",
        "HF_XET_CACHE",
        "TRANSFORMERS_CACHE",
        "HF_DATASETS_CACHE",
        "XDG_CONFIG_HOME",
        "XDG_CACHE_HOME",
        "XDG_DATA_HOME",
        "NETRC",
        "BOTO_CONFIG",
        "PIP_CONFIG_FILE",
        "CLOUDSDK_CONFIG",
        "KAGGLE_CONFIG_DIR",
        "DOCKER_CONFIG",
        "WANDB_DIR",
        "WANDB_CONFIG_DIR",
        "NPM_CONFIG_USERCONFIG",
        "NPM_CONFIG_GLOBALCONFIG",
        "YARN_RC_FILENAME",
        "GIT_CONFIG_GLOBAL",
        "GIT_CONFIG_SYSTEM",
        "CARGO_HOME",
        "RCLONE_CONFIG",
        "GIT_ASKPASS",
        "SSH_ASKPASS",
        "BASH_ENV",
        "HOMEDRIVE",
        "HOMEPATH",
    ],
)
def test_cred_location_names_are_flagged(name):
    assert _is_cred_location_env_name(name) is True


@pytest.mark.parametrize("name", ["PATH", "HOME", "LANG", "PWD", "MY_VAR"])
def test_benign_names_not_flagged_as_cred_location(name):
    assert _is_cred_location_env_name(name) is False


def test_bypass_env_drops_hf_home_so_cached_token_unreachable(monkeypatch, tmp_path):
    # huggingface_hub reads $HF_HOME/token, so HF_HOME must be dropped.
    real_cache = tmp_path / "real_hf_cache"
    real_cache.mkdir()
    (real_cache / "token").write_text("hf_cachedOperatorToken")
    monkeypatch.setenv("HF_HOME", str(real_cache))
    monkeypatch.setenv("HF_HUB_CACHE", str(real_cache / "hub"))
    env = _build_bypass_env(str(tmp_path))
    assert "HF_HOME" not in env
    assert "HF_HUB_CACHE" not in env


def test_bypass_env_hf_token_resolves_outside_real_cache(monkeypatch, tmp_path):
    pytest.importorskip("huggingface_hub")
    import subprocess

    real_cache = tmp_path / "real_hf"
    real_cache.mkdir()
    workdir = tmp_path / "sandbox"
    workdir.mkdir()
    monkeypatch.setenv("HF_HOME", str(real_cache))
    monkeypatch.setenv("XDG_CACHE_HOME", str(real_cache))
    monkeypatch.setenv("XDG_CONFIG_HOME", str(real_cache))
    env = _build_bypass_env(str(workdir))
    token_path = subprocess.run(
        [
            sys.executable,
            "-c",
            "import huggingface_hub.constants as c; print(c.HF_TOKEN_PATH)",
        ],
        env = env,
        capture_output = True,
        text = True,
    ).stdout.strip()
    assert str(real_cache) not in token_path
    assert token_path.startswith(str(workdir))


def test_bypass_env_drops_credential_config_path_vars(monkeypatch, tmp_path):
    monkeypatch.setenv("NETRC", "/home/op/.netrc")
    monkeypatch.setenv("PGPASSFILE", "/home/op/.pgpass")
    monkeypatch.setenv("BOTO_CONFIG", "/home/op/.boto")
    monkeypatch.setenv("PIP_CONFIG_FILE", "/home/op/.pip/pip.conf")
    env = _build_bypass_env(str(tmp_path))
    assert "NETRC" not in env
    assert "PGPASSFILE" not in env
    assert "BOTO_CONFIG" not in env
    assert "PIP_CONFIG_FILE" not in env


def test_bypass_env_strips_npm_auth_and_mysql_pwd(monkeypatch, tmp_path):
    monkeypatch.setenv("NPM_CONFIG__AUTH", "aGVsbG86c2VjcmV0")
    monkeypatch.setenv("MYSQL_PWD", "db-password")
    assert _is_secret_env_name("NPM_CONFIG__AUTH") is True
    assert _is_secret_env_name("MYSQL_PWD") is True
    env = _build_bypass_env(str(tmp_path))
    assert "NPM_CONFIG__AUTH" not in env
    assert "MYSQL_PWD" not in env


@_POSIX_ONLY
def test_bash_bypass_does_not_source_bash_env(monkeypatch, tmp_path):
    startup = tmp_path / "startup.sh"
    startup.write_text("export RECOVERED=leaked\n")
    monkeypatch.setenv("BASH_ENV", str(startup))
    out = _bash_exec("echo R=$RECOVERED", None, 30, "bash-env-test", disable_sandbox = True)
    assert "R=leaked" not in out
    assert "R=" in out


def test_bypass_env_repoints_windows_profile_vars(monkeypatch, tmp_path):
    monkeypatch.setenv("USERPROFILE", "/host/profile")
    monkeypatch.setenv("APPDATA", "/host/profile/AppData/Roaming")
    monkeypatch.setenv("LOCALAPPDATA", "/host/profile/AppData/Local")
    monkeypatch.setenv("HOMEDRIVE", "C:")
    monkeypatch.setenv("HOMEPATH", "\\Users\\op")
    env = _build_bypass_env(str(tmp_path))
    assert env["USERPROFILE"] == str(tmp_path)
    assert env["APPDATA"] == str(tmp_path)
    assert env["LOCALAPPDATA"] == str(tmp_path)
    assert "HOMEDRIVE" not in env
    assert "HOMEPATH" not in env


def test_bypass_env_does_not_add_unset_windows_profile_vars(monkeypatch, tmp_path):
    monkeypatch.delenv("USERPROFILE", raising = False)
    monkeypatch.delenv("APPDATA", raising = False)
    monkeypatch.delenv("LOCALAPPDATA", raising = False)
    env = _build_bypass_env(str(tmp_path))
    assert "USERPROFILE" not in env
    assert "APPDATA" not in env
    assert "LOCALAPPDATA" not in env


@_POSIX_ONLY
def test_bypass_exec_hardens_parent_proc_env(monkeypatch, captured_popen):
    # A same-UID child can read the parent's /proc environ, so harden the parent.
    calls = {"n": 0}

    def fake_harden():
        calls["n"] += 1
        return True

    monkeypatch.setattr(tools, "_harden_parent_against_proc_env_leak", fake_harden)
    _python_exec("print(1)", None, 5, "t", disable_sandbox = True)
    _bash_exec("echo hi", None, 5, "t", disable_sandbox = True)
    assert calls["n"] == 2

    calls["n"] = 0
    _python_exec("print(1)", None, 5, "t", disable_sandbox = False)
    _bash_exec("echo hi", None, 5, "t", disable_sandbox = False)
    assert calls["n"] == 2


def test_bypass_exec_fails_closed_when_hardening_fails(monkeypatch, captured_popen):
    monkeypatch.setattr(tools, "_harden_parent_against_proc_env_leak", lambda: False)
    out_py = _python_exec("print(1)", None, 5, "t", disable_sandbox = True)
    out_sh = _bash_exec("echo hi", None, 5, "t", disable_sandbox = True)
    assert "refusing bypass execution" in out_py
    assert "refusing bypass execution" in out_sh
    assert "cmd" not in captured_popen


@_POSIX_ONLY
def test_proc_env_unreadable_after_hardening():
    # After hardening, a same-UID child cannot read the parent's /proc environ.
    import subprocess

    if tools._libc is None:
        pytest.skip("no libc/prctl available")
    pid = os.getpid()
    probe = (
        "try:\n"
        f"    open('/proc/{pid}/environ', 'rb').read()\n"
        "    print('READABLE')\n"
        "except PermissionError:\n"
        "    print('DENIED')\n"
    )
    prev_dumpable = tools._libc.prctl(3, 0, 0, 0, 0)  # PR_GET_DUMPABLE
    prev_guard = tools._parent_proc_hardened
    try:
        tools._libc.prctl(4, 1, 0, 0, 0)  # PR_SET_DUMPABLE = 1
        before = subprocess.run(
            [sys.executable, "-c", probe], capture_output = True, text = True
        ).stdout.strip()
        if before != "READABLE":
            pytest.skip("/proc already restricted in this environment")

        tools._parent_proc_hardened = False
        assert tools._harden_parent_against_proc_env_leak() is True

        after = subprocess.run(
            [sys.executable, "-c", probe], capture_output = True, text = True
        ).stdout.strip()
        assert after == "DENIED"
    finally:
        if prev_dumpable in (0, 1):
            try:
                tools._libc.prctl(4, prev_dumpable, 0, 0, 0)
            except (OSError, AttributeError):
                pass
        tools._parent_proc_hardened = prev_guard


def test_anthropic_request_model_bypass_default_false():
    from models.inference import AnthropicMessagesRequest

    assert AnthropicMessagesRequest.model_fields["bypass_permissions"].default is False
    req = AnthropicMessagesRequest(model = "x", messages = [], max_tokens = 8)
    assert bool(req.bypass_permissions) is False


@_POSIX_ONLY
def test_bypass_child_leads_its_own_session():
    # Every kill path is killpg based, so the bypass child must not share the server's session.
    out = _python_exec(
        "import os; print('LEADER=' + str(os.getsid(0) == os.getpid() == os.getpgid(0)))",
        None,
        30,
        "test-bypass-session",
        disable_sandbox = True,
    )
    assert "LEADER=True" in out